Gate shares behind magic-link sessions, add comments and new-photo email digests
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
// Comments thread for the current lightbox slide, rendered as a section of
|
||||
// the info sidebar. Comment text is always set with textContent, never HTML.
|
||||
|
||||
import { state } from './state.js'
|
||||
import type { CommentView, GalleryItem } from '../shared/types.js'
|
||||
|
||||
const MAX_LENGTH = 2000
|
||||
|
||||
// Comments already fetched, by asset id, so paging back and forth is instant
|
||||
const loaded = new Map<string, CommentView[]>()
|
||||
// Unsent text by asset id: the sidebar re-renders on slide change and when
|
||||
// lazy metadata arrives, and that must not throw away what someone typed
|
||||
const drafts = new Map<string, string>()
|
||||
|
||||
export function commentCount (assetId: string): number {
|
||||
return state.comments?.counts[assetId] || 0
|
||||
}
|
||||
|
||||
function setCount (assetId: string, count: number) {
|
||||
if (state.comments) state.comments.counts[assetId] = count
|
||||
}
|
||||
|
||||
function url (assetId: string, commentId?: number): string {
|
||||
return state.comments!.base + '/' + encodeURIComponent(assetId) + (commentId != null ? '/' + commentId : '')
|
||||
}
|
||||
|
||||
export function isTyping (target: EventTarget | null): boolean {
|
||||
const el = target as HTMLElement | null
|
||||
return !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)
|
||||
}
|
||||
|
||||
const DATE_FORMAT: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short' }
|
||||
|
||||
function formatWhen (iso: string): string {
|
||||
const date = new Date(iso)
|
||||
return isNaN(date.getTime()) ? '' : date.toLocaleString(undefined, DATE_FORMAT)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the comments section for a slide. `onCountChange` runs after a
|
||||
* comment is added or removed, so the toolbar badge can follow.
|
||||
*/
|
||||
export function renderCommentsSection (item: GalleryItem, onCountChange: () => void, withHeading: boolean): HTMLElement {
|
||||
const section = document.createElement('section')
|
||||
section.className = 'ipp-sidebar-section ipp-sidebar-comments'
|
||||
|
||||
if (withHeading) {
|
||||
const heading = document.createElement('h3')
|
||||
heading.className = 'ipp-sidebar-heading'
|
||||
heading.textContent = 'Comments'
|
||||
section.appendChild(heading)
|
||||
} else {
|
||||
section.classList.add('ipp-sidebar-comments-only')
|
||||
}
|
||||
|
||||
const list = document.createElement('div')
|
||||
list.className = 'ipp-comments-list'
|
||||
list.setAttribute('aria-live', 'polite')
|
||||
section.appendChild(list)
|
||||
|
||||
const form = document.createElement('form')
|
||||
form.className = 'ipp-comment-form'
|
||||
const input = document.createElement('textarea')
|
||||
input.className = 'ipp-comment-input'
|
||||
input.rows = 3
|
||||
input.maxLength = MAX_LENGTH
|
||||
input.placeholder = 'Write a comment…'
|
||||
input.setAttribute('aria-label', 'Write a comment')
|
||||
input.value = drafts.get(item.id) || ''
|
||||
const error = document.createElement('p')
|
||||
error.className = 'ipp-comment-error'
|
||||
error.hidden = true
|
||||
const submit = document.createElement('button')
|
||||
submit.type = 'submit'
|
||||
submit.className = 'ipp-comment-submit'
|
||||
submit.textContent = 'Post'
|
||||
form.append(input, error, submit)
|
||||
section.appendChild(form)
|
||||
|
||||
input.addEventListener('input', () => {
|
||||
if (input.value) drafts.set(item.id, input.value)
|
||||
else drafts.delete(item.id)
|
||||
})
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault()
|
||||
form.requestSubmit()
|
||||
}
|
||||
})
|
||||
|
||||
const showError = (message: string) => {
|
||||
error.textContent = message
|
||||
error.hidden = false
|
||||
}
|
||||
|
||||
const renderList = (comments: CommentView[]) => {
|
||||
list.replaceChildren()
|
||||
if (!comments.length) {
|
||||
const empty = document.createElement('p')
|
||||
empty.className = 'ipp-sidebar-empty'
|
||||
empty.textContent = 'No comments yet.'
|
||||
list.appendChild(empty)
|
||||
return
|
||||
}
|
||||
for (const comment of comments) list.appendChild(renderComment(comment))
|
||||
}
|
||||
|
||||
const renderComment = (comment: CommentView): HTMLElement => {
|
||||
const el = document.createElement('article')
|
||||
el.className = 'ipp-comment'
|
||||
const meta = document.createElement('header')
|
||||
const author = document.createElement('strong')
|
||||
author.textContent = comment.author
|
||||
const when = document.createElement('time')
|
||||
when.dateTime = comment.createdAt
|
||||
when.textContent = formatWhen(comment.createdAt)
|
||||
meta.append(author, when)
|
||||
const body = document.createElement('p')
|
||||
body.textContent = comment.body
|
||||
el.append(meta, body)
|
||||
if (comment.mine) {
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'ipp-comment-delete'
|
||||
remove.textContent = 'Delete'
|
||||
remove.addEventListener('click', async () => {
|
||||
if (!confirm('Delete your comment?')) return
|
||||
remove.disabled = true
|
||||
const res = await fetch(url(item.id, comment.id), { method: 'DELETE' }).catch(() => null)
|
||||
if (!res || (res.status !== 204 && res.status !== 404)) {
|
||||
remove.disabled = false
|
||||
showError('Couldn\'t delete the comment. Try again.')
|
||||
return
|
||||
}
|
||||
const remaining = (loaded.get(item.id) || []).filter(c => c.id !== comment.id)
|
||||
loaded.set(item.id, remaining)
|
||||
setCount(item.id, remaining.length)
|
||||
renderList(remaining)
|
||||
onCountChange()
|
||||
})
|
||||
el.appendChild(remove)
|
||||
}
|
||||
return el
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault()
|
||||
const text = input.value.trim()
|
||||
if (!text) return
|
||||
submit.disabled = true
|
||||
error.hidden = true
|
||||
try {
|
||||
const res = await fetch(url(item.id), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ body: text })
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (res.status !== 201) {
|
||||
showError(data?.error || 'Couldn\'t post the comment. Try again.')
|
||||
return
|
||||
}
|
||||
const comments = [...(loaded.get(item.id) || []), data as CommentView]
|
||||
loaded.set(item.id, comments)
|
||||
setCount(item.id, comments.length)
|
||||
drafts.delete(item.id)
|
||||
input.value = ''
|
||||
renderList(comments)
|
||||
onCountChange()
|
||||
} catch {
|
||||
showError('Couldn\'t post the comment. Check your connection.')
|
||||
} finally {
|
||||
submit.disabled = false
|
||||
}
|
||||
})
|
||||
|
||||
const cached = loaded.get(item.id)
|
||||
if (cached) {
|
||||
renderList(cached)
|
||||
} else if (!commentCount(item.id) && !state.sidebarOpen) {
|
||||
// Nothing when the page loaded, and nobody's looking: skip the request
|
||||
renderList([])
|
||||
} else {
|
||||
const loading = document.createElement('p')
|
||||
loading.className = 'ipp-sidebar-empty'
|
||||
loading.textContent = 'Loading comments…'
|
||||
list.appendChild(loading)
|
||||
fetch(url(item.id), { cache: 'no-store' })
|
||||
.then(res => res.ok ? res.json() : Promise.reject(new Error(String(res.status))))
|
||||
.then((comments: CommentView[]) => {
|
||||
loaded.set(item.id, comments)
|
||||
if (commentCount(item.id) !== comments.length) {
|
||||
setCount(item.id, comments.length)
|
||||
onCountChange()
|
||||
}
|
||||
renderList(comments)
|
||||
})
|
||||
.catch(() => {
|
||||
list.replaceChildren()
|
||||
showError('Couldn\'t load comments.')
|
||||
})
|
||||
}
|
||||
|
||||
return section
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export const ICON_INFO = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden
|
||||
export const ICON_BACK = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"/></svg>'
|
||||
// Motion photo (Live Photo) toggle, off / on. Same pair as Immich's viewer.
|
||||
export const ICON_MOTION_PLAY = '<svg class="pswp__icn" 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_COMMENT = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M9,22A1,1 0 0,1 8,21V18H4A2,2 0 0,1 2,16V4C2,2.89 2.9,2 4,2H20A2,2 0 0,1 22,4V16A2,2 0 0,1 20,18H13.9L10.2,21.71C10,21.9 9.75,22 9.5,22H9M10,16V19.08L13.08,16H20V4H4V16H10Z"/></svg>'
|
||||
export const ICON_MOTION_PAUSE = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M22 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 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7M9 9H11V15H9M13 9H15V15H13"/></svg>'
|
||||
export const ICON_CLOSE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/></svg>'
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ function init () {
|
||||
if (params.metadataConfig) state.metadataConfig = params.metadataConfig
|
||||
state.groupByDate = params.groupByDate || false
|
||||
state.metaBase = params.metaBase || ''
|
||||
state.comments = params.comments || null
|
||||
state.container = document.getElementById('gallery')
|
||||
if (!state.container) return
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js' // eslint-disable-line import/no-absolute-path
|
||||
|
||||
import type { PhotoSwipeOptions } from 'photoswipe'
|
||||
import { state, SIDEBAR_WIDTH, MOBILE_BREAKPOINT } from './state.js'
|
||||
import { state, SIDEBAR_WIDTH, SIDEBAR_SHEET_FRACTION, MOBILE_BREAKPOINT } from './state.js'
|
||||
import type { GalleryItem } from '../shared/types.js'
|
||||
import {
|
||||
registerBackButton,
|
||||
@@ -211,14 +211,19 @@ export function initLightbox () {
|
||||
// precedence over `padding`, and spreading it last neutralises any `padding`
|
||||
// or (mistyped) `paddingFn` an operator put in config. Their static `padding`
|
||||
// is still honoured above via basePadding. It lets the sidebar shrink the
|
||||
// slide viewport when docked; on a narrow viewport the sidebar overlays
|
||||
// instead, so we leave padding alone there.
|
||||
paddingFn: () => ({
|
||||
...basePadding,
|
||||
right: state.sidebarOpen && window.innerWidth >= MOBILE_BREAKPOINT
|
||||
? SIDEBAR_WIDTH + basePadding.right
|
||||
: basePadding.right
|
||||
}),
|
||||
// slide viewport: from the right when docked, and from the bottom when it
|
||||
// is a bottom sheet on a narrow viewport, so the photo stays in view above
|
||||
// the comments.
|
||||
paddingFn: () => {
|
||||
const narrow = window.innerWidth < MOBILE_BREAKPOINT
|
||||
return {
|
||||
...basePadding,
|
||||
right: state.sidebarOpen && !narrow ? SIDEBAR_WIDTH + basePadding.right : basePadding.right,
|
||||
bottom: state.sidebarOpen && narrow
|
||||
? Math.round(window.innerHeight * SIDEBAR_SHEET_FRACTION) + basePadding.bottom
|
||||
: basePadding.bottom
|
||||
}
|
||||
},
|
||||
dataSource: buildDataSource(),
|
||||
// @ts-expect-error - runtime URL resolved by Express static
|
||||
pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js') // eslint-disable-line import/no-absolute-path
|
||||
|
||||
+59
-13
@@ -5,9 +5,15 @@
|
||||
// by the toolbar info button or the `i` key, persisted via localStorage.
|
||||
|
||||
import { state, SIDEBAR_STORAGE_KEY } from './state.js'
|
||||
import { ICON_INFO, ICON_CLOSE, ICON_IMAGE, ICON_CALENDAR, ICON_CAMERA, ICON_IRIS, ICON_MAP } from './icons.js'
|
||||
import { ICON_INFO, ICON_CLOSE, ICON_COMMENT, ICON_IMAGE, ICON_CALENDAR, ICON_CAMERA, ICON_IRIS, ICON_MAP } from './icons.js'
|
||||
import { commentCount, isTyping, renderCommentsSection } from './comments.js'
|
||||
import type { GalleryItem, GalleryExif } from '../shared/types.js'
|
||||
|
||||
// Re-renders the sidebar for the current slide; set while the lightbox is open
|
||||
let rerender: (() => void) | undefined
|
||||
// Updates the comment-count badge on the toolbar button
|
||||
let updateCommentBadge: (() => void) | undefined
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type LightboxInstance = any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -37,19 +43,57 @@ export function registerSidebar (lightbox: LightboxInstance) {
|
||||
appendTo: 'root',
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
el.classList.add('ipp-sidebar')
|
||||
el.setAttribute('aria-label', 'Photo information')
|
||||
el.setAttribute('aria-label', state.comments ? 'Photo information and comments' : 'Photo information')
|
||||
const renderSidebar = () => renderContents(el, state.items[pswp.currIndex])
|
||||
rerender = renderSidebar
|
||||
renderSidebar()
|
||||
pswp.on('change', renderSidebar)
|
||||
// Re-render when a lazy album item's detail arrives after open.
|
||||
state.slideRefreshers.push(renderSidebar)
|
||||
pswp.on('destroy', () => {
|
||||
document.documentElement.classList.remove('ipp-sidebar-open')
|
||||
rerender = undefined
|
||||
updateCommentBadge = undefined
|
||||
})
|
||||
// Typing a comment must not page through slides or close the lightbox
|
||||
pswp.on('keydown', (e: { originalEvent: KeyboardEvent, preventDefault: () => void }) => {
|
||||
if (isTyping(e.originalEvent.target)) e.preventDefault()
|
||||
})
|
||||
applyOpenState(pswp)
|
||||
}
|
||||
} as PswpUiElementConfig)
|
||||
|
||||
if (state.comments) {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'comments-toggle',
|
||||
order: 8,
|
||||
isButton: true,
|
||||
ariaLabel: 'Comments',
|
||||
html: ICON_COMMENT + '<span class="ipp-comment-badge" hidden></span>',
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
const badge = el.querySelector('.ipp-comment-badge') as HTMLElement
|
||||
const update = () => {
|
||||
const count = commentCount(state.items[pswp.currIndex]?.id || '')
|
||||
badge.textContent = count > 99 ? '99+' : String(count)
|
||||
badge.hidden = count === 0
|
||||
el.setAttribute('aria-label', count ? 'Comments (' + count + ')' : 'Comments')
|
||||
}
|
||||
updateCommentBadge = update
|
||||
update()
|
||||
pswp.on('change', update)
|
||||
el.addEventListener('click', () => {
|
||||
setSidebarOpen(pswp, true)
|
||||
const section = document.querySelector('.ipp-sidebar-comments')
|
||||
section?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
|
||||
// On touch screens focusing would throw the keyboard up over the photo
|
||||
if (window.matchMedia('(pointer: fine)').matches) {
|
||||
(section?.querySelector('.ipp-comment-input') as HTMLTextAreaElement | null)?.focus({ preventScroll: true })
|
||||
}
|
||||
})
|
||||
}
|
||||
} as PswpUiElementConfig)
|
||||
}
|
||||
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'sidebar-toggle',
|
||||
order: 7,
|
||||
@@ -72,11 +116,9 @@ export function registerSidebar (lightbox: LightboxInstance) {
|
||||
// keypress hook for arbitrary keys.
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (!state.lightbox || !state.lightbox.pswp) return
|
||||
// Leave keys alone while someone types a comment
|
||||
if (isTyping(e.target)) return
|
||||
if (e.key === 'i' || e.key === 'I') {
|
||||
// Don't steal `i` from text inputs (none exist in the lightbox today,
|
||||
// but better safe).
|
||||
const target = e.target as HTMLElement | null
|
||||
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return
|
||||
e.preventDefault()
|
||||
toggleSidebar(state.lightbox.pswp)
|
||||
} else if (e.key === 'Escape' && state.sidebarOpen) {
|
||||
@@ -96,6 +138,8 @@ function setSidebarOpen (pswp: PswpInstance, open: boolean) {
|
||||
state.sidebarOpen = open
|
||||
writePersistedState(open)
|
||||
applyOpenState(pswp)
|
||||
// Opening fetches the comments, which are skipped while it's closed
|
||||
if (open && state.comments) rerender?.()
|
||||
}
|
||||
|
||||
function applyOpenState (pswp: PswpInstance) {
|
||||
@@ -133,9 +177,10 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
|
||||
root.replaceChildren()
|
||||
if (!item) return
|
||||
|
||||
root.appendChild(renderHeader())
|
||||
|
||||
const showDescription = state.metadataConfig.descriptionInSidebar && !!item.description
|
||||
const metadataShown = showDescription || !!(item.exif && (hasAnyExifField(item.exif) || hasAnyLocationField(item.exif)))
|
||||
root.appendChild(renderHeader(state.comments && !metadataShown ? 'Comments' : 'Info'))
|
||||
|
||||
if (showDescription && item.description) {
|
||||
root.appendChild(renderSection('description', renderDescription(item.description)))
|
||||
}
|
||||
@@ -149,8 +194,9 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
|
||||
root.appendChild(renderSection('location', renderLocation(exif)))
|
||||
}
|
||||
|
||||
const noExifShown = !exif || (!hasAnyExifField(exif) && !hasAnyLocationField(exif))
|
||||
if (!showDescription && noExifShown) {
|
||||
if (state.comments) {
|
||||
root.appendChild(renderCommentsSection(item, () => updateCommentBadge?.(), metadataShown))
|
||||
} else if (!metadataShown) {
|
||||
const empty = document.createElement('p')
|
||||
empty.className = 'ipp-sidebar-empty'
|
||||
empty.textContent = 'No metadata available'
|
||||
@@ -158,13 +204,13 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
|
||||
}
|
||||
}
|
||||
|
||||
function renderHeader (): HTMLElement {
|
||||
function renderHeader (titleText: string): HTMLElement {
|
||||
const header = document.createElement('header')
|
||||
header.className = 'ipp-sidebar-header'
|
||||
const close = document.createElement('button')
|
||||
close.type = 'button'
|
||||
close.className = 'ipp-sidebar-close'
|
||||
close.setAttribute('aria-label', 'Close info')
|
||||
close.setAttribute('aria-label', 'Close ' + titleText.toLowerCase())
|
||||
close.innerHTML = ICON_CLOSE
|
||||
close.addEventListener('click', () => {
|
||||
if (state.lightbox && state.lightbox.pswp) setSidebarOpen(state.lightbox.pswp, false)
|
||||
@@ -172,7 +218,7 @@ function renderHeader (): HTMLElement {
|
||||
header.appendChild(close)
|
||||
const title = document.createElement('span')
|
||||
title.className = 'ipp-sidebar-title'
|
||||
title.textContent = 'Info'
|
||||
title.textContent = titleText
|
||||
header.appendChild(title)
|
||||
return header
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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`.
|
||||
|
||||
import type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js'
|
||||
import type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js'
|
||||
|
||||
// ----- layout / scroll tuning ----------------------------------------------
|
||||
|
||||
@@ -28,6 +28,8 @@ export const LONG_PRESS_MS = 500
|
||||
export const SIDEBAR_STORAGE_KEY = 'ipp-sidebar-open'
|
||||
// Width of the sidebar when docked (must match the CSS rule)
|
||||
export const SIDEBAR_WIDTH = 360
|
||||
// Height of the sidebar as a bottom sheet, as a fraction of the viewport (must match the CSS 60vh)
|
||||
export const SIDEBAR_SHEET_FRACTION = 0.6
|
||||
|
||||
// ----- mutable state -------------------------------------------------------
|
||||
|
||||
@@ -95,6 +97,8 @@ export const state = {
|
||||
sidebarOpen: false,
|
||||
// Base URL (`/share/meta/<key>`) for the on-demand per-asset metadata route.
|
||||
metaBase: '',
|
||||
// Comments API and per-photo counts; null when commenting isn't available
|
||||
comments: null as CommentsConfig | null,
|
||||
// Re-render callbacks registered by lightbox UI elements (sidebar, caption,
|
||||
// download button). Each re-renders for the current slide. Invoked after a
|
||||
// lazy item's detail arrives so the just-opened slide reflects it.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
|
||||
import { AssetType, getConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core'
|
||||
import {
|
||||
getVideoContentType,
|
||||
photoUrl,
|
||||
@@ -13,6 +13,7 @@ import { downloadFilename, positionInShare } from './filename'
|
||||
import { groupByDateMode } from './order'
|
||||
import { requiresOriginal } from './sizing'
|
||||
import { displayDimensions, metadataGroupActive, pickExif } from './exif'
|
||||
import { getStore } from '../magic/store'
|
||||
|
||||
/**
|
||||
* Render a gallery page for a given SharedLink.
|
||||
@@ -44,7 +45,13 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
const motionPhotos = !!getConfigOption('ipp.motionPhotos', true)
|
||||
const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false)
|
||||
const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
|
||||
const sidebarHasContent = shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location'))
|
||||
// A signed-in recipient can comment, which lives in the sidebar too
|
||||
const viewer = res.req.recipient
|
||||
const comments = viewer
|
||||
? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) }
|
||||
: undefined
|
||||
const sidebarHasContent = !!comments ||
|
||||
(shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location')))
|
||||
|
||||
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset, index): Promise<GalleryItem> => {
|
||||
let videoData: string | undefined
|
||||
@@ -152,14 +159,17 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
groupByDate,
|
||||
metaBase,
|
||||
uploadLink: uploadLink(share),
|
||||
uploadHealthcheck: uploadHealthcheck()
|
||||
uploadHealthcheck: uploadHealthcheck(),
|
||||
comments,
|
||||
accountLink: viewer ? '/me' : undefined
|
||||
}
|
||||
|
||||
// HTML gallery page cache time. A password-protected gallery keeps the
|
||||
// no-store that handleShareRequest set.
|
||||
// The page is per-viewer (comment counts, account link) and behind a
|
||||
// session, so it must never sit in a shared cache, and the browser should
|
||||
// recheck it so new photos and comments show up. A password-protected
|
||||
// gallery keeps the no-store that handleShareRequest set.
|
||||
if (!share.password) {
|
||||
const cacheTime = Math.max(0, getNumericConfigOption('ipp.gallery.cacheTime', 300))
|
||||
res.header('Cache-Control', 'public, max-age=' + cacheTime)
|
||||
res.header('Cache-Control', 'private, no-cache')
|
||||
}
|
||||
res.send(renderPage(h(Gallery, props)))
|
||||
}
|
||||
|
||||
+7
-302
@@ -1,46 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import 'dotenv/config'
|
||||
import express from 'express'
|
||||
import { resolve } from 'path'
|
||||
import {
|
||||
addNoStoreHeaders,
|
||||
addResponseHeaders,
|
||||
Asset,
|
||||
AssetType,
|
||||
asyncHandler,
|
||||
CORE_PUBLIC_DIR,
|
||||
decodeCookie,
|
||||
enforceMinimumImmichVersion,
|
||||
errorHandler,
|
||||
getConfigOption,
|
||||
getKeyTypeFromShare,
|
||||
healthcheck,
|
||||
isId,
|
||||
isKey,
|
||||
KeyType,
|
||||
loadConfig,
|
||||
renderPage,
|
||||
respondToInvalidRequest,
|
||||
sessionMiddleware,
|
||||
setInvalidRequestHandler,
|
||||
SharedLink,
|
||||
slugLinksDisabled,
|
||||
unlockHandler
|
||||
} from '@ipp/core'
|
||||
import { fetchAssetDetail, getShareByKey, handleShareRequest } from './immich'
|
||||
import { buildAssetMetadata } from './gallery/metadata'
|
||||
import { removedMetadataSwitches } from './gallery/exif'
|
||||
import { assetBuffer } from './stream/asset'
|
||||
import { downloadAssets } from './stream/download'
|
||||
import dayjs from 'dayjs'
|
||||
import { Request } from 'express-serve-static-core'
|
||||
import { ImageSize } from './types'
|
||||
import { canDownload, findMotionPhotoStill, uploadHealthcheck } from './share'
|
||||
import { enforceMinimumImmichVersion, loadConfig, log, setInvalidRequestHandler } from '@ipp/core'
|
||||
import { removedMetadataSwitches } from './gallery/exif'
|
||||
import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler'
|
||||
import { ASSET_VERSION } from './version'
|
||||
import { h } from 'preact'
|
||||
import { Home } from './view/home'
|
||||
import { createApp } from './server'
|
||||
import { startNotificationScheduler } from './magic/digest'
|
||||
|
||||
/*
|
||||
Must run before any code that calls getConfigOption. The bundled
|
||||
@@ -64,271 +31,7 @@ if (removedSwitches.length) {
|
||||
*/
|
||||
setInvalidRequestHandler(ippInvalidRequestHandler)
|
||||
|
||||
const app = express()
|
||||
app.use(sessionMiddleware({ name: 'session' }))
|
||||
// For parsing the password unlock form and POSTed JSON payloads
|
||||
app.use(express.json())
|
||||
// For parsing the selective-download form POST (form-encoded body)
|
||||
app.use(express.urlencoded({ extended: false, limit: '1mb' }))
|
||||
|
||||
/** Serve IPP's own `public` folder, then core's, at `path`. */
|
||||
function serveStatic (path: string, options: Parameters<typeof express.static>[1] = {}) {
|
||||
for (const dir of ['public', CORE_PUBLIC_DIR]) {
|
||||
app.use(path, express.static(dir, { ...options, setHeaders: addResponseHeaders }))
|
||||
}
|
||||
}
|
||||
|
||||
// Cache-busted, immutable static assets under a per-release version segment.
|
||||
const inProduction = process.env.NODE_ENV === 'production'
|
||||
serveStatic('/share/static/' + ASSET_VERSION, { immutable: inProduction, maxAge: inProduction ? '365d' : 0 })
|
||||
serveStatic('/share/static')
|
||||
// The same assets on /, to allow for /robots.txt and /favicon.ico
|
||||
serveStatic('/')
|
||||
app.disable('x-powered-by')
|
||||
|
||||
/*
|
||||
Shared route guards. Several routes need the same "resolve a share, reject
|
||||
invalid / password-protected ones, optionally find the requested asset"
|
||||
preamble. These return a discriminated result so each route keeps control of
|
||||
its own response (e.g. the photo route redirects on password where the meta
|
||||
and download routes return 401), while the validation order and the
|
||||
`valid`/`link`/`passwordRequired` checks live in one place.
|
||||
*/
|
||||
type ShareResolution =
|
||||
| { ok: true, link: SharedLink }
|
||||
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
|
||||
|
||||
type SharedAssetResolution =
|
||||
| { ok: true, link: SharedLink, asset: Asset }
|
||||
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
|
||||
|
||||
async function resolveShare (req: Request, keyType: KeyType): Promise<ShareResolution> {
|
||||
if (slugLinksDisabled(keyType)) {
|
||||
return { ok: false, status: 404, reason: 'Slug links are disabled in config.json' }
|
||||
}
|
||||
if (!isKey(req.params.key)) {
|
||||
return { ok: false, status: 404, reason: 'Invalid key for ' + req.path }
|
||||
}
|
||||
// The password is provided from the encrypted session cookie (if set) by
|
||||
// decodeCookie. Validating the share here prevents direct URL access from
|
||||
// bypassing password protection.
|
||||
const share = await getShareByKey(req.params.key, req.password, keyType)
|
||||
if (!share?.valid || !share.link) {
|
||||
return { ok: false, status: 404, reason: 'Invalid share link' }
|
||||
}
|
||||
if (share.passwordRequired) {
|
||||
return { ok: false, status: 401, reason: 'Password required', passwordRequired: true }
|
||||
}
|
||||
return { ok: true, link: share.link }
|
||||
}
|
||||
|
||||
async function resolveSharedAsset (req: Request, keyType: KeyType, allowMotion = false): Promise<SharedAssetResolution> {
|
||||
if (!isId(req.params.id)) {
|
||||
return { ok: false, status: 404, reason: 'Invalid ID for ' + req.path }
|
||||
}
|
||||
const resolved = await resolveShare(req, keyType)
|
||||
if (!resolved.ok) return resolved
|
||||
// Confirm the asset belongs to this share (defence in depth - Immich also
|
||||
// enforces this via the share key).
|
||||
const asset = resolved.link.assets.find(a => a.id === req.params.id)
|
||||
if (asset) return { ok: true, link: resolved.link, asset }
|
||||
// A motion photo's clip is a hidden asset outside the share's asset list.
|
||||
// Serve it on the video route only, and only if a shared still points at it.
|
||||
if (allowMotion) {
|
||||
const parent = findMotionPhotoStill(resolved.link, req.params.id)
|
||||
if (parent) {
|
||||
return {
|
||||
ok: true,
|
||||
link: resolved.link,
|
||||
// Streams inline, so the still's filename / mime must not carry over.
|
||||
asset: { ...parent, id: req.params.id, type: AssetType.video, originalFileName: undefined, originalMimeType: undefined }
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ok: false, status: 404, reason: 'Asset not found in share' }
|
||||
}
|
||||
|
||||
/*
|
||||
[ROUTE] Healthcheck, on /share/healthcheck and the legacy /healthcheck
|
||||
*/
|
||||
app.get(/^(|\/share)\/healthcheck$/, asyncHandler(healthcheck))
|
||||
|
||||
/*
|
||||
[ROUTE] The upload service's healthcheck path, when the service is assumed
|
||||
to be at a path on this hostname. The gallery page probes it before showing
|
||||
the "Add photos" button. With the upload service routed in front of IPP the
|
||||
probe never gets here; without it, this answers "nothing here" as a 204
|
||||
rather than a 404, so the probe is neither a console error in the browser
|
||||
nor a hit on the 404 policy.
|
||||
*/
|
||||
const uploadProbe = uploadHealthcheck()
|
||||
if (uploadProbe) {
|
||||
app.get(uploadProbe, (_req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
res.status(204).end()
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
[ROUTE] The main URL a visitor opens from a shared link
|
||||
*/
|
||||
app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, asyncHandler(async (req, res) => {
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
|
||||
if (slugLinksDisabled(keyType)) {
|
||||
respondToInvalidRequest(res, 404, 'Slug links are disabled in config.json')
|
||||
} else {
|
||||
await handleShareRequest({
|
||||
req,
|
||||
key: req.params.key,
|
||||
keyType,
|
||||
mode: req.params.mode,
|
||||
password: req.password
|
||||
}, res)
|
||||
}
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Password unlock from the password page
|
||||
*/
|
||||
app.post('/share/unlock', unlockHandler)
|
||||
|
||||
/*
|
||||
[ROUTE] Selective download - POST a list of asset IDs, get a zip of just those.
|
||||
The list arrives as a single "assets" form field containing a JSON array.
|
||||
Validates each ID against share.assets so the request can't pull anything
|
||||
outside the share.
|
||||
*/
|
||||
app.post('/:shareType(share|s)/:key/download', decodeCookie, asyncHandler(async (req, res) => {
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
let requestedIds: unknown
|
||||
try {
|
||||
requestedIds = JSON.parse(String(req.body?.assets ?? '[]'))
|
||||
} catch (e) {
|
||||
respondToInvalidRequest(res, 400, 'Malformed assets list')
|
||||
return
|
||||
}
|
||||
if (!Array.isArray(requestedIds) || requestedIds.length === 0) {
|
||||
respondToInvalidRequest(res, 400, 'No assets selected')
|
||||
return
|
||||
}
|
||||
|
||||
const resolved = await resolveShare(req, keyType)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
if (!canDownload(resolved.link)) {
|
||||
respondToInvalidRequest(res, 403, 'Downloads disabled for this share')
|
||||
return
|
||||
}
|
||||
|
||||
const requested = new Set(requestedIds.map(String))
|
||||
const validAssets = resolved.link.assets.filter(a => requested.has(a.id))
|
||||
if (validAssets.length === 0) {
|
||||
respondToInvalidRequest(res, 400, 'No valid assets in selection')
|
||||
return
|
||||
}
|
||||
|
||||
await downloadAssets(res, resolved.link, validAssets)
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history
|
||||
state issues) and force a clean GET redirect.
|
||||
See https://github.com/alangrainger/immich-public-proxy/pull/205
|
||||
*/
|
||||
app.post('/:shareType(share|s)/:key/:mode(download)?', (req, res) => {
|
||||
res.redirect(303, req.originalUrl)
|
||||
})
|
||||
|
||||
/*
|
||||
[ROUTE] Direct link to a photo or video asset
|
||||
*/
|
||||
app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, asyncHandler(async (req, res) => {
|
||||
addResponseHeaders(res)
|
||||
|
||||
if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid size parameter ' + req.path)
|
||||
return
|
||||
}
|
||||
|
||||
// Always key auth: this route has no slug form
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key, req.params.type === 'video')
|
||||
if (!resolved.ok) {
|
||||
// Password-protected: redirect to the share page so the visitor gets the
|
||||
// unlock prompt, rather than returning an error.
|
||||
if (resolved.passwordRequired) {
|
||||
res.redirect('/share/' + req.params.key)
|
||||
return
|
||||
}
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
if (resolved.link.password) addNoStoreHeaders(res)
|
||||
const asset: Asset = {
|
||||
...resolved.asset,
|
||||
type: req.params.type === 'video' ? AssetType.video : resolved.asset.type
|
||||
}
|
||||
|
||||
const request = {
|
||||
req,
|
||||
key: req.params.key,
|
||||
range: req.headers.range || ''
|
||||
}
|
||||
await assetBuffer(request, res, asset, req.params.size, resolved.link, req.params.type === 'video')
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] On-demand per-asset metadata for lazy album items.
|
||||
|
||||
Album shares enumerate their assets from the timeline API, which yields
|
||||
grid-only data (no exif / filename / description). When such an item opens
|
||||
in the lightbox, the client fetches its detail from here. The id is
|
||||
validated against the share's asset set (defence in depth - Immich also
|
||||
enforces this via the share key) before we fetch `GET /assets/:id`.
|
||||
*/
|
||||
app.get('/:shareType(share|s)/meta/:key/:id', decodeCookie, asyncHandler(async (req, res) => {
|
||||
addResponseHeaders(res)
|
||||
|
||||
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
|
||||
if (resolved.link.password) addNoStoreHeaders(res)
|
||||
|
||||
const detail = await fetchAssetDetail(resolved.asset)
|
||||
if (!detail) {
|
||||
respondToInvalidRequest(res, 404, 'Asset detail unavailable for ' + req.params.id)
|
||||
return
|
||||
}
|
||||
|
||||
res.json(buildAssetMetadata(detail, resolved.link))
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Home page, so the root shows *something*, as requested in
|
||||
https://github.com/alangrainger/immich-public-proxy/discussions/19.
|
||||
Turned off by https://docs.ipp.nz/config/ipp-options#showhomepage
|
||||
*/
|
||||
if (getConfigOption('ipp.showHomePage', true)) {
|
||||
app.get(/^\/(|share)\/*$/, (_req, res) => {
|
||||
addResponseHeaders(res)
|
||||
res.send(renderPage(h(Home, {})))
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
[ROUTE] Send a 404 for all other routes and methods. `all`, so a POST or DELETE to an
|
||||
unknown path gets the same policy instead of Express's own HTML error page.
|
||||
*/
|
||||
app.all('*', (req, res) => {
|
||||
respondToInvalidRequest(res, 404, 'Invalid route ' + req.path)
|
||||
})
|
||||
|
||||
app.use(errorHandler)
|
||||
const app = createApp()
|
||||
|
||||
// Exit non-zero on an uncaught exception, so Docker restarts the container
|
||||
process.on('uncaughtException', (err) => {
|
||||
@@ -353,5 +56,7 @@ process.on('SIGTERM', () => {
|
||||
const port = Number(process.env.IPP_PORT) || 3000
|
||||
const server = app.listen(port, () => {
|
||||
console.log(dayjs().format() + ' Server started on port ' + port)
|
||||
if (!process.env.ADMIN_PASSWORD) log.warn('ADMIN_PASSWORD is not set, so the /admin console is off')
|
||||
enforceMinimumImmichVersion().catch(e => console.error('Immich version check failed:', e))
|
||||
startNotificationScheduler()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
import crypto from 'crypto'
|
||||
import { Express, NextFunction, Request, Response } from 'express-serve-static-core'
|
||||
import {
|
||||
addNoStoreHeaders,
|
||||
Asset,
|
||||
asyncHandler,
|
||||
authHeaders,
|
||||
fetchSharedLink,
|
||||
isId,
|
||||
isKey,
|
||||
KeyType,
|
||||
log,
|
||||
renderPage,
|
||||
title,
|
||||
TtlLruCache
|
||||
} from '@ipp/core'
|
||||
import { h } from 'preact'
|
||||
import { assetFetchUrl } from '../immich'
|
||||
import { getStore, isFrequency, Recipient } from './store'
|
||||
import { inviteMail, mailConfigured, publicBaseUrl, sendMail } from './mailer'
|
||||
import { listShareAssets, runNotificationCycle, scanShare } from './digest'
|
||||
import { nowIso, readCookie, secureCookies } from './session'
|
||||
import { AdminDashboard, AdminLogin, AdminRecipient } from './views'
|
||||
|
||||
const ADMIN_COOKIE = 'imp_admin'
|
||||
const ADMIN_SESSION_MS = 30 * 24 * 60 * 60_000
|
||||
const MAX_LOGIN_FAILURES = 10
|
||||
const loginFailures = new TtlLruCache<number>({ ttlMs: 15 * 60_000, max: 1000 })
|
||||
|
||||
function adminPassword (): string {
|
||||
return process.env.ADMIN_PASSWORD || ''
|
||||
}
|
||||
|
||||
// Derived from the password, so changing ADMIN_PASSWORD signs every admin out
|
||||
function signingKey (): Buffer {
|
||||
return crypto.createHash('sha256').update('immich-magic-proxy admin\0' + adminPassword()).digest()
|
||||
}
|
||||
|
||||
function sign (expires: number): string {
|
||||
return expires + '.' + crypto.createHmac('sha256', signingKey()).update(String(expires)).digest('base64url')
|
||||
}
|
||||
|
||||
function safeEqual (a: string, b: string): boolean {
|
||||
const left = Buffer.from(a)
|
||||
const right = Buffer.from(b)
|
||||
return left.length === right.length && crypto.timingSafeEqual(left, right)
|
||||
}
|
||||
|
||||
function isAdmin (req: Request): boolean {
|
||||
const cookie = readCookie(req, ADMIN_COOKIE)
|
||||
if (!cookie || !adminPassword()) return false
|
||||
const expires = Number(cookie.split('.')[0])
|
||||
return Number.isFinite(expires) && expires > Date.now() && safeEqual(cookie, sign(expires))
|
||||
}
|
||||
|
||||
function requireAdmin (req: Request, res: Response, next: NextFunction) {
|
||||
if (isAdmin(req)) {
|
||||
next()
|
||||
} else if (req.method === 'GET') {
|
||||
res.redirect(303, '/admin')
|
||||
} else {
|
||||
res.status(403).send()
|
||||
}
|
||||
}
|
||||
|
||||
/** Absolute base for links an admin hands out. */
|
||||
function linkBase (req: Request): string {
|
||||
return publicBaseUrl() || (req.protocol + '://' + req.get('host'))
|
||||
}
|
||||
|
||||
function bodyString (req: Request, field: string, max = 300): string {
|
||||
const value = req.body?.[field]
|
||||
return typeof value === 'string' ? value.trim().slice(0, max) : ''
|
||||
}
|
||||
|
||||
function bodyList (req: Request, field: string): string[] {
|
||||
const value = req.body?.[field]
|
||||
return (Array.isArray(value) ? value : value === undefined ? [] : [value]).filter((v): v is string => typeof v === 'string')
|
||||
}
|
||||
|
||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
/** Pull a share key or slug out of a pasted Immich / IPP link, or a bare key. */
|
||||
export function parseShareInput (input: string): { key: string, keyType: KeyType } | undefined {
|
||||
let path = input.trim()
|
||||
if (/^https?:\/\//i.test(path)) {
|
||||
try {
|
||||
path = new URL(path).pathname
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
const slug = path.match(/(?:^|\/)s\/([\w-]+)\/?$/)
|
||||
if (slug) return { key: slug[1], keyType: KeyType.slug }
|
||||
const shared = path.match(/(?:^|\/)share\/(?:(?:photo|video|meta)\/)?([\w-]+)/)
|
||||
if (shared) return { key: shared[1], keyType: KeyType.key }
|
||||
return isKey(path) ? { key: path, keyType: KeyType.key } : undefined
|
||||
}
|
||||
|
||||
type Message = { kind: 'ok' | 'error', text: string }
|
||||
|
||||
function renderDashboard (res: Response, message?: Message) {
|
||||
const store = getStore()
|
||||
const shares = store.listShares()
|
||||
res.send(renderPage(h(AdminDashboard, {
|
||||
shares: shares.map(share => ({ share, recipients: store.countShareRecipients(share.key), assets: store.countKnownAssets(share.key) })),
|
||||
recipients: store.listRecipients().map(recipient => ({
|
||||
recipient,
|
||||
shares: store.listRecipientShares(recipient.id),
|
||||
sessions: store.countSessions(recipient.id)
|
||||
})),
|
||||
comments: store.recentComments(50),
|
||||
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
||||
message
|
||||
})))
|
||||
}
|
||||
|
||||
function renderRecipient (res: Response, recipient: Recipient, extra: { newLink?: string, message?: Message } = {}) {
|
||||
const store = getStore()
|
||||
res.send(renderPage(h(AdminRecipient, {
|
||||
recipient,
|
||||
shares: store.listShares(),
|
||||
granted: store.listRecipientShares(recipient.id).map(share => share.key),
|
||||
sessions: store.countSessions(recipient.id),
|
||||
activeLinks: store.countMagicLinks(recipient.id, nowIso()),
|
||||
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
||||
...extra
|
||||
})))
|
||||
}
|
||||
|
||||
/** Create a non-expiring invitation link, and optionally email it. */
|
||||
async function issueInvite (req: Request, recipient: Recipient, send: boolean): Promise<{ link: string, message?: Message }> {
|
||||
const store = getStore()
|
||||
const token = store.createMagicLink(recipient.id, { purpose: 'invite', expiresAt: null }, nowIso())
|
||||
const link = linkBase(req) + '/m/' + token
|
||||
if (!send) return { link }
|
||||
try {
|
||||
await sendMail(inviteMail({
|
||||
to: recipient.email,
|
||||
name: recipient.name,
|
||||
link,
|
||||
albums: store.listRecipientShares(recipient.id).map(share => share.title)
|
||||
}))
|
||||
return { link, message: { kind: 'ok', text: 'Invitation emailed to ' + recipient.email + '.' } }
|
||||
} catch (e) {
|
||||
log.error('Invitation email failed: ' + (e instanceof Error ? e.message : String(e)))
|
||||
return { link, message: { kind: 'error', text: 'The email could not be sent; copy the link below instead.' } }
|
||||
}
|
||||
}
|
||||
|
||||
function recipientParam (req: Request, res: Response): Recipient | undefined {
|
||||
const recipient = /^\d+$/.test(req.params.id) ? getStore().getRecipient(Number(req.params.id)) : undefined
|
||||
if (!recipient) res.redirect(303, '/admin')
|
||||
return recipient
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin console at /admin. Off unless ADMIN_PASSWORD is set, in which case
|
||||
* /admin falls through to the visitor gate like any other path.
|
||||
*/
|
||||
export function registerAdminRoutes (app: Express) {
|
||||
if (!adminPassword()) return
|
||||
|
||||
app.use('/admin', (_req, res, next) => {
|
||||
addNoStoreHeaders(res)
|
||||
res.set('X-Frame-Options', 'DENY')
|
||||
next()
|
||||
})
|
||||
|
||||
app.get('/admin', (req, res) => {
|
||||
if (isAdmin(req)) renderDashboard(res)
|
||||
else res.send(renderPage(h(AdminLogin, {})))
|
||||
})
|
||||
|
||||
app.post('/admin/login', (req, res) => {
|
||||
const ip = req.ip || ''
|
||||
const failures = loginFailures.get(ip) || 0
|
||||
const password = bodyString(req, 'password', 1000)
|
||||
if (failures >= MAX_LOGIN_FAILURES || !safeEqual(password, adminPassword())) {
|
||||
loginFailures.set(ip, failures + 1)
|
||||
log.warn('Failed admin sign-in from ' + ip)
|
||||
res.status(401).send(renderPage(h(AdminLogin, { failed: true })))
|
||||
return
|
||||
}
|
||||
loginFailures.delete(ip)
|
||||
res.cookie(ADMIN_COOKIE, sign(Date.now() + ADMIN_SESSION_MS), {
|
||||
httpOnly: true, sameSite: 'strict', secure: secureCookies(), path: '/admin', maxAge: ADMIN_SESSION_MS
|
||||
})
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/logout', (_req, res) => {
|
||||
res.clearCookie(ADMIN_COOKIE, { path: '/admin' })
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.use('/admin', requireAdmin)
|
||||
|
||||
app.post('/admin/shares', asyncHandler(async (req, res) => {
|
||||
const parsed = parseShareInput(bodyString(req, 'link', 2000))
|
||||
const password = bodyString(req, 'password', 1000) || undefined
|
||||
if (!parsed) {
|
||||
renderDashboard(res, { kind: 'error', text: 'That doesn\'t look like an Immich share link.' })
|
||||
return
|
||||
}
|
||||
const result = await fetchSharedLink(parsed.key, parsed.keyType, password)
|
||||
if (result.passwordRequired) {
|
||||
renderDashboard(res, { kind: 'error', text: password ? 'Immich rejected that password.' : 'That share has a password: enter it too.' })
|
||||
return
|
||||
}
|
||||
if (!result.valid || !result.link) {
|
||||
renderDashboard(res, { kind: 'error', text: 'Immich didn\'t accept that link. Check it hasn\'t expired.' })
|
||||
return
|
||||
}
|
||||
const store = getStore()
|
||||
const share = store.upsertShare({
|
||||
key: result.link.key,
|
||||
slug: result.link.slug || null,
|
||||
title: title(result.link),
|
||||
password: password ?? null
|
||||
}, nowIso())
|
||||
// Record what's there now, so recipients are only told about later photos
|
||||
await scanShare(store, share, listShareAssets, nowIso()).catch(() => false)
|
||||
renderDashboard(res, { kind: 'ok', text: 'Added "' + share.title + '".' })
|
||||
}))
|
||||
|
||||
app.post('/admin/shares/:key/delete', (req, res) => {
|
||||
getStore().deleteShare(req.params.key)
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/recipients', asyncHandler(async (req, res) => {
|
||||
const store = getStore()
|
||||
const name = bodyString(req, 'name', 100)
|
||||
const email = bodyString(req, 'email', 254)
|
||||
const frequency = bodyString(req, 'frequency')
|
||||
if (!name || !EMAIL_PATTERN.test(email) || !isFrequency(frequency)) {
|
||||
renderDashboard(res, { kind: 'error', text: 'Enter a name and a valid email address.' })
|
||||
return
|
||||
}
|
||||
if (store.getRecipientByEmail(email)) {
|
||||
renderDashboard(res, { kind: 'error', text: email + ' is already a recipient.' })
|
||||
return
|
||||
}
|
||||
const recipient = store.createRecipient({ name, email, frequency }, nowIso())
|
||||
store.setRecipientShares(recipient.id, bodyList(req, 'shares'), nowIso())
|
||||
const invite = await issueInvite(req, recipient, bodyString(req, 'sendInvite') === '1' && mailConfigured())
|
||||
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
|
||||
}))
|
||||
|
||||
app.get('/admin/recipients/:id', (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (recipient) renderRecipient(res, recipient)
|
||||
})
|
||||
|
||||
app.post('/admin/recipients/:id', (req, res) => {
|
||||
const store = getStore()
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
const name = bodyString(req, 'name', 100)
|
||||
const email = bodyString(req, 'email', 254)
|
||||
const frequency = bodyString(req, 'frequency')
|
||||
const existing = store.getRecipientByEmail(email)
|
||||
if (!name || !EMAIL_PATTERN.test(email) || !isFrequency(frequency) || (existing && existing.id !== recipient.id)) {
|
||||
renderRecipient(res, recipient, { message: { kind: 'error', text: 'Check the name and email (each email can only belong to one recipient).' } })
|
||||
return
|
||||
}
|
||||
store.updateRecipient(recipient.id, { name, email, disabled: bodyString(req, 'disabled') === '1' })
|
||||
store.setFrequency(recipient.id, frequency, nowIso())
|
||||
store.setRecipientShares(recipient.id, bodyList(req, 'shares'), nowIso())
|
||||
renderRecipient(res, store.getRecipient(recipient.id)!, { message: { kind: 'ok', text: 'Saved.' } })
|
||||
})
|
||||
|
||||
app.post('/admin/recipients/:id/link', asyncHandler(async (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
const invite = await issueInvite(req, recipient, bodyString(req, 'send') === '1')
|
||||
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
|
||||
}))
|
||||
|
||||
app.post('/admin/recipients/:id/revoke', (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
getStore().revokeAccess(recipient.id)
|
||||
renderRecipient(res, recipient, { message: { kind: 'ok', text: 'Signed out everywhere; every link they had no longer works.' } })
|
||||
})
|
||||
|
||||
app.post('/admin/recipients/:id/delete', (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
getStore().deleteRecipient(recipient.id)
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/comments/:id/delete', (req, res) => {
|
||||
if (/^\d+$/.test(req.params.id)) getStore().deleteComment(Number(req.params.id))
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/notify', asyncHandler(async (_req, res) => {
|
||||
await runNotificationCycle()
|
||||
renderDashboard(res, { kind: 'ok', text: 'Checked every album for new photos and sent any notification emails that were due.' })
|
||||
}))
|
||||
|
||||
// Thumbnail for the comment moderation list
|
||||
app.get('/admin/thumb/:key/:id', asyncHandler(async (req, res) => {
|
||||
const share = getStore().getShare(req.params.key)
|
||||
if (!share || !isId(req.params.id)) {
|
||||
res.status(404).send()
|
||||
return
|
||||
}
|
||||
const asset = { id: req.params.id, key: share.key, keyType: KeyType.key } as Asset
|
||||
const upstream = await fetch(assetFetchUrl(asset, '/thumbnail', 'thumbnail'), {
|
||||
headers: await authHeaders(KeyType.key, share.key, share.password ?? undefined)
|
||||
})
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
res.status(404).send()
|
||||
return
|
||||
}
|
||||
res.set('Content-Type', upstream.headers.get('Content-Type') || 'image/jpeg')
|
||||
res.set('Cache-Control', 'private, max-age=3600')
|
||||
res.send(Buffer.from(await upstream.arrayBuffer()))
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { KeyType, log } from '@ipp/core'
|
||||
import { getShareByKey } from '../immich'
|
||||
import { Frequency, getStore, Recipient, ShareRecord, Store } from './store'
|
||||
import { digestMail, DigestSection, mailConfigured, MailSender, publicBaseUrl, sendMail } from './mailer'
|
||||
|
||||
/** Asset ids currently in a share, or null when Immich couldn't be read. */
|
||||
export type AssetLister = (share: ShareRecord) => Promise<string[] | null>
|
||||
|
||||
const DIGEST_LINK_DAYS = 30
|
||||
|
||||
export const listShareAssets: AssetLister = async (share) => {
|
||||
const result = await getShareByKey(share.key, share.password ?? undefined, KeyType.key)
|
||||
if (!result.valid || !result.link) return null
|
||||
return result.link.assets.map(asset => asset.id)
|
||||
}
|
||||
|
||||
/** Hour of day (server local time, set with TZ) that digests go out. */
|
||||
export function digestHour (): number {
|
||||
const hour = Number(process.env.DIGEST_HOUR ?? 8)
|
||||
return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : 8
|
||||
}
|
||||
|
||||
/**
|
||||
* When a recipient's next digest is due: the next daily / weekly / monthly
|
||||
* boundary after their window opened, at the digest hour. Anchoring to a
|
||||
* calendar day keeps the send time from drifting with the scan interval.
|
||||
*/
|
||||
export function nextDigestDue (frequency: Frequency, windowStart: string | null, hour = digestHour()): Date | undefined {
|
||||
if (frequency === 'off' || !windowStart) return undefined
|
||||
const day = dayjs(windowStart).startOf('day')
|
||||
const next = frequency === 'daily'
|
||||
? day.add(1, 'day')
|
||||
: frequency === 'weekly'
|
||||
? day.add(7, 'day')
|
||||
: day.add(1, 'month')
|
||||
return next.hour(hour).toDate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Record each share's assets. The first scan of a share is its baseline:
|
||||
* those assets are dated to when the share was added, so nobody is told
|
||||
* about photos that were there before they were invited.
|
||||
*/
|
||||
export async function scanShares (store: Store, listAssets: AssetLister, now: string): Promise<Map<string, Set<string>>> {
|
||||
const current = new Map<string, Set<string>>()
|
||||
for (const share of store.listShares()) {
|
||||
const ids = await scanShare(store, share, listAssets, now)
|
||||
if (ids) current.set(share.key, ids)
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
/** Scan one share. Returns its current asset ids, or null if Immich couldn't be read. */
|
||||
export async function scanShare (store: Store, share: ShareRecord, listAssets: AssetLister, now: string): Promise<Set<string> | null> {
|
||||
let ids: string[] | null = null
|
||||
try {
|
||||
ids = await listAssets(share)
|
||||
} catch (e) {
|
||||
log.warn('Could not list assets of share ' + share.key + ': ' + (e instanceof Error ? e.message : String(e)))
|
||||
}
|
||||
if (!ids) {
|
||||
log.warn('Skipping notification scan for share "' + share.title + '": Immich did not return it')
|
||||
return null
|
||||
}
|
||||
const known = store.knownAssetIds(share.key)
|
||||
store.addAssets(share.key, ids.filter(id => !known.has(id)), share.lastScannedAt ? now : share.createdAt)
|
||||
store.setShareScanned(share.key, now)
|
||||
return new Set(ids)
|
||||
}
|
||||
|
||||
export interface DigestDeps {
|
||||
store: Store
|
||||
send: MailSender
|
||||
baseUrl: string
|
||||
now: Date
|
||||
hour?: number
|
||||
}
|
||||
|
||||
/** Send every digest that is due. Returns how many emails went out. */
|
||||
export async function sendDueDigests (deps: DigestDeps, current: Map<string, Set<string>>): Promise<number> {
|
||||
const { store, now } = deps
|
||||
const nowIso = now.toISOString()
|
||||
let sent = 0
|
||||
for (const recipient of store.listRecipients()) {
|
||||
if (recipient.disabled) continue
|
||||
const due = nextDigestDue(recipient.frequency, recipient.lastDigestAt, deps.hour)
|
||||
if (!due || now < due) continue
|
||||
try {
|
||||
if (await sendDigest(deps, recipient, current)) sent++
|
||||
store.setDigestAt(recipient.id, nowIso)
|
||||
} catch (e) {
|
||||
// The window stays open, so the next run retries with the same photos
|
||||
log.error('Digest to ' + recipient.email + ' failed: ' + (e instanceof Error ? e.message : String(e)))
|
||||
}
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
async function sendDigest (deps: DigestDeps, recipient: Recipient, current: Map<string, Set<string>>): Promise<boolean> {
|
||||
const { store, now } = deps
|
||||
const nowIso = now.toISOString()
|
||||
const pending: Array<{ share: ShareRecord, count: number }> = []
|
||||
for (const share of store.listRecipientShares(recipient.id)) {
|
||||
const present = current.get(share.key)
|
||||
// Nothing from before they had the album, and only photos still in it
|
||||
// when this run could check
|
||||
const after = share.grantedAt > recipient.lastDigestAt! ? share.grantedAt : recipient.lastDigestAt!
|
||||
const ids = store.assetsSeenBetween(share.key, after, nowIso)
|
||||
.filter(id => !present || present.has(id))
|
||||
if (ids.length) pending.push({ share, count: ids.length })
|
||||
}
|
||||
if (!pending.length) return false
|
||||
|
||||
// One sign-in link per email, so the links work on a device with no session
|
||||
const token = store.createMagicLink(recipient.id, {
|
||||
purpose: 'digest',
|
||||
expiresAt: dayjs(now).add(DIGEST_LINK_DAYS, 'day').toISOString()
|
||||
}, nowIso)
|
||||
const link = (path: string) => deps.baseUrl + '/m/' + token + '?next=' + encodeURIComponent(path)
|
||||
const sections: DigestSection[] = pending.map(({ share, count }) => ({
|
||||
title: share.title || 'Shared album',
|
||||
count,
|
||||
link: link('/share/' + share.key)
|
||||
}))
|
||||
await deps.send(digestMail({ to: recipient.email, name: recipient.name, sections, settingsLink: link('/me') }))
|
||||
return true
|
||||
}
|
||||
|
||||
let running = false
|
||||
let warnedNoMail = false
|
||||
|
||||
/** One scan-and-notify pass over every share and recipient. */
|
||||
export async function runNotificationCycle (now = new Date()) {
|
||||
if (running) return
|
||||
running = true
|
||||
try {
|
||||
const store = getStore()
|
||||
store.pruneExpiredLinks(now.toISOString())
|
||||
const current = await scanShares(store, listShareAssets, now.toISOString())
|
||||
const baseUrl = publicBaseUrl()
|
||||
if (!mailConfigured() || !baseUrl) {
|
||||
if (!warnedNoMail) {
|
||||
warnedNoMail = true
|
||||
log.warn('Photo notification emails are off: set SMTP_URL (or SMTP_HOST) and PUBLIC_BASE_URL to send them')
|
||||
}
|
||||
return
|
||||
}
|
||||
const sent = await sendDueDigests({ store, send: sendMail, baseUrl, now }, current)
|
||||
if (sent) log('Sent ' + sent + ' photo notification email' + (sent === 1 ? '' : 's'))
|
||||
} finally {
|
||||
running = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Scan for new photos every NOTIFY_INTERVAL_MINUTES (default 60), starting a minute after boot. */
|
||||
export function startNotificationScheduler () {
|
||||
const minutes = Math.max(1, Number(process.env.NOTIFY_INTERVAL_MINUTES) || 60)
|
||||
const tick = () => { runNotificationCycle().catch(e => log.error('Notification run failed: ' + e)) }
|
||||
setTimeout(tick, 60_000).unref()
|
||||
setInterval(tick, minutes * 60_000).unref()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import nodemailer, { Transporter } from 'nodemailer'
|
||||
import { log } from '@ipp/core'
|
||||
|
||||
export interface Mail {
|
||||
to: string
|
||||
subject: string
|
||||
text: string
|
||||
html: string
|
||||
}
|
||||
|
||||
export type MailSender = (mail: Mail) => Promise<void>
|
||||
|
||||
/** True when SMTP_URL or SMTP_HOST is set. */
|
||||
export function mailConfigured (): boolean {
|
||||
return !!(process.env.SMTP_URL || process.env.SMTP_HOST)
|
||||
}
|
||||
|
||||
let transport: Transporter | undefined
|
||||
|
||||
function createTransport (): Transporter {
|
||||
if (process.env.SMTP_URL) return nodemailer.createTransport(process.env.SMTP_URL)
|
||||
const port = Number(process.env.SMTP_PORT) || 587
|
||||
return nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port,
|
||||
secure: process.env.SMTP_SECURE ? process.env.SMTP_SECURE === 'true' : port === 465,
|
||||
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS || '' } : undefined
|
||||
})
|
||||
}
|
||||
|
||||
const smtpSender: MailSender = async (mail) => {
|
||||
if (!mailConfigured()) throw new Error('Email is not configured: set SMTP_URL or SMTP_HOST')
|
||||
transport ??= createTransport()
|
||||
await transport.sendMail({
|
||||
from: process.env.MAIL_FROM || process.env.SMTP_USER,
|
||||
to: mail.to,
|
||||
subject: mail.subject,
|
||||
text: mail.text,
|
||||
html: mail.html
|
||||
})
|
||||
log('Sent email "' + mail.subject + '" to ' + mail.to)
|
||||
}
|
||||
|
||||
let sender: MailSender = smtpSender
|
||||
|
||||
export function sendMail (mail: Mail): Promise<void> {
|
||||
return sender(mail)
|
||||
}
|
||||
|
||||
/** Replace how mail is sent, for tests. Pass undefined to restore SMTP. */
|
||||
export function setMailSender (next: MailSender | undefined) {
|
||||
sender = next ?? smtpSender
|
||||
}
|
||||
|
||||
export function siteName (): string {
|
||||
return process.env.SITE_NAME || 'Shared photos'
|
||||
}
|
||||
|
||||
/** The public origin for links in emails, from PUBLIC_BASE_URL. */
|
||||
export function publicBaseUrl (): string | undefined {
|
||||
const base = (process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '')
|
||||
return /^https?:\/\//i.test(base) ? base : undefined
|
||||
}
|
||||
|
||||
function escapeHtml (value: string): string {
|
||||
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
}
|
||||
|
||||
function htmlDocument (body: string): string {
|
||||
return '<!DOCTYPE html><html><body style="font-family:-apple-system,Segoe UI,Roboto,sans-serif;line-height:1.5;color:#222;max-width:560px;margin:0 auto;padding:16px">' +
|
||||
body + '</body></html>'
|
||||
}
|
||||
|
||||
const button = (url: string, label: string) =>
|
||||
`<p><a href="${escapeHtml(url)}" style="display:inline-block;background:#4250af;color:#fff;padding:10px 18px;border-radius:6px;text-decoration:none">${escapeHtml(label)}</a></p>`
|
||||
|
||||
export function inviteMail (input: { to: string, name: string, link: string, albums: string[] }): Mail {
|
||||
const site = siteName()
|
||||
const albumList = input.albums.length ? input.albums : ['your albums']
|
||||
return {
|
||||
to: input.to,
|
||||
subject: `${site}: you've been invited to view photos`,
|
||||
text: `Hi ${input.name},\n\nYou've been given access to ${albumList.join(', ')}.\n\n` +
|
||||
`Open your personal link:\n${input.link}\n\n` +
|
||||
'After opening it once, you can bookmark the page; this browser stays signed in. ' +
|
||||
'Please don\'t forward this email: anyone with the link can see the photos.\n',
|
||||
html: htmlDocument(
|
||||
`<p>Hi ${escapeHtml(input.name)},</p>` +
|
||||
`<p>You've been given access to <strong>${albumList.map(escapeHtml).join(', ')}</strong>.</p>` +
|
||||
button(input.link, 'View photos') +
|
||||
'<p style="color:#666;font-size:14px">After opening it once, you can bookmark the page; this browser stays signed in. ' +
|
||||
'Please don\'t forward this email: anyone with the link can see the photos.</p>'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function signInMail (input: { to: string, name: string, link: string }): Mail {
|
||||
const site = siteName()
|
||||
return {
|
||||
to: input.to,
|
||||
subject: `${site}: your sign-in link`,
|
||||
text: `Hi ${input.name},\n\nHere is your sign-in link:\n${input.link}\n\nIt works for 7 days. If you didn't ask for it, you can ignore this email.\n`,
|
||||
html: htmlDocument(
|
||||
`<p>Hi ${escapeHtml(input.name)},</p>` +
|
||||
button(input.link, 'Sign in') +
|
||||
'<p style="color:#666;font-size:14px">This link works for 7 days. If you didn\'t ask for it, you can ignore this email.</p>'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export interface DigestSection {
|
||||
title: string
|
||||
count: number
|
||||
link: string
|
||||
}
|
||||
|
||||
export function digestMail (input: { to: string, name: string, sections: DigestSection[], settingsLink: string }): Mail {
|
||||
const total = input.sections.reduce((sum, s) => sum + s.count, 0)
|
||||
const plural = (n: number) => n === 1 ? '1 new photo' : n + ' new photos'
|
||||
return {
|
||||
to: input.to,
|
||||
subject: `${siteName()}: ${plural(total)}`,
|
||||
text: `Hi ${input.name},\n\n` +
|
||||
input.sections.map(s => `${plural(s.count)} in ${s.title}:\n${s.link}`).join('\n\n') +
|
||||
`\n\nChange how often you get these emails: ${input.settingsLink}\n`,
|
||||
html: htmlDocument(
|
||||
`<p>Hi ${escapeHtml(input.name)},</p>` +
|
||||
input.sections.map(s =>
|
||||
`<p><strong>${escapeHtml(plural(s.count))}</strong> in ${escapeHtml(s.title)}</p>` + button(s.link, 'View ' + s.title)
|
||||
).join('') +
|
||||
`<p style="color:#666;font-size:14px"><a href="${escapeHtml(input.settingsLink)}">Change how often you get these emails</a></p>`
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { Express, Request, Response } from 'express-serve-static-core'
|
||||
import dayjs from 'dayjs'
|
||||
import { addNoStoreHeaders, asyncHandler, decodeCookie, KeyType, log, renderPage, respondToInvalidRequest, TtlLruCache } from '@ipp/core'
|
||||
import { h } from 'preact'
|
||||
import { resolveSharedAsset } from '../resolve'
|
||||
import { CommentRecord, getStore, isFrequency, Recipient } from './store'
|
||||
import { endSession, nowIso, requireShareAccess, startSession } from './session'
|
||||
import { isTokenShaped, safeNextPath } from './tokens'
|
||||
import { mailConfigured, publicBaseUrl, sendMail, signInMail } from './mailer'
|
||||
import { AccessDenied, LinkRequested, RecipientHome } from './views'
|
||||
import type { CommentView } from '../shared/types'
|
||||
|
||||
const SIGN_IN_LINK_DAYS = 7
|
||||
const LINK_REQUEST_INTERVAL_MS = 5 * 60_000
|
||||
const MAX_COMMENT_LENGTH = 2000
|
||||
const COMMENTS_PER_WINDOW = 30
|
||||
const linkRequestsByIp = new TtlLruCache<number>({ ttlMs: 60 * 60_000, max: 5000 })
|
||||
const commentsByRecipient = new TtlLruCache<number>({ ttlMs: 10 * 60_000, max: 5000 })
|
||||
|
||||
/** Routes anyone can reach: following a magic link, and asking for a new one. */
|
||||
export function registerSignInRoutes (app: Express) {
|
||||
app.get('/m/:token', (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
// Keep the token out of any Referer sent by the page we redirect to
|
||||
res.set('Referrer-Policy', 'no-referrer')
|
||||
const store = getStore()
|
||||
const recipient = isTokenShaped(req.params.token) ? store.useMagicLink(req.params.token, nowIso()) : undefined
|
||||
if (!recipient) {
|
||||
log('Invalid or expired magic link')
|
||||
res.status(401).send(renderPage(h(AccessDenied, { signedIn: !!req.recipient, invalidLink: true })))
|
||||
return
|
||||
}
|
||||
// Reuse this browser's session when it already belongs to the recipient
|
||||
if (req.recipient?.id !== recipient.id) {
|
||||
if (req.recipient) endSession(req, res)
|
||||
startSession(res, recipient)
|
||||
}
|
||||
const shares = store.listRecipientShares(recipient.id)
|
||||
const next = safeNextPath(req.query.next) ?? (shares.length === 1 ? '/share/' + shares[0].key : '/me')
|
||||
res.redirect(303, next)
|
||||
})
|
||||
|
||||
app.post('/access', (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
const email = typeof req.body?.email === 'string' ? req.body.email.trim().slice(0, 254) : ''
|
||||
const ip = req.ip || ''
|
||||
const requests = (linkRequestsByIp.get(ip) || 0) + 1
|
||||
linkRequestsByIp.set(ip, requests)
|
||||
// The same answer whether or not the address is known, and sent before
|
||||
// any email goes out, so neither content nor timing reveals who's invited
|
||||
res.send(renderPage(h(LinkRequested, {})))
|
||||
if (requests > 10 || !email) return
|
||||
emailSignInLink(email, req).catch(() => {})
|
||||
})
|
||||
}
|
||||
|
||||
async function emailSignInLink (email: string, req: Request) {
|
||||
const store = getStore()
|
||||
const recipient = store.getRecipientByEmail(email)
|
||||
if (!recipient || recipient.disabled || !mailConfigured()) return
|
||||
const now = new Date()
|
||||
if (!store.allowLinkRequest(recipient.email, now.toISOString(), new Date(now.getTime() - LINK_REQUEST_INTERVAL_MS).toISOString())) return
|
||||
const token = store.createMagicLink(recipient.id, {
|
||||
purpose: 'sign-in',
|
||||
expiresAt: dayjs(now).add(SIGN_IN_LINK_DAYS, 'day').toISOString()
|
||||
}, now.toISOString())
|
||||
const base = publicBaseUrl() || (req.protocol + '://' + req.get('host'))
|
||||
try {
|
||||
await sendMail(signInMail({ to: recipient.email, name: recipient.name, link: base + '/m/' + token }))
|
||||
} catch (e) {
|
||||
log.error('Sign-in email to ' + recipient.email + ' failed: ' + (e instanceof Error ? e.message : String(e)))
|
||||
}
|
||||
}
|
||||
|
||||
function commentView (comment: CommentRecord, viewer: Recipient): CommentView {
|
||||
return {
|
||||
id: comment.id,
|
||||
author: comment.authorName,
|
||||
body: comment.body,
|
||||
createdAt: comment.createdAt,
|
||||
mine: comment.recipientId === viewer.id
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes behind the recipient gate. */
|
||||
export function registerRecipientRoutes (app: Express) {
|
||||
const renderHome = (req: Request, res: Response, saved = false) => {
|
||||
addNoStoreHeaders(res)
|
||||
const recipient = getStore().getRecipient(req.recipient!.id)!
|
||||
res.send(renderPage(h(RecipientHome, {
|
||||
recipient,
|
||||
shares: getStore().listRecipientShares(recipient.id),
|
||||
saved,
|
||||
emailEnabled: mailConfigured() && !!publicBaseUrl()
|
||||
})))
|
||||
}
|
||||
|
||||
app.get('/me', (req, res) => renderHome(req, res))
|
||||
|
||||
app.post('/me/notifications', (req, res) => {
|
||||
const frequency = req.body?.frequency
|
||||
if (isFrequency(frequency)) getStore().setFrequency(req.recipient!.id, frequency, nowIso())
|
||||
renderHome(req, res, true)
|
||||
})
|
||||
|
||||
app.post('/logout', (req, res) => {
|
||||
endSession(req, res)
|
||||
res.redirect(303, '/')
|
||||
})
|
||||
|
||||
// The bare root and /share land on the recipient's albums
|
||||
app.get(/^\/(|share)\/*$/, (_req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
res.redirect(303, '/me')
|
||||
})
|
||||
|
||||
// ----- comments ------------------------------------------------------------
|
||||
|
||||
const commentsPath = '/share/comments/:key/:id'
|
||||
|
||||
app.get(commentsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
addNoStoreHeaders(res)
|
||||
res.json(getStore().listComments(resolved.link.key, resolved.asset.id).map(c => commentView(c, req.recipient!)))
|
||||
}))
|
||||
|
||||
app.post(commentsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
// JSON only: a cross-site HTML form can't send it
|
||||
if (!req.is('application/json')) {
|
||||
res.status(415).json({ error: 'Expected JSON' })
|
||||
return
|
||||
}
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body.trim() : ''
|
||||
if (!body || body.length > MAX_COMMENT_LENGTH) {
|
||||
res.status(400).json({ error: 'A comment must be 1 to ' + MAX_COMMENT_LENGTH + ' characters.' })
|
||||
return
|
||||
}
|
||||
const recipient = req.recipient!
|
||||
const recent = (commentsByRecipient.get(String(recipient.id)) || 0) + 1
|
||||
if (recent > COMMENTS_PER_WINDOW) {
|
||||
res.status(429).json({ error: 'You\'re commenting too quickly. Try again in a few minutes.' })
|
||||
return
|
||||
}
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
commentsByRecipient.set(String(recipient.id), recent)
|
||||
const comment = getStore().addComment({ shareKey: resolved.link.key, assetId: resolved.asset.id, recipient, body }, nowIso())
|
||||
res.status(201).json(commentView(comment, recipient))
|
||||
}))
|
||||
|
||||
app.delete(commentsPath + '/:commentId', requireShareAccess, (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
const store = getStore()
|
||||
const comment = /^\d+$/.test(req.params.commentId) ? store.getComment(Number(req.params.commentId)) : undefined
|
||||
if (!comment || comment.shareKey !== req.grantedShare!.key || comment.assetId !== req.params.id || comment.recipientId !== req.recipient!.id) {
|
||||
res.status(404).send()
|
||||
return
|
||||
}
|
||||
store.deleteComment(comment.id)
|
||||
res.status(204).send()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { CookieOptions, NextFunction, Request, Response } from 'express-serve-static-core'
|
||||
import { addNoStoreHeaders, renderPage, respondToInvalidRequest } from '@ipp/core'
|
||||
import { h } from 'preact'
|
||||
import { getStore, Recipient, ShareRecord } from './store'
|
||||
import { AccessDenied } from './views'
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
recipient?: Recipient
|
||||
sessionToken?: string
|
||||
grantedShare?: ShareRecord
|
||||
}
|
||||
}
|
||||
|
||||
export const SESSION_COOKIE = 'imp_session'
|
||||
// Browsers cap cookie lifetimes at 400 days. The cookie is re-issued daily
|
||||
// while in use, so a bookmarked gallery keeps working indefinitely.
|
||||
const SESSION_MAX_AGE_MS = 400 * 24 * 60 * 60_000
|
||||
const SESSION_REFRESH_MS = 24 * 60 * 60_000
|
||||
|
||||
export const nowIso = () => new Date().toISOString()
|
||||
|
||||
export function readCookie (req: Request, name: string): string | undefined {
|
||||
for (const part of (req.headers.cookie || '').split(';')) {
|
||||
const index = part.indexOf('=')
|
||||
if (index > 0 && part.slice(0, index).trim() === name) {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(index + 1).trim())
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Whether cookies should be `Secure`: true when the public URL is https. */
|
||||
export function secureCookies (): boolean {
|
||||
return (process.env.PUBLIC_BASE_URL || '').toLowerCase().startsWith('https://')
|
||||
}
|
||||
|
||||
function sessionCookieOptions (): CookieOptions {
|
||||
return { httpOnly: true, sameSite: 'lax', secure: secureCookies(), path: '/', maxAge: SESSION_MAX_AGE_MS }
|
||||
}
|
||||
|
||||
/** Sign a recipient in on this browser with a long-lived cookie. */
|
||||
export function startSession (res: Response, recipient: Recipient) {
|
||||
const token = getStore().createSession(recipient.id, nowIso())
|
||||
res.cookie(SESSION_COOKIE, token, sessionCookieOptions())
|
||||
}
|
||||
|
||||
export function endSession (req: Request, res: Response) {
|
||||
if (req.sessionToken) getStore().deleteSession(req.sessionToken)
|
||||
res.clearCookie(SESSION_COOKIE, { ...sessionCookieOptions(), maxAge: undefined })
|
||||
}
|
||||
|
||||
/** Attach `req.recipient` from the session cookie, if it is valid. Never blocks. */
|
||||
export function loadRecipient (req: Request, res: Response, next: NextFunction) {
|
||||
const token = readCookie(req, SESSION_COOKIE)
|
||||
if (token) {
|
||||
const store = getStore()
|
||||
const session = store.getSession(token)
|
||||
if (session && !session.recipient.disabled) {
|
||||
req.recipient = session.recipient
|
||||
req.sessionToken = token
|
||||
if (Date.now() - Date.parse(session.lastSeenAt) > SESSION_REFRESH_MS) {
|
||||
store.touchSession(token, nowIso())
|
||||
res.cookie(SESSION_COOKIE, token, sessionCookieOptions())
|
||||
}
|
||||
}
|
||||
}
|
||||
next()
|
||||
}
|
||||
|
||||
function wantsPage (req: Request): boolean {
|
||||
return req.method === 'GET' && (req.headers.accept || '').includes('text/html')
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a request without revealing anything about what was asked for. A
|
||||
* browser navigation gets a page explaining how to get back in; anything else
|
||||
* (images, API calls) goes through IPP's invalid-request policy.
|
||||
*/
|
||||
export function deny (req: Request, res: Response, reason: string) {
|
||||
if (wantsPage(req)) {
|
||||
addNoStoreHeaders(res)
|
||||
res.status(req.recipient ? 404 : 401)
|
||||
res.send(renderPage(h(AccessDenied, { signedIn: !!req.recipient })))
|
||||
return
|
||||
}
|
||||
respondToInvalidRequest(res, 404, reason)
|
||||
}
|
||||
|
||||
/** Gate for everything except static files, healthchecks, sign-in and admin. */
|
||||
export function requireRecipient (req: Request, res: Response, next: NextFunction) {
|
||||
if (req.recipient) {
|
||||
next()
|
||||
} else {
|
||||
deny(req, res, 'No magic-link session for ' + req.path)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate for a share-scoped route: the signed-in recipient must have been given
|
||||
* this share (by key or slug) in `req.params.key`. Supplies the share's stored
|
||||
* password so recipients are never asked for it.
|
||||
*/
|
||||
export function requireShareAccess (req: Request, res: Response, next: NextFunction) {
|
||||
const share = req.recipient && typeof req.params.key === 'string'
|
||||
? getStore().grantedShare(req.recipient.id, req.params.key)
|
||||
: undefined
|
||||
if (!share) {
|
||||
deny(req, res, 'Recipient has no access to ' + req.params.key)
|
||||
return
|
||||
}
|
||||
req.grantedShare = share
|
||||
if (!req.password && share.password) req.password = share.password
|
||||
// Content behind a session must never land in a shared cache
|
||||
res.set('Vary', 'Cookie')
|
||||
next()
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
import { DatabaseSync, SQLInputValue } from 'node:sqlite'
|
||||
import { mkdirSync } from 'fs'
|
||||
import { dirname, resolve } from 'path'
|
||||
import { hashToken, newToken } from './tokens'
|
||||
|
||||
export type Frequency = 'off' | 'daily' | 'weekly' | 'monthly'
|
||||
export const FREQUENCIES: Frequency[] = ['off', 'daily', 'weekly', 'monthly']
|
||||
|
||||
export function isFrequency (value: unknown): value is Frequency {
|
||||
return typeof value === 'string' && (FREQUENCIES as string[]).includes(value)
|
||||
}
|
||||
|
||||
export interface Recipient {
|
||||
id: number
|
||||
name: string
|
||||
email: string
|
||||
frequency: Frequency
|
||||
/** Start of the window the next digest covers. */
|
||||
lastDigestAt: string | null
|
||||
createdAt: string
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
export interface ShareRecord {
|
||||
key: string
|
||||
slug: string | null
|
||||
title: string
|
||||
/** Lets recipients and the background scanner open a password-protected share. */
|
||||
password: string | null
|
||||
lastScannedAt: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface CommentRecord {
|
||||
id: number
|
||||
shareKey: string
|
||||
assetId: string
|
||||
recipientId: number | null
|
||||
authorName: string
|
||||
body: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS recipients (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
frequency TEXT NOT NULL DEFAULT 'off' CHECK (frequency IN ('off', 'daily', 'weekly', 'monthly')),
|
||||
last_digest_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
disabled INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS shares (
|
||||
key TEXT PRIMARY KEY,
|
||||
slug TEXT,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
password TEXT,
|
||||
last_scanned_at TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS recipient_shares (
|
||||
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (recipient_id, share_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS magic_links (
|
||||
id INTEGER PRIMARY KEY,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||
purpose TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT,
|
||||
last_used_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||
created_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS share_assets (
|
||||
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||
asset_id TEXT NOT NULL,
|
||||
first_seen_at TEXT NOT NULL,
|
||||
PRIMARY KEY (share_key, asset_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id INTEGER PRIMARY KEY,
|
||||
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||
asset_id TEXT NOT NULL,
|
||||
recipient_id INTEGER REFERENCES recipients(id) ON DELETE SET NULL,
|
||||
author_name TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS comments_by_asset ON comments (share_key, asset_id);
|
||||
CREATE TABLE IF NOT EXISTS link_requests (
|
||||
email TEXT PRIMARY KEY COLLATE NOCASE,
|
||||
last_at TEXT NOT NULL
|
||||
);
|
||||
`
|
||||
|
||||
const RECIPIENT_COLUMNS = `id, name, email, frequency, last_digest_at AS lastDigestAt,
|
||||
created_at AS createdAt, disabled`
|
||||
const SHARE_COLUMNS = 'key, slug, title, password, last_scanned_at AS lastScannedAt, created_at AS createdAt'
|
||||
const JOINED_SHARE_COLUMNS = 's.key, s.slug, s.title, s.password, s.last_scanned_at AS lastScannedAt, s.created_at AS createdAt'
|
||||
const COMMENT_COLUMNS = `id, share_key AS shareKey, asset_id AS assetId, recipient_id AS recipientId,
|
||||
author_name AS authorName, body, created_at AS createdAt`
|
||||
|
||||
type Row = Record<string, SQLInputValue>
|
||||
|
||||
function toRecipient (row: Row | undefined): Recipient | undefined {
|
||||
if (!row) return undefined
|
||||
return { ...(row as unknown as Recipient), disabled: !!row.disabled }
|
||||
}
|
||||
|
||||
/**
|
||||
* All persistent state for magic-link access, notifications and comments.
|
||||
* Timestamps are ISO-8601 UTC strings, so they compare correctly as text.
|
||||
*/
|
||||
export class Store {
|
||||
readonly db: DatabaseSync
|
||||
|
||||
constructor (path: string) {
|
||||
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
|
||||
this.db = new DatabaseSync(path)
|
||||
this.db.exec('PRAGMA foreign_keys = ON')
|
||||
this.db.exec('PRAGMA busy_timeout = 5000')
|
||||
if (path !== ':memory:') this.db.exec('PRAGMA journal_mode = WAL')
|
||||
this.db.exec(SCHEMA)
|
||||
}
|
||||
|
||||
close () {
|
||||
this.db.close()
|
||||
}
|
||||
|
||||
private transaction (fn: () => void) {
|
||||
this.db.exec('BEGIN')
|
||||
try {
|
||||
fn()
|
||||
this.db.exec('COMMIT')
|
||||
} catch (e) {
|
||||
this.db.exec('ROLLBACK')
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// ----- recipients ----------------------------------------------------------
|
||||
|
||||
createRecipient (input: { name: string, email: string, frequency: Frequency }, now: string): Recipient {
|
||||
const result = this.db.prepare(`INSERT INTO recipients (name, email, frequency, last_digest_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)`).run(input.name, input.email, input.frequency, input.frequency === 'off' ? null : now, now)
|
||||
return this.getRecipient(Number(result.lastInsertRowid))!
|
||||
}
|
||||
|
||||
getRecipient (id: number): Recipient | undefined {
|
||||
return toRecipient(this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients WHERE id = ?`).get(id))
|
||||
}
|
||||
|
||||
getRecipientByEmail (email: string): Recipient | undefined {
|
||||
return toRecipient(this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients WHERE email = ?`).get(email))
|
||||
}
|
||||
|
||||
listRecipients (): Recipient[] {
|
||||
return this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients ORDER BY name COLLATE NOCASE`).all()
|
||||
.map(row => toRecipient(row)!)
|
||||
}
|
||||
|
||||
updateRecipient (id: number, input: { name: string, email: string, disabled: boolean }) {
|
||||
this.db.prepare('UPDATE recipients SET name = ?, email = ?, disabled = ? WHERE id = ?')
|
||||
.run(input.name, input.email, input.disabled ? 1 : 0, id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Change how often a recipient hears about new photos. Turning digests on
|
||||
* starts the window now, so they are never told about photos that were
|
||||
* already there.
|
||||
*/
|
||||
setFrequency (id: number, frequency: Frequency, now: string) {
|
||||
const current = this.getRecipient(id)
|
||||
if (!current) return
|
||||
const startWindow = frequency !== 'off' && (current.frequency === 'off' || !current.lastDigestAt)
|
||||
this.db.prepare('UPDATE recipients SET frequency = ?, last_digest_at = ? WHERE id = ?')
|
||||
.run(frequency, startWindow ? now : current.lastDigestAt, id)
|
||||
}
|
||||
|
||||
setDigestAt (id: number, at: string) {
|
||||
this.db.prepare('UPDATE recipients SET last_digest_at = ? WHERE id = ?').run(at, id)
|
||||
}
|
||||
|
||||
deleteRecipient (id: number) {
|
||||
this.db.prepare('DELETE FROM recipients WHERE id = ?').run(id)
|
||||
}
|
||||
|
||||
// ----- shares --------------------------------------------------------------
|
||||
|
||||
upsertShare (input: { key: string, slug: string | null, title: string, password: string | null }, now: string): ShareRecord {
|
||||
this.db.prepare(`INSERT INTO shares (key, slug, title, password, created_at) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (key) DO UPDATE SET slug = excluded.slug, title = excluded.title, password = excluded.password`)
|
||||
.run(input.key, input.slug, input.title, input.password, now)
|
||||
return this.getShare(input.key)!
|
||||
}
|
||||
|
||||
getShare (key: string): ShareRecord | undefined {
|
||||
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares WHERE key = ?`).get(key) as ShareRecord | undefined
|
||||
}
|
||||
|
||||
listShares (): ShareRecord[] {
|
||||
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares ORDER BY title COLLATE NOCASE`).all() as unknown as ShareRecord[]
|
||||
}
|
||||
|
||||
deleteShare (key: string) {
|
||||
this.db.prepare('DELETE FROM shares WHERE key = ?').run(key)
|
||||
}
|
||||
|
||||
setShareScanned (key: string, at: string) {
|
||||
this.db.prepare('UPDATE shares SET last_scanned_at = ? WHERE key = ?').run(at, key)
|
||||
}
|
||||
|
||||
// ----- access grants -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Set exactly which shares a recipient has. Shares they already had keep
|
||||
* their grant time, which bounds what their notifications count.
|
||||
*/
|
||||
setRecipientShares (recipientId: number, keys: string[], now: string) {
|
||||
const wanted = [...new Set(keys)]
|
||||
this.transaction(() => {
|
||||
const placeholders = wanted.map(() => '?').join(', ')
|
||||
this.db.prepare('DELETE FROM recipient_shares WHERE recipient_id = ?' +
|
||||
(wanted.length ? ` AND share_key NOT IN (${placeholders})` : '')).run(recipientId, ...wanted)
|
||||
const insert = this.db.prepare(`INSERT OR IGNORE INTO recipient_shares (recipient_id, share_key, granted_at)
|
||||
SELECT ?, key, ? FROM shares WHERE key = ?`)
|
||||
for (const key of wanted) insert.run(recipientId, now, key)
|
||||
})
|
||||
}
|
||||
|
||||
listRecipientShares (recipientId: number): Array<ShareRecord & { grantedAt: string }> {
|
||||
return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS}, rs.granted_at AS grantedAt FROM shares s
|
||||
JOIN recipient_shares rs ON rs.share_key = s.key WHERE rs.recipient_id = ? ORDER BY s.title COLLATE NOCASE`)
|
||||
.all(recipientId) as unknown as Array<ShareRecord & { grantedAt: string }>
|
||||
}
|
||||
|
||||
countShareRecipients (key: string): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM recipient_shares WHERE share_key = ?').get(key)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* The share a recipient may open by its key or slug, or undefined. This is
|
||||
* the one access check every share-scoped route goes through.
|
||||
*/
|
||||
grantedShare (recipientId: number, keyOrSlug: string): ShareRecord | undefined {
|
||||
return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS} FROM shares s
|
||||
JOIN recipient_shares rs ON rs.share_key = s.key
|
||||
WHERE rs.recipient_id = ? AND (s.key = ? OR s.slug = ?)`)
|
||||
.get(recipientId, keyOrSlug, keyOrSlug) as ShareRecord | undefined
|
||||
}
|
||||
|
||||
// ----- magic links ---------------------------------------------------------
|
||||
|
||||
/** Returns the plaintext token; only its hash is stored. */
|
||||
createMagicLink (recipientId: number, options: { purpose: string, expiresAt: string | null }, now: string): string {
|
||||
const token = newToken()
|
||||
this.db.prepare(`INSERT INTO magic_links (token_hash, recipient_id, purpose, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)`).run(hashToken(token), recipientId, options.purpose, now, options.expiresAt)
|
||||
return token
|
||||
}
|
||||
|
||||
/** The recipient a magic link signs in, if the link is live and the recipient enabled. */
|
||||
useMagicLink (token: string, now: string): Recipient | undefined {
|
||||
const hash = hashToken(token)
|
||||
const link = this.db.prepare('SELECT recipient_id AS recipientId, expires_at AS expiresAt FROM magic_links WHERE token_hash = ?')
|
||||
.get(hash) as { recipientId: number, expiresAt: string | null } | undefined
|
||||
if (!link || (link.expiresAt && link.expiresAt <= now)) return undefined
|
||||
const recipient = this.getRecipient(link.recipientId)
|
||||
if (!recipient || recipient.disabled) return undefined
|
||||
this.db.prepare('UPDATE magic_links SET last_used_at = ? WHERE token_hash = ?').run(now, hash)
|
||||
return recipient
|
||||
}
|
||||
|
||||
countMagicLinks (recipientId: number, now: string): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM magic_links WHERE recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)')
|
||||
.get(recipientId, now)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
pruneExpiredLinks (now: string) {
|
||||
this.db.prepare('DELETE FROM magic_links WHERE expires_at IS NOT NULL AND expires_at <= ?').run(now)
|
||||
}
|
||||
|
||||
/** Allow at most one self-service link request per address per interval. */
|
||||
allowLinkRequest (email: string, now: string, notBefore: string): boolean {
|
||||
const row = this.db.prepare('SELECT last_at AS lastAt FROM link_requests WHERE email = ?').get(email) as { lastAt: string } | undefined
|
||||
if (row && row.lastAt > notBefore) return false
|
||||
this.db.prepare(`INSERT INTO link_requests (email, last_at) VALUES (?, ?)
|
||||
ON CONFLICT (email) DO UPDATE SET last_at = excluded.last_at`).run(email, now)
|
||||
return true
|
||||
}
|
||||
|
||||
// ----- sessions ------------------------------------------------------------
|
||||
|
||||
createSession (recipientId: number, now: string): string {
|
||||
const token = newToken()
|
||||
this.db.prepare('INSERT INTO sessions (token_hash, recipient_id, created_at, last_seen_at) VALUES (?, ?, ?, ?)')
|
||||
.run(hashToken(token), recipientId, now, now)
|
||||
return token
|
||||
}
|
||||
|
||||
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 = ?')
|
||||
.get(hashToken(token)) as { recipientId: number, lastSeenAt: string } | undefined
|
||||
if (!row) return undefined
|
||||
const recipient = this.getRecipient(row.recipientId)
|
||||
return recipient ? { recipient, lastSeenAt: row.lastSeenAt } : undefined
|
||||
}
|
||||
|
||||
touchSession (token: string, now: string) {
|
||||
this.db.prepare('UPDATE sessions SET last_seen_at = ? WHERE token_hash = ?').run(now, hashToken(token))
|
||||
}
|
||||
|
||||
deleteSession (token: string) {
|
||||
this.db.prepare('DELETE FROM sessions WHERE token_hash = ?').run(hashToken(token))
|
||||
}
|
||||
|
||||
countSessions (recipientId: number): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM sessions WHERE recipient_id = ?').get(recipientId)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
/** Sign the recipient out everywhere and invalidate every link they were sent. */
|
||||
revokeAccess (recipientId: number) {
|
||||
this.transaction(() => {
|
||||
this.db.prepare('DELETE FROM sessions WHERE recipient_id = ?').run(recipientId)
|
||||
this.db.prepare('DELETE FROM magic_links WHERE recipient_id = ?').run(recipientId)
|
||||
})
|
||||
}
|
||||
|
||||
// ----- asset tracking (for notifications) ----------------------------------
|
||||
|
||||
knownAssetIds (shareKey: string): Set<string> {
|
||||
const rows = this.db.prepare('SELECT asset_id AS id FROM share_assets WHERE share_key = ?').all(shareKey)
|
||||
return new Set(rows.map(row => String(row.id)))
|
||||
}
|
||||
|
||||
addAssets (shareKey: string, ids: string[], firstSeenAt: string) {
|
||||
if (!ids.length) return
|
||||
this.transaction(() => {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO share_assets (share_key, asset_id, first_seen_at) VALUES (?, ?, ?)')
|
||||
for (const id of ids) insert.run(shareKey, id, firstSeenAt)
|
||||
})
|
||||
}
|
||||
|
||||
/** Assets first seen in (after, upTo]. */
|
||||
assetsSeenBetween (shareKey: string, after: string, upTo: string): string[] {
|
||||
return this.db.prepare('SELECT asset_id AS id FROM share_assets WHERE share_key = ? AND first_seen_at > ? AND first_seen_at <= ?')
|
||||
.all(shareKey, after, upTo).map(row => String(row.id))
|
||||
}
|
||||
|
||||
countKnownAssets (shareKey: string): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM share_assets WHERE share_key = ?').get(shareKey)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
// ----- comments ------------------------------------------------------------
|
||||
|
||||
addComment (input: { shareKey: string, assetId: string, recipient: Recipient, body: string }, now: string): CommentRecord {
|
||||
const result = this.db.prepare(`INSERT INTO comments (share_key, asset_id, recipient_id, author_name, body, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`).run(input.shareKey, input.assetId, input.recipient.id, input.recipient.name, input.body, now)
|
||||
return this.getComment(Number(result.lastInsertRowid))!
|
||||
}
|
||||
|
||||
getComment (id: number): CommentRecord | undefined {
|
||||
return this.db.prepare(`SELECT ${COMMENT_COLUMNS} FROM comments WHERE id = ?`).get(id) as CommentRecord | undefined
|
||||
}
|
||||
|
||||
listComments (shareKey: string, assetId: string): CommentRecord[] {
|
||||
return this.db.prepare(`SELECT ${COMMENT_COLUMNS} FROM comments WHERE share_key = ? AND asset_id = ? ORDER BY id`)
|
||||
.all(shareKey, assetId) as unknown as CommentRecord[]
|
||||
}
|
||||
|
||||
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)
|
||||
return Object.fromEntries(rows.map(row => [String(row.id), Number(row.n)]))
|
||||
}
|
||||
|
||||
recentComments (limit: number): Array<CommentRecord & { shareTitle: string }> {
|
||||
return this.db.prepare(`SELECT c.id, c.share_key AS shareKey, c.asset_id AS assetId, c.recipient_id AS recipientId,
|
||||
c.author_name AS authorName, c.body, c.created_at AS createdAt, s.title AS shareTitle
|
||||
FROM comments c JOIN shares s ON s.key = c.share_key ORDER BY c.id DESC LIMIT ?`)
|
||||
.all(limit) as unknown as Array<CommentRecord & { shareTitle: string }>
|
||||
}
|
||||
|
||||
deleteComment (id: number) {
|
||||
this.db.prepare('DELETE FROM comments WHERE id = ?').run(id)
|
||||
}
|
||||
}
|
||||
|
||||
let store: Store | undefined
|
||||
|
||||
/** `<DATA_DIR>/magic.db`, where DATA_DIR defaults to `./data`. */
|
||||
export function defaultDbPath (): string {
|
||||
return resolve(process.env.DATA_DIR || 'data', 'magic.db')
|
||||
}
|
||||
|
||||
export function getStore (): Store {
|
||||
if (!store) store = new Store(defaultDbPath())
|
||||
return store
|
||||
}
|
||||
|
||||
/** Swap the store, for tests. */
|
||||
export function setStore (next: Store | undefined) {
|
||||
store = next
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
/** 256 bits of randomness, URL-safe. */
|
||||
export function newToken (): string {
|
||||
return crypto.randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
||||
/** Tokens are stored hashed, so a leaked database does not leak working links or sessions. */
|
||||
export function hashToken (token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex')
|
||||
}
|
||||
|
||||
export function isTokenShaped (value: unknown): value is string {
|
||||
return typeof value === 'string' && /^[\w-]{20,100}$/.test(value)
|
||||
}
|
||||
|
||||
/** A same-site path to send the visitor to after sign-in, or undefined (blocks open redirects). */
|
||||
export function safeNextPath (value: unknown): string | undefined {
|
||||
if (typeof value !== 'string') return undefined
|
||||
if (!/^\/(?![/\\])/.test(value)) return undefined
|
||||
if (/[\r\n]/.test(value)) return undefined
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
import { ComponentChildren } from 'preact'
|
||||
import { CommentRecord, Frequency, FREQUENCIES, Recipient, ShareRecord } from './store'
|
||||
|
||||
const FREQUENCY_LABELS: Record<Frequency, string> = {
|
||||
off: 'Never',
|
||||
daily: 'Daily',
|
||||
weekly: 'Weekly',
|
||||
monthly: 'Monthly'
|
||||
}
|
||||
|
||||
const STYLE = `
|
||||
main.container { max-width: 760px; padding-top: 2rem; padding-bottom: 3rem; }
|
||||
.muted { color: var(--pico-muted-color); }
|
||||
.notice { padding: .75rem 1rem; border-radius: var(--pico-border-radius); background: var(--pico-card-sectioning-background-color); margin-bottom: 1rem; }
|
||||
.notice.error { border-left: 4px solid var(--pico-del-color); }
|
||||
.notice.ok { border-left: 4px solid var(--pico-ins-color); }
|
||||
.link-box { word-break: break-all; font-family: var(--pico-font-family-monospace); font-size: .85rem; }
|
||||
.row-actions { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; }
|
||||
.row-actions form { margin: 0; }
|
||||
.row-actions button { margin: 0; padding: .35rem .75rem; font-size: .85rem; }
|
||||
table td, table th { vertical-align: top; font-size: .9rem; }
|
||||
fieldset.checks label { display: block; }
|
||||
.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; }
|
||||
`
|
||||
|
||||
// Forms with data-confirm ask before submitting
|
||||
const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) {
|
||||
var message = e.target.getAttribute('data-confirm')
|
||||
if (message && !confirm(message)) e.preventDefault()
|
||||
})`
|
||||
|
||||
function Layout ({ title, children }: { title: string, children: ComponentChildren }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<meta name="referrer" content="no-referrer"/>
|
||||
<meta name="robots" content="noindex, nofollow"/>
|
||||
<title>{title}</title>
|
||||
<link rel="icon" href="/share/static/favicon.ico" type="image/x-icon"/>
|
||||
<link type="text/css" rel="stylesheet" href="/share/static/pico.min.css"/>
|
||||
<style dangerouslySetInnerHTML={{ __html: STYLE }}/>
|
||||
</head>
|
||||
<body>
|
||||
<main class="container">{children}</main>
|
||||
<script dangerouslySetInnerHTML={{ __html: CONFIRM_SCRIPT }}/>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
|
||||
function Notice ({ kind, children }: { kind: 'ok' | 'error', children: ComponentChildren }) {
|
||||
return <div class={'notice ' + kind} role={kind === 'error' ? 'alert' : 'status'}>{children}</div>
|
||||
}
|
||||
|
||||
// ----- visitors --------------------------------------------------------------
|
||||
|
||||
/** Shown in place of anything gated. Reveals nothing about what was asked for. */
|
||||
export function AccessDenied ({ signedIn, invalidLink }: { signedIn: boolean, invalidLink?: boolean }) {
|
||||
return (
|
||||
<Layout title="Private photos">
|
||||
<h1>Private photos</h1>
|
||||
{invalidLink && <Notice kind="error">That link is no longer valid.</Notice>}
|
||||
{signedIn
|
||||
? <p>This page isn't available to you. <a href="/me">See the albums you can view</a>.</p>
|
||||
: <>
|
||||
<p>These photos are only visible through a personal invitation link. Open the link from your invitation email to continue.</p>
|
||||
<RequestLinkForm/>
|
||||
</>}
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
function RequestLinkForm () {
|
||||
return (
|
||||
<form method="post" action="/access">
|
||||
<label>
|
||||
Lost your link? Enter the email address you were invited with and we'll send a new one.
|
||||
<input type="email" name="email" required autocomplete="email" placeholder="you@example.com"/>
|
||||
</label>
|
||||
<button type="submit">Email me a link</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
export function LinkRequested () {
|
||||
return (
|
||||
<Layout title="Check your email">
|
||||
<h1>Check your email</h1>
|
||||
<p>If that address has been invited, a sign-in link is on its way. It works for 7 days.</p>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
export interface RecipientHomeProps {
|
||||
recipient: Recipient
|
||||
shares: ShareRecord[]
|
||||
saved?: boolean
|
||||
emailEnabled: boolean
|
||||
}
|
||||
|
||||
export function RecipientHome ({ recipient, shares, saved, emailEnabled }: RecipientHomeProps) {
|
||||
return (
|
||||
<Layout title="Your albums">
|
||||
<hgroup>
|
||||
<h1>Hi {recipient.name}</h1>
|
||||
<p class="muted">Bookmark this page to come back to your albums. This browser stays signed in.</p>
|
||||
</hgroup>
|
||||
<section class="albums">
|
||||
<h2>Albums</h2>
|
||||
{shares.length
|
||||
? shares.map(share => <a key={share.key} href={'/share/' + share.key}>{share.title || 'Shared album'}</a>)
|
||||
: <p class="muted">Nothing has been shared with you yet.</p>}
|
||||
</section>
|
||||
<section>
|
||||
<h2>Email notifications</h2>
|
||||
{saved && <Notice kind="ok">Saved.</Notice>}
|
||||
<form method="post" action="/me/notifications">
|
||||
<fieldset>
|
||||
<legend>Email me about new photos in these albums ({recipient.email}):</legend>
|
||||
{FREQUENCIES.map(frequency => (
|
||||
<label key={frequency}>
|
||||
<input type="radio" name="frequency" value={frequency} checked={recipient.frequency === frequency}/>
|
||||
{frequency === 'off' ? 'Never' : FREQUENCY_LABELS[frequency] + ' summary'}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
{!emailEnabled && <p class="muted"><small>Email isn't set up on this server yet, so nothing will be sent for now.</small></p>}
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
</section>
|
||||
<section>
|
||||
<form method="post" action="/logout">
|
||||
<button type="submit" class="secondary outline">Sign out of this browser</button>
|
||||
</form>
|
||||
</section>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
// ----- admin -----------------------------------------------------------------
|
||||
|
||||
export function AdminLogin ({ failed }: { failed?: boolean }) {
|
||||
return (
|
||||
<Layout title="Admin sign-in">
|
||||
<h1>Admin</h1>
|
||||
{failed && <Notice kind="error">Wrong password, or too many attempts. Try again in a few minutes.</Notice>}
|
||||
<form method="post" action="/admin/login">
|
||||
<input type="password" name="password" placeholder="Admin password" aria-label="Admin password" required autofocus/>
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
export interface AdminShareRow { share: ShareRecord, recipients: number, assets: number }
|
||||
export interface AdminRecipientRow { recipient: Recipient, shares: ShareRecord[], sessions: number }
|
||||
|
||||
export interface AdminDashboardProps {
|
||||
shares: AdminShareRow[]
|
||||
recipients: AdminRecipientRow[]
|
||||
comments: Array<CommentRecord & { shareTitle: string }>
|
||||
emailEnabled: boolean
|
||||
message?: { kind: 'ok' | 'error', text: string }
|
||||
}
|
||||
|
||||
export function AdminDashboard ({ shares, recipients, comments, emailEnabled, message }: AdminDashboardProps) {
|
||||
return (
|
||||
<Layout title="Admin">
|
||||
<nav>
|
||||
<ul><li><strong>Admin</strong></li></ul>
|
||||
<ul>
|
||||
<li>
|
||||
<form method="post" action="/admin/notify" style="margin:0">
|
||||
<button type="submit" class="secondary outline" style="margin:0">Check for new photos now</button>
|
||||
</form>
|
||||
</li>
|
||||
<li>
|
||||
<form method="post" action="/admin/logout" style="margin:0">
|
||||
<button type="submit" class="secondary outline" style="margin:0">Sign out</button>
|
||||
</form>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
{message && <Notice kind={message.kind}>{message.text}</Notice>}
|
||||
{!emailEnabled && <Notice kind="error">Email is not configured (SMTP_URL or SMTP_HOST, plus PUBLIC_BASE_URL), so invitations and notifications can't be sent. You can still copy links by hand.</Notice>}
|
||||
|
||||
<section>
|
||||
<h2>Albums</h2>
|
||||
<p class="muted">Add an Immich shared link here, then give recipients access to it. Only recipients can open it through this proxy.</p>
|
||||
{shares.length > 0 && (
|
||||
<table>
|
||||
<thead><tr><th>Album</th><th>Recipients</th><th>Photos tracked</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{shares.map(({ share, recipients: count, assets }) => (
|
||||
<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>{count}</td>
|
||||
<td>{assets}</td>
|
||||
<td>
|
||||
<form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/delete'}
|
||||
data-confirm='Remove this album? Recipients lose access and its comments are deleted.'>
|
||||
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Remove</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
<details open={!shares.length}>
|
||||
<summary role="button" class="outline">Add an album</summary>
|
||||
<form method="post" action="/admin/shares">
|
||||
<label>
|
||||
Immich share link or key
|
||||
<input name="link" required placeholder="https://immich.example.com/share/AbC123… or /s/my-album"/>
|
||||
</label>
|
||||
<label>
|
||||
Share password <small class="muted">(only if the Immich link has one; stored so recipients aren't asked for it)</small>
|
||||
<input type="password" name="password" autocomplete="off"/>
|
||||
</label>
|
||||
<button type="submit">Add album</button>
|
||||
</form>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Recipients</h2>
|
||||
{recipients.length > 0 && (
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>Albums</th><th>Emails</th><th>Signed-in browsers</th></tr></thead>
|
||||
<tbody>
|
||||
{recipients.map(({ recipient, shares: granted, sessions }) => (
|
||||
<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>{granted.map(s => s.title).join(', ') || <span class="muted">none</span>}</td>
|
||||
<td>{FREQUENCY_LABELS[recipient.frequency]}</td>
|
||||
<td>{sessions}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{shares.length
|
||||
? (
|
||||
<details open={!recipients.length}>
|
||||
<summary role="button" class="outline">Add a recipient</summary>
|
||||
<form method="post" action="/admin/recipients">
|
||||
<div class="grid">
|
||||
<label>Name<input name="name" required/></label>
|
||||
<label>Email<input type="email" name="email" required/></label>
|
||||
</div>
|
||||
<ShareChecks shares={shares.map(row => row.share)} selected={[]}/>
|
||||
<FrequencySelect value="weekly"/>
|
||||
<label><input type="checkbox" name="sendInvite" value="1" checked={emailEnabled} disabled={!emailEnabled}/> Email them their invitation link now</label>
|
||||
<button type="submit">Add recipient</button>
|
||||
</form>
|
||||
</details>
|
||||
)
|
||||
: <p class="muted">Add an album first.</p>}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Recent comments</h2>
|
||||
{comments.length
|
||||
? (
|
||||
<table>
|
||||
<tbody>
|
||||
{comments.map(comment => (
|
||||
<tr key={comment.id}>
|
||||
<td style="width:72px"><img src={'/admin/thumb/' + encodeURIComponent(comment.shareKey) + '/' + comment.assetId} alt="" width={64} height={64} style="object-fit:cover;border-radius:4px" loading="lazy"/></td>
|
||||
<td><strong>{comment.authorName}</strong> on {comment.shareTitle}<br/><small class="muted">{new Date(comment.createdAt).toLocaleString('en-GB')}</small></td>
|
||||
<td style="white-space:pre-wrap">{comment.body}</td>
|
||||
<td>
|
||||
<form method="post" action={'/admin/comments/' + comment.id + '/delete'}>
|
||||
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
: <p class="muted">No comments yet.</p>}
|
||||
</section>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareChecks ({ shares, selected }: { shares: ShareRecord[], selected: string[] }) {
|
||||
return (
|
||||
<fieldset class="checks">
|
||||
<legend>Albums they can see</legend>
|
||||
{shares.map(share => (
|
||||
<label key={share.key}>
|
||||
<input type="checkbox" name="shares" value={share.key} checked={selected.includes(share.key)}/>
|
||||
{share.title || 'Untitled'}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
function FrequencySelect ({ value }: { value: Frequency }) {
|
||||
return (
|
||||
<label>
|
||||
New-photo emails
|
||||
<select name="frequency">
|
||||
{FREQUENCIES.map(frequency => <option key={frequency} value={frequency} selected={value === frequency}>{FREQUENCY_LABELS[frequency]}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export interface AdminRecipientProps {
|
||||
recipient: Recipient
|
||||
shares: ShareRecord[]
|
||||
granted: string[]
|
||||
sessions: number
|
||||
activeLinks: number
|
||||
emailEnabled: boolean
|
||||
/** A link created by this request; shown once, never stored in plain text. */
|
||||
newLink?: string
|
||||
message?: { kind: 'ok' | 'error', text: string }
|
||||
}
|
||||
|
||||
export function AdminRecipient ({ recipient, shares, granted, sessions, activeLinks, emailEnabled, newLink, message }: AdminRecipientProps) {
|
||||
const base = '/admin/recipients/' + recipient.id
|
||||
return (
|
||||
<Layout title={recipient.name + ' · Admin'}>
|
||||
<p><a href="/admin">← Admin</a></p>
|
||||
<h1>{recipient.name}</h1>
|
||||
{message && <Notice kind={message.kind}>{message.text}</Notice>}
|
||||
{newLink && (
|
||||
<article>
|
||||
<header><strong>Personal link for {recipient.name}</strong></header>
|
||||
<p class="link-box">{newLink}</p>
|
||||
<footer><small class="muted">Shown once. Anyone with this link can see their albums. It doesn't expire; revoke access below to cancel it.</small></footer>
|
||||
</article>
|
||||
)}
|
||||
<form method="post" action={base}>
|
||||
<div class="grid">
|
||||
<label>Name<input name="name" required value={recipient.name}/></label>
|
||||
<label>Email<input type="email" name="email" required value={recipient.email}/></label>
|
||||
</div>
|
||||
<ShareChecks shares={shares} selected={granted}/>
|
||||
<FrequencySelect value={recipient.frequency}/>
|
||||
<label><input type="checkbox" name="disabled" value="1" checked={recipient.disabled}/> Disabled (blocks all their links and sessions)</label>
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
|
||||
<h2>Access</h2>
|
||||
<p>{sessions} signed-in browser{sessions === 1 ? '' : 's'} · {activeLinks} working link{activeLinks === 1 ? '' : 's'}</p>
|
||||
<div class="row-actions">
|
||||
<form method="post" action={base + '/link'}>
|
||||
<button type="submit">Create a new link</button>
|
||||
</form>
|
||||
<form method="post" action={base + '/link'}>
|
||||
<input type="hidden" name="send" value="1"/>
|
||||
<button type="submit" disabled={!emailEnabled}>Email them a new link</button>
|
||||
</form>
|
||||
<form method="post" action={base + '/revoke'} data-confirm='Sign them out everywhere and cancel all their links?'>
|
||||
<button type="submit" class="secondary">Revoke all access</button>
|
||||
</form>
|
||||
<form method="post" action={base + '/delete'} data-confirm='Delete this recipient? Their comments stay, unattributed to an account.'>
|
||||
<button type="submit" class="secondary outline">Delete recipient</button>
|
||||
</form>
|
||||
</div>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Asset, AssetType, isId, isKey, KeyType, SharedLink, slugLinksDisabled } from '@ipp/core'
|
||||
import { Request } from 'express-serve-static-core'
|
||||
import { getShareByKey } from './immich'
|
||||
import { findMotionPhotoStill } from './share'
|
||||
|
||||
/*
|
||||
Shared route guards. Several routes need the same "resolve a share, reject
|
||||
invalid / password-protected ones, optionally find the requested asset"
|
||||
preamble. These return a discriminated result so each route keeps control of
|
||||
its own response (e.g. the photo route redirects on password where the meta
|
||||
and download routes return 401), while the validation order and the
|
||||
`valid`/`link`/`passwordRequired` checks live in one place.
|
||||
*/
|
||||
export type ShareResolution =
|
||||
| { ok: true, link: SharedLink }
|
||||
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
|
||||
|
||||
export type SharedAssetResolution =
|
||||
| { ok: true, link: SharedLink, asset: Asset }
|
||||
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
|
||||
|
||||
export async function resolveShare (req: Request, keyType: KeyType): Promise<ShareResolution> {
|
||||
if (slugLinksDisabled(keyType)) {
|
||||
return { ok: false, status: 404, reason: 'Slug links are disabled in config.json' }
|
||||
}
|
||||
if (!isKey(req.params.key)) {
|
||||
return { ok: false, status: 404, reason: 'Invalid key for ' + req.path }
|
||||
}
|
||||
// The password is provided from the encrypted session cookie (if set) by
|
||||
// decodeCookie. Validating the share here prevents direct URL access from
|
||||
// bypassing password protection.
|
||||
const share = await getShareByKey(req.params.key, req.password, keyType)
|
||||
if (!share?.valid || !share.link) {
|
||||
return { ok: false, status: 404, reason: 'Invalid share link' }
|
||||
}
|
||||
if (share.passwordRequired) {
|
||||
return { ok: false, status: 401, reason: 'Password required', passwordRequired: true }
|
||||
}
|
||||
return { ok: true, link: share.link }
|
||||
}
|
||||
|
||||
export async function resolveSharedAsset (req: Request, keyType: KeyType, allowMotion = false): Promise<SharedAssetResolution> {
|
||||
if (!isId(req.params.id)) {
|
||||
return { ok: false, status: 404, reason: 'Invalid ID for ' + req.path }
|
||||
}
|
||||
const resolved = await resolveShare(req, keyType)
|
||||
if (!resolved.ok) return resolved
|
||||
// Confirm the asset belongs to this share (defence in depth - Immich also
|
||||
// enforces this via the share key).
|
||||
const asset = resolved.link.assets.find(a => a.id === req.params.id)
|
||||
if (asset) return { ok: true, link: resolved.link, asset }
|
||||
// A motion photo's clip is a hidden asset outside the share's asset list.
|
||||
// Serve it on the video route only, and only if a shared still points at it.
|
||||
if (allowMotion) {
|
||||
const parent = findMotionPhotoStill(resolved.link, req.params.id)
|
||||
if (parent) {
|
||||
return {
|
||||
ok: true,
|
||||
link: resolved.link,
|
||||
// Streams inline, so the still's filename / mime must not carry over.
|
||||
asset: { ...parent, id: req.params.id, type: AssetType.video, originalFileName: undefined, originalMimeType: undefined }
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ok: false, status: 404, reason: 'Asset not found in share' }
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import express, { Express } from 'express'
|
||||
import {
|
||||
addNoStoreHeaders,
|
||||
addResponseHeaders,
|
||||
Asset,
|
||||
AssetType,
|
||||
asyncHandler,
|
||||
CORE_PUBLIC_DIR,
|
||||
decodeCookie,
|
||||
errorHandler,
|
||||
getKeyTypeFromShare,
|
||||
healthcheck,
|
||||
isKey,
|
||||
KeyType,
|
||||
respondToInvalidRequest,
|
||||
sessionMiddleware,
|
||||
slugLinksDisabled,
|
||||
unlockHandler
|
||||
} from '@ipp/core'
|
||||
import { fetchAssetDetail, handleShareRequest } from './immich'
|
||||
import { buildAssetMetadata } from './gallery/metadata'
|
||||
import { assetBuffer } from './stream/asset'
|
||||
import { downloadAssets } from './stream/download'
|
||||
import { ImageSize } from './types'
|
||||
import { canDownload, uploadHealthcheck } from './share'
|
||||
import { ASSET_VERSION } from './version'
|
||||
import { resolveShare, resolveSharedAsset } from './resolve'
|
||||
import { deny, loadRecipient, requireRecipient, requireShareAccess } from './magic/session'
|
||||
import { registerRecipientRoutes, registerSignInRoutes } from './magic/routes'
|
||||
import { registerAdminRoutes } from './magic/admin'
|
||||
import { getStore } from './magic/store'
|
||||
|
||||
/**
|
||||
* Build the Express app. Call `loadConfig` first: routes read config as they
|
||||
* are registered.
|
||||
*
|
||||
* Every route that shows anything from Immich sits behind two gates: a
|
||||
* magic-link session (`requireRecipient`), and that recipient having been
|
||||
* given the specific share (`requireShareAccess`).
|
||||
*/
|
||||
export function createApp (): Express {
|
||||
const app = express()
|
||||
// Behind a reverse proxy, so req.ip and req.protocol reflect the visitor
|
||||
app.set('trust proxy', process.env.TRUST_PROXY ?? 'loopback, linklocal, uniquelocal')
|
||||
app.use(sessionMiddleware({ name: 'session' }))
|
||||
// For parsing the password unlock form and POSTed JSON payloads
|
||||
app.use(express.json())
|
||||
// For parsing the selective-download form POST (form-encoded body)
|
||||
app.use(express.urlencoded({ extended: false, limit: '1mb' }))
|
||||
|
||||
/** Serve IPP's own `public` folder, then core's, at `path`. */
|
||||
function serveStatic (path: string, options: Parameters<typeof express.static>[1] = {}) {
|
||||
for (const dir of ['public', CORE_PUBLIC_DIR]) {
|
||||
app.use(path, express.static(dir, { ...options, setHeaders: addResponseHeaders }))
|
||||
}
|
||||
}
|
||||
|
||||
// Cache-busted, immutable static assets under a per-release version segment.
|
||||
// These hold only the app's own code and styles, never anything from Immich.
|
||||
const inProduction = process.env.NODE_ENV === 'production'
|
||||
serveStatic('/share/static/' + ASSET_VERSION, { immutable: inProduction, maxAge: inProduction ? '365d' : 0 })
|
||||
serveStatic('/share/static')
|
||||
// The same assets on /, to allow for /robots.txt and /favicon.ico
|
||||
serveStatic('/')
|
||||
app.disable('x-powered-by')
|
||||
|
||||
/*
|
||||
[ROUTE] Healthcheck, on /share/healthcheck and the legacy /healthcheck
|
||||
*/
|
||||
app.get(/^(|\/share)\/healthcheck$/, asyncHandler(healthcheck))
|
||||
|
||||
/*
|
||||
[ROUTE] The upload service's healthcheck path, when the service is assumed
|
||||
to be at a path on this hostname. Answers "nothing here" as a 204.
|
||||
*/
|
||||
const uploadProbe = uploadHealthcheck()
|
||||
if (uploadProbe) {
|
||||
app.get(uploadProbe, (_req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
res.status(204).end()
|
||||
})
|
||||
}
|
||||
|
||||
// Open the store now, so a bad DATA_DIR fails at startup rather than on the first visitor
|
||||
getStore()
|
||||
|
||||
// ----- public: magic-link sign-in and the admin console ---------------------
|
||||
app.use(loadRecipient)
|
||||
registerSignInRoutes(app)
|
||||
registerAdminRoutes(app)
|
||||
|
||||
// ----- everything below needs a magic-link session --------------------------
|
||||
app.use(requireRecipient)
|
||||
registerRecipientRoutes(app)
|
||||
|
||||
/*
|
||||
[ROUTE] The main URL a visitor opens from a shared link
|
||||
*/
|
||||
app.get('/:shareType(share|s)/:key/:mode(download)?', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
|
||||
if (slugLinksDisabled(keyType)) {
|
||||
respondToInvalidRequest(res, 404, 'Slug links are disabled in config.json')
|
||||
} else {
|
||||
await handleShareRequest({
|
||||
req,
|
||||
key: req.params.key,
|
||||
keyType,
|
||||
mode: req.params.mode,
|
||||
password: req.password
|
||||
}, res)
|
||||
}
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Password unlock from the password page. Only reachable for a
|
||||
share without a stored password, and only for a recipient of that share.
|
||||
*/
|
||||
app.post('/share/unlock', (req, res, next) => {
|
||||
const key = req.body?.key
|
||||
if (typeof key !== 'string' || !isKey(key) || !getStore().grantedShare(req.recipient!.id, key)) {
|
||||
deny(req, res, 'Unlock for a share the recipient was not given')
|
||||
return
|
||||
}
|
||||
next()
|
||||
}, unlockHandler)
|
||||
|
||||
/*
|
||||
[ROUTE] Selective download - POST a list of asset IDs, get a zip of just those.
|
||||
The list arrives as a single "assets" form field containing a JSON array.
|
||||
Validates each ID against share.assets so the request can't pull anything
|
||||
outside the share.
|
||||
*/
|
||||
app.post('/:shareType(share|s)/:key/download', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
let requestedIds: unknown
|
||||
try {
|
||||
requestedIds = JSON.parse(String(req.body?.assets ?? '[]'))
|
||||
} catch (e) {
|
||||
respondToInvalidRequest(res, 400, 'Malformed assets list')
|
||||
return
|
||||
}
|
||||
if (!Array.isArray(requestedIds) || requestedIds.length === 0) {
|
||||
respondToInvalidRequest(res, 400, 'No assets selected')
|
||||
return
|
||||
}
|
||||
|
||||
const resolved = await resolveShare(req, keyType)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
if (!canDownload(resolved.link)) {
|
||||
respondToInvalidRequest(res, 403, 'Downloads disabled for this share')
|
||||
return
|
||||
}
|
||||
|
||||
const requested = new Set(requestedIds.map(String))
|
||||
const validAssets = resolved.link.assets.filter(a => requested.has(a.id))
|
||||
if (validAssets.length === 0) {
|
||||
respondToInvalidRequest(res, 400, 'No valid assets in selection')
|
||||
return
|
||||
}
|
||||
|
||||
await downloadAssets(res, resolved.link, validAssets)
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history
|
||||
state issues) and force a clean GET redirect.
|
||||
See https://github.com/alangrainger/immich-public-proxy/pull/205
|
||||
*/
|
||||
app.post('/:shareType(share|s)/:key/:mode(download)?', (req, res) => {
|
||||
res.redirect(303, req.originalUrl)
|
||||
})
|
||||
|
||||
/*
|
||||
[ROUTE] Direct link to a photo or video asset
|
||||
*/
|
||||
app.get('/share/:type(photo|video)/:key/:id/:size?', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
addResponseHeaders(res)
|
||||
|
||||
if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid size parameter ' + req.path)
|
||||
return
|
||||
}
|
||||
|
||||
// Always key auth: this route has no slug form
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key, req.params.type === 'video')
|
||||
if (!resolved.ok) {
|
||||
// Password-protected: redirect to the share page so the visitor gets the
|
||||
// unlock prompt, rather than returning an error.
|
||||
if (resolved.passwordRequired) {
|
||||
res.redirect('/share/' + req.params.key)
|
||||
return
|
||||
}
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
if (resolved.link.password) addNoStoreHeaders(res)
|
||||
const asset: Asset = {
|
||||
...resolved.asset,
|
||||
type: req.params.type === 'video' ? AssetType.video : resolved.asset.type
|
||||
}
|
||||
|
||||
const request = {
|
||||
req,
|
||||
key: req.params.key,
|
||||
range: req.headers.range || ''
|
||||
}
|
||||
await assetBuffer(request, res, asset, req.params.size, resolved.link, req.params.type === 'video')
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] On-demand per-asset metadata for lazy album items.
|
||||
|
||||
Album shares enumerate their assets from the timeline API, which yields
|
||||
grid-only data (no exif / filename / description). When such an item opens
|
||||
in the lightbox, the client fetches its detail from here. The id is
|
||||
validated against the share's asset set (defence in depth - Immich also
|
||||
enforces this via the share key) before we fetch `GET /assets/:id`.
|
||||
*/
|
||||
app.get('/:shareType(share|s)/meta/:key/:id', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
addResponseHeaders(res)
|
||||
|
||||
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
|
||||
if (resolved.link.password) addNoStoreHeaders(res)
|
||||
|
||||
const detail = await fetchAssetDetail(resolved.asset)
|
||||
if (!detail) {
|
||||
respondToInvalidRequest(res, 404, 'Asset detail unavailable for ' + req.params.id)
|
||||
return
|
||||
}
|
||||
|
||||
res.json(buildAssetMetadata(detail, resolved.link))
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Send a 404 for all other routes and methods. `all`, so a POST or DELETE to an
|
||||
unknown path gets the same policy instead of Express's own HTML error page.
|
||||
*/
|
||||
app.all('*', (req, res) => {
|
||||
respondToInvalidRequest(res, 404, 'Invalid route ' + req.path)
|
||||
})
|
||||
|
||||
app.use(errorHandler)
|
||||
return app
|
||||
}
|
||||
@@ -98,6 +98,23 @@ export interface MetadataConfig {
|
||||
locationWebLink: boolean
|
||||
}
|
||||
|
||||
/** Per-photo comments for the signed-in recipient. */
|
||||
export interface CommentsConfig {
|
||||
// `/share/comments/<key>`; append `/<assetId>`
|
||||
base: string
|
||||
// Comment count per asset id, for the toolbar badge
|
||||
counts: Record<string, number>
|
||||
}
|
||||
|
||||
/** One comment as the comments API returns it. */
|
||||
export interface CommentView {
|
||||
id: number
|
||||
author: string
|
||||
body: string
|
||||
createdAt: string
|
||||
mine: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape of the JSON init block embedded in `gallery.tsx` and consumed by
|
||||
* `client/init.ts`. The server writes it via `jsonForInlineScript`; the
|
||||
@@ -110,4 +127,5 @@ export interface InitParams {
|
||||
metadataConfig?: MetadataConfig
|
||||
groupByDate?: GroupByDateMode | false
|
||||
metaBase?: string
|
||||
comments?: CommentsConfig
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core'
|
||||
import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
|
||||
import { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
|
||||
import { ASSET_VERSION } from '../version'
|
||||
|
||||
export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
|
||||
export type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
|
||||
|
||||
export interface GalleryProps {
|
||||
items: GalleryItem[]
|
||||
@@ -26,6 +26,10 @@ 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?: CommentsConfig
|
||||
// The recipient's albums and notification settings
|
||||
accountLink?: string
|
||||
}
|
||||
|
||||
export function Gallery (props: GalleryProps) {
|
||||
@@ -35,7 +39,8 @@ export function Gallery (props: GalleryProps) {
|
||||
lightboxConfig: props.lightboxConfig,
|
||||
metadataConfig: props.metadataConfig,
|
||||
groupByDate: props.groupByDate,
|
||||
metaBase: props.metaBase
|
||||
metaBase: props.metaBase,
|
||||
comments: props.comments
|
||||
})
|
||||
const firstItem = props.items[0]
|
||||
// og:image prefers the album cover (passed via props); for videos, previewUrl
|
||||
@@ -74,8 +79,8 @@ export function Gallery (props: GalleryProps) {
|
||||
<link type="text/css" rel="stylesheet" href={`/share/static/${ASSET_VERSION}/photoswipe-overrides.css`}/>
|
||||
</head>
|
||||
<body>
|
||||
{(showHeaderText || props.showDownloadZip || props.uploadLink) && (
|
||||
<header id="header" hidden={!showHeaderText && !props.showDownloadZip && !!props.uploadHealthcheck}>
|
||||
{(showHeaderText || props.showDownloadZip || props.uploadLink || props.accountLink) && (
|
||||
<header id="header" hidden={!showHeaderText && !props.showDownloadZip && !props.accountLink && !!props.uploadHealthcheck}>
|
||||
{showHeaderText && (
|
||||
<div class="header-text">
|
||||
{props.showTitle && <h1>{props.title || 'Gallery'}</h1>}
|
||||
@@ -104,6 +109,13 @@ export function Gallery (props: GalleryProps) {
|
||||
</svg>
|
||||
</a>
|
||||
)}
|
||||
{props.accountLink && (
|
||||
<a id="account-link" class="header-action" href={props.accountLink} title="Your albums and email settings" aria-label="Your albums and email settings">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path fill="currentColor" d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z"/>
|
||||
</svg>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user