Add view counters per album, recipient and browser, per-browser sign-out in admin, and photo hearts
This commit is contained in:
@@ -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
|
- **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
|
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.
|
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
|
- **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.
|
address was invited, and requests are rate-limited.
|
||||||
- **Password-protected shares.** Store the share password when adding the album, and recipients are never asked
|
- **Password-protected shares.** Store the share password when adding the album, and recipients are never asked
|
||||||
|
|||||||
@@ -542,10 +542,16 @@ html.ipp-sidebar-open .ipp-sidebar {
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Count badge on the lightbox's comments button */
|
/* Count badge on the lightbox's comments and heart buttons */
|
||||||
.pswp__button--comments-toggle {
|
.pswp__button--comments-toggle,
|
||||||
|
.pswp__button--heart {
|
||||||
position: relative;
|
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 {
|
.ipp-comment-badge {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 8px;
|
top: 8px;
|
||||||
|
|||||||
@@ -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<string>()
|
||||||
|
|
||||||
|
lightbox.on('uiRegister', () => {
|
||||||
|
lightbox.pswp.ui.registerElement({
|
||||||
|
name: 'heart',
|
||||||
|
order: 9,
|
||||||
|
isButton: true,
|
||||||
|
ariaLabel: 'Heart',
|
||||||
|
html: ICON_HEART_OUTLINE + ICON_HEART + '<span class="ipp-heart-badge" hidden></span>',
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -34,3 +34,5 @@ export const CHECK_SVG = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill
|
|||||||
|
|
||||||
// Tile-corner motion badge: ICON_MOTION_PLAY without the `pswp__icn` sizing.
|
// Tile-corner motion badge: ICON_MOTION_PLAY without the `pswp__icn` sizing.
|
||||||
export const ICON_MOTION_BADGE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M10 16.5L16 12L10 7.5M22 12C22 6.46 17.54 2 12 2C10.83 2 9.7 2.19 8.62 2.56L9.32 4.5C10.17 4.16 11.06 3.97 12 3.97C16.41 3.97 20.03 7.59 20.03 12C20.03 16.41 16.41 20.03 12 20.03C7.59 20.03 3.97 16.41 3.97 12C3.97 11.06 4.16 10.12 4.5 9.28L2.56 8.62C2.19 9.7 2 10.83 2 12C2 17.54 6.46 22 12 22C17.54 22 22 17.54 22 12M5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97Z"/></svg>'
|
export const ICON_MOTION_BADGE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M10 16.5L16 12L10 7.5M22 12C22 6.46 17.54 2 12 2C10.83 2 9.7 2.19 8.62 2.56L9.32 4.5C10.17 4.16 11.06 3.97 12 3.97C16.41 3.97 20.03 7.59 20.03 12C20.03 16.41 16.41 20.03 12 20.03C7.59 20.03 3.97 16.41 3.97 12C3.97 11.06 4.16 10.12 4.5 9.28L2.56 8.62C2.19 9.7 2 10.83 2 12C2 17.54 6.46 22 12 22C17.54 22 22 17.54 22 12M5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97Z"/></svg>'
|
||||||
|
export const ICON_HEART = '<svg class="pswp__icn ipp-heart-icon ipp-heart-on" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12,21.35L10.55,20.03C5.4,15.36 2,12.27 2,8.5C2,5.41 4.42,3 7.5,3C9.24,3 10.91,3.81 12,5.08C13.09,3.81 14.76,3 16.5,3C19.58,3 22,5.41 22,8.5C22,12.27 18.6,15.36 13.45,20.03L12,21.35Z"/></svg>'
|
||||||
|
export const ICON_HEART_OUTLINE = '<svg class="pswp__icn ipp-heart-icon ipp-heart-off" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.1,18.55L12,18.65L11.89,18.55C7.14,14.24 4,11.39 4,8.5C4,6.5 5.5,5 7.5,5C9.04,5 10.54,6 11.07,7.36H12.93C13.46,6 14.96,5 16.5,5C18.5,5 20,6.5 20,8.5C20,11.39 16.86,14.24 12.1,18.55M16.5,3C14.76,3 13.09,3.81 12,5.08C10.91,3.81 9.24,3 7.5,3C4.42,3 2,5.41 2,8.5C2,12.27 5.4,15.36 10.55,20.03L12,21.35L13.45,20.03C18.6,15.36 22,12.27 22,8.5C22,5.41 19.58,3 16.5,3Z"/></svg>'
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ function init () {
|
|||||||
state.groupByDate = params.groupByDate || false
|
state.groupByDate = params.groupByDate || false
|
||||||
state.metaBase = params.metaBase || ''
|
state.metaBase = params.metaBase || ''
|
||||||
state.comments = params.comments || null
|
state.comments = params.comments || null
|
||||||
|
state.hearts = params.hearts || null
|
||||||
state.container = document.getElementById('gallery')
|
state.container = document.getElementById('gallery')
|
||||||
if (!state.container) return
|
if (!state.container) return
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
registerMotionButton
|
registerMotionButton
|
||||||
} from './lightbox-ui.js'
|
} from './lightbox-ui.js'
|
||||||
import { registerSidebar } from './sidebar.js'
|
import { registerSidebar } from './sidebar.js'
|
||||||
|
import { registerHearts } from './hearts.js'
|
||||||
import { registerLazyDetail } from './metadata.js'
|
import { registerLazyDetail } from './metadata.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -252,6 +253,7 @@ export function initLightbox () {
|
|||||||
registerMotionButton(state.lightbox)
|
registerMotionButton(state.lightbox)
|
||||||
if (state.metadataConfig.descriptionInCaption) registerCaption(state.lightbox)
|
if (state.metadataConfig.descriptionInCaption) registerCaption(state.lightbox)
|
||||||
if (state.metadataConfig.sidebarHasContent) registerSidebar(state.lightbox)
|
if (state.metadataConfig.sidebarHasContent) registerSidebar(state.lightbox)
|
||||||
|
if (state.hearts) registerHearts(state.lightbox)
|
||||||
// Lazy album items load their exif / description / filename on open; this
|
// Lazy album items load their exif / description / filename on open; this
|
||||||
// refreshes the UI elements above once detail arrives.
|
// refreshes the UI elements above once detail arrives.
|
||||||
registerLazyDetail(state.lightbox)
|
registerLazyDetail(state.lightbox)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// top-level `let`s. Layout / scroll-tuning constants live here too because
|
// top-level `let`s. Layout / scroll-tuning constants live here too because
|
||||||
// they are read by multiple modules. SVG icon strings live in `icons.ts`.
|
// they are read by multiple modules. SVG icon strings live in `icons.ts`.
|
||||||
|
|
||||||
import type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js'
|
import type { CommentsConfig, GalleryItem, HeartsConfig, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js'
|
||||||
|
|
||||||
// ----- layout / scroll tuning ----------------------------------------------
|
// ----- layout / scroll tuning ----------------------------------------------
|
||||||
|
|
||||||
@@ -99,6 +99,8 @@ export const state = {
|
|||||||
metaBase: '',
|
metaBase: '',
|
||||||
// Comments API and per-photo counts; null when commenting isn't available
|
// Comments API and per-photo counts; null when commenting isn't available
|
||||||
comments: null as CommentsConfig | null,
|
comments: null as CommentsConfig | null,
|
||||||
|
// Hearts API, per-photo counts and this recipient's own; null when not available
|
||||||
|
hearts: null as HeartsConfig | null,
|
||||||
// Re-render callbacks registered by lightbox UI elements (sidebar, caption,
|
// Re-render callbacks registered by lightbox UI elements (sidebar, caption,
|
||||||
// download button). Each re-renders for the current slide. Invoked after a
|
// download button). Each re-renders for the current slide. Invoked after a
|
||||||
// lazy item's detail arrives so the just-opened slide reflects it.
|
// lazy item's detail arrives so the just-opened slide reflects it.
|
||||||
|
|||||||
@@ -48,9 +48,13 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
|||||||
// A recipient given this share can comment, which lives in the sidebar too.
|
// A recipient given this share can comment, which lives in the sidebar too.
|
||||||
// Anyone else viewing a public share (signed in or not) never sees comments.
|
// Anyone else viewing a public share (signed in or not) never sees comments.
|
||||||
const viewer = res.req.recipient
|
const viewer = res.req.recipient
|
||||||
const comments = viewer && res.req.grantedShare?.key === share.key
|
const isRecipient = !!viewer && res.req.grantedShare?.key === share.key
|
||||||
|
const comments = isRecipient
|
||||||
? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) }
|
? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) }
|
||||||
: undefined
|
: undefined
|
||||||
|
const hearts = isRecipient
|
||||||
|
? { base: '/share/hearts/' + share.key, counts: getStore().countHearts(share.key), mine: getStore().heartedBy(share.key, viewer!.id) }
|
||||||
|
: undefined
|
||||||
const sidebarHasContent = !!comments ||
|
const sidebarHasContent = !!comments ||
|
||||||
(shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location')))
|
(shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location')))
|
||||||
|
|
||||||
@@ -162,6 +166,7 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
|||||||
uploadLink: uploadLink(share),
|
uploadLink: uploadLink(share),
|
||||||
uploadHealthcheck: uploadHealthcheck(),
|
uploadHealthcheck: uploadHealthcheck(),
|
||||||
comments,
|
comments,
|
||||||
|
hearts,
|
||||||
accountLink: viewer ? '/me' : undefined
|
accountLink: viewer ? '/me' : undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,6 +178,12 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
|||||||
res.header('Cache-Control', 'private, no-cache')
|
res.header('Cache-Control', 'private, no-cache')
|
||||||
}
|
}
|
||||||
res.send(renderPage(h(Gallery, props)))
|
res.send(renderPage(h(Gallery, props)))
|
||||||
|
// Activity for the admin page: one view per gallery page opened
|
||||||
|
getStore().recordView(share.key, {
|
||||||
|
recipientId: viewer?.id,
|
||||||
|
sessionToken: res.req.sessionToken,
|
||||||
|
userAgent: res.req.headers['user-agent']
|
||||||
|
}, new Date().toISOString())
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+22
-3
@@ -107,12 +107,19 @@ type Message = { kind: 'ok' | 'error', text: string }
|
|||||||
function renderDashboard (res: Response, message?: Message) {
|
function renderDashboard (res: Response, message?: Message) {
|
||||||
const store = getStore()
|
const store = getStore()
|
||||||
const shares = store.listShares()
|
const shares = store.listShares()
|
||||||
|
const activity = store.shareActivity()
|
||||||
res.send(renderPage(h(AdminDashboard, {
|
res.send(renderPage(h(AdminDashboard, {
|
||||||
shares: shares.map(share => ({ share, recipients: store.countShareRecipients(share.key), assets: store.countKnownAssets(share.key) })),
|
shares: shares.map(share => ({
|
||||||
|
share,
|
||||||
|
recipients: store.countShareRecipients(share.key),
|
||||||
|
assets: store.countKnownAssets(share.key),
|
||||||
|
activity: activity.get(share.key)
|
||||||
|
})),
|
||||||
recipients: store.listRecipients().map(recipient => ({
|
recipients: store.listRecipients().map(recipient => ({
|
||||||
recipient,
|
recipient,
|
||||||
shares: store.listRecipientShares(recipient.id),
|
shares: store.listRecipientShares(recipient.id),
|
||||||
sessions: store.countSessions(recipient.id)
|
sessions: store.countSessions(recipient.id),
|
||||||
|
activity: store.recipientActivity(recipient.id)
|
||||||
})),
|
})),
|
||||||
comments: store.recentComments(50),
|
comments: store.recentComments(50),
|
||||||
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
||||||
@@ -126,7 +133,8 @@ function renderRecipient (res: Response, recipient: Recipient, extra: { newLink?
|
|||||||
recipient,
|
recipient,
|
||||||
shares: store.listShares(),
|
shares: store.listShares(),
|
||||||
granted: store.listRecipientShares(recipient.id).map(share => share.key),
|
granted: store.listRecipientShares(recipient.id).map(share => share.key),
|
||||||
sessions: store.countSessions(recipient.id),
|
sessions: store.listSessions(recipient.id),
|
||||||
|
activity: store.recipientActivity(recipient.id),
|
||||||
activeLinks: store.countMagicLinks(recipient.id, nowIso()),
|
activeLinks: store.countMagicLinks(recipient.id, nowIso()),
|
||||||
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
||||||
...extra
|
...extra
|
||||||
@@ -290,6 +298,17 @@ export function registerAdminRoutes (app: Express) {
|
|||||||
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
|
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
app.post('/admin/recipients/:id/sessions/:sessionId/revoke', (req, res) => {
|
||||||
|
const recipient = recipientParam(req, res)
|
||||||
|
if (!recipient) return
|
||||||
|
const signedOut = /^\d+$/.test(req.params.sessionId) && getStore().deleteSessionById(recipient.id, Number(req.params.sessionId))
|
||||||
|
renderRecipient(res, recipient, {
|
||||||
|
message: signedOut
|
||||||
|
? { kind: 'ok', text: 'Signed that browser out. Their links still work; revoke all access to cancel those too.' }
|
||||||
|
: { kind: 'error', text: 'That browser was already signed out.' }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
app.post('/admin/recipients/:id/revoke', (req, res) => {
|
app.post('/admin/recipients/:id/revoke', (req, res) => {
|
||||||
const recipient = recipientParam(req, res)
|
const recipient = recipientParam(req, res)
|
||||||
if (!recipient) return
|
if (!recipient) return
|
||||||
|
|||||||
@@ -114,6 +114,29 @@ export function registerRecipientRoutes (app: Express) {
|
|||||||
res.redirect(303, '/me')
|
res.redirect(303, '/me')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ----- hearts --------------------------------------------------------------
|
||||||
|
|
||||||
|
const heartsPath = '/share/hearts/:key/:id'
|
||||||
|
|
||||||
|
// Heart a photo. Checked against the share, so only its own photos can be hearted.
|
||||||
|
app.put(heartsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||||
|
addNoStoreHeaders(res)
|
||||||
|
const resolved = await resolveSharedAsset(req, KeyType.key)
|
||||||
|
if (!resolved.ok) {
|
||||||
|
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const count = getStore().setHeart(req.grantedShare!.key, resolved.asset.id, req.recipient!.id, true, nowIso())
|
||||||
|
res.json({ count, mine: true })
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Take a heart back. Only ever touches the recipient's own.
|
||||||
|
app.delete(heartsPath, requireShareAccess, (req, res) => {
|
||||||
|
addNoStoreHeaders(res)
|
||||||
|
const count = getStore().setHeart(req.grantedShare!.key, req.params.id, req.recipient!.id, false, nowIso())
|
||||||
|
res.json({ count, mine: false })
|
||||||
|
})
|
||||||
|
|
||||||
// ----- comments ------------------------------------------------------------
|
// ----- comments ------------------------------------------------------------
|
||||||
|
|
||||||
const commentsPath = '/share/comments/:key/:id'
|
const commentsPath = '/share/comments/:key/:id'
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ function sessionCookieOptions (req: Request): CookieOptions {
|
|||||||
|
|
||||||
/** Sign a recipient in on this browser with a long-lived cookie. */
|
/** Sign a recipient in on this browser with a long-lived cookie. */
|
||||||
export function startSession (res: Response, recipient: Recipient) {
|
export function startSession (res: Response, recipient: Recipient) {
|
||||||
const token = getStore().createSession(recipient.id, nowIso())
|
const token = getStore().createSession(recipient.id, nowIso(), res.req.headers['user-agent'])
|
||||||
res.cookie(SESSION_COOKIE, token, sessionCookieOptions(res.req))
|
res.cookie(SESSION_COOKIE, token, sessionCookieOptions(res.req))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+118
-5
@@ -33,6 +33,26 @@ export interface ShareRecord {
|
|||||||
createdAt: string
|
createdAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** How much a share, recipient or browser has been used. */
|
||||||
|
export interface Activity {
|
||||||
|
/** Gallery pages opened */
|
||||||
|
views: number
|
||||||
|
lastViewedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareActivity extends Activity {
|
||||||
|
/** Of `views`, those by visitors who weren't signed in */
|
||||||
|
anonymousViews: number
|
||||||
|
hearts: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One signed-in browser. `id` identifies it to the admin; the token never leaves the browser. */
|
||||||
|
export interface SessionRecord extends Activity {
|
||||||
|
id: number
|
||||||
|
createdAt: string
|
||||||
|
userAgent: string | null
|
||||||
|
}
|
||||||
|
|
||||||
export interface CommentRecord {
|
export interface CommentRecord {
|
||||||
id: number
|
id: number
|
||||||
shareKey: string
|
shareKey: string
|
||||||
@@ -99,6 +119,13 @@ const SCHEMA = `
|
|||||||
created_at TEXT NOT NULL
|
created_at TEXT NOT NULL
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS comments_by_asset ON comments (share_key, asset_id);
|
CREATE INDEX IF NOT EXISTS comments_by_asset ON comments (share_key, asset_id);
|
||||||
|
CREATE TABLE IF NOT EXISTS hearts (
|
||||||
|
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||||
|
asset_id TEXT NOT NULL,
|
||||||
|
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (share_key, asset_id, recipient_id)
|
||||||
|
);
|
||||||
CREATE TABLE IF NOT EXISTS link_requests (
|
CREATE TABLE IF NOT EXISTS link_requests (
|
||||||
email TEXT PRIMARY KEY COLLATE NOCASE,
|
email TEXT PRIMARY KEY COLLATE NOCASE,
|
||||||
last_at TEXT NOT NULL
|
last_at TEXT NOT NULL
|
||||||
@@ -114,6 +141,12 @@ const COMMENT_COLUMNS = `id, share_key AS shareKey, asset_id AS assetId, recipie
|
|||||||
|
|
||||||
type Row = Record<string, SQLInputValue>
|
type Row = Record<string, SQLInputValue>
|
||||||
|
|
||||||
|
/** A browser's User-Agent, trimmed for storage. */
|
||||||
|
function userAgentText (userAgent: string | undefined): string | null {
|
||||||
|
const text = (userAgent || '').trim().slice(0, 400)
|
||||||
|
return text || null
|
||||||
|
}
|
||||||
|
|
||||||
function toShare<T extends ShareRecord> (row: unknown): T | undefined {
|
function toShare<T extends ShareRecord> (row: unknown): T | undefined {
|
||||||
if (!row) return undefined
|
if (!row) return undefined
|
||||||
const share = row as Row
|
const share = row as Row
|
||||||
@@ -144,9 +177,20 @@ export class Store {
|
|||||||
|
|
||||||
/** Bring a database made by an earlier release up to the current schema. */
|
/** Bring a database made by an earlier release up to the current schema. */
|
||||||
private migrate () {
|
private migrate () {
|
||||||
const shareColumns = this.db.prepare('PRAGMA table_info(shares)').all().map(row => row.name)
|
|
||||||
// Shares added before this column existed keep requiring sign-in
|
// Shares added before this column existed keep requiring sign-in
|
||||||
if (!shareColumns.includes('public')) this.db.exec('ALTER TABLE shares ADD COLUMN public INTEGER NOT NULL DEFAULT 0')
|
this.addColumn('shares', 'public', 'INTEGER NOT NULL DEFAULT 0')
|
||||||
|
// Activity counters, which start from zero on an existing database
|
||||||
|
for (const table of ['shares', 'recipients', 'sessions']) {
|
||||||
|
this.addColumn(table, 'views', 'INTEGER NOT NULL DEFAULT 0')
|
||||||
|
this.addColumn(table, 'last_viewed_at', 'TEXT')
|
||||||
|
}
|
||||||
|
this.addColumn('shares', 'anonymous_views', 'INTEGER NOT NULL DEFAULT 0')
|
||||||
|
this.addColumn('sessions', 'user_agent', 'TEXT')
|
||||||
|
}
|
||||||
|
|
||||||
|
private addColumn (table: string, column: string, definition: string) {
|
||||||
|
const columns = this.db.prepare(`PRAGMA table_info(${table})`).all().map(row => row.name)
|
||||||
|
if (!columns.includes(column)) this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
close () {
|
close () {
|
||||||
@@ -347,13 +391,25 @@ export class Store {
|
|||||||
|
|
||||||
// ----- sessions ------------------------------------------------------------
|
// ----- sessions ------------------------------------------------------------
|
||||||
|
|
||||||
createSession (recipientId: number, now: string): string {
|
createSession (recipientId: number, now: string, userAgent?: string): string {
|
||||||
const token = newToken()
|
const token = newToken()
|
||||||
this.db.prepare('INSERT INTO sessions (token_hash, recipient_id, created_at, last_seen_at) VALUES (?, ?, ?, ?)')
|
this.db.prepare('INSERT INTO sessions (token_hash, recipient_id, created_at, last_seen_at, user_agent) VALUES (?, ?, ?, ?, ?)')
|
||||||
.run(hashToken(token), recipientId, now, now)
|
.run(hashToken(token), recipientId, now, now, userAgentText(userAgent))
|
||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A recipient's signed-in browsers, most recently used first. */
|
||||||
|
listSessions (recipientId: number): SessionRecord[] {
|
||||||
|
return this.db.prepare(`SELECT rowid AS id, created_at AS createdAt, user_agent AS userAgent, views,
|
||||||
|
COALESCE(last_viewed_at, last_seen_at) AS lastViewedAt FROM sessions WHERE recipient_id = ?
|
||||||
|
ORDER BY COALESCE(last_viewed_at, last_seen_at) DESC, rowid DESC`).all(recipientId) as unknown as SessionRecord[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sign one browser out. Scoped to the recipient, so an id from another page can't reach someone else's. */
|
||||||
|
deleteSessionById (recipientId: number, id: number): boolean {
|
||||||
|
return Number(this.db.prepare('DELETE FROM sessions WHERE rowid = ? AND recipient_id = ?').run(id, recipientId).changes) > 0
|
||||||
|
}
|
||||||
|
|
||||||
getSession (token: string): { recipient: Recipient, lastSeenAt: string } | undefined {
|
getSession (token: string): { recipient: Recipient, lastSeenAt: string } | undefined {
|
||||||
const row = this.db.prepare('SELECT recipient_id AS recipientId, last_seen_at AS lastSeenAt FROM sessions WHERE token_hash = ?')
|
const row = this.db.prepare('SELECT recipient_id AS recipientId, last_seen_at AS lastSeenAt FROM sessions WHERE token_hash = ?')
|
||||||
.get(hashToken(token)) as { recipientId: number, lastSeenAt: string } | undefined
|
.get(hashToken(token)) as { recipientId: number, lastSeenAt: string } | undefined
|
||||||
@@ -426,6 +482,63 @@ export class Store {
|
|||||||
.all(shareKey, assetId) as unknown as CommentRecord[]
|
.all(shareKey, assetId) as unknown as CommentRecord[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ----- activity ------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Count one opening of a share's gallery, against the share and, if signed in, the recipient and browser. */
|
||||||
|
recordView (shareKey: string, viewer: { recipientId?: number, sessionToken?: string, userAgent?: string }, now: string) {
|
||||||
|
this.transaction(() => {
|
||||||
|
this.db.prepare(`UPDATE shares SET views = views + 1, last_viewed_at = ?,
|
||||||
|
anonymous_views = anonymous_views + ? WHERE key = ?`).run(now, viewer.recipientId === undefined ? 1 : 0, shareKey)
|
||||||
|
if (viewer.recipientId === undefined) return
|
||||||
|
this.db.prepare('UPDATE recipients SET views = views + 1, last_viewed_at = ? WHERE id = ?').run(now, viewer.recipientId)
|
||||||
|
if (viewer.sessionToken) {
|
||||||
|
this.db.prepare(`UPDATE sessions SET views = views + 1, last_viewed_at = ?, user_agent = COALESCE(?, user_agent)
|
||||||
|
WHERE token_hash = ?`).run(now, userAgentText(viewer.userAgent), hashToken(viewer.sessionToken))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
shareActivity (): Map<string, ShareActivity> {
|
||||||
|
const rows = this.db.prepare(`SELECT key, views, anonymous_views AS anonymousViews, last_viewed_at AS lastViewedAt,
|
||||||
|
(SELECT COUNT(*) FROM hearts h WHERE h.share_key = s.key) AS hearts FROM shares s`).all()
|
||||||
|
return new Map(rows.map(row => [String(row.key), {
|
||||||
|
views: Number(row.views),
|
||||||
|
anonymousViews: Number(row.anonymousViews),
|
||||||
|
lastViewedAt: (row.lastViewedAt as string | null) ?? null,
|
||||||
|
hearts: Number(row.hearts)
|
||||||
|
}]))
|
||||||
|
}
|
||||||
|
|
||||||
|
recipientActivity (recipientId: number): Activity {
|
||||||
|
const row = this.db.prepare('SELECT views, last_viewed_at AS lastViewedAt FROM recipients WHERE id = ?').get(recipientId)
|
||||||
|
return { views: Number(row?.views ?? 0), lastViewedAt: (row?.lastViewedAt as string | null) ?? null }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- hearts --------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Heart or un-heart a photo for a recipient. Returns the photo's heart count after. */
|
||||||
|
setHeart (shareKey: string, assetId: string, recipientId: number, on: boolean, now: string): number {
|
||||||
|
if (on) {
|
||||||
|
this.db.prepare('INSERT INTO hearts (share_key, asset_id, recipient_id, created_at) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING')
|
||||||
|
.run(shareKey, assetId, recipientId, now)
|
||||||
|
} else {
|
||||||
|
this.db.prepare('DELETE FROM hearts WHERE share_key = ? AND asset_id = ? AND recipient_id = ?').run(shareKey, assetId, recipientId)
|
||||||
|
}
|
||||||
|
const row = this.db.prepare('SELECT COUNT(*) AS n FROM hearts WHERE share_key = ? AND asset_id = ?').get(shareKey, assetId)
|
||||||
|
return Number(row?.n ?? 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
countHearts (shareKey: string): Record<string, number> {
|
||||||
|
const rows = this.db.prepare('SELECT asset_id AS id, COUNT(*) AS n FROM hearts WHERE share_key = ? GROUP BY asset_id').all(shareKey)
|
||||||
|
return Object.fromEntries(rows.map(row => [String(row.id), Number(row.n)]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The photos in a share this recipient has hearted. */
|
||||||
|
heartedBy (shareKey: string, recipientId: number): string[] {
|
||||||
|
return this.db.prepare('SELECT asset_id AS id FROM hearts WHERE share_key = ? AND recipient_id = ?')
|
||||||
|
.all(shareKey, recipientId).map(row => String(row.id))
|
||||||
|
}
|
||||||
|
|
||||||
countComments (shareKey: string): Record<string, number> {
|
countComments (shareKey: string): Record<string, number> {
|
||||||
const rows = this.db.prepare('SELECT asset_id AS id, COUNT(*) AS n FROM comments WHERE share_key = ? GROUP BY asset_id').all(shareKey)
|
const rows = this.db.prepare('SELECT asset_id AS id, COUNT(*) AS n FROM comments WHERE share_key = ? GROUP BY asset_id').all(shareKey)
|
||||||
return Object.fromEntries(rows.map(row => [String(row.id), Number(row.n)]))
|
return Object.fromEntries(rows.map(row => [String(row.id), Number(row.n)]))
|
||||||
|
|||||||
+67
-10
@@ -1,5 +1,5 @@
|
|||||||
import { ComponentChildren } from 'preact'
|
import { ComponentChildren } from 'preact'
|
||||||
import { CommentRecord, Frequency, FREQUENCIES, Recipient, ShareRecord } from './store'
|
import { Activity, CommentRecord, Frequency, FREQUENCIES, Recipient, SessionRecord, ShareActivity, ShareRecord } from './store'
|
||||||
|
|
||||||
const FREQUENCY_LABELS: Record<Frequency, string> = {
|
const FREQUENCY_LABELS: Record<Frequency, string> = {
|
||||||
off: 'Never',
|
off: 'Never',
|
||||||
@@ -23,6 +23,33 @@ const STYLE = `
|
|||||||
.albums a { display: block; padding: .6rem .9rem; margin-bottom: .5rem; border-radius: var(--pico-border-radius); background: var(--pico-card-background-color); box-shadow: var(--pico-card-box-shadow); text-decoration: none; }
|
.albums a { display: block; padding: .6rem .9rem; margin-bottom: .5rem; border-radius: var(--pico-border-radius); background: var(--pico-card-background-color); box-shadow: var(--pico-card-box-shadow); text-decoration: none; }
|
||||||
`
|
`
|
||||||
|
|
||||||
|
/** When something last happened, in the server's timezone, or "never". */
|
||||||
|
function lastSeen (iso: string | null): string {
|
||||||
|
return iso ? new Date(iso).toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' }) : 'never'
|
||||||
|
}
|
||||||
|
|
||||||
|
function plural (n: number, word: string): string {
|
||||||
|
return n + ' ' + word + (n === 1 ? '' : 's')
|
||||||
|
}
|
||||||
|
|
||||||
|
// First match wins, so more specific names come before the ones they contain
|
||||||
|
const BROWSERS: Array<[RegExp, string]> = [
|
||||||
|
[/Edg\//, 'Edge'], [/OPR\/|Opera/, 'Opera'], [/SamsungBrowser\//, 'Samsung Internet'],
|
||||||
|
[/Firefox\/|FxiOS\//, 'Firefox'], [/Chrome\/|CriOS\//, 'Chrome'], [/Safari\//, 'Safari']
|
||||||
|
]
|
||||||
|
const DEVICES: Array<[RegExp, string]> = [
|
||||||
|
[/iPhone/, 'iPhone'], [/iPad/, 'iPad'], [/Android/, 'Android'], [/Windows/, 'Windows'],
|
||||||
|
[/Mac OS X|Macintosh/, 'Mac'], [/CrOS/, 'ChromeOS'], [/Linux/, 'Linux']
|
||||||
|
]
|
||||||
|
|
||||||
|
/** A short name for a browser from its User-Agent, e.g. "Safari on iPhone". */
|
||||||
|
export function browserName (userAgent: string | null): string {
|
||||||
|
if (!userAgent) return 'Unknown browser'
|
||||||
|
const browser = BROWSERS.find(([pattern]) => pattern.test(userAgent))?.[1] || 'Browser'
|
||||||
|
const device = DEVICES.find(([pattern]) => pattern.test(userAgent))?.[1]
|
||||||
|
return device ? browser + ' on ' + device : browser
|
||||||
|
}
|
||||||
|
|
||||||
// Forms with data-confirm ask before submitting
|
// Forms with data-confirm ask before submitting
|
||||||
// and inputs with data-autosubmit submit their form as soon as they change
|
// and inputs with data-autosubmit submit their form as soon as they change
|
||||||
const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) {
|
const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) {
|
||||||
@@ -157,8 +184,8 @@ export function AdminLogin ({ failed }: { failed?: boolean }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminShareRow { share: ShareRecord, recipients: number, assets: number }
|
export interface AdminShareRow { share: ShareRecord, recipients: number, assets: number, activity?: ShareActivity }
|
||||||
export interface AdminRecipientRow { recipient: Recipient, shares: ShareRecord[], sessions: number }
|
export interface AdminRecipientRow { recipient: Recipient, shares: ShareRecord[], sessions: number, activity: Activity }
|
||||||
|
|
||||||
export interface AdminDashboardProps {
|
export interface AdminDashboardProps {
|
||||||
shares: AdminShareRow[]
|
shares: AdminShareRow[]
|
||||||
@@ -194,9 +221,9 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me
|
|||||||
<p class="muted">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.</p>
|
<p class="muted">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.</p>
|
||||||
{shares.length > 0 && (
|
{shares.length > 0 && (
|
||||||
<table>
|
<table>
|
||||||
<thead><tr><th>Album</th><th>Public link works</th><th>Recipients</th><th>Photos tracked</th><th></th></tr></thead>
|
<thead><tr><th>Album</th><th>Public link works</th><th>Recipients</th><th>Views</th><th>Photos tracked</th><th></th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{shares.map(({ share, recipients: count, assets }) => (
|
{shares.map(({ share, recipients: count, assets, activity }) => (
|
||||||
<tr key={share.key}>
|
<tr key={share.key}>
|
||||||
<td>{share.title || 'Untitled'}<br/><small class="muted">{share.slug ? 's/' + share.slug : share.key.slice(0, 12) + '…'}{share.password ? ' · password stored' : ''}</small></td>
|
<td>{share.title || 'Untitled'}<br/><small class="muted">{share.slug ? 's/' + share.slug : share.key.slice(0, 12) + '…'}{share.password ? ' · password stored' : ''}</small></td>
|
||||||
<td>
|
<td>
|
||||||
@@ -211,6 +238,13 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me
|
|||||||
</form>
|
</form>
|
||||||
</td>
|
</td>
|
||||||
<td>{count}</td>
|
<td>{count}</td>
|
||||||
|
<td>
|
||||||
|
{activity?.views ?? 0}
|
||||||
|
{activity && activity.hearts > 0 && <> · ♥ {activity.hearts}</>}
|
||||||
|
<br/><small class="muted">
|
||||||
|
{activity?.anonymousViews ? activity.anonymousViews + ' not signed in · ' : ''}last {lastSeen(activity?.lastViewedAt ?? null)}
|
||||||
|
</small>
|
||||||
|
</td>
|
||||||
<td>{assets}</td>
|
<td>{assets}</td>
|
||||||
<td>
|
<td>
|
||||||
<form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/delete'}
|
<form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/delete'}
|
||||||
@@ -247,13 +281,14 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me
|
|||||||
<h2>Recipients</h2>
|
<h2>Recipients</h2>
|
||||||
{recipients.length > 0 && (
|
{recipients.length > 0 && (
|
||||||
<table>
|
<table>
|
||||||
<thead><tr><th>Name</th><th>Albums</th><th>Emails</th><th>Signed-in browsers</th></tr></thead>
|
<thead><tr><th>Name</th><th>Albums</th><th>Emails</th><th>Views</th><th>Signed-in browsers</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{recipients.map(({ recipient, shares: granted, sessions }) => (
|
{recipients.map(({ recipient, shares: granted, sessions, activity }) => (
|
||||||
<tr key={recipient.id}>
|
<tr key={recipient.id}>
|
||||||
<td><a href={'/admin/recipients/' + recipient.id}>{recipient.name}</a>{recipient.disabled && <> <small>(disabled)</small></>}<br/><small class="muted">{recipient.email}</small></td>
|
<td><a href={'/admin/recipients/' + recipient.id}>{recipient.name}</a>{recipient.disabled && <> <small>(disabled)</small></>}<br/><small class="muted">{recipient.email}</small></td>
|
||||||
<td>{granted.map(s => s.title).join(', ') || <span class="muted">none</span>}</td>
|
<td>{granted.map(s => s.title).join(', ') || <span class="muted">none</span>}</td>
|
||||||
<td>{FREQUENCY_LABELS[recipient.frequency]}</td>
|
<td>{FREQUENCY_LABELS[recipient.frequency]}</td>
|
||||||
|
<td>{activity.views}<br/><small class="muted">last {lastSeen(activity.lastViewedAt)}</small></td>
|
||||||
<td>{sessions}</td>
|
<td>{sessions}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@@ -335,7 +370,8 @@ export interface AdminRecipientProps {
|
|||||||
recipient: Recipient
|
recipient: Recipient
|
||||||
shares: ShareRecord[]
|
shares: ShareRecord[]
|
||||||
granted: string[]
|
granted: string[]
|
||||||
sessions: number
|
sessions: SessionRecord[]
|
||||||
|
activity: Activity
|
||||||
activeLinks: number
|
activeLinks: number
|
||||||
emailEnabled: boolean
|
emailEnabled: boolean
|
||||||
/** A link created by this request; shown once, never stored in plain text. */
|
/** 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 }
|
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
|
const base = '/admin/recipients/' + recipient.id
|
||||||
return (
|
return (
|
||||||
<Layout title={recipient.name + ' · Admin'}>
|
<Layout title={recipient.name + ' · Admin'}>
|
||||||
@@ -369,7 +405,28 @@ export function AdminRecipient ({ recipient, shares, granted, sessions, activeLi
|
|||||||
</form>
|
</form>
|
||||||
|
|
||||||
<h2>Access</h2>
|
<h2>Access</h2>
|
||||||
<p>{sessions} signed-in browser{sessions === 1 ? '' : 's'} · {activeLinks} working link{activeLinks === 1 ? '' : 's'}</p>
|
<p>{plural(activity.views, 'album view')}, last {lastSeen(activity.lastViewedAt)} · {plural(sessions.length, 'signed-in browser')} · {plural(activeLinks, 'working link')}</p>
|
||||||
|
{sessions.length > 0 && (
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>Browser</th><th>Signed in</th><th>Last used</th><th>Views</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{sessions.map(session => (
|
||||||
|
<tr key={session.id}>
|
||||||
|
<td title={session.userAgent || undefined}>{browserName(session.userAgent)}</td>
|
||||||
|
<td>{lastSeen(session.createdAt)}</td>
|
||||||
|
<td>{lastSeen(session.lastViewedAt)}</td>
|
||||||
|
<td>{session.views}</td>
|
||||||
|
<td>
|
||||||
|
<form method="post" action={base + '/sessions/' + session.id + '/revoke'} style="margin:0"
|
||||||
|
data-confirm='Sign this browser out? Their links still work, so they can sign in again unless you revoke those too.'>
|
||||||
|
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Revoke</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
<div class="row-actions">
|
<div class="row-actions">
|
||||||
<form method="post" action={base + '/link'}>
|
<form method="post" action={base + '/link'}>
|
||||||
<button type="submit">Create a new link</button>
|
<button type="submit">Create a new link</button>
|
||||||
|
|||||||
@@ -99,6 +99,15 @@ export interface MetadataConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Per-photo comments for the signed-in recipient. */
|
/** Per-photo comments for the signed-in recipient. */
|
||||||
|
export interface HeartsConfig {
|
||||||
|
// `/share/hearts/<key>`; append `/<assetId>`
|
||||||
|
base: string
|
||||||
|
// Heart count per asset id
|
||||||
|
counts: Record<string, number>
|
||||||
|
// Asset ids this recipient has hearted
|
||||||
|
mine: string[]
|
||||||
|
}
|
||||||
|
|
||||||
export interface CommentsConfig {
|
export interface CommentsConfig {
|
||||||
// `/share/comments/<key>`; append `/<assetId>`
|
// `/share/comments/<key>`; append `/<assetId>`
|
||||||
base: string
|
base: string
|
||||||
@@ -128,4 +137,5 @@ export interface InitParams {
|
|||||||
groupByDate?: GroupByDateMode | false
|
groupByDate?: GroupByDateMode | false
|
||||||
metaBase?: string
|
metaBase?: string
|
||||||
comments?: CommentsConfig
|
comments?: CommentsConfig
|
||||||
|
hearts?: HeartsConfig
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core'
|
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'
|
import { ASSET_VERSION } from '../version'
|
||||||
|
|
||||||
export type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
|
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
|
// Set when the upload service is assumed rather than configured: the button
|
||||||
// stays hidden until the client finds this URL answering
|
// stays hidden until the client finds this URL answering
|
||||||
uploadHealthcheck?: string
|
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
|
comments?: CommentsConfig
|
||||||
|
hearts?: HeartsConfig
|
||||||
// The recipient's albums and notification settings
|
// The recipient's albums and notification settings
|
||||||
accountLink?: string
|
accountLink?: string
|
||||||
}
|
}
|
||||||
@@ -40,7 +41,8 @@ export function Gallery (props: GalleryProps) {
|
|||||||
metadataConfig: props.metadataConfig,
|
metadataConfig: props.metadataConfig,
|
||||||
groupByDate: props.groupByDate,
|
groupByDate: props.groupByDate,
|
||||||
metaBase: props.metaBase,
|
metaBase: props.metaBase,
|
||||||
comments: props.comments
|
comments: props.comments,
|
||||||
|
hearts: props.hearts
|
||||||
})
|
})
|
||||||
const firstItem = props.items[0]
|
const firstItem = props.items[0]
|
||||||
// og:image prefers the album cover (passed via props); for videos, previewUrl
|
// og:image prefers the album cover (passed via props); for videos, previewUrl
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
|||||||
import { loadConfig } from '@ipp/core'
|
import { loadConfig } from '@ipp/core'
|
||||||
import { Recipient, setStore, Store } from '../src/magic/store'
|
import { Recipient, setStore, Store } from '../src/magic/store'
|
||||||
import { Mail, setMailSender } from '../src/magic/mailer'
|
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
|
End to end: the real app in front of a fake Immich. Proves that nothing is
|
||||||
@@ -144,6 +145,7 @@ afterAll(async () => {
|
|||||||
|
|
||||||
interface Options {
|
interface Options {
|
||||||
cookie?: string
|
cookie?: string
|
||||||
|
userAgent?: string
|
||||||
page?: boolean
|
page?: boolean
|
||||||
method?: string
|
method?: string
|
||||||
json?: unknown
|
json?: unknown
|
||||||
@@ -153,6 +155,7 @@ interface Options {
|
|||||||
async function request (path: string, options: Options = {}) {
|
async function request (path: string, options: Options = {}) {
|
||||||
const headers: Record<string, string> = {}
|
const headers: Record<string, string> = {}
|
||||||
if (options.cookie) headers.Cookie = options.cookie
|
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'
|
if (options.page) headers.Accept = 'text/html,application/xhtml+xml'
|
||||||
let body: string | undefined
|
let body: string | undefined
|
||||||
if (options.json !== undefined) {
|
if (options.json !== undefined) {
|
||||||
@@ -529,3 +532,108 @@ describe('public shares', () => {
|
|||||||
expect(store.getShare(KEY_D)?.public).toBe(true)
|
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('<th>Views</th>')
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -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({})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user