diff --git a/apps/admin/deploy/_fix_live_flv.py b/apps/admin/deploy/_fix_live_flv.py new file mode 100644 index 0000000..e016a90 --- /dev/null +++ b/apps/admin/deploy/_fix_live_flv.py @@ -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() diff --git a/apps/admin/deploy/_fix_live_nginx.py b/apps/admin/deploy/_fix_live_nginx.py new file mode 100644 index 0000000..e5d3b9e --- /dev/null +++ b/apps/admin/deploy/_fix_live_nginx.py @@ -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() diff --git a/apps/admin/deploy/_fix_live_nginx2.py b/apps/admin/deploy/_fix_live_nginx2.py new file mode 100644 index 0000000..739eb9f --- /dev/null +++ b/apps/admin/deploy/_fix_live_nginx2.py @@ -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() diff --git a/apps/admin/deploy/_fix_live_nginx3.py b/apps/admin/deploy/_fix_live_nginx3.py new file mode 100644 index 0000000..ab5776c --- /dev/null +++ b/apps/admin/deploy/_fix_live_nginx3.py @@ -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() diff --git a/apps/admin/deploy/_fix_live_nginx4.py b/apps/admin/deploy/_fix_live_nginx4.py new file mode 100644 index 0000000..f2f55cc --- /dev/null +++ b/apps/admin/deploy/_fix_live_nginx4.py @@ -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() diff --git a/apps/admin/deploy/_patch_live_nginx.py b/apps/admin/deploy/_patch_live_nginx.py new file mode 100644 index 0000000..9edde6b --- /dev/null +++ b/apps/admin/deploy/_patch_live_nginx.py @@ -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()) diff --git a/apps/admin/deploy/_proxy_rt_on_api.py b/apps/admin/deploy/_proxy_rt_on_api.py new file mode 100644 index 0000000..248916d --- /dev/null +++ b/apps/admin/deploy/_proxy_rt_on_api.py @@ -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()) diff --git a/apps/admin/deploy/_proxy_social_on_api.py b/apps/admin/deploy/_proxy_social_on_api.py new file mode 100644 index 0000000..af213a4 --- /dev/null +++ b/apps/admin/deploy/_proxy_social_on_api.py @@ -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()) diff --git a/apps/admin/deploy/_push_social_join_pay.py b/apps/admin/deploy/_push_social_join_pay.py new file mode 100644 index 0000000..7477dd7 --- /dev/null +++ b/apps/admin/deploy/_push_social_join_pay.py @@ -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()) diff --git a/apps/admin/deploy/_push_social_live_api.py b/apps/admin/deploy/_push_social_live_api.py new file mode 100644 index 0000000..a79ccaf --- /dev/null +++ b/apps/admin/deploy/_push_social_live_api.py @@ -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()) diff --git a/apps/admin/deploy/_push_social_live_py.py b/apps/admin/deploy/_push_social_live_py.py new file mode 100644 index 0000000..052902a --- /dev/null +++ b/apps/admin/deploy/_push_social_live_py.py @@ -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()) diff --git a/apps/admin/deploy/_smoke_rtmp_flv.py b/apps/admin/deploy/_smoke_rtmp_flv.py new file mode 100644 index 0000000..dc4c566 --- /dev/null +++ b/apps/admin/deploy/_smoke_rtmp_flv.py @@ -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() diff --git a/apps/admin/deploy/_verify_live_proxy.py b/apps/admin/deploy/_verify_live_proxy.py new file mode 100644 index 0000000..3e7a012 --- /dev/null +++ b/apps/admin/deploy/_verify_live_proxy.py @@ -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() diff --git a/apps/api/services/ebook_svc/routers/pay.py b/apps/api/services/ebook_svc/routers/pay.py index 7799b43..d306ea8 100644 --- a/apps/api/services/ebook_svc/routers/pay.py +++ b/apps/api/services/ebook_svc/routers/pay.py @@ -16,6 +16,7 @@ from ebook_svc.domains.books.products import PRODUCT_OFFERS from ebook_svc.schemas.pay import DevConfirmBody, OrderBody, StatusBody from ebook_svc.services.shop_store import shop_store from ebook_svc.services.store import store +from ebook_svc.services.social_join_config import SOCIAL_JOIN_BOOK_ID, read_social_join_config from ebook_svc.services.vip_config import read_vip_config from ebook_svc.services.wxpay import build_sign_data, calc_pay_sig, calc_signature, query_order @@ -24,6 +25,8 @@ router = APIRouter(prefix="/pay", tags=["pay"]) # VIP 订单在 unlocks / orders 里用的哨兵 book_id(不是真实小册) VIP_BOOK_ID = "__vip__" SHOP_BOOK_ID = "__shop__" +# 游民社区加群收费(与 VIP / community 付费体系隔离) +# SOCIAL_JOIN_BOOK_ID = "__social_join__" class ShopOrderBody(BaseModel): @@ -174,6 +177,106 @@ async def vip_status(openid: str = Depends(get_current_openid)): } +def _build_social_join_order_payload(openid: str) -> dict[str, Any]: + """游民社区加群虚拟支付 — 独立 book_id/type,不写 __vip__、不走 community。""" + cfg = read_social_join_config() + if not cfg.get("socialJoinEnabled"): + raise HTTPException(400, "加群支付暂未开放") + product_id = str(cfg.get("socialJoinProductId") or "").strip() + price_fen = int(cfg.get("socialJoinPriceFen") or 0) + if not product_id or price_fen <= 0: + raise HTTPException(400, "加群支付未配置道具,请联系运营") + if store.is_unlocked(openid, SOCIAL_JOIN_BOOK_ID): + raise HTTPException(400, "已加入游民社区,无需重复支付") + + user = store.get_user(openid) + if not user or not user.get("session_key"): + raise HTTPException(401, "session_key 缺失,请重新登录") + + attach = json.dumps( + { + "type": "social_join", + "book_id": SOCIAL_JOIN_BOOK_ID, + "openid": openid, + }, + ensure_ascii=False, + separators=(",", ":"), + ) + out_trade_no = store.create_order( + openid=openid, + book_id=SOCIAL_JOIN_BOOK_ID, + product_id=product_id, + amount_fen=price_fen, + attach=attach, + ) + sign_data = build_sign_data( + offer_id=settings.wx_offer_id, + product_id=product_id, + goods_price=price_fen, + out_trade_no=out_trade_no, + attach=attach, + ) + pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key) + signature = calc_signature(sign_data, user["session_key"]) + return { + "signData": sign_data, + "mode": "short_series_goods", + "paySig": pay_sig, + "signature": signature, + "outTradeNo": out_trade_no, + "productId": product_id, + "goodsPrice": price_fen, + "kind": "social_join", + "title": cfg.get("socialJoinTitle") or "游民社区加群", + } + + +@router.post("/social-join-order") +async def create_social_join_order( + request: Request, openid: str = Depends(get_current_openid) +): + """游民社区加群收费 — 微信小程序虚拟支付,与 VIP 订单隔离。""" + rate_limit(request, bucket="pay.social_join", limit=20, window_sec=60.0) + payload = _build_social_join_order_payload(openid) + try: + from ebook_svc.services.track import ingest_events + + await ingest_events( + [ + { + "name": "pay_order_created", + "page": "api", + "label": payload.get("productId"), + "props": { + "kind": "social_join", + "book_id": SOCIAL_JOIN_BOOK_ID, + "out_trade_no": payload.get("outTradeNo"), + "price_fen": payload.get("goodsPrice"), + }, + "ts": None, + } + ], + openid=openid, + client="api", + ) + except Exception: + pass + return payload + + +@router.get("/social-join-status") +async def social_join_status(openid: str = Depends(get_current_openid)): + cfg = read_social_join_config() + return { + "ok": True, + "isMember": store.is_unlocked(openid, SOCIAL_JOIN_BOOK_ID), + "bookId": SOCIAL_JOIN_BOOK_ID, + "title": cfg.get("socialJoinTitle") or "游民社区加群", + "priceFen": int(cfg.get("socialJoinPriceFen") or 0), + "enabled": bool(cfg.get("socialJoinEnabled")), + } + + def _require_shop_vip(openid: str) -> None: cfg = read_vip_config() if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0: diff --git a/apps/api/services/ebook_svc/services/social_join_config.py b/apps/api/services/ebook_svc/services/social_join_config.py new file mode 100644 index 0000000..afd4d83 --- /dev/null +++ b/apps/api/services/ebook_svc/services/social_join_config.py @@ -0,0 +1,49 @@ +"""游民社区「加群收费」配置 — 与 VIP / community 付费体系隔离。""" +from __future__ import annotations + +import json +from typing import Any + +from ebook_svc.services.tt_platform_config import resolve_config_file + +SOCIAL_JOIN_BOOK_ID = "__social_join__" + +DEFAULT_SOCIAL_JOIN = { + # 与 VIP(__vip__/tiktok) 隔离:默认用已发布 nomad 道具;后台可改价/改道具。 + "socialJoinPriceFen": 4900, + "socialJoinProductId": "nomad", + "socialJoinTitle": "游民社区加群", + "socialJoinEnabled": True, +} + + +def _read_raw() -> dict[str, Any]: + path = resolve_config_file() + if not path.is_file(): + return {} + try: + raw = json.loads(path.read_text(encoding="utf-8")) + return raw if isinstance(raw, dict) else {} + except Exception: + return {} + + +def read_social_join_config() -> dict[str, Any]: + raw = _read_raw() + flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {} + copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {} + out = dict(DEFAULT_SOCIAL_JOIN) + if "socialJoinEnabled" in flags: + out["socialJoinEnabled"] = bool(flags.get("socialJoinEnabled")) + for key in ("socialJoinPriceFen", "socialJoinProductId", "socialJoinTitle"): + if key in flags and flags[key] not in (None, ""): + out[key] = flags[key] + elif key in copy and copy[key] not in (None, ""): + out[key] = copy[key] + try: + out["socialJoinPriceFen"] = int(out["socialJoinPriceFen"]) + except Exception: + out["socialJoinPriceFen"] = DEFAULT_SOCIAL_JOIN["socialJoinPriceFen"] + out["socialJoinProductId"] = str(out.get("socialJoinProductId") or "").strip() + out["socialJoinTitle"] = str(out.get("socialJoinTitle") or DEFAULT_SOCIAL_JOIN["socialJoinTitle"]) + return out diff --git a/apps/api/services/social_svc/config.py b/apps/api/services/social_svc/config.py index 6b01a17..192716a 100644 --- a/apps/api/services/social_svc/config.py +++ b/apps/api/services/social_svc/config.py @@ -20,3 +20,19 @@ CENTRIFUGO_WS_URL = os.getenv( "CENTRIFUGO_WS_URL", "wss://nomadro.cn/rt/connection/websocket", ) + +# 原生音视频厅(SRS RTMP 推 / HTTP-FLV 拉)— 微信 LivePusher/LivePlayer +LIVE_RTMP_PUSH_BASE = os.getenv( + "LIVE_RTMP_PUSH_BASE", + "rtmp://82.157.112.245/live", +) +LIVE_HTTP_PLAY_BASE = os.getenv( + "LIVE_HTTP_PLAY_BASE", + "https://nomadro.cn/live", +) +LIVE_STREAM_SECRET = os.getenv( + "LIVE_STREAM_SECRET", + os.getenv("CENTRIFUGO_TOKEN_SECRET", "nomadro-live-dev-secret"), +) +LIVE_MAX_PEERS = int(os.getenv("LIVE_MAX_PEERS", "6")) +LIVE_PEER_TTL_SEC = int(os.getenv("LIVE_PEER_TTL_SEC", "45")) diff --git a/apps/api/services/social_svc/live.py b/apps/api/services/social_svc/live.py new file mode 100644 index 0000000..813ffa1 --- /dev/null +++ b/apps/api/services/social_svc/live.py @@ -0,0 +1,156 @@ +"""游民社区原生音视频厅 — SRS RTMP 推流 + HTTP-FLV 拉流 + 房间信令。 + +微信小程序:LivePusher(pushUrl) + LivePlayer(playUrl) +门户 H5:仍可用 MiroTalk;本模块给 weapp 原生厅发流地址。 +""" +from __future__ import annotations + +import hashlib +import hmac +import os +import re +import threading +import time +from typing import Any + +from social_svc.config import ( + LIVE_HTTP_PLAY_BASE, + LIVE_MAX_PEERS, + LIVE_PEER_TTL_SEC, + LIVE_RTMP_PUSH_BASE, + LIVE_STREAM_SECRET, +) + +_lock = threading.RLock() +# room_id -> { peer_id: peer_dict } +_rooms: dict[str, dict[str, dict[str, Any]]] = {} + + +def _safe(s: str, n: int = 48) -> str: + t = re.sub(r"[^a-zA-Z0-9_-]+", "", (s or "").strip())[:n] + return t or "x" + + +def _sig(stream: str, exp: int) -> str: + raw = f"{stream}:{exp}".encode("utf-8") + return hmac.new(LIVE_STREAM_SECRET.encode("utf-8"), raw, hashlib.sha256).hexdigest()[:16] + + +def stream_name(room_id: str, peer_id: str) -> str: + return f"{_safe(room_id, 24)}_{_safe(peer_id, 24)}" + + +def build_urls(room_id: str, peer_id: str) -> dict[str, str]: + stream = stream_name(room_id, peer_id) + exp = int(time.time()) + 3600 * 6 + token = _sig(stream, exp) + # 微信 LivePusher:RTMP url 勿带 query,否则真机常推流失败→本地黑屏 + push = f"{LIVE_RTMP_PUSH_BASE.rstrip('/')}/{stream}" + # HTTP-FLV 拉流可带 token(nginx/SRS 忽略未知参数) + play = f"{LIVE_HTTP_PLAY_BASE.rstrip('/')}/{stream}.flv?e={exp}&k={token}" + return {"stream": stream, "pushUrl": push, "playUrl": play} + + +def _purge(room_id: str) -> None: + now = time.time() + room = _rooms.get(room_id) or {} + dead = [pid for pid, p in room.items() if now - float(p.get("seen", 0)) > LIVE_PEER_TTL_SEC] + for pid in dead: + room.pop(pid, None) + if not room: + _rooms.pop(room_id, None) + + +def list_peers(room_id: str) -> list[dict[str, Any]]: + with _lock: + _purge(room_id) + room = _rooms.get(room_id) or {} + return [ + { + "peerId": p["peerId"], + "nick": p["nick"], + "playUrl": p["playUrl"], + "stream": p["stream"], + "seen": p["seen"], + } + for p in room.values() + ] + + +def join_room(room_id: str, guest_id: str, nick: str) -> dict[str, Any]: + rid = _safe(room_id, 40) + gid = _safe(guest_id, 40) + name = (nick or "游民").strip()[:32] or "游民" + with _lock: + _purge(rid) + room = _rooms.setdefault(rid, {}) + if gid not in room and len(room) >= LIVE_MAX_PEERS: + raise ValueError(f"厅已满(最多 {LIVE_MAX_PEERS} 人)") + urls = build_urls(rid, gid) + peer = { + "peerId": gid, + "nick": name, + "stream": urls["stream"], + "pushUrl": urls["pushUrl"], + "playUrl": urls["playUrl"], + "seen": time.time(), + "joinedAt": time.time(), + } + room[gid] = peer + peers = [ + { + "peerId": p["peerId"], + "nick": p["nick"], + "playUrl": p["playUrl"], + "stream": p["stream"], + } + for pid, p in room.items() + if pid != gid + ] + return { + "ok": True, + "roomId": rid, + "peerId": gid, + "nick": name, + "pushUrl": urls["pushUrl"], + "playUrl": urls["playUrl"], + "stream": urls["stream"], + "peers": peers, + "maxPeers": LIVE_MAX_PEERS, + "channelId": f"live-{rid}", + "engine": "srs-rtmp-flv", + } + + +def heartbeat(room_id: str, guest_id: str) -> dict[str, Any]: + rid = _safe(room_id, 40) + gid = _safe(guest_id, 40) + with _lock: + _purge(rid) + room = _rooms.get(rid) or {} + me = room.get(gid) + if not me: + raise ValueError("未在厅内,请重新进入") + me["seen"] = time.time() + peers = [ + { + "peerId": p["peerId"], + "nick": p["nick"], + "playUrl": p["playUrl"], + "stream": p["stream"], + } + for pid, p in room.items() + if pid != gid + ] + return {"ok": True, "roomId": rid, "peers": peers, "peerCount": len(peers) + 1} + + +def leave_room(room_id: str, guest_id: str) -> dict[str, Any]: + rid = _safe(room_id, 40) + gid = _safe(guest_id, 40) + with _lock: + room = _rooms.get(rid) or {} + room.pop(gid, None) + if not room: + _rooms.pop(rid, None) + return {"ok": True, "roomId": rid} diff --git a/apps/api/services/social_svc/realtime.py b/apps/api/services/social_svc/realtime.py index 8c9e73f..af54d6c 100644 --- a/apps/api/services/social_svc/realtime.py +++ b/apps/api/services/social_svc/realtime.py @@ -52,11 +52,11 @@ def issue_connection_token(guest_id: str, channel_id: str | None = None) -> dict } -async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool: +async def _publish(channel_id: str, data: dict[str, Any]) -> bool: if not CENTRIFUGO_ENABLED or not CENTRIFUGO_API_KEY: return False url = CENTRIFUGO_API_URL.rstrip("/") + "/publish" - body = {"channel": channel_name(channel_id), "data": {"type": "chat.message", "message": message}} + body = {"channel": channel_name(channel_id), "data": data} try: async with httpx.AsyncClient(timeout=3.0) as client: res = await client.post( @@ -71,3 +71,11 @@ async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool except Exception as e: # pragma: no cover log.warning("centrifugo publish failed: %s", e) return False + + +async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool: + return await _publish(channel_id, {"type": "chat.message", "message": message}) + + +async def publish_live_event(channel_id: str, event: str, payload: dict[str, Any]) -> bool: + return await _publish(channel_id, {"type": f"live.{event}", **payload}) diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index bb7bd4f..0221ff9 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -4,15 +4,22 @@ from __future__ import annotations from fastapi import APIRouter, Header, HTTPException, Query from pydantic import BaseModel, Field -from social_svc import store +from social_svc import live, store from social_svc.config import SOCIAL_ENABLED -from social_svc.realtime import issue_connection_token, publish_chat_message +from social_svc.realtime import ( + issue_connection_token, + publish_chat_message, + publish_live_event, +) router = APIRouter(tags=["social"]) -def _guest(x_social_guest_id: str | None) -> str: - gid = (x_social_guest_id or "").strip() +def _guest( + x_social_guest_id: str | None, + guest_q: str | None = None, +) -> str: + gid = (x_social_guest_id or guest_q or "").strip() if not gid or len(gid) > 80: raise HTTPException(status_code=400, detail="missing X-Social-Guest-Id") return gid @@ -67,9 +74,10 @@ async def social_health(): async def realtime_token( channel_id: str = Query(default="lobby"), x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), ): - guest = _guest(x_social_guest_id) - return issue_connection_token(guest, channel_id) + peer = _guest(x_social_guest_id, guest) + return issue_connection_token(peer, channel_id) @router.get("/channels/{channel_id}/messages") @@ -83,12 +91,13 @@ async def post_message( channel_id: str, body: MessageIn, x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), ): - guest = _guest(x_social_guest_id) + peer = _guest(x_social_guest_id, guest) store.init_db() if not body.text.strip(): raise HTTPException(status_code=400, detail="empty text") - saved = store.add_message(channel_id, body.author, body.text, guest) + saved = store.add_message(channel_id, body.author, body.text, peer) # 实时推送失败不影响落库成功 try: await publish_chat_message(channel_id, saved) @@ -157,3 +166,78 @@ async def post_gig_apply( guest = _guest(x_social_guest_id) store.init_db() return store.add_gig_app(gig_id, body.name, body.contact, body.note, guest) + + +class LiveJoinIn(BaseModel): + nick: str = Field(default="游民", max_length=32) + + +@router.post("/live/rooms/{room_id}/join") +async def live_join( + room_id: str, + body: LiveJoinIn, + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None, alias="guest"), +): + """微信原生 LivePusher/LivePlayer 进厅:下发 RTMP 推流 + FLV 拉流。""" + peer = _guest(x_social_guest_id, guest) + try: + payload = live.join_room(room_id, peer, body.nick) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) from e + try: + await publish_live_event( + payload["channelId"], + "peer_join", + { + "roomId": payload["roomId"], + "peer": { + "peerId": payload["peerId"], + "nick": payload["nick"], + "playUrl": payload["playUrl"], + "stream": payload["stream"], + }, + }, + ) + except Exception: + pass + # 附带实时通道 token,前端可订 live 频道 + payload["realtime"] = issue_connection_token(peer, payload["channelId"]) + return payload + + +@router.post("/live/rooms/{room_id}/heartbeat") +async def live_heartbeat( + room_id: str, + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), +): + peer = _guest(x_social_guest_id, guest) + try: + return live.heartbeat(room_id, peer) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) from e + + +@router.get("/live/rooms/{room_id}/peers") +async def live_peers(room_id: str): + return {"ok": True, "roomId": room_id, "peers": live.list_peers(room_id)} + + +@router.post("/live/rooms/{room_id}/leave") +async def live_leave( + room_id: str, + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), +): + peer = _guest(x_social_guest_id, guest) + out = live.leave_room(room_id, peer) + try: + await publish_live_event( + f"live-{out['roomId']}", + "peer_leave", + {"roomId": out["roomId"], "peerId": peer}, + ) + except Exception: + pass + return out diff --git a/apps/miniprogram/h5/scripts/_h5_smoke.py b/apps/miniprogram/h5/scripts/_h5_smoke.py index 16a7418..b83cb88 100644 --- a/apps/miniprogram/h5/scripts/_h5_smoke.py +++ b/apps/miniprogram/h5/scripts/_h5_smoke.py @@ -13,10 +13,15 @@ OUT = Path(__file__).resolve().parents[1] / "tmp" / "h5-smoke" OUT.mkdir(parents=True, exist_ok=True) ROUTES = [ - ("home", "/#/pages/index/index", ["nomadro", "随处工作", "自由生活", "出海导航", "数字游民小册", "旅居社群"]), + ("home", "/#/pages/home/index", ["nomadro", "随处工作", "自由生活", "游民社区"]), ("nav", "/#/pages/nav/index", ["导航"]), ("book", "/#/pages/book/index", ["Nomadro"]), # cover brand after offline/API load ("community", "/#/pages/community/index", ["nomadro"]), + ("social", "/#/pages/social/index", ["世界很大", "群组聊天", "认识一下", "想见的人", "一张一张认识新朋友"]), + ("social_date", "/#/pages/social/date/index", ["认识一下", "左滑划走", "想认识"]), + ("social_chat", "/#/pages/social/chat/index", ["大家聊天", "#general"]), + ("social_people", "/#/pages/social/people/index", ["想见的人"]), + ("social_roster", "/#/pages/social/roster/index", ["我的介绍", "保存介绍"]), ("mine", "/#/pages/mine/index", ["我的"]), ("vip", "/#/pages/vip/index", ["会员"]), ] diff --git a/apps/miniprogram/h5/src/app.config.ts b/apps/miniprogram/h5/src/app.config.ts index 5af6efe..48ba442 100644 --- a/apps/miniprogram/h5/src/app.config.ts +++ b/apps/miniprogram/h5/src/app.config.ts @@ -47,10 +47,10 @@ const wantTabBar = !isH5 && process.env.TARO_APP_TABBAR === '1' /** 微信主包必须 ≤2MB:首页/我的/小册留主包(提审小册勿进分包,避免下载失败黑屏) */ const weappConfig = { - // 提审期:小册作启动页,打开即见正文(过审后改回 home 第一) + // 启动页:门户首页(提审专用包见 apps/miniprogram/weapp-audit) pages: [ - 'pages/book/index', 'pages/home/index', + 'pages/book/index', 'pages/mine/index', 'pages/index/index', ], @@ -141,14 +141,29 @@ const weappConfig = { name: 'game', pages: ['index'], }, + { + root: 'pages/social', + name: 'social', + pages: [ + 'index', + 'chat/index', + 'date/index', + 'people/index', + 'people/profile/index', + 'roster/index', + 'meetup/index', + 'meetup-live/index', + 'team/index', + ], + }, ], preloadRule: { 'pages/home/index': { network: 'all', - packages: ['nav', 'reader'], + packages: ['nav', 'reader', 'social'], }, }, - // 提审期先关掉按需注入:Taro+React 下偶发首屏空白/黑屏;过审后再开回 requiredComponents + // AI 开发模式:agent / ai-pkg 独立分包由 weapp/scripts/copy-weapp-static 在 TARO_APP_AI_MODE=1 时注入,勿写进提审包 // lazyCodeLoading: 'requiredComponents' as const, } @@ -175,6 +190,15 @@ const h5Config = { 'pages/vip-memo/index', 'pages/vip-memo-detail/index', 'pages/game/index', + 'pages/social/index', + 'pages/social/chat/index', + 'pages/social/date/index', + 'pages/social/people/index', + 'pages/social/people/profile/index', + 'pages/social/roster/index', + 'pages/social/meetup/index', + 'pages/social/meetup-live/index', + 'pages/social/team/index', ], } @@ -187,5 +211,13 @@ export default defineAppConfig({ navigationBarTextStyle: 'white', backgroundColor: '#0c0c0f', }, + permission: { + 'scope.camera': { + desc: '用于游民社区语音视频见面(live-pusher)', + }, + 'scope.record': { + desc: '用于游民社区语音视频见面麦克风', + }, + }, ...(wantTabBar ? { tabBar } : {}), }) diff --git a/apps/miniprogram/h5/src/app.tsx b/apps/miniprogram/h5/src/app.tsx index 22807a5..44ec1b1 100644 --- a/apps/miniprogram/h5/src/app.tsx +++ b/apps/miniprogram/h5/src/app.tsx @@ -1,6 +1,6 @@ import { Fragment, useEffect } from 'react' import type { PropsWithChildren } from 'react' -import { useDidHide, useDidShow, useLaunch } from '@tarojs/taro' +import Taro, { useDidHide, useDidShow, useLaunch } from '@tarojs/taro' import { flush, trackAppLaunch } from './utils/track' import { loadRemoteConfig, @@ -25,6 +25,35 @@ function App({ children }: PropsWithChildren) { if (process.env.TARO_ENV === 'h5') { applyH5Theme(getStoredH5Theme()) } + // 小程序 AI 接力:账号卡片进入页时同步 payload(仅 weapp + 基础库支持时) + if (process.env.TARO_ENV === 'weapp') { + try { + const wxApi = Taro as unknown as { + onAgentHandoff?: ( + cb: (p: { + pageId: number + path: string + query: string + payload: unknown + }) => void, + ) => void + } + if (typeof wxApi.onAgentHandoff === 'function') { + wxApi.onAgentHandoff(({ pageId, path, query, payload }) => { + const g = globalThis as unknown as { + __nomadroAgentHandoffs?: Record< + number, + { path: string; query: string; payload: unknown } + > + } + g.__nomadroAgentHandoffs = g.__nomadroAgentHandoffs || {} + g.__nomadroAgentHandoffs[pageId] = { path, query, payload } + }) + } + } catch { + /* AI 模式未开通时忽略 */ + } + } }) useDidShow(() => { diff --git a/apps/miniprogram/h5/src/components/H5Box.tsx b/apps/miniprogram/h5/src/components/H5Box.tsx index 97dd650..dab8e4e 100644 --- a/apps/miniprogram/h5/src/components/H5Box.tsx +++ b/apps/miniprogram/h5/src/components/H5Box.tsx @@ -16,6 +16,14 @@ type BoxProps = { 'data-theme'?: string /** 设了则点击时自动 btn_click 埋点 */ trackLabel?: string + /** H5-only pointer handlers (ignored on mini programs) */ + onPointerDown?: (e: any) => void + onPointerMove?: (e: any) => void + onPointerUp?: (e: any) => void + onPointerCancel?: (e: any) => void + onTouchStart?: (e: any) => void + onTouchMove?: (e: any) => void + onTouchEnd?: (e: any) => void } /** H5 uses native div (taro-view-core defaults to inline and breaks grid/absolute). */ @@ -30,6 +38,13 @@ export function H5Box({ 'aria-label': ariaLabel, 'data-theme': dataTheme, trackLabel, + onPointerDown, + onPointerMove, + onPointerUp, + onPointerCancel, + onTouchStart, + onTouchMove, + onTouchEnd, }: BoxProps) { const handleClick = onClick ? () => { @@ -37,8 +52,8 @@ export function H5Box({ onClick() } : trackLabel - ? () => trackClick(trackLabel) - : undefined + ? () => trackClick(trackLabel) + : undefined if (isH5) { return ( @@ -47,6 +62,13 @@ export function H5Box({ className={className} style={style} onClick={handleClick} + onPointerDown={onPointerDown} + onPointerMove={onPointerMove} + onPointerUp={onPointerUp} + onPointerCancel={onPointerCancel} + onTouchStart={onTouchStart} + onTouchMove={onTouchMove} + onTouchEnd={onTouchEnd} aria-hidden={ariaHidden} aria-label={ariaLabel} data-theme={dataTheme} @@ -65,6 +87,10 @@ export function H5Box({ className={className} style={style} onClick={handleClick} + onTouchStart={onTouchStart || onPointerDown} + onTouchMove={onTouchMove || onPointerMove} + onTouchEnd={onTouchEnd || onPointerUp} + onTouchCancel={onPointerCancel} data-theme={dataTheme} > {children} diff --git a/apps/miniprogram/h5/src/components/SocialDock.tsx b/apps/miniprogram/h5/src/components/SocialDock.tsx new file mode 100644 index 0000000..5b16f21 --- /dev/null +++ b/apps/miniprogram/h5/src/components/SocialDock.tsx @@ -0,0 +1,2 @@ +/** @deprecated use pages/social/_components/SocialDock */ +export { SocialDock } from '../pages/social/_components/SocialDock' diff --git a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts index 60c4107..9016b33 100644 --- a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts +++ b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts @@ -58,6 +58,7 @@ export type NomadroRemoteConfig = { destinations: ModuleToggle home: ModuleToggle game: ModuleToggle + social: ModuleToggle } flags: { payEnabled: boolean @@ -173,6 +174,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = { meetups: { enabled: false, title: '活动' }, vip: { enabled: false, title: '会员中心' }, game: { enabled: false, title: '数字游民', note: '冻结隐藏 · 勿开入口' }, + social: { enabled: true, title: '游民社区', tabLabel: '社区', note: 'Taro 原生 /social · rem 自适应' }, }, flags: { payEnabled: true, diff --git a/apps/miniprogram/h5/src/data/socialCatalog.ts b/apps/miniprogram/h5/src/data/socialCatalog.ts new file mode 100644 index 0000000..935d7b6 --- /dev/null +++ b/apps/miniprogram/h5/src/data/socialCatalog.ts @@ -0,0 +1,237 @@ +import type { + SocialCafe, + SocialChannel, + SocialChatMessage, + SocialEbook, + SocialGig, + SocialMeetup, + SocialTeamKind, + SocialVideo, +} from './socialTypes' + +export const SEED_CHANNELS: SocialChannel[] = [ + { id: "general", name: "#general", topic: "游民闲聊 · 报到打卡", members: 128 }, + { id: "chiangmai", name: "#chiangmai", topic: "清迈同城 · cowork / visa", members: 64 }, + { id: "meetup-live", name: "#meetup-live", topic: "线上活动文字房", members: 42 }, + { id: "coffee", name: "#coffeechat", topic: "咖啡馆约见协调", members: 31 }, +]; + +export const SEED_MESSAGES: SocialChatMessage[] = [ + { + id: "m1", + channelId: "general", + author: "林远", + text: "欢迎来到游民社区实时聊天室 👋 先报个到:你在哪座城?", + at: "2026-10-28T09:00:00.000Z", + }, + { + id: "m2", + channelId: "general", + author: "Mika", + text: "清迈第三周,Nimman 找 cowork,有人一起吗?", + at: "2026-10-28T09:12:00.000Z", + }, + { + id: "m3", + channelId: "chiangmai", + author: "Ken", + text: "Graph Table 二楼靠窗位 WiFi 稳,插座够。", + at: "2026-10-29T02:20:00.000Z", + }, + { + id: "m4", + channelId: "meetup-live", + author: "Host", + text: "今晚 20:00 开视频见面,文字也可以在这儿继续聊。", + at: "2026-10-30T08:00:00.000Z", + }, +]; + +export const SEED_CAFES: SocialCafe[] = [ + { + id: "graph-table", + name: "Graph Table", + city: "清迈", + wifiMbps: 80, + power: "座位大多有插座", + vibe: "安静 · 设计感", + partners: true, + rating: 4.7, + reviews: 18, + }, + { + id: "camp", + name: "Camp", + city: "清迈", + wifiMbps: 100, + power: "全覆盖", + vibe: "社区感 · 活动多", + partners: true, + rating: 4.6, + reviews: 24, + }, + { + id: "blink", + name: "Blink Cowork", + city: "槟城", + wifiMbps: 120, + power: "全覆盖", + vibe: "海风 · 开放工位", + partners: false, + rating: 4.4, + reviews: 9, + }, + { + id: "forest", + name: "Forest Coffee", + city: "大理", + wifiMbps: 40, + power: "靠窗有限", + vibe: "慢节奏 · 适合深谈", + partners: true, + rating: 4.5, + reviews: 11, + }, +]; + +export const SEED_MEETUPS: SocialMeetup[] = [ + { + id: "wk-nomad-office", + title: "周三线上办公室", + city: "Online", + date: "2026-11-05", + time: "20:00", + mode: "online", + mirotalkRoom: "nomadro-social-office", + channelId: "meetup-live", + }, + { + id: "visa-ama", + title: "签证 AMA · 东南亚", + city: "Online", + date: "2026-11-08", + time: "21:00", + mode: "hybrid", + mirotalkRoom: "nomadro-visa-ama", + channelId: "meetup-live", + }, +]; + +export const SEED_VIDEOS: SocialVideo[] = [ + { + id: "cm-morning", + title: "清迈的周二早晨", + city: "清迈", + minutes: 12, + coverEmoji: "🛵", + summary: "咖啡馆办公、时区套利、同城聚餐。", + }, + { + id: "penang-walk", + title: "槟城街头访谈", + city: "槟城", + minutes: 8, + coverEmoji: "🎙", + summary: "两位远程设计师聊租金与 cowork。", + }, + { + id: "dali-date", + title: "大理 Coffeechat 实录", + city: "大理", + minutes: 15, + coverEmoji: "☕", + summary: "线下约见流程:场地、合照、评价。", + }, +]; + +export const SEED_EBOOKS: SocialEbook[] = [ + { + id: "social-playbook", + title: "游民社区怎么玩", + chapters: 6, + minutes: 35, + blurb: "怎么认识人、开视频、约咖啡、一起做事,一篇说清楚。", + }, + { + id: "roster-guide", + title: "怎么写好自我介绍", + chapters: 4, + minutes: 20, + blurb: "写几句让同城的人找到你,也不用写得很正式。", + }, +]; + +export const SEED_GIGS: SocialGig[] = [ + { + id: "vol-welcome", + title: "欢迎新人的帮手", + role: "帮忙志愿", + pay: "公益积分 / 社群徽章", + remote: true, + kind: "volunteer", + tags: ["带新人", "答疑", "周报"], + }, + { + id: "vol-event", + title: "线下见面局帮手", + role: "帮忙志愿", + pay: "活动席位优先", + remote: false, + kind: "volunteer", + tags: ["约咖啡", "合照", "场地协调"], + }, + { + id: "ops-assistant", + title: "运营 / 拍摄助理", + role: "大学生兼职", + pay: "按场次结算", + remote: true, + kind: "parttime", + tags: ["拍摄", "剪辑", "活动跟场"], + }, + { + id: "community-mod", + title: "社群值班主持人", + role: "线上兼职", + pay: "月度津贴", + remote: true, + kind: "parttime", + tags: ["聊天室", "视频见面主持"], + }, + { + id: "content-pt", + title: "内容兼职编辑", + role: "线上兼职", + pay: "按篇结算", + remote: true, + kind: "parttime", + tags: ["小册", "视频字幕", "社媒"], + }, + { + id: "ft-community", + title: "社群运营负责人", + role: "全职 · 线上优先", + pay: "面议 · 季度复盘", + remote: true, + kind: "fulltime", + tags: ["增长", "活动", "认识人"], + }, + { + id: "ft-fullstack", + title: "全栈工程师", + role: "全职 · 线上", + pay: "面议", + remote: true, + kind: "fulltime", + tags: ["Next.js", "FastAPI", "小程序"], + }, +]; + +export const TEAM_KIND_LABEL: Record = { + volunteer: "帮忙志愿", + parttime: "兼职机会", + fulltime: "全职机会", +}; + +/** Same box as nomadro.cn (82.x). Prefer .cn — avoid .com→107 hop. */ +export const MIROTALK_URL = 'https://mirotalk.nomadro.cn' diff --git a/apps/miniprogram/h5/src/data/socialCities.ts b/apps/miniprogram/h5/src/data/socialCities.ts new file mode 100644 index 0000000..fbd41ee --- /dev/null +++ b/apps/miniprogram/h5/src/data/socialCities.ts @@ -0,0 +1,168 @@ +/** Offline city catalog — seed inspired by meetup.hackrobot.cn destination list. */ + +export type SocialCity = { + id: string; + name: string; + country: string; + emoji: string; + vibe: string; + members: number; + costHint: string; + wifiMbps: number; + tags: string[]; + hot?: boolean; +}; + +export const SOCIAL_CITIES: SocialCity[] = [ + { + id: "dali", + name: "大理", + country: "中国", + emoji: "🏔️", + vibe: "苍山洱海 · 慢生活", + members: 520, + costHint: "¥3,000/月起", + wifiMbps: 50, + tags: ["热门", "便宜", "山城"], + hot: true, + }, + { + id: "chengdu", + name: "成都", + country: "中国", + emoji: "🌶️", + vibe: "天府之国 · 美食慢节奏", + members: 680, + costHint: "¥4,500/月起", + wifiMbps: 80, + tags: ["热门", "美食", "宜居"], + hot: true, + }, + { + id: "hangzhou", + name: "杭州", + country: "中国", + emoji: "🏞️", + vibe: "西湖 · 互联网重镇", + members: 560, + costHint: "¥6,000/月起", + wifiMbps: 100, + tags: ["热门", "高速网络"], + hot: true, + }, + { + id: "kunming", + name: "昆明", + country: "中国", + emoji: "🌸", + vibe: "四季如春 · 通往东南亚", + members: 380, + costHint: "¥3,500/月起", + wifiMbps: 55, + tags: ["温暖", "便宜"], + }, + { + id: "shenzhen", + name: "深圳", + country: "中国", + emoji: "🚀", + vibe: "科技创新 · 创业友好", + members: 850, + costHint: "¥8,000/月起", + wifiMbps: 120, + tags: ["热门", "高速网络", "一线城市"], + hot: true, + }, + { + id: "xiamen", + name: "厦门", + country: "中国", + emoji: "🏝️", + vibe: "海滨花园 · 鼓浪屿", + members: 320, + costHint: "¥5,500/月起", + wifiMbps: 70, + tags: ["海滨", "温暖"], + }, + { + id: "shanghai", + name: "上海", + country: "中国", + emoji: "🌆", + vibe: "国际大都市 · 文化交汇", + members: 1200, + costHint: "¥10,000/月起", + wifiMbps: 110, + tags: ["一线城市", "热门"], + }, + { + id: "lijiang", + name: "丽江", + country: "中国", + emoji: "🏯", + vibe: "玉龙雪山 · 古城慢旅", + members: 280, + costHint: "¥3,200/月起", + wifiMbps: 45, + tags: ["便宜", "山城"], + }, + { + id: "chiangmai", + name: "清迈", + country: "泰国", + emoji: "🌿", + vibe: "Nimman · 游民大本营", + members: 940, + costHint: "฿18,000/月起", + wifiMbps: 90, + tags: ["热门", "友好社区", "高速网络"], + hot: true, + }, + { + id: "bali", + name: "巴厘岛", + country: "印尼", + emoji: "🌴", + vibe: "Canggu · 冲浪与 cowork", + members: 720, + costHint: "Rp8jt/月起", + wifiMbps: 60, + tags: ["海滨", "温暖", "热门"], + hot: true, + }, + { + id: "lisbon", + name: "里斯本", + country: "葡萄牙", + emoji: "🌊", + vibe: "阳光海岸 · 欧洲时区", + members: 610, + costHint: "€1,200/月起", + wifiMbps: 100, + tags: ["海滨", "友好社区"], + }, + { + id: "penang", + name: "槟城", + country: "马来西亚", + emoji: "🍜", + vibe: "美食 · 海风开放工位", + members: 260, + costHint: "RM2,800/月起", + wifiMbps: 100, + tags: ["美食", "便宜"], + }, +]; + +export const CITY_FILTER_TAGS = [ + "全部", + "热门", + "便宜", + "高速网络", + "温暖", + "海滨", + "山城", + "一线城市", + "友好社区", + "美食", +] as const; diff --git a/apps/miniprogram/h5/src/data/socialRoster.ts b/apps/miniprogram/h5/src/data/socialRoster.ts new file mode 100644 index 0000000..40ccafa --- /dev/null +++ b/apps/miniprogram/h5/src/data/socialRoster.ts @@ -0,0 +1,243 @@ +/** 首页花名册 mock — 在线状态 / 想认识 / 可互动 */ + +export type SocialRosterMember = { + id: string; + name: string; + title: string; + city: string; + tags: string[]; + avatar: string; + bio: string; + vibe: string; + online: boolean; + lookingFor: string; + gender: "f" | "m"; + languages?: string[]; + availability?: string; + timezone?: string; + /** Extra photos for profile wall (nomads-style) */ + gallery?: string[]; +}; + +export const MOCK_ROSTER: SocialRosterMember[] = [ + { + id: "m01", + name: "林悦", + title: "独立设计师", + city: "清迈 · Nimman", + tags: ["咖啡局", "设计", "日出"], + avatar: "https://randomuser.me/api/portraits/women/65.jpg", + bio: "喜欢把 cowork 聊成真实见面。周末常去 Graph Table,也爱清晨骑车去山上看雾。", + vibe: "温柔 · 有品味", + online: true, + lookingFor: "想认识会拍照的远程伙伴", + gender: "f", + languages: ["中文", "English"], + availability: "本周可 Coffeechat", + timezone: "ICT (UTC+7)", + gallery: [ + "https://images.unsplash.com/photo-1523906834658-6e24ef2386f9?w=640&q=80", + "https://images.unsplash.com/photo-1554118811-1e0d58224f24?w=640&q=80", + ], + }, + { + id: "m02", + name: "Ethan", + title: "全栈 / SaaS", + city: "里斯本", + tags: ["Next.js", "夜跑", "冲浪"], + avatar: "https://randomuser.me/api/portraits/men/32.jpg", + bio: "白天写代码,傍晚海边。欢迎 Coffeechat 聊产品与出海。", + vibe: "阳光 · 靠谱", + online: true, + lookingFor: "找联创 / 一起做副业", + gender: "m", + languages: ["English", "Português", "中文"], + availability: "欧洲晚间可视频", + timezone: "WET (UTC+0)", + gallery: [ + "https://images.unsplash.com/photo-1555881403-7463c9aea225?w=640&q=80", + ], + }, + { + id: "m03", + name: "苏晴", + title: "内容创业者", + city: "巴厘岛 · Canggu", + tags: ["Vlog", "瑜伽", "出海"], + avatar: "https://randomuser.me/api/portraits/women/44.jpg", + bio: "镜头前很活泼,线下更爱深度聊天。常在 Canggu cowork。", + vibe: "活力", + online: false, + lookingFor: "想认识同频创作者", + gender: "f", + languages: ["中文", "English"], + availability: "周末可线下局", + timezone: "WITA (UTC+8)", + }, + { + id: "m04", + name: "Ken", + title: "产品经理", + city: "东京 / 远程", + tags: ["B2B", "胶片", "拉面"], + avatar: "https://randomuser.me/api/portraits/men/75.jpg", + bio: "时差玩家。开视频见面时很稳,私下爱胶片机。", + vibe: "干净 · 有梗", + online: true, + lookingFor: "想找一起探索城市的人", + gender: "m", + languages: ["日本語", "English", "中文"], + availability: "常来开视频见面", + timezone: "JST (UTC+9)", + }, + { + id: "m05", + name: "Mia", + title: "增长黑客", + city: "曼谷", + tags: ["增长", "夜市", "泰语"], + avatar: "https://randomuser.me/api/portraits/women/68.jpg", + bio: "把增长聊成故事。欢迎约路边摊。", + vibe: "聪明 · 飒", + online: true, + lookingFor: "找一起搞出海的搭档", + gender: "f", + languages: ["中文", "English", "ไทย"], + availability: "今晚可以开视频", + timezone: "ICT (UTC+7)", + }, + { + id: "m06", + name: "阿杰", + title: "独立开发者", + city: "成都 → 清迈", + tags: ["Flutter", "火锅", "副业"], + avatar: "https://randomuser.me/api/portraits/men/52.jpg", + bio: "刚到东南亚第三周,想认识本地局朋友。", + vibe: "真诚 · 幽默", + online: false, + lookingFor: "想找 cowork 搭子", + gender: "m", + languages: ["中文", "English"], + availability: "工作日 cowork", + timezone: "ICT (UTC+7)", + }, + { + id: "m07", + name: "Nora", + title: "摄影师", + city: "大城 / 曼谷", + tags: ["旅拍", "胶片", "咖啡"], + avatar: "https://randomuser.me/api/portraits/women/21.jpg", + bio: "擅长拍人。可以帮你拍「游民证件照」。", + vibe: "氛围感", + online: true, + lookingFor: "想认识爱旅行的你", + gender: "f", + languages: ["English", "中文"], + availability: "可约旅拍", + timezone: "ICT (UTC+7)", + gallery: [ + "https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?w=640&q=80", + ], + }, + { + id: "m08", + name: "Ryan", + title: "跨境电商", + city: "槟城", + tags: ["TikTok", "冲浪", "搞钱"], + avatar: "https://randomuser.me/api/portraits/men/22.jpg", + bio: "白天看数据,傍晚冲浪。社群里最活跃的那几个之一。", + vibe: "热情 · 靠谱", + online: true, + lookingFor: "找一起搞钱也搞生活的人", + gender: "m", + languages: ["中文", "English", "Bahasa"], + availability: "本周可视频", + timezone: "MYT (UTC+8)", + }, + { + id: "m09", + name: "Iris", + title: "UX 研究员", + city: "柏林", + tags: ["访谈", "市集", "播客"], + avatar: "https://randomuser.me/api/portraits/women/33.jpg", + bio: "欧洲时区,擅长把陌生人聊成朋友。", + vibe: "知性", + online: false, + lookingFor: "想认识认真做产品的人", + gender: "f", + languages: ["Deutsch", "English", "中文"], + availability: "周末可聊", + timezone: "CET (UTC+1)", + }, + { + id: "m10", + name: "Leo", + title: "AI 工程师", + city: "首尔 / 远程", + tags: ["Agent", "开源", "咖啡"], + avatar: "https://randomuser.me/api/portraits/men/41.jpg", + bio: "技术宅但不社恐。经常来开视频见面。", + vibe: "稳 · 有趣", + online: true, + lookingFor: "找一起做 AI 副业的人", + gender: "m", + languages: ["한국어", "English"], + availability: "常在视频见面里", + timezone: "KST (UTC+9)", + }, + { + id: "m11", + name: "小满", + title: "咖啡馆主理人", + city: "大理", + tags: ["手冲", "音乐会", "徒步"], + avatar: "https://randomuser.me/api/portraits/women/90.jpg", + bio: "店在古城边。来大理一定请你喝手冲。", + vibe: "松弛", + online: true, + lookingFor: "欢迎路过的游民串门", + gender: "f", + languages: ["中文"], + availability: "店里随时欢迎", + timezone: "CST (UTC+8)", + }, + { + id: "m12", + name: "Hugo", + title: "游民教练", + city: "里斯本", + tags: ["签证", "地理套利", "跑步"], + avatar: "https://randomuser.me/api/portraits/men/11.jpg", + bio: "帮过上百人规划第一站。Coffeechat 从不冷场。", + vibe: "温暖", + online: false, + lookingFor: "想认识想出发的你", + gender: "m", + languages: ["English", "Français", "中文"], + availability: "可预约 1v1", + timezone: "WET (UTC+0)", + }, +]; + +export function findRosterMember( + id: string, + extra: SocialRosterMember[] = [], +): SocialRosterMember | undefined { + return ( + extra.find((m) => m.id === id) || MOCK_ROSTER.find((m) => m.id === id) + ); +} + +/** 仅演示用,禁止当作真实运营数据展示 */ +export const SOCIAL_PROOF = { + onlineNow: MOCK_ROSTER.filter((m) => m.online).length, + members: 1280, + meetupsWeek: 6, + cities: 42, + isDemo: true as const, +}; diff --git a/apps/miniprogram/h5/src/data/socialSeed.ts b/apps/miniprogram/h5/src/data/socialSeed.ts new file mode 100644 index 0000000..0cad4e4 --- /dev/null +++ b/apps/miniprogram/h5/src/data/socialSeed.ts @@ -0,0 +1,111 @@ +/** Offline seed — aligned with Next /social landing + catalog */ +export type { SocialRosterMember } from './socialRoster' +export { MOCK_ROSTER, SOCIAL_PROOF, findRosterMember } from './socialRoster' +export { + SEED_CHANNELS, + SEED_MESSAGES, + SEED_CAFES, + SEED_MEETUPS, + SEED_VIDEOS, + SEED_EBOOKS, + SEED_GIGS, + TEAM_KIND_LABEL, + MIROTALK_URL, +} from './socialCatalog' +export { SOCIAL_CITIES } from './socialCities' + +export const SOCIAL_COPY = { + socialEyebrow: '自由生活,同频相遇', + socialHeroLine1: '世界很大,', + socialHeroAccent: '同类', + socialHeroLead: + '换一座城市,不必重新孤独。\n从一句你好、一杯咖啡开始,找到一起生活、\n一起探索、一起做点什么的人。', + socialJoinCta: '找到我的同频', + socialInviteTitle: '下一站,和同类一起。', + socialInviteLead: + '无论你正在出发,还是已经在路上,这里都有一个属于你的位置。', + socialOnlineTitle: '随时,聊得来', + socialOfflineTitle: '同城,见一面', + socialTeamTitle: '一起,做点事', + socialWayGroup: '群组聊天', + socialWayChat: '开视频聊聊', + socialWayDate: '认识一下', + socialWayCafe: '找个地方见面', + socialWayTeam: '找搭子 · 共创', +} as const + +export type SocialLandingCopy = typeof SOCIAL_COPY + +export const SOCIAL_DOCK = [ + { path: '/pages/social/index', label: '首页', short: '首页', emoji: '🏠', match: 'exact' as const }, + { path: '/pages/social/chat/index', label: '大家聊天', short: '聊天', emoji: '💬', match: 'prefix' as const }, + { path: '/pages/social/date/index', label: '认识一下', short: '认识', emoji: '💕', match: 'prefix' as const }, + { path: '/pages/social/people/index', label: '想见的人', short: '看看谁', emoji: '👋', match: 'prefix' as const }, + { path: '/pages/social/roster/index', label: '我的介绍', short: '我', emoji: '🙂', match: 'prefix' as const }, +] + +export const SOCIAL_WAYS = [ + { + id: '01', + path: '/pages/social/chat/index', + emoji: '💬', + titleKey: 'socialWayGroup' as const, + sub: '大家一起聊 · 先打个招呼', + cta: '进群聊', + tone: 'mint', + }, + { + id: '02', + path: '/pages/social/date/index', + emoji: '💕', + titleKey: 'socialWayDate' as const, + sub: '左右滑,慢慢认识', + cta: '开始看看', + tone: 'coral', + }, + { + id: '03', + path: '/pages/social/meetup/index', + emoji: '📡', + titleKey: 'socialWayChat' as const, + sub: '聊天群组 · 语音视频', + cta: '去聊聊', + tone: 'mint', + }, + { + id: '04', + path: '/pages/social/people/index?mode=cafe', + emoji: '☕', + titleKey: 'socialWayCafe' as const, + sub: '同城,见一面', + cta: '选城市', + tone: 'yellow', + }, + { + id: '05', + path: '/pages/social/team/index', + emoji: '🚀', + titleKey: 'socialWayTeam' as const, + sub: '找搭档 / 兼职 / 志愿者', + cta: '看看机会', + tone: 'mint', + }, +] + +export const PATH_CHIPS = [ + { href: '#people', label: '想见的人', emoji: '👋', page: '' }, + { href: '#date', label: '认识一下', emoji: '💕', page: '' }, + { href: '#meetup', label: '聊得来', emoji: '📡', page: '' }, + { href: '#cities', label: '见一面', emoji: '🌆', page: '' }, + { href: '#team', label: '一起做事', emoji: '🚀', page: '' }, + { href: '/pages/social/chat/index', label: '群聊', emoji: '💬', page: 'chat' }, +] as const + +export const ROLE_EMOJI: Record = { + volunteer: '🙋', + parttime: '📝', + fulltime: '💼', +} + +export const DEFAULT_PROMO = + 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4' diff --git a/apps/miniprogram/h5/src/data/socialTypes.ts b/apps/miniprogram/h5/src/data/socialTypes.ts new file mode 100644 index 0000000..42ba058 --- /dev/null +++ b/apps/miniprogram/h5/src/data/socialTypes.ts @@ -0,0 +1,93 @@ +export type SocialChannel = { + id: string; + name: string; + topic: string; + members: number; +}; + +export type SocialChatMessage = { + id: string; + channelId: string; + author: string; + text: string; + at: string; + mine?: boolean; + guestId?: string; + delivery?: "sent" | "local" | "demo"; +}; + +export type SocialCafe = { + id: string; + name: string; + city: string; + wifiMbps: number; + power: string; + vibe: string; + partners: boolean; + rating: number; + reviews: number; +}; + +export type SocialCafeReview = { + id: string; + cafeId: string; + author: string; + score: number; + text: string; + photoNote?: string; + at: string; +}; + +export type SocialMeetup = { + id: string; + title: string; + city: string; + date: string; + time: string; + mode: "online" | "hybrid"; + mirotalkRoom: string; + timeZone?: string; + channelId: string; +}; + +export type SocialVideo = { + id: string; + title: string; + city: string; + minutes: number; + coverEmoji: string; + summary: string; +}; + +export type SocialEbook = { + id: string; + title: string; + chapters: number; + minutes: number; + blurb: string; +}; + +/** 远程团队岗位类型 */ +export type SocialTeamKind = "volunteer" | "parttime" | "fulltime"; + +export type SocialGig = { + id: string; + title: string; + role: string; + pay: string; + remote: boolean; + tags: string[]; + /** 远程团队:志愿者 / 兼职 / 全职 */ + kind?: SocialTeamKind; +}; + +export type SocialRosterProfile = { + name: string; + title: string; + city: string; + phone: string; + linktree: string; + skills: string; + bio: string; + updatedAt?: string; +}; diff --git a/apps/miniprogram/h5/src/hooks/useSocialChat.ts b/apps/miniprogram/h5/src/hooks/useSocialChat.ts new file mode 100644 index 0000000..a0e4cfe --- /dev/null +++ b/apps/miniprogram/h5/src/hooks/useSocialChat.ts @@ -0,0 +1,209 @@ +/** + * 群组聊天:HTTP 拉历史/发消息 + Centrifugo WebSocket 实时。 + * 无假消息;离线时本地队列可重试,UI 标明状态。 + */ +import { useCallback, useEffect, useRef, useState } from 'react' +import Taro from '@tarojs/taro' +import { + getSocialGuestId, + socialApi, + type SocialChatMessage, +} from '@/services/socialApi' +import { connectChatRealtime } from '@/services/socialRealtime' + +export type ChatLinkStatus = 'connecting' | 'live' | 'polling' | 'offline' + +const NICK_KEY = 'nick' + +export function useSocialChat(channelId: string) { + const [messages, setMessages] = useState([]) + const [draft, setDraft] = useState('') + const [nick, setNick] = useState(() => { + try { + return String(Taro.getStorageSync(NICK_KEY) || '游民') + } catch { + return '游民' + } + }) + const [status, setStatus] = useState('connecting') + const [sending, setSending] = useState(false) + const lock = useRef(false) + const mounted = useRef(true) + const guest = getSocialGuestId() + + const mergeRemote = useCallback((items: SocialChatMessage[]) => { + setMessages((current) => { + const pendingMine = current.filter( + (m) => m.mine && (m.delivery === 'local' || m.delivery === 'pending'), + ) + const remote = items.map((item) => ({ + ...item, + mine: item.guestId === guest, + delivery: 'sent' as const, + })) + const ids = new Set(remote.map((m) => m.id)) + return [ + ...remote, + ...pendingMine.filter((m) => !ids.has(m.id)), + ].slice(-300) + }) + }, [guest]) + + useEffect(() => { + mounted.current = true + let cancelled = false + let stopWs: (() => void) | null = null + let refreshing = false + + const refresh = async () => { + if (cancelled || refreshing) return + refreshing = true + try { + const res = await socialApi.listMessages(channelId) + if (cancelled) return + mergeRemote(res.items || []) + setStatus((s) => (s === 'live' ? 'live' : 'polling')) + } catch { + if (!cancelled) setStatus((s) => (s === 'live' ? 'live' : 'offline')) + } finally { + refreshing = false + } + } + + setMessages([]) + setStatus('connecting') + void refresh() + + const poll = setInterval(() => void refresh(), 8000) + + void connectChatRealtime(channelId, (item) => { + if (cancelled) return + setMessages((current) => { + if (current.some((m) => m.id === item.id)) return current + return [ + ...current, + { + ...item, + mine: item.guestId === guest, + delivery: 'sent', + }, + ].slice(-300) + }) + setStatus('live') + }).then((conn) => { + if (cancelled) { + conn?.disconnect() + return + } + if (conn) { + stopWs = conn.disconnect + setStatus('live') + } else { + setStatus((s) => (s === 'offline' ? 'offline' : 'polling')) + } + }) + + return () => { + cancelled = true + mounted.current = false + clearInterval(poll) + stopWs?.() + } + }, [channelId, guest, mergeRemote]) + + const send = useCallback(async () => { + const text = draft.trim() + if (!text || text.length > 2000 || lock.current) return false + lock.current = true + setSending(true) + const author = nick.trim() || '游民' + const tempId = `local_${Date.now()}` + setMessages((current) => + [ + ...current, + { + id: tempId, + channelId, + author, + text, + at: new Date().toISOString(), + guestId: guest, + mine: true, + delivery: 'pending', + }, + ].slice(-300), + ) + setDraft('') + try { + Taro.setStorageSync(NICK_KEY, author) + const saved = await socialApi.sendMessage(channelId, author, text) + if (!mounted.current) return true + setMessages((current) => + [ + ...current.filter((m) => m.id !== tempId && m.id !== saved.id), + { + ...saved, + mine: true, + guestId: guest, + delivery: 'sent', + }, + ].slice(-300), + ) + return true + } catch { + if (!mounted.current) return false + setMessages((current) => + current.map((m) => + m.id === tempId ? { ...m, delivery: 'local' as const } : m, + ), + ) + setStatus('offline') + Taro.showToast({ title: '发送失败,已留在本地', icon: 'none' }) + return false + } finally { + lock.current = false + if (mounted.current) setSending(false) + } + }, [channelId, draft, guest, nick]) + + const retryLocal = useCallback( + async (id: string) => { + const item = messages.find((m) => m.id === id && m.delivery === 'local') + if (!item || lock.current) return + lock.current = true + setSending(true) + try { + const saved = await socialApi.sendMessage( + channelId, + item.author, + item.text, + ) + setMessages((current) => + [ + ...current.filter((m) => m.id !== id && m.id !== saved.id), + { ...saved, mine: true, guestId: guest, delivery: 'sent' }, + ].slice(-300), + ) + setStatus((s) => (s === 'offline' ? 'polling' : s)) + } catch { + Taro.showToast({ title: '仍失败,稍后重试', icon: 'none' }) + } finally { + lock.current = false + setSending(false) + } + }, + [channelId, guest, messages], + ) + + return { + messages, + draft, + setDraft, + nick, + setNick, + status, + sending, + send, + retryLocal, + } +} diff --git a/apps/miniprogram/h5/src/pages/home/index.tsx b/apps/miniprogram/h5/src/pages/home/index.tsx index 2912fa4..c3421c9 100644 --- a/apps/miniprogram/h5/src/pages/home/index.tsx +++ b/apps/miniprogram/h5/src/pages/home/index.tsx @@ -18,7 +18,7 @@ import { usePageShare, markPageShare } from '@/utils/pageShare' import { safePx, useSafeAreaMetrics } from '@/utils/safeArea' import { usePageTrack } from '@/hooks/usePageTrack' import './index.scss' -type PortalId = 'nav' | 'book' | 'community' | 'vip' +type PortalId = 'nav' | 'book' | 'community' | 'social' | 'vip' type Portal = { id: PortalId @@ -31,13 +31,15 @@ type Portal = { const PORTALS: Portal[] = [ { id: 'nav', moduleKey: 'nav', emoji: '🧭', name: '出海导航', main: false }, { id: 'book', moduleKey: 'book', emoji: '📖', name: '数字游民', main: false }, - { id: 'community', moduleKey: 'community', emoji: '🌏', name: '旅居社群', main: true }, + { id: 'social', moduleKey: 'social', emoji: '💕', name: '游民社区', main: true }, + { id: 'community', moduleKey: 'community', emoji: '🌏', name: '旅居社群', main: false }, ] const INTERNAL_PORTALS: Record = { nav: '/pages/nav/index', book: '/pages/book/index', community: '/pages/community/index', + social: '/pages/social/index', vip: '/pages/vip/index', } diff --git a/apps/miniprogram/h5/src/pages/social/_components/AttractiveRoster.tsx b/apps/miniprogram/h5/src/pages/social/_components/AttractiveRoster.tsx new file mode 100644 index 0000000..7452fa9 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/AttractiveRoster.tsx @@ -0,0 +1,119 @@ +import { useMemo, useState } from 'react' +import { MOCK_ROSTER } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { SocialAvatar } from './SocialAvatar' +import { PeopleChip } from './PeopleChip' +import { H5El } from './H5El' + +const FILTERS = [ + { id: 'all' as const, label: '全部', emoji: '✨' }, + { id: 'online' as const, label: '在线', emoji: '🟢' }, + { id: 'f' as const, label: '女生', emoji: '👩' }, + { id: 'm' as const, label: '男生', emoji: '👨' }, +] + +export function AttractiveRoster({ onJoin }: { onJoin: () => void }) { + const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm'>('all') + const [likes, setLikes] = useState>({}) + + const list = useMemo(() => { + return MOCK_ROSTER.filter((m) => { + if (filter === 'online') return m.online + if (filter === 'f' || filter === 'm') return m.gender === filter + return true + }) + }, [filter]) + + const online = useMemo(() => MOCK_ROSTER.filter((m) => m.online), []) + + return ( + + + + + 看看谁在这儿 + 点开认识 + + + + 👋 + + 想见的人 + + + 点开卡片,看看对方在做什么、想认识谁。现在是示例介绍,方便你先逛逛。 + + + + + + {online.slice(0, 6).map((m) => ( + + ))} + + + + {online.length} + {' '} + 位现在在线 + · 示例数据 + + + 加入社区 + + + + + {FILTERS.map((f) => ( + setFilter(f.id)} + > + {f.emoji} {f.label} + + ))} + + + + {list.map((m, i) => ( + + setLikes((prev) => ({ ...prev, [m.id]: !prev[m.id] })) + } + /> + ))} + + + + 👆 点卡片看看详情,也可以先点爱心关注 + + + + goPage('/pages/social/people/index')} + > + 看全部 + + goPage('/pages/social/date/index')} + > + 开始认识 ↗ + + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/ConnectionHero.tsx b/apps/miniprogram/h5/src/pages/social/_components/ConnectionHero.tsx new file mode 100644 index 0000000..710084a --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/ConnectionHero.tsx @@ -0,0 +1,376 @@ +import { useState, type CSSProperties } from 'react' +import { Video } from '@tarojs/components' +import Taro from '@tarojs/taro' +import { MOCK_ROSTER, SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { SocialAvatar } from './SocialAvatar' +import { FloatingEmojiField } from './SocialExperience' +import { H5El } from './H5El' + +const NODES = [ + { member: 0, x: 22, y: 22, rotate: -8 }, + { member: 1, x: 79, y: 26, rotate: 7 }, + { member: 4, x: 85, y: 65, rotate: -6 }, + { member: 3, x: 18, y: 69, rotate: 6 }, +] + +const ORBIT_SVG = `` + +const isH5 = process.env.TARO_ENV === 'h5' + +export function ConnectionHero({ + onJoin, + promoUrl, + copy = SOCIAL_COPY, +}: { + onJoin: () => void + promoUrl: string + copy?: SocialLandingCopy +}) { + const [videoOpen, setVideoOpen] = useState(false) + + return ( + + + + + + + 游民社区{' '} + {copy.socialEyebrow} + + + + {copy.socialHeroLine1} + + + 还好 + + {copy.socialHeroAccent} + + 不远 + + 。 + + + + + {copy.socialHeroLead} + + + + {copy.socialJoinCta} ↗ + + goPage('/pages/social/chat/index')} + trackLabel='social_film_chat' + > + 💬 + 群组聊天 + + goPage('/pages/social/date/index')} + trackLabel='social_film_date' + > + 💕 + 认识一下 + + setVideoOpen(true)} + trackLabel='social_film_story' + > + ▶ + 社区故事 + + + + + {MOCK_ROSTER.slice(0, 5).map((m) => ( + + ))} + + + 同频的人,正在这里相遇 + 自由职业 · 远程工作 · 出来见一面 + + + + + + + 🌐 + 不止在线,更在身边 + + + + + + + + + {isH5 ? ( + + ) : null} + + + ✨ + + 同频,自有引力 + 想见的人 + + {NODES.map(({ member, x, y, rotate }, i) => { + const m = MOCK_ROSTER[member]! + const style = { + ['--node-x' as string]: `${x}%`, + ['--node-y' as string]: `${y}%`, + ['--node-rotate' as string]: `${rotate}deg`, + ['--node-delay' as string]: `${i * -1.4}s`, + } as CSSProperties + return ( + goPage('/pages/social/people/index')} + aria-label={`认识${m.name},${m.title}`} + > + + + + + + + {m.name} + ↗ + + {m.title} + {m.city.split('·')[0]?.trim()} + + + ) + })} + + 18.79° N · 清迈 + + + 25.60° N · 大理 + + + ☕ + 下一杯咖啡,和新朋友。 + ↗ + + + + + 连接没有边界 + + 先用示例看看感觉 + + + + + + { + if (process.env.TARO_ENV === 'h5' && typeof document !== 'undefined') { + document.getElementById('people')?.scrollIntoView({ behavior: 'smooth' }) + } else { + const query = Taro.createSelectorQuery() + query.select('#people').boundingClientRect() + query.selectViewport().scrollOffset() + query.exec((res) => { + const rect = res?.[0] as { top?: number } | undefined + const offset = res?.[1] as { scrollTop?: number } | undefined + if (!rect || typeof rect.top !== 'number') return + Taro.pageScrollTo({ + scrollTop: Math.max(0, (offset?.scrollTop || 0) + rect.top - 72), + duration: 300, + }) + }) + } + }} + > + ↓ 继续往下看 + + 认识人 · 开视频 · 见一面 + + + {videoOpen ? ( + setVideoOpen(false)} + > + undefined} + > + + 游民社区 · 社区故事 + setVideoOpen(false)} aria-label='关闭'> + ✕ + + + + + ) : null} + + ) +} + +export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCopy }) { + const ways = [ + { + id: '01', + path: '/pages/social/chat/index', + emoji: '💬', + title: copy.socialWayGroup, + sub: '大家一起聊 · 先打个招呼', + cta: '进群聊', + className: 'mint', + }, + { + id: '02', + path: '/pages/social/date/index', + emoji: '💕', + title: copy.socialWayDate, + sub: '左右滑,慢慢认识', + cta: '开始看看', + className: 'coral', + }, + { + id: '03', + path: '/pages/social/meetup/index', + emoji: '📡', + title: copy.socialWayChat, + sub: '聊天群组 · 语音视频', + cta: '去聊聊', + className: 'mint', + }, + { + id: '04', + path: '/pages/social/people/index?mode=cafe', + emoji: '☕', + title: copy.socialWayCafe, + sub: copy.socialOfflineTitle, + cta: '选城市', + className: 'yellow', + }, + { + id: '05', + path: '/pages/social/team/index', + emoji: '🚀', + title: copy.socialWayTeam, + sub: copy.socialTeamTitle, + cta: '看看机会', + className: 'mint', + }, + ] + + return ( + + {ways.map((way, index) => ( + goPage(way.path)} + trackLabel={`social_way_${way.id}`} + > + + {way.id} + + + + {way.emoji} + + + + {way.title} + {way.sub} + {way.cta} + + + ↗ + + + ))} + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/H5El.tsx b/apps/miniprogram/h5/src/pages/social/_components/H5El.tsx new file mode 100644 index 0000000..e4c0cab --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/H5El.tsx @@ -0,0 +1,132 @@ +import type { + CSSProperties, + HTMLAttributes, + ReactNode, + ElementType, +} from 'react' +import { Text, View } from '@tarojs/components' +import { trackClick } from '@/utils/track' + +const isH5 = process.env.TARO_ENV === 'h5' + +type Props = { + as?: ElementType + className?: string + id?: string + children?: ReactNode + style?: CSSProperties + onClick?: (e?: any) => void + trackLabel?: string + href?: string + htmlFor?: string + type?: string + role?: string + 'aria-label'?: string + 'aria-hidden'?: boolean | 'true' | 'false' + 'aria-current'?: string + 'aria-selected'?: boolean | 'true' | 'false' + 'aria-labelledby'?: string + 'data-theme'?: string + dangerouslySetInnerHTML?: { __html: string } +} & Omit< + HTMLAttributes, + | 'onClick' + | 'className' + | 'style' + | 'children' + | 'dangerouslySetInnerHTML' + | 'aria-current' + | 'aria-selected' + | 'aria-labelledby' +> + +/** + * H5: real semantic tags so Next /social CSS selectors (h1/strong/small/em/a/nav…) match 1:1. + * Mini program: View/Text fallback. + */ +export function H5El({ + as = 'div', + className, + id, + children, + style, + onClick, + trackLabel, + href, + type, + role, + 'aria-label': ariaLabel, + 'aria-hidden': ariaHidden, + 'aria-current': ariaCurrent, + 'aria-selected': ariaSelected, + 'aria-labelledby': ariaLabelledby, + 'data-theme': dataTheme, + dangerouslySetInnerHTML, + ...rest +}: Props) { + const handleClick = onClick + ? (e?: any) => { + if (trackLabel) trackClick(trackLabel) + onClick(e) + } + : trackLabel + ? () => trackClick(trackLabel) + : undefined + + if (isH5) { + const Tag = as as ElementType + const clickProps = + Tag === 'a' + ? { + href: href || '#', + onClick: (e: any) => { + if (handleClick) { + e.preventDefault() + handleClick(e) + } + }, + } + : Tag === 'button' + ? { type: type || 'button', onClick: handleClick } + : handleClick + ? { onClick: handleClick } + : {} + + return ( + + {dangerouslySetInnerHTML ? undefined : children} + + ) + } + + const tag = typeof as === 'string' ? as : 'div' + const Mini = + tag === 'span' || + tag === 'strong' || + tag === 'small' || + tag === 'em' || + tag === 'i' + ? Text + : View + // weapp 无语义标签:补 as-* class,方便 CSS 用 .as-i / .as-h1 对齐 Next 选择器 + const miniClass = [className, `as-${tag}`].filter(Boolean).join(' ') + return ( + + {children} + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/JoinPaySheet.scss b/apps/miniprogram/h5/src/pages/social/_components/JoinPaySheet.scss new file mode 100644 index 0000000..985fb2c --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/JoinPaySheet.scss @@ -0,0 +1,140 @@ +/* 加群底栏:rem + 全宽,禁止裸 px(weapp 750 会缩水) */ +.social-join-sheet-mask { + position: fixed; + inset: 0; + z-index: 1300; + display: flex; + align-items: flex-end; + justify-content: center; + background: rgba(0, 0, 0, 0.62); + box-sizing: border-box; +} + +.social-join-sheet-panel { + position: relative; + z-index: 1; + width: 100%; + max-width: none; + border-radius: 1.25rem 1.25rem 0 0; + border: 1px solid rgba(255, 255, 255, 0.08); + border-bottom: none; + background: rgba(12, 12, 15, 0.98); + padding: 0.5rem 1.25rem calc(1.35rem + env(safe-area-inset-bottom, 0px)); + box-shadow: 0 -12px 40px rgba(0, 0, 0, 0.45); + box-sizing: border-box; +} + +.social-join-sheet-handle { + width: 2.25rem; + height: 0.25rem; + border-radius: 99px; + background: rgba(255, 255, 255, 0.2); + margin: 0.2rem auto 0.85rem; +} + +.social-join-sheet-head { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 2.75rem; + margin-bottom: 0.35rem; +} + +.social-join-brand { + font-size: 0.85rem; + color: #f59e0b; + font-weight: 650; +} + +.social-join-sheet-close { + width: 2.75rem; + height: 2.75rem; + border-radius: 0.65rem; + display: flex; + align-items: center; + justify-content: center; + color: #94a3b8; + background: transparent; + border: none; + font-size: 1.1rem; +} + +.social-join-sheet-title { + margin: 0 0 0.4rem; + font-size: 1.45rem; + font-weight: 750; + color: #f1f5f9; + letter-spacing: -0.02em; +} + +.social-join-sheet-lead { + margin: 0 0 1rem; + font-size: 0.88rem; + line-height: 1.45; + color: #94a3b8 !important; +} + +.social-join-price { + display: flex; + align-items: baseline; + gap: 0.65rem; + margin-bottom: 1rem; + padding: 0.85rem 1rem; + border-radius: 0.85rem; + background: rgba(245, 158, 11, 0.08); + border: 1px solid rgba(245, 158, 11, 0.22); +} + +.social-join-price strong { + font-size: 1.65rem; + color: #f59e0b; + font-weight: 800; +} + +.social-join-price span { + font-size: 0.78rem; + color: #94a3b8; +} + +.social-join-field { + display: flex; + flex-direction: column; + gap: 0.4rem; + margin-bottom: 0.75rem; + font-size: 0.82rem; + color: #94a3b8; +} + +.social-join-input { + width: 100%; + min-height: 2.75rem; + padding: 0 0.9rem; + border-radius: 0.75rem; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: #f1f5f9; + font-size: 1rem; + box-sizing: border-box; +} + +.social-join-err { + margin: 0 0 0.65rem; + color: #f87171; + font-size: 0.82rem; +} + +.social-join-sheet-submit { + width: 100%; + min-height: 2.85rem; + margin-top: 0.25rem; + border-radius: 0.85rem; + font-size: 1rem; + font-weight: 700; +} + +.social-join-privacy { + margin: 0.75rem 0 0; + font-size: 0.72rem; + color: #64748b; + text-align: center; +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/JoinPaySheet.tsx b/apps/miniprogram/h5/src/pages/social/_components/JoinPaySheet.tsx new file mode 100644 index 0000000..bf4fd89 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/JoinPaySheet.tsx @@ -0,0 +1,164 @@ +import { useEffect, useState } from 'react' +import { Input } from '@tarojs/components' +import Taro from '@tarojs/taro' +import { H5El } from './H5El' +import { + fetchSocialJoinStatus, + isSocialJoinLocal, + paySocialJoin, +} from '@/utils/socialJoinPay' +import './JoinPaySheet.scss' + +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ +const EMAIL_KEY = 'userEmail' + +type Props = { + open: boolean + onClose: () => void + onPaid?: () => void +} + +/** + * 加群收费底栏 — 微信虚拟支付(social-join),不是 VIP / community。 + * rem + 全宽底栏,避免 designWidth:750 缩水。 + */ +export function JoinPaySheet({ open, onClose, onPaid }: Props) { + const [email, setEmail] = useState('') + const [busy, setBusy] = useState(false) + const [err, setErr] = useState('') + const [priceLabel, setPriceLabel] = useState('¥49') + const [already, setAlready] = useState(false) + + useEffect(() => { + if (!open) return + try { + setEmail(String(Taro.getStorageSync(EMAIL_KEY) || '')) + } catch { + setEmail('') + } + setErr('') + setBusy(false) + setAlready(isSocialJoinLocal()) + void fetchSocialJoinStatus().then((s) => { + if (!s) return + if (s.isMember) setAlready(true) + if (s.priceFen > 0) setPriceLabel(`¥${(s.priceFen / 100).toFixed(0)}`) + }) + }, [open]) + + if (!open) return null + + const submit = async () => { + if (busy) return + if (already) { + onClose() + return + } + const value = email.trim().toLowerCase() + if (!EMAIL_RE.test(value)) { + setErr('请输入有效邮箱') + return + } + setErr('') + setBusy(true) + try { + Taro.setStorageSync(EMAIL_KEY, value) + Taro.setStorageSync('userName', value.split('@')[0] || '游民') + await paySocialJoin() + setAlready(true) + Taro.showToast({ title: '已加入游民社区', icon: 'success' }) + onPaid?.() + onClose() + } catch (e) { + const msg = String((e as Error)?.message || e || '') + if (/取消|cancel/i.test(msg)) { + setErr('') + } else { + setErr(msg || '支付唤起失败,请稍后重试') + } + } finally { + setBusy(false) + } + } + + return ( + !busy && onClose()}> + { + e?.stopPropagation?.() + }} + > + + + + ✨ 游民社区 · 加群 + + !busy && onClose()} + > + ✕ + + + + + {already ? '你已在群里' : '加入游民社区'} + + + {already + ? '认识同频 · 开视频 · 找搭子,直接去逛就好。' + : `认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事`} + + + {!already ? ( + <> + + {priceLabel} + 一次性加群 · 非 VIP 会员 + + + 邮箱 + setEmail(e.detail.value)} + /> + + {err ? ( + + {err} + + ) : null} + void submit()} + > + {busy ? '正在唤起支付…' : `确认并支付 ${priceLabel}`} + + + 🔒 邮箱用于账号识别 · 微信小程序虚拟支付 + + + ) : ( + + 好的,继续逛 + + )} + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/PeopleChip.tsx b/apps/miniprogram/h5/src/pages/social/_components/PeopleChip.tsx new file mode 100644 index 0000000..0d3b0fa --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/PeopleChip.tsx @@ -0,0 +1,71 @@ +import type { SocialRosterMember } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { SocialAvatar } from './SocialAvatar' +import { H5El } from './H5El' + +/** Align with Next AttractiveRoster: 点卡片进个人详情(非 date 左右滑) */ +export function PeopleChip({ + member, + liked, + onToggleLike, + staggerMs = 0, + href, +}: { + member: SocialRosterMember + liked?: boolean + onToggleLike?: () => void + staggerMs?: number + href?: string +}) { + const city = member.city.split('·')[0]?.trim() || member.city + const to = + href || + `/pages/social/people/profile/index?id=${encodeURIComponent(member.id)}` + return ( + goPage(to)} + > + + + {member.online ? : null} + {liked ? ( + + ♥ + + ) : null} + + + {member.name} + {member.online ? ' · 在线' : ''} + + + {member.title} + {member.vibe ? ` · ${member.vibe.split('·')[0].trim()}` : ''} + + + {city} + {member.tags[0] ? ` · ${member.tags[0]}` : ''} + + + {member.lookingFor} + + {onToggleLike ? ( + { + e?.stopPropagation?.() + onToggleLike() + }} + > + {liked ? '♥' : '♡'} + + ) : null} + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/SocialAvatar.tsx b/apps/miniprogram/h5/src/pages/social/_components/SocialAvatar.tsx new file mode 100644 index 0000000..865ced4 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/SocialAvatar.tsx @@ -0,0 +1,49 @@ +import type { CSSProperties } from 'react' +import { Image } from '@tarojs/components' + +const isH5 = process.env.TARO_ENV === 'h5' + +export function SocialAvatar({ + src, + size = 40, + className = '', +}: { + src: string + size?: number + className?: string +}) { + const style: CSSProperties = { + width: size, + height: size, + borderRadius: '999px', + display: 'block', + objectFit: 'cover', + flexShrink: 0, + background: '#1a1d24', + } + + if (isH5) { + return ( + // eslint-disable-next-line jsx-a11y/alt-text + + ) + } + + return ( + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/SocialDock.tsx b/apps/miniprogram/h5/src/pages/social/_components/SocialDock.tsx new file mode 100644 index 0000000..0a3edb4 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/SocialDock.tsx @@ -0,0 +1,55 @@ +import { useMemo } from 'react' +import Taro, { useRouter } from '@tarojs/taro' +import { SOCIAL_DOCK } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { H5El } from './H5El' + +function normalize(path: string) { + const raw = (path || '').split('?')[0] + if (!raw) return '' + return raw.startsWith('/') ? raw : `/${raw}` +} + +export function SocialDock() { + const router = useRouter() + const current = useMemo(() => { + const fromRouter = normalize(router?.path || '') + if (fromRouter) return fromRouter + try { + const pages = Taro.getCurrentPages() + const last = pages[pages.length - 1] as { route?: string } | undefined + return normalize(last?.route ? `/${last.route}` : '') + } catch { + return '' + } + }, [router?.path]) + + return ( + + {SOCIAL_DOCK.map((item) => { + const target = normalize(item.path) + const active = + item.match === 'exact' + ? current === target || /\/pages\/social\/index$/.test(current) + : current.startsWith(target.replace(/\/index$/, '')) || + current === target + return ( + goPage(item.path)} + trackLabel={`social_dock_${item.short}`} + > + + {item.emoji} + + {item.short} + + ) + })} + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/_components/SocialExperience.tsx b/apps/miniprogram/h5/src/pages/social/_components/SocialExperience.tsx new file mode 100644 index 0000000..0e95661 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/SocialExperience.tsx @@ -0,0 +1,266 @@ +import { + useEffect, + useRef, + useState, + type CSSProperties, + type ReactNode, +} from 'react' +import { H5El } from './H5El' + +const isH5 = process.env.TARO_ENV === 'h5' + +function Constellation({ active }: { active: boolean }) { + const canvasRef = useRef(null) + + useEffect(() => { + if (!isH5 || !active) return + const canvas = canvasRef.current + const context = canvas?.getContext('2d') + if (!canvas || !context) return + + const media = window.matchMedia('(prefers-reduced-motion: reduce)') + let frame = 0 + let width = 0 + let height = 0 + let last = 0 + let pointer = { x: -1000, y: -1000 } + let points: { + x: number + y: number + vx: number + vy: number + r: number + color: string + }[] = [] + + const resize = () => { + width = Math.max( + window.innerWidth || 0, + document.documentElement.clientWidth || 0, + window.visualViewport?.width || 0, + ) + height = Math.max( + window.innerHeight || 0, + document.documentElement.clientHeight || 0, + window.visualViewport?.height || 0, + ) + const ratio = Math.min(window.devicePixelRatio || 1, 1.5) + canvas.style.width = `${width}px` + canvas.style.height = `${height}px` + canvas.width = Math.floor(width * ratio) + canvas.height = Math.floor(height * ratio) + context.setTransform(ratio, 0, 0, ratio, 0, 0) + points = Array.from({ length: width < 700 ? 28 : 52 }, (_, i) => ({ + x: Math.random() * width, + y: Math.random() * height, + vx: (Math.random() - 0.5) * 0.28, + vy: (Math.random() - 0.5) * 0.28, + r: 0.9 + Math.random() * 1.4, + color: ['78,205,196', '255,107,107', '255,230,109'][i % 3]!, + })) + } + + const draw = (time: number) => { + if (document.hidden || media.matches) return + const delta = Math.min((time - last) / 16.67 || 1, 2) + last = time + context.clearRect(0, 0, width, height) + points.forEach((p, index) => { + p.x = (p.x + p.vx * delta + width) % width + p.y = (p.y + p.vy * delta + height) % height + const near = Math.hypot(pointer.x - p.x, pointer.y - p.y) < 240 + context.beginPath() + context.arc(p.x, p.y, p.r, 0, Math.PI * 2) + context.fillStyle = `rgba(${p.color},${near ? 0.55 : 0.28})` + context.fill() + if (near) { + context.beginPath() + context.arc(p.x, p.y, p.r + 4, 0, Math.PI * 2) + context.fillStyle = `rgba(${p.color},0.1)` + context.fill() + } + if (width > 700) { + points.slice(index + 1).forEach((q) => { + const distance = Math.hypot(q.x - p.x, q.y - p.y) + if (distance > 140) return + context.beginPath() + context.moveTo(p.x, p.y) + context.lineTo(q.x, q.y) + context.strokeStyle = `rgba(78,205,196,${(1 - distance / 140) * 0.16})` + context.lineWidth = 1.05 + context.stroke() + }) + } + }) + frame = requestAnimationFrame(draw) + } + + const restart = () => { + cancelAnimationFrame(frame) + last = 0 + context.clearRect(0, 0, width, height) + if (!document.hidden && !media.matches) { + frame = requestAnimationFrame(draw) + } + } + + const move = (event: PointerEvent) => { + if (event.pointerType === 'mouse') { + pointer = { x: event.clientX, y: event.clientY } + } + } + + resize() + restart() + window.addEventListener('resize', resize) + window.addEventListener('pointermove', move, { passive: true }) + document.addEventListener('visibilitychange', restart) + media.addEventListener('change', restart) + return () => { + cancelAnimationFrame(frame) + window.removeEventListener('resize', resize) + window.removeEventListener('pointermove', move) + document.removeEventListener('visibilitychange', restart) + media.removeEventListener('change', restart) + context.clearRect(0, 0, width, height) + } + }, [active]) + + if (!isH5) return null + return ( + + ) +} + +function FloatingEmojiField() { + const EMOJIS = [ + { e: '☕', x: '8%', y: '22%', delay: '0s', dur: '9s', size: '1.1rem' }, + { e: '🌏', x: '88%', y: '20%', delay: '1.2s', dur: '11s', size: '1.15rem' }, + { e: '✨', x: '78%', y: '62%', delay: '2.4s', dur: '10s', size: '0.95rem' }, + { e: '💬', x: '14%', y: '68%', delay: '0.8s', dur: '12s', size: '1rem' }, + { e: '🚀', x: '52%', y: '12%', delay: '3s', dur: '10.5s', size: '0.9rem' }, + ] + return ( + + {EMOJIS.map((item) => ( + + {item.e} + + ))} + + ) +} + +export function FxBelt() { + const ROW = ['☕', '🌏', '💬', '✨', '📡', '🚀'] + const line = [...ROW, ...ROW, ...ROW].join(' ') + return ( + + + {line} + {line} + + + ) +} + +export function SocialExperience({ + children, + showEmojiField = false, +}: { + children: ReactNode + showEmojiField?: boolean +}) { + const [immersive, setImmersive] = useState(true) + const rootRef = useRef(null) + + useEffect(() => { + if (!isH5 || !immersive) return + const root = rootRef.current + if (!root) return + let frame = 0 + const move = (event: PointerEvent) => { + if ( + event.pointerType !== 'mouse' || + window.matchMedia('(prefers-reduced-motion: reduce)').matches + ) { + return + } + cancelAnimationFrame(frame) + frame = requestAnimationFrame(() => { + root.style.setProperty('--pointer-x', `${event.clientX}px`) + root.style.setProperty('--pointer-y', `${event.clientY}px`) + const card = (event.target as Element).closest( + '.social-card, .social-list-item, .social-panel, .social-member-card, .social-person-card, .connection-way', + ) + if (card) { + const rect = card.getBoundingClientRect() + card.style.setProperty('--spot-x', `${event.clientX - rect.left}px`) + card.style.setProperty('--spot-y', `${event.clientY - rect.top}px`) + } + }) + } + root.addEventListener('pointermove', move, { passive: true }) + return () => { + cancelAnimationFrame(frame) + root.removeEventListener('pointermove', move) + } + }, [immersive]) + + // 微信禁止裸
/,否则整页黑屏;H5 才挂 pointer ref + if (!isH5) { + return ( + + {children} + + ) + } + + return ( +
+ + + + + + + + {showEmojiField ? : null} + {children} + setImmersive((v) => !v)} + aria-pressed={immersive} + title='切换视觉动效强度' + > + {immersive ? '✨' : '⚡'} + 动效 · {immersive ? '沉浸' : '轻量'} + +
+ ) +} + +export { FloatingEmojiField } diff --git a/apps/miniprogram/h5/src/pages/social/_components/social-subpage.scss b/apps/miniprogram/h5/src/pages/social/_components/social-subpage.scss new file mode 100644 index 0000000..c71e406 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/_components/social-subpage.scss @@ -0,0 +1,367 @@ +@import '../../../styles/page-rem.scss'; + +/* 子页公共:live-bar / body / 表单 / chat / date(微信强制可读,不靠 @media) */ +.soc-taro-root.social-weapp .social-live-bar, +.soc-taro-root.social-workspace .social-live-bar { + position: sticky; + top: 0; + z-index: 40; + padding: calc(var(--safe-status-bar, 0PX) + 8PX) 14PX 10PX; + background: rgba(10, 14, 23, 0.94); + border-bottom: 1PX solid rgba(255, 255, 255, 0.06); + backdrop-filter: blur(16PX); +} + +.soc-taro-root.social-weapp .social-live-bar-main, +.soc-taro-root.social-workspace .social-live-bar-main { + display: flex; + align-items: center; + gap: 10PX; + min-height: 44PX; + padding-right: var(--safe-menu-pad, 88PX); +} + +.soc-taro-root.social-weapp .social-nav-back, +.soc-taro-root.social-workspace .social-nav-back { + flex: 0 0 auto; + min-height: 40PX; + padding: 0 12PX; + border-radius: 999PX; + border: 1PX solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: #e2e8f0; + font-size: 13PX; +} + +.soc-taro-root.social-weapp .social-live-bar-main > .as-div, +.soc-taro-root.social-workspace .social-live-bar-main > view { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 2PX; +} + +.soc-taro-root.social-weapp .social-sub-body, +.soc-taro-root.social-workspace .social-sub-body { + padding-top: 14PX !important; + padding-bottom: 88PX !important; + padding-inline: 16PX !important; + box-sizing: border-box; +} + +.soc-taro-root.social-weapp .social-sub-block { + margin-bottom: 16PX; +} + +.soc-taro-root.social-weapp .social-muted, +.soc-taro-root.social-workspace .social-muted { + color: #64748b !important; + font-size: 12PX !important; +} + +/* —— 想见的人卡片(对齐 Next is-rich chip) —— */ +.soc-taro-root.social-weapp .social-people-filters, +.soc-taro-root.social-home .social-people-filters, +.soc-taro-root.social-workspace .social-people-filters { + display: flex !important; + flex-wrap: nowrap !important; + gap: 8PX !important; + margin-bottom: 14PX !important; + overflow-x: auto; +} + +.soc-taro-root.social-weapp .social-people-filter, +.soc-taro-root.social-home .social-people-filter, +.soc-taro-root.social-workspace .social-people-filter { + flex: 0 0 auto; + min-height: 40PX !important; + padding: 0 14PX !important; + border-radius: 999PX !important; + border: 1PX solid rgba(255, 255, 255, 0.08) !important; + background: rgba(255, 255, 255, 0.03) !important; + color: #94a3b8 !important; + font-size: 12PX !important; +} + +.soc-taro-root.social-weapp .social-people-filter.is-on, +.soc-taro-root.social-weapp .social-people-filter.active, +.soc-taro-root.social-home .social-people-filter.is-on, +.soc-taro-root.social-home .social-people-filter.active, +.soc-taro-root.social-workspace .social-people-filter.is-on, +.soc-taro-root.social-workspace .social-people-filter.active { + border-color: rgba(78, 205, 196, 0.4) !important; + background: rgba(78, 205, 196, 0.1) !important; + color: #4ecdc4 !important; +} + +.soc-taro-root.social-weapp .social-people-grid, +.soc-taro-root.social-home .social-people-grid, +.soc-taro-root.social-workspace .social-people-grid { + display: grid !important; + grid-template-columns: 1fr !important; + gap: 12PX !important; +} + +.soc-taro-root.social-weapp .social-people-chip, +.soc-taro-root.social-home .social-people-chip, +.soc-taro-root.social-workspace .social-people-chip { + position: relative !important; + display: grid !important; + grid-template-columns: 56PX 1fr !important; + grid-template-rows: auto auto auto auto !important; + column-gap: 12PX !important; + row-gap: 4PX !important; + align-items: start !important; + padding: 16PX 44PX 16PX 14PX !important; + border-radius: 18PX !important; + border: 1PX solid rgba(255, 255, 255, 0.1) !important; + background: linear-gradient(160deg, rgba(24, 32, 48, 0.95), rgba(12, 16, 26, 0.92)) !important; + box-shadow: 0 10PX 28PX rgba(0, 0, 0, 0.28) !important; + opacity: 1 !important; + transform: none !important; + animation: none !important; + box-sizing: border-box; +} + +.soc-taro-root.social-weapp .social-people-chip-ava, +.soc-taro-root.social-home .social-people-chip-ava, +.soc-taro-root.social-workspace .social-people-chip-ava { + grid-row: 1 / 3 !important; + grid-column: 1 !important; + width: 56PX !important; + height: 56PX !important; + position: relative; +} + +.soc-taro-root.social-weapp .social-people-chip .as-strong, +.soc-taro-root.social-home .social-people-chip .as-strong, +.soc-taro-root.social-workspace .social-people-chip .as-strong { + grid-column: 2 !important; + font-size: 15PX !important; + font-weight: 750 !important; + color: #f8fafc !important; + line-height: 1.3 !important; +} + +.soc-taro-root.social-weapp .social-people-chip .connection-member-role, +.soc-taro-root.social-home .social-people-chip .connection-member-role, +.soc-taro-root.social-workspace .social-people-chip .connection-member-role { + grid-column: 2 !important; + font-size: 12PX !important; + color: #94a3b8 !important; + line-height: 1.35 !important; +} + +.soc-taro-root.social-weapp .social-people-chip > .as-em, +.soc-taro-root.social-home .social-people-chip > .as-em, +.soc-taro-root.social-workspace .social-people-chip > .as-em { + grid-column: 1 / -1 !important; + font-size: 12PX !important; + font-style: normal !important; + color: #64748b !important; + margin-top: 2PX; +} + +.soc-taro-root.social-weapp .social-people-chip-want, +.soc-taro-root.social-home .social-people-chip-want, +.soc-taro-root.social-workspace .social-people-chip-want { + grid-column: 1 / -1 !important; + display: block !important; + margin-top: 2PX; + padding: 8PX 10PX; + border-radius: 12PX; + background: rgba(78, 205, 196, 0.08); + border: 1PX solid rgba(78, 205, 196, 0.16); + color: #b7f0ea !important; + font-size: 13PX !important; + line-height: 1.45 !important; + max-height: none !important; + overflow: visible !important; + -webkit-line-clamp: unset !important; +} + +.soc-taro-root.social-weapp .social-people-chip-like, +.soc-taro-root.social-home .social-people-chip-like, +.soc-taro-root.social-workspace .social-people-chip-like { + position: absolute !important; + top: 10PX !important; + right: 10PX !important; + width: 36PX !important; + height: 36PX !important; + min-height: 36PX !important; + border-radius: 999PX !important; + border: 0 !important; + background: rgba(255, 107, 107, 0.14) !important; + color: #ff8f8f !important; + font-size: 16PX !important; + display: inline-flex !important; + align-items: center; + justify-content: center; + padding: 0 !important; +} + +.soc-taro-root.social-weapp .social-people-chip.is-online .social-people-chip-ava::after, +.soc-taro-root.social-home .social-people-chip.is-online .social-people-chip-ava::after { + content: ''; + position: absolute; + right: 2PX; + bottom: 2PX; + width: 10PX; + height: 10PX; + border-radius: 50%; + background: #34d399; + border: 2PX solid #0c1018; +} + +.soc-taro-root.social-weapp .social-people-bar, +.soc-taro-root.social-home .social-people-bar { + display: grid !important; + grid-template-columns: auto 1fr !important; + gap: 8PX 12PX !important; + align-items: center !important; + margin-bottom: 16PX !important; + padding-bottom: 14PX !important; + border-bottom: 1PX solid rgba(255, 255, 255, 0.06) !important; +} + +.soc-taro-root.social-weapp .social-people-bar .btn, +.soc-taro-root.social-home .social-people-bar .btn { + grid-column: 1 / -1 !important; + justify-self: start; + min-height: 40PX !important; +} + +.soc-taro-root.social-weapp .social-people-bar-avs, +.soc-taro-root.social-home .social-people-bar-avs { + display: flex !important; +} + +.soc-taro-root.social-weapp .social-people-hint, +.soc-taro-root.social-home .social-people-hint { + margin: 12PX 0 0 !important; + font-size: 12PX !important; + color: #64748b !important; +} + +/* chat */ +.soc-taro-root.social-weapp .social-chat-layout, +.soc-taro-root.social-workspace .social-chat-layout { + display: flex !important; + flex-direction: column !important; + gap: 12PX !important; + padding-bottom: 88PX !important; +} + +.soc-taro-root.social-weapp .social-chat-sidebar, +.soc-taro-root.social-workspace .social-chat-sidebar { + display: flex !important; + flex-direction: row !important; + flex-wrap: nowrap !important; + gap: 8PX !important; + overflow-x: auto; + padding-bottom: 4PX; +} + +.soc-taro-root.social-weapp .social-chat-channel, +.soc-taro-root.social-workspace .social-chat-channel { + flex: 0 0 auto; + min-width: 140PX; + padding: 10PX 12PX !important; + border-radius: 14PX !important; + border: 1PX solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); +} + +.soc-taro-root.social-weapp .social-chat-channel.is-on, +.soc-taro-root.social-workspace .social-chat-channel.is-on { + border-color: rgba(78, 205, 196, 0.4); + background: rgba(78, 205, 196, 0.1); +} + +.soc-taro-root.social-weapp .social-chat-thread, +.soc-taro-root.social-workspace .social-chat-thread { + display: flex; + flex-direction: column; + gap: 10PX; + min-height: 280PX; + padding: 12PX; + border-radius: 16PX; + background: rgba(17, 24, 39, 0.7); + border: 1PX solid rgba(255, 255, 255, 0.06); +} + +.soc-taro-root.social-weapp .social-chat-compose, +.soc-taro-root.social-workspace .social-chat-compose { + display: flex; + gap: 8PX; + align-items: center; +} + +/* date */ +.soc-taro-root.social-weapp.social-date-root .social-date-stage, +.soc-taro-root.social-date-root .social-date-stage { + padding: 12PX 16PX 96PX; +} + +.soc-taro-root.social-weapp .social-date-deck, +.soc-taro-root.social-date-root .social-date-deck { + position: relative; + min-height: 420PX; +} + +.soc-taro-root.social-weapp .social-date-card-face, +.soc-taro-root.social-date-root .social-date-card-face { + border-radius: 22PX; + overflow: hidden; + border: 1PX solid rgba(255, 255, 255, 0.1); + background: #12141a; + box-shadow: 0 18PX 40PX rgba(0, 0, 0, 0.4); +} + +.soc-taro-root.social-weapp .social-date-card-body, +.soc-taro-root.social-date-root .social-date-card-body { + padding: 16PX; +} + +.soc-taro-root.social-weapp .social-date-actions, +.soc-taro-root.social-date-root .social-date-actions { + display: flex; + justify-content: center; + gap: 18PX; + margin-top: 18PX; +} + +.soc-taro-root.social-weapp .social-date-act, +.soc-taro-root.social-date-root .social-date-act { + width: 64PX; + height: 64PX; + border-radius: 999PX; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 24PX; + border: 1PX solid rgba(255, 255, 255, 0.12); + background: rgba(255, 255, 255, 0.06); +} + +.soc-taro-root.social-weapp .social-date-act.like, +.soc-taro-root.social-date-root .social-date-act.like { + background: rgba(255, 107, 107, 0.2); + border-color: rgba(255, 107, 107, 0.45); + color: #ff8f8f; +} + +/* roster form */ +.soc-taro-root.social-weapp .social-field-input, +.soc-taro-root.social-workspace .social-field-input { + width: 100%; + min-height: 44PX; + margin-top: 6PX; + padding: 10PX 12PX; + border-radius: 12PX; + border: 1PX solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: #f1f5f9; + box-sizing: border-box; +} diff --git a/apps/miniprogram/h5/src/pages/social/chat/index.config.ts b/apps/miniprogram/h5/src/pages/social/chat/index.config.ts new file mode 100644 index 0000000..60f59a3 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/chat/index.config.ts @@ -0,0 +1,7 @@ +export default definePageConfig({ + navigationBarTitleText: '游民大厅', + navigationBarBackgroundColor: '#0a0e17', + navigationBarTextStyle: 'white', + backgroundColor: '#0a0e17', + disableScroll: true, +}) diff --git a/apps/miniprogram/h5/src/pages/social/chat/index.scss b/apps/miniprogram/h5/src/pages/social/chat/index.scss new file mode 100644 index 0000000..04d14d6 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/chat/index.scss @@ -0,0 +1,199 @@ +@import '../../../styles/page-rem.scss'; + +/* 全屏单大厅 IM:无频道条、无侧栏、无底栏 Dock */ +.im-root { + display: flex; + flex-direction: column; + width: 100%; + height: 100vh; + height: 100dvh; + overflow: hidden; + box-sizing: border-box; + background: #0a0e17; + color: #f1f5f9; +} + +.im-status-row { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + padding: 0.45rem 0.75rem; + border-bottom: 1PX solid rgba(255, 255, 255, 0.06); +} + +.im-pill { + min-height: 1.6rem; + padding: 0 0.65rem; + border-radius: 999PX; + display: flex; + align-items: center; + font-size: 0.7rem; + background: rgba(255, 255, 255, 0.06); + color: #94a3b8; +} +.im-pill.is-live { + color: #042f2e; + background: rgba(78, 205, 196, 0.85); +} +.im-pill.is-polling { + color: #422006; + background: rgba(245, 158, 11, 0.85); +} +.im-pill.is-offline { + color: #fff; + background: rgba(244, 63, 94, 0.75); +} +.im-pill.is-connecting { + animation: im-pulse 1.2s ease-in-out infinite; +} + +@keyframes im-pulse { + 50% { + opacity: 0.45; + } +} + +.im-nick { + min-width: 5rem; + max-width: 8rem; + min-height: 2.2rem; + padding: 0 0.55rem; + border-radius: 0.55rem; + background: rgba(255, 255, 255, 0.06); + color: #e2e8f0; + font-size: 0.8rem; +} + +.im-thread { + flex: 1 1 auto; + min-height: 0; + height: 0; + width: 100%; + box-sizing: border-box; +} + +.im-list { + display: flex; + flex-direction: column; + gap: 0.7rem; + padding: 0.85rem 0.75rem 1.1rem; +} + +.im-row-wrap { + display: flex; + width: 100%; +} + +.im-empty { + padding: 18vh 1.25rem 2rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.45rem; + text-align: center; +} +.im-empty-title { + font-size: 1.05rem; + font-weight: 700; +} +.im-empty-desc { + max-width: 16rem; + font-size: 0.85rem; + line-height: 1.5; + color: #94a3b8; +} + +.im-bubble { + max-width: 84%; + padding: 0.7rem 0.85rem; + border-radius: 1rem 1rem 1rem 0.35rem; + background: rgba(30, 41, 59, 0.95); + border: 1PX solid rgba(255, 255, 255, 0.06); +} +.im-bubble.is-mine { + margin-left: auto; + border-radius: 1rem 1rem 0.35rem 1rem; + background: rgba(78, 205, 196, 0.2); + border-color: rgba(78, 205, 196, 0.35); +} +.im-bubble.is-fail { + border-style: dashed; + border-color: rgba(245, 158, 11, 0.6); +} + +.im-author { + display: block; + font-size: 0.7rem; + color: #94a3b8; + margin-bottom: 0.2rem; +} + +.im-text { + font-size: 0.95rem; + line-height: 1.55; + word-break: break-word; + white-space: pre-wrap; +} + +.im-meta { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + margin-top: 0.3rem; + font-size: 0.65rem; + color: #64748b; +} +.im-fail { + color: #fbbf24; +} + +.im-anchor { + height: 1PX; + width: 100%; +} + +.im-composer { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.55rem 0.75rem calc(0.55rem + env(safe-area-inset-bottom, 0PX)); + border-top: 1PX solid rgba(255, 255, 255, 0.08); + background: #080c14; +} + +.im-input { + flex: 1; + min-height: 2.75rem; + padding: 0 0.85rem; + border-radius: 0.9rem; + border: 1PX solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.06); + color: #f8fafc; + font-size: 1rem; + box-sizing: border-box; +} + +.im-send { + flex: 0 0 auto; + min-width: 4.25rem; + min-height: 2.75rem; + padding: 0 1rem; + border-radius: 999PX; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.08); + color: #64748b; + font-size: 0.9rem; + font-weight: 700; +} +.im-send.is-on { + background: linear-gradient(120deg, #f59e0b, #fbbf24); + color: #1c1003; +} +.im-send.is-busy { + opacity: 0.7; +} diff --git a/apps/miniprogram/h5/src/pages/social/chat/index.tsx b/apps/miniprogram/h5/src/pages/social/chat/index.tsx new file mode 100644 index 0000000..62cbaae --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/chat/index.tsx @@ -0,0 +1,200 @@ +import { useEffect, useState } from 'react' +import { Input, ScrollView, Text } from '@tarojs/components' +import Taro from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { H5Box } from '@/components/H5Box' +import { useSocialChat } from '@/hooks/useSocialChat' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import type { SocialChatMessage } from '@/services/socialApi' +import '@/styles/social-next/entry' +import '../_components/social-subpage.scss' +import './index.scss' + +/** 唯一总频道 */ +const LOBBY = 'general' + +function statusLabel(s: string) { + if (s === 'live') return '实时' + if (s === 'polling') return '同步中' + if (s === 'offline') return '离线' + return '连接中' +} + +function formatTime(iso?: string) { + if (!iso) return '' + const d = new Date(iso) + if (Number.isNaN(d.getTime())) return '' + return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}` +} + +function Bubble({ + m, + onRetry, +}: { + m: SocialChatMessage + onRetry: (id: string) => void +}) { + return ( + { + if (m.delivery === 'local') onRetry(m.id) + }} + > + {!m.mine ? ( + {m.author || '游民'} + ) : null} + {m.text} + + {formatTime(m.at)} + {m.delivery === 'pending' ? 发送中 : null} + {m.delivery === 'local' ? ( + 未送达 · 点重试 + ) : null} + {m.mine && m.delivery === 'sent' ? 已送达 : null} + + + ) +} + +function SocialChatLobby() { + usePageShare({ title: 'nomadro · 游民大厅', path: '/pages/social/chat/index' }) + usePageTrack('social_chat') + const { + messages, + draft, + setDraft, + nick, + setNick, + status, + sending, + send, + retryLocal, + } = useSocialChat(LOBBY) + + const [scrollInto, setScrollInto] = useState('') + const lastId = messages[messages.length - 1]?.id + + useEffect(() => { + try { + const q = Taro.getCurrentInstance().router?.params || {} + const raw = String(q.intro || '').trim() + if (!raw) return + setDraft((d) => d || decodeURIComponent(raw)) + } catch { + /* ignore */ + } + }, [setDraft]) + + useEffect(() => { + if (!lastId) return + const t = setTimeout(() => setScrollInto(`msg_${lastId}`), 48) + return () => clearTimeout(t) + }, [lastId, messages.length]) + + const canSend = Boolean(draft.trim()) && !sending + + const onSend = async () => { + if (!canSend) return + try { + Taro.vibrateShort({ type: 'light' }) + } catch { + /* ignore */ + } + const ok = await send() + if (ok) setScrollInto('chat_bottom') + } + + return ( + + + + {statusLabel(status)} + + setNick(e.detail.value)} + onBlur={() => { + const n = nick.trim() || '游民' + setNick(n) + try { + Taro.setStorageSync('nick', n) + } catch { + /* ignore */ + } + }} + /> + + + + {messages.length === 0 ? ( + + 游民大厅 + + {status === 'connecting' + ? '正在接入…' + : status === 'offline' + ? '暂时连不上,发出的消息会先留在本机' + : '还没有人说话,打个招呼吧'} + + + ) : ( + + {messages.map((m) => ( + + void retryLocal(id)} /> + + ))} + + + )} + + + + { + setTimeout(() => setScrollInto('chat_bottom'), 120) + }} + onInput={(e) => setDraft(e.detail.value)} + onConfirm={() => void onSend()} + /> + void onSend()} + > + {sending ? '…' : '发送'} + + + + ) +} + +export default function SocialChatPage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/date/index.config.ts b/apps/miniprogram/h5/src/pages/social/date/index.config.ts new file mode 100644 index 0000000..1d78544 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/date/index.config.ts @@ -0,0 +1,6 @@ +export default definePageConfig({ + navigationBarTitleText: '认识一下', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', +}) diff --git a/apps/miniprogram/h5/src/pages/social/date/index.scss b/apps/miniprogram/h5/src/pages/social/date/index.scss new file mode 100644 index 0000000..7f67876 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/date/index.scss @@ -0,0 +1 @@ +@import '../_components/social-subpage.scss'; diff --git a/apps/miniprogram/h5/src/pages/social/date/index.tsx b/apps/miniprogram/h5/src/pages/social/date/index.tsx new file mode 100644 index 0000000..d3397d7 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/date/index.tsx @@ -0,0 +1,393 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Text } from '@tarojs/components' +import Taro from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { H5Box } from '@/components/H5Box' +import { MOCK_ROSTER, type SocialRosterMember } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { SocialDock } from '../_components/SocialDock' +import { SocialExperience } from '../_components/SocialExperience' +import '@/styles/social-next/entry' +import './index.scss' + +type Filter = 'all' | 'f' | 'm' +type Decision = 'like' | 'pass' + +const THRESHOLD_DESKTOP = 110 +const THRESHOLD_MOBILE = 78 + +function shuffle(list: T[]) { + const next = [...list] + for (let i = next.length - 1; i > 0; i -= 1) { + const j = Math.floor(Math.random() * (i + 1)) + ;[next[i], next[j]] = [next[j]!, next[i]!] + } + return next +} + +function DateCardFace({ member }: { member: SocialRosterMember }) { + return ( + + + + + {member.name} + {member.online ? ' · 在线' : ''} + + + {member.title} · {member.city} + + + {member.bio} + + + {member.lookingFor} + + + {member.tags.map((t) => ( + {t} + ))} + + + + ) +} + +function SocialDate() { + usePageShare({ title: 'nomadro · 认识一下', path: '/pages/social/date/index' }) + usePageTrack('social_date') + const roster = MOCK_ROSTER + const [filter, setFilter] = useState('all') + const [swipes, setSwipes] = useState>({}) + const [history, setHistory] = useState<{ id: string; decision: Decision }[]>( + [], + ) + const [order, setOrder] = useState(() => + shuffle(roster.map((m) => m.id)), + ) + const [drag, setDrag] = useState({ x: 0, y: 0, active: false }) + const [fly, setFly] = useState(null) + const [likes, setLikes] = useState>({}) + const start = useRef({ x: 0, y: 0 }) + const dragging = useRef(false) + const dragRef = useRef({ x: 0, y: 0 }) + const busy = useRef(false) + + const deck = useMemo(() => { + const ids = [ + ...order, + ...roster.map((m) => m.id).filter((id) => !order.includes(id)), + ] + return ids + .map((id) => roster.find((m) => m.id === id)!) + .filter((m) => m && !swipes[m.id]) + .filter((m) => filter === 'all' || m.gender === filter) + }, [order, swipes, filter, roster]) + + const current = deck[0] || null + const next = deck[1] || null + const remaining = deck.length + const totalForFilter = roster.filter( + (m) => filter === 'all' || m.gender === filter, + ).length + + const commit = useCallback( + (member: SocialRosterMember, decision: Decision) => { + if (busy.current || fly) return + busy.current = true + setFly({ id: member.id, dir: decision }) + setTimeout(() => { + setSwipes((prev) => ({ ...prev, [member.id]: decision })) + setHistory((prev) => [...prev, { id: member.id, decision }]) + if (decision === 'like') { + setLikes((prev) => ({ ...prev, [member.id]: true })) + Taro.showToast({ title: `想认识 ${member.name}`, icon: 'none' }) + } else { + Taro.showToast({ title: '已跳过', icon: 'none' }) + } + setFly(null) + setDrag({ x: 0, y: 0, active: false }) + dragRef.current = { x: 0, y: 0 } + busy.current = false + }, 280) + }, + [fly], + ) + + const undo = useCallback(() => { + if (busy.current || fly || !history.length) return + const last = history[history.length - 1]! + setHistory(history.slice(0, -1)) + setSwipes((prev) => { + const nextStore = { ...prev } + delete nextStore[last.id] + return nextStore + }) + if (last.decision === 'like') { + setLikes((prev) => { + const n = { ...prev } + delete n[last.id] + return n + }) + } + Taro.showToast({ title: '已撤销', icon: 'none' }) + }, [history, fly]) + + const onPointerDown = (event: any) => { + if (!current || fly || busy.current) return + const clientX = event.clientX ?? event.touches?.[0]?.clientX + const clientY = event.clientY ?? event.touches?.[0]?.clientY + if (clientX == null) return + dragging.current = true + start.current = { x: clientX, y: clientY || 0 } + setDrag({ x: 0, y: 0, active: true }) + } + + const onPointerMove = (event: any) => { + if (!dragging.current || !current || fly) return + const clientX = event.clientX ?? event.touches?.[0]?.clientX + const clientY = event.clientY ?? event.touches?.[0]?.clientY + if (clientX == null) return + const nextDrag = { + x: clientX - start.current.x, + y: ((clientY || 0) - start.current.y) * 0.35, + } + dragRef.current = nextDrag + setDrag({ ...nextDrag, active: true }) + } + + const onPointerUp = () => { + if (!dragging.current || !current || fly) return + dragging.current = false + const x = dragRef.current.x + const threshold = + process.env.TARO_ENV !== 'h5' || + (typeof window !== 'undefined' && + window.matchMedia('(max-width: 900px)').matches) + ? THRESHOLD_MOBILE + : THRESHOLD_DESKTOP + if (x > threshold) commit(current, 'like') + else if (x < -threshold) commit(current, 'pass') + else { + setDrag({ x: 0, y: 0, active: false }) + dragRef.current = { x: 0, y: 0 } + } + } + + const resetDeck = () => { + setSwipes({}) + setHistory([]) + setOrder(shuffle(roster.map((m) => m.id))) + setDrag({ x: 0, y: 0, active: false }) + dragRef.current = { x: 0, y: 0 } + setFly(null) + setLikes({}) + busy.current = false + Taro.showToast({ title: '已重新洗牌', icon: 'none' }) + } + + useEffect(() => { + if (typeof window === 'undefined') return + const onKey = (event: KeyboardEvent) => { + if (event.key === 'ArrowRight' && current) { + event.preventDefault() + commit(current, 'like') + } else if (event.key === 'ArrowLeft' && current) { + event.preventDefault() + commit(current, 'pass') + } else if (event.key === 'Backspace') { + event.preventDefault() + undo() + } + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [current, commit, undo]) + + const rotate = drag.x / 18 + const stampThreshold = + process.env.TARO_ENV !== 'h5' || + (typeof window !== 'undefined' && + window.matchMedia('(max-width: 900px)').matches) + ? THRESHOLD_MOBILE + : THRESHOLD_DESKTOP + const likeOpacity = Math.min(1, Math.max(0, drag.x / stampThreshold)) + const passOpacity = Math.min(1, Math.max(0, -drag.x / stampThreshold)) + const likedCount = Object.keys(likes).length + + return ( + + + + + goPage('/pages/social/index')}> + ← 首页 + + + 认识一下 + + 左滑划走 · 右滑想认识 + {totalForFilter ? ` · 还剩 ${remaining}/${totalForFilter}` : ''} + + + 示例介绍,方便先逛逛 + + + + {( + [ + ['all', '全部'], + ['f', '女生'], + ['m', '男生'], + ] as const + ).map(([id, label]) => ( + setFilter(id)} + > + {label} + + ))} + + {likedCount > 0 ? ( + + ♥ 想认识 {likedCount} + + ) : null} + + + + + {totalForFilter > 0 ? ( + + + + ) : null} + + + {!current ? ( + + ✨ + 这批看完了 + + 想认识的人会先记在你这边。可以再看一轮,或去聊天室打个招呼。 + + + 再来一轮 + + goPage('/pages/social/chat/index')} + > + 先去群组聊聊 + + + ) : null} + + {next ? ( + + + + ) : null} + + {current ? ( + + {/* pointer events via native listeners on H5 */} + { + dragging.current = false + dragRef.current = { x: 0, y: 0 } + setDrag({ x: 0, y: 0, active: false }) + }} + /> + + 想认识 + + + 划走 + + + + ) : null} + + + + ← 划走 + 拖卡片左右滑 · 或点下面按钮 + 想认识 → + + + + current && commit(current, 'pass')} + > + ✕ + + + ↩ + + current && commit(current, 'like')} + > + ♥ + + + + + + + + ) +} + +export default function SocialDatePage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/index.config.ts b/apps/miniprogram/h5/src/pages/social/index.config.ts new file mode 100644 index 0000000..9acd8dc --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/index.config.ts @@ -0,0 +1,7 @@ +export default definePageConfig({ + navigationBarTitleText: '游民社区', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', + navigationStyle: 'custom', +}) diff --git a/apps/miniprogram/h5/src/pages/social/index.scss b/apps/miniprogram/h5/src/pages/social/index.scss new file mode 100644 index 0000000..1b31b98 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/index.scss @@ -0,0 +1,7 @@ +@import '../../styles/page-rem.scss'; +@import './_components/social-subpage.scss'; + +/* 页面级微调:主体视觉在 social-next/weapp-bridge */ +.soc-taro-root.social-weapp .social-mobile-dock { + padding-bottom: calc(8PX + env(safe-area-inset-bottom, 0PX)); +} diff --git a/apps/miniprogram/h5/src/pages/social/index.tsx b/apps/miniprogram/h5/src/pages/social/index.tsx new file mode 100644 index 0000000..a85c9ee --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/index.tsx @@ -0,0 +1,701 @@ +import { useEffect, useMemo, useState, type CSSProperties } from 'react' +import Taro, { usePageScroll } from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { + DEFAULT_PROMO, + MOCK_ROSTER, + PATH_CHIPS, + ROLE_EMOJI, + SEED_EBOOKS, + SEED_GIGS, + SEED_MEETUPS, + SEED_VIDEOS, + SOCIAL_CITIES, + SOCIAL_COPY, + TEAM_KIND_LABEL, +} from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { getSafeAreaMetrics, safePx } from '@/utils/safeArea' +import { + ConnectionHero, + ConnectionWays, +} from './_components/ConnectionHero' +import { AttractiveRoster } from './_components/AttractiveRoster' +import { SocialDock } from './_components/SocialDock' +import { SocialAvatar } from './_components/SocialAvatar' +import { FxBelt, SocialExperience } from './_components/SocialExperience' +import { H5El } from './_components/H5El' +import { JoinPaySheet } from './_components/JoinPaySheet' +import '@/styles/social-next/entry' +import './index.scss' + +const isH5 = process.env.TARO_ENV === 'h5' + +function scrollToId(id: string) { + if (!isH5) { + // 微信:用选择器滚到锚点(无 DOM scrollIntoView) + const query = Taro.createSelectorQuery() + query.select(`#${id}`).boundingClientRect() + query.selectViewport().scrollOffset() + query.exec((res) => { + const rect = res?.[0] as { top?: number } | undefined + const offset = res?.[1] as { scrollTop?: number } | undefined + if (!rect || typeof rect.top !== 'number') return + const scrollTop = Math.max(0, (offset?.scrollTop || 0) + rect.top - 72) + Taro.pageScrollTo({ scrollTop, duration: 300 }) + }) + return + } + if (typeof document === 'undefined') return + const el = document.getElementById(id) + if (!el) return + const page = document.querySelector('.taro_page') as HTMLElement | null + if (page) { + const top = + el.getBoundingClientRect().top - page.getBoundingClientRect().top + page.scrollTop - 72 + page.scrollTo({ top, behavior: 'smooth' }) + return + } + el.scrollIntoView({ behavior: 'smooth', block: 'start' }) +} + +function SocialHome() { + usePageShare({ title: 'nomadro · 游民社区', path: '/pages/social/index' }) + usePageTrack('social_home') + const [scrolled, setScrolled] = useState(false) + const [activeSection, setActiveSection] = useState('people') + const [joinOpen, setJoinOpen] = useState(false) + const copy = SOCIAL_COPY + const datePreview = useMemo( + () => MOCK_ROSTER.filter((m) => m.online).slice(0, 3), + [], + ) + const meetups = SEED_MEETUPS + const gigs = SEED_GIGS + const cities = SOCIAL_CITIES.filter((c) => c.hot).slice(0, 8) + const safe = useMemo(() => getSafeAreaMetrics(), []) + const rootStyle = useMemo( + () => + ({ + ['--safe-status-bar' as string]: safePx(safe.statusBarHeight), + ['--safe-nav-bar' as string]: safePx(safe.navBarHeight), + ['--safe-menu-pad' as string]: safePx(safe.menuRightPad), + ['--safe-header' as string]: safePx(safe.headerHeight), + }) as CSSProperties, + [safe], + ) + + const onJoin = () => { + // 加群收费(虚拟支付)≠ VIP / community 付费体系 + setJoinOpen(true) + } + + useEffect(() => { + try { + const q = Taro.getCurrentInstance()?.router?.params || {} + if (String(q.join || '') === '1') setJoinOpen(true) + } catch { + /* ignore */ + } + }, []) + + useEffect(() => { + if (!isH5 || typeof document === 'undefined') return + const html = document.documentElement + html.setAttribute('data-theme', 'dark') + html.setAttribute('data-social-skin', '1') + html.classList.add('dark') + document.body.classList.add('social-body') + return () => { + document.body.classList.remove('social-body') + } + }, []) + + // 微信:进页强制回顶,避免 sticky path + 页脚看起来像「整页只有链接列表」 + useEffect(() => { + if (isH5) return + Taro.pageScrollTo({ scrollTop: 0, duration: 0 }) + }, []) + + usePageScroll(({ scrollTop }) => { + if (!isH5) setScrolled(scrollTop > 24) + }) + + useEffect(() => { + if (!isH5 || typeof window === 'undefined') return + const scroller = + (document.querySelector('.taro_page') as HTMLElement | null) || + document.scrollingElement || + document.documentElement + const onScroll = () => { + const y = + scroller === document.scrollingElement || scroller === document.documentElement + ? window.scrollY || document.documentElement.scrollTop + : (scroller as HTMLElement).scrollTop + setScrolled(y > 24) + } + onScroll() + scroller.addEventListener('scroll', onScroll, { passive: true }) + window.addEventListener('scroll', onScroll, { passive: true }) + return () => { + scroller.removeEventListener('scroll', onScroll) + window.removeEventListener('scroll', onScroll) + } + }, []) + + useEffect(() => { + if (!isH5 || typeof document === 'undefined') return + const root = document.querySelector('.social-home') + if (!root) return + root.querySelectorAll('.reveal').forEach((el) => el.classList.add('visible')) + const observer = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) setActiveSection(entry.target.id) + }) + }, + { rootMargin: '-25% 0px -55% 0px', threshold: 0 }, + ) + root.querySelectorAll('section[id]:not(#hero)').forEach((section) => observer.observe(section)) + return () => observer.disconnect() + }, []) + + return ( + + + + + + + + + + + goPage('/pages/home/index')} + > + + 🌐 + + 游民社区 + + + + 加入社区 + + + + + + + + + + + + + {PATH_CHIPS.map((p) => ( + { + if (p.page === 'chat') goPage(p.href) + else scrollToId(p.href.slice(1)) + }} + > + + {p.emoji} + + {p.label} + + ))} + + + + + + + + + + + + + + 认识一下 + 左右滑 + + + + 💕 + + 一张一张认识新朋友 + + + 像翻相册一样:不感兴趣就划走,想认识就留下。记在你这边,之后再决定要不要打招呼。 + + + + ← 划走 + + + → 想认识 + + + ♥ 稍后打招呼 + + + + goPage('/pages/social/date/index')} + > + 开始认识 ↗ + + goPage('/pages/social/people/index')} + > + 先浏览大家 + + + + goPage('/pages/social/date/index')} + > + {datePreview.map((m, i) => ( + + {m.online ? ( + + 在线 + + ) : null} + + + {m.name} + {m.title} + + {m.city.split('·')[0]?.trim()} + {m.lookingFor} + + {m.tags.slice(0, 2).map((t) => ( + + {t} + + ))} + + + + ))} + + ♥ 点这里开始滑 + + + + + + + + + + + + + 聊天群组 + 语音 · 视频 + + + + 📡 + + {copy.socialOnlineTitle} + + + 先进聊天群组热热身,再开语音或视频见面。「想参加」会先记在你这边。 + + + + {meetups.map((m, i) => ( + + + + 0{i + 1} + + + {Array.from({ length: 14 }, (_, n) => ( + + ))} + + + {MOCK_ROSTER.slice(i, i + 4).map((p) => ( + + + + ))} + + 📡 + + + + {m.city === 'Online' ? '群组 · 语音视频' : m.city} + + + {m.date} · {m.time} + + + + {MOCK_ROSTER.slice(i + 1, i + 5).map((p) => ( + + ))} + +{6 + i} 想参加 + + {m.title} + 群里打个招呼 → 开麦 / 开视频 → 认识新朋友 + + goPage( + `/pages/social/meetup-live/index?id=${encodeURIComponent(m.id)}`, + ) + } + > + 进入聊聊 ↗ + + + ))} + + + goPage('/pages/social/chat/index')} + > + 文字群聊 + + + 加入社区 + + + + + + + + + + + + 挑一座城 + 再出来见面 + + + + 🌆 + + {copy.socialOfflineTitle} + + + 认识了、聊过之后,出来见一面会更自然。先挑一座城市,再找适合见面的咖啡馆。 + + + + {cities.map((c, i) => ( + goPage('/pages/social/people/index?mode=cafe')} + > + + {c.emoji} + + {c.name} + {c.vibe} + + {c.members} 人 · {c.costHint} + + + ))} + + + goPage('/pages/social/people/index?mode=cafe')} + > + 看看咖啡馆 + + goPage('/pages/social/people/index')} + > + 找同城的人 + + + + + + + + + + + + 找搭子 + 共创 + + + + 🚀 + + {copy.socialTeamTitle} + + + 有人在找帮手;也有人一起写小册、拍视频做共创。点卡片看看详情,合适再表达兴趣。 + + + + + + 找搭子 + + + 共创 + + + + + {gigs.slice(0, 3).map((g, i) => ( + + goPage(`/pages/social/team/index?gig=${encodeURIComponent(g.id)}`) + } + > + + {ROLE_EMOJI[g.kind || 'parttime'] || '📝'} + + + {TEAM_KIND_LABEL[g.kind || 'parttime']} + {g.remote ? '线上也能做' : '可以见面做'} + + {g.title} + {g.pay} + + {(g.tags || []).slice(0, 3).map((t) => ( + + {t} + + ))} + + + ))} + + + + {SEED_EBOOKS.slice(0, 2).map((book) => ( + goPage('/pages/book/index')} + > + + 📖 + + + 共创 · 小册 + {book.title} + {book.blurb} + + ↗ + + ))} + {SEED_VIDEOS.slice(0, 2).map((vid) => ( + + + {vid.coverEmoji} + + + 共创 · 视频 + {vid.title} + + {vid.city} · {vid.minutes} 分钟 + + + ↗ + + ))} + + + + goPage('/pages/social/team/index')} + > + 更多机会 + + + 加入社区 + + + + + + + + + + + ✨ + + + + + 加入社区 + + {copy.socialInviteTitle} + {copy.socialInviteLead} + + + 加入游民社区 ↗ + + + + + + + + + nomadro · 游民社区 + 认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事 + + + 认识人 + goPage('/pages/social/people/index')}> + 想见的人 + + goPage('/pages/social/date/index')}> + 认识一下 + + goPage('/pages/social/chat/index')}> + 大家聊天 + + + + 见面 · 做事 + goPage('/pages/social/people/index?mode=cafe')} + > + 找城市见面 + + goPage('/pages/social/team/index')} + > + 找搭子做事 + + goPage('/pages/home/index')}> + 门户首页 + + + + + © {new Date().getFullYear()} nomadro · 游民社区 + + + + + setJoinOpen(false)} /> + + + + ) +} + +export default function SocialIndexPage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/meetup-live/index.config.ts b/apps/miniprogram/h5/src/pages/social/meetup-live/index.config.ts new file mode 100644 index 0000000..9ed24ae --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/meetup-live/index.config.ts @@ -0,0 +1,7 @@ +export default definePageConfig({ + navigationBarTitleText: '语音视频', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', + disableScroll: true, +}) diff --git a/apps/miniprogram/h5/src/pages/social/meetup-live/index.scss b/apps/miniprogram/h5/src/pages/social/meetup-live/index.scss new file mode 100644 index 0000000..03476fb --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/meetup-live/index.scss @@ -0,0 +1,120 @@ +@import '../_components/social-subpage.scss'; + +.social-live-gate { + padding: 1.25rem 1rem 1.5rem; + display: flex; + flex-direction: column; + gap: 0.85rem; +} + +.social-live-nick-row { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.social-live-native-stage { + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; + overflow: visible !important; + background: transparent; + padding: 0 0 1rem; +} + +.social-meetup-live .social-live-video, +.social-meetup-live .social-live-native-stage, +.social-meetup-live .social-live-stage { + overflow: visible !important; +} + +.social-live-self { + width: 100%; + display: flex; + justify-content: center; + overflow: visible !important; +} + +.social-live-peers { + width: 100%; + display: flex; + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + gap: 8PX; + margin-top: 8PX; +} + +.social-live-tile { + position: relative; + overflow: visible !important; +} + +.social-live-pusher, +.social-live-player { + background: #1a1a1f; + overflow: visible !important; + border-radius: 0 !important; +} + +.social-live-pusher-badge { + position: absolute; + left: 8PX; + bottom: 8PX; + padding: 4PX 10PX; + font-size: 12PX; + color: #fff; + background-color: rgba(0, 0, 0, 0.55); + border-radius: 999PX; +} + +.social-live-tile-label { + margin-top: 4PX; + text-align: center; + font-size: 12PX; + color: #cbd5e1; + line-height: 1.3; +} + +.social-live-tools-cover { + width: 100%; + display: flex; + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + gap: 8PX; + padding: 8PX 4PX; +} + +.social-live-tool-btn { + min-width: 72PX; + min-height: 40PX; + line-height: 40PX; + padding: 0 12PX; + text-align: center; + font-size: 13PX; + color: #e2e8f0; + background-color: rgba(20, 28, 40, 0.92); + border: 1PX solid rgba(255, 255, 255, 0.14); + border-radius: 999PX; +} + +.social-live-tool-btn.is-leave { + color: #082b2b; + background-color: #4ecdc4; + border-color: #4ecdc4; +} + +.social-live-hint { + padding: 0 0.5rem 1rem; + font-size: 0.8rem; + line-height: 1.45; + text-align: center; +} + +.social-live-iframe-host { + width: 100%; + min-height: 62vh; +} diff --git a/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx b/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx new file mode 100644 index 0000000..758d1c7 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx @@ -0,0 +1,558 @@ +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type CSSProperties, +} from 'react' +import { + CoverView, + Input, + LivePlayer, + LivePusher, + View, +} from '@tarojs/components' +import Taro, { useRouter } from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { MIROTALK_URL, MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed' +import { socialApi, type LivePeer } from '@/services/socialApi' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { getSafeAreaMetrics, safePx } from '@/utils/safeArea' +import { SocialAvatar } from '../_components/SocialAvatar' +import { SocialDock } from '../_components/SocialDock' +import { SocialExperience } from '../_components/SocialExperience' +import { H5El } from '../_components/H5El' +import '@/styles/social-next/entry' +import '../_components/social-subpage.scss' +import './index.scss' + +const ENV = Taro.getEnv() +const isH5 = ENV === Taro.ENV_TYPE.WEB +const isWeapp = ENV === Taro.ENV_TYPE.WEAPP +const PUSHER_ID = 'socialLivePusher' + +function joinMiro(room: string, name: string) { + const q = new URLSearchParams({ + room, + name, + notify: '0', + chat: '0', + audio: '0', + video: '0', + }) + return `${MIROTALK_URL.replace(/\/$/, '')}/join?${q.toString()}` +} + +/** 微信 LivePusher 真机:RTMP 地址去掉 query,避免连不上导致黑屏 */ +function cleanRtmpUrl(url: string) { + const s = String(url || '').trim() + if (!s) return '' + const i = s.indexOf('?') + return i >= 0 ? s.slice(0, i) : s +} + +function selfTileSize() { + try { + const info = Taro.getSystemInfoSync() + const w = Math.max(300, Math.floor(Number(info.windowWidth) || 375) - 24) + const h = Math.min( + Math.floor(w * 1.333), + Math.floor((Number(info.windowHeight) || 640) * 0.55), + ) + return { width: w, height: Math.max(360, h) } + } catch { + return { width: 340, height: 460 } + } +} + +function peerTileSize() { + try { + const info = Taro.getSystemInfoSync() + const w = Math.max(140, Math.floor(((Number(info.windowWidth) || 375) - 36) / 2)) + return { width: w, height: Math.floor(w * 1.25) } + } catch { + return { width: 160, height: 200 } + } +} + +function getPusherCtx() { + try { + return ( + Taro.createLivePusherContext as (id?: string) => ReturnType< + typeof Taro.createLivePusherContext + > + )(PUSHER_ID) + } catch { + return Taro.createLivePusherContext() + } +} + +async function ensureMediaAuth(): Promise { + if (!isWeapp) return true + try { + const wxAny = Taro as unknown as { + requirePrivacyAuthorize?: (o: { + success?: () => void + fail?: () => void + }) => void + } + if (typeof wxAny.requirePrivacyAuthorize === 'function') { + await new Promise((resolve, reject) => { + wxAny.requirePrivacyAuthorize!({ + success: () => resolve(), + fail: () => reject(new Error('privacy')), + }) + }) + } + } catch { + /* continue */ + } + try { + await Taro.authorize({ scope: 'scope.camera' }) + await Taro.authorize({ scope: 'scope.record' }) + return true + } catch { + const open = await Taro.showModal({ + title: '需要摄像头与麦克风', + content: '语音视频厅需要相机和录音权限。', + confirmText: '去设置', + }) + if (open.confirm) Taro.openSetting({}) + return false + } +} + +function SocialMeetupLive() { + const router = useRouter() + const meetupId = String(router.params?.id || SEED_MEETUPS[0]?.id || 'office') + const meetup = + SEED_MEETUPS.find((m) => m.id === meetupId) || { + id: meetupId, + title: '开视频见面', + city: 'Online', + date: '', + time: '', + mode: 'online' as const, + mirotalkRoom: meetupId || 'nomadro-social-office', + channelId: 'meetup-live', + } + + usePageShare({ + title: `nomadro · ${meetup.title}`, + path: `/pages/social/meetup-live/index?id=${encodeURIComponent(meetup.id)}`, + }) + usePageTrack('social_meetup_live') + + const safe = useMemo(() => getSafeAreaMetrics(), []) + const selfSize = useMemo(() => selfTileSize(), []) + const peerSize = useMemo(() => peerTileSize(), []) + + const [nick, setNick] = useState(() => { + try { + return String(Taro.getStorageSync('nick') || router.params?.nick || '游民') + } catch { + return '游民' + } + }) + const [liveOn, setLiveOn] = useState(false) + const [micOn, setMicOn] = useState(true) + const [camOn, setCamOn] = useState(true) + /** 先空串开本地预览,预览成功后再写入 RTMP */ + const [pusherUrl, setPusherUrl] = useState('') + const pendingPush = useRef('') + const [peers, setPeers] = useState([]) + const [status, setStatus] = useState('待进入') + const [roomId, setRoomId] = useState(meetup.id) + const [previewOk, setPreviewOk] = useState(false) + const hbRef = useRef | null>(null) + + const miroSrc = useMemo( + () => joinMiro(meetup.mirotalkRoom, nick.trim() || '游民'), + [meetup.mirotalkRoom, nick], + ) + + const stopHeartbeat = () => { + if (hbRef.current) { + clearInterval(hbRef.current) + hbRef.current = null + } + } + + const leaveNative = useCallback(async () => { + stopHeartbeat() + try { + const ctx = getPusherCtx() + ctx.stop({ complete: () => undefined }) + ctx.stopPreview({ complete: () => undefined }) + } catch { + /* ignore */ + } + try { + await socialApi.liveLeave(roomId) + } catch { + /* ignore */ + } + setLiveOn(false) + setPusherUrl('') + pendingPush.current = '' + setPeers([]) + setPreviewOk(false) + setStatus('已离开') + }, [roomId]) + + useEffect(() => { + return () => { + stopHeartbeat() + if (isWeapp && liveOn) { + try { + socialApi.liveLeave(roomId) + } catch { + /* ignore */ + } + } + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + // ① 组件挂载后先本地预览(此时 url 为空) + useEffect(() => { + if (!isWeapp || !liveOn) return + let cancelled = false + const t = setTimeout(() => { + if (cancelled) return + try { + const ctx = getPusherCtx() + ctx.startPreview({ + success: () => { + if (cancelled) return + setPreviewOk(true) + setStatus('摄像头已打开') + // ② 预览成功后再挂 RTMP 并 start + const url = pendingPush.current + if (url) { + setPusherUrl(url) + } + }, + fail: (e) => { + if (cancelled) return + setStatus( + String( + (e as { errMsg?: string })?.errMsg || + '打不开摄像头,请检查权限', + ), + ) + }, + }) + } catch (e) { + if (!cancelled) { + setStatus(String((e as Error)?.message || '摄像头错误')) + } + } + }, 500) + return () => { + cancelled = true + clearTimeout(t) + } + }, [liveOn]) + + // ③ url 写入后开始推流(autopush=false,手动 start) + useEffect(() => { + if (!isWeapp || !liveOn || !pusherUrl || !previewOk) return + let cancelled = false + const t = setTimeout(() => { + if (cancelled) return + try { + getPusherCtx().start({ + success: () => !cancelled && setStatus('已推流 · 摄像头预览中'), + fail: (e) => + !cancelled && + setStatus( + `预览中 · 推流失败 ${String( + (e as { errMsg?: string })?.errMsg || '', + ).slice(0, 24)}`, + ), + }) + } catch { + /* ignore */ + } + }, 300) + return () => { + cancelled = true + clearTimeout(t) + } + }, [liveOn, pusherUrl, previewOk]) + + const startWeappLive = async () => { + const ok = await ensureMediaAuth() + if (!ok) return + const name = nick.trim() || '游民' + Taro.setStorageSync('nick', name) + setStatus('正在进厅…') + setPreviewOk(false) + setPusherUrl('') + try { + const joined = await socialApi.liveJoin(meetup.id, name) + const rtmp = cleanRtmpUrl(joined.pushUrl) + pendingPush.current = rtmp + setRoomId(joined.roomId) + setPeers(joined.peers || []) + // 先 liveOn:挂载空 url 的 LivePusher → startPreview + setLiveOn(true) + setStatus('正在打开摄像头…') + stopHeartbeat() + hbRef.current = setInterval(() => { + socialApi + .liveHeartbeat(joined.roomId) + .then((r) => setPeers(r.peers || [])) + .catch(() => undefined) + }, 4000) + } catch (e) { + const msg = String((e as Error)?.message || '进厅失败') + setStatus(msg) + Taro.showToast({ title: msg, icon: 'none', duration: 3200 }) + } + } + + const startH5 = () => { + Taro.setStorageSync('nick', nick.trim() || '游民') + setLiveOn(true) + setStatus('MiroTalk WebRTC(H5)') + } + + const switchCam = () => { + try { + getPusherCtx().switchCamera({ complete: () => undefined }) + } catch { + /* ignore */ + } + } + + return ( + + + + + { + if (liveOn && isWeapp) void leaveNative() + goPage('/pages/social/meetup/index') + }} + > + ← 场次 + + + {meetup.title} + + {status} + + + + + + + {!liveOn ? ( + + 语音视频厅 + + {isWeapp + ? '先进厅打开本地摄像头,再推流到厅内。请允许相机与麦克风。' + : 'H5 使用 MiroTalk WebRTC;微信端为自研原生厅。'} + + + {MOCK_ROSTER.filter((m) => m.online) + .slice(0, 5) + .map((m) => ( + + ))} + + + + 昵称 + + setNick(e.detail.value)} + /> + + void (isWeapp ? startWeappLive() : startH5())} + > + 进入语音视频厅 + + + ) : isWeapp ? ( + + + { + const code = (e as { detail?: { code?: number } })?.detail + ?.code + if (code === 1003 || code === 1004) { + setPreviewOk(true) + setStatus('摄像头就绪') + } else if (code === 1007 || code === 1008) { + setStatus('推流中 · 可看见自己') + } else if (code === -1307) { + setStatus('网络断连,预览仍可用') + } + }} + onError={(e) => { + const msg = String( + (e as { detail?: { errMsg?: string } })?.detail?.errMsg || + '摄像头错误', + ) + setStatus(msg) + }} + > + + 我 · {nick} + {previewOk ? ' · 预览中' : ' · 启动中'} + + + + + {peers.length > 0 ? ( + + {peers.map((p) => ( + + + + {p.nick || '游民'} + + + ))} + + ) : null} + + + { + setMicOn((v) => { + const next = !v + try { + // enableMic 靠 props;再补一手 + getPusherCtx() + } catch { + /* ignore */ + } + return next + }) + }} + > + {micOn ? '关麦' : '开麦'} + + setCamOn((v) => !v)} + > + {camOn ? '关摄像头' : '开摄像头'} + + + 翻转 + + void leaveNative()} + > + 离开 + + + + + {previewOk + ? peers.length + ? `厅内另有 ${peers.length} 人` + : '应能看见自己画面;等人进同一场次' + : '若一直黑屏:系统设置里打开微信的相机权限后重进'} + + + ) : ( + + + )} + + {!liveOn || !isWeapp ? : null} + + + ) +} + +export default function SocialMeetupLivePage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/meetup/index.config.ts b/apps/miniprogram/h5/src/pages/social/meetup/index.config.ts new file mode 100644 index 0000000..db2e386 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/meetup/index.config.ts @@ -0,0 +1,6 @@ +export default definePageConfig({ + navigationBarTitleText: '开视频场次', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', +}) diff --git a/apps/miniprogram/h5/src/pages/social/meetup/index.scss b/apps/miniprogram/h5/src/pages/social/meetup/index.scss new file mode 100644 index 0000000..7f67876 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/meetup/index.scss @@ -0,0 +1 @@ +@import '../_components/social-subpage.scss'; diff --git a/apps/miniprogram/h5/src/pages/social/meetup/index.tsx b/apps/miniprogram/h5/src/pages/social/meetup/index.tsx new file mode 100644 index 0000000..0f2ef67 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/meetup/index.tsx @@ -0,0 +1,109 @@ +import { useMemo, type CSSProperties } from 'react' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { getSafeAreaMetrics, safePx } from '@/utils/safeArea' +import { SocialAvatar } from '../_components/SocialAvatar' +import { SocialDock } from '../_components/SocialDock' +import { SocialExperience } from '../_components/SocialExperience' +import { H5El } from '../_components/H5El' +import '@/styles/social-next/entry' +import '../_components/social-subpage.scss' +import './index.scss' + +function SocialMeetupList() { + usePageShare({ title: 'nomadro · 开视频', path: '/pages/social/meetup/index' }) + usePageTrack('social_meetup') + const safe = useMemo(() => getSafeAreaMetrics(), []) + + return ( + + + + + goPage('/pages/social/index')} + > + ← 首页 + + + 开视频场次 + + WebRTC · 与门户同款 MiroTalk + + + + + + + + 先进场次热热身,再开语音或视频。小程序内会引导用系统浏览器进入真正的 WebRTC 房间(禁止 web-view)。 + + + {SEED_MEETUPS.map((m, i) => ( + + + + {m.city === 'Online' ? '群组 · 语音视频' : m.city} + + + {m.date} · {m.time} + + + + {MOCK_ROSTER.slice(i + 1, i + 5).map((p) => ( + + ))} + +{6 + i} 想参加 + + {m.title} + + 房间 {m.mirotalkRoom} + + + goPage(`/pages/social/meetup-live/index?id=${encodeURIComponent(m.id)}`) + } + > + 进入聊聊 ↗ + + + ))} + + + + + + ) +} + +export default function SocialMeetupPage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/people/index.config.ts b/apps/miniprogram/h5/src/pages/social/people/index.config.ts new file mode 100644 index 0000000..87472dc --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/people/index.config.ts @@ -0,0 +1,6 @@ +export default definePageConfig({ + navigationBarTitleText: '想见的人', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', +}) diff --git a/apps/miniprogram/h5/src/pages/social/people/index.scss b/apps/miniprogram/h5/src/pages/social/people/index.scss new file mode 100644 index 0000000..7f67876 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/people/index.scss @@ -0,0 +1 @@ +@import '../_components/social-subpage.scss'; diff --git a/apps/miniprogram/h5/src/pages/social/people/index.tsx b/apps/miniprogram/h5/src/pages/social/people/index.tsx new file mode 100644 index 0000000..5cad321 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/people/index.tsx @@ -0,0 +1,185 @@ +import { useEffect, useMemo, useState, type CSSProperties } from 'react' +import { useRouter } from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { + MOCK_ROSTER, + SEED_CAFES, + SEED_GIGS, + SOCIAL_CITIES, + TEAM_KIND_LABEL, + ROLE_EMOJI, +} from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { getSafeAreaMetrics, safePx } from '@/utils/safeArea' +import { PeopleChip } from '../_components/PeopleChip' +import { SocialDock } from '../_components/SocialDock' +import { SocialExperience } from '../_components/SocialExperience' +import { H5El } from '../_components/H5El' +import '@/styles/social-next/entry' +import './index.scss' + +function SocialPeople() { + usePageShare({ title: 'nomadro · 想见的人', path: '/pages/social/people/index' }) + usePageTrack('social_people') + const router = useRouter() + const mode = (router.params?.mode as string) || 'all' + const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm'>('all') + const [likes, setLikes] = useState>({}) + const safe = useMemo(() => getSafeAreaMetrics(), []) + + useEffect(() => { + if (mode === 'team') goPage('/pages/social/team/index') + }, [mode]) + + const title = + mode === 'cafe' ? '同城,见一面' : mode === 'team' ? '一起,做点事' : '想见的人' + + const list = useMemo(() => { + return MOCK_ROSTER.filter((m) => { + if (filter === 'online') return m.online + if (filter === 'f' || filter === 'm') return m.gender === filter + return true + }) + }, [filter]) + + return ( + + + + + goPage('/pages/social/index')} + > + ← 首页 + + + {title} + + 示例介绍 · 离线可逛 + + + goPage('/pages/social/date/index')} + > + 认识一下 + + + + + + {mode === 'cafe' ? ( + <> + + {SOCIAL_CITIES.filter((c) => c.hot) + .slice(0, 6) + .map((c) => ( + + + {c.emoji} + + {c.name} + + {c.vibe} + + + ))} + + + {SEED_CAFES.map((cafe) => ( + + ☕ {cafe.name} + + {cafe.city} · WiFi {cafe.wifiMbps}Mbps + + {cafe.vibe} + + ))} + + + ) : null} + + {mode === 'team' ? ( + + {SEED_GIGS.map((g) => ( + + {ROLE_EMOJI[g.kind || 'parttime']} + + {TEAM_KIND_LABEL[g.kind || 'parttime']} + + {g.title} + {g.pay} + + ))} + + ) : null} + + {mode === 'all' || mode === 'cafe' ? ( + <> + + {( + [ + ['all', '全部', '✨'], + ['online', '在线', '🟢'], + ['f', '女生', '👩'], + ['m', '男生', '👨'], + ] as const + ).map(([id, label, emoji]) => ( + setFilter(id)} + > + {emoji} {label} + + ))} + + + {list.map((m, i) => ( + + setLikes((prev) => ({ ...prev, [m.id]: !prev[m.id] })) + } + /> + ))} + + + ) : null} + + + + + ) +} + +export default function SocialPeoplePage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/people/profile/index.config.ts b/apps/miniprogram/h5/src/pages/social/people/profile/index.config.ts new file mode 100644 index 0000000..0be2109 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/people/profile/index.config.ts @@ -0,0 +1,6 @@ +export default definePageConfig({ + navigationBarTitleText: '游民名片', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', +}) diff --git a/apps/miniprogram/h5/src/pages/social/people/profile/index.scss b/apps/miniprogram/h5/src/pages/social/people/profile/index.scss new file mode 100644 index 0000000..c0b8b5d --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/people/profile/index.scss @@ -0,0 +1,34 @@ +@import '../../../../styles/page-rem.scss'; +@import '../../_components/social-subpage.scss'; + +.soc-taro-root.social-profile-page .social-sub-body { + padding-bottom: calc(5.5rem + env(safe-area-inset-bottom, 0PX)); +} + +.soc-taro-root.social-profile-page .social-profile-actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +.soc-taro-root.social-profile-page .social-profile-actions .btn, +.soc-taro-root.social-profile-page .social-profile-actions .social-btn { + min-height: 2.75rem; + padding: 0 0.9rem; + font-size: 0.875rem; +} + +.soc-taro-root.social-profile-page .social-profile-gallery-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.5rem; +} + +.soc-taro-root.social-profile-page .social-profile-gallery-grid image, +.soc-taro-root.social-profile-page .social-profile-gallery-grid .as-img { + width: 100%; + aspect-ratio: 4 / 3; + object-fit: cover; + border-radius: 0.75rem; + display: block; +} diff --git a/apps/miniprogram/h5/src/pages/social/people/profile/index.tsx b/apps/miniprogram/h5/src/pages/social/people/profile/index.tsx new file mode 100644 index 0000000..05c178f --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/people/profile/index.tsx @@ -0,0 +1,270 @@ +import { useMemo, useState, type CSSProperties } from 'react' +import { Image } from '@tarojs/components' +import { useRouter } from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { findRosterMember, MOCK_ROSTER } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { getSafeAreaMetrics, safePx } from '@/utils/safeArea' +import { H5El } from '../../_components/H5El' +import { SocialAvatar } from '../../_components/SocialAvatar' +import { SocialDock } from '../../_components/SocialDock' +import { SocialExperience } from '../../_components/SocialExperience' +import { PeopleChip } from '../../_components/PeopleChip' +import '@/styles/social-next/entry' +import './index.scss' + +function SocialPeopleProfile() { + const router = useRouter() + const id = String(router.params?.id || '').trim() + const member = useMemo(() => findRosterMember(id), [id]) + const [liked, setLiked] = useState(false) + const safe = useMemo(() => getSafeAreaMetrics(), []) + + usePageShare({ + title: member + ? `nomadro · ${member.name}` + : 'nomadro · 游民名片', + path: member + ? `/pages/social/people/profile/index?id=${member.id}` + : '/pages/social/people/index', + }) + usePageTrack('social_people_profile') + + const similar = useMemo(() => { + if (!member) return [] + const cityKey = member.city.split(/[·/]/)[0]?.trim() || '' + return MOCK_ROSTER.filter( + (m) => + m.id !== member.id && + cityKey.length >= 2 && + m.city.includes(cityKey.slice(0, 2)), + ).slice(0, 4) + }, [member]) + + const intro = member + ? encodeURIComponent( + `嗨 ${member.name}!看到你在做${member.tags[0] || '远程'},想认识一下。`, + ) + : '' + + return ( + + + + + goPage('/pages/social/people/index')} + > + ← 回去看看大家 + + + {member?.name || '游民名片'} + + 示例介绍 · 离线可逛 + + + + + + + {!member ? ( + + 没有这位游民 + + 这位朋友可能已离开,或者链接有点旧。回去再看看其他人吧。 + + goPage('/pages/social/people/index')} + > + 回去看看大家 + + + ) : ( + + + + + + + + + {member.online ? '在线' : '离线'} + + {member.vibe} + + {member.name} + + {member.title} + + + 📍 {member.city} + {member.timezone ? ` · ${member.timezone}` : ''} + + + + + + + setLiked((v) => !v)} + > + {liked ? '♥ 已关注' : '♡ 关注一下'} + + + goPage(`/pages/social/chat/index?intro=${intro}`) + } + > + 进群组打招呼 + + goPage('/pages/social/meetup/index')} + > + 语音视频场 + + goPage('/pages/social/date/index')} + > + 去左右滑 + + + + + + 关于 TA + {member.bio} + + ✨ 想认识: + {member.lookingFor} + + {member.availability ? ( + + 什么时候方便 · {member.availability} + + ) : null} + + + + 兴趣标签 + + {member.tags.map((t) => ( + + {t} + + ))} + + {member.languages?.length ? ( + <> + 语言 + + {member.languages.map((l) => ( + + {l} + + ))} + + + ) : null} + + + + {member.gallery && member.gallery.length > 0 ? ( + + 生活瞬间 + + {member.gallery.map((src) => ( + + ))} + + + ) : null} + + {similar.length > 0 ? ( + + 附近可能同城的人 + + {similar.map((m) => ( + + ))} + + + ) : null} + + + goPage('/pages/social/date/index')} + > + 去左右滑认识更多人 + + goPage('/pages/social/roster/index')} + > + 写写我的介绍 + + + + )} + + + + + ) +} + +export default function SocialPeopleProfilePage() { + return ( + + + + ) +} diff --git a/apps/miniprogram/h5/src/pages/social/roster/index.config.ts b/apps/miniprogram/h5/src/pages/social/roster/index.config.ts new file mode 100644 index 0000000..1b98d5f --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/roster/index.config.ts @@ -0,0 +1,6 @@ +export default definePageConfig({ + navigationBarTitleText: '我的介绍', + navigationBarBackgroundColor: '#0c0c0f', + navigationBarTextStyle: 'white', + backgroundColor: '#0c0c0f', +}) diff --git a/apps/miniprogram/h5/src/pages/social/roster/index.scss b/apps/miniprogram/h5/src/pages/social/roster/index.scss new file mode 100644 index 0000000..6363c2b --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/roster/index.scss @@ -0,0 +1 @@ +@import '../_components/social-subpage.scss'; \ No newline at end of file diff --git a/apps/miniprogram/h5/src/pages/social/roster/index.tsx b/apps/miniprogram/h5/src/pages/social/roster/index.tsx new file mode 100644 index 0000000..a667793 --- /dev/null +++ b/apps/miniprogram/h5/src/pages/social/roster/index.tsx @@ -0,0 +1,121 @@ +import { useState } from 'react' +import { Text, Input, Textarea } from '@tarojs/components' +import Taro from '@tarojs/taro' +import { MiniModuleGate } from '@/components/MiniModuleGate' +import { H5Box } from '@/components/H5Box' +import { MOCK_ROSTER } from '@/data/socialSeed' +import { goPage } from '@/utils/nav' +import { usePageShare } from '@/utils/pageShare' +import { usePageTrack } from '@/hooks/usePageTrack' +import { SocialAvatar } from '../_components/SocialAvatar' +import { SocialDock } from '../_components/SocialDock' +import { SocialExperience } from '../_components/SocialExperience' +import '@/styles/social-next/entry' +import './index.scss' + +const SEED = MOCK_ROSTER[0]! + +function SocialRoster() { + usePageShare({ title: 'nomadro · 我的介绍', path: '/pages/social/roster/index' }) + usePageTrack('social_roster') + const [name, setName] = useState(SEED.name) + const [title, setTitle] = useState(SEED.title) + const [city, setCity] = useState(SEED.city) + const [bio, setBio] = useState(SEED.bio) + const [lookingFor, setLookingFor] = useState(SEED.lookingFor) + + return ( + + + + + goPage('/pages/social/index')} + > + ← 首页 + + + 我的介绍 + 让别人更快认识你 + + + + + + + + + + {name || '未命名'} + + {title || '身份'} · {city || '城市'} + + + + + + + 昵称 + setName(e.detail.value)} + /> + + + 身份 + setTitle(e.detail.value)} + /> + + + 城市 + setCity(e.detail.value)} + /> + + + 简介 +