Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat: resolve analytics page links and rank popular photos

Timothy Yinc4b27cde6c73
diff --git a/apps/cloud/app/components/CloudMapSettings.vue b/apps/cloud/app/components/CloudMapSettings.vue
index 7999a6db..6c58d39f 100644
--- a/apps/cloud/app/components/CloudMapSettings.vue
+++ b/apps/cloud/app/components/CloudMapSettings.vue
@@ -56,7 +56,7 @@ async function save() {
{{
t(
'Use platform maps or your own Mapbox / MapTiler browser keys for this site. These keys and style URLs are public. Restrict them to your gallery domains; never enter a secret key.',
- '此站点可使用平台地图,或配置自己的 Mapbox/MapTiler 浏览器公共密钥。密钥及样式地址会公开发送到浏览器,请限制允许的图库域名,切勿填写服务端密钥。',
+ '此站点可使用平台地图,或配置自己的 Mapbox/MapTiler 浏览器公共密钥。密钥及样式地址会公开发送到浏览器,请限制允许的图库域名,切勿填写服务端密钥。',
)
}}
</p>
diff --git a/apps/cloud/app/pages/analytics.vue b/apps/cloud/app/pages/analytics.vue
index 53caaabd..9569e2a1 100644
--- a/apps/cloud/app/pages/analytics.vue
+++ b/apps/cloud/app/pages/analytics.vue
@@ -95,7 +95,7 @@ await load()
>
<label class="grid gap-2"
>{{ tr('Site', '站点')
- }}<select
+ }}<CfSelect
v-model="siteId"
@change="load"
class="cf-input"
@@ -108,7 +108,7 @@ await load()
>
{{ site.name }}
</option>
- </select></label
+ </CfSelect></label
>
<CfAnalyticsRange
v-model="range"
diff --git a/apps/cloud/app/pages/sites/[siteId]/overview.vue b/apps/cloud/app/pages/sites/[siteId]/overview.vue
index 3f22238a..eddde8d0 100644
--- a/apps/cloud/app/pages/sites/[siteId]/overview.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/overview.vue
@@ -67,6 +67,33 @@ const actions = computed(() => [
help: t('cloud.dashboard.storageHelp'),
},
])
+const { locale } = useI18n()
+const zh = computed(() => locale.value.startsWith('zh'))
+const billing = useWorkspaceBilling()
+const analyticsEnabled = computed(
+ () =>
+ !!billing.data.value?.plan?.analytics &&
+ billing.selected.value === site.value.workspaceId,
+)
+const requestFetch = useRequestFetch()
+const {
+ data: popular,
+ status: popularStatus,
+ error: popularError,
+ refresh: refreshPopular,
+} = useAsyncData(
+ () => `site-popular-${site.value.siteId}-${analyticsEnabled.value}`,
+ async () =>
+ analyticsEnabled.value
+ ? requestFetch<any>('/api/analytics/report', {
+ query: {
+ workspaceId: site.value.workspaceId,
+ siteId: site.value.siteId,
+ popular: '1',
+ },
+ })
+ : null,
+)
</script>
<template>
<div class="cf-dashboard cf-site-dashboard">
@@ -132,68 +159,144 @@ const actions = computed(() => [
/></NuxtLink></div
></CfCard>
</div>
- <CfCard class="cf-dashboard-panel"
- ><h2>{{ $t('cloud.dashboard.siteHealth') }}</h2>
- <CfSkeleton
- v-if="!ready && !loadError"
- class="h-32 w-full"
- />
- <ul
- v-else-if="ready"
- class="cf-site-health-list"
+ <div class="min-w-0 space-y-4">
+ <CfCard
+ v-if="analyticsEnabled"
+ class="cf-dashboard-panel"
+ >
+ <div class="cf-dashboard-section-heading">
+ <h2>{{ zh ? '最受欢迎' : 'Most popular' }}</h2>
+ <span class="cf-field-hint">{{
+ zh ? '近 7 天 · 访问量' : 'Past 7 days · Page views'
+ }}</span>
+ </div>
+ <CfSkeleton
+ v-if="popularStatus === 'pending'"
+ class="h-32 w-full"
+ />
+ <div
+ v-else-if="popularError"
+ role="status"
+ >
+ <p class="cf-field-hint">
+ {{
+ zh ? '暂时无法加载访问排名。' : 'Unable to load popular photos.'
+ }}
+ </p>
+ <button
+ type="button"
+ class="cf-text-link"
+ @click="refreshPopular()"
+ >
+ {{ zh ? '重试' : 'Retry' }}
+ </button>
+ </div>
+ <ol
+ v-else-if="popular?.pages?.length"
+ class="cf-popular-photos"
+ >
+ <li
+ v-for="(photo, index) in popular.pages"
+ :key="photo.label"
+ >
+ <span class="cf-field-hint">{{ index + 1 }}</span
+ ><CfAnalyticsPageLink
+ :row="photo"
+ :zh="zh"
+ /><span class="cf-field-hint">{{
+ photo.pv.toLocaleString()
+ }}</span>
+ </li>
+ </ol>
+ <p
+ v-else
+ class="cf-field-hint"
+ >
+ {{
+ zh
+ ? '近 7 天暂无照片访问记录。'
+ : 'No photo views in the past 7 days.'
+ }}
+ </p>
+ </CfCard>
+ <CfCard class="cf-dashboard-panel"
+ ><h2>{{ $t('cloud.dashboard.siteHealth') }}</h2>
+ <CfSkeleton
+ v-if="!ready && !loadError"
+ class="h-32 w-full"
+ />
+ <ul
+ v-else-if="ready"
+ class="cf-site-health-list"
+ >
+ <li>
+ <component
+ :is="failed ? CircleAlert : CheckCircle2"
+ :size="17"
+ />
+ <div>
+ <strong>{{
+ $t(
+ failed
+ ? 'cloud.dashboard.needsAttention'
+ : 'cloud.dashboard.processingHealthy',
+ )
+ }}</strong>
+ <p>
+ {{
+ failed
+ ? $t('cloud.dashboard.failedJobs', { count: failed })
+ : $t('cloud.dashboard.processingHelp')
+ }}
+ </p>
+ </div>
+ </li>
+ <li>
+ <HardDrive :size="17" />
+ <div>
+ <strong>{{
+ $t(
+ connection?.pool_id
+ ? 'cloud.messages.platformStorage'
+ : connection
+ ? 'cloud.billing.byos'
+ : 'cloud.dashboard.storagePending',
+ )
+ }}</strong>
+ <p>{{ $t('cloud.dashboard.storageHelp') }}</p>
+ </div>
+ </li>
+ <li>
+ <Globe :size="17" />
+ <div>
+ <strong>{{
+ $t(
+ site.published
+ ? 'cloud.messages.publishedGallery'
+ : 'cloud.messages.privateDraft',
+ )
+ }}</strong>
+ <p>{{ $t('cloud.dashboard.publicationHelp') }}</p>
+ </div>
+ </li>
+ </ul></CfCard
>
- <li>
- <component
- :is="failed ? CircleAlert : CheckCircle2"
- :size="17"
- />
- <div>
- <strong>{{
- $t(
- failed
- ? 'cloud.dashboard.needsAttention'
- : 'cloud.dashboard.processingHealthy',
- )
- }}</strong>
- <p>
- {{
- failed
- ? $t('cloud.dashboard.failedJobs', { count: failed })
- : $t('cloud.dashboard.processingHelp')
- }}
- </p>
- </div>
- </li>
- <li>
- <HardDrive :size="17" />
- <div>
- <strong>{{
- $t(
- connection?.pool_id
- ? 'cloud.messages.platformStorage'
- : connection
- ? 'cloud.billing.byos'
- : 'cloud.dashboard.storagePending',
- )
- }}</strong>
- <p>{{ $t('cloud.dashboard.storageHelp') }}</p>
- </div>
- </li>
- <li>
- <Globe :size="17" />
- <div>
- <strong>{{
- $t(
- site.published
- ? 'cloud.messages.publishedGallery'
- : 'cloud.messages.privateDraft',
- )
- }}</strong>
- <p>{{ $t('cloud.dashboard.publicationHelp') }}</p>
- </div>
- </li>
- </ul></CfCard
- >
+ </div>
</div>
</div>
</template>
+
+<style scoped>
+.cf-popular-photos {
+ display: grid;
+ gap: 12px;
+ margin-top: 16px;
+}
+.cf-popular-photos li {
+ display: grid;
+ grid-template-columns: 18px minmax(0, 1fr) auto;
+ gap: 10px;
+ align-items: baseline;
+ overflow-wrap: anywhere;
+}
+</style>
diff --git a/apps/cloud/app/plugins/visit-analytics.client.ts b/apps/cloud/app/plugins/visit-analytics.client.ts
index 0900dc44..121dc225 100644
--- a/apps/cloud/app/plugins/visit-analytics.client.ts
+++ b/apps/cloud/app/plugins/visit-analytics.client.ts
@@ -1,5 +1,13 @@
-import { installVisitTracking } from '../../../shared/analytics/tracker'
+import {
+ installVisitTracking,
+ visitRoutePath,
+} from '../../../shared/analytics/tracker'
export default defineNuxtPlugin((app) => {
const router = useRouter()
- installVisitTracking(app, () => router.currentRoute.value.path)
+ const track = installVisitTracking(app, () =>
+ visitRoutePath(router.currentRoute.value),
+ )
+ router.afterEach((_to, _from, failure) => {
+ if (!failure) track()
+ })
})
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index c13bb48d..de561d51 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -664,7 +664,7 @@
"fileBytes": "Maximum file size",
"sites": "Sites",
"photos": "Photographs",
- "analytics": "Site analytics",
+ "analytics": "Analytics",
"photosQuotaHelp": "Photo usage includes uploaded photographs and reserved slots for uploads that have been requested but are not yet complete. Reservations prevent concurrent uploads from exceeding your plan limit; they do not mean those uploads have completed.",
"customDomains": "Custom domains",
"byos": "Custom S3 storage",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 1f5eb8ee..2d5f779e 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -664,7 +664,7 @@
"fileBytes": "单文件上限",
"sites": "站点数量",
"photos": "照片数量",
- "analytics": "站点分析",
+ "analytics": "分析",
"photosQuotaHelp": "照片配额按已上传的照片与已申请上传但尚未完成的预留名额合计。预留名额用于防止并发上传超出套餐上限,不代表这些照片已上传完成。",
"customDomains": "自定义域名",
"byos": "自定义 S3 存储",
diff --git a/apps/cloud/server/api/analytics/report.get.ts b/apps/cloud/server/api/analytics/report.get.ts
index 60951c31..6b931506 100644
--- a/apps/cloud/server/api/analytics/report.get.ts
+++ b/apps/cloud/server/api/analytics/report.get.ts
@@ -1,3 +1,6 @@
+import { popularPhotos } from '../../../../../packages/platform/src/analytics-popular'
+import { allRows } from '../../../../../packages/platform/src/subscriptions'
+import { resolveAnalyticsPages } from '../../../../../packages/platform/src/analytics-pages'
import { getQuery, createError, setResponseHeader } from 'h3'
import {
definePlatformHandler,
@@ -42,6 +45,46 @@ export default definePlatformHandler(async (event) => {
.first())
)
throw createError({ statusCode: 404 })
+ if (query.popular === '1') {
+ if (!filter.siteId) throw createError({ statusCode: 400 })
+ const range = {
+ ...analyticsFilter({}),
+ workspaceId: filter.workspaceId,
+ siteId: filter.siteId,
+ kind: 'site' as const,
+ }
+ const photos = await allRows<{ id: string }>(
+ db
+ .prepare('SELECT id FROM cloud_photos WHERE site_id=? AND deleted=0')
+ .bind(filter.siteId),
+ )
+ const env = event.context.cloudflare?.env ?? {}
+ try {
+ const pages = await popularPhotos(
+ {
+ accountId: String(env.ANALYTICS_ACCOUNT_ID ?? ''),
+ token: String(env.ANALYTICS_API_TOKEN ?? ''),
+ dataset: String(env.ANALYTICS_DATASET ?? ''),
+ },
+ range,
+ photos.map((p) => p.id),
+ )
+ return await resolveAnalyticsPages(
+ db,
+ { pages, from: range.from, to: range.to },
+ range,
+ )
+ } catch {
+ throw createError({
+ statusCode: 503,
+ statusMessage: 'Analytics is temporarily unavailable',
+ })
+ }
+ }
// Client kind/scope can never broaden this query to portal traffic or another tenant.
- return analyticsReport(event, { ...filter, kind: 'site' })
+ return resolveAnalyticsPages(
+ db,
+ await analyticsReport(event, { ...filter, kind: 'site' }),
+ { ...filter, kind: 'site' },
+ )
})
diff --git a/apps/shared/analytics/tracker.ts b/apps/shared/analytics/tracker.ts
index d614818b..85b22f01 100644
--- a/apps/shared/analytics/tracker.ts
+++ b/apps/shared/analytics/tracker.ts
@@ -1,3 +1,17 @@
+/** Only the album photo identity is retained; arbitrary query parameters never enter paths. */
+export function visitRoutePath(route: {
+ path: string
+ query: Record<string, unknown>
+}) {
+ const photo = route.query.photo
+ return /^\/albums\/[^/]+\/?$/.test(route.path) &&
+ typeof photo === 'string' &&
+ /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(
+ photo,
+ )
+ ? `${route.path.replace(/\/$/, '')}/${photo}`
+ : route.path
+}
/** Explicit page views cover SSR entry and SPA navigation; assets and prefetches are excluded. */
export function installVisitTracking(
app: {
@@ -37,4 +51,5 @@ export function installVisitTracking(
}
app.hook('app:mounted', track)
app.hook('page:finish', track)
+ return track
}
diff --git a/apps/site/app/plugins/visit-analytics.client.ts b/apps/site/app/plugins/visit-analytics.client.ts
index 0900dc44..121dc225 100644
--- a/apps/site/app/plugins/visit-analytics.client.ts
+++ b/apps/site/app/plugins/visit-analytics.client.ts
@@ -1,5 +1,13 @@
-import { installVisitTracking } from '../../../shared/analytics/tracker'
+import {
+ installVisitTracking,
+ visitRoutePath,
+} from '../../../shared/analytics/tracker'
export default defineNuxtPlugin((app) => {
const router = useRouter()
- installVisitTracking(app, () => router.currentRoute.value.path)
+ const track = installVisitTracking(app, () =>
+ visitRoutePath(router.currentRoute.value),
+ )
+ router.afterEach((_to, _from, failure) => {
+ if (!failure) track()
+ })
})
diff --git a/packages/gallery/i18n/locales/ja.json b/packages/gallery/i18n/locales/ja.json
index 06c502a0..f30fda79 100644
--- a/packages/gallery/i18n/locales/ja.json
+++ b/packages/gallery/i18n/locales/ja.json
@@ -224,7 +224,7 @@
"hint": {
"livePhoto": {
"mobile": "長押しでライブフォトを再生 · ダブルタップまたはピンチでズーム",
- "desktop": "再生アイコンにホバー · ダブルクリック/スクロールでズーム"
+ "desktop": "再生アイコンにホバー · ダブルクリック/スクロールでズーム"
},
"mobile": "ダブルタップまたはピンチでズーム",
"desktop": "ダブルクリックまたはマウスホイールでズーム"
diff --git a/packages/gallery/i18n/locales/zh-Hant-HK.json b/packages/gallery/i18n/locales/zh-Hant-HK.json
index 87758b9f..e7fe6f7c 100644
--- a/packages/gallery/i18n/locales/zh-Hant-HK.json
+++ b/packages/gallery/i18n/locales/zh-Hant-HK.json
@@ -220,7 +220,7 @@
"hint": {
"livePhoto": {
"mobile": "長按播放原況照片 · 點兩下或兩指縮放",
- "desktop": "滑鼠移到左上角播放 · 點兩下/滾輪縮放"
+ "desktop": "滑鼠移到左上角播放 · 點兩下/滾輪縮放"
},
"mobile": "點兩下或兩指縮放",
"desktop": "點兩下或用滑鼠滾輪縮放"
@@ -280,7 +280,7 @@
"artist": "攝影師",
"software": "軟件",
"tz": "時區",
- "country": "國家/地區",
+ "country": "國家/地區",
"city": "城市",
"gps": {
"title": "座標"
diff --git a/packages/gallery/i18n/locales/zh-Hant-TW.json b/packages/gallery/i18n/locales/zh-Hant-TW.json
index 2233ea45..ea2dc88d 100644
--- a/packages/gallery/i18n/locales/zh-Hant-TW.json
+++ b/packages/gallery/i18n/locales/zh-Hant-TW.json
@@ -220,7 +220,7 @@
"hint": {
"livePhoto": {
"mobile": "長按播放原況照片 · 點兩下或雙指縮放",
- "desktop": "游標移到左上角播放 · 點兩下/滾輪縮放"
+ "desktop": "游標移到左上角播放 · 點兩下/滾輪縮放"
},
"mobile": "點兩下或雙指縮放",
"desktop": "點兩下或使用滑鼠滾輪縮放"
diff --git a/packages/platform/src/analytics-archive.ts b/packages/platform/src/analytics-archive.ts
index 2ff70ddf..d77c4263 100644
--- a/packages/platform/src/analytics-archive.ts
+++ b/packages/platform/src/analytics-archive.ts
@@ -1,3 +1,4 @@
+import { PAGE_LABEL_SQL } from './analytics-pages.ts'
import type { PlatformD1 } from './index.ts'
import { allRows } from './subscriptions.ts'
import {
@@ -13,7 +14,7 @@ const DAY = 86400000,
DETAIL_LIMIT = 5000
const dimensions = [
['summary', "''"],
- ['pages', 'blob6'],
+ ['pages', PAGE_LABEL_SQL],
['sources', 'blob8'],
['countries', 'blob9'],
['browsers', 'blob10'],
diff --git a/packages/platform/src/analytics-pages.ts b/packages/platform/src/analytics-pages.ts
new file mode 100644
index 00000000..ca0e17be
--- /dev/null
+++ b/packages/platform/src/analytics-pages.ts
@@ -0,0 +1,221 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows } from './subscriptions.ts'
+import type { AnalyticsFilter, AnalyticsRow } from './analytics.ts'
+/** Attribution survives multi-site aggregation and daily archival. */
+export const PAGE_LABEL_SQL = "format('{}|{}|{}',blob4,blob5,blob6)"
+export function decodeAnalyticsPage(value: string) {
+ const match = /^(\d+)\|([^|]+)\|([\s\S]*)$/.exec(value)
+ if (!match) return null
+ const siteId = Number(match[1]),
+ host = match[2]!,
+ path = match[3]!
+ if (
+ !Number.isSafeInteger(siteId) ||
+ siteId < 0 ||
+ !/^([a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)$/.test(host) ||
+ host.length > 253 ||
+ !path.startsWith('/') ||
+ path.startsWith('//')
+ )
+ return null
+ return { siteId, host, path }
+}
+export type AnalyticsLink = { title: string; href?: string; kind?: string }
+export type AnalyticsPage = {
+ key: string
+ path: string
+ site: AnalyticsLink
+ segments: AnalyticsLink[]
+}
+export async function resolveAnalyticsPages<
+ T extends { pages: AnalyticsRow[] },
+>(db: PlatformD1, report: T, filter: AnalyticsFilter, now = Date.now()) {
+ const entries = report.pages.map((row) => ({
+ row,
+ context:
+ decodeAnalyticsPage(row.label) ??
+ (filter.siteId && row.label.startsWith('/')
+ ? { siteId: filter.siteId, host: '', path: row.label }
+ : null),
+ }))
+ const ids = [
+ ...new Set(
+ entries.flatMap((e) => (e.context?.siteId ? [e.context.siteId] : [])),
+ ),
+ ]
+ const sites = new Map<number, any>(),
+ domains = new Map<number, any[]>()
+ if (ids.length) {
+ const marks = ids.map(() => '?').join(',')
+ for (const site of await allRows<any>(
+ db
+ .prepare(
+ `SELECT s.id,s.workspace_id,s.name,s.gallery_title,s.published,s.suspended,COALESCE(c.suspended,0) AS owner_suspended FROM platform_sites s LEFT JOIN platform_workspaces w ON w.id=s.workspace_id LEFT JOIN platform_account_controls c ON c.user_id=w.owner_user_id WHERE s.id IN (${marks})${filter.workspaceId ? ' AND s.workspace_id=?' : ''}`,
+ )
+ .bind(...ids, ...(filter.workspaceId ? [filter.workspaceId] : [])),
+ ))
+ sites.set(Number(site.id), site)
+ for (const domain of await allRows<any>(
+ db
+ .prepare(
+ `SELECT d.site_id,d.hostname,COALESCE(c.is_primary,0) AS is_primary,d.kind FROM platform_domains d LEFT JOIN platform_custom_domains c ON c.hostname=d.hostname AND c.site_id=d.site_id WHERE d.site_id IN (${marks}) AND d.active=1 AND d.verified=1 AND (d.kind<>'custom' OR (c.state='active' AND c.verified_at>=?)) AND (d.kind<>'alias' OR d.redirect_until>?) ORDER BY is_primary DESC,CASE WHEN d.kind='default' THEN 0 ELSE 1 END,d.hostname`,
+ )
+ .bind(...ids, now - 3600000, now),
+ )) {
+ const list = domains.get(Number(domain.site_id)) ?? []
+ list.push(domain)
+ domains.set(Number(domain.site_id), list)
+ }
+ }
+ const paths = entries
+ .filter((e) => e.context && sites.has(e.context.siteId))
+ .map((e) => e.context!)
+ const photoIds = [
+ ...new Set(
+ paths.flatMap((p) => {
+ const parts = p.path.split('/').filter(Boolean)
+ return parts[0] === 'albums' && parts.length === 3
+ ? [parts[2]!]
+ : parts.length === 1
+ ? [parts[0]!]
+ : []
+ }),
+ ),
+ ]
+ const albumSlugs = [
+ ...new Set(
+ paths.flatMap((p) => {
+ const parts = p.path.split('/').filter(Boolean)
+ return parts[0] === 'albums' && parts[1] ? [parts[1]] : []
+ }),
+ ),
+ ]
+ const photos = new Map<string, any>(),
+ albums = new Map<string, any>()
+ if (ids.length && photoIds.length)
+ for (const p of await allRows<any>(
+ db
+ .prepare(
+ `SELECT site_id,id,title FROM cloud_photos WHERE deleted=0 AND site_id IN (${ids.map(() => '?')}) AND id IN (${photoIds.map(() => '?')})`,
+ )
+ .bind(...ids, ...photoIds),
+ ))
+ if (sites.has(Number(p.site_id))) photos.set(`${p.site_id}:${p.id}`, p)
+ if (ids.length && albumSlugs.length)
+ for (const a of await allRows<any>(
+ db
+ .prepare(
+ `SELECT a.site_id,a.id,a.title,sl.slug,current.slug AS canonical FROM cloud_albums a LEFT JOIN cloud_album_slugs sl ON sl.site_id=a.site_id AND sl.album_id=a.id LEFT JOIN cloud_album_slugs current ON current.site_id=a.site_id AND current.album_id=a.id AND current.is_current=1 WHERE a.site_id IN (${ids.map(() => '?')}) AND (sl.slug IN (${albumSlugs.map(() => '?')}) OR a.id IN (${albumSlugs.map(() => '?')}))`,
+ )
+ .bind(...ids, ...albumSlugs, ...albumSlugs),
+ )) {
+ if (!sites.has(Number(a.site_id))) continue
+ albums.set(`${a.site_id}:${a.slug}`, a)
+ albums.set(`${a.site_id}:${a.id}`, a)
+ }
+ const memberships = new Set<string>()
+ if (ids.length && photoIds.length && albumSlugs.length)
+ for (const item of await allRows<{
+ site_id: number
+ album_id: string
+ photo_id: string
+ }>(
+ db
+ .prepare(
+ `SELECT site_id,album_id,photo_id FROM cloud_album_photos WHERE site_id IN (${ids.map(() => '?')}) AND photo_id IN (${photoIds.map(() => '?')})`,
+ )
+ .bind(...ids, ...photoIds),
+ ))
+ memberships.add(`${item.site_id}:${item.album_id}:${item.photo_id}`)
+ return {
+ ...report,
+ pages: entries.map(({ row, context }) => {
+ if (!context) return row
+ const { siteId, host, path } = context,
+ site = sites.get(siteId)
+ if (siteId && (!site || (filter.siteId && filter.siteId !== siteId)))
+ return { ...row, label: path }
+ const choices = domains.get(siteId) ?? [],
+ domain =
+ choices.find((d) => d.is_primary) ||
+ choices.find((d) => d.hostname === host) ||
+ choices[0]
+ const origin = siteId
+ ? domain
+ ? `https://${domain.hostname}`
+ : undefined
+ : `https://${host}`
+ const available =
+ !siteId || (site.published && !site.suspended && !site.owner_suspended)
+ const url = (suffix: string) =>
+ available && origin ? origin + suffix : undefined
+ const page: AnalyticsPage = {
+ key: row.label,
+ path,
+ site: {
+ title:
+ site?.gallery_title ||
+ site?.name ||
+ (host === 'app.chronoframe.art'
+ ? 'ChronoFrame Cloud'
+ : host === 'chronoframe.art'
+ ? 'ChronoFrame'
+ : host),
+ href: url('/'),
+ },
+ segments: [],
+ }
+ const parts = path
+ .split('/')
+ .filter(Boolean)
+ .map((segment) => {
+ try {
+ return decodeURIComponent(segment)
+ } catch {
+ return segment
+ }
+ })
+ if (!parts.length) return { ...row, label: path, page }
+ if (parts[0] === 'albums') {
+ page.segments.push({
+ title: 'Albums',
+ kind: 'albums',
+ href: url('/albums'),
+ })
+ if (parts[1]) {
+ const album = albums.get(`${siteId}:${parts[1]}`),
+ albumPath = `/albums/${encodeURIComponent(album?.canonical || parts[1])}`
+ page.segments.push({
+ title: album?.title || parts[1],
+ href: album ? url(albumPath) : undefined,
+ })
+ if (parts[2]) {
+ const photo = photos.get(`${siteId}:${parts[2]}`)
+ page.segments.push({
+ title: photo?.title || parts[2],
+ href: photo
+ ? url(
+ album &&
+ memberships.has(`${siteId}:${album.id}:${photo.id}`)
+ ? `${albumPath}?photo=${encodeURIComponent(photo.id)}`
+ : `/${encodeURIComponent(photo.id)}`,
+ )
+ : undefined,
+ })
+ }
+ }
+ } else if (parts.length === 1 && photos.has(`${siteId}:${parts[0]}`)) {
+ const photo = photos.get(`${siteId}:${parts[0]}`)
+ page.segments.push({
+ title: photo.title || photo.id,
+ href: url(`/${encodeURIComponent(photo.id)}`),
+ })
+ } else
+ page.segments.push({
+ title: path.slice(1),
+ href: !path.includes(':') ? url(path) : undefined,
+ })
+ return { ...row, label: path, page }
+ }),
+ }
+}
diff --git a/packages/platform/src/analytics-popular.ts b/packages/platform/src/analytics-popular.ts
new file mode 100644
index 00000000..5d3edf74
--- /dev/null
+++ b/packages/platform/src/analytics-popular.ts
@@ -0,0 +1,91 @@
+import {
+ analyticsQueries,
+ type AnalyticsConfig,
+ type AnalyticsFilter,
+ type AnalyticsRow,
+} from './analytics.ts'
+const cache = new Map<string, { until: number; rows: AnalyticsRow[] }>()
+/** Query every current photo, merging root and album views before ranking. Each chunk's top five suffices for the global top five. */
+export async function popularPhotos(
+ config: AnalyticsConfig,
+ filter: AnalyticsFilter,
+ ids: string[],
+ fetcher: typeof fetch = fetch,
+): Promise<AnalyticsRow[]> {
+ if (!/^[a-f0-9]{32}$/.test(config.accountId) || !config.token)
+ throw new Error('analytics_not_configured')
+ if (!filter.siteId || !filter.workspaceId || filter.kind !== 'site')
+ throw new Error('invalid_analytics_scope')
+ const valid = [
+ ...new Set(ids.filter((id) => /^[a-f0-9-]{36}$/i.test(id))),
+ ].sort()
+ const key = JSON.stringify([config.accountId, config.dataset, filter, valid])
+ const hit = cache.get(key)
+ if (hit && hit.until > Date.now()) return hit.rows
+ const base = analyticsQueries(config.dataset, filter).summary.replace(
+ / FORMAT JSON$/,
+ '',
+ )
+ const photo = 'substring(blob6, length(blob6) - 35, 36)'
+ const chunks: string[][] = []
+ for (let i = 0; i < valid.length; i += 100)
+ chunks.push(valid.slice(i, i + 100))
+ const rows: AnalyticsRow[] = []
+ let cursor = 0
+ await Promise.all(
+ Array.from({ length: Math.min(4, chunks.length) }, async () => {
+ while (cursor < chunks.length) {
+ const chunk = chunks[cursor++]!
+ const sql =
+ base.replace('SELECT ', `SELECT ${photo} AS label, `) +
+ ` AND (length(blob6) = 37 OR startsWith(blob6, '/albums/')) AND ${photo} IN (${chunk.map((id) => `'${id}'`).join(',')}) GROUP BY label ORDER BY pv DESC, label LIMIT 5 FORMAT JSON`
+ const response = await fetcher(
+ `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/analytics_engine/sql`,
+ {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${config.token}` },
+ body: sql,
+ signal: AbortSignal.timeout(10000),
+ },
+ )
+ if (!response.ok) {
+ const message = await response.text()
+ if (
+ response.status === 400 &&
+ /(?:unknown table|table[^\n]*(?:does not exist|not found))/i.test(
+ message,
+ )
+ )
+ continue
+ throw new Error('analytics_query_failed')
+ }
+ const data = (await response.json()) as {
+ data?: Record<string, unknown>[]
+ }
+ if (!Array.isArray(data.data)) throw new Error('analytics_query_failed')
+ for (const row of data.data)
+ if (chunk.includes(String(row.label)))
+ rows.push({
+ label: `/${row.label}`,
+ pv: Number(row.pv) || 0,
+ uv: Number(row.uv) || 0,
+ sampleInterval: Number(row.sampleInterval) || 1,
+ })
+ }
+ }),
+ )
+ if (
+ rows.some(
+ (row) =>
+ !Number.isFinite(row.pv) ||
+ !Number.isFinite(row.uv) ||
+ !Number.isFinite(row.sampleInterval),
+ )
+ )
+ throw new Error('analytics_query_failed')
+ rows.sort((a, b) => b.pv - a.pv || a.label.localeCompare(b.label))
+ const result = rows.slice(0, 5)
+ if (cache.size > 100) cache.clear()
+ cache.set(key, { until: Date.now() + 60000, rows: result })
+ return result
+}
diff --git a/packages/platform/src/analytics.ts b/packages/platform/src/analytics.ts
index df7bc996..d840f7da 100644
--- a/packages/platform/src/analytics.ts
+++ b/packages/platform/src/analytics.ts
@@ -1,3 +1,4 @@
+import { PAGE_LABEL_SQL } from './analytics-pages.ts'
/** Workers Analytics Engine visit schema v1. No raw IP, query strings or full user agent. */
export type VisitScope = {
kind: 'website' | 'portal' | 'site'
@@ -259,7 +260,7 @@ export function analyticsQueries(
return {
summary: `SELECT ${metrics} FROM ${where} FORMAT JSON`,
daily: `SELECT ${window.bucket === 'minute' ? 'toStartOfMinute(timestamp)' : window.bucket === 'hour' ? 'toStartOfHour(timestamp)' : 'toDate(timestamp)'} AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY label FORMAT JSON`,
- pages: group('blob6'),
+ pages: group(PAGE_LABEL_SQL),
sources: group('blob8'),
countries: group('blob9'),
browsers: group('blob10'),
@@ -270,6 +271,7 @@ export function analyticsQueries(
}
}
export type AnalyticsRow = {
+ page?: import('./analytics-pages.ts').AnalyticsPage
label: string
pv: number
uv: number
diff --git a/packages/platform/src/legal-defaults.ts b/packages/platform/src/legal-defaults.ts
index 4fc68982..66461489 100644
--- a/packages/platform/src/legal-defaults.ts
+++ b/packages/platform/src/legal-defaults.ts
@@ -123,7 +123,7 @@ The effective date and latest revision appear on this page. We will provide appr
平台使用登录、安全、语言及外观等必要的 Cookie 和本地偏好设置。这些功能不等同于广告追踪。未来如引入可选分析或营销技术,我们会提供适用法律要求的说明与选择。
### 访问统计
-我们使用 Cloudflare Workers Analytics Engine 统计官网、门户及托管站点的页面浏览量、每日独立访客、来源域名、国家/地区、设备与浏览器类别及推广活动标签。该数据集不保存原始 IP、完整浏览器信息、URL 查询参数,也不设置分析 Cookie。IP 和浏览器信息仅用于即时生成每日轮换的匿名密钥标识;我们遵循 Do Not Track 与 Global Privacy Control 信号。具有套餐权益的图库用户可查看所属工作区的汇总数据,平台人员访问受权限控制。跨天 UV 表示每日独立访客合计,Cloudflare 可能对结果采样。Analytics Engine 中的明细最长保留三个月;每日汇总计数会单独保存,用于长期及所有时间报表,不包含访客标识。
+我们使用 Cloudflare Workers Analytics Engine 统计官网、门户及托管站点的页面浏览量、每日独立访客、来源域名、国家/地区、设备与浏览器类别及推广活动标签。该数据集不保存原始 IP、完整浏览器信息、URL 查询参数,也不设置分析 Cookie。IP 和浏览器信息仅用于即时生成每日轮换的匿名密钥标识;我们遵循 Do Not Track 与 Global Privacy Control 信号。具有套餐权益的图库用户可查看所属工作区的汇总数据,平台人员访问受权限控制。跨天 UV 表示每日独立访客合计,Cloudflare 可能对结果采样。Analytics Engine 中的明细最长保留三个月;每日汇总计数会单独保存,用于长期及所有时间报表,不包含访客标识。
## 六、保存与删除
我们按提供服务、保护账号、解决争议及履行法律义务所需的期限保存信息。内容可因您的删除操作或适用的账号生命周期规则被清理。未验证或不活跃账号可能收到包含具体日期的删除通知。账号被标记删除后将无法登录,保留期内可联系客服申请恢复,保留期结束后进行永久清理;配额、豁免和生命周期设置可能影响具体流程。计费、安全或依法必须留存的记录可能适用不同期限。备份、缓存及第三方系统中的副本可能需要额外时间到期。您自行运营的存储桶和相关服务合同仍由您控制。
diff --git a/packages/saas-ui/app/components/CfAnalyticsPageLink.vue b/packages/saas-ui/app/components/CfAnalyticsPageLink.vue
new file mode 100644
index 00000000..f4cf284e
--- /dev/null
+++ b/packages/saas-ui/app/components/CfAnalyticsPageLink.vue
@@ -0,0 +1,61 @@
+<script setup lang="ts">
+import type { AnalyticsRow } from '../../../platform/src/analytics'
+const props = defineProps<{
+ row: AnalyticsRow
+ admin?: boolean
+ zh?: boolean
+}>()
+const parts = computed(() =>
+ props.row.page
+ ? [
+ ...(props.admin ? [props.row.page.site] : []),
+ ...props.row.page.segments,
+ ]
+ : [],
+)
+</script>
+<template>
+ <span
+ v-if="row.page"
+ class="cf-page-links"
+ >
+ <template v-if="!parts.length"
+ ><a
+ v-if="row.page.site.href"
+ :href="row.page.site.href"
+ target="_blank"
+ rel="noopener noreferrer"
+ >/</a
+ ><span v-else>/</span></template
+ >
+ <template
+ v-for="(part, index) in parts"
+ :key="index"
+ >
+ <span v-if="!admin || index > 0">/</span>
+ <a
+ v-if="part.href"
+ :href="part.href"
+ target="_blank"
+ rel="noopener noreferrer"
+ >{{ part.kind === 'albums' && zh ? '相簿' : part.title }}</a
+ >
+ <span v-else>{{
+ part.kind === 'albums' && zh ? '相簿' : part.title
+ }}</span>
+ </template>
+ </span>
+ <span v-else>{{ row.label }}</span>
+</template>
+<style scoped>
+.cf-page-links a {
+ color: var(--color-blue-600, #2563eb);
+ text-decoration: none;
+}
+.cf-page-links a:hover {
+ text-decoration: underline;
+}
+:global(.dark .cf-page-links a) {
+ color: #60a5fa;
+}
+</style>
diff --git a/packages/saas-ui/app/components/CfAnalyticsRange.vue b/packages/saas-ui/app/components/CfAnalyticsRange.vue
index e3d1295d..f2c359d7 100644
--- a/packages/saas-ui/app/components/CfAnalyticsRange.vue
+++ b/packages/saas-ui/app/components/CfAnalyticsRange.vue
@@ -291,7 +291,7 @@ function changeZone() {
{{ error }}
</p>
<footer class="cf-range-footer">
- <select
+ <CfSelect
v-model="utc"
class="cf-input"
:aria-label="tr('Time zone', '时区')"
@@ -302,7 +302,7 @@ function changeZone() {
zoneLabel === 'UTC' ? tr('Local time', '本地时间') : zoneLabel
}}
</option>
- <option :value="true">UTC</option></select
+ <option :value="true">UTC</option></CfSelect
><CfButton
type="button"
@click="apply"
diff --git a/packages/saas-ui/app/components/CfAnalyticsReport.vue b/packages/saas-ui/app/components/CfAnalyticsReport.vue
index f3646d3a..b2ed78ad 100644
--- a/packages/saas-ui/app/components/CfAnalyticsReport.vue
+++ b/packages/saas-ui/app/components/CfAnalyticsReport.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-const props = defineProps<{ report: any; zh?: boolean }>()
+const props = defineProps<{ report: any; zh?: boolean; admin?: boolean }>()
const tr = (en: string, zh: string) => (props.zh ? zh : en)
const format = (value: number) =>
new Intl.NumberFormat(props.zh ? 'zh-CN' : 'en-US', {
@@ -8,14 +8,14 @@ const format = (value: number) =>
const groups = computed(() => [
['pages', tr('Pages', '页面')],
['sources', tr('Referrer hosts', '来源域名')],
- ['countries', tr('Countries / regions', '国家/地区')],
+ ['countries', tr('Countries / regions', '国家/地区')],
['sites', tr('Site hosts', '站点域名')],
['browsers', tr('Browsers', '浏览器')],
['devices', tr('Devices', '设备')],
['systems', tr('Operating systems', '操作系统')],
[
'campaigns',
- tr('Campaigns (source / medium / campaign)', '推广来源/媒介/活动'),
+ tr('Campaigns (source / medium / campaign)', '推广来源/媒介/活动'),
],
])
</script>
@@ -113,7 +113,7 @@ const groups = computed(() => [
<tbody>
<tr
v-for="row in report.daily"
- :key="row.label"
+ :key="row.page?.key ?? row.label"
>
<td>{{ row.label }}</td>
<td>{{ format(row.pv) }}</td>
@@ -155,9 +155,16 @@ const groups = computed(() => [
<tbody>
<tr
v-for="row in report[key]"
- :key="row.label"
+ :key="row.page?.key ?? row.label"
>
- <td>{{ row.label }}</td>
+ <td>
+ <CfAnalyticsPageLink
+ v-if="key === 'pages'"
+ :row="row"
+ :admin="admin"
+ :zh="zh"
+ /><template v-else>{{ row.label }}</template>
+ </td>
<td>{{ format(row.pv) }}</td>
<td>{{ format(row.uv) }}</td>
</tr>
@@ -193,8 +200,10 @@ const groups = computed(() => [
margin-bottom: 16px;
}
.cf-analytics-table-wrap {
- overflow-x: auto;
+ overflow: auto;
max-height: 360px;
+ margin: 0 -20px -20px;
+ padding: 0 20px 20px;
}
.cf-analytics-table {
width: 100%;
diff --git a/packages/saas-ui/app/components/CfSelect.vue b/packages/saas-ui/app/components/CfSelect.vue
index 1cf9869e..af90c038 100644
--- a/packages/saas-ui/app/components/CfSelect.vue
+++ b/packages/saas-ui/app/components/CfSelect.vue
@@ -1,23 +1,68 @@
<script setup lang="ts">
-// Keep an omitted Boolean-union prop distinct from an explicitly controlled false.
+import { computed, useSlots, type VNode } from 'vue'
+defineOptions({ inheritAttrs: false })
const props = withDefaults(
defineProps<{ value?: string | number | boolean | null }>(),
{ value: undefined },
)
const model = defineModel<string | number | boolean | null>()
-// Preserve native controlled-value forms as well as v-model consumers.
-const selected = computed({
- get: () => (props.value !== undefined ? props.value : model.value),
- set: (value) => {
- if (props.value === undefined) model.value = value
- },
+const emit = defineEmits<{
+ change: [
+ event: { target: { value: string }; currentTarget: { value: string } },
+ ]
+}>()
+const slots = useSlots()
+type Option = {
+ id: string
+ label: string
+ raw: string | number | boolean | null
+ disabled: boolean
+}
+function text(value: unknown): string {
+ if (Array.isArray(value)) return value.map(text).join('')
+ if (value && typeof value === 'object' && 'children' in value)
+ return text((value as VNode).children)
+ return typeof value === 'string' || typeof value === 'number'
+ ? String(value)
+ : ''
+}
+function options(nodes: VNode[], output: Option[] = []): Option[] {
+ for (const node of nodes) {
+ if (node.type === 'option')
+ output.push({
+ id: `option-${output.length}`,
+ label: text(node.children).trim(),
+ raw:
+ node.props && Object.hasOwn(node.props, 'value')
+ ? node.props.value
+ : text(node.children).trim(),
+ disabled: node.props?.disabled === '' || !!node.props?.disabled,
+ })
+ else if (Array.isArray(node.children))
+ options(node.children as VNode[], output)
+ }
+ return output
+}
+const items = computed(() => options(slots.default?.() ?? []))
+const selected = computed(() => {
+ const value = props.value !== undefined ? props.value : model.value
+ return items.value.find((item) => item.raw === value)?.id
})
+function update(id: string) {
+ const item = items.value.find((option) => option.id === id)
+ if (!item || item.disabled) return
+ if (props.value === undefined) model.value = item.raw
+ const target = { value: String(item.raw ?? '') }
+ emit('change', { target, currentTarget: target })
+}
</script>
<template>
- <select
- v-model="selected"
- class="cf-input cf-select"
- >
- <slot />
- </select>
+ <USelect
+ v-bind="$attrs"
+ :items="items"
+ value-key="id"
+ :model-value="selected"
+ class="cf-select"
+ @update:model-value="update"
+ />
</template>
diff --git a/tests/analytics-archive.test.ts b/tests/analytics-archive.test.ts
index 2b013d8a..60b35274 100644
--- a/tests/analytics-archive.test.ts
+++ b/tests/analytics-archive.test.ts
@@ -47,7 +47,8 @@ test('daily archive resumes failures, publishes complete snapshots atomically, a
if (sql.includes('MIN(timestamp)'))
return new Response(JSON.stringify({ data: [{ day: '2026-10-28' }] }))
if (sql.includes('AS workspaceId')) {
- if (sql.includes('blob6 AS label')) pageSql = sql
+ if (sql.includes("format('{}|{}|{}',blob4,blob5,blob6) AS label"))
+ pageSql = sql
if (fail && sql.includes('blob9 AS label')) {
fail = false
return new Response('Temporary failure', { status: 503 })
@@ -55,7 +56,7 @@ test('daily archive resumes failures, publishes complete snapshots atomically, a
const match = sql.includes("timestamp>=toDateTime('2026-10-28")
const label = sql.includes("'' AS label")
? ''
- : sql.includes('blob6 AS label')
+ : sql.includes("format('{}|{}|{}',blob4,blob5,blob6) AS label")
? '/'
: 'example'
return new Response(
@@ -82,7 +83,7 @@ test('daily archive resumes failures, publishes complete snapshots atomically, a
{
label: sql.includes('toDate(timestamp) AS label')
? '2026-11-01'
- : sql.includes('blob6 AS label')
+ : sql.includes("format('{}|{}|{}',blob4,blob5,blob6) AS label")
? '/'
: '',
pv: 2,
@@ -287,10 +288,18 @@ test('archive pages keep the top labels independently per workspace and site', a
'2026-10-28 12:00:00',
1,
)
+ sqlite.exec(
+ "ALTER TABLE archive_fixture ADD COLUMN blob5 TEXT DEFAULT 'site.example'",
+ )
+ sqlite.function('format', { varargs: true }, (pattern, ...values) => {
+ let i = 0
+ return String(pattern).replace(/\{\}/g, () => String(values[i++]))
+ })
const offsets: number[] = []
const fetcher: typeof fetch = async (_url, opts) => {
const sql = String(opts?.body)
- if (!sql.includes('blob6 AS label')) return Response.json({ data: [] })
+ if (!sql.includes("format('{}|{}|{}',blob4,blob5,blob6) AS label"))
+ return Response.json({ data: [] })
assert.doesNotMatch(sql, /FROM \(/)
offsets.push(Number(/OFFSET (\d+)/.exec(sql)![1]))
return Response.json({
@@ -317,12 +326,14 @@ test('archive pages keep the top labels independently per workspace and site', a
.all()
).results as any[]
assert.equal(rows.length, 5002)
- assert.ok(rows.some((r) => r.label === 'label-5000'))
- assert.ok(!rows.some((r) => r.label === 'label-4999'))
+ assert.ok(rows.some((r) => r.label.endsWith('|label-5000')))
+ assert.ok(!rows.some((r) => r.label.endsWith('|label-4999')))
assert.ok(
rows.some(
(r) =>
- r.workspace_id === 1 && r.site_id === 12 && r.label === 'other-site',
+ r.workspace_id === 1 &&
+ r.site_id === 12 &&
+ r.label.endsWith('|other-site'),
),
)
assert.ok(
@@ -330,7 +341,7 @@ test('archive pages keep the top labels independently per workspace and site', a
(r) =>
r.workspace_id === 2 &&
r.site_id === 21 &&
- r.label === 'other-workspace',
+ r.label.endsWith('|other-workspace'),
),
)
await db
@@ -354,13 +365,13 @@ test('archive pages keep the top labels independently per workspace and site', a
).results as any[]
assert.equal(workspaceRows.length, 5001)
assert.equal(workspaceRows.filter((r) => r.workspace_id === 1).length, 5000)
- assert.ok(workspaceRows.some((r) => r.label === 'label-5000'))
+ assert.ok(workspaceRows.some((r) => r.label.endsWith('|label-5000')))
assert.ok(
workspaceRows.some(
(r) =>
r.workspace_id === 2 &&
r.site_id === 0 &&
- r.label === 'other-workspace',
+ r.label.endsWith('|other-workspace'),
),
)
} finally {
diff --git a/tests/analytics-links.test.ts b/tests/analytics-links.test.ts
new file mode 100644
index 00000000..b0334160
--- /dev/null
+++ b/tests/analytics-links.test.ts
@@ -0,0 +1,133 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { DatabaseSync } from 'node:sqlite'
+import {
+ resolveAnalyticsPages,
+ decodeAnalyticsPage,
+ PAGE_LABEL_SQL,
+} from '../packages/platform/src/analytics-pages.ts'
+import { popularPhotos } from '../packages/platform/src/analytics-popular.ts'
+import { visitRoutePath } from '../apps/shared/analytics/tracker.ts'
+
+test('page metadata resolves current titles and canonical domains within the authorized workspace', async () => {
+ const sqlite = new DatabaseSync(':memory:')
+ sqlite.exec(`CREATE TABLE platform_sites(id,workspace_id,name,gallery_title,published,suspended);
+ CREATE TABLE platform_workspaces(id,owner_user_id); CREATE TABLE platform_account_controls(user_id,suspended);
+ CREATE TABLE platform_domains(site_id,hostname,kind,active,verified,redirect_until);
+ CREATE TABLE platform_custom_domains(site_id,hostname,is_primary,state,verified_at);
+ CREATE TABLE cloud_photos(site_id,id,title,deleted);CREATE TABLE cloud_albums(site_id,id,title);
+ CREATE TABLE cloud_album_slugs(site_id,album_id,slug,is_current); CREATE TABLE cloud_album_photos(site_id,album_id,photo_id); INSERT INTO cloud_album_photos VALUES(1,'album-id','photo');
+ INSERT INTO platform_sites VALUES(1,7,'Site','Gallery',1,0),(2,8,'Other','Private title',1,0);
+ INSERT INTO platform_domains VALUES(1,'gallery.example','default',1,1,NULL);
+ INSERT INTO cloud_photos VALUES(1,'photo','Photo title',0),(2,'photo','Private photo',0),(1,'deleted','Deleted title',1);
+ INSERT INTO cloud_albums VALUES(1,'album-id','Album title');
+ INSERT INTO cloud_album_slugs VALUES(1,'album-id','old-slug',0),(1,'album-id','new-slug',1);`)
+ const db = {
+ prepare: (sql: string) => ({
+ bind: (...values: any[]) => ({
+ all: async () => ({ results: sqlite.prepare(sql).all(...values) }),
+ }),
+ }),
+ } as any
+ const labels = [
+ '1|gallery.example|/photo',
+ '1|gallery.example|/albums/old-slug/photo',
+ '2|other.example|/photo',
+ '1|gallery.example|/deleted',
+ '/photo',
+ ]
+ const report = await resolveAnalyticsPages(
+ db,
+ {
+ pages: labels.map((label) => ({
+ label,
+ pv: 1,
+ uv: 1,
+ sampleInterval: 1,
+ })),
+ },
+ { workspaceId: 7, from: '2026-11-01', to: '2026-11-01' },
+ )
+ assert.equal(report.pages[0]!.page?.segments[0]?.title, 'Photo title')
+ assert.equal(
+ report.pages[1]!.page?.segments[1]?.href,
+ 'https://gallery.example/albums/new-slug',
+ )
+ assert.equal(
+ report.pages[1]!.page?.segments[2]?.href,
+ 'https://gallery.example/albums/new-slug?photo=photo',
+ )
+ assert.equal(report.pages[2]!.page, undefined)
+ assert.equal(report.pages[3]!.page?.segments[0]?.title, 'deleted')
+ assert.equal(report.pages[4]!.page, undefined)
+ assert.equal(decodeAnalyticsPage('1|evil.example|//evil.example'), null)
+ assert.equal(decodeAnalyticsPage('1|https://evil.example|/'), null)
+ assert.match(PAGE_LABEL_SQL, /format/)
+ sqlite.close()
+})
+
+test('album photo tracking records only a validated photo identity and never arbitrary query strings', () => {
+ const id = '12345678-1234-1234-1234-123456789012'
+ assert.equal(
+ visitRoutePath({
+ path: '/albums/travel',
+ query: { photo: id, token: 'secret' },
+ }),
+ `/albums/travel/${id}`,
+ )
+ assert.equal(
+ visitRoutePath({
+ path: '/albums/travel',
+ query: { photo: '../../secret' },
+ }),
+ '/albums/travel',
+ )
+ assert.equal(
+ visitRoutePath({ path: '/albums', query: { photo: id } }),
+ '/albums',
+ )
+})
+
+test('popular photo ranking includes every current photo, merges path variants in SQL and ranks across chunks', async () => {
+ const ids = Array.from(
+ { length: 205 },
+ (_, i) => `12345678-1234-1234-1234-${String(i).padStart(12, '0')}`,
+ )
+ let requests = 0
+ const rows = await popularPhotos(
+ { accountId: 'a'.repeat(32), token: 'test', dataset: 'visits' },
+ {
+ kind: 'site',
+ workspaceId: 7,
+ siteId: 1,
+ from: '2026-11-01',
+ to: '2026-11-01',
+ },
+ ids,
+ async (_url, opts) => {
+ const sql = String(opts?.body)
+ requests++
+ assert.match(sql, /blob3 = '7'/)
+ assert.match(sql, /blob4 = '1'/)
+ assert.match(sql, /substring\(blob6, length\(blob6\) - 35, 36\)/)
+ assert.match(sql, /startsWith\(blob6, '\/albums\/'\)/)
+ const group = [...sql.matchAll(/'(12345678[^']+)'/g)].map((m) => m[1]!)
+ return Response.json({
+ data: group
+ .map((id) => ({
+ label: id,
+ pv: Number(id.slice(-12)) + 1,
+ uv: 1,
+ sampleInterval: 1,
+ }))
+ .sort((a, b) => b.pv - a.pv)
+ .slice(0, 5),
+ })
+ },
+ )
+ assert.equal(requests, 3)
+ assert.deepEqual(
+ rows.map((r) => r.pv),
+ [205, 204, 203, 202, 201],
+ )
+})
diff --git a/tests/visit-analytics.test.ts b/tests/visit-analytics.test.ts
index a0ae6651..4816bd2a 100644
--- a/tests/visit-analytics.test.ts
+++ b/tests/visit-analytics.test.ts
@@ -232,6 +232,7 @@ test('portal report checks membership, live entitlement and selected-site owners
platformDatabase: () => db,
workspaceEntitlements: async () => ({ analytics: entitled }),
analyticsFilter,
+ resolveAnalyticsPages: async (_db: any, report: any) => report,
analyticsReport: async (_: any, f: any) => {
reports++
return f