Files
Avery_Template_System/src/avery_studio/avery_download.py
T
Michael-A-SloanandCursor 389e68ab08 Initial commit: Avery Label Studio desktop app.
Windows designer for Avery templates with Avery.com Word download, print, and PyInstaller build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 18:09:47 -04:00

229 lines
7.5 KiB
Python

"""Download official Avery blank Word templates from avery.com."""
from __future__ import annotations
import base64
import json
import re
import urllib.error
import urllib.request
from pathlib import Path
from .app_paths import user_templates_dir
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
)
# Avery "Download as a Guest" uses this marketing signup before redirecting
# to the signed Word blank URL. Email matches the app's guest continue flow.
GUEST_EMAIL = "a@a.com"
GUEST_SOURCE_ID = "21046"
_AVERY_AES_SECRET = "wwjH7clZ8E5v5BsgCqQ5zHYf9OlZ8dCB"
class AveryDownloadError(Exception):
pass
def avery_template_page_url(product_number: str) -> str:
num = product_number.strip()
return f"https://www.avery.com/templates/{num}"
def _request_headers(referer: str | None = None) -> dict[str, str]:
headers = {
"User-Agent": USER_AGENT,
"Accept": "application/json, text/html, */*",
"Origin": "https://www.avery.com",
}
if referer:
headers["Referer"] = referer
return headers
def _fetch_html(url: str) -> str:
req = urllib.request.Request(url, headers=_request_headers())
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read().decode("utf-8", "replace")
except urllib.error.HTTPError as exc:
if exc.code == 404:
raise AveryDownloadError(
f"No Avery template page found for that number.\n{url}"
) from exc
raise AveryDownloadError(f"Could not open Avery page ({exc.code}):\n{url}") from exc
except Exception as exc:
raise AveryDownloadError(f"Network error fetching Avery page:\n{exc}") from exc
def _unescape_avery_html(html: str) -> str:
"""Normalize JSON / HTML escapes Avery embeds in template pages."""
return (
html.replace("\\u0026", "&")
.replace("\\/", "/")
.replace('\\"', '"')
)
def find_word_download_url(html: str) -> tuple[str, str]:
"""
Return (download_url, suggested_filename) from an Avery template page.
Avery embeds signed S3 links for Microsoft Word blanks in the page HTML.
"""
text = _unescape_avery_html(html)
# Path must stop at '?' so the signed query (X-Amz-*) is kept — without it
# S3 returns 400 for anonymous GETs that use response-content-disposition.
match = re.search(
r'https://s3\.amazonaws\.com/[^\s"\'<>?]+Downloadables/doc/[^\s"\'<>?]+\.doc'
r'(?:\?[^\s"\'<>]*)?',
text,
re.I,
)
if not match:
raise AveryDownloadError(
"Could not find a Microsoft Word blank on that Avery page.\n"
"Open the page in your browser and use Import Template File… instead."
)
url = match.group(0).rstrip("\\").rstrip('"').rstrip("'")
fname = "AveryTemplate.doc"
fm = re.search(r"filename%3D([^&\"'\\]+)", url, re.I)
if fm:
from urllib.parse import unquote
fname = unquote(fm.group(1))
else:
fm2 = re.search(r"filename=([^&\"'\\]+)", url, re.I)
if fm2:
from urllib.parse import unquote
fname = unquote(fm2.group(1))
if not fname.lower().endswith(".doc"):
fname += ".doc"
return url, fname
def _avery_encrypt(plaintext: str) -> str:
"""
Match Avery avylib CryptoJS AES-128-CBC encrypt used by guest signup.
Key/IV are Utf8 of the first/second 16 chars of their shared secret;
Base64 ciphertext with '/' replaced by 'Avy21Ld'.
"""
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
except ImportError as exc:
raise AveryDownloadError(
"Missing dependency 'cryptography' (needed for Avery guest download).\n"
"Install it with: pip install cryptography"
) from exc
key = _AVERY_AES_SECRET[:16].encode("utf-8")
iv = _AVERY_AES_SECRET[16:32].encode("utf-8")
padder = padding.PKCS7(128).padder()
padded = padder.update(plaintext.encode("utf-8")) + padder.finalize()
encryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
ct = encryptor.update(padded) + encryptor.finalize()
return base64.b64encode(ct).decode("ascii").replace("/", "Avy21Ld")
def _post_json(url: str, payload: dict, referer: str) -> tuple[int, bytes]:
body = json.dumps(payload).encode("utf-8")
headers = _request_headers(referer)
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.status, resp.read()
except urllib.error.HTTPError as exc:
return exc.code, exc.read() if exc.fp else b""
def continue_as_guest(email: str = GUEST_EMAIL, referer: str | None = None) -> bool:
"""
Perform Avery's "Download as a Guest" email signup.
Returns True if Avery acknowledged the guest signup (HTTP 200).
checkUser 404 (unknown email) is expected for a guest address.
"""
ref = referer or "https://www.avery.com/templates"
email = email.strip().lower()
if not email or "@" not in email:
return False
# Same check the site runs before showing guest vs sign-in
_post_json(
"https://www.avery.com/account/checkUser",
{"email": _avery_encrypt(email)},
ref,
)
payload = {
"email": email,
"optIn": True,
"messageTypes": ["promotions"],
"sourceid": GUEST_SOURCE_ID,
}
status, raw = _post_json(
"https://www.avery.com/account/email-signup",
{"data": _avery_encrypt(json.dumps(payload, separators=(",", ":")))},
ref,
)
if status != 200:
return False
try:
data = json.loads(raw.decode("utf-8", "replace"))
except Exception:
return True
if isinstance(data, dict) and data.get("httpStatusCode") not in (None, 200):
return data.get("httpStatusCode") == 200
return True
def download_avery_word_template(
product_number: str,
dest_dir: Path | None = None,
guest_email: str = GUEST_EMAIL,
) -> Path:
"""
Open avery.com/templates/{number}, continue as guest, download the Word blank.
Returns the local .doc path under AppData templates (or dest_dir).
"""
num = re.sub(r"[^0-9A-Za-z\-]", "", product_number.strip())
if not num:
raise AveryDownloadError("Enter an Avery product / template number (e.g. 60504).")
page_url = avery_template_page_url(num)
html = _fetch_html(page_url)
doc_url, filename = find_word_download_url(html)
# Avery's UI requires guest continue before navigating to the Word URL.
continue_as_guest(guest_email, referer=page_url)
# Prefer product number in the saved name when Avery uses a long filename
safe_name = filename
if num not in filename:
safe_name = f"Avery{num}_{filename}"
folder = dest_dir or user_templates_dir()
folder.mkdir(parents=True, exist_ok=True)
dest = folder / safe_name
# S3 signed URLs: avoid Origin/extra headers that can break the signature.
req = urllib.request.Request(doc_url, headers={"User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(req, timeout=60) as resp:
data = resp.read()
except Exception as exc:
raise AveryDownloadError(f"Download failed:\n{exc}") from exc
if len(data) < 1000:
raise AveryDownloadError("Downloaded file looks empty or invalid.")
dest.write_bytes(data)
return dest