Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/deploy-modelscope.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ on:
branches: [main]
paths:
- 'app.py'
- 'admin/**'
- 'requirements.txt'
- 'Dockerfile'
- 'tests/**'
Expand Down
16 changes: 16 additions & 0 deletions AUTH-AND-DISCUSSION.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ Docker 监听 7860,持久化数据目录固定为 `/mnt/workspace/purplebook`

统计页面位于 `/analytics`,打开后直接显示累计、今日、每小时和所选时间范围的数据。小时视图支持今天、昨天和最近 90 天内的指定日期。今日指标每日 0 点重新计算,近 N 天指标使用滚动窗口,累计指标从有效统计数据的首日持续增长。该地址不放入读者页面的公开导航,知道固定网址即可访问。统计接口只提供聚合后的只读数据。

## 魔搭登录账号统计

`/analytics` 显示累计、今日和所选日期范围内的去重登录账号数。唯一采集入口为紫皮书的魔搭 OAuth 登录成功回调,不依赖点评、评论或渠道参数。取消登录、授权失败、匿名阅读和刷新会话不会新增登录记录。同一账号重复登录只计一个用户,登录次数另行累加。

账号登录记录保存在 `reading.sqlite3` 的 `account_login_daily`,与匿名 PV/UV 库分开。已有 `users` 中的账号全部来自历史登录,因此计入累计账号数;历史登录日期无法还原,留空,不以部署时间补造。今日与区间统计从功能上线后的成功登录开始记录,使用上海时区。

管理员在持有数据库的环境中运行以下命令导出账号名单:

```sh
python3 admin/export-login-accounts.py --database /mnt/workspace/purplebook/reading.sqlite3 > login-accounts.csv
```

CSV 一行对应一个魔搭登录账号,包含紫皮书内部用户 ID、魔搭 OIDC `sub`、魔搭用户名、首次/最近记录的登录时间和记录的登录次数。`sub` 是提供方返回的身份标识,不假定与魔搭内部数字用户 ID 相同;核对注册记录时需由魔搭侧解析对应账号。名单不通过公开统计接口提供。

当前登录流程未取得魔搭账号注册时间,所以登录人数不能直接称为“新增注册人数”;需将导出的魔搭身份与魔搭侧注册记录核对。首次登录紫皮书不代表首次注册魔搭。本功能不虚构注册时间或新注册标记。

## 身份与安全

使用 Authlib 完成 OIDC state、nonce、签名及身份校验。Cookie 中只保存随机服务端会话 ID、CSRF 与短期授权事务;不保存访问令牌。
Expand Down
40 changes: 40 additions & 0 deletions admin/export-login-accounts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Export successful Purplebook login identities for matching ModelScope registrations."""
import argparse
import csv
from datetime import datetime
from pathlib import Path
import sqlite3
import sys
from zoneinfo import ZoneInfo


def export_accounts(database, output):
# A read-only connection prevents an incorrect path from creating a new DB.
with sqlite3.connect(Path(database).resolve().as_uri()+'?mode=ro',uri=True) as conn:
conn.row_factory=sqlite3.Row
rows=conn.execute('''SELECT u.id,u.sub,p.username,
MIN(l.first_login) first_login,MAX(l.last_login) last_login,
COALESCE(SUM(l.login_count),0) login_count
FROM users u LEFT JOIN user_profiles p ON p.user_id=u.id
LEFT JOIN account_login_daily l ON l.user_id=u.id
GROUP BY u.id,u.sub,p.username ORDER BY first_login,u.id''')
writer=csv.writer(output)
writer.writerow(['purplebook_user_id','modelscope_sub','modelscope_username',
'first_recorded_login_at','last_recorded_login_at','recorded_login_count'])
for row in rows:
def timestamp(value):
return datetime.fromtimestamp(value,ZoneInfo('Asia/Shanghai')).isoformat() if value is not None else ''
writer.writerow([spreadsheet_text(row['id']),spreadsheet_text(row['sub']),spreadsheet_text(row['username'] or ''),
timestamp(row['first_login']),timestamp(row['last_login']),row['login_count']])


def spreadsheet_text(value):
# Account handles are external text; keep spreadsheet programs from evaluating it.
return "'"+value if value.startswith(('=','+','-','@','\t','\r','\n')) else value


if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--database',type=Path,required=True,help='Path to reading.sqlite3')
args=parser.parse_args()
export_accounts(args.database,sys.stdout)
17 changes: 17 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ def db():
CREATE TABLE IF NOT EXISTS wishes(id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), text TEXT NOT NULL, created INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS wishes_user_time ON wishes(user_id, created);
CREATE TABLE IF NOT EXISTS user_profiles(user_id TEXT PRIMARY KEY REFERENCES users(id), username TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS account_login_daily(user_id TEXT NOT NULL REFERENCES users(id), day TEXT NOT NULL, first_login INTEGER NOT NULL, last_login INTEGER NOT NULL, login_count INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(user_id, day));
CREATE INDEX IF NOT EXISTS account_logins_day ON account_login_daily(day);
CREATE TABLE IF NOT EXISTS entry_replies(entry_id TEXT PRIMARY KEY REFERENCES entries(id) ON DELETE CASCADE, parent_id TEXT REFERENCES entries(id) ON DELETE SET NULL);
''')

Expand Down Expand Up @@ -500,6 +502,17 @@ def read_hourly():
'updatedAt':current.isoformat(timespec='seconds'),
}

@app.get('/api/analytics/accounts')
def account_summary(days: int = Query(7,ge=1,le=90), start: str = '', end: str = ''):
today,first,last,span=analytics_range(days,start,end)
with db() as conn:
total=conn.execute('SELECT COUNT(*) FROM users').fetchone()[0]
selected=conn.execute('SELECT COUNT(DISTINCT user_id) FROM account_login_daily WHERE day BETWEEN ? AND ?',(first.isoformat(),last.isoformat())).fetchone()[0]
today_total=conn.execute('SELECT COUNT(*) FROM account_login_daily WHERE day=?',(today.isoformat(),)).fetchone()[0]
since=conn.execute('SELECT MIN(day) FROM account_login_daily').fetchone()[0]
return {'total':total,'today':today_total,'selected':selected,'trackedSince':since,
'range':{'start':first.isoformat(),'end':last.isoformat(),'days':span,'timezone':'Asia/Shanghai'}}

@app.get('/auth/login')
async def login(request: Request, return_to: str = '#home'):
if not enabled: raise HTTPException(503,'魔搭登录尚未配置')
Expand Down Expand Up @@ -545,6 +558,10 @@ async def callback(request: Request):
conn.execute('INSERT INTO user_profiles VALUES (?,?) ON CONFLICT(user_id) DO UPDATE SET username=excluded.username',(uid,username.strip()))
conn.execute('DELETE FROM sessions WHERE expires<=? OR id=?',(now,request.session.get('sid','')))
conn.execute('INSERT INTO sessions VALUES (?,?,?)',(sid,uid,now+7*86400))
day=datetime.fromtimestamp(now,analytics_timezone).date().isoformat()
conn.execute('''INSERT INTO account_login_daily(user_id,day,first_login,last_login,login_count)
VALUES (?,?,?,?,1) ON CONFLICT(user_id,day) DO UPDATE SET
last_login=MAX(last_login,excluded.last_login),login_count=login_count+1''',(uid,day,now,now))
target=request.session.get('return_to','#home')
request.session.clear()
request.session.update(sid=sid,csrf=secrets.token_urlsafe(32))
Expand Down
20 changes: 19 additions & 1 deletion assets/analytics-dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
}

function rangeLabel(data) {
if(data.range.days===1)return '今天';
if(data.range.days===1)return data.range.end===todayInShanghai()?'今天':data.range.end;
if(data.range.end===todayInShanghai())return `近 ${data.range.days} 天`;
return `${data.range.start} 至 ${data.range.end}`;
}
Expand Down Expand Up @@ -146,11 +146,29 @@
try {
const data=await request('/api/analytics/summary?'+query);
render(data);
await loadAccounts(query);
} catch(error) {
$('#dashboardStatus').textContent=error.message;
}
}

async function loadAccounts(query) {
for(const id of ['accountTotal','accountToday','accountSelected'])$('#'+id).textContent='—';
$('#accountNote').textContent='正在加载登录统计…';
try {
const data=await request('/api/analytics/accounts?'+query);
$('#accountTotal').textContent=number.format(data.total);
$('#accountToday').textContent=number.format(data.today);
$('#accountSelected').textContent=number.format(data.selected);
$('#accountRangeLabel').textContent=rangeLabel(data)+'登录账号';
$('#accountNote').textContent=data.trackedSince
?`登录日期自 ${data.trackedSince} 起记录;更早的账号只计入累计人数。`
:'登录日期将在功能上线后的首次成功登录时开始记录。';
} catch(error) {
$('#accountNote').textContent='登录统计加载失败:'+error.message;
}
}

async function loadHourly(date=todayInShanghai()) {
$('#dashboardStatus').textContent='';
try {
Expand Down
1 change: 1 addition & 0 deletions assets/analytics.css
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ a { color: inherit; }
.metric-grid strong { display: block; margin: 10px 0 7px; color: var(--brand); font-size: 32px; line-height: 1.1; }
.metric-grid small { color: var(--muted); font-size: 11px; }
.metric-grid .lifetime-metric { border-color: #d9cef0; background: linear-gradient(145deg,#fff 15%,#f8f4ff 100%); }
.account-metrics { grid-template-columns: repeat(3, 1fr); }
.panel { margin-top: 20px; padding: 24px; }
.panel > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; margin-bottom: 22px; }
.panel h2 { margin: 0; font-size: 20px; }
Expand Down
15 changes: 13 additions & 2 deletions assets/analytics.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<meta name="theme-color" content="#6b48e8">
<meta name="robots" content="noindex,nofollow">
<link rel="icon" href="assets/brand/book-mark.svg" type="image/svg+xml">
<link rel="stylesheet" href="assets/analytics.css?v=c9ba86246885">
<link rel="stylesheet" href="assets/analytics.css?v=cfa6f8f5a437">
<title>访问统计|魔搭紫皮书</title>
</head>
<body>
Expand Down Expand Up @@ -34,6 +34,17 @@
<article><span id="rangeUvLabel">近 7 天 UV</span><strong id="rangeUv">—</strong><small id="rangeUvCompare">正在计算</small></article>
</section>

<section class="panel" aria-labelledby="accountsTitle">
<header><div><h2 id="accountsTitle">魔搭账号登录</h2><p>统计在紫皮书页面使用魔搭账号成功登录的用户,按账号去重。</p></div></header>
<div class="metric-grid account-metrics">
<article><span>累计登录账号</span><strong id="accountTotal">—</strong><small>包含统计上线前已登录的账号</small></article>
<article><span>今日登录账号</span><strong id="accountToday">—</strong><small>同一账号今天只计一次</small></article>
<article><span id="accountRangeLabel">近 7 天登录账号</span><strong id="accountSelected">—</strong><small>同一账号在所选时间内只计一次</small></article>
</div>
<p class="hourly-note" id="accountNote">正在加载登录统计…</p>
<p class="hourly-note">登录账号不等于新注册账号。账号名单可由管理员导出,与魔搭注册记录核对。</p>
</section>

<section class="panel hourly-panel" aria-labelledby="hourlyTitle">
<header><div><h2 id="hourlyTitle">每小时访问趋势</h2><p id="hourlyMeta">正在加载小时数据…</p></div><div class="legend"><span class="pv-dot">PV</span><span class="uv-dot">UV</span></div></header>
<div class="hourly-toolbar" aria-label="小时统计日期">
Expand All @@ -58,6 +69,6 @@
<footer>累计指标持续增长 · 今日指标每日 0 点重新计算 · 小时明细保留 90 天 · 近 N 天为滚动窗口 · UV 为匿名浏览器标识的估算结果 · 统计时区:Asia/Shanghai</footer>
</main>
</div>
<script src="assets/analytics-dashboard.js?v=8c6cda54ad5e"></script>
<script src="assets/analytics-dashboard.js?v=228821153591"></script>
</body>
</html>
2 changes: 1 addition & 1 deletion scripts/deploy-modelscope.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ try {
run('git', ['config', 'user.email', '41898282+github-actions[bot]@users.noreply.github.com'], target);

// Export committed files only. Deployment scripts and credentials stay out of the site.
const files = ['Dockerfile', 'requirements.txt', 'app.py', 'index.html', 'favicon.svg', 'assets', 'content', 'chapters', 'CONTRIBUTING.md', 'README.md', 'README.zh-CN.md', 'LICENSE'];
const files = ['Dockerfile', 'requirements.txt', 'app.py', 'index.html', 'favicon.svg', 'assets', 'content', 'chapters', 'admin', 'CONTRIBUTING.md', 'README.md', 'README.zh-CN.md', 'LICENSE'];
const archive = join(temporary, 'site.tar');
const buildScripts=['scripts/build-content.py','scripts/chapter_markdown.py','scripts/version-assets.mjs'];
run('git', ['archive', '--format=tar', '--output', archive, commit, '--', ...files, ...buildScripts]);
Expand Down
121 changes: 121 additions & 0 deletions tests/test_login_accounts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import csv
from datetime import datetime, timedelta
import importlib.util
import io
from pathlib import Path
from unittest.mock import AsyncMock
from zoneinfo import ZoneInfo

import pytest
from fastapi.testclient import TestClient

from app import create_app


@pytest.fixture
def login_site(tmp_path,monkeypatch):
monkeypatch.setenv('APP_BASE_URL','http://127.0.0.1:7860')
monkeypatch.setenv('OAUTH_CLIENT_ID','test-client')
monkeypatch.setenv('OAUTH_CLIENT_SECRET','test-secret')
app=create_app(tmp_path)
app.state.oauth.modelscope.authorize_access_token=AsyncMock(return_value={
'userinfo':{'sub':'modelscope-123','name':'读者','preferred_username':'reader'}})
return app,TestClient(app,base_url='http://127.0.0.1:7860'),tmp_path


def test_login_without_comment_is_counted_and_repeated_logins_are_deduplicated(login_site):
app,client,_=login_site
assert client.get('/api/analytics/accounts').json()['total']==0
for _ in range(2):
assert client.get('/auth/callback',follow_redirects=False).status_code==303
for _ in range(3):
client.get('/api/session')
summary=client.get('/api/analytics/accounts').json()
assert (summary['total'],summary['today'],summary['selected'])==(1,1,1)
with app.state.db() as db:
row=db.execute('SELECT * FROM account_login_daily').fetchone()
assert row['login_count']==2
assert row['first_login']<=row['last_login']
assert db.execute('SELECT COUNT(*) FROM entries').fetchone()[0]==0
assert 'modelscope-123' not in str(summary) and 'reader' not in str(summary)


def test_failed_or_cancelled_login_does_not_add_accounts(login_site):
app,client,_=login_site
# The real provider rejects missing/invalid OAuth state before saving an identity.
del app.state.oauth.modelscope.authorize_access_token
response=client.get('/auth/callback?error=access_denied',follow_redirects=False)
assert 'login=failed' in response.headers['location']
assert client.get('/api/analytics/accounts').json()['total']==0


def test_legacy_accounts_keep_unknown_login_dates_and_survive_restart(login_site):
app,client,path=login_site
with app.state.db() as db:
db.execute('INSERT INTO users VALUES (?,?,?)',('old','old-sub','历史读者'))
summary=client.get('/api/analytics/accounts').json()
assert summary['total']==1 and summary['today']==summary['selected']==0
assert summary['trackedSince'] is None
client.get('/auth/callback',follow_redirects=False)
restarted=TestClient(create_app(path))
summary=restarted.get('/api/analytics/accounts').json()
assert summary['total']==2 and summary['today']==summary['selected']==1


def test_date_range_counts_each_account_once_across_days(login_site):
app,client,_=login_site
client.get('/auth/callback',follow_redirects=False)
today=datetime.now(ZoneInfo('Asia/Shanghai')).date()
yesterday=(today-timedelta(days=1)).isoformat()
with app.state.db() as db:
uid=db.execute('SELECT id FROM users').fetchone()[0]
db.execute('INSERT INTO users VALUES (?,?,?)',('second','second-sub','另一个账号'))
for user_id in (uid,'second'):
db.execute('INSERT INTO account_login_daily VALUES (?,?,?,?,?)',(user_id,yesterday,1,2,3))
assert client.get('/api/analytics/accounts?days=2').json()['selected']==2
summary=client.get(f'/api/analytics/accounts?start={today}&end={today}').json()
assert summary['selected']==summary['today']==1
assert summary['range']['timezone']=='Asia/Shanghai'
assert client.get('/api/analytics/accounts?days=0').status_code==422
assert client.get('/api/analytics/accounts?start=bad&end=bad').status_code==422


def test_upgrade_existing_database_preserves_accounts_without_fabricated_dates(login_site):
app,_,path=login_site
with app.state.db() as db:
db.execute('INSERT INTO users VALUES (?,?,?)',('legacy','legacy-sub','已有账号'))
db.execute('DROP TABLE account_login_daily')
upgraded=TestClient(create_app(path))
summary=upgraded.get('/api/analytics/accounts').json()
assert summary['total']==1
assert summary['selected']==summary['today']==0
assert summary['trackedSince'] is None


def test_export_has_one_row_per_identity_and_no_invented_registration_date(login_site):
app,client,path=login_site
client.get('/auth/callback',follow_redirects=False)
client.get('/auth/callback',follow_redirects=False)
with app.state.db() as db:
db.execute('INSERT INTO users VALUES (?,?,?)',('old','old-sub','历史读者'))
db.execute('INSERT INTO user_profiles VALUES (?,?)',('old','=formula'))
spec=importlib.util.spec_from_file_location('export_accounts',Path(__file__).resolve().parents[1]/'admin/export-login-accounts.py')
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
output=io.StringIO();module.export_accounts(path/'reading.sqlite3',output)
rows=list(csv.DictReader(io.StringIO(output.getvalue())))
assert len(rows)==2
by_sub={row['modelscope_sub']:row for row in rows}
assert by_sub['modelscope-123']['recorded_login_count']=='2'
assert by_sub['modelscope-123']['first_recorded_login_at'].endswith('+08:00')
assert by_sub['old-sub']['first_recorded_login_at']==''
assert by_sub['old-sub']['recorded_login_count']=='0'
assert by_sub['old-sub']['modelscope_username']=="'=formula"
assert not any('registered' in key for key in rows[0])


def test_analytics_page_has_account_metrics(login_site):
_,client,_=login_site
page=client.get('/analytics').text
assert 'id="accountTotal"' in page and 'id="accountSelected"' in page
assert client.get('/api/analytics/accounts').headers['cache-control']=='no-store'
assert client.get('/admin/export-login-accounts.py').status_code==404
Loading