From 1db425d493be827b9d7883f3fcf073c2104ee43d Mon Sep 17 00:00:00 2001 From: zyphlar Date: Sat, 7 Nov 2026 22:55:29 -0800 Subject: [PATCH] Add view counters per album, recipient and browser, per-browser sign-out in admin, and photo hearts --- README.md | 7 ++ app/public/style.css | 10 ++- app/src/client/hearts.ts | 78 +++++++++++++++++++++ app/src/client/icons.ts | 2 + app/src/client/init.ts | 1 + app/src/client/lightbox.ts | 2 + app/src/client/state.ts | 4 +- app/src/gallery/builder.ts | 13 +++- app/src/magic/admin.ts | 25 ++++++- app/src/magic/routes.ts | 23 +++++++ app/src/magic/session.ts | 2 +- app/src/magic/store.ts | 123 ++++++++++++++++++++++++++++++++-- app/src/magic/views.tsx | 77 ++++++++++++++++++--- app/src/shared/types.ts | 10 +++ app/src/view/gallery.tsx | 8 ++- app/tests/magicAccess.test.ts | 108 +++++++++++++++++++++++++++++ app/tests/magicStore.test.ts | 44 ++++++++++++ 17 files changed, 511 insertions(+), 26 deletions(-) create mode 100644 app/src/client/hearts.ts diff --git a/README.md b/README.md index 1f3aebb..ad136c1 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,13 @@ or **sign-in only** (only people you invite). - **Comments.** Recipients can comment on any photo from the lightbox (comment button, or the info sidebar). They can delete their own; you can moderate all of them from the admin page. Comments are only ever shown to recipients given that share, never to other visitors of a public share. +- **Hearts.** Recipients can heart a photo from the lightbox (heart button, beside the comments button). The count is + everyone's; each recipient hearts a photo at most once and can take it back. Like comments, hearts are for + recipients given that share only. +- **Activity.** `/admin` shows how often each album's gallery was opened (and how many of those opens were by + visitors who weren't signed in), its hearts, and how often each recipient opened their albums. A recipient's page + lists each signed-in browser with when it was last used and its views, and can sign out any one of them. Counting + started with this release; earlier visits aren't included. - **Lost links.** A visitor with no session can ask for a new link by email. The reply is the same whether or not the address was invited, and requests are rate-limited. - **Password-protected shares.** Store the share password when adding the album, and recipients are never asked diff --git a/app/public/style.css b/app/public/style.css index 33661ed..6ae4dbb 100644 --- a/app/public/style.css +++ b/app/public/style.css @@ -542,10 +542,16 @@ html.ipp-sidebar-open .ipp-sidebar { font-size: 13px; } -/* Count badge on the lightbox's comments button */ -.pswp__button--comments-toggle { +/* Count badge on the lightbox's comments and heart buttons */ +.pswp__button--comments-toggle, +.pswp__button--heart { position: relative; } +/* Outline heart until hearted, then a filled red one */ +.pswp__top-bar .pswp__button--heart .ipp-heart-on { display: none; } +.pswp__top-bar .pswp__button--heart.ipp-hearted .ipp-heart-off { display: none; } +.pswp__top-bar .pswp__button--heart.ipp-hearted .ipp-heart-on { display: block; color: #ff4d6d; } +.ipp-heart-badge, .ipp-comment-badge { position: absolute; top: 8px; diff --git a/app/src/client/hearts.ts b/app/src/client/hearts.ts new file mode 100644 index 0000000..ce8edaa --- /dev/null +++ b/app/src/client/hearts.ts @@ -0,0 +1,78 @@ +// Heart button in the lightbox toolbar, beside the comments button. A +// recipient given the share can heart a photo once; the count is everyone's. + +import { state } from './state.js' +import { ICON_HEART, ICON_HEART_OUTLINE } from './icons.js' + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type LightboxInstance = any +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type PswpInstance = any + +function url (assetId: string): string { + return state.hearts!.base + '/' + encodeURIComponent(assetId) +} + +/** Register the heart toolbar button. Only called when hearts are available. */ +export function registerHearts (lightbox: LightboxInstance) { + const mine = new Set(state.hearts!.mine) + // Photos with a request in flight, so a double click can't race itself + const pending = new Set() + + lightbox.on('uiRegister', () => { + lightbox.pswp.ui.registerElement({ + name: 'heart', + order: 9, + isButton: true, + ariaLabel: 'Heart', + html: ICON_HEART_OUTLINE + ICON_HEART + '', + onInit: (el: HTMLElement, pswp: PswpInstance) => { + const badge = el.querySelector('.ipp-heart-badge') as HTMLElement + const currentId = () => state.items[pswp.currIndex]?.id || '' + + const update = () => { + const id = currentId() + const count = state.hearts!.counts[id] || 0 + const hearted = mine.has(id) + el.classList.toggle('ipp-hearted', hearted) + el.setAttribute('aria-pressed', String(hearted)) + badge.textContent = count > 99 ? '99+' : String(count) + badge.hidden = count === 0 + el.setAttribute('aria-label', (hearted ? 'Remove your heart' : 'Heart this') + (count ? ' (' + count + ')' : '')) + el.title = hearted ? 'Remove your heart' : 'Heart this' + } + + update() + pswp.on('change', update) + + el.addEventListener('click', async () => { + const id = currentId() + if (!id || pending.has(id)) return + const on = !mine.has(id) + const before = state.hearts!.counts[id] || 0 + // Show it straight away; put it back if the server says no + pending.add(id) + if (on) mine.add(id) + else mine.delete(id) + state.hearts!.counts[id] = Math.max(0, before + (on ? 1 : -1)) + update() + try { + const res = await fetch(url(id), { method: on ? 'PUT' : 'DELETE' }) + if (!res.ok) throw new Error(String(res.status)) + const data = await res.json() as { count: number, mine: boolean } + state.hearts!.counts[id] = data.count + if (data.mine) mine.add(id) + else mine.delete(id) + } catch { + state.hearts!.counts[id] = before + if (on) mine.delete(id) + else mine.add(id) + } finally { + pending.delete(id) + if (currentId() === id) update() + } + }) + } + }) + }) +} diff --git a/app/src/client/icons.ts b/app/src/client/icons.ts index 3f596c0..17693b2 100644 --- a/app/src/client/icons.ts +++ b/app/src/client/icons.ts @@ -34,3 +34,5 @@ export const CHECK_SVG = '

Any Immich shared link opened through this proxy is added here automatically. A public album opens for anyone with its link; otherwise only signed-in recipients can open it. Comments and new-photo emails are for recipients only.

{shares.length > 0 && ( - + - {shares.map(({ share, recipients: count, assets }) => ( + {shares.map(({ share, recipients: count, assets, activity }) => ( + ') + expect(page.text).toContain('not signed in') + }) +}) + +describe('hearts', () => { + let cookie: string + beforeAll(async () => { cookie = await signIn() }) + const heart = (key: string, id: string, method: string, as = cookie) => request('/share/hearts/' + key + '/' + id, { cookie: as, method }) + + it('a recipient hearts a photo once, and can take it back', async () => { + let res = await heart(KEY_A, ASSET_1, 'PUT') + expect(res.res.status).toBe(200) + expect(JSON.parse(res.text)).toEqual({ count: 1, mine: true }) + res = await heart(KEY_A, ASSET_1, 'PUT') + expect(JSON.parse(res.text)).toEqual({ count: 1, mine: true }) + + const page = await request('/share/' + KEY_A, { page: true, cookie }) + expect(page.text).toContain('/share/hearts/' + KEY_A) + expect(page.text).toContain('"mine":["' + ASSET_1 + '"]') + + res = await heart(KEY_A, ASSET_1, 'DELETE') + expect(JSON.parse(res.text)).toEqual({ count: 0, mine: false }) + }) + + it('only on photos in the album', async () => { + expect((await heart(KEY_A, ASSET_B, 'PUT')).res.status).toBe(404) + }) + + it('not for someone without the album, or not signed in', async () => { + const bobCookie = await signIn('/m/' + store.createMagicLink(bob.id, { purpose: 'invite', expiresAt: null }, new Date().toISOString())) + expect((await heart(KEY_A, ASSET_1, 'PUT', bobCookie)).res.status).toBe(404) + expect((await request('/share/hearts/' + KEY_A + '/' + ASSET_1, { method: 'PUT' })).res.status).toBe(404) + // A public share's anonymous visitors don't get hearts at all + const page = await request('/share/' + KEY_D, { page: true }) + expect(page.text).not.toContain('/share/hearts/') + expect((await request('/share/hearts/' + KEY_D + '/' + ASSET_2, { method: 'PUT' })).res.status).toBe(404) + }) +}) diff --git a/app/tests/magicStore.test.ts b/app/tests/magicStore.test.ts index 4d5404e..0dc481f 100644 --- a/app/tests/magicStore.test.ts +++ b/app/tests/magicStore.test.ts @@ -207,3 +207,47 @@ describe('public shares', () => { } }) }) + +describe('activity and hearts', () => { + it('counts views per share, recipient and browser, and lists browsers newest first', () => { + store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null }, T0) + const ann = recipient() + const older = store.createSession(ann.id, T0, 'Firefox') + const newer = store.createSession(ann.id, T0, 'Chrome') + store.recordView('k1', {}, T1) + store.recordView('k1', { recipientId: ann.id, sessionToken: older, userAgent: 'Firefox 2' }, T1) + store.recordView('k1', { recipientId: ann.id, sessionToken: newer }, T2) + + expect(store.shareActivity().get('k1')).toEqual({ views: 3, anonymousViews: 1, lastViewedAt: T2, hearts: 0 }) + expect(store.recipientActivity(ann.id)).toEqual({ views: 2, lastViewedAt: T2 }) + const [first, second] = store.listSessions(ann.id) + expect(first).toMatchObject({ views: 1, lastViewedAt: T2, userAgent: 'Chrome' }) + expect(second).toMatchObject({ views: 1, lastViewedAt: T1, userAgent: 'Firefox 2' }) + }) + + it('signs out one browser, only for its own recipient', () => { + const ann = recipient() + const bob = recipient('bob@example.com') + store.createSession(ann.id, T0) + const [session] = store.listSessions(ann.id) + expect(store.deleteSessionById(bob.id, session.id)).toBe(false) + expect(store.deleteSessionById(ann.id, session.id)).toBe(true) + expect(store.listSessions(ann.id)).toHaveLength(0) + }) + + it('hearts once per recipient per photo, and counts them', () => { + store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null }, T0) + const ann = recipient() + const bob = recipient('bob@example.com') + expect(store.setHeart('k1', 'p1', ann.id, true, T0)).toBe(1) + expect(store.setHeart('k1', 'p1', ann.id, true, T0)).toBe(1) + expect(store.setHeart('k1', 'p1', bob.id, true, T0)).toBe(2) + expect(store.countHearts('k1')).toEqual({ p1: 2 }) + expect(store.heartedBy('k1', ann.id)).toEqual(['p1']) + expect(store.shareActivity().get('k1')?.hearts).toBe(2) + expect(store.setHeart('k1', 'p1', ann.id, false, T0)).toBe(1) + // Deleting the share takes its hearts with it + store.deleteShare('k1') + expect(store.countHearts('k1')).toEqual({}) + }) +})
AlbumPublic link worksRecipientsPhotos tracked
AlbumPublic link worksRecipientsViewsPhotos tracked
{share.title || 'Untitled'}
{share.slug ? 's/' + share.slug : share.key.slice(0, 12) + '…'}{share.password ? ' · password stored' : ''}
@@ -211,6 +238,13 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me {count} + {activity?.views ?? 0} + {activity && activity.hearts > 0 && <> · ♥ {activity.hearts}} +
+ {activity?.anonymousViews ? activity.anonymousViews + ' not signed in · ' : ''}last {lastSeen(activity?.lastViewedAt ?? null)} + +
{assets}
Recipients {recipients.length > 0 && ( - + - {recipients.map(({ recipient, shares: granted, sessions }) => ( + {recipients.map(({ recipient, shares: granted, sessions, activity }) => ( + ))} @@ -335,7 +370,8 @@ export interface AdminRecipientProps { recipient: Recipient shares: ShareRecord[] granted: string[] - sessions: number + sessions: SessionRecord[] + activity: Activity activeLinks: number emailEnabled: boolean /** A link created by this request; shown once, never stored in plain text. */ @@ -343,7 +379,7 @@ export interface AdminRecipientProps { message?: { kind: 'ok' | 'error', text: string } } -export function AdminRecipient ({ recipient, shares, granted, sessions, activeLinks, emailEnabled, newLink, message }: AdminRecipientProps) { +export function AdminRecipient ({ recipient, shares, granted, sessions, activity, activeLinks, emailEnabled, newLink, message }: AdminRecipientProps) { const base = '/admin/recipients/' + recipient.id return ( @@ -369,7 +405,28 @@ export function AdminRecipient ({ recipient, shares, granted, sessions, activeLi

Access

-

{sessions} signed-in browser{sessions === 1 ? '' : 's'} · {activeLinks} working link{activeLinks === 1 ? '' : 's'}

+

{plural(activity.views, 'album view')}, last {lastSeen(activity.lastViewedAt)} · {plural(sessions.length, 'signed-in browser')} · {plural(activeLinks, 'working link')}

+ {sessions.length > 0 && ( +
NameAlbumsEmailsSigned-in browsers
NameAlbumsEmailsViewsSigned-in browsers
{recipient.name}{recipient.disabled && <> (disabled)}
{recipient.email}
{granted.map(s => s.title).join(', ') || none} {FREQUENCY_LABELS[recipient.frequency]}{activity.views}
last {lastSeen(activity.lastViewedAt)}
{sessions}
+ + + {sessions.map(session => ( + + + + + + + + ))} + +
BrowserSigned inLast usedViews
{browserName(session.userAgent)}{lastSeen(session.createdAt)}{lastSeen(session.lastViewedAt)}{session.views} +
+ +
+
+ )}
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts index da77784..892468a 100644 --- a/app/src/shared/types.ts +++ b/app/src/shared/types.ts @@ -99,6 +99,15 @@ export interface MetadataConfig { } /** Per-photo comments for the signed-in recipient. */ +export interface HeartsConfig { + // `/share/hearts/`; append `/` + base: string + // Heart count per asset id + counts: Record + // Asset ids this recipient has hearted + mine: string[] +} + export interface CommentsConfig { // `/share/comments/`; append `/` base: string @@ -128,4 +137,5 @@ export interface InitParams { groupByDate?: GroupByDateMode | false metaBase?: string comments?: CommentsConfig + hearts?: HeartsConfig } diff --git a/app/src/view/gallery.tsx b/app/src/view/gallery.tsx index 393b954..99f184e 100644 --- a/app/src/view/gallery.tsx +++ b/app/src/view/gallery.tsx @@ -1,5 +1,5 @@ import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core' -import { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types' +import { CommentsConfig, GalleryItem, HeartsConfig, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types' import { ASSET_VERSION } from '../version' export type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } @@ -26,8 +26,9 @@ export interface GalleryProps { // Set when the upload service is assumed rather than configured: the button // stays hidden until the client finds this URL answering uploadHealthcheck?: string - // Comments on each photo, for a signed-in recipient + // Comments and hearts on each photo, for a recipient given the share comments?: CommentsConfig + hearts?: HeartsConfig // The recipient's albums and notification settings accountLink?: string } @@ -40,7 +41,8 @@ export function Gallery (props: GalleryProps) { metadataConfig: props.metadataConfig, groupByDate: props.groupByDate, metaBase: props.metaBase, - comments: props.comments + comments: props.comments, + hearts: props.hearts }) const firstItem = props.items[0] // og:image prefers the album cover (passed via props); for videos, previewUrl diff --git a/app/tests/magicAccess.test.ts b/app/tests/magicAccess.test.ts index 0abe53d..f8da13a 100644 --- a/app/tests/magicAccess.test.ts +++ b/app/tests/magicAccess.test.ts @@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { loadConfig } from '@ipp/core' import { Recipient, setStore, Store } from '../src/magic/store' import { Mail, setMailSender } from '../src/magic/mailer' +import { browserName } from '../src/magic/views' /* End to end: the real app in front of a fake Immich. Proves that nothing is @@ -144,6 +145,7 @@ afterAll(async () => { interface Options { cookie?: string + userAgent?: string page?: boolean method?: string json?: unknown @@ -153,6 +155,7 @@ interface Options { async function request (path: string, options: Options = {}) { const headers: Record = {} if (options.cookie) headers.Cookie = options.cookie + if (options.userAgent) headers['User-Agent'] = options.userAgent if (options.page) headers.Accept = 'text/html,application/xhtml+xml' let body: string | undefined if (options.json !== undefined) { @@ -529,3 +532,108 @@ describe('public shares', () => { expect(store.getShare(KEY_D)?.public).toBe(true) }) }) + +describe('activity', () => { + const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1' + + it('counts gallery views against the album, the recipient and the browser', async () => { + const shareBefore = store.shareActivity().get(KEY_A)! + const annBefore = store.recipientActivity(ann.id).views + const { res } = await request(annLink, { page: true, userAgent: IPHONE }) + const cookie = cookieFrom(res, 'imp_session')! + await request('/share/' + KEY_A, { page: true, cookie, userAgent: IPHONE }) + await request('/share/' + KEY_A, { page: true, cookie, userAgent: IPHONE }) + // Photos and metadata aren't views; only the gallery page is + await request('/share/photo/' + KEY_A + '/' + ASSET_1 + '/thumbnail', { cookie }) + + const share = store.shareActivity().get(KEY_A)! + expect(share.views - shareBefore.views).toBe(2) + expect(share.anonymousViews).toBe(shareBefore.anonymousViews) + expect(share.lastViewedAt).not.toBeNull() + expect(store.recipientActivity(ann.id).views - annBefore).toBe(2) + const browser = store.listSessions(ann.id).find(s => s.userAgent === IPHONE)! + expect(browser.views).toBe(2) + expect(browserName(browser.userAgent)).toBe('Safari on iPhone') + }) + + it('counts views of a public share by visitors who aren\'t signed in', async () => { + const before = store.shareActivity().get(KEY_D)! + await request('/share/' + KEY_D, { page: true }) + const after = store.shareActivity().get(KEY_D)! + expect(after.views - before.views).toBe(1) + expect(after.anonymousViews - before.anonymousViews).toBe(1) + }) + + it('lists each browser for the admin, who can sign one out', async () => { + await signIn() + const others = store.listSessions(ann.id).map(s => s.id) + const kept = await signIn() + const keptId = store.listSessions(ann.id).map(s => s.id).find(id => !others.includes(id))! + const login = await request('/admin/login', { form: { password: 'admin-secret' } }) + const admin = cookieFrom(login.res, 'imp_admin')! + const page = await request('/admin/recipients/' + ann.id, { page: true, cookie: admin }) + expect(page.text).toContain('Safari on iPhone') + expect(page.text).toMatch(/album views?, last/) + + // Sign out one browser; the others stay signed in + const target = others[0] + await request('/admin/recipients/' + ann.id + '/sessions/' + target + '/revoke', { cookie: admin, method: 'POST' }) + const left = store.listSessions(ann.id).map(s => s.id) + expect(left).not.toContain(target) + expect(left).toContain(keptId) + expect((await request('/share/' + KEY_A, { page: true, cookie: kept })).res.status).toBe(200) + + // Another recipient's browser can't be signed out from this page + const bobs = store.listSessions(bob.id) + if (bobs.length) { + await request('/admin/recipients/' + ann.id + '/sessions/' + bobs[0].id + '/revoke', { cookie: admin, method: 'POST' }) + expect(store.listSessions(bob.id)).toHaveLength(bobs.length) + } + // Not without the admin session + await request('/admin/recipients/' + ann.id + '/sessions/' + keptId + '/revoke', { method: 'POST' }) + expect(store.listSessions(ann.id).map(s => s.id)).toContain(keptId) + }) + + it('shows views and hearts on the dashboard', async () => { + const login = await request('/admin/login', { form: { password: 'admin-secret' } }) + const admin = cookieFrom(login.res, 'imp_admin')! + const page = await request('/admin', { page: true, cookie: admin }) + expect(page.text).toContain('
Views