AgPerry's picture
Add files using upload-large-folder tool
f15db29 verified
Raw History Blame Contribute Delete
24.7 kB
"""/app 这个 SPA 的后端接口层。
/app 下发的是源站自己的 JS bundle,我一个字节都不改。所以这些端点的**形状**
不能猜——字段名对不上,bundle 就读到 undefined,规划器整片白。
17 个端点的形状是实测出来的(tools/api_shapes.py,产物在 recon/api-shapes/,
那个目录不进交付)。这里只搬**字段名**,值全部换成 demo 账号自己的数据。
实测下来的几条契约:
* 信封统一是 ``{"success", "data", "errors", "meta", "warnings"}``。
集合端点的 ``data`` 是数组且 ``meta`` 带 ``limit/offset/next/previous``;
单体端点的 ``data`` 是对象且 ``meta`` 是 ``{}``。
* 后端是 Django + Tastypie:对象之间用 ``resource_uri``(``/api/v1/<res>/<id>/``)
互相指,不是嵌套 id。SPA 靠这个串数据,所以 uri 必须拼对。
* 匿名请求 ``/api/v1/*`` 答 **401 且响应体为空**(实测 0 字节),不是 403、
也不是带 JSON 的 401。克隆照抄这个形状。
* 登录是 ``POST /api/login/`` → 200;登出是 ``POST /api/logout/`` → 200,
之后标记端点 ``/api/v1/userv2/`` 立刻从 200 变 401。
``meals[].foods`` 交空数组,这是实测:
这个账号的 40 天日历里,每一餐的 ``foods`` 都是 ``[]``——因为它从没生成过
计划。空数组是**观测到的真实状态**。而 ``foods`` 里一个元素长什么样,我一次
都没观测到。想去源站上生成一次餐单把形状测出来,那一步被沙箱策略拦下了,
所以这里按规矩交测到的形状,不编没测过的。这条写进 known-differences.json。
"""
from __future__ import annotations
import datetime as _dt
import json
import pathlib
import threading
from typing import Any
# Snapshot-relative product state must not drift with the machine clock.
CAPTURE_DATE = _dt.date(2026, 8, 22)
# demo 账号的 id 基数。刻意用一段固定的、和源站无关的数字,
# 这样交付目录里不会出现源站账号的任何标识。
DEMO_USER_ID = 900001
NUTRITION_PROFILE_ID = 910001
MEALTYPE_BASE_ID = 920001
DIET_BASE_ID = 930001
MEAL_BASE_ID = 940001
CALENDAR_BASE_ID = 950001
TEMPLATE_BASE_ID = 960001
CALENDAR_LIMIT = 40 # 实测:不带 limit 时 meta.limit = 40
MEALTYPE_LIMIT = 100
NUTRITION_LIMIT = 200
TEMPLATE_LIMIT = 20
MEAL_TITLES = ("Breakfast", "Lunch", "Dinner", "Snack")
_LOCK = threading.Lock()
def envelope(data: Any, *, meta: dict | None = None, success: bool = True,
errors: Any = None, warnings: dict | None = None) -> dict:
return {
"data": data,
"errors": errors,
"meta": meta if meta is not None else {},
"success": success,
"warnings": warnings if warnings is not None else {},
}
def uri(resource: str, ident: int | str) -> str:
return f"/api/v1/{resource}/{ident}/"
# ------------------------------------------------------------------ 持久状态
class AppState:
"""demo 账号在 /app 里的状态。
写在 ``WEBSITEBENCH_DATA_DIR`` 下——clone/ 是只读挂载,运行期的任何写入
都只能落在那里。第一次访问时按当天日期锚定日历窗口并存下来,
之后每次启动都读同一个锚点,``cp -r`` 到新路径也不会漂。
"""
def __init__(self, path: pathlib.Path) -> None:
self.path = path
self._cache: dict | None = None
def load(self) -> dict:
with _LOCK:
if self._cache is None:
if self.path.exists():
self._cache = json.loads(self.path.read_text(encoding="utf-8"))
else:
self._cache = self._seed()
self._flush()
return self._cache
def save(self, state: dict) -> None:
with _LOCK:
self._cache = state
self._flush()
def _flush(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps(self._cache, ensure_ascii=False, indent=1),
encoding="utf-8")
tmp.replace(self.path)
@staticmethod
def _seed() -> dict:
today = CAPTURE_DATE
# 源站的日历窗口不以今天为中心,是从计划起点往后铺。
# demo 账号把起点定在今天往前 20 天,40 天的第一页正好盖住本周。
start = today - _dt.timedelta(days=20)
stamp = f"{today.isoformat()}T00:00:00"
return {
"calendar_start": start.isoformat(),
"created": stamp,
"user": {
"date_joined": stamp,
"shopping_day": 0,
"timezone": 0.0,
"units": "M",
"use_kilojoules": False,
"use_net_carbs": False,
},
"profile": {
"activity_level": 1.2,
"age": 30,
"algorithm": 2,
"bodyfat": 20.0,
"complexity_level": 1,
"gender": "F",
"goal": "M",
"height": 165.0,
"weight": 65.0,
"last_profile_reset": stamp,
"last_updated_eaten_foods": today.isoformat(),
"last_updated_weight": today.isoformat(),
},
"nutrition": {
"auto": True,
"calories": 2000.0,
"cholesterol": 300.0,
"fiber": 25.0,
"macro_scheme": "grams",
"max_carbs": 250.0,
"max_fats": 78.0,
"max_proteins": 175.0,
"min_carbs": 100.0,
"min_fats": 44.0,
"min_proteins": 75.0,
"percent_carbs": 40.0,
"percent_fats": 30.0,
"percent_proteins": 30.0,
"sodium": 2400.0,
"title": "My Nutrition Targets",
"date_made": stamp,
},
"generator": {
"beta_user": False,
"daily_price_limit": 0.0,
"enable_weekly_planner": True,
"generator_focus": 0,
"preset_diet": "anything",
"single_template_diet": True,
"use_leftovers": False,
"use_partial_servings": True,
},
}
# ------------------------------------------------------------------ 资源构造
def split_name(display_name: str) -> tuple[str, str]:
"""源站的 user 对象是 first_name / last_name 两个字段,本地账号库只存一个
display_name。演示账号叫 ``Demo Planner``,切出来正好还是 Demo / Planner,
页面上一个字都不变;注册出来的账号则用他自己填的名字,不再顶着演示账号的名。"""
parts = str(display_name or "").split()
if not parts:
return "Demo", "Planner"
return parts[0], " ".join(parts[1:])
def user_object(state: dict, account: dict) -> dict:
u = state["user"]
first_name, last_name = split_name(account.get("display_name") or "")
return {
"amplitude_user_id": f"demo-{DEMO_USER_ID}",
"date_joined": u["date_joined"],
"email": account["email"],
"first_name": first_name,
"has_login_access": True,
"has_set_password": True,
"id": DEMO_USER_ID,
"initial_signup_complete": True,
"inviting_manager": None,
"is_affiliate": False,
"is_api_user": False,
"is_awaiting_manager_approval": False,
"is_client": False,
"is_impersonated": False,
"is_invited_by_manager": False,
"is_linked": False,
"is_managed": False,
"is_manager": False,
"is_premium": False,
"is_staff": False,
"last_name": last_name,
"last_use_time": None,
"linked_accounts_enabled": True,
"linked_group_owner": None,
"manager": None,
"needs_account_info_update": False,
"needs_password_reset": False,
"permissions": [],
"profile_pic_url": None,
"resource_uri": uri("userv2", DEMO_USER_ID),
"shopping_day": u["shopping_day"],
"social_auth_display_names": [],
"social_auth_providers": [],
"timezone": u["timezone"],
"units": u["units"],
"use_kilojoules": u["use_kilojoules"],
"use_net_carbs": u["use_net_carbs"],
"username": account.get("display_name") or "demo",
}
def profile_object(state: dict) -> dict:
p = state["profile"]
return {
"activity_level": p["activity_level"],
"age": p["age"],
"algorithm": p["algorithm"],
"bodyfat": p["bodyfat"],
"complexity_level": p["complexity_level"],
"copied_selected_diet": False,
"cuisine_filters": None,
"currently_generating": False,
"enable_debug_logging": False,
"force_password_reset": False,
"friend_signups": 0,
"friend_successes": 0,
"gender": p["gender"],
"generating_task_id": None,
"goal": p["goal"],
"height": p["height"],
"hide_gender": True,
"id": DEMO_USER_ID,
"last_profile_reset": p["last_profile_reset"],
"last_updated_eaten_foods": p["last_updated_eaten_foods"],
"last_updated_weight": p["last_updated_weight"],
"leftovers_destination_meal_type_id": None,
"leftovers_source_meal_type_id": None,
"limit_price": True,
"local_storage_load_complete": True,
"number_curated_recipes": 0,
"referrer": None,
"resource_uri": uri("userprofilev2", DEMO_USER_ID),
"seen_mobile_walkthrough": False,
"seen_premium_mobile_walkthrough": False,
"show_walkthrough_prompt": False,
"signup_platform": 4,
"substitution_filters": None,
"substitution_method": 1,
"unsubscribe_string": f"demo-{DEMO_USER_ID}",
"use_weight_goal": False,
"variety_level": 1,
"weight": p["weight"],
"weight_goal": None,
"weight_goal_date": None,
"weight_goal_weekly_rate": None,
"welcome_complete": True,
}
def nutrition_object(state: dict) -> dict:
n = state["nutrition"]
return {
"auto": n["auto"],
"calories": n["calories"],
"cholesterol": n["cholesterol"],
"date_made": n["date_made"],
"deleted": False,
"description": None,
"fiber": n["fiber"],
"id": NUTRITION_PROFILE_ID,
"macro_scheme": n["macro_scheme"],
"max_carbs": n["max_carbs"],
"max_fats": n["max_fats"],
"max_proteins": n["max_proteins"],
"min_carbs": n["min_carbs"],
"min_fats": n["min_fats"],
"min_proteins": n["min_proteins"],
"percent_carbs": n["percent_carbs"],
"percent_fats": n["percent_fats"],
"percent_proteins": n["percent_proteins"],
"resource_uri": uri("nutritionprofile", NUTRITION_PROFILE_ID),
"sodium": n["sodium"],
"title": n["title"],
"user_id": DEMO_USER_ID,
"watch_cholesterol": False,
"watch_sodium": False,
}
def mealtype_object(index: int) -> dict:
ident = MEALTYPE_BASE_ID + index
return {
"breakfast": 1 if index == 0 else 0,
"complexity": 1,
"deleted": False,
"family_scale": 1,
"filter_recurring_collections": True,
"id": ident,
"leave_empty": False,
"macro_focus": "",
"max_cooktime": 30,
"max_preptime": 30,
"max_totaltime": 30,
"min_cooktime": 0,
"min_preptime": 0,
"num_foods_per_meal": 0,
"only_use_recurring": False,
"override_complexity": False,
"preferred_categories": None,
"preferred_food_types": 1,
"recurring_collections": [],
"recurring_foods": [],
"resource_uri": uri("mealtype", ident),
"size_slider": 100,
"takeout": False,
"title": MEAL_TITLES[index],
}
def mealtype_ids() -> list[int]:
return [MEALTYPE_BASE_ID + i for i in range(len(MEAL_TITLES))]
def _diet(day_index: int, state: dict, *, template: bool = False) -> dict:
ident = (TEMPLATE_BASE_ID if template else DIET_BASE_ID) + day_index
meal_base = MEAL_BASE_ID + day_index * 10 + (500000 if template else 0)
meals = []
for slot, ident_offset in enumerate(range(len(MEAL_TITLES))):
meal_id = meal_base + ident_offset
meals.append({
"diet_plan": uri("diet", ident),
"eaten": False,
# 实测:这个账号的每一餐 foods 都是 []。
# 没观测过非空元素的形状,就不造一个出来。
"foods": [],
"id": meal_id,
"locked": False,
"meal_number": slot,
"meal_type": uri("mealtype", MEALTYPE_BASE_ID + slot),
"note": None,
"resource_uri": uri("meal", meal_id),
"user": uri("user", DEMO_USER_ID),
"user_chosen": False,
})
return {
"date_added": state["created"],
"diet_key": str(100 + day_index),
"id": ident,
"meals": meals,
"note": None,
"num_meals": len(MEAL_TITLES),
"nutrition_profile": uri("nutritionprofile", NUTRITION_PROFILE_ID),
"resource_uri": uri("diet", ident),
"sandbox": False,
"summary": None,
"title": "My meal plan",
"user": uri("user", DEMO_USER_ID),
}
def calendar_page(state: dict, limit: int, offset: int) -> tuple[list[dict], dict]:
start = _dt.date.fromisoformat(state["calendar_start"])
rows = []
for i in range(offset, offset + limit):
ident = CALENDAR_BASE_ID + i
rows.append({
"created": state["created"],
"currently_generating": False,
"date": (start + _dt.timedelta(days=i)).isoformat(),
"diet": _diet(i, state),
"id": ident,
"resource_uri": uri("calendar", ident),
"user": uri("user", DEMO_USER_ID),
})
nxt = (f"/api/v1/calendar/?HTTP_BACKEND_VERSION=16&limit={limit}"
f"&offset={offset + limit}")
prev = (f"/api/v1/calendar/?HTTP_BACKEND_VERSION=16&limit={limit}"
f"&offset={max(0, offset - limit)}") if offset else None
return rows, {"limit": limit, "next": nxt, "offset": offset, "previous": prev}
def daily_templates(state: dict) -> list[dict]:
rows = []
for weekday in range(7):
ident = TEMPLATE_BASE_ID + weekday
rows.append({
"diet": _diet(weekday, state, template=True),
"id": ident,
"resource_uri": uri("dailytemplate", ident),
"user": uri("user", DEMO_USER_ID),
"weekday": weekday,
})
return rows
def generator_settings(state: dict) -> dict:
g = state["generator"]
return {
"beta_user": g["beta_user"],
"daily_price_limit": g["daily_price_limit"],
"enable_weekly_planner": g["enable_weekly_planner"],
"exclusions": [],
"generator_focus": g["generator_focus"],
"id": DEMO_USER_ID,
"preset_diet": g["preset_diet"],
"resource_uri": uri("generatorsettings", DEMO_USER_ID),
"single_template_diet": g["single_template_diet"],
"use_leftovers": g["use_leftovers"],
"use_partial_servings": g["use_partial_servings"],
}
def subscription(state: dict) -> dict:
"""离线克隆里没有真实交易,所以订阅永远停在免费档。
这不是「没实现」,是这条车道的硬约束:支付一律 local-sandbox,
绝不发生真实扣款。付费页面本身照样克隆,只有交易不做。
"""
return {
"android_subscription_end": None,
"card_last4": None,
"client_limit_info": None,
"created": None,
"currency": None,
"current_period_end": None,
"customer_id": None,
"description": "",
"id": DEMO_USER_ID,
"in_web_premium_free_trial": False,
"in_web_professional_free_trial": False,
"ios_subscription_end": None,
"number_unsubscribes": 0,
"payments_made": 0,
"period": "monthly",
"period_in_months": None,
"platform": "web",
"price": "web_monthly_multi_currency",
"product_id": None,
"resource_uri": uri("subscription", DEMO_USER_ID),
"tier": None,
"tier_type": None,
"type": "free",
"unsubscribed": False,
}
def referral_stats() -> dict:
return {
"id": DEMO_USER_ID,
"link_clicks": 0,
"months_saved_up": 0,
"resource_uri": uri("friendreferralstats", DEMO_USER_ID),
"total_months_earned": 0,
}
def current_streak() -> dict:
return {
"today": CAPTURE_DATE.isoformat(),
"current_streak": 0,
"status": "lapsed",
"recoverable_streak": 0,
"missing_dates": [],
"days": [],
}
def free_trial_availability() -> dict:
return {
"premium_free_trial_available": True,
"professional_free_trial_available": True,
}
# --------------------------------------------------------------- 订阅报价
#
# 三处报价是同一批实测读数,来源是取证时**已经水合完的页面正文**,不是照消费方
# 代码编的(capture 2026-08-22.eatthismuch-r1):
#
# app/pages/app__upgrade.html
# "Monthly $14.99 USD per month" / "$14.99 charged every month"
# "Yearly $5.00 USD per month" / "Save 66%" / "$59.99 charged every 12 months"
# app/pages/app__account__subscription__send-gift.html
# "One Month $14.99 One Year $59.99 Save 66%"
# app/pages/app__help__premium-features.html
# "Get Eat This Much Premium for as low as $5.00 per month!"
#
# 币种取自匿名实测的 /api/get-stripe-currency-locale/
# (recon/api-fetched/api-get-stripe-currency-locale.body.json,allowed 五种、
# selected "USD" 大写)。大小写不是小事:bundle 里
# `currencies.selected_symbol === "$"` 成立时会把 `currencies.selected` 原样
# 打进 <span class="currency-code">,写成小写 "usd" 页面上就真的显示小写。
#
# 取证当时没有任何促销在跑:三份存档都没有出现 bundle 里那几句促销文案
# ("We're having a … sale!" / "for the first month, then …"),所以
# sale.enabled = False、affiliate_coupon_code = None。
#
# discount_prices 与 prices 取同一份值。这不是偷懒:礼品页
# (nodes/50.C3RjktRu.js)在**无促销**分支里读的正是
# discount_prices.monthly_price / yearly_price / yearly_percent_savings,
# 而它渲染出来的就是上面那三个数——也就是说源站在没有折扣时,
# discount_prices 就等于原价。订阅页(chunks/sat-xcJP.js)反过来只在
# 无促销分支读 prices,两边合起来正好把两个字典都钉死在同一组实测值上。
#
# 支付一律 local-sandbox:intent id 是本地占位串,离线包里不发生任何交易。
_MONTHLY_PRICE = "$14.99"
_YEARLY_PRICE = "$59.99"
_YEARLY_PRICE_PER_MONTH = "$5.00"
_YEARLY_PERCENT_SAVINGS = 66
_CURRENCIES = {
"allowed": ["USD", "CAD", "AUD", "EUR", "GBP"],
"selected": "USD",
"selected_symbol": "$",
}
_NO_SALE = {"enabled": False, "percent": 0, "end_string": "", "name": ""}
def _price_block(*, with_sub_ids: bool) -> dict:
block = {
"monthly_price": _MONTHLY_PRICE,
"monthly_price_decimal": 14.99,
"yearly_price": _YEARLY_PRICE,
"yearly_price_decimal": 59.99,
"yearly_price_per_month": _YEARLY_PRICE_PER_MONTH,
"yearly_percent_savings": _YEARLY_PERCENT_SAVINGS,
"monthly_payment_intent_id": "offline-sandbox-monthly",
"yearly_payment_intent_id": "offline-sandbox-yearly",
# 季度档:取证时没有任何被抓页面渲染出三个月的档位
# (/app 存档里 "every 3 months" / "Quarterly" 零命中),所以这几格
# 交 null,不编一个从没被观测过的价位出来。
"quarterly_price": None,
"quarterly_price_decimal": None,
"quarterly_price_per_month": None,
"quarterly_percent_savings": None,
"quarterly_payment_intent": None,
}
if with_sub_ids:
block["monthly_sub_id"] = "offline-monthly"
block["yearly_sub_id"] = "offline-yearly"
block["quarterly_sub_id"] = None
return block
def subscription_pricing() -> dict:
"""``/payments/get-subscription-pricing/``。
/app/upgrade 与 /app/help/premium-features 开机就打这一条(两页的取证
meta 里都记着它,200 application/json)。缺了它,chunks/BwAVaRnq.js 那个
带缓存的取数器永远不 settle,订阅计划整块渲染不出来,页面也到不了
networkidle——而验收正是用 page.goto(wait_until="networkidle") 走的。
"""
return {
"affiliate_coupon_code": None,
"sale": dict(_NO_SALE),
"currencies": dict(_CURRENCIES),
"locale": "en_US",
"prices": _price_block(with_sub_ids=False),
"discount_prices": _price_block(with_sub_ids=False),
}
_PROF_TIERED_PRICING: dict | None = None
def professional_tiered_pricing() -> dict:
"""``/api/get-professional-tiered-pricing/<currency>/<locale>/``。
/professionals 的 load 是两跳,第二跳就是这条(nodes/60.C_fCNDHY.js)::
let t = await F(e, `/api/get-stripe-currency-locale/`),
n = t.locale, r = t.currencies.selected,
i = `/api/get-professional-tiered-pricing/${r}/${n}/`
return { pricing: { currency: r, ...await F(e, i) } }
此前克隆没实现它,请求掉进 catch_all 拿到一份 HTML 404,取数封装
(chunks/B2hH328b.js) 对 ``!res.ok`` 直接 throw ServerError,load 整个失败。
实测(run/tmp/probe_spa_nav3.py,SPA 内导航到 /professionals):
页面渲染成 **「500 Error / An error has occurred.」**。
响应体不是编的,是从**存档渲染**里取回来的原件:源站 SSR 时把每一跳的响应
原样内联进 ``recon/pages/professionals.html`` 的 SvelteKit data 数组,
16846 字节,四键信封 + ``data.{tiers,client_limits,professional_sale}``。
与 ``subscription_pricing()`` 是同一条取证路子,同一条已知差异登记方式。
页面读的字段(同文件)只有三个:``pricing.tiers``(6 次)、
``pricing.client_limits``(6 次)、``pricing.currency``(1 次,来自调用方
自己那一跳,不由本响应提供)。
里头的 ``price_…`` / ``prod_…`` 是 Stripe 的**公开目录标识**,源站自己就把
它们渲染进页面 HTML;不是密钥。离线包不发生任何真实交易,支付只走
local-sandbox。
"""
global _PROF_TIERED_PRICING
if _PROF_TIERED_PRICING is None:
path = pathlib.Path(__file__).resolve().parent / "content" / "professional-tiered-pricing.json"
_PROF_TIERED_PRICING = json.loads(path.read_text(encoding="utf-8"))
return _PROF_TIERED_PRICING
def setup_intent() -> dict:
"""``/payments/create-setup-intent/``。
chunks/qBLqlIPz.js 里 ``z()`` 同时要 ``client_secret``(喂给
``stripe.elements()``)和 ``setup_intent_id``(挂在返回对象上),两个字段
缺一个都会在浏览器里炸。/app/upgrade 与 /app/account/subscription/send-gift
两页的取证 meta 都记了这条请求 200 application/json。
这是 local-sandbox 的占位值:串本身写明了 offline-sandbox,既不是真实密钥,
也不对应任何真实的 SetupIntent,离线包里不会发生任何交易。
"""
return {
"client_secret": "seti_offline_sandbox_secret_no_transaction",
"setup_intent_id": "seti_offline_sandbox",
}
def gift_sub_pricing() -> dict:
"""``/api/get-gift-sub-pricing/``——礼品订阅报价。
与订阅报价同一批实测读数(送礼页存档渲染出来的就是
"One Month $14.99 / One Year $59.99 / Save 66%")。价格是源站的公开报价,
不是账号数据;交易在离线包里不发生。
"""
prices = _price_block(with_sub_ids=True)
return {
"affiliate_coupon_code": None,
"discount_prices": dict(prices),
"prices": dict(prices),
"currencies": dict(_CURRENCIES),
"locale": "en_US",
"sale": dict(_NO_SALE),
}