Compare commits

..

134 Commits

Author SHA1 Message Date
Eric
60606e53a7 Isolate WeChat audit books as always-free from paid unlocks.
Keep review-mode content off nomad VIP/purchase state, document the rule in README, and add the 82 API push script.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 20:04:22 +08:00
Eric
cee288b764 Give each ebook independent trial percent and paid unlock offers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:45:01 +08:00
Eric
1c2486a9c5 Hot-sync ebook and VIP offer changes from admin to clients within 1-2s.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:33:00 +08:00
Eric
76c22c23f4 Align live pay catalog with WeChat ops SKUs and shelf names.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:18:12 +08:00
Eric
ac1239c828 Redesign WeChat paid props as ops shelf: Chinese names, SKUs, icons.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:12:34 +08:00
Eric
362dab20f6 Keep WeChat props batch xlsx in-repo under docs/wx-props-batch for reuse.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:05:57 +08:00
Eric
5dd573ce22 Add WeChat virtual-pay props 29, 298 and 588 with batch upload sheet.
Include CORS images and prefer exact product_id match over legacy price remaps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:04:36 +08:00
Eric
b574a54d4c Add WeChat MP batch props xlsx and CORS-ready prop image URLs.
Generate upload sheet from PRODUCT_OFFERS and serve /props/ with mp.weixin.qq.com CORS.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 11:02:03 +08:00
Eric
b845d0bcea Update WeChat virtual pay OfferID and AppKeys; document miniprogram props.
Switch pay signing to sandbox/live AppKey by WX_PAY_ENV and record the product catalog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 10:59:27 +08:00
Eric
525fbf7766 Add VIP payment, PocketBase schema, and full backend sync under apps/hackrobot.
Pull payjsapi/nomadmini/vip-track/PB and extend deploy backups so VIP backends are git-managed locally.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 10:54:08 +08:00
Eric
1dac5fd5fd Sync vip.hackrobot.cn and admin.hackrobot.cn into apps/hackrobot with mandatory server backups.
Keep VIP stack isolated from Nomadro admin; pull/deploy scripts always snapshot /opt/hackrobot-backup first.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 10:48:49 +08:00
Eric
de75f41816 Update WeChat miniprogram AppID and AppSecret to wx11f6afc44ea1532f.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 08:58:53 +08:00
Eric
3940a4ed3b Ship VIP wechat user CRUD and in-shell user-list nav.
Enrich vip-track ntfy/avatar lookup, add wechat-users API CRUD, and mount admin user-list inside the SPA shell instead of a fullscreen back-button overlay.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 09:29:32 +08:00
Eric
29b8bdc55e Document VIP ops vs Nomadro admin hosts and ship LIVE/tag assets.
Hard-separate admin.hackrobot.cn (VIP ops) from admin.nomadro.cn forever; add live_ops bus, overlay tags, and deploy helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 02:38:03 +08:00
Eric
e1ff83e96c Show resume attachments on .com admin gig application detail.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 14:59:02 +08:00
Eric
bcde3a1535 Fix duplicate phrase key blocking Next production build.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 14:55:21 +08:00
Eric
756f02594d Add optional resume uploads to social hiring applications.
Let applicants attach PDF/Word/image resumes on team apply, store the file URL with the gig application, and surface it in admin gig apps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 14:14:40 +08:00
Eric
566d625100 docs: close out test14 and open test15 for development.
Record the 2026-11-10 baseline (theme switch + feedback images + local debug ball) and switch active work to test15 without deploying.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 13:03:29 +08:00
Eric
893526942c Ship social theme switching, feedback image ops, and local skin debug ball.
Save current look as theme 1, add admin experience skin controls for themes 1-4, fix feedback image sync/lightbox, move hiring to the home bottom, and expose a localhost-only debug orb for instant skin preview.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 13:02:04 +08:00
Eric
9ef0729eeb Fix .com upgrade pack for Next proxy path and skip missing sources.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-09 21:19:43 +08:00
Eric
985ecf5e77 Ship feedback identity limits, admin visitor dossiers, and a cleaner hiring board.
Cap feedback at 10 per user with clustered admin views, and redesign /social/team as a denser job board.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-09 21:17:33 +08:00
Eric
35e5f863fe Retitle social IA and float feedback as a corner mate.
Move 想见的人 to 一起做事/找搭子, rename gigs to 招聘, hide skill swap and the motion toggle, keep coffeechat online-backed, and add a non-dismissive feedback orb.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-09 20:33:03 +08:00
Eric
1a84587c5c ops: record verified test14 deployment to nomadro.com 2026-11-09 06:09:32 +08:00
Eric
1f44d3acee ops: add reversible test14 release for the US stack 2026-11-09 06:03:24 +08:00
Eric
83d00822dc fix: harden portal routing, API transport and admin builds on test14 2026-11-09 05:55:48 +08:00
Eric
21f44059e4 docs: close out test13 before test14 development 2026-11-09 05:37:18 +08:00
Eric
abdcafb1eb Ship Work access gate, pads/boards upgrades, and locale hydration fix on .com.
Gate /social/work behind join/login/profile; harden Work UX and LanguageSwitcher SSR; deploy portal, admin, and work API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 00:14:39 +08:00
Eric
58a845db32 Add WeChat minigame triple-engine scaffold with Godot Chiang Mai plaza SoT.
Unity and Cocos stay as parallel schemes; apps/minigame ships the Godot 4.7 WeChat pack for DevTools.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 20:17:14 +08:00
Eric
83f87e5ef3 Ship room-archive identity + join gates, and fix ntfy Beijing time for second timestamps.
Room archives resolve guest nick/email for admin lists; social join/date/people/coffee use clearer access gates; ntfy no longer shows 1970 when track.ts sends Unix seconds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 20:52:37 +08:00
Eric
d830097b00 Show Beijing time across admin UI and ntfy payloads.
Format ISO/unix stamps with Asia/Shanghai so join leads and alerts match China local clock.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 19:35:30 +08:00
Eric
344886172d Fix join leads so portal writes reach PocketBase for admin.
Await same-origin social forward and fall back when portal only stored local JSON.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 19:27:06 +08:00
Eric
69949b3d82 Document that archived test12 must never be deployed.
Keep the Codex experimental branch discoverable from the active tree without shipping its code.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 19:22:33 +08:00
Eric
499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00
Eric
8f32c3fbba Fix duplicate phrase keys blocking Next build.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:49:39 +08:00
Eric
ae6dba026e Ship social live UX gates, hide no-face roster avatars, and slim join profile.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:48:49 +08:00
Eric
613f639952 Add com-local-build-deploy skill: always build Next locally before US upload.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:23:51 +08:00
Eric
d828c109d4 Widen .com upgrade pack to ship ntfy, places, and social API sources.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:21:33 +08:00
Eric
3e60ba1a1b Ship social places/join UX, room-archive ops, and rich Markdown ntfy alerts.
Unify city+cafe into one places page, gate join with on-page modal, and enrich ntfy with icons, tables, and action buttons across portal/API/admin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 12:21:01 +08:00
Eric
308974bf5e Harden platform upgrade: ops admin, live config, shared service proxy, and smoke deploys.
Ship Operations console polish, PocketBase social fixtures, and portal join-leads without local DBs or probe scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 01:20:55 +08:00
Eric
9b7ffb24dc Ship social-first admin console, soft trials, and safer join gates.
Rebuild admin.nomadro.com around community ops, add configurable free peeks instead of nav locks, humanize user copy, and harden UGC/liveness admin APIs with backup/self-test scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 23:47:04 +08:00
Eric
ab2535971d Polish social discovery: intent guide on home, richer people filters/cards, and travel status semantics.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 16:59:32 +08:00
Eric
b06a14b6aa Ship social admin nested menus with list/detail CRUD, soft-archive UGC, and PocketBase-ready stores.
admin.nomadro.com gets sidebar L1/L2 social ops (paginated lists + entity detail); API adds soft-delete archives/stats and shared nomadro_pb for social/coffee/notify/work.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 16:41:43 +08:00
Eric
3e8458581a Require album face photo first, then full-session live video for audit.
Store challenge frames plus MediaRecorder stream for human review, and soft-gate dating/coffee/meetup until liveness passes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 14:53:54 +08:00
Eric
ac754c700b Add social Profile cold-start: ranked discovery and join onboarding.
Persist city/intents/availability/status on roster, expose /roster/discovery, and fire welcome + same-city recs via notify on first profile save.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 14:46:19 +08:00
Eric
5271aabc98 Ship social selfie face-check, avatar UX by device, blog/admin, and notify polish.
Add InsightFace/OpenCV challenge upload, PC vs mobile capture branching, and fix avatar persistence into roster/profile pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 14:38:20 +08:00
Eric
ffa456afdf Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 02:25:05 +08:00
Eric
2b574f7957 Ship native /social/work: Planka-shaped boards + Etherpad pads on FastAPI.
Secondary-dev Next UI with DnD, labels, stopwatch, archive, activity; pads with revisions; README documents pnpm dev:work-api.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 01:06:26 +08:00
Eric
4389ebe6cb Ship WeChat audit release 2026-11-02: realtime config, audit vip-ebook shell, admin ops.
Document test9 tag 2026-11-02 for upload; POST config pull + WS, fixed dark home, no debug bar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 16:12:57 +08:00
Eric
f20406397a Harden social UX and APIs: idempotent chat/join, config cache, weapp polish.
Improve hall chat retries, meetup-live lifecycle, home/mine remote-config UX, and add isolated social/API regression tests without deploying.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 14:00:11 +08:00
Eric
92bbee3c6c Ship native social weapp: immersive hall chat, SRS live, join pay.
Wire Taro social pages to social_svc (Centrifugo + live RTMP), drop multi-channel chat chrome, and add weapp WXSS sanitize/deploy helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 12:33:35 +08:00
Eric
065dd7dc68 Harden local-build deploy: never pnpm install while Next is running.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 00:09:12 +08:00
Eric
8edd9a0733 Prefer local Next build upload for 2C/4G portal deploys.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 00:04:24 +08:00
Eric
8b4c3c6a4f Ensure pnpm install before low-mem portal build on 2C/4G.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:52:41 +08:00
Eric
fb703c8b85 Harden 82 deploys for 2C/4G: 1536MB heap, swap, nice, .next rollback.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:50:10 +08:00
Eric
70816b6ebe Point README at test8 as the active development branch.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:34:56 +08:00
Eric
8b7222127c Fix social deploy pack to skip __pycache__ and extract safely on 82.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:28:07 +08:00
Eric
e65728601f Ship /social H5 deep polish on test7 and document release line.
Tighten mobile Ways/dock/chat/date sheets, add social loading/error boundaries, and mark test8 as the next branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:19:59 +08:00
Eric
da22814584 Polish /social H5: Ways order, dock, mobile sheets, and chat/date touch UX.
Add dedicated h5.css so group chat leads CTAs, orbit stays compact on phones, and composer/actions clear the bottom dock.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 22:43:27 +08:00
Eric
efb408162d Deepen /social UX: people profiles, city directory, date deck, and plain-language IA.
Hide membership entry, brand ebook/video as 共创, harden H5 touch layout, and align copy with everyday nomad language.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 21:25:37 +08:00
Eric
bbe2514e96 Restore immersive /social motion FX and expand the glass community workspace.
Keep Codex layout polish, but force emoji/orbit/constellation animations when immersive is on even under OS reduced-motion.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 18:38:04 +08:00
Eric
4789785f11 Ship remaining business changes across social API, miniprogram audit/book, VIP track, and deploy.
Includes social realtime entrypoints, weapp audit book surfaces, VIP analytics track routes, MiroTalk/Centrifugo deploy helpers, and related admin/config wiring. Excludes local DB dumps and .tmp probe scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 17:10:10 +08:00
Eric
d38bf6c475 Polish /social home UX with glass panels, compact roster, and motion FX.
Keep community-aligned layout without photo big-cards; add particles, emoji belts, and SVG sparks while hardening SiteShell mobile nav and join modal.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 17:06:53 +08:00
Eric
6e15868e04 Add isolated 游民社区 (/social) with social_svc and document test5.
Ship portal module + /api/social/v1 SQLite backend separate from /community; update README for MiroTalk CSP and test5 as the next development branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 11:24:21 +08:00
Eric
932f912087 Ship WeChat VIP↔Web bridge, netdisk sheet, and per-lesson materials gate for audit.
Freeze pre4 as the in-review weapp package; document pre5 as the next iteration branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-24 20:14:31 +08:00
Eric
dfc5f2d502 Fix VIP Youtube notes routing and VIP/join-group switch sync for weapp audit.
Tag 20261011-2: youtube-notes opens reader?id=default; VIP center toggle drives join popup vs VIP jump.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 19:42:28 +08:00
Eric
017008dd7c Harden weapp/API P0 paths: VIP auth, ebook login, WAL limits, game stub.
Drop Three from weapp game, mount VIP library on unified API, and auto-enable local debug without manual .env.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 19:06:50 +08:00
Eric
85211f2ff2 Document release tag 20261011b for the home launch path.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 16:04:35 +08:00
Eric
dc7a46ee0b Make WeChat launch path pages/home/index and document the index redirect.
Keep 20261011 hub visuals on home; index only reLaunches to avoid missing page wxss.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 16:03:31 +08:00
Eric
d0262eb58d Ship WeChat audit mode, package-size fixes, and live VIP switches.
Harden weapp for review: silent audit book, no flashy module defaults, safe-area PX, subpackages/lazyCodeLoading, and CDN nav icons. Document pre3 and move next work to pre4.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 15:12:06 +08:00
Eric
9779b80d25 Ship WeChat admin UX overhaul and VIP content library.
Restructure /wechat nav (VIP submenu for ebooks/course/shop/memo), rebuild ops pages with shared wx UI, and wire vip-library remote content end-to-end with README paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 09:59:57 +08:00
Eric
02232177e9 Sharpen portal PWA icons and add social preview image metadata.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 23:29:08 +08:00
Eric
b90e524b25 Add portal/admin PWA icons and freeze the game home entry.
Ship brand favicons and install-to-home manifests for nomadro.cn and admin, improve admin mobile drawer UX, and keep the game module forced off.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 23:19:59 +08:00
Eric
4a7690c0b1 Add remote-controlled nav CRUD and fix weapp VIP/nav chrome.
Ship admin nav editor + navContent remote-config, custom nav bars for memo/store, and weapp icon copy/webp path so nav icons render in DevTools.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 18:37:34 +08:00
Eric
3f7528f824 Add VIP knowledge community and device shop with native weapp UX.
Document memo/shop admin routes, deploy scripts, and cache-first feed performance in README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 16:58:17 +08:00
eric
98a54730ff Port nomadvip VIP into native WeChat pages and document the flow.
Add vip-course/lesson/ebook with source markdown seeds, VIP order API + admin offers, ban web-view for content, and update READMEs for weapp rebuild/extract scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 22:30:27 +08:00
eric
b2851c210c Add Douyin share card cover assets (840x474, no text).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 06:40:03 -05:00
eric
bbb0000943 Integrate Douyin join-group into modules panel and document git deploy flow.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 06:38:44 -05:00
eric
8c5eb388c1 Scrub BMI medical copy and live-refresh Douyin home A/B + portals.
Rename titles to BMI指数, soften audit-sensitive tips, and subscribe remote config so homepage variant and entrance toggles apply within a few seconds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 19:17:21 +08:00
eric
d7d828ec78 Restore TT index.tsx comments and normalize UTF-8 newlines.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 15:42:56 +08:00
eric
ea0786ea9d Fix TT index.tsx quote escaping that broke Babel compile.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 15:42:42 +08:00
eric
534400f554 Merge stash WIP onto BMI A/B: join-group, live config, channel tracking.
Keep Douyin homeVariant BMI router intact while restoring admin join-group controls, TLS-safe config fetch, and ntfy channel labels.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 15:42:09 +08:00
eric
0e85d71386 Add Douyin BMI audit homepage with remote A/B switch.
Ship a health-management BMI home for review, keep the nomad hub as hub, and let admin switch platforms.tt.homeVariant live with track/ntfy; fix tt config fetch to api.nomadro.cn/api/config.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 02:32:26 -05:00
05b9ab3e33 Add admin toggle for WeChat/X follow popup with safe config writes.
Expose socialFollowAuto in /admin/config, default off so live behavior stays unchanged; backup and preserve platforms.tt on save; protect remote-config.json during deploy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 04:51:02 +08:00
eric
3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00
eric
419cf3e331 Add platform picker on admin.nomadro.cn before WeChat console.
WeChat stays under /wechat unchanged; Douyin opens dyadmin.nomadro.cn. Does not touch nomadro.cn/admin portal.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 20:48:58 +08:00
eric
f688c03720 Preserve WeChat top-level remote-config on Douyin admin deploy.
Backup live modules before git reset; only seed platforms.tt for Douyin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 20:45:55 +08:00
eric
5d442b6783 Isolate Douyin admin from WeChat: drop shared tt-default-book seed.
Keep platforms.tt Douyin-only; weapp offline book and top-level modules unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 20:45:18 +08:00
eric
14d93a5cc8 Add Douyin admin controls: module toggles and remote 7-chapter booklet.
Seed platforms.tt with nav/community off and book on; restore original 数字游民 markdown editable from /admin/tt.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 20:37:53 +08:00
eric
71157a2df4 Polish Douyin reader: scroll-to-top fab, stable bodyReady, drop dead marktext images.
Avoid remount flicker on silent reload and strip three absolute local image paths that never resolve in-package.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 19:27:53 +08:00
eric
1313f24b10 Docs: document Douyin continuous reader and scroll-pin fix.
Align acceptance checklists with progressive mount, no cover bounce, and hidden nav entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 19:07:30 +08:00
eric
1de9200d18 Fix Douyin reader scroll fight and ship audit/content pack updates.
Stop aggressive chapter pin/progressive remount from yanking back to cover; restore booklet images and hide review-sensitive nav entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 19:04:15 +08:00
eric
bcbf54ce76 Align Douyin nav icons with WeChat: PNG export and relative paths for real devices.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:58:57 +08:00
eric
4fd2e574c1 Soften audit-sensitive copy for store review and fix weapp real-device nav icons.
Keep original link titles in encoded *Origin fields; soft-sanitize booklet/VIP display for XHS/weapp/tt; export PNG icons for WeChat Image on device.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:57:10 +08:00
eric
e5a6561fa7 Fix Douyin nav header: fixed topbar outside ScrollView.
Sticky headers inside ScrollView sit under the status bar on tt; move brand bar to fixed + content paddingTop.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:21:52 +08:00
eric
1d3e513ae2 Ship Douyin tt/ miniprogram: offline reader, clipboard privacy, README.
Add apps/miniprogram/tt as a standalone Douyin app with official usePrivacyCheck + tt.showModal/setClipboardData flow, single-chapter offline reader, and document console privacy setup for clipboard.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:17:52 +08:00
eric
626f6b19e8 Ship unified miniprogram H5/weapp parity and XHS offline portal.
Align Taro pages with Next hub/nav/book/community/VIP, pack the single-index Xiaohongshu portal with host-chrome safe areas, and refresh shared book content plus portal README constraints.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 09:37:03 +08:00
eric
69b0bd8224 Ship Taro H5 Vite build and Next-parity hub/nav/book/vip pages.
Switch miniprogram H5 to Vite for fast local compile; align portal pages and static icons for cross-machine continue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 04:36:12 -05:00
eric
c90670a1f7 Harden portal deploy path: chunked .next upload and observability docs.
Avoid remote pnpm build overload; document health/ntfy/Kuma anchors for miniprogram smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 01:18:12 -05:00
eric
9f8fec1723 Ship portal PC/H5 acceptance, VIP ScrollReader, admin analytics and ops anchors.
Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 23:52:00 -05:00
eric
56b29205e7 Integrate four verticals into nomadro portal with shared packages and API gateway.
Mount /vip with nomadvip+payjsapi, add @nomadro/pay|pb|sdk, apps/api, /admin shell, and backup/rollback scripts under git.nomadro.cn workflow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:16:44 -05:00
eric
28998243c3 Add community root-path middleware and fix login next= targets.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 19:07:54 -05:00
eric
0fc608ea26 Fix ebook /read links to /book/read and add compat redirects.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 18:54:03 -05:00
eric
6cae715727 Fix monorepo book content path and exclude Vite entry from portal tsc.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 17:20:26 -05:00
eric
9928c5185b Mount nav/book/community as native App Router routes in one Next process.
Replace reverse-proxy/iframe approach with @ebook/@community/@navmini imports under /nav /book /community so localhost:3000 serves all three products directly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:49:16 -05:00
eric
d93a355fd5 Migrate navmini/ebook/nomadweb into apps/ as same-origin portal subpaths.
Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:30:34 -05:00
eric
5569904bff Rebuild homepage to match nomadHub PC/H5 portal landing.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 01:59:49 -05:00
eric
acc0a81ab9 Fix nomadro.live ads.txt always served (ignore zh cookie)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 06:34:49 -05:00
eric
c60fdf0fd4 Replace nomadro.live with unique YouTube packaging articles and images
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 06:28:02 -05:00
eric
f360a68e4b Lengthen YouTube ops articles, add hero images, align trust pages
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 05:16:26 -05:00
eric
5a339a4658 Restyle WordPress themes for editorial YouTube ops look
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 05:01:08 -05:00
eric
4d9ee50d07 Rewrite all WordPress articles for YouTube channel operations (AdSense quality)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 04:56:35 -05:00
eric
7a9365480e Add nomadro.live English WordPress stack and audience router
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 04:35:48 -05:00
eric
0e997576c1 Add batch3: 10 new English articles for AdSense review
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 03:07:45 -05:00
eric
08f484780d feat: Umami/ntfy 可观测性栈与 WordPress AdSense 部署 2026-08-15 23:49:19 -05:00
eric
ba0b1058b0 Document locale detection, language easter egg, and deploy pointers in README.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 09:11:00 -05:00
eric
9c2eeb9df2 Hide language switcher by default; unlock with 5 taps on top-right.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 09:08:30 -05:00
eric
7453780e06 Add language switcher dropdown and persist manual locale choice.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 09:02:19 -05:00
eric
af0a430864 Detect locale with is-china-user and show English copy for non-Chinese visitors.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 08:54:39 -05:00
eric
4c2101a87a Fix www redirect and document Cloudflare redirect loop
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 11:36:37 -05:00
eric
460da1a6a3 Fix Caddy install method and add deployment docs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 11:30:35 -05:00
eric
d2b381ac7b Redesign landing page and add Caddy deployment for nomadro.com
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-11 11:25:50 -05:00
eric
e452424f61 's' 2026-03-23 02:37:36 -05:00
eric
3cebb7f905 's' 2026-03-18 02:36:20 -05:00
eric
538fdfea01 's' 2026-03-18 02:35:18 -05:00
eric
1f8c9c6d26 's' 2026-03-14 00:28:34 -05:00
eric
cf1e3760c2 's' 2025-12-14 08:00:13 -06:00
eric
f8efc290c4 's' 2025-12-06 04:03:06 +08:00
eric
dd988524a8 's' 2025-12-06 03:00:17 +08:00
root
5f9657d2ce s 2025-12-06 02:53:22 +08:00
eric
5db68af05a 's' 2025-12-06 02:48:53 +08:00
eric
3ffb59153c 's' 2025-12-06 02:46:28 +08:00
eric
72764015da 's' 2025-12-06 02:45:01 +08:00
eric
5983313979 's' 2025-12-06 02:37:47 +08:00
eric
cb78fe2422 's' 2025-12-06 02:28:28 +08:00
5316 changed files with 792237 additions and 22586 deletions

View File

@ -0,0 +1,27 @@
# 管理后台域名:永远禁止混淆
## 铁律
**`https://admin.hackrobot.cn/` 与 `https://admin.nomadro.cn/` 永远不允许混淆。**
改后台、部署、反代、注入脚本、鉴权、文档时必须先认域名;禁止把 A 的包/API/文案套到 B。
| 域名 | 产品 | 后端 | 源码 / 产物 | 鉴权 |
|------|------|------|-------------|------|
| **admin.hackrobot.cn** | **VIP 运营台**(`vip.hackrobot.cn`) | `/api/ops` → nomadvip `:4007`;`/api/admin/live/*` → nomadmini `:8010` | **`apps/hackrobot/admin-site/`**(勿用 Nomadro 微信壳覆盖) | `vip_ops_token`(HMAC) |
| **admin.nomadro.cn** | Nomadro 中国站后台(微信 / 抖音) | Nomadro API / PocketBase | `apps/admin` → admin.nomadro.cn | ebook/admin JWT |
| admin.nomadro.com | Nomadro 国际站后台(仅 Web) | `.com` API | `apps/com/admin` | `.com` admin 会话 |
VIP 前台源码:`apps/hackrobot/vip/`(线上 `/www/wwwroot/nomadvip`)。同步/发版/强制备份见 `apps/hackrobot/README.md` 与 `hackrobot-vip-git.mdc`。
## 禁止
- 把 `apps/admin`(微信/抖音壳)部署成 `admin.hackrobot.cn`
- 把 VIP 运营台 `/api` 整站指到 `:8010` 导致 `/api/ops` 失效
- 用 UI locale /「都叫 admin」假定两边同一套用户、拉黑、LIVE、支付
- 在文档或脚本里用「管理后台」不写全称域名
## 正确习惯
- VIP LIVE / 拉黑存档 / 线索 → 只谈 **admin.hackrobot.cn** + **vip.hackrobot.cn**
- 微信小程序运营 / 抖音模块 → 只谈 **admin.nomadro.cn** + `apps/admin`
- 国际 Web 运营 → **admin.nomadro.com** + `apps/com/admin`

View File

@ -0,0 +1,48 @@
---
description: 中文/国际受众模块化 — 支付登录关注文案VIP埋点等全进模块
alwaysApply: true
---
# 受众模块化(强制)
## SoT
`src/modules/audience/`
| 路径 | 职责 |
|------|------|
| `detect.ts` | 微信 UA + is-china-user 识别 |
| `cn/` | 中文用户:支付/登录/关注/文案/VIP/埋点/社群 |
| `intl/` | 国际用户(.com 默认):同上全套 |
| `resolve.ts` | `resolveAudienceBundle()` 合并远程 `audience.*` |
| `index.ts` | **唯一公共面** |
## 产品姿态
- **intl**:`.com` 默认(英语为主 + 多语言 UI)
- **cn**:必须特殊对待(微信内置 / is-china-user 命中)
## 开发铁律
```ts
import { resolveAudienceBundle, useAudienceModule } from "~/modules/audience"
const { module, lane, profile } = resolveAudienceBundle()
// module.pay / .login / .follow / .copy / .vip / .track / .social
```
**禁止**在页面散落 `if (isChina)` / `if (locale === "zh")` 决定支付网关、登录方式、关注渠道、VIP CTA。
新增能力(支付、登录、关注、文案、VIP、埋点、社群、小册 PDF/加密货币、运营位…)→ **同时改 `cn/` 与 `intl/`**,再经 `AudienceModule` 类型约束。
小册变现:`module.ebook.showPdfBuy` / `showCryptoSupport` — **仅 intl**;中文用户禁止展示 Download Edition / Buy Now $29 / Coffee·Lunch·Sponsor。
## 后台
登录后全屏选模块 → `/cn/*` | `/intl/*`(`admin.nomadro.com`)。
## 识别
1. 微信 / 企业微信内置 → cn
2. `is-china-user` → cn
3. 否则 → intl
勿用 UI locale 反推受众轨。

View File

@ -0,0 +1,42 @@
---
description: .com 美国机为开发发版核心;.cn 独立同步;Taro→三端小程序链路
alwaysApply: true
---
# 核心机与发版顺序(强制)
## 一句话
**本仓开发与默认发版核心是 `nomadro.com`(美国 VPS),不是 `.cn`。**
## 双站关系
| 站 | 机 | 角色 |
|---|---|---|
| **`.com`** | 美国 VPS(如 `108.174.50.68`) | **主开发 / 默认部署目标** |
| **`.cn`** | 中国机 `82.157.112.245` | 独立生产;**仅在 .com 中文轨测稳后**再同步 |
- `.com` 内分 **中文用户 / 国际用户**(`src/modules/audience/{cn,intl}`,`resolveAudienceBundle()`)。
- `.com` 中文用户体验测好 → 再同步到 `.cn` 与中国服务器。
- **`.com` 中文轨与 `.cn` 服务器彼此独立**(库、配置、进程、发版互不顶替)。禁止「只发 82 就当 .com 已上线」。
- 用户说「部署上线」且未点名域名 → **默认发 `.com` / 美国机**;发 `.cn` 必须明确说 `.cn` / 中国机 / 82。
- **前端另加门禁**:未经本轮明确允许,不能上线前端(见 `no-frontend-deploy-without-ok`);「默认 .com」不等于已获前端许可。
## 产品复制链(中国三端)
```
.com(Next · 受众 cn/intl)
└─ 中文轨测稳 → 同步 .cn(Next · 中国机,独立)
└─ Taro H5(apps/miniprogram/h5)对齐 .cn 体验
└─ Taro 多端编译 → 微信 / 抖音 / 小红书
```
- **微信小程序**是中国核心;抖音、小红书跟 Taro H5 SoT。
- 小程序 **禁止 web-view** 承载业务(见 `no-webview-content.mdc`)。
- `.com` 树 `apps/com/*` **无小程序**;小程序只走 `apps/miniprogram/*`。
## 反模式
- 默认 `deploy_*_82.py` / 只冒烟 `nomadro.cn` 却对用户说「已上线」
- 把 `.cn` 当主站、把 `.com` 当镜像
- 用 UI locale 代替受众轨;或假定 `.com` 中文与 `.cn` 共享同一后端

View File

@ -0,0 +1,21 @@
---
description: 本地调试 → 线上部署 → 更新 README;生产机与运维栈
alwaysApply: true
---
# 部署与运维
## 流程
本地确认 → 部署 `82.157.112.245`(ubuntu/`Xiao4669805`)→ 线上确认 → 更新 README。
## 线上习惯
- 前端多为 Next(PM2/systemd);API FastAPI;静态/反代可用 Caddy 或宝塔 Nginx
- 可观测:Umami、Uptime-Kuma、ntfy;对象存储优先 SeaweedFS / MinIO(`s3`/`minio` 子域)
- 数据:在线定时备份,支持回滚与日志溯源;改 PB schema 先备份
## Git
- 远程默认 `https://git.nomadro.cn/hackrobot/<repo>.git`
- 当前门户主开发分支常见为 `pre1`;发版前与 README 中声明的分支对齐

View File

@ -0,0 +1,24 @@
# 异度星球 VIP(hackrobot)本地 SoT
## 源码位置(本仓)
| 线上 | 本地 |
|---|---|
| vip.hackrobot.cn(`/www/wwwroot/nomadvip` · `:4007`,含 `app/api`) | `apps/hackrobot/vip/` |
| admin.hackrobot.cn(静态 SPA) | `apps/hackrobot/admin-site/` |
| LIVE API `:8010` | `apps/hackrobot/nomadmini/` |
| 支付 payjsapi | `apps/hackrobot/payjsapi/` |
| 埋点 `:4011` | `apps/hackrobot/vip-track/` |
| PocketBase `:8090` | `apps/hackrobot/pocketbase/` |
同步:`pull_from_129.py` + `pull_backends_from_129.py`
发版:`deploy_admin_site.py` / `deploy_vip.py` / `deploy_nomadmini.py` / `deploy_payjsapi.py`(**一律先** `hackrobot-backup`)
## 铁律
- **禁止**把 `apps/admin`(Nomadro 微信/抖音壳)部署到 `admin.hackrobot.cn`
- 改 VIP / 运营台只动 `apps/hackrobot/**`,勿与 `apps/admin` / `apps/com/admin` 混用
- 发版前服务器必须有快照:`/opt/hackrobot-backup/snapshots/`
- 前端上线仍受 `no-frontend-deploy-without-ok` 约束;未明确允许勿跑 `deploy_vip.py --build` / 上传 admin 静态站以外的擅自覆盖
详见 `apps/hackrobot/README.md` 与 `admin-hosts-never-confuse.mdc`。

View File

@ -0,0 +1,12 @@
---
description: 本地前端默认直连线上 .com 后端(禁止默认 127.0.0.1:802x)
alwaysApply: true
---
# 本地前端直连线上后端(写死)
**本地前端直连线上后端。**
- `pnpm dev` / localhost:`WORK_API_URL` / `NOTIFY_API_URL` / `COFFEE_API_URL` / `API_URL` 默认 **`https://nomadro.com`**
- 禁止默认 `127.0.0.1:8021/8023/8024`;本机后端仅在用户本轮明确要求联调时使用
- 细节见 `.cursor/skills/local-frontend-online-backend/SKILL.md`

View File

@ -0,0 +1,17 @@
---
description: 模块化设计 — 易扩展业务、解耦
alwaysApply: true
---
# 模块化与解耦
- **门户业务**:垂直前端进 `src/modules/<name>`,路由在 `src/app/<route>`;禁止把业务堆进 `src/components/` 壳层。
- **受众横切**:中文 / 国际进 `src/modules/audience/{cn,intl}`(支付·登录·关注·文案·VIP·埋点·社群等);见 `audience-cn-intl.mdc`。禁止页面散落 `if (isChina)`。
- **端形态**:小程序 / 管理 SPA / API 进 `apps/{miniprogram,admin,api}`;**.com(美国 VPS)进 `apps/com/*`,与 `.cn` 源码隔离**;共享进 `packages/*`。
- **远程工作**:门户壳 `src/modules/work`;Planka / Etherpad 上游与 overlay 在 `apps/work`(二次开发写 overlay,勿把整个 upstream 硬塞进主仓)。
- **稳定公共面**:`@nomadro/pay`、`@nomadro/pb`、`@nomadro/sdk` 经显式导出;模块之间禁止深路径互相 import。
- **依赖方向**:`packages` ← `apps` / `src/modules` ← 门户路由;下层不依赖上层;**`apps/com` 禁止依赖 `apps/admin` / 小程序源码**。
- **新增业务清单**:`src/modules/<name>` + 可选 `apps/api` 路由前缀 + 门户挂载路径(如 `/xxx`)+ 内容进 `src/modules/*-content`;不改无关模块。**.com Web 能力进 `apps/com`,勿塞进微信/抖音后台。**
- **接口优先**:模块对外用 HTTP/OpenAPI 或清晰 TS 类型;配置与密钥走 env。
- **可替换**:支付/存储/分析经 provider 接入(见 `@nomadro/pay.resolvePayProvider`)。
- **统一编排**:`.cn` 跨垂直入口在 `/admin` 与 `apps/admin`;`.com` 在 `apps/com/admin`(`admin.nomadro.com`);后台壳不承载垂直页面实现。

View File

@ -0,0 +1,17 @@
---
description: 多端 UI 比例铁律 — Web/微信/抖音/小红书;禁止把 Web px 弹窗原样搬进小程序
alwaysApply: true
---
# 多端 UI 比例(强制)
**Web 只参考结构;尺寸必须按端适配。** 详情见 `.cursor/skills/multi-platform-ui-scale/SKILL.md`。
| 端 | 要点 |
|----|------|
| Web VIP | 可居中 `max-w-[400px]` |
| Taro H5/weapp/tt/xhs | `designWidth: 750`;**裸 `px` → rpx 会缩水**;弹窗/表单用 **`rem` 或 `rpx`** |
| 小程序弹窗 | **全宽底栏** + 触控 ≥44px;勿抄 Web 桌面小卡片 |
反模式:VIP LoginModal 在微信里变成拇指盖大的居中框。
正确参考:`apps/miniprogram/h5/src/components/VipLoginModal.scss`、`vip-landing.scss`。

View File

@ -0,0 +1,13 @@
---
description: 未经允许禁止上线前端(门户/admin/小程序产物)
alwaysApply: true
---
# 未经允许,不能上线前端(写死)
**未经允许,不能上线前端。**
- 上传 `.next`、admin `dist`、小程序包,或宣称前端已上线 → 必须本轮用户明确说可以部署/上线前端。
- 「继续改 / 修好 / 深度定制 / 只查线上」**不是**许可。
- 无许可时只本地改与自测;后端-only 部署可做,但脚本里带前端包则跳过前端或整段停。
- 细节见 `.cursor/skills/no-frontend-deploy-without-ok/SKILL.md`。

View File

@ -0,0 +1,25 @@
---
description: 全端小程序禁止 web-view(微信/抖音/小红书/H5 SoT)
alwaysApply: true
---
# 全端小程序禁止 web-view
适用范围:`apps/miniprogram/{h5,weapp,tt,xhs}` 及一切 Taro/小程序业务页。
## 强制
- **禁止**使用 `WebView`、`web-view`、`pages/*-web`、内嵌 H5 壳承载任何业务内容。
- **禁止**用 web-view「偷懒」打开:VIP、电子书、视频课、社群、导航详情、目的地、活动、会员落地。
- 内容必须是**原生页面**:Taro 组件 + 包内/离线数据(markdown、catalog、Video、现有 reader)。
- 真外链(社群二维码页、商城):只允许复制链接 / 提示外部打开;**不得**当内容页塞进 web-view。
## 反模式
- `import { WebView } from '@tarojs/components'`
- `goPage('/pages/vip-web/...')` 或任何 `*-web` 内容页
- 导航栏标题出现 `%E4%...` 编码串却打开空白黑页(典型 web-view 失败)
## 发现即改
搜到业务页 WebView → 立刻改成原生页再继续其它需求;不得留下「先 web-view 以后再说」。

View File

@ -0,0 +1,52 @@
---
description: Nomadro 总章程 — 统一门户、默认栈、Git/域名
alwaysApply: true
---
# Nomadro 章程
## 远程配置 + 离线兜底(强制)
- 前端内容/元素/页面开关与文案 → 后端配置,`/admin/config` 可改
- 网络异常、小红书纯前端工具 → 必须包内/本地 catalog 兜底(见 `.cursor/rules/remote-config-offline.mdc`)
## 定位
`nomadro` **统一集成**四个垂直能力(导航 / 小册 / 社群 / VIP):同仓同规范,统一管理后台。
### 仓库布局(强制)
| 层 | 路径 | 说明 |
|----|------|------|
| 门户 Next | `src/app` + `src/modules/{nav,ebook,community,vip}` | PC/H5:`/nav` `/book` `/community` `/vip` |
| 内容 | `src/modules/ebook-content` 等 | 包内离线种子 |
| 小程序 | `apps/miniprogram/{h5,weapp,tt,xhs}` | Taro;H5 为 SoT,weapp 共用 `h5/src` |
| API | `apps/api` | 统一 FastAPI(ebook + community + pay) |
| 管理后台 .cn | `apps/admin` | admin.nomadro.cn(微信 / 抖音) |
| 管理后台 .com | `apps/com/admin` | admin.nomadro.com(美国 VPS · 仅 Web · 无小程序) |
| 共享包 | `packages/{pay,pb,sdk}` | 显式导出 |
禁止再引入已删除垂直树:`apps/ebook` `navmini` `nomadweb` `nomadvip` `wemini` `payjsapi` `community-api`。
挂载方式:同进程 App Router,**禁止** iframe / 反代嵌套。
## 默认技术栈
- Web:前端 Next.js(`src/`),后端 FastAPI(`apps/api`),DB PocketBase
- 支付:海外 Creem / NOWPayments;国内 zpay(PC/H5)、xpay(微信内);虚拟支付走 `apps/api`
- 多端:PC/H5 + Taro(微信 / 抖音 / 小红书)
- 运维开源:Caddy / Docker / Umami / Uptime-Kuma / ntfy / SeaweedFS / webhook
## 仓库与账号
- Git:https://git.nomadro.cn (管理员 `hackrobot` / `Xiao4669805@`)
- **开发主域 `nomadro.com`(美国 VPS)**;`.cn` 为中国独立站(测稳后同步)
- `.cn` 机:`82.157.112.245`,`ubuntu` / `Xiao4669805`;二级 DNS 在 Cloudflare
- 发版默认目标与双站关系见 `com-first-deploy.mdc`
## 开发流程(强制)
1. Windows 本地改 → `pnpm dev` / 对应后端启动 → 自测 OK
2. **默认部署 `.com`(美国机)** → 冒烟 OK;`.cn` 仅明确要求或中文轨同步时再发
3. 最后更新 README
模块化见 `modular-design.mdc`:门户业务在 `src/modules/`,端形态进 `apps/`,共享进 `packages/`。

View File

@ -0,0 +1,24 @@
---
description: 支付网关与多语言约定
alwaysApply: true
---
# 支付与 i18n
## 支付分流
| 场景 | 网关 |
|------|------|
| 海外 | Creem / NOWPayments |
| 国内 PC/H5 浏览器 | zpay |
| 国内微信内 H5 | xpay / xorpay(与现网 VIP 一致) |
| 微信小程序虚拟支付 | OfferID + AppKey(见 wechat 规则) |
统一经 FastAPI(`apps/api`)写 PocketBase;前端勿直连商户密钥。
## 多语言与受众
- **`.com`**:国际(英语为主)默认;中文用户特殊对待(见 `audience-cn-intl.mdc`)
- UI 语言:中文 / 英语;扩展日语、越南语、泰语等小语种
- 支付分流跟 **`detectAudience().isChina`**(含微信内置),**不要**跟 UI locale
- 门户:`lib/i18n` + `lib/audience` + `is-china-user`;垂直应用对齐,勿再造冲突 locale 键

View File

@ -0,0 +1,37 @@
---
description: 前端内容后台可配;网络异常与纯前端端必须离线兜底
alwaysApply: true
---
# 远程配置 + 离线兜底
## 强制
1. **前端内容/元素/页面须可被后端配置**
- 文案、入口开关、Tab/模块显隐、运营位、价格展示、功能 flag 等,默认走远程配置(API / PocketBase / 统一 `remote-config`)。
- **管理后台**(`/admin`)必须能动态开关、修改;禁止只写死在前端且无法运营改。
- 允许「默认值内置在客户端」作为离线/首屏种子,但线上以服务端配置覆盖。
2. **网络异常必须有离线数据兜底**
- 列表/详情/配置请求:失败、超时、空响应 → 使用打包内或本地缓存的 catalog(如 `localCatalog`、`links.json`、小红书 `book-data.js`)。
- 用户可感知:可标「离线模式 / 本地数据」,但页面不能白屏崩掉。
3. **纯前端端(尤其小红书小工具 / redmini / xhs minitool)**
- 默认按**离线优先**:构建时把内容打进包(assemble/pack);有网再尝试拉配置刷新缓存。
- 禁止假设运行时一定能访问业务 API。
## 实现约定
| 层 | 约定 |
|---|---|
| 配置键 | 统一 `NomadroRemoteConfig`(modules/pages/flags/copy) |
| 拉取 | `GET /v1/config` 或门户 `/api/config`;客户端缓存 `storage` |
| 管理 | `/admin/config` 读写;鉴权同后台会话 |
| 兜底顺序 | 内存缓存 → localStorage/Storage → 包内静态 JSON → 最小硬编码 |
| 垂直参考 | `src/modules/community` catalog、`src/modules/nav` links、`apps/miniprogram` 离线包 |
## 反模式
- 新页面只有硬编码文案、无配置键、后台改不了
- `fetch` 失败直接空白页、无 fallback
- 小红书工具依赖在线 API 才能打开首页

14
.cursor/rules/ui-ux.mdc Normal file
View File

@ -0,0 +1,14 @@
---
description: UI/UX — 深色科技风、主题、动效、可视化
alwaysApply: true
---
# UI / UX
- 风格:深色科技风为主;必须支持日间/夜间切换(`next-themes` 或等价,防闪烁)
- 视觉:充分使用 emoji / SVG / CSS 动画 / JS 动效;图表可用 D3;3D/沉浸可用 three.js、WebGL、WebVR;优先考虑 WASM / PWA
- 反模式:勿用 AI 默认紫渐变、奶油衬线、报纸密栏;门户首屏品牌优先、少卡片堆砌
- 响应式:移动优先,PC/H5 双端;触控热区约 44px
- **多端比例**:Web 只参考结构;微信/抖音/小红书/Taro 禁止照抄 Web 桌面 `px` 弹窗(`designWidth: 750` 会缩水)。见 `multi-platform-ui-scale` skill + rule
- 社媒引导:海外弹 X 关注;中文弹公众号二维码
- VIP 参考色:琥珀强调 `#f59e0b`,夜间底 `#0c0c0f`(见 `src/modules/vip`)

View File

@ -0,0 +1,26 @@
---
description: 微信/抖音/小红书小程序与 Taro、虚拟支付配置
globs: "**/miniprogram/**,**/weapp/**,**/tt/**,**/xhs/**,**/h5/**"
alwaysApply: false
---
# 小程序 / Taro
- 框架:Taro + React;UI 优先 Taro UI
- 统一仓:`apps/miniprogram`(`h5` SoT · `weapp` · `tt` · `xhs`)
- **远程配置**:模块/文案走 `/api/config`;`/admin/config` 可动态开关
- **离线兜底**:网络失败用包内 catalog;小红书 minitool **离线优先**(见 `remote-config-offline.mdc`)
- 文档:微信 https://developers.weixin.qq.com/miniprogram/dev/framework/ ;Taro https://docs.taro.zone/docs/GETTING-STARTED ;Taro UI https://taro-ui.jd.com
- 小红书:https://miniapp-sandbox.xiaohongshu.com/minitool/doc
- 抖音:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/introduction/usage-guide
- 虚拟支付(个人主体):https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/virtual-payment/person — 部署前按文末清单验收
## 微信配置(本项目允许写入 README;运行时仍可用环境变量覆盖)
```
WX_APPID=wx11f6afc44ea1532f
WX_APPSECRET=04214ecc910dca4526781c90bae94da1
WX_OFFER_ID=1450642200
WX_SANDBOX_APPKEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_LIVE_APPKEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
```

View File

@ -0,0 +1,57 @@
---
name: com-local-build-deploy
description: >-
Deploy nomadro.com (US VPS) by building Next + admin locally, then uploading
artifacts. Use ONLY after explicit user permission to 部署/上线 frontend
(see no-frontend-deploy-without-ok). Also when remote VPS CPU is too weak
for next build. Never rebuild Next on the US server.
---
# .com 本地构建再部署(强制)
## 许可门禁(先于一切)
**未经允许,不能上线前端。** 必须本轮用户明确授权前端发版后才能执行本 skill。
详见 `.cursor/skills/no-frontend-deploy-without-ok/SKILL.md`。无许可 → 停,勿上传 `.next` / admin dist。
## 铁律
**性能不够就本地构建。** 美国机只接收已构建产物,**禁止**在 `108.174.50.68` 上跑 `pnpm exec next build` / `next build`。
默认发版目标:`nomadro.com`(美国 VPS)。未点名 `.cn` / 82 时不要发中国机。
## 步骤(按序)
1. **本地构建(Windows 仓根)**
```powershell
pnpm build
pnpm build:admin-com
```
确认存在:
- `.next/BUILD_ID`
- `apps/com/admin/dist/index.html`
2. **发版脚本**(打包 `.next` + admin dist + API/social 增量源码):
```powershell
python scripts/deploy_platform_upgrade_com.py
```
- 目标:门户 `/var/www/nomadro.cn`(机器是美国,路径历史名)、`admin.nomadro.com`、`nomadmini-api`、`nomadro-social`
- 带备份与失败回滚
3. **冒烟**
- `https://nomadro.com/`
- `https://nomadro.com/social/places`
- `https://admin.nomadro.com/`
- API health(脚本内已 curl)
## 反模式
- SSH 上美国机 `pnpm build` / `next build`(慢、易 OOM、易挂死)
- 只改源码不重建本地 `.next` 就上传
- 默认 `deploy_*_82.py` 却对用户说「.com 已上线」
## 相关
- 双站顺序:`.cursor/rules/com-first-deploy.mdc`
- 上传连接:`apps/admin/deploy/_upload_next_us.py`(`connect()`)
- 仅门户包:可参考 `_upload_next_us.py`,完整栈仍用 `deploy_platform_upgrade_com.py`

View File

@ -0,0 +1,45 @@
---
name: local-frontend-online-backend
description: >-
Hard gate: local frontend must talk to online .com backends, not localhost
FastAPI by default. Use when configuring WORK_API_URL / COFFEE_API_URL /
NOTIFY_API_URL / API_URL, pnpm dev, or fixing「无法连接 work API」on localhost.
---
# 本地前端直连线上后端(写死)
## 铁律(逐字)
**本地前端直连线上后端。**
`pnpm dev` / `localhost:3000` 的业务 API **默认**打 **`https://nomadro.com`**(美国机线上),**禁止**默认假设本机已起 `dev:work-api` / `8021` / `8023` / `8024`。
## 默认上游
| 本地 Next 路径 | 环境变量 | 默认值(无 env 时) |
|----------------|----------|---------------------|
| `/api/work/v1/*` | `WORK_API_URL` | `https://nomadro.com` |
| `/api/notify/v1/*` | `NOTIFY_API_URL` | `https://nomadro.com` |
| `/api/coffee/v1/*` | `COFFEE_API_URL` | `https://nomadro.com` |
| 其它门户业务 | `API_URL` | `https://nomadro.com` |
| 远程配置(浏览器) | `NEXT_PUBLIC_REMOTE_CONFIG_URL` | `https://nomadro.com/api/config` |
代理拼法:`{ORIGIN}/api/work/v1/...` —— **只写站点根**(`https://nomadro.com`),不要写成带 `/api/work/v1` 的完整前缀以免双拼。
## 反模式(禁止)
- `.env.local` 默认 `WORK_API_URL=http://127.0.0.1:8021`,导致 pads「请先启动 pnpm dev:work-api」
- 代码默认 `127.0.0.1:802x` 却对用户说「本地开前端就能用」
- 为躲线上后端,把本地 offline JSON 当成主路径(offline **仅**线上不可达时兜底)
- 要求用户「再开一个 work-api 终端」才算本地可用
## 唯一例外
用户**本轮明确**说要联调本机后端(例如「起本地 work-api」「WORK_API_URL 指 8021」)时,才允许 `.env.local` 指向 `127.0.0.1:802x`。
## Agent 行为
1. 改 work/notify/coffee 代理或 `.env*` 时先读本 skill。
2. 发现默认仍是 localhost → **立刻改成** `https://nomadro.com`。
3. 本地 pads/boards 连不上 → 先查是否误指 127.0.0.1,再查线上 `https://nomadro.com/api/work/v1/health`。
4. **不要**为修本地连通性去上线前端(见 `no-frontend-deploy-without-ok`)。

View File

@ -0,0 +1,60 @@
---
name: multi-platform-ui-scale
description: >-
Nomadro 多端 UI 比例与 CSS 单位铁律:Web / H5 / 微信小程序 / 抖音小程序 / 小红书。
写或改任何弹窗、按钮、落地页、VIP LoginModal、Taro 样式时必须遵守;
禁止把 Web 桌面尺寸原样搬到小程序导致弹窗缩成一团。
---
# 多端 UI 比例铁律(写死,勿再问)
## 一句话
**Web 只参考结构与信息架构;最终尺寸必须按当前端的触控与单位体系适配。禁止「照抄 Web 的 px 弹窗」到微信/抖音/小红书。**
## 端与技术
| 端 | 路径 | 单位 / 设计稿 |
|----|------|----------------|
| Web 门户 VIP | `src/modules/vip` | CSS / Tailwind;桌面可居中 `max-w-[400px]` |
| Taro H5 SoT | `apps/miniprogram/h5` | 与落地页一致优先 **`rem`**(对齐 vip-landing) |
| 微信 weapp | `apps/miniprogram/weapp` · `designWidth: 750` | **裸写 `px` 会被转成 rpx → 尺寸腰斩** |
| 抖音 tt | `apps/miniprogram/tt` · `designWidth: 750` | 同 weapp |
| 小红书 xhs | `apps/miniprogram/xhs` | 同 Taro 750;纯工具页离线优先 |
H5 SoT 共用源码:`weapp/tt` 的 `sourceRoot` 指向 `../h5/src` —— **一处样式四端吃**,写样式时按「最严端(小程序)」适配。
## 强制规则
1. **小程序 / Taro 共用样式**
- 弹窗、表单、CTA:**用 `rem`(与 `vip-landing.scss` 同尺度)或显式 `rpx`**
- **禁止**在共用 SCSS 里写死 Web 桌面感的 `max-width: 400px` + 一堆裸 `px`(会被 750 稿压成拇指盖大的卡片)
- 触控热区:**≥ 44px 等价**(约 `2.75rem` / `88rpx`)
- 手机弹窗:**全宽底栏 sheet**(`align-items: flex-end` + 顶圆角);宽屏再可居中。不要默认桌面居中小卡片。
2. **Web VIP LoginModal**
- 仅参考:**标题「登录」+ Tab「账号/邮箱」+ 输入 +「验证并登录」+ 验证中全屏层**
- **不要**把 Web 的 `max-w-[400px]` 居中小卡原样搬进小程序
- 不要加品牌眉、副标题、字段标签等「超级优化」花活,除非产品明确要求
3. **参考 ≠ 复制尺寸**
- 结构、文案、交互流:可对齐 Web
- padding / font / 宽度 / 圆角:**按小程序重算**
4. **改弹窗前自检**
- [ ] 微信模拟器里弹窗是否接近屏宽、按钮是否好点
- [ ] 是否误用裸 `px` 导致缩水
- [ ] H5 / weapp / tt 是否同源样式、比例一致
## 反模式(禁止)
- 把 Web `LoginModal` 的 Tailwind 间距原样抄成 Taro `px`
- 小程序里居中一块「桌面对话框」又细又小
- 用户每次提醒「比例」才改 —— 本 skill 已写死,开工先遵守
## 关联
- 全端禁止 web-view:`.cursor/rules/no-webview-content.mdc`
- 远程配置 + 离线:`.cursor/rules/remote-config-offline.mdc`
- 现成正确示例:`apps/miniprogram/h5/src/components/VipLoginModal.scss`(rem + 底栏)
`apps/miniprogram/h5/src/styles/vip-landing.scss`

View File

@ -0,0 +1,56 @@
---
name: no-frontend-deploy-without-ok
description: >-
Hard gate: never deploy / 上线 frontend without explicit user permission.
Use whenever 部署、上线、deploy、发版、upload .next、admin dist、小程序包, or any
script that ships portal/admin/miniprogram UI to a server.
---
# 未经允许,不能上线前端(写死)
## 铁律(逐字)
**未经允许,不能上线前端。**
未得到用户**本轮明确许可**时:禁止任何前端发版动作。没有例外(「修完顺手发」「冒烟需要线上」「全权操作」历史句、上一轮曾说过部署、默认 .com 发版流程)都不能覆盖本条。
## 什么算「上线前端」
下列任一均算,必须先停、先问:
| 动作 | 示例 |
|------|------|
| 门户 Next 产物 | `pnpm build` 后上传 `.next`、`_upload_next_us.py`、`deploy_platform_upgrade_com.py`、`_deploy_*_us.py` 里带 portal `.next` |
| 管理后台 SPA | `pnpm build:admin-com` / `build:admin` 后上传 `dist` |
| 小程序 / Taro | 上传 weapp/tt/xhs/H5 构建包、提审包 |
| 线上替换 UI | `systemctl restart nomadro` **且**刚换了 `.next` / 静态前端;rsync/scp 门户 `src/` 指望线上再 build(仍禁止) |
| 对用户宣称已上线 | 说「已上线 / 已部署前端 / 打开某某 URL 看新 UI」而本轮未获许可 |
## 允许(不叫上线前端)
- 本地改代码、`pnpm dev`、本地 `pnpm build` **仅自测**(产物不上传)
- 只动后端:FastAPI / work_svc / PocketBase schema / systemd 环境变量 / 不换 UI 产物的服务重启
- 只 curl / 读日志排查线上,不换前端包
若脚本**同时**含前端包 + API:未获前端许可时,**只跑 API/后端部分**,或整段不跑并说明卡在前端门禁。
## 许可怎么算「明确」
本轮用户原话须直接授权前端发版,例如:
- 「可以上线前端」「部署前端」「发门户」「上传 .next」「按 com-local-build-deploy 发」
- 「全权操作 / 部署上线」且语境是发版(仍以本轮为准;不要用更早会话的「全权」推断)
**不算许可:**「继续改」「修好」「参考开源深度定制」「部署 API / 管理后台后端」「看看线上」「冒烟一下」。
## Agent 行为
1. 触达任何前端上线步骤前,先读本 skill。
2. 无明确许可 → **立刻停止**,用一两句问用户是否允许上线前端;禁止先传再问。
3. 有许可 → 再读 `com-local-build-deploy`,本地构建再上传;禁止在美国机上 `next build`。
4. 未获许可却已改好前端:只保留本地改动 + 说明如何自测;**不要**自行发版。
## 与其它规则
- `com-first-deploy.mdc`:默认发版目标仍是 `.com`,但**须先有本 skill 的前端许可**。
- `com-local-build-deploy`:有许可后的执行手册,不能单独当作许可。

View File

@ -0,0 +1,63 @@
---
name: nomadro-platform
description: >-
Use Nomadro public API / SDK / MCP tools for nomadro.com (US primary).
Health, remote-config, social map/meetups/gigs/join, VIP check, nav links.
Prefer MCP tools or GET https://nomadro.com/api/public/v1/* .
---
# Nomadro Platform
## Deploy truth
- **Core**: `https://nomadro.com` (US). Default for agents and SDK `baseUrl`.
- **China mirror**: `https://nomadro.cn` — independent; sync only after `.com` cn-audience is stable.
- Audience lanes: `cn` | `intl` via `src/modules/audience`.
## Surfaces (same tool list)
| Surface | Entry |
|---|---|
| Docs UI | `https://nomadro.com/developers` (Scalar) |
| OpenAPI | `GET /api/public/v1/openapi.json` |
| Tools | `GET /api/public/v1/tools` |
| SDK | `@nomadro/sdk` → `createNomadroClient({ baseUrl })` |
| MCP | `pnpm mcp` / `node packages/mcp/src/cli.mjs` |
| WeChat skill | `apps/miniprogram/weapp/ai-pkg/socialSkill` |
Tool SoT: `packages/sdk/tools.json`
## When to call which tool
- Platform probe → `health` / `getMeta` / `getConfig`
- Map / cities → `listMapCities` / `searchCities` → handoff `/social/map`
- Video rooms → `listMeetups` / `openMeetup` (no web-view in miniprograms)
- Gigs → `listGigs` / `applyGig` (name+contact required)
- Paid community join (not VIP) → `joinSocial` → `/social/join`
- VIP membership → `checkVip` with email
- Nav catalog → `listNavLinks`
## MCP config (Cursor)
```json
{
"mcpServers": {
"nomadro": {
"command": "node",
"args": ["packages/mcp/src/cli.mjs"],
"env": {
"NOMADRO_PUBLIC_ORIGIN": "https://nomadro.com"
}
}
}
}
```
Optional: `NOMADRO_PUBLIC_API_KEY`, `NOMADRO_SOCIAL_GUEST_ID`.
## Constraints
1. Do not treat `.cn` as the default ship target.
2. Social join ≠ VIP (`__social_join__` vs `__vip__`).
3. Miniprogram content must stay native (no business web-view).
4. Prefer returning `pagePath` handoffs so users complete pay/forms in UI.

View File

@ -1,24 +1,70 @@
# Since the ".env" file is gitignored, you can use the ".env.example" file to
# build a new ".env" file when you clone the repo. Keep this file up-to-date
# when you add new variables to `.env`.
# Copy to .env.local — never commit real secrets
# This file will be committed to version control, so make sure not to have any
# secrets in it. If you are cloning this repo, create a copy of this file named
# ".env" and populate it with your secrets.
# 本地前端直连线上后端(默认 .com;仅本机联调 API 时才改 127.0.0.1:802x)
# WORK_API_URL=https://nomadro.com
# NOTIFY_API_URL=https://nomadro.com
# COFFEE_API_URL=https://nomadro.com
# API_URL=https://nomadro.com
# When adding additional environment variables, the schema in "/src/env.js"
# should be updated accordingly.
# Admin panel
NOMADRO_ADMIN_PASSWORD=change-me
NOMADRO_ADMIN_SESSION_SECRET=change-me-session
# Optional PocketBase admin token for /admin/users
# PB_ADMIN_TOKEN=
# Next Auth
# You can generate a new secret on the command line with:
# npx auth secret
# https://next-auth.js.org/configuration/options#secret
AUTH_SECRET=""
# WeChat miniprogram virtual pay (apps/api)
WX_APPID=wx11f6afc44ea1532f
WX_SECRET=04214ecc910dca4526781c90bae94da1
WX_OFFER_ID=1450705308
WX_APP_KEY=JUN15h8sl5sNQt0awMSrd4Jpv1aSGOYY
WX_SANDBOX_APP_KEY=BQ1DlPjq3PIEzV4UwXQrKxLtqAqlmAEi
# 0=现网 1=沙箱
WX_PAY_ENV=0
# Next Auth Discord Provider
AUTH_DISCORD_ID=""
AUTH_DISCORD_SECRET=""
# 公众号 userid 档案:读 vip.hackrobot.cn wechat-profile;可选 VIP 运营 token 拉全量列表
# VIP_WEB_API_BASE=https://vip.hackrobot.cn
# VIP_OPS_TOKEN=
# Prisma
# https://www.prisma.io/docs/reference/database-reference/connection-urls#env
DATABASE_URL="file:./db.sqlite"
# Observability (production)
# NOMADRO_PUBLIC_ORIGIN=https://nomadro.com
# API_URL=https://api.nomadro.com
# 本地前端直连线上配置(浏览器 CORS;与 admin.nomadro.com 同源)
# NEXT_PUBLIC_REMOTE_CONFIG_URL=https://nomadro.com/api/config
# NEXT_PUBLIC_UMAMI_WEBSITE_ID=
# NEXT_PUBLIC_UMAMI_SCRIPT_URL=https://umami.nomadro.cn/script.js
# PostHog(https://github.com/PostHog/posthog · 可自建或 Cloud)
# NEXT_PUBLIC_POSTHOG_KEY=
# NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
# FingerprintJS 开源 visitorId(https://github.com/fingerprintjs/fingerprintjs)默认开;关:remote-config flags.fingerprintEnabled=false
# Google (portal GoogleTags · remote-config flags override)
# NEXT_PUBLIC_SITE_URL=https://nomadro.com
# NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXX
# NEXT_PUBLIC_GOOGLE_ADS_ID=AW-XXXXXXXX
# NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABEL=
# NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION=
# NEXT_PUBLIC_ADSENSE_CLIENT_ID=ca-pub-XXXXXXXX
# NEXT_PUBLIC_ADSENSE_PUBLISHER_ID=pub-XXXXXXXX
# Google OAuth(admin「用 Google 账号授权」→ 跳转登录)
# GOOGLE_OAUTH_CLIENT_ID=
# GOOGLE_OAUTH_CLIENT_SECRET=
# GOOGLE_OAUTH_REDIRECT_URI=https://api.nomadro.com/api/admin/google/oauth/callback
# GOOGLE_OAUTH_ADMIN_RETURN=https://admin.nomadro.com
# GOOGLE_OAUTH_TOKEN_PATH=/var/www/nomadro-data/google_oauth_tokens.json
# NTFY_BASE_URL=https://ntfy.nomadro.cn
# NTFY_TOPIC=nomadro
# Optional: .com 专用 topic(不设则用 NTFY_TOPIC)
# NTFY_TOPIC_COM=nomadro-com
# NTFY_TOKEN=
# Overseas pay (payjsapi)
# CREEM_API_KEY=
# NOWPAYMENTS_API_KEY=
# Social geo (MapLibre + Photon + PocketBase trips)
# NEXT_PUBLIC_MAP_STYLE_URL=https://tiles.openfreemap.org/styles/dark
# PHOTON_BASE_URL=https://photon.komoot.io
# SOCIAL_GEO_USE_PB=true
# SOCIAL_TRIPS_COLLECTION=social_trips
# PB_URL=http://127.0.0.1:8090
# PB_ADMIN_EMAIL=
# PB_ADMIN_PASSWORD=

46
.env.vip.example Normal file
View File

@ -0,0 +1,46 @@
# ========== 与 payjsapi/digital/cnomadcna 同源 ==========
# 复制为 .env.local,PB/Memos 与 payjsapi 保持一致
#
# 本地无 PocketBase:next dev 下可用 POCKETBASE_INTERNAL_URL 指远程 PB。
# next start 生产同机部署:服务端只用 POCKETBASE_URL(默认 http://127.0.0.1:8090),不会读取 POCKETBASE_INTERNAL_URL,避免误配公网域名拖慢 API。
# payjsapi 生产请配本机 PB(如 PB_INTERNAL_URL=http://127.0.0.1:8090),勿让 payjs 再绕公网打 pocketbase 域名。
# ========== PocketBase ==========
NEXT_PUBLIC_POCKETBASE_URL=https://pocketbase.hackrobot.cn
# 仅 next dev 服务端生效:远程 PB
POCKETBASE_INTERNAL_URL=https://pocketbase.hackrobot.cn
# 仅 next start 生产服务端生效(同机示例)
# POCKETBASE_URL=http://127.0.0.1:8090
POCKETBASE_EMAIL=xiaoshuang.eric@gmail.com
POCKETBASE_PASSWORD=Xiao4669805@
# ========== 支付(payjsapi)==========
PAYMENT_API_URL=http://127.0.0.1:8007
NEXT_PUBLIC_API_URL=http://127.0.0.1:8007
PAYMENT_API_INTERNAL_URL=http://127.0.0.1:8007
# 内网/慢网络可适当提高超时(毫秒):check_vip 默认 15s,payh5/redirect 默认 60s
# PAYJSAPI_CHECK_TIMEOUT=15000
# PAYJSAPI_CHECK_BY_EMAIL_TIMEOUT=20000
# PAYJSAPI_CHECK_BY_EMAIL_RETRIES=1
# PAYJSAPI_PAYH5_TIMEOUT=60000
# PAYJSAPI_REDIRECT_TIMEOUT=60000
PAYMENT_PROVIDER=zpay
PAYMENT_DEFAULT_AMOUNT=100
NEXT_PUBLIC_SITE_ID=vip
ZPAY_SUBMIT_URL=https://zpayz.cn/submit.php
# ========== Memos(pay/confirm 创建账号,与 payjsapi MEMOS_TOKEN 同值)==========
MEMOS_API_URL=https://qun.hackrobot.cn
MEMOS_ACCESS_TOKEN=eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoiaGFja3JvYm90IiwiaXNzIjoibWVtb3MiLCJzdWIiOiIxIiwiYXVkIjpbInVzZXIuYWNjZXNzLXRva2VuIl0sImlhdCI6MTc1NzQwNTE0OX0.Idn7kBlxE-CoSOXwWuZ1tHGIRKHAIeDyXSafGS5OHsg
# ========== MinIO ==========
MINIO_ENDPOINT=minioweb.hackrobot.cn
MINIO_PORT=9035
MINIO_USE_SSL=false
MINIO_BUCKET=hackrobot
MINIO_PUBLIC_URL=https://minioweb.hackrobot.cn/hackrobot
# 如需上传需配置(服务端)
# MINIO_ACCESS_KEY=
# MINIO_SECRET_KEY=
# MINIO_REGION=china

89
.gitignore vendored
View File

@ -1,22 +1,29 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# See https://help.github.com/articles/ignoring-files/
# dependencies
node_modules/
/node_modules
/apps/**/node_modules
/packages/**/node_modules
/.pnp
.pnp.js
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# database
/prisma/db.sqlite
/prisma/db.sqlite-journal
db.sqlite
# next.js
# next.js / builds
/.next/
/out/
next-env.d.ts
/apps/**/.next/
/apps/**/out/
/apps/**/dist/
/apps/miniprogram/**/dist/
/apps/admin/dist/
# production
/build
@ -24,6 +31,25 @@ next-env.d.ts
# misc
.DS_Store
*.pem
**/__pycache__/
*.pyc
*.log
.turbo/
.claude/
# xhs offline assemble output (regenerate via pnpm build:xhs)
/apps/miniprogram/xhs/release/
# remote-config 本地备份(写入时自动生成)
/data/backups/
/data/notify/
/data/work/
/data/coffee/
# secondary-dev upstream clones (reference only)
/apps/work/upstream/
/apps/notify/upstream/
/apps/coffee/upstream/
# debug
npm-debug.log*
@ -31,16 +57,49 @@ yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables
.env
.env*.local
# env
.env*
!.env.example
!**/.env.example
!**/.env.production.example
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# python / api local
/apps/**/.venv/
/apps/**/venv/
/apps/api/.venv/
/deploy/**/__pycache__/
# secrets / private mini-program configs
**/*credentials*.txt
**/nowpayments.env
**/nomadro-api.env
!**/*.env.example
!**/.env*.example
**/project.private.config.json
# local deploy/ops noise
/deploy/observability/_*.txt
/apps/admin/deploy/*-verify*.txt
/apps/admin/deploy/remote-*.txt
/apps/admin/deploy/*-debug*.txt
/apps/admin/deploy/certbot*.txt
/apps/admin/deploy/*-redeploy*.txt
/apps/admin/deploy/*-deploy.txt
/apps/hackrobot/deploy/.cache/
/apps/hackrobot/**/.venv/
/apps/hackrobot/**/__pycache__/
/apps/hackrobot/**/*.bak
/apps/hackrobot/**/*.bak-*
/apps/hackrobot/**/*.db
/apps/hackrobot/**/*.sqlite*
!/apps/hackrobot/pocketbase/data.db
/apps/hackrobot/vip/config/server-actions.key
# idea files
.idea

7
.npmrc Normal file
View File

@ -0,0 +1,7 @@
# Nomadro monorepo — prefer hoisted peers for Taro/Vite tooling
auto-install-peers=true
strict-peer-dependencies=false
public-hoist-pattern[]=*eslint*
public-hoist-pattern[]=*prettier*
public-hoist-pattern[]=@tarojs/*
node-linker=isolated

38
AGENTS.md Normal file
View File

@ -0,0 +1,38 @@
# Nomadro agent notes
Follow `.cursor/rules/*.mdc`。
**管理后台域名永远禁止混淆**:dmin.hackrobot.cn = VIP 运营台(vip.hackrobot.cn);dmin.nomadro.cn = Nomadro 中国站微信/抖音后台(pps/admin);dmin.nomadro.com = 国际站(pps/com/admin)。禁止互盖包/互指 API。见 .cursor/rules/admin-hosts-never-confuse.mdc。
**发版核心:`nomadro.com`(美国机)**。`.com` 分中文/国际受众;中文轨测稳后再**独立同步** `.cn`(中国机)。未点名域名时默认部署 `.com`,见 `com-first-deploy.mdc`。链路:`.com` → `.cn`(Next) → Taro H5 → 微信/抖音/小红书(微信为中国核心)。
**未经允许,不能上线前端**(写死):见 `.cursor/skills/no-frontend-deploy-without-ok` + `.cursor/rules/no-frontend-deploy-without-ok.mdc`。无本轮明确许可勿上传 `.next` / admin dist / 小程序包。
**本地前端直连线上后端**(写死):`pnpm dev` 默认 `WORK_API_URL`/`NOTIFY_API_URL`/`COFFEE_API_URL`/`API_URL` → `https://nomadro.com`;禁止默认 `127.0.0.1:802x`。见 `.cursor/skills/local-frontend-online-backend`。
**对外标准面**:`/api/public/v1` + `@nomadro/sdk` + `@nomadro/mcp` + `.cursor/skills/nomadro-platform`(工具 SoT `packages/sdk/tools.json`)。文档 [`docs/public-api.md`](docs/public-api.md)。
| Layer | Path |
|---|---|
| Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` |
| Remote work | 读 Planka/Etherpad 域模型后自研:Next `src/modules/work` + FastAPI `apps/api/services/work_svc`(`/api/work/v1`,`work_main.py :8021`)。禁止 iframe/二级域 |
| Notify | 读 Novu 域模型后自研:Next `src/modules/notify` + FastAPI `apps/api/services/notify_svc`(`/api/notify/v1`,`notify_main.py :8023`)。禁止 iframe/二级域 |
| Coffeechat booking | 读 Cal.com 域模型后自研:Next `src/modules/coffee` + FastAPI `coffee_svc`(`/api/coffee/v1`,`coffee_main.py :8024`),挂 `/social/coffeechat`。禁止 iframe/二级域 |
| Taro H5 SoT | `apps/miniprogram/h5`(weapp 共用 `../h5/src`) |
| Unified API | `apps/api` |
| Admin SPA (.cn) | `apps/admin` → `admin.nomadro.cn`(微信 / 抖音) |
| **VIP hackrobot(隔离)** | `apps/hackrobot/{vip,admin-site,nomadmini}` → `vip.hackrobot.cn` / `admin.hackrobot.cn`(129);发版强制备份 |
| **.com 隔离树** | `apps/com/*`(美国 VPS · **无小程序**);`apps/com/admin` → `admin.nomadro.com` |
| Shared | `packages/{pay,pb,sdk}` |
## Dev
根目录:`pnpm install` → `pnpm dev` / `dev:h5` / `dev:admin` / `dev:admin-com` / `dev:api` / `typecheck` / `clean`。
Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline defaults. Current WeChat audit branch/tag: `test9` / `2026-11-02`. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `wemini`). VIP 源码在隔离树 `apps/hackrobot/`(勿再开顶层 `apps/nomadvip`)。
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
**受众模块**:`src/modules/audience/{cn,intl}` — 支付/登录/关注/文案/VIP/埋点/社群全模块化;`resolveAudienceBundle()`。后台登录后选 `/cn`|`/intl`。见 `audience-cn-intl.mdc`。
H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。

423
README.md
View File

@ -1,92 +1,401 @@
# nomadro
# Nomadro
> **管理后台域名铁律(永远禁止混淆)**
>
> | 域名 | 是什么 | 不是什么 |
> |------|--------|----------|
> | [admin.hackrobot.cn](https://admin.hackrobot.cn/) | **VIP 运营台**(服务 [vip.hackrobot.cn](https://vip.hackrobot.cn/):线索 / 拉黑存档 / LIVE 在线与弹窗通知) | 不是 Nomadro 微信/抖音后台 |
> | [admin.nomadro.cn](https://admin.nomadro.cn/) | Nomadro **中国站**管理 SPA(pps/admin:微信 / 抖音) | 不是 VIP 运营台;禁止用它的包覆盖 hackrobot |
> | [admin.nomadro.com](https://admin.nomadro.com/) | Nomadro **国际站**管理 SPA(pps/com/admin,美国 VPS,无小程序) | 与上两者均独立 |
>
> 反代、发版、鉴权、LIVE 注入、文档里写「管理后台」时必须带全称域名。规则见 \.cursor/rules/admin-hosts-never-confuse.mdc\。
2026-11-22:微信小册**提审态默认免费**,且与正式付费数据隔离 — `platforms.weapp.bookAudit.reviewMode` 开启时读独立 `audit*` 书(永远 `is_free` / 不可下单 / 不读正式 `unlocks`·`__vip__`);关闭后重新拉正式已购与 VIP,互不粘态。weapp App 挂远程配置 WS + 1s 轮询,后台开关约 1s 热更新。API 已推 `api.nomadro.cn`(`_push_audit_free_isolate.py`);体验包须本轮许可后再 `build:weapp` 上传。
2026-11-15:VIP 运营台实时能力 — dmin.hackrobot.cn LIVE 在线/弹窗通知(ops token ↔ /api/admin/live)、用户拉黑/曾拉黑 tag 与身份提示;**写死** dmin.hackrobot.cn 与 dmin.nomadro.cn 永远禁止混淆。资产 pps/admin/deploy/_vip_live_assets/ · API live_ops/ops_live。
## Getting started
2026-11-10:`test14` 收尾(`8935269` / tag `2026-11-10`)后切换 `test15` 开发。基线含社区主题 1–4、后台体验主题切换、反馈图片灯箱、招聘首页底部化、本地皮肤调试小球。见 [test14 收尾](docs/test14-closeout.md) · [test15 开发](docs/test15-development.md)。
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
2026-11-09:`test14` 门户、后端及 `.com` 管理后台已获许可并部署美国机。门户构建 `T9G517UdX-JND3zgNO3SD`;修复生产通知/预约代理自循环,公网接口恢复 200。门户/后台静态资源哈希、服务健康与后台鉴权验证通过,`.cn` 未同步。备份与验收见 [test14 上线记录](docs/test14-release.md)。
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
2026-11-09:`test13` 收尾后切换 `test14`,仅优化门户/后端/后台功能与构建,不调整前端视觉、不部署生产。修复首页重写循环、迁移 Next.js 16 `proxy`、统一本地 `.com` API/配置默认值、修复 Strict Mode 埋点监听及后台请求异常处理、为共享 PocketBase 凭证增加并发保护与一次 401 恢复,并修复 `.cn` 后台构建类型冲突。范围与验证见 [test14 开发记录](docs/test14-development.md)。
## Add your files
2026-11-08:远程工作门禁 + Work UX + 语言水合修复并部署 `.com` — `/social/work` 未加入社区不可用(登录/注册/补资料,与约会同门禁);Pads/Boards 增强(收藏复制删除、专注预览快捷键、看板筛选模板);`LocaleProvider`/`LanguageSwitcher` 首帧固定 zh 消除 hydration mismatch;反馈页英文短语补全。本地构建上传门户 `.next` + `admin.nomadro.com` + API/social;`.cn` 未同步。
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
2026-11-07:Work Pads 深度定制(Etherpad 域模型 → Next 原生)— `/social/work/pads`:作者色条、行号、在场名单、侧栏聊天、时间轴浏览/还原、冲突提示、导入导出、Ctrl/⌘+S、删除;API `presence`/`chat`/`DELETE` + Welcome pad;work 服务补 PocketBase 鉴权。无 iframe。
2026-11-07:Google 增长 OAuth UX 修复 — 未配 Client 时不再展示灰掉的「用 Google 账号授权」;改为红条提示 +「① 保存客户端」为主按钮,保存成功后再出现「② 用 Google 账号授权」。
2026-11-07:用户分析补全环境特征并部署 `.com` — 埋点写入 IP(服务端)+ UA/浏览器/系统/设备/屏幕/时区/语言等;后台「访客明细 → 看明细」展示环境特征卡与时间线;API `track-analytics` / `track-visitor`。
2026-11-07:产品分析 — 门户接入 [PostHog](https://github.com/PostHog/posthog)(`posthog-js`)与开源 [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs) visitorId;经 `PortalAnalytics` + `src/lib/analytics/*` 镜像现有 `/api/track`;远程配置 `flags.posthog*` / `fingerprintEnabled` + env `NEXT_PUBLIC_POSTHOG_KEY`。未配 key 时 PostHog 静默跳过。
2026-11-07:Google 增长自动化 — 后台「增长 → Google 增长」支持粘贴片段 / 同步 env / 一键写入;API `/api/admin/google/{status,parse,auto-link}`;`ca-pub` 自动补 `ads.txt` publisher;保留手填。门户 `GoogleTags` + `/sitemap.xml` `/robots.txt` `/ads.txt`。文字厅双语与咖啡聊离线兜底见 [`src/modules/social/README.md`](src/modules/social/README.md)。
2026-11-05:UI/UX 与预约、通知功能升级已上线 .com,详见 [本轮发布与验收记录](docs/uiux-upgrade-2026-11-05.md),包括当前构建、备份位置及功能边界。
数字游民操作系统(主开发与默认发版:[nomadro.com](https://nomadro.com);中国独立站:[nomadro.cn](https://nomadro.cn))。
2026-11 平台升级已部署至 `.com` 门户、API 与 [Web 管理后台](https://admin.nomadro.com)。升级内容、验收范围、构建编号与回滚位置见 [升级记录](docs/platform-upgrade-2026-11.md)。`.cn` 未同步本次发版。
**归档禁发:** 分支 `test12`(Codex 实验改动)已冻结,**永远不要上线**;见 [docs/archive/test12-NEVER-DEPLOY.md](docs/archive/test12-NEVER-DEPLOY.md) 与 tag `archive/test12-never-deploy`。
## 架构
```
cd existing_repo
git remote add origin http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadro.git
git branch -M main
git push -uf origin main
src/ Next.js 门户 .cn(app 路由壳 + modules 业务)
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs(仅 .cn 备案线)
apps/api/ 统一 FastAPI(ebook + community + pay + social + work + notify)
apps/admin/ admin.nomadro.cn 管理 SPA(微信 / 抖音)
apps/com/ .com 源码隔离树(美国 VPS · 无小程序)→ admin.nomadro.com
apps/work/ 远程工作参考 upstream / overlay(Planka · Etherpad;产品 UI 不跑 iframe)
apps/notify/ 通知参考 upstream(Novu;产品 UI 不跑 iframe)
apps/coffee/ 咖啡聊预约参考 upstream(Cal.com;产品 UI 不跑 iframe)
packages/ @nomadro/pay · pb · sdk
data/ 远程配置等运行时数据(含 social.db · work/notify/coffee.sqlite3)
scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
```
## Integrate with your tools
| 产品 | 门户路由 | 源码 |
|------|----------|------|
| 导航 | `/nav` | `src/modules/nav` · 远程 `navContent`(后台 `/wechat/nav` 可 CRUD) |
| 小册 | `/book` | `src/modules/ebook` + `src/modules/ebook-content` |
| 旅居社群 | `/community` | `src/modules/community`(Lounge / Ergo / MiroTalk;**勿改名**) |
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite · Centrifugo 实时 · 视觉默认 T1 |
| **远程工作** | `/social/work` | `src/modules/work` · FastAPI `work_svc` `/api/work/v1`(看板 + 文档) |
| **通知** | `/notifications` · `/social/notify` | `src/modules/notify` · FastAPI `notify_svc` `/api/notify/v1`(收件箱 + 工作流) |
| **咖啡聊预约** | `/social/coffeechat` | `src/modules/coffee` · FastAPI `coffee_svc` `/api/coffee/v1`(Cal.com 域:日程/时段/预约) |
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
| 后台 .cn | admin.nomadro.cn | `apps/admin`(`/wechat` · `/douyin`) |
| **VIP 运营台** | **admin.hackrobot.cn** | 独立 VIP SPA(vip.hackrobot.cn);**禁止**与 admin.nomadro.cn 混淆;LIVE/拉黑见 _vip_live_assets |
| 后台 .com | admin.nomadro.com | `apps/com/admin`(**仅 Web**;美国 VPS) |
| API | api.nomadro.cn | `apps/api` |
- [ ] [Set up project integrations](http://gitlab.yidooplanet.com/gitlab-instance-0a899031/nomadro/-/settings/integrations)
`.cn` 后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗集成在 **`/douyin/modules`**。`.com` 未备案,**无**小程序后台。
## Collaborate with your team
## 技术栈(Next 门户 + FastAPI)
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
### 前端(`src/` · Next.js)
## Test and Deploy
| 层 | 技术 |
|---|---|
| 框架 | Next.js 16(App Router)· React 19 · TypeScript · pnpm workspace |
| 样式 | Tailwind CSS 4 · Sass · 模块 CSS |
| 主题 | `next-themes`(日/夜防闪烁) |
| 动效 / 图标 | Framer Motion · animate.css · Lucide |
| 地图 | MapLibre GL · h3-js |
| 实时 | Centrifuge(对接 Centrifugo)· socket.io-client |
| Markdown / 编辑 | react-markdown · marked · markdown-it · Gravity UI Markdown · Diplodoc · highlight.js |
| DnD / 组件库 | `@hello-pangea/dnd` · Ant Design · Gravity UI · Semantic UI React |
| 3D | three.js |
| i18n / 受众 | i18next · `is-china-user` · `src/modules/audience/{cn,intl}` |
| 产品分析 | PostHog(`posthog-js`)· FingerprintJS(开源 visitorId)· Umami · GA4/Ads gtag · `/api/track` |
| 其它 | PocketBase JS SDK · QR · PhotoSwipe · `@nomadro/{pay,pb,sdk}` |
Use the built-in continuous integration in GitLab.
业务垂直在 `src/modules/{nav,ebook,community,social,work,notify,vip,audience}`;`src/app` 只挂路由。同源 API 经 Next Route Handler 反代到 FastAPI(如 `/api/work/v1`、`/api/notify/v1`)。
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
### 后端(`apps/api` · FastAPI)
***
| 层 | 技术 |
|---|---|
| 运行时 | FastAPI · Uvicorn |
| 服务 | `ebook_svc` · `community_svc` · `pay_svc` · `social_svc` · `work_svc` · `notify_svc` · `coffee_svc` |
| 独立进程 | `social_main :8020` · `work_main :8021` · `notify_main :8023` · `coffee_main :8024`(主 API 另有统一入口) |
| 数据 | PocketBase(账号/订单等)· SQLite(social / work / notify / coffee) |
| 对象存储 | SeaweedFS S3(`s3.nomadro.com`;社群 / 加入头像共用 `S3_*`) |
| 支付 | 海外 Creem / NOWPayments;国内 zpay · xpay/xorpay;密钥只走 API |
# Editing this README
### 周边同仓
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
| 端 | 技术 |
|---|---|
| 小程序 | Taro 4 + React(H5 SoT → 微信 / 抖音 / 小红书);**禁止 web-view 承载业务** |
| 管理后台 | Vite SPA(`apps/admin` · `apps/com/admin`) |
| 运维常见 | Nginx / Caddy · Docker · Umami · Uptime-Kuma · ntfy · SeaweedFS / MinIO |
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## 开源对照(域模型二次开发)
## Name
Choose a self-explaining name for your project.
原则:**读开源域模型后自研进 Nomadro**,同域原生页;**禁止** iframe / 二级域硬嵌官方 UI。上游仅对照:`pnpm work:fetch` · `pnpm notify:fetch`。
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
| 开源项目 | 用途 | Nomadro 落点 |
|---|---|---|
| [Planka](https://github.com/plankanban/planka) | 看板域模型 | `/social/work/boards` · `work_svc` |
| [Etherpad](https://github.com/ether/etherpad) | 协作文档 / 修订 | `/social/work/pads` · `work_svc` |
| [Novu](https://github.com/novuhq/novu) | 通知工作流 / Inbox | `/social/notify` · `/notifications` · `notify_svc` |
| [Cal.com](https://github.com/calcom/cal.com) | 预约 / 日程 / 时段 | `/social/coffeechat` · `coffee_svc` |
| MiroTalk | 视频厅(白标同域) | 社群活动直播 / join |
| Centrifugo | 实时推送 | Social 聊天 WebSocket |
| PocketBase | BaaS / 鉴权与业务库 | `@nomadro/pb` · 支付写库 |
| Taro | 多端小程序 | `apps/miniprogram/*` |
| MapLibre | 地图 | `/social/map` 等 |
| three.js | 3D | 门户 / H5(游戏模块冷冻) |
| [PostHog](https://github.com/PostHog/posthog) | 产品分析 / 事件 | 门户 `src/lib/analytics` · `PortalAnalytics`(env / remote-config) |
| [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs) | 浏览器 fingerprint → visitorId(MIT 开源) | `src/lib/analytics/fingerprint.ts`(挂到 track / PostHog identify) |
| Umami | 隐私友好访问统计 | 运维 · `UmamiAnalytics` |
| Uptime-Kuma | 可用性监控 | 运维 |
| ntfy | 运维通知 | 运维 |
| SeaweedFS / MinIO | 对象存储(头像 / 社群媒体 → `s3.nomadro.com`) | `social_svc` · `community_svc` |
| Caddy | 反代(可选) | 运维 |
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
细节:[`apps/work/README.md`](apps/work/README.md) · [`apps/notify/README.md`](apps/notify/README.md)。
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
### 微信后台(admin.nomadro.cn/wechat)
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
侧栏分组:**总览** · **内容** · **运营** · **数据与发布**。系统字体;侧栏菜单区单独滚动、底栏固定。
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
| 分组 | 菜单 | 路径 |
|------|------|------|
| 总览 | 运营概览 | `/wechat` |
| 内容 | 导航(组内第一) | `/wechat/nav` |
| 内容 | 小册与试读% | `/wechat/books/default` |
| 内容 | **VIP**(二级)→ 运营配置 | `/wechat/vip` |
| | → 电子书(含数字游民提审开关) | `/wechat/vip/ebooks` |
| | → 视频课程 | `/wechat/vip/course` |
| | → 电商 | `/wechat/shop` |
| | → 知识社群 | `/wechat/memo` |
| 总览 | **开关**(模块/入口远程配置) | `/wechat/switches` |
| 运营 | 读者 · VIP 用户 · 订单 | `/wechat/users` · `/wechat/vip-users` · `/wechat/orders` |
| 数据 | 埋点 · 部署检查清单 | `/wechat/events` · `/wechat/checklist` |
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
兼容:`/wechat/vip/library` → 重定向到 `/wechat/vip/ebooks`。
UI 组件:`apps/admin/src/pages/wechat.css` · `apps/admin/src/components/wxUi.tsx`。
发版 admin:`cd apps/admin && pnpm exec vite build && python deploy/redeploy_admin.py`(根仓 `@types/react@19` 时勿裸跑 `tsc -b`)。
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
### 微信小程序 VIP(原生,禁止 web-view)
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
对照 `src/modules/vip` / nomadvip H5,微信端业务内容必须原生页(见 `.cursor/rules/no-webview-content.mdc`):
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
| 能力 | 小程序页 | 说明 |
|------|----------|------|
| VIP 落地 | `pages/vip/index` | 模块锚点真滚动、虚拟支付 / 免费方案 |
| 专题课 | `pages/vip-course/index?id=` | `cloudphone` / `livestream` / `indie` / `aiagent` |
| 课时 | `pages/vip-lesson/index` | 原生 Video + 配套 markdown |
| 电子书 | `pages/vip-ebook/index?id=` | `nomad`(免费)/ `cloudphone`(VIP);**Youtube运营笔记**走 `pages/reader?id=default`(后台 books/default) |
| **知识社群** | `pages/vip-memo` · `vip-memo-detail` | 知识星球风格:精华/收藏/Markdown/图/#话题;缓存秒开 |
| **设备商城** | `pages/vip-store*` | 虚拟卡 + 实物发货;微信 `chooseAddress` |
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
内容种子:`h5/src/data/vipEbooks.ts` · `vipLessonContent.ts` · `vipStoreCatalog.ts`(可由 `h5/scripts/extract-vip-*.py` 从 `src/modules/vip/app/data` 重生)。
正式正文库:`data/vip-library.json`(电子书章节 / 视频课 / 课时文档);公开 `GET /api/vip/ebooks/{id}` · `/api/vip/course` · `/api/vip/lessons/{key}`;小程序优先拉远程,失败用包内兜底。落地页运营仍走 `platforms.weapp.vipContent`(`/api/config`)。
下单:`POST /api/ebook/pay/vip-order` · 商城 `/api/ebook/shop/*` · 社群 `/api/ebook/memo/*` · 导航 `/api/admin/nav`。
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
部署脚本(本地构建 admin + 同步 API):
## License
For open source projects, say how it is licensed.
```bash
python apps/admin/deploy/deploy_vip_library.py # VIP 正式内容库 + Admin
python apps/admin/deploy/deploy_vip_admin.py # VIP 付费/落地页运营
python apps/admin/deploy/deploy_nav.py # 导航远程 CRUD
python apps/admin/deploy/deploy_shop.py # 电商
python apps/admin/deploy/deploy_memo.py # 知识社群
python apps/admin/deploy/redeploy_admin.py # 仅同步 admin dist 到线上
```
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
## 本地
根目录一次安装(pnpm workspace):
```bash
pnpm install
pnpm dev # 门户 :3000
pnpm dev:h5 # Taro H5 :10086
pnpm dev:weapp # 微信小程序
pnpm dev:tt # 抖音小程序
pnpm dev:admin # 管理后台 :5173
pnpm dev:api # FastAPI(需先建 apps/api/.venv)
pnpm dev:work-api # 仅本机联调 work_svc :8021;日常 pnpm dev 直连线上 nomadro.com
pnpm dev:notify-api # 通知 notify_svc :8023(收件箱 / 工作流)
pnpm dev:coffee-api # 咖啡聊 coffee_svc :8024(预约 / 时段)
pnpm build:portal
pnpm build:admin
pnpm build:xhs # 小红书离线包 → apps/miniprogram/xhs/release
pnpm typecheck
pnpm clean # 清 .next / dist
```
API 首次:
```bash
cd apps/api
python -m venv .venv
.\.venv\Scripts\pip install -r requirements.txt
cd ../..
pnpm dev:api
```
若原生依赖未构建(esbuild / `@tarojs/binding` 等):`pnpm rebuild`(根 `package.json` 已声明 `pnpm.onlyBuiltDependencies`)。
## 约定
- **业务在 `src/modules/`**,`src/app/` 只挂路由与薄 re-export
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
- 审核冻结分支:`pre4`(历史审核包);历史微信提审包:`test9` + tag `2026-11-02`
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
- **当前开发分支:`test14`**(微信小册提审隔离与热更新在此迭代;历史定版 tag 仍见 `test9`)
### 游民社区(`/social`)
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db` 或 `SOCIAL_DB_PATH`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。
**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。**人脸门禁**(默认开):头像需**单人正脸**;优先 InsightFace 检测 + RGB 活体。**现场自拍核验**(推荐):`POST /api/social/v1/avatar/challenge` 收正脸+转头两帧,校验同人 embedding + 转头幅度后再存头像。关检测:`SOCIAL_AVATAR_FACE_CHECK=false`;关活体:`SOCIAL_AVATAR_LIVENESS=false`。
**地理发现**:`/social/map`、`/social/places`;内部 API `GET /api/social/v1/map/cities`。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
**文字厅(`/social/chat`)**:Centrifugo WS 优先(`/rt` 反代 · token `/api/social/v1/realtime/token`),失败降级轮询。侧栏为 Lobby + **国家频道**(多语言国名,不做大洲分组)。消息能力:未读分隔、在线 presence、发送中态、@提及、转发、已读回执、频道 rail 实时。气泡内 **MessageBilingual**:原文 + 当前 UI 语言译文同框(细线分隔,非第二气泡);不展示活动条 / 置顶条。本地:`pnpm` 起 Next `:3000` + `social_main :8020` + Centrifugo(见 `deploy/social/centrifugo`)。
### 远程工作(`/social/work`)
游民社区「一起做事」下的 **看板 + 实时文档**:读 Planka / Etherpad **域模型后自研** Next + FastAPI,同域挂载,**禁止** iframe / 二级域跳转 / micro-app 壳。
| 能力 | 路由 | 前端 | 后端 |
|------|------|------|------|
| 落地 | `/social/work` | `WorkClient` 品牌首屏;**加入社区门禁**(`WorkAccessGate`) | — |
| 看板 | `/social/work/boards` · `/boards/:id` | DnD · 筛选 · 模板 · 标签/清单/成员/活动流 | `work_svc` |
| 文档 | `/social/work/pads` · `/pads/:id` | 自动保存 · 修订 · 专注/预览/快捷键 · 收藏复制 | 同上 |
```bash
pnpm dev:work-api # 可选本机 :8021;默认 WORK_API_URL=https://nomadro.com(本地前端直连线上)
pnpm dev # http://localhost:3000/social/work
```
数据:`data/work/work.sqlite3`(或 `WORK_DATA_DIR`)。参考 upstream:`pnpm work:fetch`(仅对照,产品不跑 Docker Planka UI)。细节见 [`apps/work/README.md`](apps/work/README.md)。
### 通知(`/notifications` · `/social/notify`)
读 **Novu** 域模型后自研。用户向收件箱与编排控制台分离;同域原生页,**禁止** iframe。
| 能力 | 路由 | 说明 |
|------|------|------|
| 全部通知 | `/social/notifications`(根路径 `/notifications` 重定向) | 分类:社交 / 搭子 / 项目 / 系统;点击跳转;全部/单条已读;删除 |
| 偏好设置 | `/social/notifications/settings` | 免打扰 · 邮件订阅 · 浏览器推送授权 |
| 顶部铃铛 | SiteShell | 未读角标,轮询 `/api/notify/v1/inbox/unread` |
| 编排控制台 | `/social/notify` | 工作流 / 订阅者 / 主题 / 活动(Novu 二次开发) |
```bash
pnpm dev:notify-api # :8023 · NOTIFY_API_URL → /api/notify/v1
pnpm notify:fetch # 可选对照源码
pnpm dev # http://localhost:3000/notifications
```
数据:`data/notify/notify.sqlite3`。细节见 [`apps/notify/README.md`](apps/notify/README.md)。
### 咖啡聊预约(`/social/coffeechat`)
读 **Cal.com** 域模型后自研:Host · EventType · Schedule/Availability · Slots · Booking。同域原生页;咖啡馆点位仍见 `/social/places?tab=cafes`。
```bash
pnpm dev:coffee-api # :8024 · COFFEE_API_URL → /api/coffee/v1
pnpm coffee:fetch # 可选对照源码
pnpm dev # http://localhost:3000/social/coffeechat
```
数据:`data/coffee/coffee.sqlite3`。细节见 [`apps/coffee/README.md`](apps/coffee/README.md)。
**`.com`(美国机,默认发版)**:`python deploy/work/deploy_us.py` → 门户 `nomadro` `:4003` + `nomadro-work` `:8021`;nginx `^~ /api/work/` **直连** work_svc(勿经 Next,避免 `Connection: upgrade` 导致 503)。冒烟:`https://nomadro.com/social/work` · `/api/work/v1/boards`。
| 层 | 线上(82 · `.cn`) | 说明 |
|---|---|---|
| 门户 | `nomadro.service` `:4003` | `/social/*`;前端发版须**本地确认后再上线** |
| Social API | `nomadro-social.service` `:8020` | `apps/api/social_main.py`;nginx `/api/social/` |
| 实时 | `centrifugo.service` `:8008` | `wss://nomadro.cn/rt/connection/websocket`;密钥 `/etc/nomadro/centrifugo.env` |
| 视频 | `mirotalk-p2p` → `mirotalk.nomadro.cn` | 白标中文极速进房;禁 `.com`/107 |
**视觉主题**:代码保留 T1(旅居社群对齐,**默认**)与 T2(琥珀信号,`theme2.css`);导航切换器已隐藏,强制 T1。恢复切换:见 `SiteShell` + `lib/skin.ts`。
**生产铁律**:[`https://nomadro.cn`](https://nomadro.cn/) 全链路只跑 **`82.157.112.245`**。视频厅用同机 **`https://mirotalk.nomadro.cn`**(nginx → `127.0.0.1:9300`),禁止进房再走 `mirotalk.nomadro.com` / 107。
## pre4 摘要(审核包)
- 微信启动页 **`pages/home/index`**;`pages/index` 兼容 `reLaunch` → home
- 本轮标记:**`20261011-2`**(审核中;承接 `20261011b` 路径 + `20261011` 视觉)
- **VIP ↔ Web 账号打通(增量,默认关)**
- Flag:`flags.vipWebBridgeEnabled`(后台 VIP 运营可开;`VIP_WEB_BRIDGE_ENABLED` 可强开)
- 小程序:`VipLoginModal`(rem 底栏)· `pages/vip-account`;已绑定不展示废按钮/支付 hint
- API:`/api/ebook/auth/vip-web-login` · `vip-bind-email` · `vip-bridge-status`(只读校验 vip.hackrobot.cn)
- **网盘 / 课时资料**
- VIP 落地:`netdisk` 列表 + `NetdiskShareModal`(对齐 Web 分享弹窗结构,小程序全宽底栏)
- 课时页:默认**不**展示资料;仅 `lessonMaterials[课时key]` 单独配了 `url` 才显示
- **多端 UI 比例**:`.cursor/skills/multi-platform-ui-scale` + rule(Web 只参考结构,小程序用 rem/rpx)
- **课时播放**:视频 URL 编码空格/中文;本地片源先起播,不挡 `forceRefresh`
- **审核前修复(`20261011-2`)**
- VIP「Youtube运营笔记」→ `reader?id=default`;提审开关不劫持 `book_id=default`
- VIP/加群开关联动;加群点击强制拉最新 `/api/config`
- **P0/P1 加固**(`017008d`):VIP library 鉴权、Mine 登录、game stub、WAL/限流、CORS
## pre5 摘要
从 `pre4` 切出;**勿改动审核包行为**。本轮落地:
- **游民社区**:`/social` 全站能力(加入 / 文字厅 / 活动直播嵌 MiroTalk / coffeechat / 约会 / 花名册 / UGC / 接单 / 反馈 / VIP 入口)
- 隔离 API + SQLite;远程配置 `modules.social`;门户 hero 主入口切换为游民社区
- 社区 Settings `extra="ignore"`,避免统一 `.env` 拖垮 community 启动
## test5
从 `pre5` 切出。已落地(细节以 `deploy/social/README.md` 为准):
- **Social 实时**:Centrifugo + `/api/social/v1/realtime/token`;聊天页优先 WS,失败降级轮询
- **Social API 独立进程**:`nomadro-social` `:8020`,与 ebook/community/pay 隔离
- **MiroTalk**:钉死 82 `.cn`、白标中文、极速进房
- **视觉**:T1 默认;T2 代码保留、切换器隐藏
## test6 / test7(已发版)
游民社区 `/social` 手机端深优(门户 `h5.css` 最后加载):
- **Ways**:`群组聊天 → 认识一下 → 开视频 → 见面 → 找搭子`;竖列表,勿再做成轮播
- **底栏**:首页 → 聊天 → 认识 → 看看谁 → 我;聊天/滑卡操作区避开 dock + safe-area
- **首屏**:群组聊天在左、认识一下在右;窄屏收掉宇宙轨道,Ways 进首视口
- **滑卡 / 群聊**:手机更低滑动阈值、震动反馈;composer / 加入 sheet 全宽底栏
- **Meetup**:活动卡保留参与者头像 + 声纹条
- **发版**:`python deploy/social/deploy_82.py`(仅 82;**2C/4G**:堆 1536MB + swap + nice;打包跳过 `__pycache__`;勿并发 SSH);冒烟 `https://nomadro.cn/social`
## test8
从 `test7` 切出;原生 weapp 游民社区、SRS 直播、加群支付等已合入 `test9`。
## test9 · tag `2026-11-02`(微信提审包)
从 `test8` / `f204063` 线切出并定版,准备上传微信审核与上线。
| 项 | 说明 |
|---|---|
| 分支 / Tag | `test9` · **`2026-11-02`** |
| 启动页 | `pages/home/index`;门户入口 2×2;固定暗色(无主题切换) |
| 远程配置 | `POST /api/config/pull`(避微信 GET 缓存)· `WS /api/config/ws` · SSE `/stream` · meta 兜底;后台 `/wechat/switches` |
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 **audit 正文(默认免费全文)**;关则正式 nomad |
| 提审/正式隔离 | 提审不读正式已购·VIP·付费方案;正式不粘提审免费态;`audit*` 书禁下单 / 禁手动解锁 / 禁配付费档 |
| 配置热更新 | weapp `app.weapp`:WS + 1s poll;封面/阅读页 1s 拉配置;后台开关约 1s 生效 |
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` · VIP 库「微信提审」卡 |
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
| 加入资料 | `/social/join`:支付 → profile 双栏名片 · 头像 `POST /upload` → SeaweedFS `s3.nomadro.com` |
| 同域自研 | `/social/work` · `/social/notify` · `/notifications` · `/social/coffeechat`(禁 iframe) |
提审上传(**须本轮明确许可**,见 `no-frontend-deploy-without-ok`):
```bash
pnpm build:weapp
# 微信开发者工具 / cli 上传 apps/miniprogram/weapp(miniprogramRoot=dist/)
# 后台 VIP→电子书→数字游民打开「提审中」;socket 合法域名含 api.nomadro.cn
# 后端隔离补丁:python apps/admin/deploy/_push_audit_free_isolate.py
```
## pre3 摘要(已合入)
微信提审与包体:
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书(**默认免费**,与正式已购/VIP 隔离),关则回正式 VIP 书;前端不展示「提审」文案
- **入口默认隐藏**:远程配置未就绪不渲染门户卡片 / 模块闸门,避免先闪后藏
- **安全区**:自定义顶栏内联尺寸用大写 `PX` 跳过 Taro rpx;阅读页顶栏不再叠状态栏 padding
- **代码质量**:`lazyCodeLoading` · 分包 + `optimizeMainPackage`(主包 ≪1.5MB)· 导航图标走 `https://nomadro.cn/icons`(包内图片合计 ≤200K)
构建微信包:`pnpm build:weapp` / `pnpm dev:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)。图片域名需放行 `nomadro.cn`。
微信启动首页为 **`pages/home/index`**。历史审核 tag:`20261011` / `20261011b` / `20261011-2`;**本轮提审 tag:`2026-11-02`(分支 `test9`)**。`pages/index/index` 仅兼容 `reLaunch` → home。详见 `apps/miniprogram/weapp/README.md`。

10
apps/README.md Normal file
View File

@ -0,0 +1,10 @@
# apps/
| 目录 | 角色 |
|---|---|
| **`api/`** | 统一 FastAPI(电子书 + 社群 + 支付) |
| **`miniprogram/`** | Taro:`h5` SoT · `weapp` / `tt` / `xhs` |
| **`admin/`** | admin.nomadro.cn 管理 SPA(Vite) |
| **`hackrobot/`** | 异度星球 VIP:`vip.hackrobot.cn` + `admin.hackrobot.cn`(与 Nomadro 后台隔离) |
门户 Next 在仓库根:`src/`(`src/app` + `src/modules`)。

30
apps/admin/.gitignore vendored Normal file
View File

@ -0,0 +1,30 @@
# dependencies
node_modules/
.pnpm-store/
# builds
dist/
admin/dist/
miniapp/dist/
miniapp/.swc/
.temp/
.rn_temp/
*.tsbuildinfo
# python
__pycache__/
*.pyc
.venv/
venv/
backend/.venv/
# runtime db (内容稿保留;库文件大且可重建)
data/*.db
data/*.db-*
data/pocketbase/pb_data/
# ide / os
.DS_Store
.idea/
.vscode/
*.log

76
apps/admin/README.md Normal file
View File

@ -0,0 +1,76 @@
# Nomadro 管理后台(admin.nomadro.cn)
Vite + React SPA。业务 API 经同源反代到 **`nomadmini-api`** / `apps/api`。
> **`.com` Web 后台已源码隔离**:见 [`apps/com`](../com) → `admin.nomadro.com`(美国 VPS,无微信/抖音)。勿把小程序能力做到 `.com` 树,也勿把 `.com` 合回本包。
## 本地
```bash
# 仓库根目录
pnpm install
pnpm dev:admin # :5173
pnpm build:admin
```
## 平台入口
登录后先选平台(数据隔离):
| 入口 | 路径 | 说明 |
|------|------|------|
| 微信小程序 | `/wechat/*` | 读者 · 订单 · 书籍 · **导航** · VIP · **知识社群** · **电商** · 埋点 |
| 抖音小程序 | `/douyin/*` | 首页 A/B · 入口 · **加群弹窗** · 小册 · 验收 |
### 微信:导航(远程 CRUD)
路径 **`/wechat/nav`**:
- 分类 / 分组 / 链接:新增、编辑、隐藏、删除、排序
- 写入 `remote-config.json` 的 `navContent`;门户 `/nav` 与小程序导航实时拉取,离线用包内 `links.json`
- API:`GET/PUT /api/admin/nav`
- 部署:`python apps/admin/deploy/deploy_nav.py`
### 微信:知识社群(对标知识星球)
路径 **`/wechat/memo`**:
- 博主发帖(Markdown / 图片 URL / #话题 / 置顶 / 精华)
- 星球名称、简介、公告与权限(默认仅博主发帖,会员点赞/评论/收藏)
- 小程序页:`vip-memo` 列表(全部/精华/最新/收藏)· `vip-memo-detail` 阅读页
- API:`/api/ebook/memo/*` · 管理 `/api/admin/memo/*`
- 部署:`python apps/admin/deploy/deploy_memo.py`
### 微信:设备商城
路径 **`/wechat/shop`**:
- 商品(虚拟卡密 / 实物发货)、订单履约
- 小程序:`vip-store` · `vip-store-detail` · `vip-store-orders`(含 `chooseAddress`)
- API:`/api/ebook/shop*` · 支付扩展 `shop-order`
- 部署:`python apps/admin/deploy/deploy_shop.py`
### 抖音:加群弹窗(非独立页)
配置在 **`/douyin/modules`**(侧栏「首页与入口」)同页下半段:
- 点选 **微信公众号** / **抖音群** → 即时写 `flags.joinGroupWechat` / `joinGroupDouyin`
- 文案 / 二维码 URL 点「保存文案」
- 旧 URL `/douyin/join-group` 会跳到 `#join-group` 锚点
API:`GET/PUT /api/admin/join-group`
## 部署(git 管理)
本地改 → `pre4`(或当前开发分支)commit/push → 构建 dist → 部署脚本同步线上:
```bash
pnpm build:admin
python apps/admin/deploy/deploy_join_group.py # 前端 dist + 加群 API
python apps/admin/deploy/deploy_nav.py # 导航远程 CRUD
python apps/admin/deploy/deploy_memo.py # 知识社群
python apps/admin/deploy/deploy_shop.py # 设备商城
# 或仅前端:python apps/admin/deploy/_deploy_douyin_ui.py
```
线上静态目录:`/www/wwwroot/admin.nomadro.cn`

View File

@ -0,0 +1,17 @@
# Deploy:脚本与密钥均保留在仓库中,便于本机直接运维
SSH: ubuntu@82.157.112.245 / Xiao4669805
Admin: admin / Xiao4669805
SPA 根目录即 `apps/admin`(已拍平,无嵌套 `admin/`)。
```bash
cd apps/admin
pnpm build
python deploy/redeploy_admin.py # 仅前端 dist
python deploy/deploy_memo.py # 知识社群 API + admin
python deploy/deploy_shop.py # 设备商城 API + admin
# 或历史全量:python deploy/deploy.py(backend 已迁 apps/api,慎用)
```
常用文件:`redeploy_admin.py`、`deploy_memo.py`、`deploy_shop.py`、`deploy.py`、nginx / systemd 配置。

View File

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
import json
import sys
import urllib.request
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
url = "https://api.nomadro.cn/api/ebook/config"
with urllib.request.urlopen(url, timeout=15) as r:
d = json.loads(r.read().decode("utf-8", "replace"))
cfg = d.get("config") or {}
flags = cfg.get("flags") or {}
copy = cfg.get("copy") or {}
plat = ((cfg.get("platforms") or {}).get("weapp") or {})
print("flags.reviewMode / bookAudit =", {k: flags.get(k) for k in flags if "audit" in k.lower() or "review" in k.lower()})
print("copy keys sample", [k for k in copy if "audit" in k.lower() or "book" in k.lower() or "review" in k.lower()])
print("weapp keys", list(plat.keys())[:20])
# dump relevant
import pprint
pprint.pp({k: flags[k] for k in sorted(flags) if k in flags})

View File

@ -0,0 +1,104 @@
# -*- coding: utf-8 -*-
"""Build apps/com/admin and deploy static dist to admin.nomadro.com (US VPS)."""
from __future__ import annotations
import io
import subprocess
import tarfile
import time
from pathlib import Path
import paramiko
US = ("108.174.50.68", "root", "Xiao4669805")
ROOT = Path(__file__).resolve().parents[3]
ADMIN_COM = ROOT / "apps" / "com" / "admin"
REMOTE_ROOT = "/www/wwwroot/admin.nomadro.com"
def build() -> Path:
subprocess.run(
["pnpm", "--filter", "@nomadro/admin-com", "build"],
cwd=str(ROOT),
check=True,
shell=True,
)
dist = ADMIN_COM / "dist"
if not dist.is_dir():
raise SystemExit("dist missing")
return dist
def pack(dist: Path) -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname=p.relative_to(dist).as_posix())
return buf.getvalue()
def main() -> int:
print("=== build ===", flush=True)
dist = build()
blob = pack(dist)
print("pack", len(blob), "bytes", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host, user, password = US
c.connect(host, 22, user, password, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/admin-com.tgz", "wb") as f:
f.write(blob)
sftp.close()
remote = rf"""
set -euo pipefail
mkdir -p {REMOTE_ROOT}
ts=$(date +%Y%m%d%H%M%S)
if [ -d {REMOTE_ROOT} ] && [ "$(ls -A {REMOTE_ROOT} 2>/dev/null)" ]; then
mkdir -p /www/wwwroot/_bak_admin_com
tar -C {REMOTE_ROOT} -czf /www/wwwroot/_bak_admin_com/admin-$ts.tgz . || true
fi
rm -rf {REMOTE_ROOT}.new
mkdir -p {REMOTE_ROOT}.new
tar -xzf /tmp/admin-com.tgz -C {REMOTE_ROOT}.new
# atomic swap
rm -rf {REMOTE_ROOT}.old
mv {REMOTE_ROOT} {REMOTE_ROOT}.old 2>/dev/null || true
mv {REMOTE_ROOT}.new {REMOTE_ROOT}
rm -rf {REMOTE_ROOT}.old
# spa fallback already in nginx; smoke
curl -sk -o /dev/null -w "admin_home %{{http_code}}\n" https://admin.nomadro.com/
curl -sk https://admin.nomadro.com/ | tr '\n' ' ' | grep -o 'Nomadro' | head -1 || true
# keep API up
systemctl is-active nomadmini-api
curl -sS -o /tmp/login.json -w "login %{{http_code}}\n" --max-time 10 -X POST https://api.nomadro.com/api/admin/login \
-H 'content-type: application/json' \
-d '{{"username":"hackrobot","password":"Xiao4669805@"}}'
head -c 120 /tmp/login.json; echo
echo DEPLOY_ADMIN_COM_OK
"""
chan = c.get_transport().open_session()
chan.settimeout(180)
chan.get_pty()
chan.exec_command(remote)
buf = []
end = time.time() + 180
while time.time() < end:
if chan.recv_ready():
buf.append(chan.recv(65536).decode("utf-8", "replace"))
if chan.exit_status_ready():
while chan.recv_ready():
buf.append(chan.recv(65536).decode("utf-8", "replace"))
break
time.sleep(0.05)
print("".join(buf)[-5000:], flush=True)
code = chan.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""Deploy books_live + admin router (offer hot bump) to api.nomadro.cn."""
from __future__ import annotations
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(
REPO / "apps/api/services/ebook_svc/services/books_live.py",
"/opt/nomadmini/backend/app/services/books_live.py",
),
(
REPO / "apps/api/services/ebook_svc/routers/admin.py",
"/opt/nomadmini/backend/app/routers/admin.py",
),
]
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for src, dest in FILES:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
tmp = f"/tmp/{Path(dest).name}"
with sftp.file(tmp, "wb") as rf:
rf.write(data)
print("up", src.name, len(data))
sftp.close()
_, o, e = c.exec_command(
"sudo cp /tmp/books_live.py /opt/nomadmini/backend/app/services/books_live.py && "
"sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py && "
"sudo systemctl restart nomadmini-api.service && sleep 2 && "
"systemctl is-active nomadmini-api.service && curl -s http://127.0.0.1:8010/health",
timeout=60,
)
print(o.read().decode())
err = e.read().decode()
if err:
print("STDERR", err[-800:])
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Build admin SPA and rsync dist to admin.nomadro.cn (frontend only)."""
from __future__ import annotations
import subprocess
import tarfile
import time
from io import BytesIO
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
ADMIN = ROOT # SPA root (flattened)
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
print("building…", flush=True)
r = subprocess.run(
["pnpm", "build"],
cwd=ADMIN,
shell=True,
capture_output=True,
text=True,
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
# fallback npm
r2 = subprocess.run(
"npm run build",
cwd=ADMIN,
shell=True,
capture_output=True,
text=True,
)
print(r2.stdout)
print(r2.stderr)
if r2.returncode != 0:
return r2.returncode or 1
else:
print(r.stdout[-800:] if r.stdout else "ok", flush=True)
dist = ADMIN / "dist"
if not dist.exists():
print("no dist")
return 1
buf = BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
buf.seek(0)
print(f"pack {buf.getbuffer().nbytes} bytes", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/dy-ui-admin.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf dy-ui-unpack && mkdir dy-ui-unpack
tar -xzf dy-ui-admin.tar.gz -C dy-ui-unpack
sudo rsync -a --delete dy-ui-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
curl -sk -o /dev/null -w "douyin %{http_code}\n" https://admin.nomadro.cn/douyin
ls /www/wwwroot/admin.nomadro.cn/assets/ | head -8
rm -rf dy-ui-unpack dy-ui-admin.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""Deploy Douyin homeVariant A/B: admin SPA + API + seed remote-config."""
from __future__ import annotations
import io
import subprocess
import sys
import tarfile
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REPO = Path(__file__).resolve().parents[3]
ADMIN = REPO / "apps" / "admin"
API_SVC = REPO / "apps" / "api" / "services" / "ebook_svc"
def build_admin() -> Path:
print("building admin SPA (vite only)…", flush=True)
# monorepo 根 @types/react@19 会让 tsc -b 炸;生产只需要 vite bundle
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ADMIN,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout[-2000:] if r.stdout else "")
print(r.stderr[-2000:] if r.stderr else "")
raise SystemExit(f"admin build failed: {r.returncode}")
dist = ADMIN / "dist"
if not dist.is_dir():
raise SystemExit("no apps/admin/dist")
print((r.stdout or "")[-400:], flush=True)
print("build ok", flush=True)
return dist
def rewrite_app_imports(src: Path) -> str:
"""Local monorepo uses ebook_svc.*; production /opt/nomadmini uses app.*."""
text = src.read_text(encoding="utf-8")
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf dy-hv-unpack && mkdir dy-hv-unpack
tar -xzf dy-home-variant.tar.gz -C dy-hv-unpack
echo "==> admin SPA"
sudo rsync -a --delete dy-hv-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo "==> API files"
B=/opt/nomadmini/backend/app
sudo cp dy-hv-unpack/api/douyin_admin.py "$B/routers/douyin_admin.py"
sudo cp dy-hv-unpack/api/tt_platform_config.py "$B/services/tt_platform_config.py"
if [ -f dy-hv-unpack/api/track.py ]; then
sudo cp dy-hv-unpack/api/track.py "$B/services/track.py"
fi
sudo chown ubuntu:ubuntu "$B/routers/douyin_admin.py" "$B/services/tt_platform_config.py" "$B/services/track.py" 2>/dev/null || true
echo "==> seed homeVariant (keep live modules/book)"
sudo python3 <<'PY'
import json
from datetime import datetime, timezone
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
cfg = json.loads(p.read_text(encoding="utf-8"))
plats = cfg.setdefault("platforms", {})
tt = dict(plats.get("tt") or {})
if tt.get("homeVariant") not in ("bmi", "hub"):
tt["homeVariant"] = "bmi"
print("set homeVariant=bmi")
else:
print("keep homeVariant", tt.get("homeVariant"))
# ensure modules skeleton
mods = tt.setdefault("modules", {})
for key, title in (("nav", "出海导航"), ("book", "数字游民小册"), ("community", "旅居社群")):
if key not in mods or not isinstance(mods[key], dict):
mods[key] = {"enabled": False, "title": title, "tabLabel": title[:2]}
plats["tt"] = tt
cfg["platforms"] = plats
cfg["updatedAt"] = datetime.now(timezone.utc).isoformat()
# backup
bak = p.with_suffix(".json.bak-homevariant")
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
print("tt.homeVariant", tt.get("homeVariant"))
print("tt.mods", {k: (v or {}).get("enabled") for k, v in (tt.get("modules") or {}).items()})
PY
echo "==> restart API"
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
echo "==> smoke"
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
curl -sk -o /dev/null -w "douyin %{http_code}\n" https://admin.nomadro.cn/douyin
curl -sk -o /dev/null -w "meta_noauth %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/meta
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"Xiao4669805"}')
TOKEN=$(echo "$BODY" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
echo "token_len=${#TOKEN}"
if [ -n "$TOKEN" ]; then
curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/config \
| python3 -c 'import sys,json; d=json.load(sys.stdin); c=d.get("config") or {}; print("ok", d.get("ok"), "homeVariant", c.get("homeVariant"), "mods", list((c.get("modules") or {}).keys()))'
fi
# SPA bundle should mention 首页变体 / homeVariant copy
grep -o '首页变体\|Home A / B\|BMI 健康管理\|homeVariant' /www/wwwroot/admin.nomadro.cn/assets/*.js 2>/dev/null | head -8 || true
rm -rf dy-hv-unpack dy-home-variant.tar.gz
echo DONE
"""
def main() -> int:
dist = build_admin()
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
for name, src in (
("api/douyin_admin.py", API_SVC / "routers" / "douyin_admin.py"),
("api/tt_platform_config.py", API_SVC / "services" / "tt_platform_config.py"),
("api/track.py", API_SVC / "services" / "track.py"),
):
data = rewrite_app_imports(src).encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
buf.seek(0)
print(f"pack {buf.getbuffer().nbytes} bytes", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/dy-home-variant.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command(REMOTE_SH, timeout=240, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
"""Deploy admin.py (book shells) + admin SPA for per-book monetize."""
from __future__ import annotations
import subprocess
import tarfile
import time
from io import BytesIO
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
ROOT = REPO / "apps" / "admin"
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
print("vite build…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
return r.returncode
dist = ROOT / "dist"
buf = BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
buf.seek(0)
api = (REPO / "apps/api/services/ebook_svc/routers/admin.py").read_text(encoding="utf-8")
api = api.replace("ebook_svc.", "app.").encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/admin-spa.tar.gz", "wb") as rf:
rf.write(buf.getvalue())
with sftp.file("/tmp/admin.py", "wb") as rf:
rf.write(api)
sftp.close()
cmd = r"""
set -e
# keep props
sudo mkdir -p /tmp/props-bak && sudo cp -a /www/wwwroot/admin.nomadro.cn/props/. /tmp/props-bak/ 2>/dev/null || true
cd /tmp
rm -rf admin-unpack && mkdir admin-unpack
tar -xzf admin-spa.tar.gz -C admin-unpack
sudo rsync -a --delete admin-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo mkdir -p /www/wwwroot/admin.nomadro.cn/props
sudo cp -a /tmp/props-bak/. /www/wwwroot/admin.nomadro.cn/props/ 2>/dev/null || true
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py
sudo systemctl restart nomadmini-api.service
sleep 2
systemctl is-active nomadmini-api.service
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/vip/ebooks/nomad
curl -sk -o /dev/null -w "props %{http_code}\n" https://admin.nomadro.cn/props/nomad_lite.png
"""
_, stdout, stderr = c.exec_command(cmd, timeout=120)
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print("STDERR", err[-800:])
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,109 @@
# -*- coding: utf-8 -*-
"""Push ops prop catalog (products.py / vip_config) to api.nomadro.cn + migrate old SKUs."""
from __future__ import annotations
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(
REPO / "apps/api/services/ebook_svc/domains/books/products.py",
"/opt/nomadmini/backend/app/domains/books/products.py",
),
(
REPO / "apps/api/services/ebook_svc/services/vip_config.py",
"/opt/nomadmini/backend/app/services/vip_config.py",
),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for src, dest in FILES:
data = rewrite(src.read_text(encoding="utf-8")).encode("utf-8")
tmp = f"/tmp/{Path(dest).name}"
with sftp.file(tmp, "wb") as rf:
rf.write(data)
print("up", src.name, "->", dest, len(data))
sftp.close()
remote = r"""
set -e
sudo cp /tmp/products.py /opt/nomadmini/backend/app/domains/books/products.py
sudo cp /tmp/vip_config.py /opt/nomadmini/backend/app/services/vip_config.py
sudo chown -R ubuntu:ubuntu /opt/nomadmini/backend/app/domains/books/products.py /opt/nomadmini/backend/app/services/vip_config.py
# 旧微信草稿 id → 新运营 SKU(书籍 + 商城商品)
python3 <<'PY'
import sqlite3
db = "/opt/nomadmini/data/nomadmini.db"
con = sqlite3.connect(db)
maps = {
"29": "nomad_lite",
"298": "nomad_plus",
"588": "nomad_pro",
"test": "pay_test",
}
# books.product_id
for old, new in maps.items():
cur = con.execute("update books set product_id=? where product_id=?", (new, old))
print("books", old, "->", new, "rows", cur.rowcount)
# shop products wxProductId if column exists
cols = {r[1] for r in con.execute("pragma table_info(shop_products)").fetchall()} if con.execute(
"select name from sqlite_master where type='table' and name='shop_products'"
).fetchone() else set()
if "wxProductId" in cols or "wx_product_id" in cols:
col = "wxProductId" if "wxProductId" in cols else "wx_product_id"
for old, new in maps.items():
cur = con.execute(f"update shop_products set {col}=? where {col}=?", (new, old))
print("shop", old, "->", new, "rows", cur.rowcount)
# goods table variants
for table in ("products", "goods"):
row = con.execute(
"select name from sqlite_master where type='table' and name=?", (table,)
).fetchone()
if not row:
continue
cols = {r[1] for r in con.execute(f"pragma table_info({table})").fetchall()}
for col in ("wxProductId", "wx_product_id", "product_id"):
if col not in cols:
continue
for old, new in maps.items():
cur = con.execute(f"update {table} set {col}=? where {col}=?", (new, old))
if cur.rowcount:
print(table, col, old, "->", new, "rows", cur.rowcount)
con.commit()
# show current book SKUs
print("--- books product_id ---")
for r in con.execute("select id, title, product_id, price_fen from books order by id").fetchall():
print(r)
con.close()
PY
sudo systemctl restart nomadmini-api.service
sleep 2
systemctl is-active nomadmini-api.service
curl -s http://127.0.0.1:8010/health || true
echo
"""
_, o, e = c.exec_command(remote, timeout=120)
print(o.read().decode())
err = e.read().decode()
if err:
print("stderr", err[-2000:])
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Diagnose config source mismatch: admin PUT vs public /api/config."""
from __future__ import annotations
import json
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo '=== remote-config.json tt ==='
python3 - <<'PY'
import json
from pathlib import Path
for p in [
Path('/var/www/nomadro.cn/data/remote-config.json'),
Path('/opt/nomadmini/backend/data/tt-platform-config.json'),
Path('/opt/nomadmini/data/tt-platform-config.json'),
]:
print('---', p, 'exists', p.exists())
if not p.exists():
continue
try:
d=json.loads(p.read_text(encoding='utf-8'))
except Exception as e:
print('read err', e); continue
tt=(d.get('platforms') or {}).get('tt') if 'platforms' in d else d
if not isinstance(tt, dict):
tt={}
mods=tt.get('modules') or {}
print('homeVariant', tt.get('homeVariant'))
print('mods', {k:(v or {}).get('enabled') for k,v in mods.items()})
print('mtime', p.stat().st_mtime)
PY
echo '=== who serves api.nomadro.cn/api/config ==='
curl -sk https://api.nomadro.cn/api/config | python3 -c 'import sys,json; d=json.load(sys.stdin); print("source", d.get("source")); tt=((d.get("config") or {}).get("platforms") or {}).get("tt") or {}); print("hv", tt.get("homeVariant")); print("mods", {k:(v or {}).get("enabled") for k,v in (tt.get("modules") or {}).items()})'
echo '=== nginx hint ==='
sudo grep -R "api.nomadro.cn\|/api/config" /www/server/panel/vhost/nginx/ /etc/nginx/ 2>/dev/null | head -30 || true
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Diagnose + fix: ensure admin write and public config share same file."""
from __future__ import annotations
import json
import sys
import time
import urllib.request
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASSWD = "82.157.112.245", "ubuntu", "Xiao4669805"
BASE = "https://admin.nomadro.cn"
CMD = r"""
set -e
echo '=== resolve path from API code ==='
cd /opt/nomadmini/backend && .venv/bin/python - <<'PY'
from app.services.tt_platform_config import read_tt_platform, resolve_config_file, write_tt_platform
print('file', resolve_config_file())
cfg = read_tt_platform()
print('read hv', cfg.get('homeVariant'))
print('read mods', {k:(v or {}).get('enabled') for k,v in (cfg.get('modules') or {}).items()})
PY
echo '=== public config ==='
curl -sk https://api.nomadro.cn/api/config | python3 - <<'PY'
import sys, json
d=json.load(sys.stdin)
print('source', d.get('source'))
tt=((d.get('config') or {}).get('platforms') or {}).get('tt') or {}
print('public hv', tt.get('homeVariant'))
print('public mods', {k:(v or {}).get('enabled') for k,v in (tt.get('modules') or {}).items()})
PY
"""
def http(method: str, path: str, token: str | None = None, body: dict | None = None):
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWD, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=90, get_pty=True)
out = ""
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
out += chunk
print(chunk, end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
chunk = stdout.channel.recv(65536).decode("utf-8", "replace")
out += chunk
print(chunk, end="", flush=True)
c.close()
login = http("POST", "/api/admin/login", body={"username": "admin", "password": "Xiao4669805"})
token = login.get("token") or login.get("access_token")
adm = http("GET", "/api/admin/douyin/config", token=token)
cfg = adm.get("config") or {}
print("admin hv", cfg.get("homeVariant"))
print("admin mods", {k: (v or {}).get("enabled") for k, v in (cfg.get("modules") or {}).items()})
# Force write hub then bmi roundtrip via admin API to prove public follows
print("=== roundtrip hub ===", flush=True)
http("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": "hub"})
time.sleep(1)
pub = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config", timeout=20).read().decode())
tt = ((pub.get("config") or {}).get("platforms") or {}).get("tt") or {}
print("public after hub", tt.get("homeVariant"))
print("=== roundtrip bmi ===", flush=True)
http("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": "bmi"})
time.sleep(1)
pub2 = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config", timeout=20).read().decode())
tt2 = ((pub2.get("config") or {}).get("platforms") or {}).get("tt") or {}
print("public after bmi", tt2.get("homeVariant"))
ok = tt.get("homeVariant") == "hub" and tt2.get("homeVariant") == "bmi"
print("SYNC_OK" if ok else "SYNC_FAIL")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Diagnose Douyin config 500 and fix parents IndexError on server."""
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
set -e
echo '=== journal ==='
sudo journalctl -u nomadmini-api -n 40 --no-pager | tail -40
echo '=== local import test ==='
cd /opt/nomadmini/backend
sudo -u ubuntu python3 <<'PY'
import sys
sys.path.insert(0, '.')
try:
from app.services.tt_platform_config import read_tt_platform, resolve_config_file, _candidate_paths
print('path', resolve_config_file())
print('cands', [str(p) for p in _candidate_paths()])
cfg = read_tt_platform()
print('ok modules', list((cfg.get('modules') or {}).keys()))
print('chapters', len((cfg.get('bookContent') or {}).get('chapters') or []))
except Exception as e:
import traceback
traceback.print_exc()
PY
echo '=== curl config no auth ==='
curl -sk -o /tmp/dy_cfg.json -w "http %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/config
head -c 300 /tmp/dy_cfg.json; echo
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, stderr = c.exec_command(REMOTE, timeout=120, get_pty=True)
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
print(out)
if err.strip():
print("STDERR", err)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set +e
echo '=== systemd api-ish ==='
systemctl list-units --type=service --all --no-pager 2>/dev/null | grep -iE 'api|pay|uvicorn|nomad|fastapi|ebook' || true
echo
echo '=== known services ==='
for s in nomadmini-api payjsapi payjsapi-api nomadro-api api ebook-api wemini-api; do
if systemctl status "$s" >/dev/null 2>&1 || systemctl cat "$s" >/dev/null 2>&1; then
echo "-- $s --"
systemctl show "$s" -p Id -p ActiveState -p WorkingDirectory -p FragmentPath -p ExecStart --no-pager 2>/dev/null
echo
fi
done
echo '=== dirs ==='
ls -d /opt/*/backend /opt/*/app /www/wwwroot/*/backend /www/wwwroot/payjsapi /www/wwwroot/api 2>/dev/null
echo
echo '=== ports ==='
ss -lntp 2>/dev/null | grep -E ':(8000|8007|8010|8080)\s' || true
echo
echo '=== curls ==='
for u in \
'https://api.nomadro.cn/health' \
'https://api.nomadro.cn/v1/health' \
'https://api.nomadro.cn/docs' \
'http://127.0.0.1:8000/v1/health' \
'http://127.0.0.1:8007/health' \
'http://127.0.0.1:8010/health'
do
code=$(curl -sk -m 5 -o /tmp/h.txt -w '%{http_code}' "$u"); echo "$code $u"; head -c 120 /tmp/h.txt; echo; echo
done
"""
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command(CMD, timeout=90, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Export VIP formal content seed JSON from miniprogram H5 data TS files."""
from __future__ import annotations
import json
import re
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
H5 = REPO / "apps" / "miniprogram" / "h5" / "src" / "data"
OUT = REPO / "apps" / "api" / "services" / "ebook_svc" / "data" / "vip_library_seed.json"
def _extract_json_assign(text: str, name: str):
m = re.search(rf"(?:export\s+)?const {name}\s*(?::[^=]+)?=\s*", text)
if not m:
raise SystemExit(f"missing {name}")
i = m.end()
while i < len(text) and text[i].isspace():
i += 1
if text[i] not in "{[":
raise SystemExit(f"{name}: expected object/array")
open_ch, close_ch = ("{", "}") if text[i] == "{" else ("[", "]")
depth = 0
in_str = False
esc = False
j = i
while j < len(text):
ch = text[j]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
else:
if ch == '"':
in_str = True
elif ch == open_ch:
depth += 1
elif ch == close_ch:
depth -= 1
if depth == 0:
raw = text[i : j + 1]
# TS → JSON: trailing commas, quotes, bare keys
raw = re.sub(r",\s*([}\]])", r"\1", raw)
raw = re.sub(r"(?m)^\s*'([^']+)'\s*:", r'"\1":', raw)
raw = re.sub(r"([{\[,]\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:", r'\1"\2":', raw)
raw = re.sub(r":\s*'([^']*)'", r': "\1"', raw)
return json.loads(raw)
j += 1
raise SystemExit(f"{name}: unclosed")
def main() -> int:
ebooks = _extract_json_assign((H5 / "vipEbooks.ts").read_text(encoding="utf-8"), "VIP_EBOOKS")
course_txt = (H5 / "vipCourse.ts").read_text(encoding="utf-8")
videos = _extract_json_assign(course_txt, "V")
fallback = (
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
)
# RAW uses unquoted keys — parse lesson rows via regex
row_re = re.compile(
r"\{\s*name:\s*'([^']*)'\s*,\s*duration:\s*'([^']*)'\s*,\s*key:\s*'([^']*)'\s*\}"
)
mod_re = re.compile(
r"\{\s*emoji:\s*'([^']*)'\s*,\s*title:\s*'([^']*)'\s*,\s*lessons:\s*\[(.*?)\]\s*,?\s*\}",
re.S,
)
# slice RAW block
mi0 = course_txt.find("const RAW =")
mi1 = course_txt.find("] as const", mi0)
raw_block = course_txt[mi0:mi1]
course_mods = []
for mi, mm in enumerate(mod_re.finditer(raw_block)):
lessons_list = []
for li, lm in enumerate(row_re.finditer(mm.group(3))):
key = lm.group(3)
lessons_list.append(
{
"key": key,
"moduleIndex": mi,
"lessonIndex": li,
"name": lm.group(1),
"duration": lm.group(2),
"videoUrl": str(videos.get(key) or fallback),
}
)
course_mods.append(
{"emoji": mm.group(1), "title": mm.group(2), "lessons": lessons_list}
)
if not course_mods:
raise SystemExit("failed to parse RAW modules")
lessons = _extract_json_assign(
(H5 / "vipLessonContent.ts").read_text(encoding="utf-8"), "VIP_LESSON_CONTENT"
)
lib = {
"version": 1,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"ebooks": ebooks,
"course": {"id": "cloudphone", "title": "云手机实战课", "modules": course_mods},
"lessons": lessons,
}
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(lib, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
print(
"wrote",
OUT,
"ebooks",
list(ebooks.keys()),
"modules",
len(course_mods),
"lessons",
len(lessons),
"kb",
OUT.stat().st_size // 1024,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,110 @@
# -*- coding: utf-8 -*-
"""Fix audit book API 500 (missing chapter order) + deploy read_policy/store."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(
REPO / "apps/api/services/ebook_svc/domains/books/read_policy.py",
"/opt/nomadmini/backend/app/domains/books/read_policy.py",
),
(
REPO / "apps/api/services/ebook_svc/services/store.py",
"/opt/nomadmini/backend/app/services/store.py",
),
]
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for src, dest in FILES:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
tmp = f"/tmp/{Path(dest).name}"
with sftp.file(tmp, "wb") as rf:
rf.write(data)
print("upload", src.name, flush=True)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/read_policy.py /opt/nomadmini/backend/app/domains/books/read_policy.py
sudo cp /tmp/store.py /opt/nomadmini/backend/app/services/store.py
python3 - <<'PY'
import json, sqlite3, time
db='/opt/nomadmini/data/nomadmini.db'
con=sqlite3.connect(db)
row=con.execute("select chapters_json from books where id='audit'").fetchone()
if row:
ch=json.loads(row[0] or '[]')
fixed=[]
for i,c in enumerate(ch if isinstance(ch,list) else []):
if not isinstance(c, dict):
continue
c=dict(c)
c['id']=str(c.get('id') or f'ch-{i+1}')
c['title']=str(c.get('title') or f'章节 {i+1}')
c['order']=int(c['order']) if c.get('order') is not None else i+1
c['content']=str(c.get('content') or '')
fixed.append(c)
if not fixed:
fixed=[{
'id':'01-audit','title':'欢迎阅读','order':1,
'content':'# 数字游民·提审版\n\n这是微信提审用的独立内容,与会员正式书无关。\n'
}]
con.execute(
"update books set title=?, subtitle=?, unlock_percent=100, price_fen=0, product_id='', chapters_json=?, updated_at=? where id='audit'",
('数字游民·提审版','微信提审专用 · 与正式会员书无关', json.dumps(fixed, ensure_ascii=False), time.time())
)
con.commit()
print('fixed chapters', len(fixed), 'orders', [x['order'] for x in fixed])
else:
print('no audit row')
PY
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
curl -sk -o /tmp/audit.json -w "books/audit %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit"
python3 - <<'PY'
import json
d=json.load(open('/tmp/audit.json',encoding='utf-8'))
print('title', d.get('title'), 'chapters', len(d.get('chapters') or []), 'free', d.get('is_free'))
print('ch0', (d.get('chapters') or [{}])[0])
PY
curl -sk -o /tmp/audit_read.json -w "books/audit/read %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit/read"
python3 - <<'PY'
import json
d=json.load(open('/tmp/audit_read.json',encoding='utf-8'))
chs=d.get('chapters') or []
print('read chapters', len(chs), 'title', (d.get('book') or {}).get('title'))
if chs:
print('body', (chs[0].get('content') or '')[:120].replace('\n',' '))
PY
rm -f /tmp/read_policy.py /tmp/store.py /tmp/audit.json /tmp/audit_read.json
"""
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(REPO / "apps/api/services/ebook_svc/core/deps.py", "/opt/nomadmini/backend/app/core/deps.py"),
(REPO / "apps/api/services/ebook_svc/routers/books.py", "/opt/nomadmini/backend/app/routers/books.py"),
]
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for src, dest in FILES:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
with sftp.file(f"/tmp/{Path(dest).name}", "wb") as rf:
rf.write(data)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/deps.py /opt/nomadmini/backend/app/core/deps.py
sudo cp /tmp/books.py /opt/nomadmini/backend/app/routers/books.py
sudo systemctl restart nomadmini-api
sleep 2
curl -sk -o /tmp/r.json -w "read %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit/read
python3 - <<'PY'
import json
d=json.load(open('/tmp/r.json',encoding='utf-8'))
print('title', (d.get('book') or {}).get('title'))
print('chapters', len(d.get('chapters') or []))
body=((d.get('chapters') or [{}])[0].get('content') or '')[:100]
print('body', body.replace('\n',' '))
PY
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
set -e
ls -la /www/server/panel/vhost/nginx/*api* 2>/dev/null || true
echo ---CONF---
CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
if [ -f "$CONF" ]; then
grep -n 'config/ws\|proxy_pass\|location /' "$CONF" | head -80
else
echo missing_conf
ls /www/server/panel/vhost/nginx/ | head
fi
echo ---DIRECT---
curl -sk -i -N --max-time 3 \
-H 'Connection: Upgrade' \
-H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
http://127.0.0.1:8010/api/config/ws | head -30
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(REMOTE, timeout=60)
print(stdout.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
set -e
echo '=== find api host conf ==='
sudo grep -RIl 'api.nomadro.cn' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30
echo '=== find 8010 ==='
sudo grep -RIl '8010' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30
echo '=== our bak? ==='
ls -la /www/server/panel/vhost/nginx/api.nomadro.cn.conf* 2>/dev/null || true
ls -la /www/server/panel/vhost/nginx/*.bak-config-ws 2>/dev/null || true
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(REMOTE, timeout=90)
print(stdout.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,72 @@
# -*- coding: utf-8 -*-
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
EXT=/www/server/panel/vhost/nginx/extension/www.nomadro.cn/live-flv.conf
sudo tee "$EXT" >/dev/null <<'EOF'
# Nomadro social native live — must beat Next catch-all
location ^~ /live/ {
proxy_pass http://127.0.0.1:1985/live/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
chunked_transfer_encoding on;
add_header Access-Control-Allow-Origin * always;
add_header Cache-Control no-cache always;
add_header X-Nomadro-Live srs always;
}
EOF
sudo nginx -t
sudo systemctl reload nginx
echo '=== public /live/ headers ==='
curl -skI --max-time 5 'https://nomadro.cn/live/nope.flv' | head -20 || true
echo '=== local srs headers ==='
curl -sI --max-time 3 'http://127.0.0.1:1985/live/nope.flv' | head -15 || true
echo '=== join 2 peers ==='
curl -sk --max-time 8 -X POST 'https://nomadro.cn/api/social/v1/live/rooms/hall1/join' \
-H 'Content-Type: application/json' -H 'X-Social-Guest-Id: peer_alice' \
-d '{"nick":"Alice"}' > /tmp/a.json
curl -sk --max-time 8 -X POST 'https://nomadro.cn/api/social/v1/live/rooms/hall1/join' \
-H 'Content-Type: application/json' -H 'X-Social-Guest-Id: peer_bob' \
-d '{"nick":"Bob"}' > /tmp/b.json
python3 - <<'PY'
import json
a=json.load(open('/tmp/a.json'))
b=json.load(open('/tmp/b.json'))
print('alice_ok', a.get('ok'), 'peers', [p['nick'] for p in a.get('peers',[])])
print('bob_ok', b.get('ok'), 'peers', [p['nick'] for p in b.get('peers',[])])
print('push', (a.get('pushUrl') or '')[:90])
print('play', (a.get('playUrl') or '')[:90])
print('engine', a.get('engine'))
PY
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
print("[exit", stdout.channel.recv_exit_status(), "]", flush=True)
c.close()

View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
echo '=== who serves 443 ==='
sudo ss -lntp | grep ':443'
echo '=== caddy? ==='
systemctl is-active caddy 2>/dev/null || true
ls /etc/caddy 2>/dev/null | head
echo '=== nginx? ==='
systemctl is-active nginx 2>/dev/null || true
sudo nginx -T 2>/dev/null | grep -E 'server_name|8020|api/social|listen 443' | head -40
echo '=== find social proxy ==='
sudo grep -R '8020\|api/social' /etc /var/www -g '!*.log' 2>/dev/null | head -30
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
sudo nginx -T 2>/dev/null | grep -n 'server_name nomadro.cn' | head
# dump the nomadro.cn server block roughly
sudo nginx -T 2>/dev/null | awk '/server_name nomadro.cn/{flag=1} flag{print} /server_name / && !/nomadro.cn/{if(flag&&seen++){exit}}' | head -120
echo '==== conf files ===='
sudo ls /www/server/panel/vhost/nginx 2>/dev/null | head
sudo ls /www/server/nginx/conf/vhost 2>/dev/null | head
ls /etc/nginx/sites-enabled 2>/dev/null
find /www /etc/nginx -name '*nomadro*' 2>/dev/null | head -40
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
find /www/server/panel/vhost/nginx -maxdepth 1 -type f -name '*.conf' | sort
echo '---'
F=$(find /www/server/panel/vhost/nginx -maxdepth 1 -type f -name 'nomadro.cn.conf' | head -1)
echo "F=$F"
if [ -n "$F" ]; then
grep -n 'location\|8020\|proxy_pass\|social\|live\|server_name' "$F" | head -80
fi
# also check extension
ls /www/server/panel/vhost/nginx/extension/nomadro.cn 2>/dev/null || true
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
sudo ls /www/server/panel/vhost/nginx | grep -i nomad | head -40
echo '===='
sudo grep -Rnl 'server_name nomadro.cn' /www/server/panel/vhost/nginx 2>/dev/null | head
F=$(sudo grep -Rnl 'server_name nomadro.cn;' /www/server/panel/vhost/nginx 2>/dev/null | head -1)
echo F=$F
sudo grep -n 'location\|8020\|proxy_pass\|social\|#LIVE' "$F" | head -100
echo '==== ext ===='
sudo ls "/www/server/panel/vhost/nginx/extension/nomadro.cn" 2>/dev/null || true
"""
_, o, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
REMOTE = r"""
CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
sudo sed -n '1,220p' "$CONF"
echo '===== WS LOC ====='
sudo grep -n 'config/ws\|Upgrade\|location ' "$CONF" | head -80
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(REMOTE, timeout=60)
print(stdout.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
"""Patch api.nomadro.cn 443 block for /api/config/ws Upgrade."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
PATCHER = r'''
from pathlib import Path
import shutil
p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
text = p.read_text(encoding="utf-8")
marker = "location /api/config/ws"
parts = text.split("listen 443")
if len(parts) < 2:
raise SystemExit("no 443 block")
if marker in parts[1]:
print("ssl_ws_already")
raise SystemExit(0)
lines = [
"",
" location /api/config/ws {",
" proxy_pass http://127.0.0.1:8010;",
" proxy_http_version 1.1;",
" proxy_set_header Upgrade $http_upgrade;",
' proxy_set_header Connection "upgrade";',
" proxy_set_header Host $host;",
" proxy_set_header X-Real-IP $remote_addr;",
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
" proxy_set_header X-Forwarded-Proto $scheme;",
" proxy_read_timeout 3600s;",
" proxy_send_timeout 3600s;",
" proxy_buffering off;",
" }",
" location /api/ebook/config/ws {",
" proxy_pass http://127.0.0.1:8010;",
" proxy_http_version 1.1;",
" proxy_set_header Upgrade $http_upgrade;",
' proxy_set_header Connection "upgrade";',
" proxy_set_header Host $host;",
" proxy_set_header X-Real-IP $remote_addr;",
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
" proxy_set_header X-Forwarded-Proto $scheme;",
" proxy_read_timeout 3600s;",
" proxy_send_timeout 3600s;",
" proxy_buffering off;",
" }",
"",
]
snippet = "\n".join(lines)
ssl = parts[1]
idx = ssl.find("location / {")
if idx < 0:
raise SystemExit("no location / in 443")
ssl2 = ssl[:idx] + snippet + "\n" + ssl[idx:]
out = parts[0] + "listen 443" + ssl2
shutil.copy2(p, str(p) + ".bak-ws-ssl")
p.write_text(out, encoding="utf-8")
print("ssl_ws_patched")
'''
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/patch_ws_ssl.py", "w") as rf:
rf.write(PATCHER)
sftp.close()
cmd = "sudo python3 /tmp/patch_ws_ssl.py && sudo nginx -t && sudo nginx -s reload && rm -f /tmp/patch_ws_ssl.py && echo DONE"
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,28 @@
#!/usr/bin/env python3
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
LOCAL = Path(__file__).resolve().parents[1] / "backend/app/services/tt_platform_config.py"
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
sftp.put(str(LOCAL), "/tmp/tt_platform_config.py")
sftp.close()
cmd = """
sudo cp /tmp/tt_platform_config.py /opt/nomadmini/backend/app/services/tt_platform_config.py
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w 'api_health %{http_code}\\n' https://api.nomadro.cn/health
curl -sk -o /dev/null -w 'dy_meta %{http_code}\\n' https://admin.nomadro.cn/api/admin/douyin/meta
journalctl -u nomadmini-api -n 12 --no-pager
"""
_, stdout, _ = c.exec_command(cmd, timeout=60, get_pty=True)
print(stdout.read().decode("utf-8", "replace"))
c.close()

View File

@ -0,0 +1,137 @@
# -*- coding: utf-8 -*-
"""Deploy vip_content.py + patch remote-config: Youtube运营笔记 → books/default."""
from __future__ import annotations
import json
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/services/vip_content.py"
YT = {
"id": "youtube-notes",
"title": "Youtube运营笔记",
"desc": "试读可进,单买或 VIP 解锁全文",
"ebookId": "default",
"href": "/pages/reader/index?id=default",
"free": False,
"enabled": True,
"sort": 1,
}
def to_app_pkg(src: Path) -> bytes:
return src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
def main() -> int:
data = to_app_pkg(SRC)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/vip_content_yt.py", "wb") as rf:
rf.write(data)
print("up vip_content", len(data), flush=True)
sftp.close()
patch_json = json.dumps(YT, ensure_ascii=False)
cmd = r"""
set -e
B=/opt/nomadmini/backend/app
sudo cp /tmp/vip_content_yt.py "$B/services/vip_content.py"
# patch remote-config ebooks
python3 <<'PY'
import json
from pathlib import Path
paths = [
Path("/var/www/nomadro.cn/data/remote-config.json"),
Path("/opt/nomadmini/backend/data/remote-config.json"),
]
yt = {
"id": "youtube-notes",
"title": "Youtube运营笔记",
"desc": "试读可进,单买或 VIP 解锁全文",
"ebookId": "default",
"href": "/pages/reader/index?id=default",
"free": False,
"enabled": True,
"sort": 1,
}
for p in paths:
if not p.is_file():
print("skip missing", p)
continue
raw = json.loads(p.read_text(encoding="utf-8"))
platforms = raw.setdefault("platforms", {})
weapp = platforms.setdefault("weapp", {})
vc = weapp.setdefault("vipContent", {})
ebooks = list(vc.get("ebooks") or [])
hit = -1
for i, e in enumerate(ebooks):
if not isinstance(e, dict):
continue
t = str(e.get("title") or "")
if (
e.get("id") == "youtube-notes"
or e.get("ebookId") == "default"
or "youtube" in t.lower()
or "运营笔记" in t
):
hit = i
break
if hit >= 0:
prev = ebooks[hit]
ebooks[hit] = {**yt, "title": prev.get("title") or yt["title"], "desc": prev.get("desc") or yt["desc"], "enabled": prev.get("enabled") is not False, "sort": prev.get("sort", 1)}
else:
idx = next((i for i, e in enumerate(ebooks) if isinstance(e, dict) and (e.get("id") == "1" or e.get("title") == "数字游民")), -1)
if idx >= 0:
ebooks.insert(idx + 1, dict(yt))
else:
ebooks.append(dict(yt))
# fix cloudphone sort if needed
for e in ebooks:
if isinstance(e, dict) and e.get("id") == "2" and e.get("sort") in (None, 1):
e["sort"] = 2
vc["ebooks"] = ebooks
stats = dict(vc.get("stats") or {})
stats["ebooks"] = "3"
vc["stats"] = stats
weapp["vipContent"] = vc
platforms["weapp"] = weapp
raw["platforms"] = platforms
raw["updatedAt"] = raw.get("updatedAt") or ""
bak = p.with_suffix(p.suffix + ".bak-yt")
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
p.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
print("patched", p, "ebooks=", [e.get("id") for e in ebooks if isinstance(e, dict)])
PY
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.services import vip_content as v; d=v.default_vip_content(); ids=[e["id"] for e in d["ebooks"]]; assert "youtube-notes" in ids; print("default_ok", ids)'
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk https://api.nomadro.cn/api/config | python3 -c 'import sys,json; d=json.load(sys.stdin); e=((d.get("config") or {}).get("platforms") or {}).get("weapp",{}).get("vipContent",{}).get("ebooks") or []); print("live_ebooks", [(x.get("id"), x.get("ebookId"), x.get("href")) for x in e])'
rm -f /tmp/vip_content_yt.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Hotfix tt_platform_config.py and verify /api/admin/douyin/config."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
LOCAL = Path(__file__).resolve().parents[1] / "backend" / "app" / "services" / "tt_platform_config.py"
REMOTE = "/opt/nomadmini/backend/app/services/tt_platform_config.py"
def main() -> int:
text = LOCAL.read_text(encoding="utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/tt_platform_config.py", "w") as f:
f.write(text)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/tt_platform_config.py /opt/nomadmini/backend/app/services/tt_platform_config.py
sudo chown ubuntu:ubuntu /opt/nomadmini/backend/app/services/tt_platform_config.py
# also copy seed book if missing
if [ ! -f /opt/nomadmini/backend/data/tt-default-book.json ] && [ -f /var/www/nomadro.cn/lib/tt-default-book.json ]; then
sudo mkdir -p /opt/nomadmini/backend/data
sudo cp /var/www/nomadro.cn/lib/tt-default-book.json /opt/nomadmini/backend/data/
fi
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
cd /opt/nomadmini/backend && .venv/bin/python - <<'PY'
from app.services.tt_platform_config import read_tt_platform, resolve_config_file
print('file', resolve_config_file())
cfg = read_tt_platform()
print('modules', {k: v.get('enabled') for k,v in (cfg.get('modules') or {}).items()})
print('chapters', len((cfg.get('bookContent') or {}).get('chapters') or []))
PY
# login then hit config
TOKEN=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"Xiao4669805"}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token") or json.load(open("/dev/stdin")).get("access_token",""))' 2>/dev/null || true)
# try common login shapes
if [ -z "$TOKEN" ]; then
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}')
echo "login_body=$BODY"
TOKEN=$(echo "$BODY" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
fi
echo "token_len=${#TOKEN}"
if [ -n "$TOKEN" ]; then
curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/config | python3 -c 'import sys,json; d=json.load(sys.stdin); print("config_ok", d.get("ok"), "mods", list((d.get("config") or {}).get("modules") or {}).keys())'
else
curl -sk -o /dev/null -w "config_noauth %{http_code}\n" https://admin.nomadro.cn/api/admin/douyin/config
fi
"""
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,90 @@
# -*- coding: utf-8 -*-
"""Add /live/ FLV proxy next to social-api extension for www.nomadro.cn."""
from __future__ import annotations
import time
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
EXT_DIR=/www/server/panel/vhost/nginx/extension/www.nomadro.cn
sudo mkdir -p "$EXT_DIR"
echo '--- existing ---'
sudo ls -la "$EXT_DIR"
sudo cat "$EXT_DIR/social-api.conf" 2>/dev/null | head -40 || true
# write live-flv.conf
sudo tee "$EXT_DIR/live-flv.conf" >/dev/null <<'EOF'
# Nomadro social native live — SRS HTTP-FLV for WeChat LivePlayer
location /live/ {
proxy_pass http://127.0.0.1:1985/live/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
chunked_transfer_encoding on;
add_header Access-Control-Allow-Origin * always;
add_header Cache-Control no-cache always;
}
EOF
# also ensure www.nomadro.cn.conf exists and includes extension (baota usually does)
F=/www/server/panel/vhost/nginx/www.nomadro.cn.conf
if sudo test -f "$F"; then
echo "www conf exists"
sudo grep -n 'extension\|include\|server_name' "$F" | head -30
else
echo "www conf missing?"
sudo ls /www/server/panel/vhost/nginx | grep -i www || true
fi
sudo nginx -t
sudo systemctl reload nginx
echo '--- verify ---'
curl -sk -o /dev/null -w 'flv_public %{http_code}\n' 'https://nomadro.cn/live/smoke_smoke_peer_1.flv' || true
curl -sk -o /dev/null -w 'www_flv %{http_code}\n' 'https://www.nomadro.cn/live/smoke_smoke_peer_1.flv' || true
curl -sk -o /dev/null -w 'srs_local %{http_code}\n' 'http://127.0.0.1:1985/api/v1/versions' || true
curl -sk 'http://127.0.0.1:1985/api/v1/versions' | head -c 200; echo
curl -sk -X POST 'https://nomadro.cn/api/social/v1/live/rooms/demo/join' \
-H 'Content-Type: application/json' -H 'X-Social-Guest-Id: demo_a' \
-d '{"nick":"A"}' | head -c 350; echo
sudo docker ps --filter name=nomadro-srs --format '{{.Names}} {{.Status}} {{.Ports}}'
systemctl is-active nomadro-social
"""
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Probe live douyin admin / API layout on production."""
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo "=== systemd ==="
systemctl show nomadmini-api -p WorkingDirectory -p FragmentPath --no-pager 2>/dev/null || true
echo "=== files ==="
ls -la /opt/nomadmini/backend/app/routers/douyin_admin.py /opt/nomadmini/backend/app/services/tt_platform_config.py 2>&1 || true
ls -la /opt/nomadmini/backend/app/main.py 2>&1 || true
echo "=== imports ==="
head -20 /opt/nomadmini/backend/app/routers/douyin_admin.py 2>/dev/null || true
echo "=== homeVariant in py ==="
grep -n homeVariant /opt/nomadmini/backend/app/services/tt_platform_config.py 2>/dev/null || echo no_homeVariant
echo "=== remote-config tt ==="
python3 - <<'PY'
import json
from pathlib import Path
p = Path("/var/www/nomadro.cn/data/remote-config.json")
d = json.loads(p.read_text(encoding="utf-8"))
tt = (d.get("platforms") or {}).get("tt") or {}
print("homeVariant", tt.get("homeVariant"))
mods = tt.get("modules") or {}
print("mods", {k: (v or {}).get("enabled") for k, v in mods.items()})
print("chapters", len(((tt.get("bookContent") or {}).get("chapters") or [])))
PY
"""
def main() -> int:
import sys
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, stdout, _ = c.exec_command(CMD, timeout=60, get_pty=True)
print(stdout.read().decode("utf-8", "replace"))
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
CMD = r"""
set -e
echo '=== file head ==='
head -8 /opt/nomadmini/backend/app/domains/books/products.py
echo '=== grep nomad_lite ==='
grep -n nomad_lite /opt/nomadmini/backend/app/domains/books/products.py || true
echo '=== processes ==='
ps aux | grep -E 'uvicorn|nomadmini|gunicorn|8010' | grep -v grep || true
echo '=== pm2 ==='
pm2 list 2>/dev/null || true
echo '=== systemd units ==='
ls /etc/systemd/system/*nom* /etc/systemd/system/*ebook* /etc/systemd/system/*api* 2>/dev/null || true
echo '=== how 8010 listens ==='
sudo ss -lntp | grep -E '8010|8000' || true
echo '=== find restart scripts ==='
ls /opt/nomadmini/*.sh /opt/nomadmini/backend/*.sh 2>/dev/null || true
cat /opt/nomadmini/ecosystem.config.* 2>/dev/null || true
"""
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(CMD, timeout=60)
print(o.read().decode())
err = e.read().decode()
if err:
print("STDERR", err[-1500:])
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-
"""Proxy Centrifugo /rt/ on api.nomadro.cn for weapp socket合法域名."""
from __future__ import annotations
import time
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
# also push latest social api router
from pathlib import Path
repo = Path(__file__).resolve().parents[3]
sftp = c.open_sftp()
for rel, remote in (
("apps/api/services/social_svc/routers/api.py", "/tmp/social_routers_api.py"),
):
data = (repo / rel).read_bytes()
with sftp.file(remote, "wb") as rf:
rf.write(data)
sftp.close()
cmd = r"""
set -e
EXT=/www/server/panel/vhost/nginx/extension/api.nomadro.cn
sudo mkdir -p "$EXT"
# copy www centrifugo snippet if exists, else write
if sudo test -f /www/server/panel/vhost/nginx/extension/www.nomadro.cn/centrifugo-rt.conf; then
sudo cp /www/server/panel/vhost/nginx/extension/www.nomadro.cn/centrifugo-rt.conf "$EXT/centrifugo-rt.conf"
else
sudo tee "$EXT/centrifugo-rt.conf" >/dev/null <<'EOF'
location ^~ /rt/ {
proxy_pass http://127.0.0.1:8008/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
EOF
fi
# ensure social-api still there
sudo test -f "$EXT/social-api.conf" || true
sudo nginx -t
sudo systemctl reload nginx
sudo cp /tmp/social_routers_api.py /var/www/nomadro.cn/apps/api/services/social_svc/routers/api.py
sudo systemctl restart nomadro-social
sleep 2
echo '=== token ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/realtime/token?channel_id=general&guest=chat1' | head -c 280; echo
echo '=== list ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/channels/general/messages?guest=chat1' | head -c 200; echo
echo '=== post ==='
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/channels/general/messages?guest=chat1' \
-H 'Content-Type: application/json' --data-binary '{"author":"系统","text":"Centrifugo 聊天通路已接通"}' | head -c 240; echo
echo '=== list2 ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/channels/general/messages?guest=chat1' | head -c 400; echo
systemctl is-active centrifugo nomadro-social
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
"""Proxy /api/social/ on api.nomadro.cn → nomadro-social:8020 (weapp whitelist)."""
from __future__ import annotations
import time
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
EXT_DIR=/www/server/panel/vhost/nginx/extension/api.nomadro.cn
sudo mkdir -p "$EXT_DIR"
sudo tee "$EXT_DIR/social-api.conf" >/dev/null <<'EOF'
# weapp 合法域名多为 api.nomadro.cn — 社交 live/join 必须可直连
location ^~ /api/social/ {
proxy_pass http://127.0.0.1:8020;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Social-Guest-Id $http_x_social_guest_id;
}
EOF
# ensure api conf includes extension/*.conf
F=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
sudo grep -n 'extension/api.nomadro.cn\|include' "$F" | head -20
if ! sudo grep -q 'extension/api.nomadro.cn/\*\.conf' "$F"; then
# inject include after server_name line in https server
sudo python3 - <<'PY'
from pathlib import Path
p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
text = p.read_text(encoding="utf-8")
inc = " include /www/server/panel/vhost/nginx/extension/api.nomadro.cn/*.conf;\n"
if "extension/api.nomadro.cn" in text:
print("include already")
else:
# after first ssl server_name api.nomadro.cn;
needle = "server_name api.nomadro.cn;"
# prefer the ssl block (second occurrence often); insert after both
parts = text.split(needle)
if len(parts) < 2:
raise SystemExit("no server_name")
out = parts[0]
for i, part in enumerate(parts[1:], 1):
out += needle
if "extension/api.nomadro.cn" not in part[:200]:
out += "\n" + inc
out += part
p.write_text(out, encoding="utf-8")
print("include injected")
PY
fi
sudo nginx -t
sudo systemctl reload nginx
echo '=== api social health ==='
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/health' | head -c 300; echo
echo '=== api live join ==='
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/live/rooms/office/join' \
-H 'Content-Type: application/json' \
-H 'X-Social-Guest-Id: weapp_real_1' \
--data-binary '{"nick":"真机"}' | head -c 400; echo
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,257 @@
# -*- coding: utf-8 -*-
"""Deploy admin SPA + CRUD APIs (stats series, social ugc, community, memo/books/orders).
- Never wipe catalogs unless catalog PUT is called by operator
- Snapshot /api/config version before/after
- Set SOCIAL_DB_PATH + fix social.db perms for www
"""
from __future__ import annotations
import io
import json
import subprocess
import tarfile
import time
import urllib.request
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
ADMIN = REPO / "apps/admin"
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
API_FILES = [
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def snapshot() -> dict:
req = urllib.request.Request(
"https://api.nomadro.cn/api/config",
headers={"User-Agent": "nomadro-admin-crud-deploy"},
)
with urllib.request.urlopen(req, timeout=20) as resp:
data = json.loads(resp.read().decode("utf-8"))
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
return {
"version": cfg.get("version"),
"social": mods.get("social"),
"source": data.get("source"),
}
def build_admin() -> None:
print("vite build…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ADMIN,
shell=True,
capture_output=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
raise SystemExit(r.returncode)
def pack() -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in API_FILES:
src = REPO / rel
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc" in text and dest != "main.py":
# main may mention ebook only in comments; services must be clean
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name="api/" + dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
dist = ADMIN / "dist"
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
buf.seek(0)
blob = buf.read()
print("pack", len(blob), flush=True)
return blob
def main() -> int:
before = snapshot()
print("BEFORE", before, flush=True)
build_admin()
blob = pack()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/admin-crud.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf admin-crud && mkdir admin-crud
tar -xzf admin-crud.tar.gz -C admin-crud
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
echo B=$B
TS=$(date -u +%Y%m%dT%H%M%SZ)
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
for f in \
services/store.py \
services/social_ugc.py \
services/memo_store.py \
services/shop_store.py \
schemas/admin.py \
routers/admin.py \
routers/social_ugc_admin.py \
routers/community_admin.py \
routers/memo_admin.py \
routers/shop_admin.py
do
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
sudo cp "admin-crud/api/$f" "$B/$f"
done
# Patch main.py to include new routers (idempotent)
python3 - <<'PY'
from pathlib import Path
p = Path("/opt/nomadmini/backend/app/main.py")
text = p.read_text(encoding="utf-8")
changed = False
if "social_ugc_admin" not in text:
needle = "from app.routers import social_ops_admin"
if needle in text:
text = text.replace(
needle,
needle
+ "\nfrom app.routers import social_ugc_admin # noqa: E402\nfrom app.routers import community_admin # noqa: E402",
1,
)
changed = True
if "include_router(social_ugc_admin.router)" not in text:
needle2 = "include_router(social_ops_admin.router)"
if needle2 in text:
text = text.replace(
needle2,
needle2
+ "\napp.include_router(social_ugc_admin.router)\napp.include_router(community_admin.router)",
1,
)
changed = True
if changed:
p.write_text(text, encoding="utf-8")
print("patched_main")
else:
print("main_ok")
PY
# social db perms + env for nomadmini-api
sudo mkdir -p /var/www/nomadro-data/social /var/www/nomadro-data/community
if [ -f /var/www/nomadro-data/social/social.db ]; then
sudo chown www:www /var/www/nomadro-data/social/social.db || true
sudo chmod 664 /var/www/nomadro-data/social/social.db || true
sudo chown www:www /var/www/nomadro-data/social || true
fi
sudo mkdir -p /etc/systemd/system/nomadmini-api.service.d
sudo tee /etc/systemd/system/nomadmini-api.service.d/social-db.conf >/dev/null <<'EOF'
[Service]
Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db
Environment=COMMUNITY_STORE_PATH=/var/www/nomadro-data/community/community_store.json
EOF
sudo systemctl daemon-reload
sudo rsync -a --delete /tmp/admin-crud/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_synced
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
AUTH="Authorization: Bearer $TOK"
echo -n 'stats '
curl -sk -o /tmp/st.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
python3 - <<'PY'
import json
d=json.load(open('/tmp/st.json',encoding='utf-8'))
assert 'series' in d, d
print('series_ok', len(d['series'].get('revenue',[])), 'top', len(d.get('topEvents') or []))
PY
echo -n 'social_ugc '
curl -sk -o /tmp/su.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/social/ugc/overview
python3 - <<'PY'
import json
d=json.load(open('/tmp/su.json',encoding='utf-8'))
print('ugc', d.get('exists'), d.get('writable'), d.get('counts'))
PY
echo -n 'community '
curl -sk -o /tmp/co.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/community/overview
for u in /wechat /wechat/social/data /wechat/community /wechat/books; do
curl -sk -o /dev/null -w "admin$u %{http_code}\n" "https://admin.nomadro.cn$u"
done
curl -sk https://api.nomadro.cn/api/config -o /tmp/cfg-after.json
python3 - <<'PY'
import json
d=json.load(open('/tmp/cfg-after.json',encoding='utf-8'))
social=d.get('config',{}).get('modules',{}).get('social')
print('live_social', social)
assert isinstance(social, dict) and social.get('enabled') is True
print('config_ok')
PY
rm -rf /tmp/admin-crud /tmp/admin-crud.tar.gz /tmp/st.json /tmp/su.json /tmp/co.json /tmp/cfg-after.json
"""
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
after = snapshot()
print("AFTER", after, flush=True)
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
print("FAIL config drifted", flush=True)
return 3
print(f"[exit {code}] admin CRUD deployed; version {after.get('version')}", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/routers/admin.py"
DEST = "/opt/nomadmini/backend/app/routers/admin.py"
def main() -> None:
data = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/admin.py", "wb") as rf:
rf.write(data)
sftp.close()
_, o, e = c.exec_command(
"sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py && "
"sudo systemctl restart nomadmini-api.service && sleep 2 && "
"systemctl is-active nomadmini-api.service && curl -s http://127.0.0.1:8010/health",
timeout=60,
)
print(o.read().decode())
err = e.read().decode()
if err:
print("STDERR", err[-800:])
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,229 @@
# -*- coding: utf-8 -*-
"""Deploy pending ebook API backend only (no admin SPA).
- Rewrite ebook_svc.* → app.*
- Hot-copy into /opt/nomadmini/backend/app
- Restart nomadmini-api only
- Snapshot /api/config version before/after (must not drift)
"""
from __future__ import annotations
import io
import json
import tarfile
import time
import urllib.request
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
API_FILES = [
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
("apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"),
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
("apps/api/services/ebook_svc/services/social_ops.py", "services/social_ops.py"),
(
"apps/api/services/ebook_svc/services/public_config_snapshot.py",
"services/public_config_snapshot.py",
),
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
("apps/api/services/ebook_svc/routers/social_ops_admin.py", "routers/social_ops_admin.py"),
("apps/api/services/ebook_svc/routers/public_config.py", "routers/public_config.py"),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def snapshot() -> dict:
req = urllib.request.Request(
"https://api.nomadro.cn/api/config",
headers={"User-Agent": "nomadro-api-backend-deploy"},
)
with urllib.request.urlopen(req, timeout=20) as resp:
data = json.loads(resp.read().decode("utf-8"))
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
return {
"version": cfg.get("version"),
"social": mods.get("social"),
"book": mods.get("book"),
"source": data.get("source"),
}
def pack() -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in API_FILES:
src = REPO / rel
if not src.is_file():
raise SystemExit(f"missing {rel}")
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name="api/" + dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
buf.seek(0)
blob = buf.read()
print("pack", len(blob), "files", len(API_FILES), flush=True)
return blob
def main() -> int:
before = snapshot()
print("BEFORE", before, flush=True)
blob = pack()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/api-backend.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf api-backend && mkdir api-backend
tar -xzf api-backend.tar.gz -C api-backend
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
echo B=$B
TS=$(date -u +%Y%m%dT%H%M%SZ)
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
for f in \
services/store.py \
services/memo_store.py \
services/shop_store.py \
services/weapp_switches.py \
services/social_ugc.py \
services/social_ops.py \
services/public_config_snapshot.py \
schemas/admin.py \
routers/admin.py \
routers/memo_admin.py \
routers/shop_admin.py \
routers/social_ugc_admin.py \
routers/community_admin.py \
routers/social_ops_admin.py \
routers/public_config.py
do
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
sudo cp "api-backend/api/$f" "$B/$f"
echo copied $f
done
# Ensure main.py registers new admin routers (idempotent)
python3 - <<'PY'
from pathlib import Path
candidates = [
Path("/opt/nomadmini/backend/app/main.py"),
]
for p in candidates:
if not p.is_file():
continue
text = p.read_text(encoding="utf-8")
changed = False
imports = [
("social_ops_admin", "from app.routers import social_ops_admin # noqa: E402"),
("social_ugc_admin", "from app.routers import social_ugc_admin # noqa: E402"),
("community_admin", "from app.routers import community_admin # noqa: E402"),
]
for key, line in imports:
if key not in text:
# append near other router imports
anchor = "from app.routers import"
idx = text.rfind(anchor)
if idx >= 0:
end = text.find("\n", idx)
text = text[: end + 1] + line + "\n" + text[end + 1 :]
changed = True
else:
text = line + "\n" + text
changed = True
includes = [
("social_ops_admin.router", "app.include_router(social_ops_admin.router)"),
("social_ugc_admin.router", "app.include_router(social_ugc_admin.router)"),
("community_admin.router", "app.include_router(community_admin.router)"),
]
for key, line in includes:
if key not in text:
# after last include_router
needle = "app.include_router("
idx = text.rfind(needle)
if idx >= 0:
end = text.find("\n", idx)
text = text[: end + 1] + line + "\n" + text[end + 1 :]
changed = True
if changed:
p.write_text(text, encoding="utf-8")
print("patched_main", p)
else:
print("main_ok", p)
PY
cd "$API_ROOT"
if [ -x .venv/bin/python ]; then
.venv/bin/python - <<'PY'
from app.services.weapp_switches import read_weapp_switches
from app.services import public_config_snapshot
print("import_ok", read_weapp_switches().get("bookAudit"))
print("snapshot_cls", public_config_snapshot.PublicConfigSnapshot)
PY
fi
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health
curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config
curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
echo token_len=${#TOK}
AUTH="Authorization: Bearer $TOK"
curl -sk -o /dev/null -w "switches %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/weapp/switches
curl -sk -o /dev/null -w "stats %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
rm -rf /tmp/api-backend /tmp/api-backend.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
after = snapshot()
print("AFTER", after, flush=True)
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
print("FAIL config drifted", flush=True)
return 3
print(f"[exit {code}] api backend deployed; version {after.get('version')}", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,108 @@
# -*- coding: utf-8 -*-
"""Push audit-book free + pay isolation patches → 82 nomadmini-api (backend only)."""
from __future__ import annotations
import io
import tarfile
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
("apps/api/services/ebook_svc/domains/books/products.py", "domains/books/products.py"),
("apps/api/services/ebook_svc/domains/books/__init__.py", "domains/books/__init__.py"),
("apps/api/services/ebook_svc/routers/books.py", "routers/books.py"),
("apps/api/services/ebook_svc/routers/pay.py", "routers/pay.py"),
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def pack() -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in FILES:
src = REPO / rel
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name="api/" + dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
print("pack", dest, flush=True)
buf.seek(0)
blob = buf.read()
print("blob", len(blob), flush=True)
return blob
REMOTE_CMD = r"""
set -e
cd /tmp
rm -rf audit-free-api && mkdir audit-free-api
tar -xzf audit-free-api.tar.gz -C audit-free-api
B=/opt/nomadmini/backend/app
for f in domains/books/products.py domains/books/__init__.py routers/books.py routers/pay.py routers/admin.py services/store.py; do
sudo cp -a "$B/$f" "$B/$f.bak-audit-free" 2>/dev/null || true
sudo mkdir -p "$(dirname "$B/$f")"
sudo cp "audit-free-api/api/$f" "$B/$f"
echo copied $f
done
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.domains.books import is_audit_book_id, is_book_free
assert is_audit_book_id('audit')
assert is_audit_book_id('audit-v2')
assert not is_audit_book_id('nomad')
assert is_book_free({'id': 'audit', 'unlock_percent': 30})
print('audit_free_ok')
PY
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w 'health %{http_code}\n' https://api.nomadro.cn/health
curl -sk 'https://api.nomadro.cn/api/ebook/books/audit' | python3 -c 'import sys,json; d=json.load(sys.stdin); print("audit", d.get("id"), "free", d.get("is_free"), "pct", d.get("unlock_percent"), "fen", d.get("price_fen"))'
rm -rf /tmp/audit-free-api /tmp/audit-free-api.tar.gz
"""
def main() -> int:
blob = pack()
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
with sftp.file("/tmp/audit-free-api.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
_, stdout, stderr = c.exec_command(REMOTE_CMD, timeout=180)
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
print(out)
if err.strip():
print("STDERR", err)
c.close()
if "audit_free_ok" not in out:
return 2
if "active" not in out:
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/routers/public_config.py"
def main() -> int:
text = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.")
if "ebook_svc." in text:
raise SystemExit("rewrite failed")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/public_config.py", "w") as rf:
rf.write(text)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/public_config.py /opt/nomadmini/backend/app/routers/public_config.py
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk -X POST https://api.nomadro.cn/api/config/pull -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);c=d['config'];print('POST_PULL',c.get('version'),c.get('modules',{}).get('nav'))"
curl -sk -X POST https://api.nomadro.cn/api/config -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);print('POST_CFG',d['config'].get('version'))"
rm -f /tmp/public_config.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,164 @@
# -*- coding: utf-8 -*-
"""Deploy config SSE/WebSocket realtime to api.nomadro.cn (nomadmini-api)."""
from __future__ import annotations
import io
import json
import tarfile
import time
import urllib.request
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
FILES = [
(
"apps/api/services/ebook_svc/services/config_live.py",
"services/config_live.py",
),
(
"apps/api/services/ebook_svc/routers/public_config.py",
"routers/public_config.py",
),
(
"apps/api/services/ebook_svc/services/weapp_switches.py",
"services/weapp_switches.py",
),
]
def rewrite(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def main() -> int:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for rel, dest in FILES:
src = REPO / rel
text = rewrite(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed {rel}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name=dest)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
blob = buf.getvalue()
print("pack", len(blob), flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/config-rt.tar.gz", "wb") as rf:
rf.write(blob)
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf config-rt && mkdir config-rt
tar -xzf config-rt.tar.gz -C config-rt
B=/opt/nomadmini/backend/app
TS=$(date -u +%Y%m%dT%H%M%SZ)
sudo mkdir -p "$B/services" "$B/routers"
for f in services/config_live.py routers/public_config.py services/weapp_switches.py; do
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
sudo cp "config-rt/$f" "$B/$f"
echo copied $f
done
# nginx websocket:写到 /tmp 再 sudo 覆盖
sudo python3 - <<'PY'
from pathlib import Path
import shutil
src = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
if not src.is_file():
print("nginx_ws_skip_no_conf")
raise SystemExit(0)
text = src.read_text(encoding="utf-8")
if "location /api/config/ws" in text:
print("nginx_ws_ok")
raise SystemExit(0)
upstream = "http://127.0.0.1:8000"
for line in text.splitlines():
s = line.strip()
if s.startswith("proxy_pass ") and "127.0.0.1" in s:
upstream = s.split("proxy_pass", 1)[1].strip().rstrip(";")
break
snippet = (
"\n location /api/config/ws {\n"
f" proxy_pass {upstream};\n"
" proxy_http_version 1.1;\n"
" proxy_set_header Upgrade $http_upgrade;\n"
' proxy_set_header Connection "upgrade";\n'
" proxy_set_header Host $host;\n"
" proxy_set_header X-Real-IP $remote_addr;\n"
" proxy_read_timeout 3600s;\n"
" proxy_send_timeout 3600s;\n"
" }\n"
" location /api/ebook/config/ws {\n"
f" proxy_pass {upstream};\n"
" proxy_http_version 1.1;\n"
" proxy_set_header Upgrade $http_upgrade;\n"
' proxy_set_header Connection "upgrade";\n'
" proxy_set_header Host $host;\n"
" proxy_set_header X-Real-IP $remote_addr;\n"
" proxy_read_timeout 3600s;\n"
" proxy_send_timeout 3600s;\n"
" }\n"
)
idx = text.find("location /")
if idx < 0:
idx = text.rfind("}")
if idx <= 0:
print("nginx_ws_skip")
raise SystemExit(0)
out = text[:idx] + snippet + "\n" + text[idx:]
bak = src.with_suffix(src.suffix + ".bak-config-ws")
shutil.copy2(src, bak)
src.write_text(out, encoding="utf-8")
print("nginx_ws_patched", upstream)
PY
sudo nginx -t && sudo nginx -s reload || true
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.services import config_live
from app.routers import public_config
print("import_ok", config_live.read_config_meta())
PY
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health
curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config
curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta
# SSE hello (2s)
timeout 3 curl -sk -N -H 'Accept: text/event-stream' https://api.nomadro.cn/api/config/stream | head -c 400 || true
echo
rm -rf /tmp/config-rt /tmp/config-rt.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
# local meta check
meta = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config/meta", timeout=15).read())
print("META", meta, flush=True)
print(f"[exit {code}] config realtime deployed", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,98 @@
# -*- coding: utf-8 -*-
"""Push social-join virtual pay routes to production (/opt/nomadmini)."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def to_app_pkg(src: Path) -> bytes:
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
assert b"ebook_svc" not in data, f"rewrite failed: {src}"
return data
def main() -> int:
pairs = [
(
REPO / "apps/api/services/ebook_svc/core/rate_limit.py",
"/tmp/rate_limit_app.py",
"/opt/nomadmini/backend/app/core/rate_limit.py",
),
(
REPO / "apps/api/services/ebook_svc/services/social_join_config.py",
"/tmp/social_join_config_app.py",
"/opt/nomadmini/backend/app/services/social_join_config.py",
),
(
REPO / "apps/api/services/ebook_svc/routers/pay.py",
"/tmp/pay_app.py",
"/opt/nomadmini/backend/app/routers/pay.py",
),
]
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
for src, tmp, _final in pairs:
data = to_app_pkg(src)
with sftp.file(tmp, "wb") as rf:
rf.write(data)
print("up", tmp, len(data), flush=True)
sftp.close()
cmd = r"""
set -e
B=/opt/nomadmini/backend/app
sudo cp /tmp/rate_limit_app.py "$B/core/rate_limit.py"
sudo cp /tmp/social_join_config_app.py "$B/services/social_join_config.py"
sudo cp /tmp/pay_app.py "$B/routers/pay.py"
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.core.rate_limit import rate_limit
from app.services.social_join_config import SOCIAL_JOIN_BOOK_ID, read_social_join_config
from app.routers import pay
print(
"import_ok",
SOCIAL_JOIN_BOOK_ID,
hasattr(pay, "create_social_join_order"),
callable(rate_limit),
read_social_join_config().get("socialJoinEnabled"),
)
PY
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health || true
# 未登录应 401,不应再 404
curl -sk -o /dev/null -w "sj-status %{http_code}\n" https://api.nomadro.cn/api/pay/social-join-status || true
curl -sk -o /dev/null -w "sj-ebook %{http_code}\n" https://api.nomadro.cn/api/ebook/pay/social-join-status || true
rm -f /tmp/rate_limit_app.py /tmp/social_join_config_app.py /tmp/pay_app.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
"""Push social live API router + smoke join via api.nomadro.cn."""
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
local = REPO / "apps/api/services/social_svc/routers/api.py"
with sftp.file("/tmp/social_routers_api.py", "wb") as rf:
rf.write(local.read_bytes())
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/social_routers_api.py /var/www/nomadro.cn/apps/api/services/social_svc/routers/api.py
sudo systemctl restart nomadro-social
sleep 2
systemctl is-active nomadro-social
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/live/rooms/office/join?guest=weapp_real_2' \
-H 'Content-Type: application/json' \
--data-binary '{"nick":"真机"}' | head -c 420; echo
curl -sk --max-time 5 'https://api.nomadro.cn/api/social/v1/health'; echo
"""
_, stdout, _ = c.exec_command(cmd, timeout=60, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,55 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
)
sftp = c.open_sftp()
for rel in ("live.py", "routers/api.py"):
local = REPO / "apps/api/services/social_svc" / rel
remote = f"/tmp/social_{rel.replace('/', '_')}"
with sftp.file(remote, "wb") as rf:
rf.write(local.read_bytes())
print("up", remote, flush=True)
sftp.close()
cmd = r"""
set -e
B=/var/www/nomadro.cn/apps/api/services/social_svc
sudo cp /tmp/social_live.py "$B/live.py"
sudo cp /tmp/social_routers_api.py "$B/routers/api.py"
sudo systemctl restart nomadro-social
sleep 2
curl -sk --max-time 8 -X POST 'https://api.nomadro.cn/api/social/v1/live/rooms/office/join?guest=camtest1' \
-H 'Content-Type: application/json' --data-binary '{"nick":"cam"}' | head -c 360; echo
"""
_, stdout, _ = c.exec_command(cmd, timeout=60, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
print("[exit", stdout.channel.recv_exit_status(), "]", flush=True)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
"""Push PocketBase social_ugc admin stack to US nomadmini-api + social_svc.
admin.nomadro.com Social page needs:
GET /api/admin/social/ugc/{stats,archives,detail/...}
and soft-delete via social_svc.pb_data → PocketBase.
"""
from __future__ import annotations
import io
import sys
import tarfile
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
ROOT = Path(__file__).resolve().parents[3]
US = ("108.174.50.68", "root", "Xiao4669805")
REMOTE_APP = "/opt/nomadmini/backend/app"
REMOTE_API = "/var/www/nomadro.cn/apps/api"
REMOTE_BACKEND = "/opt/nomadmini/backend"
LOCAL_UGC = ROOT / "apps/api/services/ebook_svc/services/social_ugc.py"
LOCAL_ADMIN = ROOT / "apps/api/services/ebook_svc/routers/social_ugc_admin.py"
LOCAL_SVC = ROOT / "apps/api/services/social_svc"
LOCAL_PB = ROOT / "apps/api/services/nomadro_pb"
def to_app(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def connect() -> paramiko.SSHClient:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
h, u, p = US
c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=90)
t = c.get_transport()
if t:
t.set_keepalive(15)
return c
def sh(c: paramiko.SSHClient, cmd: str, timeout: int = 240) -> tuple[int, str]:
print(f"$ {cmd[:240].replace(chr(10), ' ')}", flush=True)
_, o, e = c.exec_command(cmd, timeout=timeout)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
code = o.channel.recv_exit_status()
text = out + (("\n" + err) if err.strip() else "")
if text.strip():
print(text[-8000:], flush=True)
print("exit", code, flush=True)
return code, text
def pack() -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for src, name in (
(LOCAL_UGC, "api/services/social_ugc.py"),
(LOCAL_ADMIN, "api/routers/social_ugc_admin.py"),
):
if not src.is_file():
raise SystemExit(f"missing {src}")
text = to_app(src.read_text(encoding="utf-8"))
if "ebook_svc." in text:
raise SystemExit(f"rewrite failed: {src}")
data = text.encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
tar.add(LOCAL_SVC, arcname="services/social_svc")
tar.add(LOCAL_PB, arcname="services/nomadro_pb")
buf.seek(0)
return buf.read()
def main() -> int:
if not LOCAL_SVC.is_dir() or not LOCAL_PB.is_dir():
raise SystemExit("missing social_svc or nomadro_pb")
blob = pack()
print(f"pack {len(blob)} bytes", flush=True)
c = connect()
try:
sftp = c.open_sftp()
with sftp.file("/tmp/social_ugc_admin_us.tgz", "wb") as rf:
rf.write(blob)
sftp.close()
code, _ = sh(
c,
f"""
set -euo pipefail
mkdir -p /tmp/social_ugc_extract
rm -rf /tmp/social_ugc_extract/*
tar -xzf /tmp/social_ugc_admin_us.tgz -C /tmp/social_ugc_extract
TS=$(date +%Y%m%d%H%M%S)
# 1) social_svc + nomadro_pb → social API tree
mkdir -p {REMOTE_API}/services
[ -d {REMOTE_API}/services/social_svc ] && cp -a {REMOTE_API}/services/social_svc /tmp/social_svc.bak.$TS || true
rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_API}/services/social_svc/
rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_API}/services/nomadro_pb/
# 2) same packages on nomadmini PYTHONPATH (import social_svc / nomadro_pb)
rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_BACKEND}/social_svc/
rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_BACKEND}/nomadro_pb/
# also under services/ for social_ugc parents[2] path probe
mkdir -p {REMOTE_BACKEND}/services
rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_BACKEND}/services/social_svc/
rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_BACKEND}/services/nomadro_pb/
# 3) hot-patch ugc modules (ebook_svc→app already rewritten)
cp -a {REMOTE_APP}/services/social_ugc.py {REMOTE_APP}/services/social_ugc.py.bak-$TS 2>/dev/null || true
cp -a {REMOTE_APP}/routers/social_ugc_admin.py {REMOTE_APP}/routers/social_ugc_admin.py.bak-$TS 2>/dev/null || true
cp /tmp/social_ugc_extract/api/services/social_ugc.py {REMOTE_APP}/services/social_ugc.py
cp /tmp/social_ugc_extract/api/routers/social_ugc_admin.py {REMOTE_APP}/routers/social_ugc_admin.py
# 4) ensure PB URL in nomadmini env (do not clobber secrets)
ENVF={REMOTE_BACKEND}/.env
touch "$ENVF"
grep -q '^PB_URL=' "$ENVF" || echo 'PB_URL=http://127.0.0.1:8090' >> "$ENVF"
grep -q '^POCKETBASE_URL=' "$ENVF" || echo 'POCKETBASE_URL=http://127.0.0.1:8090' >> "$ENVF"
# 5) import smoke
cd {REMOTE_BACKEND}
.venv/bin/python - <<'PY'
import sys
sys.path.insert(0, ".")
sys.path.insert(0, "services")
from app.routers import social_ugc_admin
from app.services import social_ugc
paths = sorted({{getattr(r, "path", "") for r in social_ugc_admin.router.routes}})
need = [
"/api/admin/social/ugc/stats",
"/api/admin/social/ugc/archives",
"/api/admin/social/ugc/detail/{{entity}}/{{entity_id}}",
"/api/admin/social/ugc/overview",
]
for p in need:
assert p in paths, (p, paths)
print("ugc_routes_ok", len(paths))
print("backend", social_ugc.available())
PY
# 6) restart APIs
systemctl kill -s9 nomadro-social.service 2>/dev/null || true
fuser -k 8020/tcp 2>/dev/null || true
sleep 1
systemctl reset-failed nomadro-social 2>/dev/null || true
systemctl start nomadro-social 2>/dev/null || true
systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
systemctl is-active nomadro-social || true
curl -sS -o /dev/null -w 'social_health:%{{http_code}}\\n' --max-time 8 http://127.0.0.1:8020/api/social/v1/health || true
curl -sS -o /dev/null -w 'api_health:%{{http_code}}\\n' --max-time 8 http://127.0.0.1:8010/docs || true
TOKEN=$(curl -sS --max-time 12 -X POST https://api.nomadro.com/api/admin/login \\
-H 'content-type: application/json' \\
-d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token",""))')
echo "token_len ${{#TOKEN}}"
for path in overview stats archives; do
code=$(curl -sS -o /tmp/ugc_$path.json -w '%{{http_code}}' --max-time 15 \\
-H "Authorization: Bearer $TOKEN" \\
"https://api.nomadro.com/api/admin/social/ugc/$path")
echo "ugc_$path $code"
head -c 220 /tmp/ugc_$path.json; echo
done
curl -sk -o /dev/null -w 'admin_com %{{http_code}}\\n' https://admin.nomadro.com/
echo PUSH_SOCIAL_UGC_ADMIN_US_OK
""",
)
return code
finally:
c.close()
print("done", time.strftime("%H:%M:%S"), flush=True)
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,97 @@
# -*- coding: utf-8 -*-
"""Hot-patch US nomadmini social_ugc to SQLite soft-delete + stats (no PocketBase)."""
from __future__ import annotations
from pathlib import Path
import paramiko
US = ("108.174.50.68", "root", "Xiao4669805")
HERE = Path(__file__).resolve().parent
SRC = HERE / "_us_social_ugc_sqlite.py"
ADMIN_SRC = (
Path(__file__).resolve().parents[3]
/ "apps/api/services/ebook_svc/routers/social_ugc_admin.py"
)
REMOTE_APP = "/opt/nomadmini/backend/app"
def to_app(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def main() -> int:
if not SRC.is_file():
raise SystemExit(f"missing {SRC}")
body = SRC.read_text(encoding="utf-8").encode("utf-8")
admin_body = to_app(ADMIN_SRC.read_text(encoding="utf-8")).encode("utf-8")
if b"ebook_svc." in admin_body:
raise SystemExit("admin rewrite failed")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
h, u, p = US
c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/social_ugc_sqlite_us.py", "wb") as f:
f.write(body)
with sftp.file("/tmp/social_ugc_admin_us.py", "wb") as f:
f.write(admin_body)
sftp.close()
print("uploaded", len(body), len(admin_body), flush=True)
cmd = rf"""
set -euo pipefail
TS=$(date +%Y%m%d%H%M%S)
B={REMOTE_APP}
cp -a "$B/services/social_ugc.py" "$B/services/social_ugc.py.bak-pre-sqlite-$TS" || true
cp -a "$B/routers/social_ugc_admin.py" "$B/routers/social_ugc_admin.py.bak-pre-sqlite-$TS" || true
cp /tmp/social_ugc_sqlite_us.py "$B/services/social_ugc.py"
cp /tmp/social_ugc_admin_us.py "$B/routers/social_ugc_admin.py"
# ensure SOCIAL_DB_PATH on nomadmini
ENVF=/opt/nomadmini/backend/.env
grep -q '^SOCIAL_DB_PATH=' "$ENVF" || echo 'SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db' >> "$ENVF"
# prefer empty PB so nothing accidental
sed -i 's/^USE_POCKETBASE=.*/USE_POCKETBASE=false/' "$ENVF" || true
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.services import social_ugc as ugc
from app.routers import social_ugc_admin
print('available', ugc.available())
print('overview', ugc.overview())
print('stats', {{k: ugc.stats().get(k) for k in ('ok','counts','backend')}})
paths = sorted({{getattr(r,'path','') for r in social_ugc_admin.router.routes}})
for need in ['/api/admin/social/ugc/stats','/api/admin/social/ugc/archives','/api/admin/social/ugc/detail/{{entity}}/{{entity_id}}']:
assert need in paths, need
print('routes_ok', len(paths))
PY
systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
systemctl is-active nomadro-social
curl -sS --max-time 8 http://127.0.0.1:8020/api/social/v1/health; echo
TOKEN=$(curl -sS --max-time 12 -X POST https://api.nomadro.com/api/admin/login \
-H 'content-type: application/json' \
-d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token",""))')
echo "token_len ${{#TOKEN}}"
for path in overview stats archives roster; do
code=$(curl -sS -o /tmp/ugc_$path.json -w '%{{http_code}}' --max-time 15 \
-H "Authorization: Bearer $TOKEN" \
"https://api.nomadro.com/api/admin/social/ugc/$path")
echo "ugc_$path $code"
head -c 260 /tmp/ugc_$path.json; echo
done
curl -sk -o /dev/null -w 'admin_com %{{http_code}}\n' https://admin.nomadro.com/
echo PUSH_UGC_SQLITE_US_OK
"""
_, o, e = c.exec_command(cmd, timeout=180)
print(o.read().decode("utf-8", "replace"), flush=True)
err = e.read().decode("utf-8", "replace")
if err.strip():
print("STDERR", err[-3000:], flush=True)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
"""Deploy weapp switches API + admin SPA."""
from __future__ import annotations
import subprocess
import tarfile
import time
from io import BytesIO
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1]
REPO = ROOT.parents[1]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
API_FILES = [
(REPO / "apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"),
(REPO / "apps/api/services/ebook_svc/routers/weapp_switches_admin.py", "routers/weapp_switches_admin.py"),
(REPO / "apps/api/services/ebook_svc/services/store.py", "services/store.py"),
(REPO / "apps/api/services/ebook_svc/main.py", "main.py"),
]
def to_app(src: Path) -> bytes:
return src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
def main() -> int:
print("vite build…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
return r.returncode
dist = ROOT / "dist"
buf = BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
for src, rel in API_FILES:
data = to_app(src)
info = tarfile.TarInfo(name="api/" + rel.replace("/", "__"))
info.size = len(data)
tar.addfile(info, BytesIO(data))
buf.seek(0)
print("pack", buf.getbuffer().nbytes, flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/weapp-switches.tar.gz", "wb") as rf:
rf.write(buf.read())
sftp.close()
cmd = r"""
set -e
cd /tmp
rm -rf sw-unpack && mkdir sw-unpack
tar -xzf weapp-switches.tar.gz -C sw-unpack
sudo rsync -a --delete sw-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
B=/opt/nomadmini/backend/app
sudo mkdir -p "$B/services" "$B/routers"
sudo cp sw-unpack/api/services__weapp_switches.py "$B/services/weapp_switches.py"
sudo cp sw-unpack/api/routers__weapp_switches_admin.py "$B/routers/weapp_switches_admin.py"
sudo cp sw-unpack/api/services__store.py "$B/services/store.py"
sudo cp sw-unpack/api/main.py "$B/../main.py" 2>/dev/null || sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py
# main may live as app package entry
if [ -f /opt/nomadmini/backend/app/main.py ]; then
sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/app/main.py
elif [ -f /opt/nomadmini/backend/main.py ]; then
sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py
fi
cd /opt/nomadmini/backend
.venv/bin/python - <<'PY'
from app.services.weapp_switches import read_weapp_switches
from app.routers import weapp_switches_admin
from app.services.store import store
assert hasattr(store, "ensure_book")
print("ok", "switches", list(read_weapp_switches().get("modules", {}).keys())[:3])
PY
sudo systemctl restart nomadmini-api
sleep 3
systemctl is-active nomadmini-api
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/switches
curl -sk -o /dev/null -w "api %{http_code}\n" https://api.nomadro.cn/health
rm -rf sw-unpack weapp-switches.tar.gz
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
SRC = REPO / "apps/api/services/ebook_svc/services/weapp_switches.py"
def main() -> int:
data = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/weapp_switches.py", "wb") as rf:
rf.write(data)
sftp.close()
cmd = r"""
set -e
sudo cp /tmp/weapp_switches.py /opt/nomadmini/backend/app/services/weapp_switches.py
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.services.weapp_switches import read_weapp_switches; print("ok", read_weapp_switches()["bookAudit"])'
sudo systemctl restart nomadmini-api
sleep 2
systemctl is-active nomadmini-api
rm -f /tmp/weapp_switches.py
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import json
import urllib.request
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(
"sudo systemctl restart nomadmini-api.service && sleep 2 && "
"systemctl is-active nomadmini-api.service && "
"curl -s http://127.0.0.1:8010/health",
timeout=60,
)
print(o.read().decode())
err = e.read().decode()
if err:
print("STDERR", err[-1000:])
c.close()
req = urllib.request.Request(
"https://api.nomadro.cn/api/admin/login",
data=json.dumps({"username": "admin", "password": "Xiao4669805"}).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
tok = json.loads(urllib.request.urlopen(req, timeout=20).read()).get("token", "")
req2 = urllib.request.Request(
"https://api.nomadro.cn/api/admin/product-offers",
headers={"Authorization": "Bearer " + tok},
)
items = json.loads(urllib.request.urlopen(req2, timeout=20).read()).get("items") or []
for o in items:
print(o.get("key"), o.get("product_id"), o.get("name"), o.get("price_yuan"), o.get("remark"))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
"""Restore US social_svc to pre-PB SQLite backup; fetch bak ugc for local enhance."""
from __future__ import annotations
from pathlib import Path
import paramiko
US = ("108.174.50.68", "root", "Xiao4669805")
OUT = Path(__file__).resolve().parent
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
h, u, p = US
c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
sftp.get(
"/opt/nomadmini/backend/app/services/social_ugc.py.bak-20261104081910",
str(OUT / "_tmp_social_ugc_sqlite.py"),
)
sftp.get(
"/opt/nomadmini/backend/app/routers/social_ugc_admin.py.bak-20261104081910",
str(OUT / "_tmp_social_ugc_admin_old.py"),
)
sftp.close()
print("downloaded bak ugc", flush=True)
cmd = r"""
set -euo pipefail
BAK=$(ls -dt /tmp/social_svc.bak.* | head -1)
echo restoring_from "$BAK"
rsync -a --delete "$BAK/" /var/www/nomadro.cn/apps/api/services/social_svc/
rm -rf /opt/nomadmini/backend/social_svc /opt/nomadmini/backend/services/social_svc
systemctl kill -s9 nomadro-social 2>/dev/null || true
fuser -k 8020/tcp 2>/dev/null || true
sleep 1
systemctl reset-failed nomadro-social 2>/dev/null || true
systemctl start nomadro-social
sleep 2
systemctl is-active nomadro-social
curl -sS --max-time 8 http://127.0.0.1:8020/api/social/v1/health; echo
python3 - <<'PY'
import sqlite3
db=sqlite3.connect('/var/www/nomadro-data/social/social.db')
print('tables', [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1")])
for t in ['roster','messages','cafe_reviews','gig_apps','feedback']:
try:
print(t, db.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0])
except Exception as e:
print(t, e)
PY
echo RESTORE_SOCIAL_SQLITE_OK
"""
_, o, e = c.exec_command(cmd, timeout=120)
print(o.read().decode("utf-8", "replace"), flush=True)
err = e.read().decode("utf-8", "replace")
if err.strip():
print("STDERR", err[-2000:], flush=True)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,116 @@
# -*- coding: utf-8 -*-
"""Write WeChat-safe digital-nomad audit booklet into prod DB."""
from __future__ import annotations
import json
import re
import time
from pathlib import Path
import paramiko
HERE = Path(__file__).resolve().parent
MD = (HERE / "audit_book_seed.md").read_text(encoding="utf-8")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def split_markdown_chapters(md: str) -> list[dict]:
text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip()
if not text:
return []
parts = re.split(r"(?m)^(#{1} .+)$", text)
chapters: list[dict] = []
preamble = (parts[0] or "").strip()
order = 1
if preamble and len(parts) == 1:
return [{"id": "c1", "title": "正文", "order": 1, "content": preamble + "\n"}]
if preamble:
chapters.append({"id": "c0", "title": "前言", "order": order, "content": preamble + "\n"})
order += 1
i = 1
while i < len(parts):
heading = parts[i].strip()
body = parts[i + 1] if i + 1 < len(parts) else ""
title = re.sub(r"^#\s+", "", heading).strip() or f"第{order}章"
content = f"{heading}\n{body}".strip() + "\n"
chapters.append({"id": f"c{order}", "title": title, "order": order, "content": content})
order += 1
i += 2
return chapters
def main() -> int:
chapters = split_markdown_chapters(MD)
assert chapters, "no chapters"
payload = {
"title": "数字游民入门指南",
"subtitle": "远程办公 · 自律生活 · 稳健成长",
"description": "面向普通人的数字游民与远程办公入门读本:时间管理、协作沟通、健康作息与职业成长。",
"chapters": chapters,
}
raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/audit_book_seed.json", "wb") as rf:
rf.write(raw)
sftp.close()
cmd = r"""
set -e
python3 <<'PY'
import json, sqlite3, time
data=json.load(open('/tmp/audit_book_seed.json',encoding='utf-8'))
chapters=data['chapters']
con=sqlite3.connect('/opt/nomadmini/data/nomadmini.db')
now=time.time()
row=con.execute("select id from books where id='audit'").fetchone()
meta=(
data['title'], data['subtitle'], '', '📗', data['description'],
json.dumps(['数字游民','远程办公','生活方式'], ensure_ascii=False),
0, '', 100, 5.0, json.dumps(chapters, ensure_ascii=False), now,
)
if row:
con.execute(
'UPDATE books SET title=?, subtitle=?, author=?, cover_emoji=?, description=?, tags=?,'
' price_fen=?, product_id=?, unlock_percent=?, rating=?, chapters_json=?, updated_at=? WHERE id=?',
meta + ('audit',),
)
else:
con.execute(
'INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags,'
'price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) '
"VALUES ('audit',?,?,?,?,?,?,?,?,?,?,?,?)",
meta,
)
con.commit()
print('chapters', len(chapters))
print('titles', [c['title'] for c in chapters])
print('words', sum(len(c.get('content') or '') for c in chapters))
PY
curl -sk -o /tmp/audit_check.json -w "audit %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit
python3 <<'PY'
import json
d=json.load(open('/tmp/audit_check.json',encoding='utf-8'))
print('api', d.get('title'), d.get('chapter_count'), d.get('is_free'))
print('toc', [c.get('title') for c in (d.get('chapters') or [])])
PY
rm -f /tmp/audit_book_seed.json /tmp/audit_check.json
"""
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import json
import time
import urllib.error
import urllib.request
import paramiko
US = ("108.174.50.68", "root", "Xiao4669805")
def http(url: str, **kw):
req = urllib.request.Request(url, **kw)
try:
with urllib.request.urlopen(req, timeout=20) as resp:
body = resp.read().decode("utf-8", "replace")
return resp.status, body
except urllib.error.HTTPError as e:
return e.code, e.read().decode("utf-8", "replace")
except Exception as e:
return 0, str(e)
def main() -> int:
time.sleep(2)
code, body = http("https://admin.nomadro.com/")
print("admin_com", code, "Nomadro" in body)
code, body = http(
"https://api.nomadro.com/api/admin/login",
data=json.dumps(
{"username": "hackrobot", "password": "Xiao4669805@"}
).encode(),
headers={"content-type": "application/json"},
method="POST",
)
print("login", code, body[:160])
token = ""
try:
token = json.loads(body).get("token") or ""
except Exception:
pass
if not token:
# remote curl fallback
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
h, u, p = US
c.connect(h, 22, u, p, timeout=40, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(
r"""
systemctl is-active nomadmini-api
journalctl -u nomadmini-api -n 40 --no-pager
curl -sS -o /tmp/login.json -w 'login %{http_code}\n' --max-time 15 -X POST https://api.nomadro.com/api/admin/login \
-H 'content-type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}'
head -c 300 /tmp/login.json; echo
""",
timeout=60,
)
print(o.read().decode("utf-8", "replace"))
print(e.read().decode("utf-8", "replace")[-1500:])
c.close()
return 1
headers = {"Authorization": f"Bearer {token}"}
for path in ("overview", "stats", "archives", "messages?limit=5", "roster?limit=5"):
c2, b2 = http(
f"https://api.nomadro.com/api/admin/social/ugc/{path}",
headers=headers,
)
print(f"ugc/{path}", c2, b2[:220].replace("\n", " "))
print("SMOKE_OK")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""Smoke: admin VIP + book offer switch bumps remote config for live sync."""
from __future__ import annotations
import json
import urllib.request
BASE = "https://api.nomadro.cn"
def post(url: str, data: dict | None = None, token: str = "") -> dict:
body = None if data is None else json.dumps(data).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = "Bearer " + token
req = urllib.request.Request(url, data=body, headers=headers, method="POST" if body else "GET")
with urllib.request.urlopen(req, timeout=20) as r:
return json.loads(r.read().decode())
def main() -> None:
tok = post(f"{BASE}/api/admin/login", {"username": "admin", "password": "Xiao4669805"})["token"]
before = post(f"{BASE}/api/config/pull", {"t": 1})
cfg0 = before.get("config") or {}
print("before", cfg0.get("version"), (cfg0.get("copy") or {}).get("vipProductId"), (cfg0.get("copy") or {}).get("booksOfferRev"))
vip = post(f"{BASE}/api/admin/vip/offer", {"offer_key": "nomad"}, tok)
print("vip", vip.get("vipProductId"), vip.get("vipPriceFen"), vip.get("vipCta"))
book = post(f"{BASE}/api/admin/books/default/offer", {"offer_key": "yen29"}, tok)
print("book", book.get("product_id"), book.get("price_fen"), book.get("offer_name"))
after = post(f"{BASE}/api/config/pull", {"t": 2})
cfg1 = after.get("config") or {}
copy = cfg1.get("copy") or {}
print(
"after",
cfg1.get("version"),
copy.get("vipProductId"),
copy.get("vipPriceFen"),
copy.get("booksOfferRev"),
copy.get("booksOfferBookId"),
)
# restore book to nomad (main push)
restored = post(f"{BASE}/api/admin/books/default/offer", {"offer_key": "nomad"}, tok)
print("restore_book", restored.get("product_id"), restored.get("offer_name"))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
"""Publish a short test stream to SRS and confirm HTTPS FLV proxy responds."""
from __future__ import annotations
import time
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
set -e
# ffmpeg available?
which ffmpeg || sudo apt-get install -y -qq ffmpeg >/tmp/ffinstall.log 2>&1 || true
which ffmpeg
# publish 8s color bars in background
nohup ffmpeg -re -f lavfi -i color=c=black:s=320x240:d=12 -f lavfi -i sine=f=440:d=12 \
-c:v libx264 -tune zerolatency -preset ultrafast -pix_fmt yuv420p -g 30 \
-c:a aac -f flv rtmp://127.0.0.1/live/smoke_test \
>/tmp/ff_push.log 2>&1 &
FFPID=$!
echo "ffmpeg pid $FFPID"
sleep 3
echo '=== local flv code ==='
curl -s --max-time 4 -o /tmp/chunk.flv -w 'local %{http_code} size %{size_download}\n' \
'http://127.0.0.1:1985/live/smoke_test.flv' || true
file /tmp/chunk.flv 2>/dev/null || ls -la /tmp/chunk.flv
echo '=== public flv code ==='
curl -sk --max-time 4 -o /tmp/chunk2.flv -D /tmp/chunk2.hdr -w 'public %{http_code} size %{size_download}\n' \
'https://nomadro.cn/live/smoke_test.flv' || true
head -20 /tmp/chunk2.hdr || true
ls -la /tmp/chunk2.flv || true
kill $FFPID 2>/dev/null || true
sleep 1
tail -5 /tmp/ff_push.log || true
"""
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
print("[exit", stdout.channel.recv_exit_status(), "]", flush=True)
c.close()

View File

@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
import json
import urllib.request
login = json.loads(
urllib.request.urlopen(
urllib.request.Request(
"https://api.nomadro.com/api/admin/login",
data=json.dumps(
{"username": "hackrobot", "password": "Xiao4669805@"}
).encode(),
headers={"content-type": "application/json"},
),
timeout=20,
).read()
)
tok = login["token"]
for p in (
"liveness",
"reports",
"coffee-bookings",
"meetup-reviews",
"trips",
"blocks",
"files",
):
req = urllib.request.Request(
f"https://api.nomadro.com/api/admin/social/ugc/{p}?limit=5",
headers={"Authorization": f"Bearer {tok}"},
)
try:
with urllib.request.urlopen(req, timeout=20) as r:
d = json.loads(r.read())
print(p, r.status, "total=", d.get("total"), "items=", len(d.get("items") or []))
except Exception as e:
print(p, getattr(e, "code", None), e)

View File

@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""Upload ops prop PNGs to admin.nomadro.cn/props/ (CORS for WeChat batch)."""
from __future__ import annotations
from pathlib import Path
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
LOCAL = Path(__file__).resolve().parents[1] / "public" / "props"
FILES = (
"nomad_lite.png",
"nomad_plus.png",
"nomad_pro.png",
"pay_test.png",
"29.png",
"298.png",
"588.png",
"test.png",
"nomad.png",
"tiktok.png",
"youtube.png",
"ebook.png",
"svip.png",
)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
c.exec_command("mkdir -p /tmp/wx_props_new", timeout=10)
for name in FILES:
path = LOCAL / name
if not path.is_file():
print("skip missing", name)
continue
sftp.put(str(path), f"/tmp/wx_props_new/{name}")
print("up", name, path.stat().st_size)
sftp.close()
_, o, e = c.exec_command(
"sudo cp -a /tmp/wx_props_new/. /www/wwwroot/admin.nomadro.cn/props/ && "
"sudo chown -R www:www /www/wwwroot/admin.nomadro.cn/props && "
"ls -lah /www/wwwroot/admin.nomadro.cn/props/ && "
"curl -sI https://admin.nomadro.cn/props/nomad_lite.png -H 'Origin: https://mp.weixin.qq.com' | tr -d '\\r' | head -15"
)
print(o.read().decode())
err = e.read().decode()
if err:
print("stderr", err)
c.close()

View File

@ -0,0 +1,869 @@
"""游民社区 UGC 管理 — 直连 social.db(US 生产;软删除 + social_archives)。
默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db
"""
from __future__ import annotations
import json
import os
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Iterator
from app.core.sqlite_util import connect as _connect
_DEFAULT = Path("/var/www/nomadro-data/social/social.db")
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve()
ENTITY_TABLES = {
"roster": ("roster", "guest_id"),
"messages": ("messages", "id"),
"reviews": ("cafe_reviews", "id"),
"gigApps": ("gig_apps", "id"),
"feedback": ("feedback", "id"),
}
def _now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
def _uid(prefix: str = "arc") -> str:
return f"{prefix}_{uuid.uuid4().hex[:12]}"
@contextmanager
def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]:
SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
if readonly and SOCIAL_DB_PATH.is_file():
uri = f"file:{SOCIAL_DB_PATH.as_posix()}?mode=ro"
conn = sqlite3.connect(uri, uri=True, timeout=30.0)
conn.row_factory = sqlite3.Row
else:
conn = _connect(SOCIAL_DB_PATH)
try:
if not readonly:
_ensure_schema(conn)
yield conn
if not readonly:
conn.commit()
except Exception:
if not readonly:
conn.rollback()
raise
finally:
conn.close()
def _ensure_schema(conn: sqlite3.Connection) -> None:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS social_archives (
id TEXT PRIMARY KEY,
entity TEXT NOT NULL,
entity_id TEXT NOT NULL,
guest_id TEXT DEFAULT '',
action TEXT NOT NULL,
note TEXT DEFAULT '',
payload TEXT DEFAULT '{}',
created_at TEXT NOT NULL
)
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_social_archives_entity ON social_archives(entity, entity_id, created_at)"
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS join_leads (
id TEXT PRIMARY KEY,
email TEXT NOT NULL,
guest_id TEXT DEFAULT '',
stage TEXT DEFAULT '',
name TEXT DEFAULT '',
paid TEXT DEFAULT '',
face_ok TEXT DEFAULT '',
liveness_status TEXT DEFAULT '',
ua TEXT DEFAULT '',
payload TEXT DEFAULT '{}',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_join_leads_email ON join_leads(email)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_join_leads_updated ON join_leads(updated_at)"
)
# soft-delete markers on live tables (idempotent)
for table, _pk in {
"roster": "guest_id",
"messages": "id",
"cafe_reviews": "id",
"gig_apps": "id",
"feedback": "id",
}.items():
cols = {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
if "deleted_at" not in cols:
try:
conn.execute(f"ALTER TABLE {table} ADD COLUMN deleted_at TEXT")
except sqlite3.OperationalError:
pass
if table == "roster" and "status" not in cols:
try:
conn.execute("ALTER TABLE roster ADD COLUMN status TEXT DEFAULT ''")
except sqlite3.OperationalError:
pass
def _row_dict(row: sqlite3.Row | None) -> dict[str, Any] | None:
if row is None:
return None
return {k: row[k] for k in row.keys()}
def _archive(
conn: sqlite3.Connection,
*,
entity: str,
entity_id: str,
action: str,
payload: dict[str, Any] | None,
guest_id: str = "",
note: str = "",
) -> str:
aid = _uid("arc")
conn.execute(
"""
INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at)
VALUES(?,?,?,?,?,?,?,?)
""",
(
aid,
entity,
entity_id,
guest_id or "",
action,
note or "",
json.dumps(payload or {}, ensure_ascii=False),
_now(),
),
)
return aid
def _soft_delete(
conn: sqlite3.Connection,
*,
entity: str,
entity_id: str,
table: str,
pk: str,
guest_id: str = "",
) -> bool:
row = conn.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone()
if not row:
return False
payload = _row_dict(row) or {}
if payload.get("deleted_at"):
return True
_archive(
conn,
entity=entity,
entity_id=entity_id,
action="soft_delete",
payload=payload,
guest_id=guest_id or str(payload.get("guest_id") or ""),
)
if table == "roster":
conn.execute(
"UPDATE roster SET deleted_at=?, status='deleted', updated_at=? WHERE guest_id=?",
(_now(), _now(), entity_id),
)
else:
conn.execute(
f"UPDATE {table} SET deleted_at=? WHERE {pk}=?",
(_now(), entity_id),
)
return True
def _alive_clause(alias: str = "") -> str:
col = f"{alias}.deleted_at" if alias else "deleted_at"
return f"({col} IS NULL OR {col}='')"
def available() -> dict[str, Any]:
exists = SOCIAL_DB_PATH.is_file()
size = SOCIAL_DB_PATH.stat().st_size if exists else 0
writable = False
if exists:
try:
writable = os.access(SOCIAL_DB_PATH, os.W_OK)
except Exception:
writable = False
return {
"ok": True,
"path": str(SOCIAL_DB_PATH),
"exists": exists,
"bytes": size,
"writable": writable,
"backend": "sqlite",
}
def overview() -> dict[str, Any]:
info = available()
counts = {
"messages": 0,
"roster": 0,
"reviews": 0,
"gigApps": 0,
"feedback": 0,
}
if not info["exists"]:
return {**info, "counts": counts}
try:
with _db() as c:
counts["messages"] = c.execute(
f"SELECT COUNT(*) AS n FROM messages WHERE {_alive_clause()}"
).fetchone()["n"]
counts["roster"] = c.execute(
f"SELECT COUNT(*) AS n FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'"
).fetchone()["n"]
counts["reviews"] = c.execute(
f"SELECT COUNT(*) AS n FROM cafe_reviews WHERE {_alive_clause()}"
).fetchone()["n"]
counts["gigApps"] = c.execute(
f"SELECT COUNT(*) AS n FROM gig_apps WHERE {_alive_clause()}"
).fetchone()["n"]
counts["feedback"] = c.execute(
f"SELECT COUNT(*) AS n FROM feedback WHERE {_alive_clause()}"
).fetchone()["n"]
except Exception as e:
return {**info, "counts": counts, "error": str(e)}
return {**info, "counts": counts}
def list_messages(
*,
channel_id: str = "",
q: str = "",
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
limit = max(1, min(int(limit or 100), 500))
offset = max(0, int(offset or 0))
clauses: list[str] = [_alive_clause()]
params: list[Any] = []
if channel_id.strip():
clauses.append("channel_id=?")
params.append(channel_id.strip())
if q.strip():
clauses.append("(author LIKE ? OR text LIKE ? OR guest_id LIKE ?)")
like = f"%{q.strip()}%"
params.extend([like, like, like])
where = f" WHERE {' AND '.join(clauses)}"
with _db() as c:
total = c.execute(f"SELECT COUNT(*) AS n FROM messages{where}", tuple(params)).fetchone()["n"]
rows = c.execute(
f"""
SELECT id, channel_id, author, text, guest_id, created_at, deleted_at
FROM messages{where}
ORDER BY created_at DESC, rowid DESC
LIMIT ? OFFSET ?
""",
(*params, limit, offset),
).fetchall()
items = [
{
"id": r["id"],
"channelId": r["channel_id"],
"author": r["author"],
"text": r["text"],
"guestId": r["guest_id"],
"at": r["created_at"],
}
for r in rows
]
return {"ok": True, "total": total, "items": items}
def delete_message(message_id: str) -> bool:
with _db() as c:
return _soft_delete(
c, entity="messages", entity_id=message_id, table="messages", pk="id"
)
def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
limit = max(1, min(int(limit or 100), 500))
offset = max(0, int(offset or 0))
clauses: list[str] = [_alive_clause(), "IFNULL(status,'')!='deleted'"]
params: list[Any] = []
if q.strip():
clauses.append("(name LIKE ? OR city LIKE ? OR title LIKE ? OR guest_id LIKE ? OR bio LIKE ?)")
like = f"%{q.strip()}%"
params.extend([like, like, like, like, like])
where = f" WHERE {' AND '.join(clauses)}"
with _db() as c:
total = c.execute(f"SELECT COUNT(*) AS n FROM roster{where}", tuple(params)).fetchone()["n"]
rows = c.execute(
f"""
SELECT guest_id, name, title, city, phone, linktree, skills, bio, updated_at, status, deleted_at
FROM roster{where}
ORDER BY updated_at DESC
LIMIT ? OFFSET ?
""",
(*params, limit, offset),
).fetchall()
items = [
{
"guestId": r["guest_id"],
"name": r["name"],
"title": r["title"] or "",
"city": r["city"] or "",
"phone": r["phone"] or "",
"linktree": r["linktree"] or "",
"skills": r["skills"] or "",
"bio": r["bio"] or "",
"updatedAt": r["updated_at"],
"status": r["status"] or "",
}
for r in rows
]
return {"ok": True, "total": total, "items": items}
def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
with _db() as c:
row = c.execute("SELECT * FROM roster WHERE guest_id=?", (guest_id,)).fetchone()
if not row:
return None
restore = bool(patch.get("restore"))
fields = {
"name": str(patch.get("name", row["name"] or ""))[:64] or "游民",
"title": str(patch.get("title", row["title"] or ""))[:80],
"city": str(patch.get("city", row["city"] or ""))[:64],
"phone": str(patch.get("phone", row["phone"] or ""))[:32],
"linktree": str(patch.get("linktree", row["linktree"] or ""))[:240],
"skills": str(patch.get("skills", row["skills"] or ""))[:200],
"bio": str(patch.get("bio", row["bio"] or ""))[:2000],
}
status = str(patch.get("status", row["status"] if "status" in row.keys() else "") or "")
deleted_at = row["deleted_at"] if "deleted_at" in row.keys() else None
if restore:
status = ""
deleted_at = None
_archive(
c,
entity="roster",
entity_id=guest_id,
action="restore",
payload=_row_dict(row),
guest_id=guest_id,
)
updated = _now()
c.execute(
"""
UPDATE roster SET name=?, title=?, city=?, phone=?, linktree=?, skills=?, bio=?,
status=?, deleted_at=?, updated_at=?
WHERE guest_id=?
""",
(
fields["name"],
fields["title"],
fields["city"],
fields["phone"],
fields["linktree"],
fields["skills"],
fields["bio"],
status,
deleted_at,
updated,
guest_id,
),
)
_archive(
c,
entity="roster",
entity_id=guest_id,
action="update",
payload={**fields, "status": status},
guest_id=guest_id,
)
return {
**fields,
"guestId": guest_id,
"updatedAt": updated,
"status": status,
}
def delete_roster(guest_id: str) -> bool:
with _db() as c:
return _soft_delete(
c,
entity="roster",
entity_id=guest_id,
table="roster",
pk="guest_id",
guest_id=guest_id,
)
def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
limit = max(1, min(int(limit or 100), 500))
offset = max(0, int(offset or 0))
clauses: list[str] = [_alive_clause()]
params: list[Any] = []
if cafe_id.strip():
clauses.append("cafe_id=?")
params.append(cafe_id.strip())
where = f" WHERE {' AND '.join(clauses)}"
with _db() as c:
total = c.execute(
f"SELECT COUNT(*) AS n FROM cafe_reviews{where}", tuple(params)
).fetchone()["n"]
rows = c.execute(
f"""
SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at
FROM cafe_reviews{where}
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""",
(*params, limit, offset),
).fetchall()
items = [
{
"id": r["id"],
"cafeId": r["cafe_id"],
"author": r["author"],
"score": r["score"],
"text": r["text"],
"photoNote": r["photo_note"] or "",
"guestId": r["guest_id"],
"at": r["created_at"],
}
for r in rows
]
return {"ok": True, "total": total, "items": items}
def delete_review(review_id: str) -> bool:
with _db() as c:
return _soft_delete(
c, entity="reviews", entity_id=review_id, table="cafe_reviews", pk="id"
)
def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
limit = max(1, min(int(limit or 100), 500))
offset = max(0, int(offset or 0))
clauses: list[str] = [_alive_clause()]
params: list[Any] = []
if gig_id.strip():
clauses.append("gig_id=?")
params.append(gig_id.strip())
where = f" WHERE {' AND '.join(clauses)}"
with _db() as c:
total = c.execute(
f"SELECT COUNT(*) AS n FROM gig_apps{where}", tuple(params)
).fetchone()["n"]
rows = c.execute(
f"""
SELECT id, gig_id, name, contact, note, guest_id, created_at
FROM gig_apps{where}
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""",
(*params, limit, offset),
).fetchall()
items = [
{
"id": r["id"],
"gigId": r["gig_id"],
"name": r["name"],
"contact": r["contact"],
"note": r["note"] or "",
"guestId": r["guest_id"],
"at": r["created_at"],
}
for r in rows
]
return {"ok": True, "total": total, "items": items}
def delete_gig_app(app_id: str) -> bool:
with _db() as c:
return _soft_delete(
c, entity="gigApps", entity_id=app_id, table="gig_apps", pk="id"
)
def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]:
limit = max(1, min(int(limit or 100), 500))
offset = max(0, int(offset or 0))
where = f" WHERE {_alive_clause()}"
with _db() as c:
total = c.execute(f"SELECT COUNT(*) AS n FROM feedback{where}").fetchone()["n"]
rows = c.execute(
f"""
SELECT id, kind, text, contact, guest_id, created_at
FROM feedback{where}
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""",
(limit, offset),
).fetchall()
items = [
{
"id": r["id"],
"kind": r["kind"],
"text": r["text"],
"contact": r["contact"] or "",
"guestId": r["guest_id"],
"at": r["created_at"],
}
for r in rows
]
return {"ok": True, "total": total, "items": items}
def delete_feedback(fid: str) -> bool:
with _db() as c:
return _soft_delete(
c, entity="feedback", entity_id=fid, table="feedback", pk="id"
)
def stats() -> dict[str, Any]:
with _db() as c:
def cnt(sql: str) -> int:
return int(c.execute(sql).fetchone()[0])
counts = {
"messages": cnt(f"SELECT COUNT(*) FROM messages WHERE {_alive_clause()}"),
"roster": cnt(
f"SELECT COUNT(*) FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'"
),
"reviews": cnt(f"SELECT COUNT(*) FROM cafe_reviews WHERE {_alive_clause()}"),
"gigApps": cnt(f"SELECT COUNT(*) FROM gig_apps WHERE {_alive_clause()}"),
"feedback": cnt(f"SELECT COUNT(*) FROM feedback WHERE {_alive_clause()}"),
"archives": cnt("SELECT COUNT(*) FROM social_archives"),
}
soft = {
"roster": cnt(
"SELECT COUNT(*) FROM roster WHERE (deleted_at IS NOT NULL AND deleted_at!='') OR status='deleted'"
),
"messages": cnt(
"SELECT COUNT(*) FROM messages WHERE deleted_at IS NOT NULL AND deleted_at!=''"
),
"reviews": cnt(
"SELECT COUNT(*) FROM cafe_reviews WHERE deleted_at IS NOT NULL AND deleted_at!=''"
),
"gigApps": cnt(
"SELECT COUNT(*) FROM gig_apps WHERE deleted_at IS NOT NULL AND deleted_at!=''"
),
"feedback": cnt(
"SELECT COUNT(*) FROM feedback WHERE deleted_at IS NOT NULL AND deleted_at!=''"
),
}
rows = c.execute(
f"""
SELECT IFNULL(NULLIF(TRIM(city),''),'未填') AS city, COUNT(*) AS n
FROM roster
WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'
GROUP BY 1
ORDER BY n DESC
LIMIT 12
"""
).fetchall()
by_city = [{"name": r["city"], "value": int(r["n"])} for r in rows]
day_rows = c.execute(
f"""
SELECT substr(updated_at,1,10) AS d, COUNT(*) AS n
FROM roster
WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'
AND updated_at IS NOT NULL AND updated_at!=''
GROUP BY 1
ORDER BY 1
"""
).fetchall()
day_series = [{"date": r["d"], "value": int(r["n"])} for r in day_rows][-30:]
return {
"ok": True,
"counts": counts,
"softDeleted": soft,
"activeRoster": counts["roster"],
"byCity": by_city,
"rosterByDay": day_series,
"backend": "sqlite",
}
def get_detail(entity: str, entity_id: str) -> dict[str, Any] | None:
meta = ENTITY_TABLES.get(entity)
if not meta:
return None
table, pk = meta
with _db() as c:
row = c.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone()
if not row:
return None
item = _row_dict(row) or {}
hist = c.execute(
"""
SELECT id, action, note, payload, created_at
FROM social_archives
WHERE entity=? AND entity_id=?
ORDER BY created_at DESC
LIMIT 50
""",
(entity, entity_id),
).fetchall()
soft = bool(item.get("deleted_at")) or item.get("status") == "deleted"
history = []
for h in hist:
try:
payload = json.loads(h["payload"] or "{}")
except Exception:
payload = {}
history.append(
{
"id": h["id"],
"action": h["action"],
"at": h["created_at"],
"note": h["note"] or "",
"payload": payload,
}
)
return {
"ok": True,
"entity": entity,
"id": entity_id,
"item": item,
"softDeleted": soft,
"history": history,
}
def upsert_join_lead(
*,
email: str,
guest_id: str = "",
stage: str = "email_submit",
name: str = "",
payload: dict[str, Any] | None = None,
ua: str = "",
paid: str = "",
face_ok: str = "",
liveness_status: str = "",
) -> dict[str, Any]:
email_n = (email or "").strip().lower()[:160]
if not email_n or "@" not in email_n:
raise ValueError("invalid email")
now = _now()
stage_n = (stage or "email_submit")[:48]
body = payload if isinstance(payload, dict) else {}
with _db() as c:
existing = c.execute(
"SELECT * FROM join_leads WHERE email=?", (email_n,)
).fetchone()
if existing:
new_payload = {}
try:
new_payload = json.loads(existing["payload"] or "{}")
except Exception:
new_payload = {}
if isinstance(new_payload, dict):
stages = list(new_payload.get("stages") or [])
if stage_n not in stages:
stages.append(stage_n)
new_payload = {**new_payload, **body, "stages": stages}
else:
new_payload = {**body, "stages": [stage_n]}
c.execute(
"""
UPDATE join_leads SET
guest_id=COALESCE(NULLIF(?,''), guest_id),
stage=?,
name=COALESCE(NULLIF(?,''), name),
paid=COALESCE(NULLIF(?,''), paid),
face_ok=COALESCE(NULLIF(?,''), face_ok),
liveness_status=COALESCE(NULLIF(?,''), liveness_status),
ua=COALESCE(NULLIF(?,''), ua),
payload=?,
updated_at=?
WHERE email=?
""",
(
(guest_id or "")[:120],
stage_n,
(name or "")[:64],
(paid or "")[:8],
(face_ok or "")[:8],
(liveness_status or "")[:24],
(ua or "")[:240],
json.dumps(new_payload, ensure_ascii=False),
now,
email_n,
),
)
rid = existing["id"]
else:
rid = _uid("jl")
c.execute(
"""
INSERT INTO join_leads(
id, email, guest_id, stage, name, paid, face_ok, liveness_status,
ua, payload, created_at, updated_at
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
""",
(
rid,
email_n,
(guest_id or "")[:120],
stage_n,
(name or "")[:64],
(paid or "")[:8],
(face_ok or "")[:8],
(liveness_status or "")[:24],
(ua or "")[:240],
json.dumps({**body, "stages": [stage_n]}, ensure_ascii=False),
now,
now,
),
)
# also archive snapshot
c.execute(
"""
INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at)
VALUES (?,?,?,?,?,?,?,?)
""",
(
_uid("arc"),
"join_leads",
email_n,
(guest_id or "")[:120],
stage_n,
f"join:{stage_n}",
json.dumps(
{
"email": email_n,
"guestId": guest_id,
"stage": stage_n,
"name": name,
"paid": paid,
"faceOk": face_ok,
"livenessStatus": liveness_status,
"ua": ua,
"payload": body,
},
ensure_ascii=False,
),
now,
),
)
return {
"ok": True,
"id": rid,
"email": email_n,
"guestId": guest_id,
"stage": stage_n,
"at": now,
}
def list_join_leads(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
lim = max(1, min(int(limit or 100), 500))
off = max(0, int(offset or 0))
needle = (q or "").strip().lower()
with _db(readonly=True) as c:
rows = c.execute(
"SELECT * FROM join_leads ORDER BY updated_at DESC"
).fetchall()
items = []
for r in rows:
try:
payload = json.loads(r["payload"] or "{}")
except Exception:
payload = {}
item = {
"id": r["id"],
"email": r["email"] or "",
"guestId": r["guest_id"] or "",
"stage": r["stage"] or "",
"name": r["name"] or "",
"paid": r["paid"] or "",
"faceOk": r["face_ok"] or "",
"livenessStatus": r["liveness_status"] or "",
"ua": r["ua"] or "",
"payload": payload,
"createdAt": r["created_at"] or "",
"updatedAt": r["updated_at"] or "",
}
if needle:
blob = " ".join(
[
item["email"],
item["guestId"],
item["name"],
item["stage"],
]
).lower()
if needle not in blob:
continue
items.append(item)
total = len(items)
return {"ok": True, "total": total, "items": items[off : off + lim]}
def list_archives(
*, entity: str = "", limit: int = 100, offset: int = 0
) -> dict[str, Any]:
lim = max(1, min(int(limit or 100), 500))
off = max(0, int(offset or 0))
clauses: list[str] = []
params: list[Any] = []
if entity.strip():
clauses.append("entity=?")
params.append(entity.strip())
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
with _db() as c:
total = c.execute(
f"SELECT COUNT(*) AS n FROM social_archives{where}", tuple(params)
).fetchone()["n"]
rows = c.execute(
f"""
SELECT id, entity, entity_id, guest_id, action, note, payload, created_at
FROM social_archives{where}
ORDER BY created_at DESC
LIMIT ? OFFSET ?
""",
(*params, lim, off),
).fetchall()
items = []
for r in rows:
try:
payload = json.loads(r["payload"] or "{}")
except Exception:
payload = {}
items.append(
{
"id": r["id"],
"entity": r["entity"],
"entityId": r["entity_id"],
"guestId": r["guest_id"] or "",
"action": r["action"],
"note": r["note"] or "",
"at": r["created_at"],
"payload": payload,
}
)
return {"ok": True, "total": total, "items": items}

View File

@ -0,0 +1,38 @@
#!/usr/bin/env python3
import json
import urllib.request
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main():
# get password from server env
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command(
r"""
cd /opt/nomadmini/backend
USER=$(grep -E '^ADMIN_USERNAME=' .env 2>/dev/null | cut -d= -f2- | tr -d '"' | tr -d "'")
PASS=$(grep -E '^ADMIN_PASSWORD=' .env 2>/dev/null | cut -d= -f2- | tr -d '"' | tr -d "'")
[ -z "$USER" ] && USER=admin
echo "user=$USER"
BODY=$(curl -sk -X POST https://admin.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d "{\"username\":\"$USER\",\"password\":\"$PASS\"}")
echo "login=$BODY"
TOKEN=$(echo "$BODY" | .venv/bin/python -c 'import sys,json; d=json.load(sys.stdin); print(d.get("token") or d.get("access_token") or "")')
echo "tok=${#TOKEN}"
CFG=$(curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/config)
echo "$CFG" | .venv/bin/python -c 'import sys,json; d=json.load(sys.stdin); print(json.dumps({k:d.get(k) if k!="config" else {"modules": (d.get("config") or {}).get("modules"), "ch": len(((d.get("config") or {}).get("bookContent") or {}).get("chapters") or [])} for k in d}, ensure_ascii=False, indent=2)[:2000])'
META=$(curl -sk -H "Authorization: Bearer $TOKEN" https://admin.nomadro.cn/api/admin/douyin/meta)
echo "meta=$META"
""",
timeout=60,
get_pty=True,
)
print(o.read().decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Smoke-check Douyin admin + API on production."""
from __future__ import annotations
import json
import urllib.request
import paramiko
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def http(url: str) -> tuple[int, str]:
req = urllib.request.Request(url, method="GET")
try:
with urllib.request.urlopen(req, timeout=20) as r:
return r.status, r.read().decode("utf-8", "replace")[:800]
except urllib.error.HTTPError as e:
return e.code, e.read().decode("utf-8", "replace")[:800]
def main() -> int:
for url in (
"https://api.nomadro.cn/health",
"https://admin.nomadro.cn/",
"https://admin.nomadro.cn/douyin",
"https://admin.nomadro.cn/api/admin/douyin/meta",
):
code, body = http(url)
print(f"{code} {url}")
if "health" in url or "meta" in url:
print(" ", body[:200].replace("\n", " "))
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
_, o, _ = c.exec_command(
"grep -o 'douyin' /www/wwwroot/admin.nomadro.cn/assets/*.js | wc -l; "
"grep -o 'PlatformSelect\\|入口开关\\|小册 Markdown' /www/wwwroot/admin.nomadro.cn/assets/*.js | head -5; "
"python3 -c \"import ast; ast.parse(open('/opt/nomadmini/backend/app/services/tt_platform_config.py').read()); print('tt_platform_config AST ok')\"; "
"systemctl is-active nomadmini-api",
timeout=60,
)
print(o.read().decode("utf-8", "replace"))
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Verify realtime homeVariant PUT + config_change track."""
from __future__ import annotations
import json
import sys
import urllib.request
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
BASE = "https://admin.nomadro.cn"
def req(method: str, path: str, token: str | None = None, body: dict | None = None):
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(r, timeout=25) as resp:
return json.loads(resp.read().decode())
def main() -> int:
login = req("POST", "/api/admin/login", body={"username": "admin", "password": "Xiao4669805"})
token = login.get("token") or login.get("access_token")
if not token:
print("login fail", login)
return 1
before = req("GET", "/api/admin/douyin/config", token=token)
hv = (before.get("config") or {}).get("homeVariant") or "bmi"
print("before", hv)
target = "bmi" if hv == "hub" else "hub"
put = req("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": target})
after = (put.get("config") or {}).get("homeVariant")
print("after", after, "ok", put.get("ok"))
# restore
req("PUT", "/api/admin/douyin/config", token=token, body={"homeVariant": hv})
print("restored", hv)
events = req("GET", "/api/admin/track-events?limit=5&name=config_change", token=token)
rows = events.get("events") or events.get("items") or events
if isinstance(rows, dict):
rows = rows.get("events") or []
print("recent config_change count sample", len(rows) if isinstance(rows, list) else type(rows))
if isinstance(rows, list) and rows:
e0 = rows[0]
print("latest", e0.get("name"), e0.get("label"), e0.get("client"))
return 0 if after == target else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"82.157.112.245",
username="ubuntu",
password="Xiao4669805",
timeout=60,
allow_agent=False,
look_for_keys=False,
)
cmd = r"""
# GET with max-time; print status + key headers
curl -sk --max-time 3 -D - -o /dev/null 'https://nomadro.cn/live/nope.flv' | head -25 || true
echo '----'
curl -s --max-time 3 -D - -o /dev/null 'http://127.0.0.1:1985/live/nope.flv' | head -20 || true
echo '---- ext file ----'
sudo cat /www/server/panel/vhost/nginx/extension/www.nomadro.cn/live-flv.conf
echo '---- rtmp port ----'
ss -lntp | grep 1935 || true
"""
_, o, _ = c.exec_command(cmd, timeout=40, get_pty=True)
print(o.read().decode("utf-8", "replace"))
c.close()

View File

@ -0,0 +1,149 @@
/*! admin-leads-online.js — animate 在线 column on /leads without touching SPA bundle */
(function () {
"use strict";
if (window.__adminLeadsOnlineBooted) return;
window.__adminLeadsOnlineBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TTL_MS = 120000;
var STYLE_ID = "admin-leads-online-style";
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var s = document.createElement("style");
s.id = STYLE_ID;
s.textContent =
"@keyframes comOnlinePulse{0%{box-shadow:0 0 0 0 rgba(52,211,153,.55)}70%{box-shadow:0 0 0 8px rgba(52,211,153,0)}100%{box-shadow:0 0 0 0 rgba(52,211,153,0)}}" +
"@keyframes comOnlineGlow{0%,100%{filter:none}50%{filter:drop-shadow(0 0 6px rgba(52,211,153,.4))}}" +
".alo-cell{display:inline-flex;flex-direction:column;align-items:flex-start;gap:4px;min-width:64px}" +
".alo-badge{display:inline-flex;align-items:center;gap:6px;padding:3px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.1em}" +
".alo-badge.on{color:#6ee7b7;border:1px solid rgba(52,211,153,.4);background:rgba(52,211,153,.08);animation:comOnlineGlow 2s ease-in-out infinite}" +
".alo-badge.on i{width:7px;height:7px;border-radius:50%;background:#34d399;animation:comOnlinePulse 1.6s ease-out infinite}" +
".alo-badge.off{color:#a8a29e;border:1px solid rgba(168,162,158,.25);background:rgba(255,255,255,.03)}" +
".alo-time{font-size:12px;color:#a8a29e}" +
".alo-badge.on + .alo-time,.alo-cell.is-live .alo-time{color:#6ee7b7;font-weight:600}" +
"th.alo-th-live{color:#6ee7b7}" +
"tr.alo-row-live td:first-child{animation:comOnlineGlow 2.4s ease-in-out infinite}";
document.head.appendChild(s);
}
function parseTs(text, title) {
// title often full locale string; text is relative like 刚刚 / 3分钟前
if (title && title !== "—") {
var d = Date.parse(title.replace(/年|月/g, "/").replace(/日/g, " "));
if (!Number.isNaN(d)) return d;
d = Date.parse(title);
if (!Number.isNaN(d)) return d;
}
var t = (text || "").trim();
if (!t || t === "—") return 0;
if (t === "刚刚") return Date.now();
var m = t.match(/^(\d+)\s*秒/);
if (m) return Date.now() - Number(m[1]) * 1000;
m = t.match(/^(\d+)\s*分钟/);
if (m) return Date.now() - Number(m[1]) * 60000;
m = t.match(/^(\d+)\s*小时/);
if (m) return Date.now() - Number(m[1]) * 3600000;
return 0;
}
function paintCell(td, live) {
if (!td) return;
if (td.getAttribute("data-alo") === "1") {
var badge = td.querySelector(".alo-badge");
var time = td.querySelector(".alo-time");
if (badge) {
badge.className = "alo-badge " + (live ? "on" : "off");
badge.innerHTML = live ? "<i></i>在线" : "离线";
}
td.classList.toggle("is-live", !!live);
var tr = td.closest("tr");
if (tr) tr.classList.toggle("alo-row-live", !!live);
return;
}
var rawText = (td.textContent || "").trim();
var title = td.getAttribute("title") || "";
td.setAttribute("data-alo", "1");
td.innerHTML = "";
var wrap = document.createElement("div");
wrap.className = "alo-cell" + (live ? " is-live" : "");
var badge = document.createElement("span");
badge.className = "alo-badge " + (live ? "on" : "off");
badge.innerHTML = live ? "<i></i>在线" : "离线";
var time = document.createElement("span");
time.className = "alo-time";
time.textContent = rawText || "—";
if (title) time.title = title;
wrap.appendChild(badge);
wrap.appendChild(time);
td.appendChild(wrap);
var tr = td.closest("tr");
if (tr) tr.classList.toggle("alo-row-live", !!live);
}
function findOnlineColIndex(table) {
var ths = table.querySelectorAll("thead th");
for (var i = 0; i < ths.length; i++) {
var label = (ths[i].textContent || "").trim();
if (label === "最近活跃" || label === "在线" || label.indexOf("活跃") >= 0) {
ths[i].classList.add("alo-th-live");
if (label === "最近活跃") ths[i].textContent = "在线";
return i;
}
}
return 0; // leads list first col
}
function enhance() {
if (!location.pathname.replace(/\/$/, "").endsWith("/leads") && location.pathname !== "/leads") {
// also allow /leads with query
if (location.pathname.replace(/\/+$/, "") !== "/leads") return;
}
ensureStyle();
var tables = document.querySelectorAll("table.com-table");
tables.forEach(function (table) {
var idx = findOnlineColIndex(table);
var rows = table.querySelectorAll("tbody tr");
rows.forEach(function (tr) {
var tds = tr.querySelectorAll("td");
if (!tds.length || idx >= tds.length) return;
var td = tds[idx];
var title = td.getAttribute("title") || "";
var text = td.getAttribute("data-alo") === "1"
? (td.querySelector(".alo-time") || {}).textContent || ""
: (td.textContent || "").trim();
// Prefer title absolute time; if missing, relative text
var ts = parseTs(text, title);
var live = ts > 0 && Date.now() - ts < TTL_MS;
// relative "刚刚" / N分钟
if (!ts) {
var rel = text;
if (td.getAttribute("data-alo") === "1") {
rel = (td.querySelector(".alo-time") || {}).textContent || "";
}
if (rel === "刚刚" || /^\d+\s*秒/.test(rel) || /^[1-2]\s*分钟/.test(rel)) live = true;
}
paintCell(td, live);
});
});
}
function boot() {
ensureStyle();
enhance();
setInterval(enhance, 5000);
var obs = new MutationObserver(function () {
enhance();
});
obs.observe(document.documentElement, { childList: true, subtree: true });
window.addEventListener("popstate", function () {
setTimeout(enhance, 50);
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,275 @@
/*! admin-live.js — LIVE online + broadcast dock for admin.hackrobot.cn VIP 运营台 */
(function () {
"use strict";
if (window.__adminLiveBooted) return;
window.__adminLiveBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TOKEN_KEY = "vip_ops_token";
var API_ONLINE = "/api/admin/live/online";
var API_BC = "/api/admin/live/broadcast";
var API_STREAM = "/api/admin/live/stream";
var POLL_MS = 5000;
function token() {
try {
return localStorage.getItem(TOKEN_KEY) || "";
} catch (e) {
return "";
}
}
function authHeaders() {
var t = token();
return t
? { Authorization: "Bearer " + t, "Content-Type": "application/json" }
: { "Content-Type": "application/json" };
}
function el(tag, attrs, kids) {
var n = document.createElement(tag);
if (attrs) {
Object.keys(attrs).forEach(function (k) {
if (k === "style" && typeof attrs[k] === "object") {
Object.assign(n.style, attrs[k]);
} else if (k === "text") {
n.textContent = attrs[k];
} else if (k.slice(0, 2) === "on") {
n.addEventListener(k.slice(2).toLowerCase(), attrs[k]);
} else {
n.setAttribute(k, attrs[k]);
}
});
}
(kids || []).forEach(function (c) {
if (c == null) return;
n.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
});
return n;
}
function ensureStyle() {
if (document.getElementById("admin-live-style")) return;
var s = document.createElement("style");
s.id = "admin-live-style";
s.textContent =
"@keyframes alPulse{0%,100%{opacity:1}50%{opacity:.45}}" +
"@keyframes alIn{from{opacity:0;transform:translateY(12px) scale(.98)}to{opacity:1;transform:none}}" +
"#admin-live-fab{position:fixed;right:18px;bottom:18px;z-index:2147482500;display:flex;align-items:center;gap:8px;padding:12px 16px;min-height:44px;border-radius:999px;border:1px solid rgba(245,158,11,.45);background:linear-gradient(135deg,#1a1408,#0c0c0f 55%,#121016);color:#fbbf24;font:600 13px/1.2 'DM Sans',Syne,system-ui,sans-serif;cursor:pointer;box-shadow:0 12px 40px rgba(0,0,0,.45),0 0 0 1px rgba(245,158,11,.12);backdrop-filter:blur(10px)}" +
"#admin-live-fab .dot{width:8px;height:8px;border-radius:50%;background:#22c55e;box-shadow:0 0 10px #22c55e;animation:alPulse 1.6s ease-in-out infinite}" +
"#admin-live-fab[data-off=1] .dot{background:#78716c;box-shadow:none;animation:none}" +
"#admin-live-panel{position:fixed;right:14px;bottom:72px;z-index:2147482501;width:min(380px,calc(100vw - 28px));max-height:min(72vh,560px);overflow:auto;border-radius:16px;border:1px solid rgba(245,158,11,.28);background:linear-gradient(165deg,#141418 0%,#0c0c0f 60%,#1a1408 100%);color:#e7e5e4;box-shadow:0 24px 60px rgba(0,0,0,.55);animation:alIn .28s ease;font-family:'DM Sans',system-ui,sans-serif;padding:14px}" +
"#admin-live-panel h3{margin:0 0 8px;font:700 15px/1.2 Syne,'DM Sans',sans-serif;color:#fbbf24;letter-spacing:.02em}" +
"#admin-live-panel .meta{font-size:12px;color:#a8a29e;margin-bottom:10px}" +
"#admin-live-panel .list{display:flex;flex-direction:column;gap:6px;margin:0 0 12px;max-height:180px;overflow:auto}" +
"#admin-live-panel .row{display:flex;flex-direction:column;gap:2px;padding:8px 10px;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);font-size:12px}" +
"#admin-live-panel .row b{color:#fafaf9;font-weight:600}" +
"#admin-live-panel .row span{color:#a8a29e}" +
"#admin-live-panel label{display:block;font-size:11px;color:#a8a29e;margin:8px 0 4px}" +
"#admin-live-panel input,#admin-live-panel textarea,#admin-live-panel select{width:100%;box-sizing:border-box;border-radius:10px;border:1px solid rgba(255,255,255,.1);background:#0a0a0c;color:#f5f5f4;padding:10px 12px;font:400 13px/1.35 inherit;min-height:44px}" +
"#admin-live-panel textarea{min-height:72px;resize:vertical}" +
"#admin-live-panel .actions{display:flex;gap:8px;margin-top:12px}" +
"#admin-live-panel button{flex:1;min-height:44px;border-radius:12px;border:0;font:600 13px/1 inherit;cursor:pointer}" +
"#admin-live-panel .send{background:linear-gradient(135deg,#f59e0b,#d97706);color:#111}" +
"#admin-live-panel .ghost{background:rgba(255,255,255,.06);color:#e7e5e4}" +
"#admin-live-panel .msg{margin-top:8px;font-size:12px;color:#86efac}" +
"#admin-live-panel .err{color:#fda4af}" +
"#admin-live-panel .empty{font-size:12px;color:#78716c;padding:8px 0}";
document.head.appendChild(s);
}
var state = { open: false, online: [], ok: false, err: "", busy: false };
var fab, panel;
function renderList() {
if (!panel) return;
var list = panel.querySelector(".list");
list.innerHTML = "";
if (!state.online.length) {
list.appendChild(
el("div", { class: "empty", text: state.ok ? "当前无人在线" : "等待连接…" })
);
return;
}
state.online.slice(0, 40).forEach(function (u) {
var title = u.nick || u.email || u.id || "访客";
var sub = [u.page || "/", u.role || "", u.email && u.nick ? u.email : ""]
.filter(Boolean)
.join(" · ");
list.appendChild(
el("div", { class: "row" }, [el("b", { text: title }), el("span", { text: sub })])
);
});
}
function syncFab() {
if (!fab) return;
fab.setAttribute("data-off", state.ok ? "0" : "1");
fab.querySelector(".lab").textContent = "LIVE · " + state.online.length;
}
async function refresh() {
var t = token();
if (!t) {
state.ok = false;
state.online = [];
syncFab();
if (state.open) renderList();
return;
}
try {
var res = await fetch(API_ONLINE, { headers: authHeaders(), credentials: "omit" });
if (!res.ok) throw new Error("HTTP " + res.status);
var data = await res.json();
state.online = Array.isArray(data.webOnline) ? data.webOnline : [];
state.ok = true;
} catch (e) {
state.ok = false;
}
syncFab();
if (state.open) renderList();
}
async function sendBroadcast() {
if (state.busy || !panel) return;
var title = panel.querySelector("[name=title]").value.trim();
var body = panel.querySelector("[name=body]").value.trim();
var cta = panel.querySelector("[name=cta]").value.trim() || "知道了";
var href = panel.querySelector("[name=href]").value.trim();
var tone = panel.querySelector("[name=tone]").value || "amber";
var msgEl = panel.querySelector(".msg");
if (!title) {
msgEl.className = "msg err";
msgEl.textContent = "请填写标题";
return;
}
state.busy = true;
msgEl.className = "msg";
msgEl.textContent = "发送中…";
try {
var res = await fetch(API_BC, {
method: "POST",
headers: authHeaders(),
credentials: "omit",
body: JSON.stringify({
title: title,
body: body,
cta: cta,
href: href,
tone: tone,
ttlSec: 90,
}),
});
var data = await res.json().catch(function () {
return {};
});
if (!res.ok) throw new Error(data.detail || "HTTP " + res.status);
msgEl.className = "msg";
msgEl.textContent = "已推送到 vip.hackrobot.cn 在线用户";
panel.querySelector("[name=title]").value = "";
panel.querySelector("[name=body]").value = "";
} catch (e) {
msgEl.className = "msg err";
msgEl.textContent = (e && e.message) || "发送失败";
} finally {
state.busy = false;
}
}
function openPanel() {
if (panel) {
state.open = !state.open;
panel.style.display = state.open ? "block" : "none";
if (state.open) {
renderList();
refresh();
}
return;
}
panel = el("div", { id: "admin-live-panel" }, [
el("h3", { text: "实时在线 · 通知" }),
el("div", { class: "meta", text: "vip.hackrobot.cn 访客心跳 · 一键弹窗推送" }),
el("div", { class: "list" }),
el("label", { text: "标题" }),
el("input", { name: "title", placeholder: "例如:限时优惠", maxlength: "80" }),
el("label", { text: "正文" }),
el("textarea", { name: "body", placeholder: "弹窗内容(可选)", maxlength: "400" }),
el("label", { text: "按钮文案" }),
el("input", { name: "cta", value: "知道了", maxlength: "32" }),
el("label", { text: "跳转链接" }),
el("input", { name: "href", value: "https://vip.hackrobot.cn/", maxlength: "300" }),
el("label", { text: "色调" }),
el("select", { name: "tone" }, [
el("option", { value: "amber", text: "琥珀" }),
el("option", { value: "mint", text: "薄荷绿" }),
el("option", { value: "rose", text: "玫红" }),
]),
el("div", { class: "actions" }, [
el("button", {
class: "ghost",
type: "button",
text: "刷新",
onClick: function () {
refresh();
},
}),
el("button", {
class: "send",
type: "button",
text: "推送弹窗",
onClick: sendBroadcast,
}),
]),
el("div", { class: "msg" }),
]);
document.body.appendChild(panel);
state.open = true;
renderList();
}
function boot() {
ensureStyle();
fab = el(
"button",
{
id: "admin-live-fab",
type: "button",
title: "实时在线 / 通知",
onClick: openPanel,
},
[el("span", { class: "dot" }), el("span", { class: "lab", text: "LIVE · 0" })]
);
document.body.appendChild(fab);
refresh();
setInterval(refresh, POLL_MS);
try {
var t = token();
if (t && window.EventSource) {
var es = new EventSource(API_STREAM + "?token=" + encodeURIComponent(t));
es.addEventListener("tick", function (ev) {
try {
var data = JSON.parse(ev.data || "{}");
if (Array.isArray(data.webOnline)) {
state.online = data.webOnline;
state.ok = true;
syncFab();
if (state.open) renderList();
}
} catch (e) {}
});
es.onerror = function () {
try {
es.close();
} catch (e) {}
};
}
} catch (e) {}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,272 @@
/*! admin-user-tags.js — blacklist/archive tags + identity across VIP ops */
(function () {
"use strict";
if (window.__adminUserTagsBooted) return;
window.__adminUserTagsBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TOKEN_KEY = "vip_ops_token";
var STYLE_ID = "admin-user-tags-style";
var CACHE_MS = 20000;
var state = { blocks: [], archives: [], leads: [], byId: {}, fetchedAt: 0, busy: false };
function token() {
try { return localStorage.getItem(TOKEN_KEY) || ""; } catch (e) { return ""; }
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var s = document.createElement("style");
s.id = STYLE_ID;
s.textContent =
".aut-chip{display:inline-flex;align-items:center;gap:4px;margin-left:6px;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.04em;vertical-align:middle;white-space:nowrap;cursor:help;line-height:1.4}" +
".aut-chip-block{color:#fecaca;border:1px solid rgba(248,113,113,.45);background:rgba(239,68,68,.14)}" +
".aut-chip-was{color:#fcd34d;border:1px solid rgba(245,158,11,.4);background:rgba(245,158,11,.12)}" +
".aut-hint{display:block;font-size:11px;color:#a8a29e;margin-top:2px;line-height:1.35}" +
"#admin-live-panel .row .aut-chip{margin-left:0;margin-top:2px}" +
"code.aut-marked{outline:1px dashed rgba(245,158,11,.25);outline-offset:2px;border-radius:4px}";
document.head.appendChild(s);
}
function norm(s) { return String(s || "").trim().toLowerCase(); }
function addKeys(map, key, info) {
var k = norm(key);
if (!k || k === "-" || k === "—") return;
var cur = map[k];
if (!cur) { map[k] = info; return; }
if (info.status === "blocked" || (info.status === "was" && cur.status !== "blocked")) {
map[k] = Object.assign({}, cur, info);
}
}
function rebuildIndex() {
var map = {};
(state.blocks || []).forEach(function (b) {
var info = {
status: "blocked",
reason: b.reason || "",
note: b.note || "",
kind: b.kind || "user",
at: b.createdAt || "",
by: b.createdBy || ""
};
addKeys(map, b.userId, info);
(b.aliases || []).forEach(function (a) { addKeys(map, a, info); });
});
(state.archives || []).forEach(function (a) {
var info = {
status: "was",
reason: a.reason || "",
note: a.note || "",
kind: a.kind || "user",
at: a.createdAt || "",
by: a.createdBy || "",
unblockedAt: a.unblockedAt || "",
unblockedBy: a.unblockedBy || ""
};
addKeys(map, a.userId, info);
(a.aliases || []).forEach(function (x) { addKeys(map, x, info); });
});
(state.leads || []).forEach(function (u) {
var ids = [u.key, u.display, u.email, u.openid, u.userId, u.ip].concat(u.aliases || []);
var hit = null;
for (var i = 0; i < ids.length; i++) {
hit = map[norm(ids[i])];
if (hit) break;
}
if (!hit && u.blocked) hit = { status: "blocked", reason: "线索标记", at: "", by: "" };
if (hit) ids.forEach(function (id) { addKeys(map, id, hit); });
});
state.byId = map;
}
function lookup() {
for (var i = 0; i < arguments.length; i++) {
var hit = state.byId[norm(arguments[i])];
if (hit) return hit;
}
return null;
}
function findLead() {
var ids = [];
for (var i = 0; i < arguments.length; i++) {
var n = norm(arguments[i]);
if (n) ids.push(n);
}
var leads = state.leads || [];
for (var li = 0; li < leads.length; li++) {
var u = leads[li];
var bag = [u.key, u.display, u.email, u.openid, u.userId, u.ip]
.concat(u.aliases || [])
.map(norm);
for (var j = 0; j < ids.length; j++) {
if (ids[j] && bag.indexOf(ids[j]) >= 0) return u;
}
}
return null;
}
function tipFor(info) {
if (!info) return "";
var parts = [];
if (info.status === "blocked") parts.push("当前拉黑");
if (info.status === "was") parts.push("历史拉黑(已解除,须重新付款开通)");
if (info.reason) parts.push("原因: " + info.reason);
if (info.note) parts.push("备注: " + info.note);
if (info.at) parts.push("拉黑: " + info.at);
if (info.unblockedAt) parts.push("解除: " + info.unblockedAt);
if (info.by) parts.push("操作: " + info.by);
return parts.join("\n");
}
function chipEl(info) {
var span = document.createElement("span");
if (info.status === "blocked") {
span.className = "aut-chip aut-chip-block";
span.textContent = "已拉黑";
} else {
span.className = "aut-chip aut-chip-was";
span.textContent = "曾拉黑";
}
span.title = tipFor(info);
return span;
}
function identityHint(lead) {
if (!lead) return null;
var bits = [];
var nick = null;
(lead.aliases || []).forEach(function (a) {
if (!a) return;
if (/^user\d+$/i.test(a)) return;
if (/^\d+\.\d+\.\d+\.\d+$/.test(a)) return;
if (/^smw/i.test(a)) return;
if (a.length >= 2 && a.length <= 32) nick = nick || a;
});
if (nick) bits.push("昵称 " + nick);
if (lead.email && lead.email !== lead.display) bits.push(lead.email);
if (lead.ip) bits.push("IP " + lead.ip);
if (!bits.length) return null;
var d = document.createElement("span");
d.className = "aut-hint";
d.textContent = bits.slice(0, 3).join(" · ");
d.title = bits.join("\n");
return d;
}
function paintNear(node, ids) {
if (!node || node.nodeType !== 1) return;
var info = lookup.apply(null, ids);
var lead = findLead.apply(null, ids);
var next = node.nextSibling;
while (next && next.nodeType === 1 && next.classList && next.classList.contains("aut-chip")) {
var rm = next;
next = next.nextSibling;
rm.remove();
}
if (info) {
node.classList.add("aut-marked");
node.insertAdjacentElement("afterend", chipEl(info));
}
var host = node.parentElement;
if (lead && host && node.tagName === "CODE" && !host.querySelector(":scope > .aut-hint")) {
var hint = identityHint(lead);
if (hint) host.appendChild(hint);
}
}
function enhanceCodes() {
document.querySelectorAll("code").forEach(function (code) {
if (code.closest("#admin-live-panel")) return;
paintNear(code, [(code.textContent || "").trim()]);
});
}
function enhanceLivePanel() {
var panel = document.getElementById("admin-live-panel");
if (!panel) return;
panel.querySelectorAll(".row").forEach(function (row) {
var b = row.querySelector("b");
var span = row.querySelector("span");
var ids = [];
if (b) ids.push(b.textContent || "");
if (span) {
String(span.textContent || "").split("·").forEach(function (p) {
ids.push(p.trim());
});
}
row.querySelectorAll(".aut-chip, .aut-hint").forEach(function (c) {
if (c.parentElement === row) c.remove();
});
var info = lookup.apply(null, ids);
if (info) row.appendChild(chipEl(info));
var hint = identityHint(findLead.apply(null, ids));
if (hint) row.appendChild(hint);
});
}
async function refreshData(force) {
var t = token();
if (!t) return;
if (!force && Date.now() - state.fetchedAt < CACHE_MS) return;
if (state.busy) return;
state.busy = true;
try {
var headers = { Authorization: "Bearer " + t };
var ctrl = await fetch("/api/ops/control", {
headers: headers,
credentials: "omit"
}).then(function (r) { return r.ok ? r.json() : {}; });
state.blocks = ctrl.blocks || [];
state.archives = ctrl.archives || [];
try {
var leads = await fetch("/api/ops/leads?limit=400", {
headers: headers,
credentials: "omit"
}).then(function (r) { return r.ok ? r.json() : {}; });
state.leads = leads.users || [];
} catch (e) {}
rebuildIndex();
state.fetchedAt = Date.now();
} catch (e) {
} finally {
state.busy = false;
}
}
var paintTimer = null;
function schedulePaint() {
if (paintTimer) return;
paintTimer = setTimeout(function () {
paintTimer = null;
try {
ensureStyle();
enhanceCodes();
enhanceLivePanel();
} catch (e) {}
}, 120);
}
async function tick() {
await refreshData(false);
schedulePaint();
}
function boot() {
ensureStyle();
tick();
setInterval(tick, 8000);
new MutationObserver(function () { schedulePaint(); }).observe(
document.documentElement,
{ childList: true, subtree: true }
);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,786 @@
/*! admin-users.js — 用户列表 CRUD(表格页) */
(function () {
"use strict";
if (window.__adminUsersBooted) return;
window.__adminUsersBooted = true;
if (!/admin\.hackrobot\.cn$/i.test(location.hostname)) return;
var TOKEN_KEY = "vip_ops_token";
var PATH = "/user-list";
var API = "https://vip.hackrobot.cn/api/wechat-users";
function token() {
try {
return localStorage.getItem(TOKEN_KEY) || "";
} catch (e) {
return "";
}
}
function el(tag, attrs, kids) {
var n = document.createElement(tag);
if (attrs) {
Object.keys(attrs).forEach(function (k) {
if (k === "style" && typeof attrs[k] === "object") Object.assign(n.style, attrs[k]);
else if (k === "text") n.textContent = attrs[k];
else if (k === "html") n.innerHTML = attrs[k];
else if (k.slice(0, 2) === "on") n.addEventListener(k.slice(2).toLowerCase(), attrs[k]);
else if (k === "checked") n.checked = !!attrs[k];
else if (k === "value") n.value = attrs[k];
else n.setAttribute(k, attrs[k]);
});
}
(kids || []).forEach(function (c) {
if (c == null) return;
n.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
});
return n;
}
function ensureStyle() {
if (document.getElementById("admin-users-style")) return;
var s = document.createElement("style");
s.id = "admin-users-style";
s.textContent = [
"#admin-users-root{--bg:transparent;--fg:#F8FAFC;--muted:#94A3B8;--card:rgba(27,35,54,.92);--border:#475569;--accent:#22C55E;--danger:#EF4444;--sky:#38BDF8;display:none;color:var(--fg);font:400 14px/1.45 ui-sans-serif,system-ui,sans-serif;width:100%}",
"#admin-users-root[data-on='1']{display:block}",
"main.com-main.admin-users-active > .com-page-enter{display:none!important}",
"#admin-users-root .wrap{max-width:100%;margin:0;padding:4px 0 32px}",
"#admin-users-root h1{margin:0 0 6px;font:700 22px/1.2 ui-sans-serif,system-ui,sans-serif}",
"#admin-users-root .sub{color:var(--muted);font-size:13px;margin:0 0 14px}",
"#admin-users-root .bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:12px}",
"#admin-users-root input,#admin-users-root select,#admin-users-root textarea{min-height:44px;border-radius:10px;border:1px solid var(--border);background:#121826;color:var(--fg);padding:10px 12px;font:inherit}",
"#admin-users-root input[type=search]{flex:1;min-width:200px}",
"#admin-users-root textarea{min-height:88px;resize:vertical;width:100%}",
"#admin-users-root button,.btn{min-height:40px;border-radius:10px;border:0;padding:0 14px;font:600 13px/1 ui-sans-serif,system-ui,sans-serif;cursor:pointer;transition:opacity .15s}",
"#admin-users-root button:hover,.btn:hover{opacity:.92}",
"#admin-users-root button:focus-visible,.btn:focus-visible{outline:2px solid #fff;outline-offset:2px}",
"#admin-users-root .primary{background:var(--accent);color:#0F172A}",
"#admin-users-root .sky{background:var(--sky);color:#0F172A}",
"#admin-users-root .ghost{background:rgba(255,255,255,.08);color:var(--fg)}",
"#admin-users-root .danger{background:rgba(239,68,68,.2);color:#FECACA}",
"#admin-users-root .meta{font-size:12px;color:var(--muted);margin:8px 0 12px}",
"#admin-users-root .err{color:#FDA4AF;font-size:13px;margin:8px 0}",
"#admin-users-root .ok{color:#86EFAC;font-size:13px;margin:8px 0}",
"#admin-users-root .table-wrap{overflow:auto;border:1px solid var(--border);border-radius:14px;background:var(--card)}",
"#admin-users-root table{width:100%;border-collapse:collapse;min-width:980px}",
"#admin-users-root th,#admin-users-root td{padding:10px 12px;text-align:left;border-bottom:1px solid rgba(71,85,105,.55);vertical-align:top}",
"#admin-users-root th{font-size:12px;color:var(--muted);font-weight:600;position:sticky;top:0;background:#171f33;z-index:1}",
"#admin-users-root tr:hover td{background:rgba(255,255,255,.03)}",
"#admin-users-root .av{width:40px;height:40px;border-radius:999px;object-fit:cover;background:#0b1220;display:block}",
"#admin-users-root .av.ph{width:40px;height:40px;border-radius:999px;display:flex;align-items:center;justify-content:center;background:#0b1220;color:var(--muted);font-size:14px}",
"#admin-users-root .nick{font-weight:600}",
"#admin-users-root .mono{font:12px/1.4 ui-monospace,Consolas,monospace;color:var(--sky);word-break:break-all}",
"#admin-users-root .sig{font-size:12px;color:#CBD5E1;max-width:220px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}",
"#admin-users-root .chip{display:inline-block;font-size:11px;padding:2px 7px;border-radius:999px;background:rgba(56,189,248,.14);color:#7DD3FC;margin-right:4px}",
"#admin-users-root .ops{display:flex;flex-wrap:wrap;gap:6px}",
"#admin-users-root .ops button{min-height:32px;padding:0 10px;font-size:12px}",
"#admin-users-root .pager{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}",
"#admin-users-root .modal-mask{position:fixed;inset:0;background:rgba(2,6,23,.72);display:flex;align-items:center;justify-content:center;padding:16px;z-index:2147483000}",
"#admin-users-root .modal{width:min(560px,100%);max-height:90vh;overflow:auto;background:#121826;border:1px solid var(--border);border-radius:16px;padding:18px}",
"#admin-users-root .modal h2{margin:0 0 12px;font-size:18px}",
"#admin-users-root .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}",
"#admin-users-root .form-grid .full{grid-column:1 / -1}",
"#admin-users-root label{display:block;font-size:12px;color:var(--muted);margin-bottom:4px}",
"#admin-users-root .modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}",
"@media (max-width:720px){#admin-users-root .form-grid{grid-template-columns:1fr}}",
"a.admin-users-nav.com-nav-link{display:flex!important}",
].join("");
document.head.appendChild(s);
}
var state = {
users: [],
total: 0,
page: 1,
perPage: 50,
totalPages: 1,
q: "",
busy: false,
err: "",
msg: "",
selected: {},
modal: null, // {mode:'create'|'edit', user:{}}
};
function authHeaders() {
return { Authorization: "Bearer " + token(), Accept: "application/json", "Content-Type": "application/json" };
}
async function api(method, path, body) {
var res = await fetch(API + (path || ""), {
method: method || "GET",
headers: authHeaders(),
body: body ? JSON.stringify(body) : undefined,
cache: "no-store",
});
var data = await res.json().catch(function () {
return {};
});
if (!res.ok || data.ok === false) {
throw new Error(data.error || "请求失败 " + res.status);
}
return data;
}
function isOn() {
return location.pathname.replace(/\/+$/, "") === PATH;
}
function setTopbarTitle(on) {
var title = document.querySelector(".com-topbar-title");
if (!title) return;
if (on) {
if (!title.getAttribute("data-users-prev")) {
title.setAttribute("data-users-prev", title.innerHTML);
}
title.innerHTML = '<span aria-hidden="true">👥</span> 用户列表';
} else if (title.getAttribute("data-users-prev")) {
title.innerHTML = title.getAttribute("data-users-prev");
title.removeAttribute("data-users-prev");
}
}
function mountRoot() {
var main = document.querySelector("main.com-main");
var root = document.getElementById("admin-users-root");
if (!root) {
root = el("div", { id: "admin-users-root" });
}
if (main) {
if (root.parentElement !== main) main.appendChild(root);
} else if (!root.parentElement) {
document.body.appendChild(root);
}
return root;
}
function syncShell(on) {
var main = document.querySelector("main.com-main");
if (main) main.classList.toggle("admin-users-active", !!on);
document.querySelectorAll("a.admin-users-nav").forEach(function (a) {
a.classList.toggle("active", !!on);
});
document.querySelectorAll(".com-side-nav a.com-nav-link").forEach(function (a) {
if (a.classList.contains("admin-users-nav")) return;
if (on) a.classList.remove("active");
});
setTopbarTitle(on);
}
function scrollMainIntoView() {
var main = document.querySelector("main.com-main");
if (!main) return;
// 窄屏侧栏 translate 隐藏后仍占 grid 行,把主区滚进视口
var y = main.getBoundingClientRect().top + window.scrollY - 4;
if (y > 8) window.scrollTo(0, y);
}
function openPage() {
if (!isOn()) {
history.pushState({}, "", PATH);
}
// 关掉 SPA 移动端侧栏
var scrim = document.querySelector(".com-nav-scrim");
if (scrim) scrim.click();
var closeBtn = document.querySelector('button[aria-label="关闭菜单"]');
if (closeBtn) closeBtn.click();
render(true);
scrollMainIntoView();
setTimeout(scrollMainIntoView, 50);
if (!state.busy) load();
}
async function load() {
state.busy = true;
state.err = "";
state.msg = "";
paint();
if (!token()) {
state.busy = false;
state.err = "未登录运营台(缺少 vip_ops_token)";
paint();
return;
}
try {
var qs =
"?page=" +
state.page +
"&limit=" +
state.perPage +
(state.q ? "&q=" + encodeURIComponent(state.q) : "");
var data = await api("GET", qs);
state.users = data.users || [];
state.total = data.total || 0;
state.totalPages = data.totalPages || 1;
state.page = data.page || state.page;
} catch (e) {
state.err = (e && e.message) || String(e);
state.users = [];
}
state.busy = false;
paint();
}
function n(v) {
return v == null || v === "" ? 0 : Number(v) || 0;
}
function copyText(text) {
try {
navigator.clipboard.writeText(text || "");
state.msg = "已复制";
paint();
} catch (e) {
state.err = "复制失败";
paint();
}
}
function openModal(mode, user) {
state.modal = {
mode: mode,
user: Object.assign(
{
userid: "",
nick: "",
avatar: "",
signature: "",
gender_txt: "",
region: "",
follow_since: "",
remark: "",
matched_last_msg: "",
channel_id: "",
},
user || {}
),
};
paint();
}
function closeModal() {
state.modal = null;
paint();
}
async function saveModal() {
var m = state.modal;
if (!m) return;
var u = m.user || {};
try {
state.busy = true;
paint();
if (m.mode === "create") {
await api("POST", "", {
userid: u.userid,
nick: u.nick,
avatar: u.avatar,
signature: u.signature,
gender_txt: u.gender_txt,
region: u.region,
follow_since: u.follow_since,
remark: u.remark,
matched_last_msg: u.matched_last_msg,
channel_id: u.channel_id,
});
state.msg = "已创建/更新用户";
} else {
await api("PATCH", "/" + encodeURIComponent(u.id), {
userid: u.userid,
nick: u.nick,
avatar: u.avatar,
signature: u.signature,
gender_txt: u.gender_txt,
region: u.region,
follow_since: u.follow_since,
remark: u.remark,
matched_last_msg: u.matched_last_msg,
channel_id: u.channel_id,
});
state.msg = "已保存";
}
state.modal = null;
await load();
} catch (e) {
state.busy = false;
state.err = (e && e.message) || String(e);
paint();
}
}
async function removeUser(u, alsoOa) {
if (!u || !u.id) return;
var tip = alsoOa
? "确定删除该用户,并同时删除 oa_fans 档案?"
: "确定删除该用户(wechat_private_users)?";
if (!window.confirm(tip)) return;
try {
state.busy = true;
paint();
await api("DELETE", "/" + encodeURIComponent(u.id) + (alsoOa ? "?also_oa_fans=1" : ""));
state.msg = alsoOa ? "已删除用户 + OA档案" : "已删除用户";
delete state.selected[u.id];
await load();
} catch (e) {
state.busy = false;
state.err = (e && e.message) || String(e);
paint();
}
}
async function refreshUser(u) {
if (!u || !u.id) return;
try {
state.busy = true;
paint();
await api("POST", "/" + encodeURIComponent(u.id) + "/refresh", {});
state.msg = "已从 oa_fans 回填";
await load();
} catch (e) {
state.busy = false;
state.err = (e && e.message) || String(e);
paint();
}
}
async function batchDelete(alsoOa) {
var ids = Object.keys(state.selected).filter(function (k) {
return state.selected[k];
});
if (!ids.length) {
state.err = "请先勾选用户";
paint();
return;
}
if (!window.confirm("批量删除 " + ids.length + " 个用户" + (alsoOa ? "(含 oa_fans)" : "") + "?")) return;
state.busy = true;
paint();
var ok = 0;
var fail = 0;
for (var i = 0; i < ids.length; i++) {
try {
await api("DELETE", "/" + encodeURIComponent(ids[i]) + (alsoOa ? "?also_oa_fans=1" : ""));
ok += 1;
delete state.selected[ids[i]];
} catch (e) {
fail += 1;
}
}
state.msg = "批量删除完成:成功 " + ok + (fail ? ",失败 " + fail : "");
await load();
}
function field(label, key, opts) {
opts = opts || {};
var u = state.modal.user;
var isArea = !!opts.area;
var input = isArea
? el("textarea", {
value: u[key] || "",
oninput: function (ev) {
state.modal.user[key] = ev.target.value;
},
})
: el("input", {
type: opts.type || "text",
value: u[key] || "",
placeholder: opts.placeholder || "",
oninput: function (ev) {
state.modal.user[key] = ev.target.value;
},
});
return el("div", { class: opts.full ? "full" : "" }, [el("label", { text: label }), input]);
}
function renderModal() {
if (!state.modal) return null;
var m = state.modal;
var title = m.mode === "create" ? "新增用户" : "编辑用户";
var form = el("div", { class: "form-grid" }, [
field("微信 userid / openid", "userid", { full: true, placeholder: "oBVe71..." }),
field("昵称", "nick"),
field("性别", "gender_txt", { placeholder: "男/女" }),
field("头像 URL", "avatar", { full: true }),
field("签名", "signature", { full: true, area: true }),
field("地区", "region"),
field("关注时间", "follow_since", { placeholder: "2026/11/20 开始关注" }),
field("备注", "remark", { full: true }),
field("最近消息", "matched_last_msg", { full: true }),
field("channel_id", "channel_id"),
]);
if (m.mode === "edit") {
// userid 可改但通常保持
}
return el("div", { class: "modal-mask", onclick: function (ev) {
if (ev.target.classList && ev.target.classList.contains("modal-mask")) closeModal();
} }, [
el("div", { class: "modal" }, [
el("h2", { text: title }),
form,
el("div", { class: "modal-actions" }, [
el("button", { class: "ghost", text: "取消", onclick: closeModal }),
el("button", {
class: "primary",
text: state.busy ? "保存中…" : "保存",
onclick: function () {
saveModal();
},
}),
]),
]),
]);
}
function paint() {
ensureStyle();
var root = mountRoot();
var on = isOn();
root.setAttribute("data-on", on ? "1" : "0");
syncShell(on);
if (!on) {
root.innerHTML = "";
return;
}
root.innerHTML = "";
var wrap = el("div", { class: "wrap" });
wrap.appendChild(
el("p", {
class: "sub",
text: "微信私信用户档案(wechat_private_users + oa_fans)",
})
);
var bar = el("div", { class: "bar" });
var input = el("input", {
type: "search",
placeholder: "搜昵称 / userid",
value: state.q,
oninput: function (ev) {
state.q = ev.target.value || "";
},
onkeydown: function (ev) {
if (ev.key === "Enter") {
state.page = 1;
load();
}
},
});
bar.appendChild(input);
bar.appendChild(
el("button", {
class: "sky",
text: state.busy ? "加载中…" : "查询",
onclick: function () {
state.page = 1;
load();
},
})
);
bar.appendChild(
el("button", {
class: "primary",
text: "新增",
onclick: function () {
openModal("create", {});
},
})
);
bar.appendChild(
el("button", {
class: "danger",
text: "批量删除",
onclick: function () {
batchDelete(false);
},
})
);
bar.appendChild(
el("button", {
class: "danger",
text: "批量删(含OA)",
onclick: function () {
batchDelete(true);
},
})
);
wrap.appendChild(bar);
wrap.appendChild(
el("div", {
class: "meta",
text:
"共 " +
state.total +
" 人 · 第 " +
state.page +
"/" +
state.totalPages +
" 页 · 每页 " +
state.perPage,
})
);
if (state.err) wrap.appendChild(el("div", { class: "err", text: state.err }));
if (state.msg) wrap.appendChild(el("div", { class: "ok", text: state.msg }));
var tableWrap = el("div", { class: "table-wrap" });
var table = el("table");
table.appendChild(
el("thead", {}, [
el("tr", {}, [
el("th", { text: "" }),
el("th", { text: "头像" }),
el("th", { text: "昵称 / 签名" }),
el("th", { text: "userid" }),
el("th", { text: "档案" }),
el("th", { text: "互动" }),
el("th", { text: "更新" }),
el("th", { text: "操作" }),
]),
])
);
var tbody = el("tbody");
if (!state.users.length && !state.busy) {
tbody.appendChild(
el("tr", {}, [el("td", { text: "暂无数据", style: { color: "#94A3B8" } })])
);
}
state.users.forEach(function (u) {
var checked = !!state.selected[u.id];
var av =
u.avatar && String(u.avatar).indexOf("http") === 0
? el("img", { class: "av", src: u.avatar, alt: "" })
: el("div", { class: "av ph", text: "?" });
var nickCell = el("div", {}, [
el("div", { class: "nick", text: u.nick || "(无昵称)" }),
u.gender_txt ? el("span", { class: "chip", text: u.gender_txt }) : null,
u.has_oa_fans ? el("span", { class: "chip", text: "OA" }) : null,
u.signature ? el("div", { class: "sig", text: u.signature }) : null,
]);
var profile = [
u.region || "",
u.follow_since || "",
u.remark ? "备注:" + u.remark : "",
]
.filter(Boolean)
.join(" · ");
var stats =
"赞" +
n(u.like_cnt) +
" / 在看" +
n(u.look_cnt) +
" / 留言" +
n(u.comment_cnt) +
" / 赞赏" +
(u.reward_amt || "¥0");
var ops = el("div", { class: "ops" }, [
el("button", {
class: "ghost",
text: "编辑",
onclick: function () {
openModal("edit", u);
},
}),
el("button", {
class: "sky",
text: "回填OA",
onclick: function () {
refreshUser(u);
},
}),
el("button", {
class: "ghost",
text: "复制",
onclick: function () {
copyText(
[u.nick, u.userid, u.signature, u.h5].filter(Boolean).join("\n")
);
},
}),
el("button", {
class: "ghost",
text: "打开VIP",
onclick: function () {
if (u.h5) window.open(u.h5, "_blank");
},
}),
el("button", {
class: "danger",
text: "删除",
onclick: function () {
removeUser(u, false);
},
}),
el("button", {
class: "danger",
text: "删含OA",
onclick: function () {
removeUser(u, true);
},
}),
]);
tbody.appendChild(
el("tr", {}, [
el("td", {}, [
el("input", {
type: "checkbox",
checked: checked,
onchange: function (ev) {
if (ev.target.checked) state.selected[u.id] = true;
else delete state.selected[u.id];
},
}),
]),
el("td", {}, [av]),
el("td", {}, [nickCell]),
el("td", {}, [el("div", { class: "mono", text: u.userid || "-" })]),
el("td", { text: profile || "-" }),
el("td", { text: stats }),
el("td", { text: (u.updated || u.created || "-").slice(0, 19) }),
el("td", {}, [ops]),
])
);
});
table.appendChild(tbody);
tableWrap.appendChild(table);
wrap.appendChild(tableWrap);
var pager = el("div", { class: "pager" });
pager.appendChild(
el("button", {
class: "ghost",
text: "上一页",
onclick: function () {
if (state.page > 1) {
state.page -= 1;
load();
}
},
})
);
pager.appendChild(
el("button", {
class: "ghost",
text: "下一页",
onclick: function () {
if (state.page < state.totalPages) {
state.page += 1;
load();
}
},
})
);
var sel = el("select", {
onchange: function (ev) {
state.perPage = Number(ev.target.value) || 50;
state.page = 1;
load();
},
});
[20, 50, 100, 200].forEach(function (n) {
var opt = el("option", { value: String(n), text: String(n) + " / 页" });
if (n === state.perPage) opt.selected = true;
sel.appendChild(opt);
});
pager.appendChild(sel);
wrap.appendChild(pager);
var modal = renderModal();
if (modal) wrap.appendChild(modal);
root.appendChild(wrap);
}
function injectNav() {
var existing = document.querySelector("a.admin-users-nav");
if (existing) return true;
var nav = document.querySelector(".com-side-nav");
var leads =
document.querySelector('.com-side-nav a[href="/leads"]') ||
document.querySelector('.com-side-nav a[href*="/leads"]');
if (!nav || !leads || !leads.parentElement) return false;
var a = document.createElement("a");
a.href = PATH;
a.className = "com-nav-link com-nav-link-rich admin-users-nav";
a.innerHTML =
'<span class="com-nav-ico" aria-hidden="true">👥</span>' +
'<span class="com-nav-label">用户列表</span>' +
'<span class="com-nav-emoji" aria-hidden="true">📋</span>';
a.addEventListener(
"click",
function (ev) {
ev.preventDefault();
ev.stopPropagation();
openPage();
},
true
);
// 插在「加入线索」后面,同一经营分组
if (leads.nextSibling) leads.parentElement.insertBefore(a, leads.nextSibling);
else leads.parentElement.appendChild(a);
return true;
}
function onSpaNavigate() {
// 用户点了侧栏其它 React Router 链接:离开用户列表
if (!isOn()) {
paint();
return;
}
render(true);
scrollMainIntoView();
if (!state.users.length) load();
}
function boot() {
ensureStyle();
injectNav();
mountRoot();
if (isOn()) {
render(true);
scrollMainIntoView();
load();
} else {
paint();
}
}
function render(forceLoad) {
paint();
if (forceLoad && isOn() && !state.busy && !state.users.length) load();
}
window.addEventListener("popstate", function () {
onSpaNavigate();
});
// 侧栏其它菜单用 React Router,监听 DOM/路径变化自动收起本页
var lastPath = location.pathname;
setInterval(function () {
injectNav();
if (location.pathname !== lastPath) {
lastPath = location.pathname;
onSpaNavigate();
}
}, 300);
// 点击侧栏其它链接时,先清掉我们的 active 态(RR 会改 URL)
document.addEventListener(
"click",
function (ev) {
var a = ev.target && ev.target.closest ? ev.target.closest(".com-side-nav a.com-nav-link") : null;
if (!a || a.classList.contains("admin-users-nav")) return;
// 留给 RR 跳转;短延迟后按新路径同步
setTimeout(onSpaNavigate, 0);
setTimeout(onSpaNavigate, 50);
},
true
);
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();

View File

@ -0,0 +1,191 @@
/*! vip-live.js — presence heartbeat + admin broadcast popup for vip.hackrobot.cn */
(function () {
"use strict";
if (window.__vipLiveBooted) return;
window.__vipLiveBooted = true;
var API_PRESENCE = "/api/vip/live/presence";
var API_STREAM = "/api/vip/live/stream";
var HEARTBEAT_MS = 20000;
var SEEN_KEY = "vip_live_seen_bc";
function lsGet(k) {
try {
return localStorage.getItem(k) || "";
} catch (e) {
return "";
}
}
function lsSet(k, v) {
try {
localStorage.setItem(k, v);
} catch (e) {}
}
function cookie(name) {
var m = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
return m ? decodeURIComponent(m[1]) : "";
}
function visitorId() {
var anon = cookie("nomadvip_anon_uid") || lsGet("userid") || lsGet("wechatUserId") || "";
if (anon) return String(anon).slice(0, 80);
var vid = lsGet("vip_live_vid");
if (!vid) {
vid = "web_" + Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
lsSet("vip_live_vid", vid);
}
return vid;
}
function identity() {
var email = (lsGet("email") || lsGet("vipEmail") || "").trim().toLowerCase();
var name = (lsGet("name") || lsGet("nickname") || "").trim();
var role = (lsGet("role") || "").trim() || (lsGet("isVip") === "1" ? "vip" : "guest");
var openid = (lsGet("wechatUserId") || lsGet("userid") || "").trim();
return { email: email, nick: name, role: role, openid: openid };
}
function ping() {
var id = identity();
var body = {
visitorId: visitorId(),
openid: id.openid,
nick: id.nick,
email: id.email,
page: (location.pathname || "/") + (location.search || ""),
role: id.role,
};
try {
fetch(API_PRESENCE, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
credentials: "omit",
keepalive: true,
}).catch(function () {});
} catch (e) {}
}
function ensureStyles() {
if (document.getElementById("vip-live-style")) return;
var s = document.createElement("style");
s.id = "vip-live-style";
s.textContent =
"@keyframes vipLiveIn{from{opacity:0;transform:translateY(18px) scale(.96);filter:blur(6px)}to{opacity:1;transform:none;filter:none}}" +
"@keyframes vipLiveGlow{0%,100%{box-shadow:0 0 0 1px rgba(245,158,11,.35),0 24px 60px rgba(0,0,0,.45)}50%{box-shadow:0 0 0 1px rgba(245,158,11,.7),0 28px 70px rgba(245,158,11,.18)}}" +
"#vip-live-mask{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:flex-end;justify-content:center;padding:20px;background:rgba(8,8,10,.55);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}" +
"@media(min-width:720px){#vip-live-mask{align-items:center}}" +
"#vip-live-card{width:min(420px,100%);border-radius:18px;padding:22px 22px 18px;background:linear-gradient(165deg,#141418 0%,#0c0c0f 55%,#1a1408 100%);color:#f5f5f4;border:1px solid rgba(245,158,11,.35);animation:vipLiveIn .45s cubic-bezier(.2,.8,.2,1),vipLiveGlow 3.2s ease-in-out infinite;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,PingFang SC,Microsoft YaHei,sans-serif}" +
"#vip-live-card[data-tone=mint]{border-color:rgba(94,196,120,.45);background:linear-gradient(165deg,#121816,#0c0f0d 60%,#0f1a14)}" +
"#vip-live-card[data-tone=rose]{border-color:rgba(244,114,182,.4);background:linear-gradient(165deg,#181218,#0f0c0e 60%,#1a1014)}" +
"#vip-live-kicker{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:rgba(245,158,11,.9);margin:0 0 8px;font-weight:700}" +
"#vip-live-title{margin:0;font-size:22px;line-height:1.25;letter-spacing:-.02em;font-weight:750}" +
"#vip-live-body{margin:10px 0 0;font-size:14px;line-height:1.65;color:rgba(245,245,244,.78)}" +
"#vip-live-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:18px}" +
"#vip-live-actions button{min-height:44px;padding:0 16px;border-radius:12px;border:1px solid rgba(255,255,255,.12);background:#f59e0b;color:#111;font-weight:700;font-size:14px;cursor:pointer}" +
"#vip-live-actions button.ghost{background:transparent;color:#f5f5f4}";
document.head.appendChild(s);
}
function seenIds() {
try {
return JSON.parse(lsGet(SEEN_KEY) || "[]");
} catch (e) {
return [];
}
}
function markSeen(id) {
var arr = seenIds().filter(Boolean);
if (arr.indexOf(id) >= 0) return;
arr.unshift(id);
lsSet(SEEN_KEY, JSON.stringify(arr.slice(0, 30)));
}
function closePopup() {
var m = document.getElementById("vip-live-mask");
if (m) m.remove();
}
function showBroadcast(msg) {
if (!msg || !msg.id || !msg.title) return;
if (seenIds().indexOf(msg.id) >= 0) return;
ensureStyles();
closePopup();
markSeen(msg.id);
var mask = document.createElement("div");
mask.id = "vip-live-mask";
mask.setAttribute("role", "dialog");
mask.setAttribute("aria-modal", "true");
var card = document.createElement("div");
card.id = "vip-live-card";
card.setAttribute("data-tone", msg.tone || "amber");
card.innerHTML =
'<p id="vip-live-kicker">运营通知</p>' +
"<h2 id=\"vip-live-title\"></h2>" +
'<p id="vip-live-body"></p>' +
'<div id="vip-live-actions"></div>';
card.querySelector("#vip-live-title").textContent = String(msg.title || "");
var body = card.querySelector("#vip-live-body");
if (msg.body) body.textContent = String(msg.body);
else body.remove();
var actions = card.querySelector("#vip-live-actions");
var primary = document.createElement("button");
primary.type = "button";
primary.textContent = String(msg.cta || "知道了");
primary.onclick = function () {
if (msg.href) {
try {
window.open(String(msg.href), "_blank", "noopener");
} catch (e) {
location.href = String(msg.href);
}
}
closePopup();
};
actions.appendChild(primary);
if (msg.href) {
var ghost = document.createElement("button");
ghost.type = "button";
ghost.className = "ghost";
ghost.textContent = "稍后";
ghost.onclick = closePopup;
actions.appendChild(ghost);
}
mask.appendChild(card);
mask.addEventListener("click", function (e) {
if (e.target === mask) closePopup();
});
document.body.appendChild(mask);
var ttl = Math.max(8, Number(msg.ttlSec) || 60) * 1000;
window.setTimeout(closePopup, ttl);
}
function connectStream() {
if (!window.EventSource) return;
var es;
try {
es = new EventSource(API_STREAM);
} catch (e) {
return;
}
es.addEventListener("broadcast", function (ev) {
try {
showBroadcast(JSON.parse(ev.data));
} catch (e) {}
});
es.onerror = function () {
/* browser auto-reconnects */
};
}
ping();
window.setInterval(ping, HEARTBEAT_MS);
document.addEventListener("visibilitychange", function () {
if (document.visibilityState === "visible") ping();
});
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", connectStream);
} else {
connectStream();
}
})();

View File

@ -0,0 +1,31 @@
# vip.hackrobot.cn 旁路埋点 / 监控 / ntfy
部署机:`129.204.21.129` · 目录 `/opt/vip-track` · 进程 `pm2 vip-track`(**不**重启业务 `vip`)。
## 能力
| 层 | 说明 |
|---|---|
| 前端 | `/vip-track.js` nginx 注入;page_view / CTA / 登录 / 支付回跳 / SPA / 错误 / web vital / heartbeat |
| API | `POST /api/track` → sidecar `:4011`;事件写入 `/opt/vip-track/events.db`(独立 SQLite,不碰 VIP/PB) |
| ntfy | 高价值事件推 `https://ntfy.nomadro.cn/vip-hackrobot`(匿名可写;`hackrobot` 管理员可读) |
| 健康 | cron `/etc/cron.d/vip-track-health` 每 3 分钟;down/up 边沿推 ntfy |
## 订阅
ntfy App 登录 `hackrobot`,订阅 topic:`vip-hackrobot`。
## 安全部署
```bash
python apps/admin/deploy/_push_vip_track_v2.py
```
仅更新 track 文件 + `pm2 restart vip-track` + nginx reload;冒烟要求 `vip` restart 计数不变。
## 本机统计
```bash
curl -s http://127.0.0.1:4011/stats
curl -s http://127.0.0.1:4011/health
```

View File

@ -0,0 +1,105 @@
#!/bin/bash
# vip.hackrobot.cn health → ntfy on edge (down/up). Does not touch VIP process.
# Anti-flap: require N consecutive fails/oks; never append echo after curl -w.
STATE_FILE=/opt/vip-track/health.state
STREAK_FILE=/opt/vip-track/health.streak
NTFY_ENV=/opt/vip-track/ntfy.env
URL_HOME=https://vip.hackrobot.cn/
URL_TRACK=http://127.0.0.1:4011/health
# 不探公网 /vip-track.js(易被 SSL/CDN 抖成 000);只看本地文件是否在
JS_FILE=/opt/vip-track/vip-track.js
NEED_DOWN=2
NEED_UP=2
if [ -f "$NTFY_ENV" ]; then
# shellcheck disable=SC1090
set -a
. "$NTFY_ENV"
set +a
fi
NTFY_BASE=${NTFY_BASE_URL:-https://ntfy.nomadro.cn}
NTFY_TOPIC=${NTFY_TOPIC:-vip-hackrobot}
NTFY_TOKEN=${NTFY_TOKEN:-}
http_code() {
# Only %{http_code}; on total failure curl still prints 000 and exits non-zero — do NOT echo again.
code=$(curl -sk -o /dev/null -w '%{http_code}' --connect-timeout 5 --max-time 12 "$1" 2>/dev/null || true)
case "$code" in
[1-5][0-9][0-9]) printf '%s' "$code" ;;
*) printf '000' ;;
esac
}
notify() {
title="$1"
msg="$2"
tags="$3"
pri="$4"
ev="$5"
ascii_title=$(printf '%s' "$title" | tr -cd 'A-Za-z0-9 _\[\]VIPWeb.-' | cut -c1-60)
[ -n "$ascii_title" ] || ascii_title="WebVIP"
hdr=(-H "Title: $ascii_title" -H "Tags: $tags" -H "Priority: $pri")
if [ -n "$NTFY_TOKEN" ]; then
hdr+=(-H "Authorization: Bearer $NTFY_TOKEN")
fi
curl -sS -o /dev/null --max-time 5 "${hdr[@]}" -d "${title}: ${msg}" "${NTFY_BASE}/${NTFY_TOPIC}" || true
curl -sS -o /dev/null --max-time 3 -X POST http://127.0.0.1:4011/ \
-H 'content-type: application/json' \
-d "{\"events\":[{\"name\":\"${ev}\",\"page\":\"/\",\"label\":\"health\"}],\"client\":\"healthcheck\"}" || true
}
code_home=$(http_code "$URL_HOME")
code_track=$(http_code "$URL_TRACK")
if [ -f "$JS_FILE" ] && [ -s "$JS_FILE" ]; then
code_js=file_ok
else
code_js=missing
fi
# Primary = homepage. Sidecar/track secondary; js 只看本地文件,避免公网误报。
ok=1
if [ "$code_home" != "200" ]; then
ok=0
elif [ "$code_track" != "200" ] && [ "$code_js" != "file_ok" ]; then
ok=0
fi
prev=$(cat "$STATE_FILE" 2>/dev/null || echo up)
# streak format: kind count e.g. fail 2 / ok 1
read -r streak_kind streak_n <"$STREAK_FILE" 2>/dev/null || true
streak_kind=${streak_kind:-ok}
streak_n=${streak_n:-0}
if [ "$ok" = 1 ]; then
if [ "$streak_kind" = "ok" ]; then
streak_n=$((streak_n + 1))
else
streak_kind=ok
streak_n=1
fi
else
if [ "$streak_kind" = "fail" ]; then
streak_n=$((streak_n + 1))
else
streak_kind=fail
streak_n=1
fi
fi
echo "$streak_kind $streak_n" >"$STREAK_FILE"
now=$prev
if [ "$prev" != "down" ] && [ "$streak_kind" = "fail" ] && [ "$streak_n" -ge "$NEED_DOWN" ]; then
now=down
elif [ "$prev" = "down" ] && [ "$streak_kind" = "ok" ] && [ "$streak_n" -ge "$NEED_UP" ]; then
now=up
fi
echo "$now" >"$STATE_FILE"
detail="home=$code_home js=$code_js track=$code_track streak=${streak_kind}:${streak_n} · vip.hackrobot.cn"
if [ "$now" = "down" ] && [ "$prev" != "down" ]; then
notify "[WebVIP] 站点异常" "$detail" "rotating_light,skull" "5" "health_down"
elif [ "$now" = "up" ] && [ "$prev" = "down" ]; then
notify "[WebVIP] 站点恢复" "$detail" "white_check_mark,tada" "3" "health_up"
fi
exit 0

View File

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
from pathlib import Path
import re
p = Path("/www/server/panel/vhost/nginx/proxy/vip.hackrobot.cn/886f743b90957775e40b8bbb4aa07c67_vip.hackrobot.cn.conf")
t = p.read_text(encoding="utf-8")
if "vip-track.js" in t:
print("inject already present")
raise SystemExit(0)
m = re.search(r"location \^~ /\s*\{", t)
if not m:
raise SystemExit("proxy location not found")
insert = """
proxy_set_header Accept-Encoding "";
sub_filter_types text/html;
sub_filter '</body>' '<script src="/vip-track.js" defer></script></body>';
sub_filter_once on;
"""
t2 = t[: m.end()] + insert + t[m.end() :]
p.write_text(t2, encoding="utf-8")
print("proxy inject ok")

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,66 @@
#!/bin/bash
set -euo pipefail
echo "=== localhost publish ==="
code=$(curl -sS -o /tmp/ntfy_local.txt -w '%{http_code}' -H 'Title: local-test' -d 'vip setup probe' http://127.0.0.1:2586/nomadro || true)
echo "local_nomadro $code"
head -c 120 /tmp/ntfy_local.txt; echo
which ntfy || true
docker ps --format '{{.Names}} {{.Image}}' 2>/dev/null | grep -i ntfy || true
NTFY_BIN=$(command -v ntfy || true)
if [ -z "$NTFY_BIN" ]; then
if docker ps --format '{{.Names}}' 2>/dev/null | grep -qx ntfy; then
NTFY_BIN="docker exec ntfy ntfy"
fi
fi
echo "NTFY_BIN=$NTFY_BIN"
if [ -n "$NTFY_BIN" ]; then
$NTFY_BIN user list 2>/dev/null || true
# write-only public topic for VIP web publisher (read still denied by default)
$NTFY_BIN access everyone vip-hackrobot write-only 2>/dev/null \
|| $NTFY_BIN access everyone vip-hackrobot wo 2>/dev/null \
|| true
$NTFY_BIN access list 2>/dev/null || true
fi
echo "=== auth.db peek ==="
python3 - <<'PY'
import os, sqlite3
auth = "/var/lib/ntfy/auth.db"
print("auth exists", os.path.exists(auth))
if not os.path.exists(auth):
raise SystemExit(0)
con = sqlite3.connect(auth)
try:
tables = [r[0] for r in con.execute("select name from sqlite_master where type='table'")]
print("tables", tables)
for t in tables:
try:
rows = con.execute(f"select * from {t} limit 8").fetchall()
print(t, rows)
except Exception as e:
print("skip", t, e)
finally:
con.close()
PY
echo "=== https publish vip-hackrobot ==="
curl -sS -o /tmp/ntfy_pub.txt -w "pub %{http_code}\n" -H "Title: vip-acl-test" -d "from setup script" https://ntfy.nomadro.cn/vip-hackrobot || true
head -c 200 /tmp/ntfy_pub.txt; echo
curl -sS -o /tmp/ntfy_pub2.txt -w "local_vip %{http_code}\n" -H "Title: vip-acl-local" -d "local" http://127.0.0.1:2586/vip-hackrobot || true
head -c 200 /tmp/ntfy_pub2.txt; echo
# Try create user+token non-interactively if possible
if [ -n "$NTFY_BIN" ]; then
echo "=== try token ==="
# password via env for user add (ntfy may prompt; ignore failure)
printf 'VipTrack#2026\nVipTrack#2026\n' | $NTFY_BIN user add vip-publisher 2>/tmp/ntfy_user_err.txt || true
cat /tmp/ntfy_user_err.txt 2>/dev/null || true
$NTFY_BIN token add vip-publisher 2>/tmp/ntfy_tok.txt || true
cat /tmp/ntfy_tok.txt 2>/dev/null || true
$NTFY_BIN access vip-publisher nomadro read-write 2>/dev/null || true
$NTFY_BIN access vip-publisher vip-hackrobot read-write 2>/dev/null || true
fi
echo DONE

View File

@ -0,0 +1,22 @@
# VIP track sidecar — isolate from Next (no vip restart)
location = /api/track {
proxy_pass http://127.0.0.1:4011;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 2s;
proxy_read_timeout 5s;
}
# 微信用户列表 CRUD(需 ops token)
location ^~ /api/wechat-users {
proxy_pass http://127.0.0.1:4011;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Authorization $http_authorization;
proxy_connect_timeout 3s;
proxy_read_timeout 20s;
}

View File

@ -0,0 +1,402 @@
(function () {
try {
if (window.__vipTrackInstalled) return;
window.__vipTrackInstalled = true;
var q = [];
var flushing = false;
var flushTimer = null;
var lastPage = { k: "", t: 0 };
var sessionId = "";
var startedAt = Date.now();
function ls(key) {
try {
return (localStorage.getItem(key) || "").trim();
} catch (e) {
return "";
}
}
function ss(key, val) {
try {
if (val != null && String(val).trim()) {
localStorage.setItem(key, String(val).trim());
}
} catch (e) {}
}
// 关键:在任何 track 之前同步落盘 URL 上的微信 userid。
// HomeClient 水合后才会写 localStorage,且会 location.replace 清掉参数;
// 若此处不抢先,首屏 page_view/session_start 的 ntfy 会全是「-」。
try {
var bootSp = new URLSearchParams(location.search || "");
var bootUid = (
bootSp.get("userid") ||
bootSp.get("wechat_userid") ||
bootSp.get("openid") ||
""
).trim();
if (bootUid) {
ss("userid", bootUid);
ss("wechatUserId", bootUid);
}
var bootNick = (bootSp.get("nick") || bootSp.get("nickname") || "").trim();
if (bootNick) ss("wechatNick", bootNick);
var bootAv = (bootSp.get("avatar") || "").trim();
if (bootAv) ss("wechatAvatar", bootAv);
} catch (e) {}
function page() {
try {
return (location.pathname || "/").slice(0, 64);
} catch (e) {
return "/";
}
}
function hrefFull() {
try {
return String(location.href || "").slice(0, 180);
} catch (e) {
return "";
}
}
function identity() {
var userId = ls("userId");
var email = ls("userEmail");
var name = ls("userName");
var memos = ls("memosAccount");
var paid = ls("paidType");
var wechatUserId = ls("wechatUserId") || ls("userid");
var wechatNick = ls("wechatNick");
var wechatAvatar = ls("wechatAvatar");
var account = email || (name && name.indexOf("@") >= 0 ? name : "") || memos || "";
var display =
wechatNick || name || email || memos || wechatUserId || userId || "";
var isVip = paid === "vip";
return {
user_id: userId.slice(0, 64),
email: account.slice(0, 80),
name: display.slice(0, 80),
wechat_userid: wechatUserId.slice(0, 64),
wechat_nick: wechatNick.slice(0, 80),
wechat_avatar: wechatAvatar.slice(0, 300),
avatar: wechatAvatar.slice(0, 300),
paid_type: paid || "guest",
role: isVip ? "vip" : "guest",
role_cn: isVip ? "会员VIP" : "普通访客",
};
}
function deviceInfo() {
var ua = "";
try {
ua = navigator.userAgent || "";
} catch (e) {}
var device = "desktop";
if (/MicroMessenger/i.test(ua)) device = "wechat";
else if (/Mobile|Android|iPhone|iPad/i.test(ua)) device = "mobile";
var browser = "other";
if (/Edg\//i.test(ua)) browser = "edge";
else if (/Chrome\//i.test(ua)) browser = "chrome";
else if (/Safari\//i.test(ua) && !/Chrome/i.test(ua)) browser = "safari";
else if (/Firefox\//i.test(ua)) browser = "firefox";
return {
device: device,
browser: browser,
ua: ua.slice(0, 140),
lang: (navigator.language || "").slice(0, 16),
screen: (screen.width || 0) + "x" + (screen.height || 0),
tz: (function () {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || "";
} catch (e) {
return "";
}
})(),
online: navigator.onLine ? 1 : 0,
};
}
function sid() {
if (sessionId) return sessionId;
try {
sessionId = sessionStorage.getItem("__vip_sid") || "";
if (!sessionId) {
sessionId =
"s" +
Date.now().toString(36) +
Math.random().toString(36).slice(2, 8);
sessionStorage.setItem("__vip_sid", sessionId);
}
} catch (e) {
sessionId = "s" + Date.now().toString(36);
}
return sessionId;
}
function scheduleFlush(immediate) {
if (immediate) {
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
flush();
return;
}
if (flushTimer) return;
flushTimer = setTimeout(function () {
flushTimer = null;
flush();
}, 600);
}
function flush() {
if (flushing || !q.length) return;
flushing = true;
var batch = q.splice(0, 20);
var id = identity();
try {
fetch("/api/track", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
events: batch,
openid: id.wechat_userid || id.user_id || id.email || undefined,
client: "vip_web",
session: sid(),
identity: id,
}),
keepalive: true,
cache: "no-store",
}).catch(function () {});
} catch (e) {}
flushing = false;
if (q.length) scheduleFlush(false);
}
function baseProps(extra) {
var id = identity();
var d = deviceInfo();
return Object.assign(
{
channel: "vip_web",
sid: sid(),
role: id.role,
role_cn: id.role_cn,
paid_type: id.paid_type,
email: id.email,
name: id.name,
user_id: id.user_id,
wechat_userid: id.wechat_userid,
wechat_nick: id.wechat_nick,
wechat_avatar: id.wechat_avatar,
avatar: id.avatar,
device: d.device,
browser: d.browser,
ua: d.ua,
lang: d.lang,
screen: d.screen,
tz: d.tz,
online: d.online,
href: hrefFull(),
ref: (document.referrer || "").slice(0, 160),
title: (document.title || "").slice(0, 80),
alive_ms: Date.now() - startedAt,
},
extra || {}
);
}
function track(name, opts) {
try {
opts = opts || {};
q.push({
name: String(name || "").slice(0, 64),
page: String(opts.page || page()).slice(0, 64),
label: opts.label ? String(opts.label).slice(0, 160) : undefined,
props: baseProps(opts.props || {}),
ts: Date.now() / 1000,
});
if (opts.immediate || q.length >= 5) scheduleFlush(true);
else scheduleFlush(false);
} catch (e) {}
}
window.__vipTrack = track;
try {
var pathNow = page();
var pk = pathNow + "|view";
var now = Date.now();
if (!(lastPage.k === pk && now - lastPage.t < 2000)) {
lastPage = { k: pk, t: now };
track("page_view", {
page: pathNow,
label: pathNow === "/" ? "异度星球首页" : pathNow,
immediate: true,
});
}
track("session_start", {
label: identity().role_cn,
immediate: true,
});
} catch (e) {}
try {
var sp = new URLSearchParams(location.search || "");
if (pathNow === "/paid" || sp.get("paid") === "1") {
track("pay_success", { label: "支付回跳", page: page(), immediate: true });
}
} catch (e) {}
function labelOf(el) {
if (!el) return "";
var t =
(el.getAttribute &&
(el.getAttribute("aria-label") ||
el.getAttribute("title") ||
el.getAttribute("data-track"))) ||
"";
if (!t) t = (el.innerText || el.textContent || "").replace(/\s+/g, " ").trim();
return String(t).slice(0, 120);
}
document.addEventListener(
"click",
function (ev) {
try {
var el = ev.target;
if (!el || !el.closest) return;
var btn = el.closest(
"button,a,[role=button],.pay-btn,[data-track],input[type=submit]"
);
if (!btn) return;
var txt = labelOf(btn);
var href = (btn.getAttribute && btn.getAttribute("href")) || "";
var dataTrack = btn.getAttribute && btn.getAttribute("data-track");
var tag = (btn.tagName || "").toLowerCase();
var props = {
el: tag,
href: String(href).slice(0, 120),
text: txt,
};
if (dataTrack) {
track("btn_click", {
label: dataTrack + (txt ? "·" + txt : ""),
props: props,
immediate: true,
});
return;
}
if (!txt && !href) return;
if (/立即加入|加入星球|开通|支付|报名|购买|续费/.test(txt)) {
track("pay_start", {
label: "cta:" + (txt || href).slice(0, 80),
props: props,
immediate: true,
});
} else if (/登录|已有账号|验证码|邮箱登录/.test(txt)) {
track("btn_click", {
label: "登录入口:" + txt.slice(0, 60),
props: props,
immediate: true,
});
} else if (/退出|登出/.test(txt)) {
track("btn_click", { label: "退出登录", props: props, immediate: true });
} else if (/复制|网盘|资料|下载/.test(txt)) {
track("btn_click", {
label: "资料:" + txt.slice(0, 60),
props: props,
immediate: true,
});
} else {
track("btn_click", {
label: (txt || href || tag).slice(0, 100),
props: props,
immediate: true,
});
}
} catch (e) {}
},
true
);
document.addEventListener(
"submit",
function (ev) {
try {
var form = ev.target;
if (!form || !form.tagName || form.tagName.toLowerCase() !== "form") return;
var html = (form.innerHTML || "").slice(0, 400);
var id = identity();
if (/password|邮箱|账号|登录|验证码/i.test(html)) {
track("login_submit", {
label: "登录表单提交",
props: { email_hint: (id.email || "").slice(0, 40) },
immediate: true,
});
} else {
track("form_submit", {
label: (form.id || form.className || "form").slice(0, 40),
immediate: true,
});
}
} catch (e) {}
},
true
);
try {
var lastPath = page();
function onRoute() {
try {
var p = page();
if (p === lastPath) return;
lastPath = p;
track("page_view", {
page: p,
label: p === "/" ? "异度星球首页" : p,
props: { spa: 1 },
immediate: true,
});
} catch (e) {}
}
var _ps = history.pushState;
var _rs = history.replaceState;
history.pushState = function () {
var r = _ps.apply(this, arguments);
setTimeout(onRoute, 0);
return r;
};
history.replaceState = function () {
var r = _rs.apply(this, arguments);
setTimeout(onRoute, 0);
return r;
};
window.addEventListener("popstate", onRoute);
} catch (e) {}
try {
document.addEventListener("visibilitychange", function () {
track("visibility", {
label: document.visibilityState,
props: { alive_ms: Date.now() - startedAt },
});
});
setInterval(function () {
if (document.visibilityState !== "visible") return;
track("heartbeat", {
props: { alive_ms: Date.now() - startedAt, path: page() },
});
}, 60000);
} catch (e) {}
try {
window.addEventListener("error", function (ev) {
try {
track("error", {
label: String((ev && ev.message) || "error").slice(0, 120),
props: {
src: ((ev && ev.filename) || "").slice(0, 100),
line: (ev && ev.lineno) || 0,
col: (ev && ev.colno) || 0,
},
});
} catch (e2) {}
});
} catch (e) {}
} catch (e) {}
})();

View File

@ -0,0 +1,7 @@
Reload service nginx... done
---
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=d

Some files were not shown because too many files have changed in this diff Show More