mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 03:26:07 +00:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 711015d5fd | |||
| 6ebd5cf0c7 | |||
| 8ab7547edf | |||
| f599892a4b | |||
| 1436cec35c | |||
| fe90502955 | |||
| 0431741ad7 | |||
| fa99940945 | |||
| 09316025c3 | |||
| 100313cfa9 | |||
| 411ec4af59 | |||
| ec7f5e0585 | |||
| 8e38749bc3 | |||
| 2c17edd74c | |||
| c5e2afc21b | |||
| 502e6916d9 | |||
| 61674cf918 | |||
| ac01925be7 |
+4
-4
@@ -94,8 +94,8 @@ RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/p
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
chown -R node:node /app
|
||||
|
||||
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
|
||||
# it to drop to node.
|
||||
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
|
||||
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
|
||||
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
|
||||
|
||||
ENV XDG_CACHE_HOME=/tmp/kf6-cache
|
||||
@@ -173,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
# carrying quotes does not survive that round-trip (the container then dies with
|
||||
# a shell syntax error before Node starts). A CMD of one bare token does.
|
||||
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
|
||||
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
|
||||
# node. chmod is explicit because a checkout on Windows carries no exec bit.
|
||||
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
|
||||
# chmod is explicit because a checkout on Windows carries no exec bit.
|
||||
RUN chmod 0755 /usr/local/bin/trek-entrypoint
|
||||
|
||||
ENTRYPOINT ["dumb-init", "--"]
|
||||
|
||||
@@ -512,8 +512,8 @@ struct StopList: View {
|
||||
ForEach(Array(window.enumerated()), id: \.offset) { offset, stop in
|
||||
let past = (stop.minutes ?? Int.max) < nowMinutes
|
||||
let isNext = !past && (offset == 0 || (window[offset - 1].minutes ?? Int.max) < nowMinutes)
|
||||
if isNext && offset > 0, let nowLabel { nowLine(nowLabel) }
|
||||
row(stop, past: past, isNext: isNext, last: offset == window.count - 1)
|
||||
if isNext && offset > 0, let nowLabel { nowLine(nowLabel, in: window) }
|
||||
row(stop, in: window, past: past, isNext: isNext, last: offset == window.count - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -528,13 +528,33 @@ struct StopList: View {
|
||||
|
||||
private var ink: Color { onPhoto ? .white : Trek.ink(scheme) }
|
||||
|
||||
private func row(_ stop: WidgetSnapshot.Stop, past: Bool, isNext: Bool, last: Bool) -> some View {
|
||||
/// The time column, as wide as the longest time in the window (and the now
|
||||
/// marker's label): every row lays all of them over each other, hidden, so
|
||||
/// "5:45 AM" fits as well as "09:30" and the dots still stand in one line.
|
||||
private func timeColumn<Label: View>(_ window: [WidgetSnapshot.Stop], @ViewBuilder label: () -> Label) -> some View {
|
||||
ZStack(alignment: .leading) {
|
||||
ForEach(Array(window.enumerated()), id: \.offset) { _, stop in
|
||||
Text(stop.time ?? "–").font(Trek.number(11.5, .heavy)).hidden()
|
||||
}
|
||||
if let nowLabel { nowText(nowLabel).hidden() }
|
||||
label()
|
||||
}
|
||||
.lineLimit(1)
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
.frame(minWidth: 38, alignment: .leading)
|
||||
}
|
||||
|
||||
private func nowText(_ label: String) -> some View {
|
||||
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
|
||||
}
|
||||
|
||||
private func row(_ stop: WidgetSnapshot.Stop, in window: [WidgetSnapshot.Stop], past: Bool, isNext: Bool, last: Bool) -> some View {
|
||||
let color = Color(css: stop.color) ?? (onPhoto ? .white : Trek.info)
|
||||
return HStack(alignment: .top, spacing: 8) {
|
||||
Text(stop.time ?? "–")
|
||||
.font(Trek.number(11.5, isNext ? .heavy : .semibold))
|
||||
.frame(width: 38, alignment: .leading)
|
||||
.padding(.top, 1)
|
||||
timeColumn(window) {
|
||||
Text(stop.time ?? "–").font(Trek.number(11.5, isNext ? .heavy : .semibold))
|
||||
}
|
||||
.padding(.top, 1)
|
||||
VStack(spacing: 0) {
|
||||
ZStack {
|
||||
Circle().fill(color).frame(width: isNext ? 11 : 8, height: isNext ? 11 : 8)
|
||||
@@ -562,10 +582,9 @@ struct StopList: View {
|
||||
.frame(height: 24, alignment: .top)
|
||||
}
|
||||
|
||||
private func nowLine(_ label: String) -> some View {
|
||||
private func nowLine(_ label: String, in window: [WidgetSnapshot.Stop]) -> some View {
|
||||
HStack(spacing: 5) {
|
||||
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
|
||||
.frame(width: 38, alignment: .leading)
|
||||
timeColumn(window) { nowText(label) }
|
||||
Circle().fill(Trek.danger).frame(width: 5, height: 5).frame(width: 15)
|
||||
Rectangle().fill(Trek.danger).frame(height: 1.2)
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@
|
||||
{
|
||||
"feature": "Booking mail import: admin card",
|
||||
"hooks": ["src/components/Admin/mailIngest/useMailIngestAdmin.ts", "src/components/Admin/mailIngest/mailIngestAdminModel.ts"],
|
||||
"desktop": ["src/components/Admin/mailIngest/MailIngestAdminCard.tsx"],
|
||||
"desktop": ["src/components/Admin/mailIngest/MailIngestAddonTile.tsx"],
|
||||
"mobile": ["src/mobile/screens/admin/MMailIngestAdminCard.tsx"]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1542,7 +1542,6 @@
|
||||
"src/pages/journeyDetail/useJourneyDetail.ts",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.test.tsx",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
|
||||
"src/pages/journeyPublic/journeyPublicModel.ts",
|
||||
"src/pages/journeyPublic/useJourneyPublic.ts",
|
||||
"src/pages/journeyStudio/useJourneyStudio.test.tsx",
|
||||
"src/pages/journeyStudio/useJourneyStudio.ts",
|
||||
|
||||
@@ -113,7 +113,6 @@
|
||||
"src/pages/AtlasPage.tsx": 6,
|
||||
"src/pages/FilesPage.tsx": 1,
|
||||
"src/pages/JourneyDetailPage.tsx": 1,
|
||||
"src/pages/JourneyPublicPage.test.tsx": 1,
|
||||
"src/pages/LoginPage.tsx": 1,
|
||||
"src/pages/VacayPage.tsx": 1,
|
||||
"src/pages/admin/useAdmin.ts": 4,
|
||||
|
||||
@@ -146,7 +146,7 @@
|
||||
"mobile/components/MToastHost.tsx": 2,
|
||||
"mobile/components/MUserPickerList.tsx": 1,
|
||||
"mobile/screens/admin/MAdmin.tsx": 8,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 4,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 3,
|
||||
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
|
||||
"mobile/screens/admin/MAdminBackupPanel.tsx": 7,
|
||||
"mobile/screens/admin/MAdminCategoryManager.tsx": 8,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import AddonManager from './AddonManager';
|
||||
|
||||
function buildAddon(overrides = {}) {
|
||||
@@ -691,4 +692,40 @@ describe('AddonManager', () => {
|
||||
expect(roadtrip.querySelector('svg.lucide-car-front')).toBeInTheDocument();
|
||||
expect(tours.querySelector('svg.lucide-puzzle')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-045: live flight status is a row of the trip card, switched there and locked by the environment', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Lists', icon: 'ListChecks', type: 'trip', enabled: true })]));
|
||||
const onToggle = vi.fn();
|
||||
const { unmount } = render(<AddonManager flightLive={{ on: false, locked: false, managed: false, onToggle }} />);
|
||||
const trip = (await screen.findByRole('heading', { name: 'Trip' })).closest('section')!;
|
||||
await userEvent.click(within(trip).getByRole('button', { name: 'Follow booked flights live' }));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
// The count stays the addons': the flight row is an instance option beside them.
|
||||
expect(within(trip).getByText('1/1')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
render(<AddonManager flightLive={{ on: true, locked: true, managed: false, onToggle }} />);
|
||||
expect(await screen.findByRole('button', { name: 'Follow booked flights live' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-046: the booking mail import is a row of the integration card whose setup opens in a dialog', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
vi.spyOn(mailIngestRepo, 'adminSettings').mockResolvedValue({ mail_ingest_enabled: 'true' });
|
||||
vi.spyOn(mailIngestRepo, 'adminStatus').mockRejectedValue(new Error('no status'));
|
||||
render(<AddonManager mailImport />);
|
||||
const integration = (await screen.findByRole('heading', { name: 'Integration' })).closest('section')!;
|
||||
expect(within(integration).getByText('Booking mail import')).toBeInTheDocument();
|
||||
await userEvent.click(await within(integration).findByRole('button', { name: 'Set up mail import' }));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('How mail arrives')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-047: without the mail option the integration card has no mail row and nothing is loaded', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
const load = vi.spyOn(mailIngestRepo, 'adminSettings');
|
||||
render(<AddonManager />);
|
||||
await screen.findByRole('heading', { name: 'Integration' });
|
||||
expect(screen.queryByText('Booking mail import')).not.toBeInTheDocument();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType, ReactNode } from 'react'
|
||||
import type { ComponentType } from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront } from 'lucide-react'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||
@@ -12,6 +12,9 @@ import { SettingsCard, SettingsColumns, StatusPill } from '../Settings/settingsK
|
||||
import { type Addon, type CollabFeatures, COLLAB_SUB_FEATURES, getAddonLabel } from './addons/addonModel'
|
||||
import { useAddonManager } from './addons/useAddonManager'
|
||||
import AiAddonTile from './addons/AiAddonTile'
|
||||
import MailIngestAddonTile from './mailIngest/MailIngestAddonTile'
|
||||
import PaddleRegionsPanel from './paddle/PaddleRegionsPanel'
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch'
|
||||
import { ImmichIcon, SynologyIcon } from './addons/PhotoProviderIcons'
|
||||
import WandererMark from '../Tours/wanderer/WandererMark'
|
||||
|
||||
@@ -65,13 +68,24 @@ const TYPE_META: Record<string, { icon: ComponentType<{ size?: number }>; labelK
|
||||
integration: { icon: Link2, labelKey: 'admin.addons.type.integration', hintKey: 'admin.addons.integrationHint' },
|
||||
}
|
||||
|
||||
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, aside }: {
|
||||
/** The live flight status switch, an instance setting that sits with the trip addons. */
|
||||
export interface FlightLiveOption {
|
||||
on: boolean
|
||||
/** The server environment (FLIGHT_LIVE_ENABLED) holds it; the switch shows the state and says why. */
|
||||
locked: boolean
|
||||
managed: boolean
|
||||
onToggle: () => void
|
||||
}
|
||||
|
||||
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
|
||||
bagTrackingEnabled?: boolean
|
||||
onToggleBagTracking?: () => void
|
||||
collabFeatures?: CollabFeatures
|
||||
onToggleCollabFeature?: (key: string) => void
|
||||
/** Cards that set up what the integrations reach (flight status, booking mails), under them in the right column. */
|
||||
aside?: ReactNode
|
||||
/** Live flight status, a row of the trip card: it follows the trips' booked flights. */
|
||||
flightLive?: FlightLiveOption
|
||||
/** Booking mail import, a row of the integration card with its setup dialog; off on a managed install. */
|
||||
mailImport?: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
@@ -181,6 +195,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
onToggle={() => void toggle()}
|
||||
/>
|
||||
)),
|
||||
// The paddle water data the tour planner reads, set up in a dialog of its own.
|
||||
<PaddleRegionsPanel key="paddle-regions" />,
|
||||
]
|
||||
}
|
||||
return null
|
||||
@@ -202,6 +218,9 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether a card holds rows beside its own addons: the AI tile, an instance option. */
|
||||
const extraRows = (key: string) =>
|
||||
(key === 'trip' && !!flightLive) || (key === 'integration' && (aiAddons.length > 0 || mailImport))
|
||||
/* A card per type, the way every other admin tab sets its cards: Trip in the
|
||||
left column, Global and Integration in the right one, each card with the
|
||||
dialogs' head band carrying the type, its count and what it means. */
|
||||
@@ -209,14 +228,14 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{ key: 'trip', addons: tripAddons },
|
||||
{ key: 'global', addons: globalAddons },
|
||||
{ key: 'integration', addons: integrationAddons },
|
||||
].filter(g => g.addons.length > 0 || (g.key === 'integration' && aiAddons.length > 0))
|
||||
].filter(g => g.addons.length > 0 || extraRows(g.key))
|
||||
|
||||
const card = (g: (typeof groups)[number]) => {
|
||||
const meta = TYPE_META[g.key]
|
||||
const all = g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons
|
||||
const visible = g.addons
|
||||
const ai = g.key === 'integration' && aiAddons.length > 0
|
||||
if (!visible.length && !ai) return null
|
||||
if (!visible.length && !ai && !extraRows(g.key)) return null
|
||||
const on = all.filter(a => a.enabled).length
|
||||
return (
|
||||
<SettingsCard
|
||||
@@ -235,6 +254,10 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{/* The AI addons share a connection and a settings dialog, so they head the card as one tile. */}
|
||||
{ai && <AiAddonTile addons={aiAddons} onToggle={handleToggle} />}
|
||||
{visible.map(tile)}
|
||||
{/* Not addons but instance options of the same kind, as rows of the same card;
|
||||
the count above stays the addons'. */}
|
||||
{g.key === 'trip' && flightLive && <FlightLiveTile option={flightLive} />}
|
||||
{g.key === 'integration' && mailImport && <MailIngestAddonTile />}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
)
|
||||
@@ -251,5 +274,21 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
}
|
||||
|
||||
return <SettingsColumns start={cards.start} end={<>{cards.end}{aside}</>} />
|
||||
return <SettingsColumns start={cards.start} end={cards.end} />
|
||||
}
|
||||
|
||||
/** Live flight status as a trip row: on, it follows every booked flight on its day. */
|
||||
function FlightLiveTile({ option }: { option: FlightLiveOption }) {
|
||||
const { t } = useTranslation()
|
||||
const name = t('flightLive.adminTitle')
|
||||
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
|
||||
return (
|
||||
<AddonTile
|
||||
icon={<Radar size={18} />}
|
||||
name={name}
|
||||
description={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
|
||||
enabled={option.on}
|
||||
trailing={<ToggleSwitch on={option.on} label={t('flightLive.adminToggle')} disabled={option.locked} onToggle={option.onToggle} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import React, { useId, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The dialog an addon's setup row opens: the icon tile, the addon it belongs
|
||||
* to above the title, what it sets up below, and one Close, since everything
|
||||
* inside saves on its own (booking mails, paddle water data).
|
||||
*/
|
||||
export default function AddonSetupDialog({
|
||||
icon,
|
||||
eyebrow,
|
||||
title,
|
||||
sub,
|
||||
onClose,
|
||||
blocked = false,
|
||||
children,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
sub: string;
|
||||
onClose: () => void;
|
||||
/** A confirmation stacked on top holds the dialog while it is open. */
|
||||
blocked?: boolean;
|
||||
children: ReactNode;
|
||||
}): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="detail"
|
||||
blocked={blocked}
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={<DialogTile>{icon}</DialogTile>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
eyebrow={eyebrow}
|
||||
title={title}
|
||||
sub={sub}
|
||||
subWraps
|
||||
onClose={onClose}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton variant="primary" onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ChevronRight, Settings2 } from 'lucide-react';
|
||||
import React, { type ReactNode } from 'react';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The last row of an addon's shelf that opens its settings dialog: a gear, what
|
||||
* the dialog sets up, and a chevron. It keeps a card of addons as short as its
|
||||
* switches and puts the long forms behind one tap (AI, booking mails, paddle
|
||||
* water data). A badge says what waits inside, such as requests to look at.
|
||||
*/
|
||||
export default function AddonSetupRow({
|
||||
label,
|
||||
onOpen,
|
||||
badge,
|
||||
}: {
|
||||
label: string;
|
||||
onOpen: () => void;
|
||||
badge?: ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
|
||||
<Settings2 size={14} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{label}
|
||||
</span>
|
||||
{badge}
|
||||
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ChevronRight, Settings2, Sparkles } from 'lucide-react';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { StatusPill } from '../../Settings/settingsKit';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import AddonSubRow from '../AddonSubRow';
|
||||
import AddonTile from '../AddonTile';
|
||||
import { type Addon, getAddonLabel } from './addonModel';
|
||||
@@ -54,23 +55,7 @@ export default function AiAddonTile({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{tile.canSetUp && (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={tile.openDialog}
|
||||
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
|
||||
<Settings2 size={14} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{t('admin.addons.ai.setup')}
|
||||
</span>
|
||||
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
{tile.canSetUp && <AddonSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
|
||||
</AddonTile>
|
||||
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
|
||||
</>
|
||||
|
||||
+42
-33
@@ -1,22 +1,17 @@
|
||||
import { AlertTriangle, CheckCircle, Copy, Loader2, Mail, PlugZap, Save, XCircle } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { copyText } from '../../../utils/clipboard';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import {
|
||||
HintMark,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_BUTTON_PRIMARY,
|
||||
SettingRow,
|
||||
SettingRows,
|
||||
SettingsCard,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
import { HintMark, SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, StatusPill } from '../../Settings/settingsKit';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import CustomSelect from '../../shared/CustomSelect';
|
||||
import { EditorField, GRID_2, INPUT, READONLY_BOX } from '../../shared/dialogParts';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import AddonSetupDialog from '../AddonSetupDialog';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import AddonTile from '../AddonTile';
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
@@ -306,32 +301,46 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the admin settings of a self-hosted install: the
|
||||
* instance switch, how mail arrives (IMAP or a signed webhook), the forwarding
|
||||
* address template, the AI allowance per person and day, a connection test and
|
||||
* the status in counts. Not shown on a managed install, where the operator
|
||||
* runs the TREK Cloud relay.
|
||||
* The booking mail import as a row of the integration card: its switch, and
|
||||
* while it is on one row to the dialog that sets it up (how mail arrives, the
|
||||
* forwarding address template, the AI allowance per person and day, a
|
||||
* connection test and the status in counts). Not shown on a managed install,
|
||||
* where the operator runs the TREK Cloud relay.
|
||||
*/
|
||||
export default function MailIngestAdminCard() {
|
||||
export default function MailIngestAddonTile() {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
const [open, setOpen] = useState(false);
|
||||
const name = t('mailAdmin.title');
|
||||
return (
|
||||
<SettingsCard icon={Mail} title={t('mailAdmin.title')} hint={t('mailAdmin.hint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</SettingsCard>
|
||||
<>
|
||||
<AddonTile
|
||||
icon={<Mail size={15} />}
|
||||
name={name}
|
||||
description={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
|
||||
enabled={admin.enabled}
|
||||
trailing={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{admin.enabled && admin.form && <AddonSetupRow label={t('mailAdmin.setup')} onOpen={() => setOpen(true)} />}
|
||||
</AddonTile>
|
||||
{open && admin.enabled && admin.form && (
|
||||
<AddonSetupDialog
|
||||
icon={<Mail size={20} strokeWidth={2} />}
|
||||
eyebrow={name}
|
||||
title={t('mailAdmin.setup')}
|
||||
sub={t('mailAdmin.hint')}
|
||||
onClose={() => setOpen(false)}
|
||||
>
|
||||
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
|
||||
</AddonSetupDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -78,17 +78,22 @@ function adminState(overrides: Partial<Admin> = {}, search: Partial<Admin['searc
|
||||
};
|
||||
}
|
||||
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}) {
|
||||
/** The panel as the Tours shelf shows it: a setup row, opened into its dialog unless asked not to. */
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}, { open = true } = {}) {
|
||||
const state = adminState(overrides, search);
|
||||
hook.usePaddleRegionsAdmin.mockReturnValue(state);
|
||||
return { state, ...render(<PaddleRegionsPanel />) };
|
||||
const view = render(
|
||||
<ul>
|
||||
<PaddleRegionsPanel />
|
||||
</ul>
|
||||
);
|
||||
if (open && state.toursOn) fireEvent.click(setupRow());
|
||||
return { state, ...view };
|
||||
}
|
||||
|
||||
/** The card's title row, where the number of regions sits beside the title. */
|
||||
function titleRow(): HTMLElement {
|
||||
const row = screen.getByRole('heading', { name: 'Paddle water data' }).parentElement;
|
||||
if (!row) throw new Error('no title row');
|
||||
return row;
|
||||
/** The shelf row that opens the dialog, where the count of requests or regions sits beside the title. */
|
||||
function setupRow(): HTMLElement {
|
||||
return screen.getAllByRole('button', { name: /^Paddle water data/ })[0];
|
||||
}
|
||||
|
||||
function rowOf(name: string): HTMLElement {
|
||||
@@ -100,7 +105,7 @@ function rowOf(name: string): HTMLElement {
|
||||
describe('PaddleRegionsPanel', () => {
|
||||
it('FE-ADMIN-PADDLEREG-001: renders nothing while the Tours addon is off', () => {
|
||||
const { container } = show({ toursOn: false, regions: [READY] });
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
expect(container.querySelector('ul')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-002: shows the card with its hint, the attribution and the empty state', () => {
|
||||
@@ -110,7 +115,7 @@ describe('PaddleRegionsPanel', () => {
|
||||
expect(screen.getByText(EMPTY)).toBeInTheDocument();
|
||||
expect(screen.getByText(ATTRIBUTION)).toBeInTheDocument();
|
||||
// No count beside the title while there is no region.
|
||||
expect(titleRow()).toHaveTextContent(/^Paddle water data$/);
|
||||
expect(setupRow()).toHaveTextContent(/^Paddle water data$/);
|
||||
const search = screen.getByRole('searchbox', { name: 'Add a region' });
|
||||
expect(search).toBeEnabled();
|
||||
expect(search).toHaveAttribute('placeholder', 'Search Geofabrik, for example Oberpfalz');
|
||||
@@ -277,12 +282,31 @@ describe('PaddleRegionsPanel', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-019: the title carries the number of regions', () => {
|
||||
it('FE-ADMIN-PADDLEREG-019: the setup row carries the open requests, else the number of regions', () => {
|
||||
show({ regions: [READY, WAITING, FAILED_FIRST] });
|
||||
expect(within(titleRow()).getByText('3')).toBeInTheDocument();
|
||||
expect(within(setupRow()).getByText('3')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('paddle-region-row')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-019b: an open request outranks the region count, a declined one does not count', () => {
|
||||
const base = { bytes: 1, requested_by: 'elmo', requested_at: '2026-10-18T09:00:00Z' };
|
||||
show(
|
||||
{
|
||||
regions: [READY, WAITING],
|
||||
requests: [
|
||||
{ ...base, id: 'norway', name: 'Norway', reason: 'too_large', declined: true },
|
||||
{ ...base, id: 'saale', name: 'Saale', reason: 'limit', declined: false },
|
||||
],
|
||||
},
|
||||
{},
|
||||
{ open: false }
|
||||
);
|
||||
expect(within(setupRow()).getByText('1')).toBeInTheDocument();
|
||||
expect(within(setupRow()).queryByText('2')).toBeNull();
|
||||
// Closed until the row is opened.
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-020: removing asks first, naming the region, and confirming hands it to the hook', () => {
|
||||
const { state } = show({ regions: [READY], removing: READY });
|
||||
const message = 'Oberpfalz and its obstacle data are removed. Paddle tours there then show no data.';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
|
||||
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react';
|
||||
import { useId } from 'react';
|
||||
import { useId, useState } from 'react';
|
||||
import { useDateFormat } from '../../../hooks/useDateFormat';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { formatDisplayDate } from '../../../utils/dateFormat';
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
SettingRows,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_ICON_BUTTON,
|
||||
SettingsCard,
|
||||
SettingsHint,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
@@ -17,6 +16,8 @@ import { EditorField, INPUT } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import ErrorBoundary from '../../shared/ErrorBoundary';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import AddonSetupDialog from '../AddonSetupDialog';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import { AutoLoadSettings, AutoOriginPill, RequestList } from './PaddleAutoLoadParts';
|
||||
import { progressPercent, regionStatusTone } from './paddleRegionsModel';
|
||||
import { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
|
||||
@@ -27,8 +28,10 @@ type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
|
||||
* PAD-05A in the admin area: the regions TREK reads paddle obstacles for,
|
||||
* picked from Geofabrik's list, and (PAD-11C) how TREK loads the region of a
|
||||
* place a paddler plans in by itself, with the regions that wait for an admin.
|
||||
* The desktop admin shows this card under the addons while the Tours addon
|
||||
* is on; the phone has MAdminPaddleRegionsPanel on the same hook.
|
||||
* The desktop admin shows it as a row of the Tours addon that opens it as a
|
||||
* dialog while the addon is on; the row counts what waits for the admin (the
|
||||
* requests) or else the regions. The phone has MAdminPaddleRegionsPanel on
|
||||
* the same hook.
|
||||
*/
|
||||
export default function PaddleRegionsPanel() {
|
||||
return (
|
||||
@@ -41,14 +44,42 @@ export default function PaddleRegionsPanel() {
|
||||
function Panel() {
|
||||
const { t } = useTranslation();
|
||||
const admin = usePaddleRegionsAdmin();
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!admin.toursOn) return null;
|
||||
const title = t('admin.paddleRegions.title');
|
||||
// A declined request no longer waits for anyone; only the open ones ask for a look.
|
||||
const waiting = admin.requests.filter((r) => !r.declined).length;
|
||||
const badge =
|
||||
waiting > 0 ? (
|
||||
<StatusPill tone="warning">{waiting}</StatusPill>
|
||||
) : admin.regions.length > 0 ? (
|
||||
<StatusPill>{admin.regions.length}</StatusPill>
|
||||
) : undefined;
|
||||
const close = () => setOpen(false);
|
||||
return (
|
||||
<SettingsCard
|
||||
icon={Waves}
|
||||
title={t('admin.paddleRegions.title')}
|
||||
hint={t('admin.paddleRegions.hint')}
|
||||
badge={admin.regions.length > 0 ? <StatusPill>{admin.regions.length}</StatusPill> : undefined}
|
||||
>
|
||||
<>
|
||||
<AddonSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
|
||||
{open && (
|
||||
<AddonSetupDialog
|
||||
icon={<Waves size={20} strokeWidth={2} />}
|
||||
eyebrow={t('admin.addons.catalog.tours.name')}
|
||||
title={title}
|
||||
sub={t('admin.paddleRegions.hint')}
|
||||
onClose={close}
|
||||
blocked={admin.removing !== null}
|
||||
>
|
||||
<PanelBody admin={admin} />
|
||||
</AddonSetupDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the dialog holds: the state of the list, the settings, the requests, the search and the regions. */
|
||||
function PanelBody({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{admin.offline && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -86,7 +117,7 @@ function Panel() {
|
||||
message={t('admin.paddleRegions.removeMessage', { name: admin.removing?.name ?? '' })}
|
||||
confirmLabel={t('common.remove')}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
|
||||
photoId: 7,
|
||||
video: false,
|
||||
photoCount: 1,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: 0,
|
||||
@@ -86,13 +85,15 @@ afterEach(() => {
|
||||
|
||||
describe('the journal entries card', () => {
|
||||
it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => {
|
||||
const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]);
|
||||
// A card stored while entries carried a visibility: it reads, and says nothing of it.
|
||||
const stored = { ...look({ draft: true, photoCount: 4, video: true }), visibility: 'public' };
|
||||
const { container } = block([card([stored])]);
|
||||
expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument();
|
||||
expect(screen.getByText('14:30')).toBeInTheDocument();
|
||||
expect(screen.getByText('Berlin')).toBeInTheDocument();
|
||||
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Public')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Public')).toBeNull();
|
||||
expect(screen.getByText('Draft')).toBeInTheDocument();
|
||||
expect(screen.getByText('4 photos')).toBeInTheDocument();
|
||||
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
|
||||
@@ -225,13 +226,12 @@ describe('a change row of a journal entry', () => {
|
||||
}
|
||||
|
||||
it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => {
|
||||
const entry = look({ fromTripPlace: true, visibility: 'shared' });
|
||||
const entry = look({ fromTripPlace: true });
|
||||
const held = card([entry], { change: 'willDelete', tripJournal: true });
|
||||
const onOpen = vi.fn();
|
||||
const first = inView(<AssistantChangeCard items={[item('pending', held)]} />, { onOpen });
|
||||
expect(screen.getByText('Delete the journal entry')).toBeInTheDocument();
|
||||
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shared')).toBeInTheDocument();
|
||||
expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument();
|
||||
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
|
||||
expect(screen.getByText('Museum Island')).toBeInTheDocument();
|
||||
@@ -255,7 +255,6 @@ describe('a change row of a journal entry', () => {
|
||||
{ op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' },
|
||||
{ op: 'change', labelKey: 'time', before: '14:30', after: '' },
|
||||
{ op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' },
|
||||
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' },
|
||||
{ op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' },
|
||||
{ op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' },
|
||||
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' },
|
||||
@@ -267,8 +266,6 @@ describe('a change row of a journal entry', () => {
|
||||
expect(screen.getByText('14:30')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Old story')).toHaveClass('line-through');
|
||||
expect(screen.getByText('New story')).toBeInTheDocument();
|
||||
expect(screen.getByText('Private')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Public')).toBeInTheDocument();
|
||||
expect(screen.getByText('Good')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Sunny')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Drizzle')).toBeInTheDocument();
|
||||
|
||||
@@ -28,7 +28,6 @@ const ENTRY: JourneyEntryLook = {
|
||||
photoId: null,
|
||||
video: false,
|
||||
photoCount: 0,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: null,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { JourneyEntryLook } from '@trek/shared';
|
||||
import { CalendarDays, Globe, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp, Users } from 'lucide-react';
|
||||
import { CalendarDays, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard';
|
||||
@@ -12,8 +12,8 @@ import { moodOf, weatherOf } from './journeyTones';
|
||||
/**
|
||||
* The pieces a journal entry is drawn from in the chat, the same in an
|
||||
* answer, a change row and a receipt: its photo, the facts of when and where
|
||||
* as the planner's badges, the marks of how it reads (shared, draft, mood,
|
||||
* weather, more photos) and the start of its text. Every fact wraps, none is
|
||||
* as the planner's badges, the marks of how it reads (draft, mood, weather,
|
||||
* more photos) and the start of its text. Every fact wraps, none is
|
||||
* cut.
|
||||
*/
|
||||
|
||||
@@ -63,19 +63,6 @@ export function EntryWhen({ look }: { look: JourneyEntryLook }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Shared or public; nothing for a private entry. */
|
||||
function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) {
|
||||
const { t } = useTranslation();
|
||||
if (visibility === 'private') return null;
|
||||
const shared = visibility === 'shared';
|
||||
const Icon = shared ? Users : Globe;
|
||||
return (
|
||||
<SoftPill tone="info" icon={<Icon size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{shared ? t('journey.visibility.shared') : t('journey.visibility.public')}
|
||||
</SoftPill>
|
||||
);
|
||||
}
|
||||
|
||||
/** A mood the journal knows, in its own colour; nothing for any other. */
|
||||
function MoodMark({ id }: { id: string | null }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -129,17 +116,16 @@ function ListMarks({ look }: { look: JourneyEntryLook }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first, its tags and verdict. */
|
||||
/** How the entry reads: a draft, its mood and weather, its photos past the first, its tags and verdict. */
|
||||
export function EntryMarks({ look }: { look: JourneyEntryLook }) {
|
||||
const { t } = useTranslation();
|
||||
const mood = moodOf(look.mood) !== null;
|
||||
const lists = (look.tags?.length ?? 0) > 0 || !!look.verdict;
|
||||
if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
|
||||
if (!look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<CardFacts>
|
||||
<VisibilityMark visibility={look.visibility} />
|
||||
{look.draft && <SoftPill tone="warning">{t('journey.entry.draft')}</SoftPill>}
|
||||
<MoodMark id={look.mood} />
|
||||
<WeatherMark weather={look.weather} />
|
||||
|
||||
@@ -31,7 +31,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
|
||||
photoId: null,
|
||||
video: false,
|
||||
photoCount: 0,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: null,
|
||||
@@ -97,12 +96,13 @@ describe('journeyCardModel', () => {
|
||||
});
|
||||
|
||||
it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => {
|
||||
expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public');
|
||||
// The stored visibility keeps nothing off the share link, so it has no name to show.
|
||||
expect(stateOf('visibility', 'private')).toBeNull();
|
||||
expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion');
|
||||
expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good');
|
||||
expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold');
|
||||
expect(stateOf('weather', 'Drizzle')).toBeNull();
|
||||
expect(stateOf('visibility', 'toString')).toBeNull();
|
||||
expect(stateOf('type', 'toString')).toBeNull();
|
||||
expect(stateOf(undefined, 'public')).toBeNull();
|
||||
expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft');
|
||||
expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft');
|
||||
|
||||
@@ -7,8 +7,6 @@ import {
|
||||
Eye,
|
||||
EyeOff,
|
||||
Frown,
|
||||
Globe,
|
||||
Lock,
|
||||
type LucideIcon,
|
||||
MapPinCheck,
|
||||
Meh,
|
||||
@@ -19,14 +17,13 @@ import {
|
||||
Snowflake,
|
||||
Sparkles,
|
||||
Sun,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
|
||||
/**
|
||||
* How the states of a journal entry read in the chat, the way the journal
|
||||
* draws them: its moods with the glyphs of its tiles, its weathers, and the
|
||||
* words for what an update sets beyond the text (who sees the entry, its
|
||||
* kind, a draft, the route, a waved-away suggestion).
|
||||
* words for what an update sets beyond the text (its kind, a draft, the
|
||||
* route, a waved-away suggestion).
|
||||
*/
|
||||
|
||||
/** How a state is drawn: its glyph and the key of its name. */
|
||||
@@ -57,12 +54,6 @@ const WEATHERS: Readonly<Record<string, EntryTone>> = {
|
||||
cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' },
|
||||
};
|
||||
|
||||
const VISIBILITIES: Readonly<Record<string, EntryTone>> = {
|
||||
private: { Icon: Lock, labelKey: 'journey.visibility.private' },
|
||||
shared: { Icon: Users, labelKey: 'journey.visibility.shared' },
|
||||
public: { Icon: Globe, labelKey: 'journey.visibility.public' },
|
||||
};
|
||||
|
||||
const TYPES: Readonly<Record<string, EntryTone>> = {
|
||||
entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' },
|
||||
checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' },
|
||||
@@ -119,7 +110,6 @@ export function flagOf(field: string | undefined, value: string): EntryTone | nu
|
||||
export function stateOf(field: string | undefined, value: string | null): EntryTone | null {
|
||||
if (field === 'mood') return moodOf(value);
|
||||
if (field === 'weather') return weatherOf(value);
|
||||
if (field === 'visibility') return own(VISIBILITIES, value);
|
||||
if (field === 'type') return own(TYPES, value);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -54,6 +54,14 @@ describe('TransitLegs', () => {
|
||||
expect(screen.getByText('BVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-009: stop names and a walk target wrap instead of being cut off (#3139)', () => {
|
||||
render(<TransitLegs legs={[ride, walk]} compact />);
|
||||
for (const text of ['Alexanderplatz', 'Eberswalder Str.', 'Walk to Mauerpark']) {
|
||||
expect(screen.getByText(text)).not.toHaveClass('truncate');
|
||||
expect(screen.getByText(text)).toHaveClass('break-words');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
|
||||
render(<TransitLegs legs={[walk]} compact />);
|
||||
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
|
||||
|
||||
@@ -48,9 +48,11 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
|
||||
}}>{leg.line || leg.mode}</span>
|
||||
)}
|
||||
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
|
||||
<div className="flex min-w-0 items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
|
||||
{walk ? <span className="truncate text-content-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
|
||||
<><span className="truncate">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span className="truncate">{leg.to?.name}</span></>
|
||||
{/* Detail views show a stop name whole: the names wrap and the
|
||||
arrow moves to the next line with them when it has to (#3139). */}
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
|
||||
{walk ? <span className="min-w-0 break-words text-content-muted [overflow-wrap:anywhere]">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
|
||||
<><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span></>
|
||||
)}
|
||||
</div>
|
||||
<TransitMetaBadges size={compact ? 'sm' : 'md'} items={[
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import type { TransitLegDisplay } from './transitDisplay';
|
||||
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay';
|
||||
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
params ? `${key}:${Object.values(params).join(',')}` : key;
|
||||
|
||||
const ride: TransitLegDisplay = {
|
||||
mode: 'RAIL',
|
||||
line: 'XC',
|
||||
duration: 1260,
|
||||
from: { name: 'Basingstoke', time: '12:48' },
|
||||
to: { name: 'Reading', time: '13:09' },
|
||||
};
|
||||
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Reading station, Station Approach' } };
|
||||
|
||||
/** Whether a rendered element clips its text to one line. */
|
||||
function clipsToOneLine(el: HTMLElement): boolean {
|
||||
return el.style.whiteSpace === 'nowrap' || el.style.textOverflow === 'ellipsis';
|
||||
}
|
||||
|
||||
describe('TransitItineraryInline (#3139)', () => {
|
||||
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
|
||||
render(<TransitItineraryInline legs={[ride]} t={t} />);
|
||||
for (const name of ['Basingstoke', 'Reading']) {
|
||||
const el = screen.getByText(name);
|
||||
expect(clipsToOneLine(el)).toBe(false);
|
||||
expect(el.style.overflowWrap).toBe('anywhere');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSITDISPLAY-002: a ride shows its arrival time under its departure', () => {
|
||||
render(<TransitItineraryInline legs={[ride, { ...ride, to: { name: 'Oxford' } }]} t={t} />);
|
||||
expect(screen.getByText('13:09')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('12:48')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransitWalkDivider (#3139)', () => {
|
||||
it('FE-PLANNER-TRANSITDISPLAY-003: the walk target wraps instead of being cut off', () => {
|
||||
render(<TransitWalkDivider leg={walk} t={t} size="sm" />);
|
||||
const text = screen.getByText(/transit\.walkTo:Reading station, Station Approach/);
|
||||
expect(clipsToOneLine(text)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -41,14 +41,14 @@ export function TransitWalkDivider({ leg, t, size = 'md' }: {
|
||||
background: `linear-gradient(to ${dir}, var(--text-faint), transparent)`,
|
||||
opacity: 0.55,
|
||||
})
|
||||
// On phones the minutes lead so a long stop name only ever clips the name.
|
||||
// On phones the minutes lead, so they stay on the first line when a long stop name wraps.
|
||||
const text = isMobile
|
||||
? `${mins ? `${t('transit.min', { count: mins })} · ` : ''}${t('transit.walkTo', { name: leg.to?.name || '' })}`
|
||||
: `${t('transit.walkTo', { name: leg.to?.name || '' })}${mins ? ` · ${t('transit.min', { count: mins })}` : ''}`
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: size === 'sm' ? '1px 0' : '2px 0' }}>
|
||||
<span style={rule('left')} />
|
||||
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? '85%' : '75%' }}>
|
||||
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, textAlign: 'center', overflowWrap: 'anywhere', maxWidth: isMobile ? '85%' : '75%' }}>
|
||||
<Footprints size={size === 'sm' ? 11 : 12} style={{ flexShrink: 0 }} />
|
||||
{text}
|
||||
</span>
|
||||
@@ -72,8 +72,10 @@ export function TransitItineraryInline({ legs, t }: {
|
||||
const mins = leg.duration ? Math.round(leg.duration / 60) : null
|
||||
return (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
|
||||
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
|
||||
{leg.from?.time || ''}
|
||||
{/* Departure beside the stops, arrival under it (#3139). */}
|
||||
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
|
||||
<span>{leg.from?.time || ''}</span>
|
||||
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
|
||||
</span>
|
||||
<span style={{
|
||||
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px',
|
||||
@@ -84,10 +86,11 @@ export function TransitItineraryInline({ legs, t }: {
|
||||
{leg.line || leg.mode}
|
||||
</span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.from?.name}</span>
|
||||
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
|
||||
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
|
||||
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
|
||||
<MoveRight size={10} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.to?.name}</span>
|
||||
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
|
||||
</div>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', marginTop: 1 }}>
|
||||
{[
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { dayColor } from './dayColors'
|
||||
import { stageMapData, stagePlaceIds, stagePoints } from './stageMap'
|
||||
import { stageConnectionIds, stageMapData, stagePlaceIds, stagePoints } from './stageMap'
|
||||
import type { AccessSpur, RoadtripDay, RoadtripRoutes, RoadtripStop } from '@trek/shared/roadtrip'
|
||||
|
||||
// FE-RTSTAGE-001 to FE-RTSTAGE-021
|
||||
// FE-RTSTAGE-001 to FE-RTSTAGE-023
|
||||
|
||||
function stop(name: string, over: Partial<RoadtripStop> = {}): RoadtripStop {
|
||||
return {
|
||||
@@ -268,3 +268,23 @@ describe('a stage that starts or ends at a booked night', () => {
|
||||
expect(data.accessLines).toEqual([walk])
|
||||
})
|
||||
})
|
||||
|
||||
describe('stageConnectionIds', () => {
|
||||
const flight = (reservationId: number, role: 'arrival' | 'departure') =>
|
||||
stop('Airport', { carrier: { reservationId, type: 'flight', role, title: 'Flight', code: null, at: null } })
|
||||
|
||||
it("FE-RTSTAGE-022: a stage draws its own rides, not the drive's ride home from a later day", () => {
|
||||
// The flight in (31) seams this stage; the flight home (32) belongs to a stage days later
|
||||
// and is not on this one at all.
|
||||
const stage = day([flight(31, 'arrival'), stop('Ubud')])
|
||||
expect(stageConnectionIds(stage, [], () => true)).toEqual([31])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-023: of the bookings switched on by hand only those running on the stage day stay', () => {
|
||||
const stage = day([stop('Ubud')])
|
||||
const onThisDay = new Set([40])
|
||||
expect(stageConnectionIds(stage, [40, 41], id => onThisDay.has(id))).toEqual([40])
|
||||
// A ride that seams the stage stays even when it was booked on another day.
|
||||
expect(stageConnectionIds(day([flight(31, 'arrival')]), [31], () => false)).toEqual([31])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { dayColor } from './dayColors'
|
||||
import { carrierReservationIds } from '@trek/shared/roadtrip'
|
||||
import type { AccessSpur, RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip'
|
||||
|
||||
/**
|
||||
@@ -88,6 +89,20 @@ export function stagePlaceIds(stage: RoadtripDay): Set<number> {
|
||||
return new Set(stage.stops.filter(s => !s.automaticNight).map(s => s.placeId))
|
||||
}
|
||||
|
||||
/**
|
||||
* The bookings the map draws as arcs on ONE stage: the rides that seam this stage's
|
||||
* drive, whatever day they were booked on, and of the ones switched on by hand only
|
||||
* those that run on the stage's day. Taking the rides of the whole drive put a flight
|
||||
* home across every stage before it, as if it were part of that day.
|
||||
*/
|
||||
export function stageConnectionIds(
|
||||
stage: RoadtripDay,
|
||||
switchedOn: readonly number[],
|
||||
runsOnStageDay: (reservationId: number) => boolean,
|
||||
): number[] {
|
||||
return [...new Set([...switchedOn.filter(runsOnStageDay), ...carrierReservationIds([stage])])]
|
||||
}
|
||||
|
||||
/** The stage's stops as coordinates, for the fit. */
|
||||
export function stagePoints(stage: RoadtripDay): [number, number][] {
|
||||
return stage.stops
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import MAdminSchoolHolidayCatalog from './MAdminSchoolHolidayCatalog'
|
||||
import MAdminPaddleRegionsPanel from './MAdminPaddleRegionsPanel'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
ArrowUp,
|
||||
@@ -246,10 +245,17 @@ export default function MAdmin() {
|
||||
onToggleBagTracking={toggleBagTracking}
|
||||
collabFeatures={collabFeatures}
|
||||
onToggleCollabFeature={toggleCollabFeature}
|
||||
// Live flight status and the booking mail import are rows of the addon groups,
|
||||
// and the paddle water data a row under Tours (desktop parity).
|
||||
flightLive={{
|
||||
on: admin.flightLive,
|
||||
locked: admin.flightLiveLocked,
|
||||
managed: !!managed,
|
||||
onToggle: () =>
|
||||
void admin.handleToggleAuthSetting('flight_live_enabled', !admin.flightLive, admin.setFlightLive),
|
||||
}}
|
||||
mailImport={!managed}
|
||||
/>
|
||||
{/* How the integrations reach the world (live flights, booking mails), beside the addons they serve. */}
|
||||
<MAdminSettingsSection admin={admin} t={t} part="features" />
|
||||
<MAdminPaddleRegionsPanel />
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'plugins' && <MAdminPluginsPanel />}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useTranslation } from '../../../i18n'
|
||||
import { useIsDark } from '../../../hooks/useIsDark'
|
||||
import {
|
||||
Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen,
|
||||
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Settings2, ChevronRight,
|
||||
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Radar,
|
||||
} from 'lucide-react'
|
||||
import DawarichIcon from '../../../components/shared/DawarichIcon'
|
||||
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
|
||||
@@ -21,7 +21,10 @@ import AiSettingsDialog from '../../../components/Admin/addons/AiAdminConfig'
|
||||
import { AI_ADDON_ICONS, type AiAddonId } from '../../../components/Admin/addons/aiAddons'
|
||||
import { useAiAddonTile } from '../../../components/Admin/addons/useAiAddonTile'
|
||||
import { ImmichIcon, SynologyIcon } from '../../../components/Admin/addons/PhotoProviderIcons'
|
||||
import { MAdminCard } from './MAdminUi'
|
||||
import { MAdminCard, MAdminOptionRow, MAdminSetupRow } from './MAdminUi'
|
||||
import MAdminPaddleRegionsPanel from './MAdminPaddleRegionsPanel'
|
||||
import MMailIngestAdminCard from './MMailIngestAdminCard'
|
||||
import type { FlightLiveOption } from '../../../components/Admin/AddonManager'
|
||||
import MHintLabel from '../../components/MHintLabel'
|
||||
import WandererMark from '../../../components/Tours/wanderer/WandererMark'
|
||||
import MSkeleton from '../../components/MSkeleton'
|
||||
@@ -59,7 +62,16 @@ function AddonIcon({ name, size = 18, enabled = true }: AddonIconProps) {
|
||||
return <Icon size={size} />
|
||||
}
|
||||
|
||||
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature }: { bagTrackingEnabled?: boolean; onToggleBagTracking?: () => void; collabFeatures?: CollabFeatures; onToggleCollabFeature?: (key: string) => void }) {
|
||||
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
|
||||
bagTrackingEnabled?: boolean
|
||||
onToggleBagTracking?: () => void
|
||||
collabFeatures?: CollabFeatures
|
||||
onToggleCollabFeature?: (key: string) => void
|
||||
/** Live flight status, a row of the trip group (desktop parity). */
|
||||
flightLive?: FlightLiveOption
|
||||
/** Booking mail import, a row of the integration group with its setup sheet; off on a managed install. */
|
||||
mailImport?: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const dark = useIsDark()
|
||||
const {
|
||||
@@ -98,7 +110,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
) : (
|
||||
<>
|
||||
{/* Trip Addons */}
|
||||
{tripAddons.length > 0 && (
|
||||
{(tripAddons.length > 0 || flightLive) && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Briefcase} label={t('admin.addons.type.trip')} hint={t('admin.addons.tripHint')} />
|
||||
{tripAddons.map((addon, i) => (
|
||||
@@ -135,6 +147,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
onToggle={() => void toggle()}
|
||||
/>
|
||||
))}
|
||||
<MAdminPaddleRegionsPanel />
|
||||
</>
|
||||
)}
|
||||
{addon.id === 'collab' && addon.enabled && collabFeatures && onToggleCollabFeature && (
|
||||
@@ -153,6 +166,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{flightLive && <MFlightLiveRow option={flightLive} first={tripAddons.length === 0} />}
|
||||
</MAdminCard>
|
||||
)}
|
||||
|
||||
@@ -171,13 +185,14 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
)}
|
||||
|
||||
{/* Integration Addons, headed by the AI ones as one group, as on the desktop */}
|
||||
{(integrationAddons.length > 0 || aiAddons.length > 0) && (
|
||||
{(integrationAddons.length > 0 || aiAddons.length > 0 || mailImport) && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Link2} label={t('admin.addons.type.integration')} hint={t('admin.addons.integrationHint')} />
|
||||
{aiAddons.length > 0 && <MAiAddons addons={aiAddons} onToggle={handleToggle} />}
|
||||
{integrationAddons.map((addon, i) => (
|
||||
<MAddonRow key={addon.id} addon={addon} onToggle={handleToggle} t={t} first={i === 0 && aiAddons.length === 0} />
|
||||
))}
|
||||
{mailImport && <MMailIngestAdminCard first={integrationAddons.length === 0 && aiAddons.length === 0} />}
|
||||
</MAdminCard>
|
||||
)}
|
||||
</>
|
||||
@@ -216,16 +231,28 @@ interface MAddonRowProps {
|
||||
function MAddonRow({ addon, onToggle, t, first }: MAddonRowProps) {
|
||||
const label = getAddonLabel(t, addon)
|
||||
return (
|
||||
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
{/* overflow-hidden so a brand mark that fills the slot keeps its rounded corners. */}
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center overflow-hidden rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
<AddonIcon name={addon.icon} size={18} enabled={addon.enabled} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<MHintLabel label={label.name} hint={label.description} />
|
||||
</div>
|
||||
<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />
|
||||
</div>
|
||||
<MAdminOptionRow
|
||||
icon={<AddonIcon name={addon.icon} size={18} enabled={addon.enabled} />}
|
||||
title={label.name}
|
||||
hint={label.description}
|
||||
first={first}
|
||||
trailing={<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Live flight status as a trip row, locked with a word when the server environment holds it. */
|
||||
function MFlightLiveRow({ option, first }: { option: FlightLiveOption; first: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
|
||||
return (
|
||||
<MAdminOptionRow
|
||||
icon={<Radar size={18} />}
|
||||
title={t('flightLive.adminTitle')}
|
||||
hint={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
|
||||
first={first}
|
||||
trailing={<MToggle checked={option.on} ariaLabel={t('flightLive.adminToggle')} disabled={option.locked} onChange={option.onToggle} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -301,17 +328,7 @@ function MAiAddons({ addons, onToggle }: { addons: Addon[]; onToggle: (addon: Ad
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{tile.canSetUp && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={tile.openDialog}
|
||||
className="flex w-full items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ps-[50px] text-start"
|
||||
>
|
||||
<Settings2 size={14} className="flex-none text-m-faint" />
|
||||
<span className="min-w-0 flex-1 truncate text-[0.75rem] font-bold text-m-ink">{t('admin.addons.ai.setup')}</span>
|
||||
<ChevronRight size={15} className="flex-none text-m-faint rtl:rotate-180" />
|
||||
</button>
|
||||
)}
|
||||
{tile.canSetUp && <MAdminSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
|
||||
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Waves,
|
||||
WifiOff,
|
||||
} from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
AUTO_LOAD_MODES,
|
||||
autoLoadSizes,
|
||||
@@ -28,8 +29,9 @@ import { useTranslation } from '../../../i18n';
|
||||
import { formatDisplayDate } from '../../../utils/dateFormat';
|
||||
import MBadge from '../../components/MBadge';
|
||||
import MChip from '../../components/MChip';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import MConfirmSheet from '../settings/MConfirmSheet';
|
||||
import { MAdminButton, MAdminCard, MAdminClampedText } from './MAdminUi';
|
||||
import { MAdminButton, MAdminClampedText, MAdminSetupRow, MAdminSheetFrame } from './MAdminUi';
|
||||
|
||||
type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
|
||||
|
||||
@@ -393,32 +395,49 @@ function Regions({ admin }: { admin: Admin }) {
|
||||
|
||||
/**
|
||||
* PAD-05A/PAD-11C on the phone: the regions TREK reads paddle data for, how it
|
||||
* loads a paddler's region by itself and the regions that wait for an admin.
|
||||
* usePaddleRegionsAdmin is the desktop card's state; this is only the markup.
|
||||
* loads a paddler's region by itself and the regions that wait for an admin, as
|
||||
* a row under the Tours addon that opens them in a sheet. The row counts the
|
||||
* open requests, else the regions. usePaddleRegionsAdmin is the desktop
|
||||
* dialog's state; this is only the markup.
|
||||
*/
|
||||
export default function MAdminPaddleRegionsPanel() {
|
||||
const { t } = useTranslation();
|
||||
const admin = usePaddleRegionsAdmin();
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!admin.toursOn) return null;
|
||||
const title = t('admin.paddleRegions.title');
|
||||
// A declined request no longer waits for anyone; only the open ones ask for a look.
|
||||
const waiting = admin.requests.filter((r) => !r.declined).length;
|
||||
const badge =
|
||||
waiting > 0 ? (
|
||||
<MBadge caps={false} tone="strong">
|
||||
{waiting}
|
||||
</MBadge>
|
||||
) : admin.regions.length > 0 ? (
|
||||
<MBadge caps={false}>{admin.regions.length}</MBadge>
|
||||
) : undefined;
|
||||
return (
|
||||
<MAdminCard>
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
<Waves size={18} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 truncate text-[length:calc(14px*var(--fs-scale-body,1))] font-extrabold text-m-ink">
|
||||
{t('admin.paddleRegions.title')}
|
||||
</span>
|
||||
{admin.regions.length > 0 && <MBadge caps={false}>{admin.regions.length}</MBadge>}
|
||||
</div>
|
||||
<MAdminClampedText className="mt-[2px] text-[length:calc(10px*var(--fs-scale-caption,1))]">
|
||||
{t('admin.paddleRegions.hint')}
|
||||
</MAdminClampedText>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<MAdminSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
|
||||
{open && (
|
||||
<MSheet open onClose={() => setOpen(false)} variant="bottom" material="glass" ariaLabel={title}>
|
||||
<MAdminSheetFrame icon={<Waves size={19} strokeWidth={1.8} />} title={title} onClose={() => setOpen(false)}>
|
||||
<p className="m-0 font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-relaxed text-m-muted">
|
||||
{t('admin.paddleRegions.hint')}
|
||||
</p>
|
||||
<PanelBody admin={admin} />
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the sheet holds: the state of the list, the settings, the requests, the search and the regions. */
|
||||
function PanelBody({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{admin.offline && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -462,6 +481,6 @@ export default function MAdminPaddleRegionsPanel() {
|
||||
danger
|
||||
onConfirm={admin.confirmRemove}
|
||||
/>
|
||||
</MAdminCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { MBlockDisclosure, MProviderBlock, MTrekApiBlock } from './MApiProviderBlocks'
|
||||
import MAdminOidcCard from './MAdminOidcCard'
|
||||
import MMailIngestAdminCard from './MMailIngestAdminCard'
|
||||
import MAdminGoogleDailyLimit from './MAdminGoogleDailyLimit'
|
||||
import MAdminPlaceContrib from './MAdminPlaceContrib'
|
||||
import MAdminServiceQuota from './MAdminServiceQuota'
|
||||
@@ -27,41 +26,22 @@ interface MAdminSettingsSectionProps {
|
||||
t: TranslationFn
|
||||
/**
|
||||
* Which section this renders, cut the way the desktop tabs are: who may sign
|
||||
* in and what it takes (security), what the install talks to outside
|
||||
* (services), and the setup of the features the addons switch on (features).
|
||||
* in and what it takes (security) or what the install talks to outside
|
||||
* (services). Live flight status and the booking mail import are rows of the
|
||||
* addon groups (MAdminAddonManager).
|
||||
*/
|
||||
part: 'security' | 'services' | 'features'
|
||||
part: 'security' | 'services'
|
||||
}
|
||||
|
||||
type PartProps = Omit<MAdminSettingsSectionProps, 'part'>
|
||||
|
||||
// The admin's security, services and feature setup sections as phone cards,
|
||||
// The admin's security and services sections as phone cards,
|
||||
// one function each. All state and mutations come from useAdmin.
|
||||
export default function MAdminSettingsSection({ admin, t, part }: MAdminSettingsSectionProps) {
|
||||
if (part === 'features') return <FeaturesPart admin={admin} t={t} />
|
||||
if (part === 'security') return <SecurityPart admin={admin} t={t} />
|
||||
return <ServicesPart admin={admin} t={t} />
|
||||
}
|
||||
|
||||
/** Live flights and booking mails: how the integrations of the addons tab reach the world. */
|
||||
function FeaturesPart({ admin, t }: PartProps) {
|
||||
const { managed, flightLive, setFlightLive, flightLiveLocked, handleToggleAuthSetting } = admin
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}
|
||||
<FlightLiveCard
|
||||
t={t}
|
||||
managed={!!managed}
|
||||
on={flightLive}
|
||||
locked={flightLiveLocked}
|
||||
onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}
|
||||
/>
|
||||
{/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}
|
||||
{!managed && <MMailIngestAdminCard />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Who may sign in and what it takes, with the one destructive action last. */
|
||||
function SecurityPart({ admin, t }: PartProps) {
|
||||
const {
|
||||
@@ -482,23 +462,3 @@ function ServicesPart({ admin, t }: PartProps) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The live flight status switch, locked with a word when the server environment holds it. */
|
||||
function FlightLiveCard({ t, managed, on, locked, onChange }: {
|
||||
t: TranslationFn
|
||||
managed: boolean
|
||||
on: boolean
|
||||
locked: boolean
|
||||
onChange: (on: boolean) => void
|
||||
}) {
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')} />
|
||||
<MAdminRow
|
||||
title={t('flightLive.adminToggle')}
|
||||
hint={locked ? t('flightLive.envLocked') : undefined}
|
||||
trailing={<MToggle checked={on} ariaLabel={t('flightLive.adminToggle')} disabled={locked} onChange={onChange} />}
|
||||
/>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { InputHTMLAttributes, ReactNode, useState } from 'react'
|
||||
import { ChevronDown, Eye, EyeOff, Loader2, X } from 'lucide-react'
|
||||
import { ChevronDown, ChevronRight, Eye, EyeOff, Loader2, Settings2, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MHintLabel from '../../components/MHintLabel'
|
||||
@@ -61,6 +61,58 @@ export function MAdminRow({
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A row of the addons screen: the icon tile, the name with its description
|
||||
* behind the info mark, and the switch. Addons and the instance options that
|
||||
* sit with them (live flight status, booking mails) share it.
|
||||
*/
|
||||
export function MAdminOptionRow({
|
||||
icon,
|
||||
title,
|
||||
hint,
|
||||
trailing,
|
||||
first = false,
|
||||
}: {
|
||||
icon: ReactNode
|
||||
title: string
|
||||
hint?: string
|
||||
trailing: ReactNode
|
||||
first?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
{/* overflow-hidden so a brand mark that fills the slot keeps its rounded corners. */}
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center overflow-hidden rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
{icon}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<MHintLabel label={title} hint={hint} />
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The last row under an addon that opens its settings: a gear, what it sets up,
|
||||
* an optional badge for what waits inside, and a chevron (AI, booking mails,
|
||||
* paddle water data).
|
||||
*/
|
||||
export function MAdminSetupRow({ label, onOpen, badge }: { label: string; onOpen: () => void; badge?: ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex w-full items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ps-[50px] text-start"
|
||||
>
|
||||
<Settings2 size={14} className="flex-none text-m-faint" />
|
||||
<span className="min-w-0 flex-1 truncate text-[length:calc(12px*var(--fs-scale-body,1))] font-bold text-m-ink">{label}</span>
|
||||
{badge}
|
||||
<ChevronRight size={15} className="flex-none text-m-faint rtl:rotate-180" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A description that keeps to two lines until it is tapped. On a phone the long
|
||||
* ones (a map provider's terms, how a loader decides) pushed every control off
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Inbox, Upload, Webhook, type LucideIcon } from 'lucide-react';
|
||||
import { Inbox, Mail, Upload, Webhook, type LucideIcon } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
@@ -15,15 +16,16 @@ import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import MSegmented from '../../components/MSegmented';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import MToggle from '../../components/MToggle';
|
||||
import {
|
||||
MAdminButton,
|
||||
MAdminCard,
|
||||
MAdminCardHead,
|
||||
MAdminField,
|
||||
MAdminInput,
|
||||
MAdminRow,
|
||||
MAdminOptionRow,
|
||||
MAdminSecretInput,
|
||||
MAdminSetupRow,
|
||||
MAdminSheetFrame,
|
||||
} from './MAdminUi';
|
||||
|
||||
interface PartProps {
|
||||
@@ -250,19 +252,23 @@ function Setup({ admin, form, t, locale }: PartProps & { locale: string }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the phone's admin settings, the same card as on
|
||||
* the desktop (useMailIngestAdmin): the switch, how mail arrives, the address
|
||||
* template, the AI allowance, the test and the status. Self-hosted only.
|
||||
* The booking mail import as a row of the phone's integration group, the same
|
||||
* as on the desktop (useMailIngestAdmin): the switch, and while it is on a row
|
||||
* to the sheet that sets it up (how mail arrives, the address template, the AI
|
||||
* allowance, the test and the status). Self-hosted only.
|
||||
*/
|
||||
export default function MMailIngestAdminCard() {
|
||||
export default function MMailIngestAdminCard({ first = false }: { first?: boolean }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
const [open, setOpen] = useState(false);
|
||||
const setupLabel = t('mailAdmin.setup');
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('mailAdmin.title')} hint={t('mailAdmin.hint')} />
|
||||
<MAdminRow
|
||||
title={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
<>
|
||||
<MAdminOptionRow
|
||||
icon={<Mail size={18} />}
|
||||
title={t('mailAdmin.title')}
|
||||
hint={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
|
||||
first={first}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={admin.enabled}
|
||||
@@ -272,7 +278,18 @@ export default function MMailIngestAdminCard() {
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</MAdminCard>
|
||||
{admin.enabled && admin.form && <MAdminSetupRow label={setupLabel} onOpen={() => setOpen(true)} />}
|
||||
{open && admin.enabled && admin.form && (
|
||||
<MSheet open onClose={() => setOpen(false)} variant="bottom" material="glass" ariaLabel={setupLabel}>
|
||||
<MAdminSheetFrame
|
||||
icon={<Mail size={19} strokeWidth={1.8} />}
|
||||
title={setupLabel}
|
||||
onClose={() => setOpen(false)}
|
||||
>
|
||||
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill'
|
||||
import { usePoiExplore } from '../../../../components/Map/usePoiExplore'
|
||||
import { useMergedMapPois } from '../../../../components/Map/useMergedMapPois'
|
||||
import { firstStopOfPlace, stageOf } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { stageMapData } from '../../../../components/Roadtrip/stageMap'
|
||||
import { stageConnectionIds, stageMapData } from '../../../../components/Roadtrip/stageMap'
|
||||
import { usePlanMapViewport } from '../../../../hooks/usePlanMapViewport'
|
||||
import { useIsDark } from '../../../../hooks/useIsDark'
|
||||
import { useTileUrl } from '../../../../hooks/useTileUrl'
|
||||
@@ -21,6 +21,7 @@ import { RT_ALT_BAR_LIFT } from '../roadtrip/useMRtAlternatives'
|
||||
import type { MMapAreaProps } from '../MTripShell'
|
||||
import type { Poi } from '../../../../components/Map/poiCategories'
|
||||
import type { ViewportPadding } from '../../../../utils/mapViewport'
|
||||
import { runsOnDay } from '../../../../utils/reservationRoutes'
|
||||
|
||||
/** One array, so an explore set switched off does not move every pin on the stage. */
|
||||
const NO_POIS: Poi[] = []
|
||||
@@ -215,6 +216,20 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
() => onStage ? stageMapData(planner.roadtripRoutes, stage, !!dayColorsOn) : null,
|
||||
[onStage, planner.roadtripRoutes, stage, dayColorsOn],
|
||||
)
|
||||
// The arcs the stage draws: its own rides and what was switched on for its day. The
|
||||
// all-days view keeps every ride of the drive.
|
||||
const stageConnections = useMemo(() => {
|
||||
if (!onStage) return null
|
||||
if (!stage) return planner.roadtripConnections
|
||||
const byId = new Map(planner.reservations.map(r => [r.id, r]))
|
||||
return stageConnectionIds(stage, planner.visibleConnections, id => {
|
||||
const r = byId.get(id)
|
||||
return !r || runsOnDay(r, planner.selectedDayId, planner.days)
|
||||
})
|
||||
}, [
|
||||
onStage, stage, planner.roadtripConnections, planner.reservations,
|
||||
planner.visibleConnections, planner.selectedDayId, planner.days,
|
||||
])
|
||||
|
||||
// Only what the stage carries, so a trip's other 200 pins stay off a screen that
|
||||
// is answering one question. Without a stage (the all-days view) every place a stored
|
||||
@@ -412,10 +427,11 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
// toggled on or not, the way the desktop map does it in road trip mode. The
|
||||
// ride's leg carries no geometry, so without this the road ended at the
|
||||
// departure terminal and picked up again at the arrival with nothing between.
|
||||
visibleConnectionIds={onStage ? planner.roadtripConnections : planner.visibleConnections}
|
||||
visibleConnectionIds={stageConnections ?? planner.visibleConnections}
|
||||
// The plan map shows one day, so a booking switched on for another day stays off
|
||||
// it until that day is picked, or the whole trip is. The switch itself is still
|
||||
// trip-wide. The stage keeps its seamed rides whatever day they were booked on.
|
||||
// trip-wide. The stage scopes its own set above, since its seamed rides stay on
|
||||
// it whatever day they were booked on.
|
||||
scopeConnectionsToDay={!onStage}
|
||||
// Transport overlay tap → the mobile transport detail sheet (desktop
|
||||
// routes this through mapTransportDetail into the day sidebar instead).
|
||||
|
||||
@@ -508,12 +508,15 @@ function TimelineHeader({ tl, dayLabel, openLabel, weatherLabel, onOpenDay, onOp
|
||||
stayLabel: (chip: HotelChip) => string
|
||||
}) {
|
||||
const WeatherIcon = weatherIconFor(tl.weather?.main)
|
||||
const [strip, setStrip] = useState<HTMLSpanElement | null>(null)
|
||||
const stripFade = useEdgeFade(strip)
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 border-b border-[color:var(--m-rowbr)] px-0.5 py-[9px]">
|
||||
{/* The one horizontal scroller inside the day pager. Nested scrolling is
|
||||
the browser's: while the chips overflow they pan first, and the pager
|
||||
takes over at their end or when they fit. */}
|
||||
<span className="flex min-w-0 items-center gap-1.5 overflow-x-auto">
|
||||
takes over at their end or when they fit. The ends fade while more
|
||||
waits behind them. */}
|
||||
<span ref={setStrip} className={`flex min-w-0 items-center gap-1.5 overflow-x-auto ${edgeFadeClass(stripFade)}`}>
|
||||
{/* The same glass controls as the edit header's: a round one when the day
|
||||
is already named above it, a pill with the day's name otherwise. */}
|
||||
<button
|
||||
@@ -532,20 +535,20 @@ function TimelineHeader({ tl, dayLabel, openLabel, weatherLabel, onOpenDay, onOp
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{/* A stay gives way before anything else in the header does: its name ends
|
||||
in an ellipsis rather than under the edge or the weather (the chip's
|
||||
label says it whole), and the time after it stays. */}
|
||||
{/* A stay's name stands whole: two stays and the weather rarely fit a
|
||||
phone, and a name cut to a letter or two said nothing, so the strip
|
||||
scrolls instead of squeezing the chips. */}
|
||||
{tl.hotelChips.map(chip => (
|
||||
<button
|
||||
key={chip.key}
|
||||
type="button"
|
||||
onClick={() => onOpenStay(chip)}
|
||||
aria-label={stayLabel(chip)}
|
||||
className={`${GLASS_CHIP} min-w-[4.5rem] shrink gap-[5px] px-2.5`}
|
||||
className={`${GLASS_CHIP} gap-[5px] px-2.5`}
|
||||
>
|
||||
<HotelChipIcon variant={chip.variant} />
|
||||
{/* Its own direction, so a Latin name in an Arabic header is cut at its end, not its start. */}
|
||||
<span dir="auto" className="min-w-0 truncate">{chip.name}</span>
|
||||
{/* Its own direction, so a Latin name reads the right way in an Arabic header. */}
|
||||
<span dir="auto">{chip.name}</span>
|
||||
{chip.time && <span className="flex-none tabular-nums text-m-muted">{chip.time.slice(0, 5)}</span>}
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -350,8 +350,11 @@ function TransitLegRows({ legs, t }: { legs: TransitLegDisplay[]; t: Translation
|
||||
const hasSeg = i < legs.length - 1
|
||||
return (
|
||||
<div key={i} className="flex gap-[9px]">
|
||||
<span className="w-9 flex-none pt-[9px] text-end font-geist text-[0.65625rem] font-semibold tabular-nums text-m-muted">
|
||||
{isWalk ? '' : leg.from?.time?.slice(0, 5) || ''}
|
||||
{/* A ride's departure stands beside its stops, its arrival at the
|
||||
bottom of its row, so the open card holds the whole journey (#3139). */}
|
||||
<span className="flex w-9 flex-none flex-col justify-between py-[9px] text-end font-geist text-[0.65625rem] font-semibold tabular-nums text-m-muted">
|
||||
<span>{isWalk ? '' : leg.from?.time?.slice(0, 5) || ''}</span>
|
||||
{!isWalk && leg.to?.time && <span className="text-m-faint">{leg.to.time.slice(0, 5)}</span>}
|
||||
</span>
|
||||
<div className="flex w-3 flex-none flex-col items-center">
|
||||
{isWalk ? (
|
||||
@@ -371,16 +374,16 @@ function TransitLegRows({ legs, t }: { legs: TransitLegDisplay[]; t: Translation
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 py-[7px]">
|
||||
{isWalk ? (
|
||||
<div className="truncate font-geist text-[0.6875rem] font-semibold text-m-muted">
|
||||
<div className="break-words font-geist text-[0.6875rem] font-semibold text-m-muted [overflow-wrap:anywhere]">
|
||||
<Footprints size={10} strokeWidth={2.2} className="me-1 inline-block align-[-1px]" />
|
||||
{[mins ? t('transit.min', { count: mins }) : '', t('transit.walkTo', { name: leg.to?.name || '' })]
|
||||
.filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<LineBadge leg={leg} className="flex-none" />
|
||||
<span className="truncate text-[0.78125rem] font-bold">
|
||||
<div className="flex items-start gap-1.5">
|
||||
<LineBadge leg={leg} className="mt-px flex-none" />
|
||||
<span dir="auto" className="min-w-0 break-words text-[0.78125rem] font-bold [overflow-wrap:anywhere]">
|
||||
{flowText([leg.from?.name, leg.to?.name].filter((n): n is string => !!n))}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -122,3 +122,15 @@ describe('MPlaceSheet ask the assistant', () => {
|
||||
expect(chatOf(useAssistantStore.getState(), 5).focus).toEqual({ placeIds: [42] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('MPlaceSheet header (#3140)', () => {
|
||||
it('lets a long place name wrap instead of cutting it to one line', () => {
|
||||
const longName = 'Broad Street Christmas Lights & Market'
|
||||
render(<MPlaceSheet planner={planner({ selectedPlace: buildPlace({ id: 7, name: longName, address: 'Broad Street, RG1 2AF, Reading' }) })} shell={shell} />)
|
||||
|
||||
const title = screen.getByText(longName)
|
||||
expect(title).not.toHaveClass('truncate')
|
||||
expect(title).toHaveClass('break-words')
|
||||
expect(screen.getByText('Broad Street, RG1 2AF, Reading').closest('div')).not.toHaveClass('truncate')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -208,12 +208,14 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</PlacePhotoGallery>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span dir="auto" className="min-w-0 truncate text-[1rem] font-bold leading-snug">{place.name}</span>
|
||||
<div className="flex items-start gap-1.5">
|
||||
{/* The sheet is where a place is read in full, so its name wraps
|
||||
onto as many lines as it needs, as on the desktop (#3140). */}
|
||||
<span dir="auto" className="min-w-0 break-words text-[1rem] font-bold leading-snug [overflow-wrap:anywhere]">{place.name}</span>
|
||||
{/* Accepted out of the traveller's own recordings — the same
|
||||
mark the desktop inspector carries. */}
|
||||
{place.source === 'dawarich' && (
|
||||
<span className="flex-none overflow-hidden rounded-[5px]">
|
||||
<span className="mt-[3px] flex-none overflow-hidden rounded-[5px]">
|
||||
<DawarichIcon size={15} />
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -236,8 +236,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<div className="flex-none px-[18px] pt-4">
|
||||
<TileHeader
|
||||
icon={<ResIcon size={19} strokeWidth={1.8} />}
|
||||
title={<span dir="auto" className="truncate text-[1rem]">{res.title}</span>}
|
||||
title={<span dir="auto" className="min-w-0 break-words text-[1rem] [overflow-wrap:anywhere]">{res.title}</span>}
|
||||
sub={subParts.length > 0 ? subParts.join(' · ') : undefined}
|
||||
subWrap
|
||||
onClose={shell.closeSheet}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
@@ -314,9 +315,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<span className="text-m-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span>
|
||||
) : (
|
||||
<>
|
||||
<span dir="auto" className="truncate">{leg.from?.name}</span>
|
||||
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span>
|
||||
<ArrowRight size={10} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
<span dir="auto" className="truncate">{leg.to?.name}</span>
|
||||
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -20,9 +20,6 @@ vi.mock('../components/Admin/BackupPanel', () => ({
|
||||
vi.mock('../components/Admin/GitHubPanel', () => ({
|
||||
default: () => <div data-testid="github-panel" />,
|
||||
}));
|
||||
vi.mock('../components/Admin/paddle/PaddleRegionsPanel', () => ({
|
||||
default: () => <div data-testid="paddle-regions-panel" />,
|
||||
}));
|
||||
|
||||
// AddonManager is stubbed but keeps its two callbacks reachable — the page owns
|
||||
// the optimistic toggle logic behind them.
|
||||
@@ -225,8 +222,6 @@ describe('AdminPage', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
|
||||
|
||||
expect(screen.getByTestId('addon-manager')).toBeInTheDocument();
|
||||
// The paddle water data sit under the addons; the panel hides itself while Tours is off.
|
||||
expect(screen.getByTestId('paddle-regions-panel')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import SchoolHolidayCatalog from '../components/Admin/SchoolHolidayCatalog'
|
||||
import PaddleRegionsPanel from '../components/Admin/paddle/PaddleRegionsPanel'
|
||||
import React, { Fragment } from 'react'
|
||||
import DevNotificationsPanel from '../components/Admin/DevNotificationsPanel'
|
||||
import DefaultUserSettingsTab from '../components/Admin/DefaultUserSettingsTab'
|
||||
@@ -166,10 +165,17 @@ function AdminPageDesktop(): React.ReactElement {
|
||||
onToggleBagTracking={toggleBagTracking}
|
||||
collabFeatures={collabFeatures}
|
||||
onToggleCollabFeature={toggleCollabFeature}
|
||||
// How the integrations reach the world: live flight status, booking mails.
|
||||
aside={<AdminSettingsTab admin={admin} t={t} part="features" />}
|
||||
// Live flight status follows the trips' flights; the booking mail import is
|
||||
// the operator's relay on a managed install.
|
||||
flightLive={{
|
||||
on: admin.flightLive,
|
||||
locked: admin.flightLiveLocked,
|
||||
managed,
|
||||
onToggle: () =>
|
||||
void admin.handleToggleAuthSetting('flight_live_enabled', !admin.flightLive, admin.setFlightLive),
|
||||
}}
|
||||
mailImport={!managed}
|
||||
/>
|
||||
<PaddleRegionsPanel />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -576,8 +576,9 @@ describe('JourneyPublicPage', () => {
|
||||
// broken-image glyph on every shared layout (#2341).
|
||||
it('FE-PAGE-PUBLICJOURNEY-023: a shared clip without a poster is a black tile, with a poster its poster', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bare = { id: 200, entry_id: 20, photo_id: 200, provider: 'local', asset_id: null, owner_id: null, file_path: 'journey/a.mp4', thumbnail_path: null, media_type: 'video', caption: null };
|
||||
const withPoster = { id: 201, entry_id: 21, photo_id: 201, provider: 'local', asset_id: null, owner_id: null, file_path: 'journey/b.mp4', thumbnail_path: 'journey/b.jpg', media_type: 'video', caption: null };
|
||||
// The share link carries no storage key: the server says which clip has no poster.
|
||||
const bare = { id: 200, photo_id: 200, media_type: 'video', caption: null, posterless: true };
|
||||
const withPoster = { id: 201, photo_id: 201, media_type: 'video', caption: null, posterless: false };
|
||||
const entry = (id: number, photo: typeof bare) => ({
|
||||
id, title: `Clip ${id}`, story: null, entry_date: '2026-03-15', entry_time: null,
|
||||
location_name: null, location_lat: null, location_lng: null, mood: null, weather: null, pros_cons: null,
|
||||
@@ -587,8 +588,8 @@ describe('JourneyPublicPage', () => {
|
||||
...mockJourneyData,
|
||||
entries: [entry(20, bare), entry(21, withPoster)],
|
||||
gallery: [
|
||||
{ ...bare, journey_id: 1, shared: 1, sort_order: 0, created_at: 0 },
|
||||
{ ...withPoster, journey_id: 1, shared: 1, sort_order: 1, created_at: 0 },
|
||||
{ ...bare, lat: null, lng: null, taken_at: null },
|
||||
{ ...withPoster, lat: null, lng: null, taken_at: null },
|
||||
],
|
||||
stats: { entries: 2, photos: 2, places: 0 },
|
||||
})));
|
||||
|
||||
@@ -39,7 +39,7 @@ vi.mock('../components/Journey/JournalBody', () => ({
|
||||
// ── Fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function photo(id: number): PublicEntry['photos'][number] {
|
||||
return { id, entry_id: 1, photo_id: id * 10, caption: `caption ${id}`, provider: 'local' };
|
||||
return { id, photo_id: id * 10, caption: `caption ${id}`, posterless: false };
|
||||
}
|
||||
|
||||
function buildEntry(over: Partial<PublicEntry> = {}): PublicEntry {
|
||||
|
||||
@@ -13,13 +13,12 @@ import AdminSettingsTab from './AdminSettingsTab';
|
||||
type Spy = ReturnType<typeof vi.fn>;
|
||||
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
|
||||
|
||||
/** The three tabs the settings are split into (security, services, features), on one page. */
|
||||
/** The two tabs the settings are split into (security, services), on one page. */
|
||||
function AllParts({ admin, t }: { admin: AdminHook; t: ReturnType<typeof useTranslation>['t'] }) {
|
||||
return (
|
||||
<>
|
||||
<AdminSettingsTab admin={admin} t={t} part="security" />
|
||||
<AdminSettingsTab admin={admin} t={t} part="services" />
|
||||
<AdminSettingsTab admin={admin} t={t} part="features" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react'
|
||||
import {
|
||||
AlertTriangle, CheckCircle, Compass, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn,
|
||||
Plane, RefreshCw, Save, XCircle,
|
||||
RefreshCw, Save, XCircle,
|
||||
} from 'lucide-react'
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch'
|
||||
import CustomSelect from '../../components/shared/CustomSelect'
|
||||
@@ -14,7 +14,6 @@ import GoogleOptions from './GoogleOptions'
|
||||
import GoogleDailyLimitRow from '../../components/Admin/GoogleDailyLimitRow'
|
||||
import ProviderBlock from './ProviderBlock'
|
||||
import TrekApiCard from './TrekApiCard'
|
||||
import MailIngestAdminCard from '../../components/Admin/mailIngest/MailIngestAdminCard'
|
||||
import PlaceContribPanel from '../../components/Admin/PlaceContribPanel'
|
||||
import { useAdminSettingsActions } from '../../components/Admin/useAdminSettingsActions'
|
||||
import { placesGoogleOnlyHint } from '../../utils/placeSource'
|
||||
@@ -25,11 +24,10 @@ interface AdminSettingsTabProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
/**
|
||||
* Which tab this renders: sign-in and its safety (security), what the
|
||||
* install talks to outside (services), or the setup of the features the
|
||||
* addons tab switches on (features).
|
||||
* Which tab this renders: sign-in and its safety (security) or what the
|
||||
* install talks to outside (services).
|
||||
*/
|
||||
part: 'security' | 'services' | 'features'
|
||||
part: 'security' | 'services'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,7 +124,6 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
|
||||
oidcConfig, setOidcConfig, savingOidc,
|
||||
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
|
||||
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, oidcAutoRedirect, setOidcAutoRedirect,
|
||||
flightLive, setFlightLive, flightLiveLocked,
|
||||
envOverrideOidcOnly, oidcConfigured, requireMfa,
|
||||
passkeyLogin, setPasskeyLogin, passkeyConfigured,
|
||||
webauthnRpId, setWebauthnRpId, webauthnOrigins, setWebauthnOrigins, savingWebauthn, handleSaveWebauthn,
|
||||
@@ -395,34 +392,6 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
|
||||
)}
|
||||
</>
|
||||
)
|
||||
const flightCard = (
|
||||
<>
|
||||
{/* Live flight status: open ADS-B data, no key, on by default; the admin may keep it off. */}
|
||||
<SettingsCard icon={Plane} title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('flightLive.adminToggle')}
|
||||
hint={flightLiveLocked ? t('flightLive.envLocked') : undefined}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={flightLive}
|
||||
label={t('flightLive.adminToggle')}
|
||||
disabled={flightLiveLocked}
|
||||
onToggle={() => void handleToggleAuthSetting('flight_live_enabled', !flightLive, setFlightLive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
</SettingsCard>
|
||||
</>
|
||||
)
|
||||
const mailCard = (
|
||||
<>
|
||||
{/* Booking mail import: how forwarded booking mails reach this install. On a managed
|
||||
install the operator runs the TREK Cloud relay, so the card is not shown there. */}
|
||||
{!managed && <MailIngestAdminCard />}
|
||||
</>
|
||||
)
|
||||
const servicesCard = (
|
||||
<>
|
||||
{/* Place search and routing: TREK's own services first, then which provider
|
||||
@@ -714,16 +683,9 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
|
||||
)
|
||||
|
||||
// What used to be one "Settings" tab, split by what an admin comes for:
|
||||
// who may sign in and how (security), what the install talks to outside
|
||||
// (services), and how the features in the addons tab are set up there.
|
||||
if (part === 'features') {
|
||||
return (
|
||||
<>
|
||||
{flightCard}
|
||||
{mailCard}
|
||||
</>
|
||||
)
|
||||
}
|
||||
// who may sign in and how (security) and what the install talks to outside
|
||||
// (services). Live flight status and the booking mail import are rows of the
|
||||
// addons tab's cards now.
|
||||
if (part === 'services') {
|
||||
// Place search and the services on the left, the keys and file types on the right.
|
||||
return (
|
||||
|
||||
@@ -260,6 +260,13 @@ describe('posterlessVideo (#2341)', () => {
|
||||
expect(posterlessVideo({ provider: 'local', thumbnail_path: null })).toBe(false);
|
||||
expect(posterlessVideo({ media_type: 'video', provider: 'immich', thumbnail_path: null })).toBe(false);
|
||||
});
|
||||
|
||||
it('takes the answer a shared journey sends, which carries no storage key', () => {
|
||||
expect(posterlessVideo({ media_type: 'video', posterless: true })).toBe(true);
|
||||
expect(posterlessVideo({ media_type: 'video', posterless: false })).toBe(false);
|
||||
// The flag wins over the columns, so a public photo never needs them.
|
||||
expect(posterlessVideo({ media_type: 'video', provider: 'local', thumbnail_path: null, posterless: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchRemainingProviderPages (#1587)', () => {
|
||||
|
||||
@@ -95,12 +95,17 @@ export function photoUrl(p: { photo_id: number }, size: 'thumbnail' | 'original'
|
||||
* purpose rather than streaming the whole file, and an <img> pointed at it
|
||||
* shows the broken-image glyph (#2341). A provider clip is not one of these,
|
||||
* its poster comes from the provider whether or not a local path is recorded.
|
||||
*
|
||||
* A shared journey carries no storage keys, so the server answers the question
|
||||
* itself there (`posterless`).
|
||||
*/
|
||||
export function posterlessVideo(p: {
|
||||
media_type?: string | null;
|
||||
provider?: string | null;
|
||||
thumbnail_path?: string | null;
|
||||
posterless?: boolean;
|
||||
}): boolean {
|
||||
if (typeof p.posterless === 'boolean') return p.posterless;
|
||||
return p.media_type === 'video' && p.provider === 'local' && !p.thumbnail_path;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,68 +4,61 @@
|
||||
* presentational page.
|
||||
*/
|
||||
|
||||
/**
|
||||
* An entry as the share link sends it (`journeyPublicEntrySchema` in
|
||||
* @trek/shared). A map-only share leaves out the story fields and the photos.
|
||||
*/
|
||||
export interface PublicEntry {
|
||||
id: number
|
||||
type?: string | null
|
||||
sort_order?: number | null
|
||||
title?: string | null
|
||||
story?: string | null
|
||||
entry_date: string
|
||||
entry_time?: string | null
|
||||
location_name?: string | null
|
||||
location_lat?: number | null
|
||||
location_lng?: number | null
|
||||
mood?: string | null
|
||||
weather?: string | null
|
||||
pros_cons?: { pros: string[]; cons: string[] } | null
|
||||
photos: PublicPhoto[]
|
||||
id: number;
|
||||
type?: string | null;
|
||||
sort_order?: number | null;
|
||||
title?: string | null;
|
||||
story?: string | null;
|
||||
entry_date: string;
|
||||
entry_time?: string | null;
|
||||
location_name?: string | null;
|
||||
location_lat?: number | null;
|
||||
location_lng?: number | null;
|
||||
country_code?: string | null;
|
||||
mood?: string | null;
|
||||
weather?: string | null;
|
||||
tags?: string[];
|
||||
pros_cons?: { pros: string[]; cons: string[] } | null;
|
||||
photos: PublicPhoto[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A photo of a shared journey (`journeyPublicPhotoSchema`). It carries no
|
||||
* storage key or asset id: the bytes are fetched by `photo_id` through the
|
||||
* share token.
|
||||
*/
|
||||
export interface PublicPhoto {
|
||||
id: number
|
||||
entry_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
id: number;
|
||||
photo_id: number;
|
||||
caption?: string | null;
|
||||
// 'image' (default) or 'video' (#823)
|
||||
media_type?: string | null
|
||||
/** Null on a local clip whose poster frame could not be grabbed; the page
|
||||
* draws a marked tile instead of an <img> then (#2341). */
|
||||
thumbnail_path?: string | null
|
||||
duration_ms?: number | null
|
||||
media_type?: string | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
duration_ms?: number | null;
|
||||
/** A clip whose poster frame could not be grabbed; the page draws a plain tile instead of an <img> (#2341). */
|
||||
posterless?: boolean;
|
||||
}
|
||||
|
||||
export interface PublicGalleryPhoto {
|
||||
id: number
|
||||
journey_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
// 'image' (default) or 'video' (#823)
|
||||
media_type?: string | null
|
||||
/** Null on a local clip whose poster frame could not be grabbed; the gallery
|
||||
* draws a marked tile instead of an <img> then (#2341). */
|
||||
thumbnail_path?: string | null
|
||||
duration_ms?: number | null
|
||||
/** Where and when the picture was taken (#1614). Absent for most photos, and the
|
||||
export interface PublicGalleryPhoto extends PublicPhoto {
|
||||
/** When and where the picture was taken (#1614). Absent for most photos, and the
|
||||
* coordinates are withheld entirely unless the owner shared the map. */
|
||||
taken_at?: string | null
|
||||
lat?: number | null
|
||||
lng?: number | null
|
||||
taken_at?: string | null;
|
||||
lat?: number | null;
|
||||
lng?: number | null;
|
||||
}
|
||||
|
||||
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
|
||||
const groups = new Map<string, PublicEntry[]>()
|
||||
const groups = new Map<string, PublicEntry[]>();
|
||||
for (const e of entries) {
|
||||
const d = e.entry_date
|
||||
if (!groups.has(d)) groups.set(d, [])
|
||||
groups.get(d)!.push(e)
|
||||
const d = e.entry_date;
|
||||
if (!groups.has(d)) groups.set(d, []);
|
||||
groups.get(d)!.push(e);
|
||||
}
|
||||
return groups
|
||||
return groups;
|
||||
}
|
||||
|
||||
@@ -61,9 +61,6 @@ vi.mock('../../../../src/mobile/screens/admin/MAdminStoragePanel', () => ({
|
||||
}));
|
||||
|
||||
// The addon manager is reduced to the two controls MAdmin wires itself.
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminPaddleRegionsPanel', () => ({
|
||||
default: () => <div data-testid="paddle-regions-panel" />,
|
||||
}));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminAddonManager', () => ({
|
||||
default: ({
|
||||
bagTrackingEnabled,
|
||||
@@ -232,7 +229,8 @@ describe('MAdmin', () => {
|
||||
expect(screen.getByTestId('category-manager')).toBeInTheDocument();
|
||||
|
||||
await openSection('Addons');
|
||||
expect(screen.getByTestId('paddle-regions-panel')).toBeInTheDocument();
|
||||
// The paddle water data, live flights and booking mails are rows inside the addon groups now.
|
||||
expect(screen.getByTestId('bag-state')).toBeInTheDocument();
|
||||
|
||||
await openSection('Plugins');
|
||||
expect(screen.getByTestId('plugins-panel')).toBeInTheDocument();
|
||||
|
||||
@@ -8,6 +8,7 @@ import { buildSettings } from '../../../helpers/factories';
|
||||
import { useSettingsStore } from '../../../../src/store/settingsStore';
|
||||
import { useAddonStore } from '../../../../src/store/addonStore';
|
||||
import { ToastContainer } from '../../../../src/components/shared/Toast';
|
||||
import { mailIngestRepo } from '../../../../src/repo/mailIngestRepo';
|
||||
import MAdminAddonManager from '../../../../src/mobile/screens/admin/MAdminAddonManager';
|
||||
|
||||
interface AddonFixture {
|
||||
@@ -571,4 +572,26 @@ describe('MAdminAddonManager', () => {
|
||||
await user.click(toggle);
|
||||
await waitFor(() => expect(puts).toEqual([{ enabled: true }]));
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-038: live flight status is a row of the trip group, switched there and locked by the environment', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Lists', type: 'trip', enabled: true })]));
|
||||
const onToggle = vi.fn();
|
||||
const { unmount } = render(<MAdminAddonManager flightLive={{ on: false, locked: false, managed: false, onToggle }} />);
|
||||
await userEvent.click(await screen.findByRole('switch', { name: 'Follow booked flights live' }));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
|
||||
render(<MAdminAddonManager flightLive={{ on: true, locked: true, managed: false, onToggle }} />);
|
||||
expect(await screen.findByRole('switch', { name: 'Follow booked flights live' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-AADD-039: the booking mail import is a row of the integration group whose setup opens in a sheet', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
vi.spyOn(mailIngestRepo, 'adminSettings').mockResolvedValue({ mail_ingest_enabled: 'true' });
|
||||
vi.spyOn(mailIngestRepo, 'adminStatus').mockRejectedValue(new Error('no status'));
|
||||
render(<MAdminAddonManager mailImport />);
|
||||
expect(await screen.findByText('Booking mail import')).toBeInTheDocument();
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Set up mail import' }));
|
||||
expect(await screen.findByText('How mail arrives')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-MOB-APAD-001 to FE-MOB-APAD-010: the paddle regions card of the phone admin, drawn from a
|
||||
// FE-MOB-APAD-001 to FE-MOB-APAD-011: the paddle regions row and sheet of the phone admin, drawn from a
|
||||
// controlled usePaddleRegionsAdmin (the hook has its own test).
|
||||
import type { PaddleRegion, PaddleRegionPending } from '@trek/shared';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
@@ -39,7 +39,7 @@ const REQUEST: PaddleRegionPending = {
|
||||
declined: false,
|
||||
} as PaddleRegionPending;
|
||||
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}) {
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}, { open = true } = {}) {
|
||||
const state: Admin = {
|
||||
toursOn: true,
|
||||
offline: false,
|
||||
@@ -64,9 +64,16 @@ function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> =
|
||||
};
|
||||
hook.usePaddleRegionsAdmin.mockReturnValue(state);
|
||||
render(<MAdminPaddleRegionsPanel />);
|
||||
// The row under Tours opens the sheet that holds everything below.
|
||||
if (state.toursOn && open) fireEvent.click(setupRow());
|
||||
return state;
|
||||
}
|
||||
|
||||
/** The row under the Tours addon that opens the sheet, with its count beside the title. */
|
||||
function setupRow(): HTMLElement {
|
||||
return screen.getAllByRole('button', { name: /^Paddle water data/ })[0];
|
||||
}
|
||||
|
||||
describe('MAdminPaddleRegionsPanel', () => {
|
||||
it('FE-MOB-APAD-001: shows nothing while the Tours addon is off', () => {
|
||||
show({ toursOn: false });
|
||||
@@ -164,4 +171,20 @@ describe('MAdminPaddleRegionsPanel', () => {
|
||||
fireEvent.click(within(question).getByRole('button', { name: 'Remove' }));
|
||||
expect(state.confirmRemove).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-APAD-011: the row counts the open requests before the regions, and opens the sheet only when tapped', () => {
|
||||
show(
|
||||
{
|
||||
regions: [region(), region({ id: 'saale', name: 'Saale' })],
|
||||
requests: [REQUEST, { ...REQUEST, id: 'x', declined: true }],
|
||||
},
|
||||
{},
|
||||
{ open: false }
|
||||
);
|
||||
expect(within(setupRow()).getByText('1')).toBeInTheDocument();
|
||||
expect(within(setupRow()).queryByText('2')).toBeNull();
|
||||
expect(screen.queryByTestId('paddle-region-row')).toBeNull();
|
||||
fireEvent.click(setupRow());
|
||||
expect(screen.getAllByTestId('paddle-region-row')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ vi.mock('../../../../src/mobile/screens/admin/MAdminServiceQuota', () => ({ defa
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminPlaceContrib', () => ({ default: () => <div data-testid="place-contrib" /> }));
|
||||
vi.mock('../../../../src/mobile/screens/admin/MAdminGoogleDailyLimit', () => ({ default: () => <div data-testid="google-daily-limit" /> }));
|
||||
|
||||
const PARTS = ['security', 'services', 'features'] as const;
|
||||
const PARTS = ['security', 'services'] as const;
|
||||
|
||||
/** All three sections at once, so each card's behaviour is tested wherever it now lives. */
|
||||
function AllParts({ admin, t }: { admin: AdminHook; t: ReturnType<typeof useTranslation>['t'] }) {
|
||||
@@ -114,12 +114,9 @@ describe('MAdminSettingsSection', () => {
|
||||
expect(screen.getByText('API Keys')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Allowed File Types').length).toBeGreaterThan(0);
|
||||
expect(screen.queryByText('Authentication Methods')).not.toBeInTheDocument();
|
||||
// Live flight status is a row of the addons' trip group now, in neither section.
|
||||
expect(screen.queryByText('Live flight status')).not.toBeInTheDocument();
|
||||
services.unmount();
|
||||
|
||||
render(<PartHarness admin={admin} part="features" />);
|
||||
expect(screen.getByText('Live flight status')).toBeInTheDocument();
|
||||
expect(screen.queryByText('API Keys')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Danger Zone')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-ASET-026: a managed install keeps the danger zone and the passkey domain to its operator', () => {
|
||||
|
||||
@@ -218,13 +218,16 @@ describe('MPlanTimeline', () => {
|
||||
weatherTemp: 17,
|
||||
})
|
||||
|
||||
// The name gives way with an ellipsis; the time after it stays, with no dot between.
|
||||
// The name stands whole, never cut to a few letters: the chip keeps its
|
||||
// size and the strip scrolls instead. The time follows with no dot between.
|
||||
const sacher = screen.getByText('Hotel Sacher')
|
||||
expect(sacher).toHaveClass('truncate', 'min-w-0')
|
||||
// In an Arabic header a Latin name keeps its own direction, so the ellipsis lands at its end.
|
||||
expect(sacher).not.toHaveClass('truncate')
|
||||
// In an Arabic header a Latin name keeps its own direction.
|
||||
expect(sacher).toHaveAttribute('dir', 'auto')
|
||||
expect(sacher.closest('button')).toHaveTextContent('Hotel Sacher11:00')
|
||||
expect(sacher.closest('button')).toHaveClass('shrink')
|
||||
expect(sacher.closest('button')).toHaveClass('flex-none')
|
||||
expect(sacher.closest('button')).not.toHaveClass('shrink')
|
||||
expect(sacher.closest('button')?.parentElement).toHaveClass('overflow-x-auto')
|
||||
expect(screen.getByText('Ryokan Kyoto').closest('button')).toHaveTextContent('Ryokan Kyoto15:00')
|
||||
expect(screen.getByText('Capsule Tokyo')).toBeInTheDocument()
|
||||
expect(screen.getByText('17°')).toBeInTheDocument()
|
||||
|
||||
@@ -327,6 +327,18 @@ describe('TransitRow', () => {
|
||||
expect(screen.getByText('transit.min:1 · transit.walkTo:Hotel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-MOB-PLROW-046: the expanded legs show every stop name in full and each ride arrival time (#3139)', () => {
|
||||
const { container } = render(<TransitRow {...base} open />)
|
||||
|
||||
const ride = screen.getByText('Shibuya Sta. → Asakusa Sta.')
|
||||
expect(ride).not.toHaveClass('truncate')
|
||||
expect(ride).toHaveClass('break-words')
|
||||
expect(screen.getByText('transit.min:4 · transit.walkTo:Shibuya Sta.')).not.toHaveClass('truncate')
|
||||
expect(screen.getByText('10:30')).toBeInTheDocument()
|
||||
// the departure keeps its place beside the arrival
|
||||
expect(container.textContent).toContain('10:05')
|
||||
})
|
||||
|
||||
it('FE-MOB-PLROW-024: tapping the header toggles the row', () => {
|
||||
const onToggle = vi.fn()
|
||||
render(<TransitRow {...base} open={false} onToggle={onToggle} />)
|
||||
|
||||
@@ -144,6 +144,24 @@ describe('MTransportSheet', () => {
|
||||
expect(screen.getByText('Prater')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-025: the title and every stop name wrap instead of being cut off (#3139)', () => {
|
||||
const res = {
|
||||
...FLIGHT, type: 'transit', title: 'Basingstoke station → Reading station', endpoints: [], metadata: {
|
||||
transit: {
|
||||
legs: [{
|
||||
mode: 'RAIL', line: 'CrossCountry', duration: 1260,
|
||||
from: { name: 'Basingstoke', time: '12:48' }, to: { name: 'Reading', time: '13:09' },
|
||||
}],
|
||||
},
|
||||
},
|
||||
} as unknown as Reservation
|
||||
render(<MTransportSheet planner={makePlanner({ reservations: [res] })} shell={makeShell()} />)
|
||||
expect(screen.getByText('Basingstoke station → Reading station')).not.toHaveClass('truncate')
|
||||
expect(screen.getByText('Basingstoke')).not.toHaveClass('truncate')
|
||||
expect(screen.getByText('Reading')).not.toHaveClass('truncate')
|
||||
expect(screen.getByText('Reading')).toHaveClass('break-words')
|
||||
})
|
||||
|
||||
it('FE-MOB-TRSH-010: shows the pending status and the booking code unblurred by default', () => {
|
||||
render(<MTransportSheet planner={makePlanner()} shell={makeShell()} />)
|
||||
expect(screen.getByText('Pending')).toBeInTheDocument()
|
||||
|
||||
@@ -25,7 +25,7 @@ fi
|
||||
cd /app/server
|
||||
|
||||
# Already started as a non-root user (Kubernetes runAsUser, docker --user): there
|
||||
# is nothing to chown and no privilege to drop, and gosu would only fail to switch
|
||||
# is nothing to chown and no privilege to drop, and setpriv would only fail to switch
|
||||
# users. Run Node as whoever we are; the volumes are that user's to provide.
|
||||
if [ "$(id -u)" != "0" ]; then
|
||||
exec node --require tsconfig-paths/register dist/index.js
|
||||
@@ -42,7 +42,7 @@ fi
|
||||
# Troubleshooting page of the wiki has the one-off chown for that.
|
||||
#
|
||||
# Only the owning user has to be node, because that is what Node runs as and
|
||||
# what gosu leaves it with. The group is left to whoever set it: a Kubernetes
|
||||
# what the drop below leaves it with. The group is left to whoever set it: a Kubernetes
|
||||
# fsGroup other than 1000 gives every file its own gid, and taking that back
|
||||
# here would make the kubelet's OnRootMismatch walk the volume again on the
|
||||
# next start, and this script after it, every time. Only a root group (a fresh
|
||||
@@ -65,4 +65,11 @@ for dir in /app/data /app/uploads; do
|
||||
fi
|
||||
done
|
||||
|
||||
exec gosu node node --require tsconfig-paths/register dist/index.js
|
||||
# setpriv, not gosu: gosu is Go, and Go changes the ids of a process by signalling
|
||||
# every runtime thread with a realtime signal and spinning until each one has
|
||||
# answered. A host whose security module drops that signal inside the container
|
||||
# (AppArmor on recent Ubuntu under Podman) left it spinning at full CPU, before
|
||||
# Node had printed a line (#3135). setpriv is single-threaded C and makes the same
|
||||
# id changes without any signal. It leaves HOME alone, which gosu set from passwd.
|
||||
export HOME=/home/node
|
||||
exec setpriv --reuid=node --regid=node --init-groups -- node --require tsconfig-paths/register dist/index.js
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-explicit-any": 84,
|
||||
"@typescript-eslint/no-explicit-any": 81,
|
||||
"@typescript-eslint/no-non-null-assertion": 263,
|
||||
"@typescript-eslint/no-require-imports": 18,
|
||||
"@typescript-eslint/no-unsafe-function-type": 1,
|
||||
|
||||
@@ -365,7 +365,6 @@
|
||||
"route-usage -> AppSettings (owned by settings)",
|
||||
"school-holidays -> VacayHolidayCalendars (owned by vacay)",
|
||||
"share -> BudgetItems (owned by budget)",
|
||||
"share -> Categories (owned by categories)",
|
||||
"share -> CollabMessages (owned by collab)",
|
||||
"share -> DayAssignments (owned by assignments)",
|
||||
"share -> DayNotes (owned by day-notes)",
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"src/nest/help/help.controller.ts": 4,
|
||||
"src/nest/integrations/airtrail.controller.ts": 6,
|
||||
"src/nest/integrations/dawarich.controller.ts": 15,
|
||||
"src/nest/journey/journey-public.controller.ts": 3,
|
||||
"src/nest/journey/journey-public.controller.ts": 2,
|
||||
"src/nest/journey/journey.controller.ts": 20,
|
||||
"src/nest/llm-parse/llm-capabilities.controller.ts": 1,
|
||||
"src/nest/llm-parse/llm-local.controller.ts": 2,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"scripts/db-call-graph.mjs": 1036,
|
||||
"scripts/generate-entities.ts": 2259,
|
||||
"src/db/repositories/Places.repository.ts": 1435,
|
||||
"src/db/repositories/Places.repository.ts": 1432,
|
||||
"src/db/repositories/Reservations.repository.ts": 1550,
|
||||
"src/db/repositories/Trips.repository.ts": 1120,
|
||||
"src/db/repositories/Users.repository.ts": 1421,
|
||||
"src/nest/atlas/atlas.service.ts": 1174,
|
||||
"src/nest/atlas/atlas.service.ts": 1166,
|
||||
"src/nest/auth/auth.service.ts": 1141,
|
||||
"src/nest/budget/budget.service.ts": 1607,
|
||||
"src/nest/collections/collections.service.ts": 1414,
|
||||
|
||||
@@ -33,7 +33,6 @@
|
||||
"src/nest/integrations/dawarich-sync.service.ts#DawarichSyncService.syncUserOnce": 3,
|
||||
"src/nest/journey/journey.controller.ts#JourneyController.uploadEntryPhotos": 4,
|
||||
"src/nest/memories/photo-resolver.service.ts#PhotoResolverService.streamCachedThumbnail": 3,
|
||||
"src/nest/memories/photo-resolver.service.ts#PhotoResolverService.streamPhoto": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService._fetchAllSynologyAlbums": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService._getSynologySession": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService._requestSynologyApi": 3,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { PUBLIC_ROUTE_ALLOW_LIST, validateRouteGuards } from './nest/common/vali
|
||||
import { DatabaseLifecycle } from './nest/database/database-lifecycle.service';
|
||||
import { withRequestContext } from './nest/database/request-context';
|
||||
import { MANAGED_PUBLIC_ROUTES } from './nest/managed/managed-ext.module';
|
||||
import { PublicMediaService } from './nest/memories/public-media.service';
|
||||
import { setupApiDocs } from './nest/platform/api-docs';
|
||||
import { MCP_METADATA_MIDDLEWARE } from './nest/platform/mcp-metadata.middleware';
|
||||
import { applyPlatformUploads, applyPlatformStatic } from './nest/platform/platform.routes';
|
||||
@@ -146,7 +147,8 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
// Same pre-init consumption bridge as httpConfig above: the StorageService
|
||||
// instance is resolvable before init, and the handlers only *register* here —
|
||||
// per-request resolution runs after app.init() completed the registry load.
|
||||
applyPlatformUploads(instance, app.get(StorageService), orm);
|
||||
// PublicMediaService hands anonymous viewers the location-free copies.
|
||||
applyPlatformUploads(instance, app.get(StorageService), orm, app.get(PublicMediaService));
|
||||
// The SDK discovery router (+ its addon gate). Container-built so its deps
|
||||
// are injected (same pre-init consumption bridge as httpConfig above), but
|
||||
// applied here as a PATHLESS app.use: the SDK router matches absolute
|
||||
|
||||
@@ -21,18 +21,6 @@ export class CategoriesRepository extends TrekRepository<Categories> {
|
||||
return categories.map((category) => toRow(category) as CategoryRow);
|
||||
}
|
||||
|
||||
/**
|
||||
* `share.service.ts:396` SH15 (`getSharedTripData`) — `SELECT * FROM
|
||||
* categories`, no `ORDER BY` (unlike `list()` above, which adds `ORDER BY
|
||||
* name ASC` for the authenticated `/api/categories` list — the legacy
|
||||
* public-share statement never sorted). Unscoped by trip on purpose: "a
|
||||
* shared global pool", the same statement the authed list reads from.
|
||||
*/
|
||||
async listAllUnordered(): Promise<CategoryRow[]> {
|
||||
const categories = await this.find({});
|
||||
return categories.map((category) => toRow(category) as CategoryRow);
|
||||
}
|
||||
|
||||
/**
|
||||
* PL33 (`PlacesService.importKmlPlaces`) — `SELECT id, name FROM
|
||||
* categories`, the id/name-only projection the KML importer folds into
|
||||
|
||||
@@ -231,6 +231,11 @@ export class JourneysRepository extends TrekRepository<Journeys> {
|
||||
await this.nativeUpdate({ id }, { cover_image });
|
||||
}
|
||||
|
||||
/** Whether some journey names one of these stored values as its cover (the anonymous /uploads/journey gate). */
|
||||
async isCoverImage(values: string[]): Promise<boolean> {
|
||||
return (await this.count({ cover_image: { $in: values } })) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* JG24 — `updateJourney`'s dynamic SET (R6, `presenceSet`). The SERVICE
|
||||
* resolves every field to its final bound value first (the `ALLOWED_STATUSES`
|
||||
|
||||
@@ -1108,21 +1108,18 @@ export class PlacesRepository extends TrekRepository<Places> {
|
||||
}
|
||||
|
||||
/**
|
||||
* AT41 (`AtlasService#getTravelStats`) — `SELECT DISTINCT p.address,
|
||||
* p.lat, p.lng, pr.region_name FROM places p JOIN trips t ON p.trip_id =
|
||||
* t.id LEFT JOIN trip_members tm ON t.id = tm.trip_id LEFT JOIN
|
||||
* place_regions pr ON pr.place_id = p.id WHERE t.user_id = ? OR tm.user_id
|
||||
* = ?`. The resolved region rides along so `cityFromAddress` can tell the
|
||||
* city apart from the region sitting right above it in the same address
|
||||
* (#1115) — unchanged from the legacy projection.
|
||||
* AT41 (`AtlasService#placeFootprint`): one row per place on a trip the user owns
|
||||
* or is a member of. `p.id` keeps the DISTINCT to undoing the trip_members fan-out,
|
||||
* so places sharing an address and coordinates stay apart (#3137). The resolved
|
||||
* region rides along so `cityFromAddress` can skip it (#1115).
|
||||
*/
|
||||
async listAddressesForUser(user_id: number): Promise<{ address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
|
||||
async listAddressesForUser(user_id: number): Promise<{ id: number; address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
|
||||
return await this.kysely<PlacesAddressesForUserKyselyDB>()
|
||||
.selectFrom('places as p')
|
||||
.innerJoin('trips as t', 't.id', 'p.trip_id')
|
||||
.leftJoin('trip_members as tm', 'tm.trip_id', 't.id')
|
||||
.leftJoin('place_regions as pr', 'pr.place_id', 'p.id')
|
||||
.select(['p.address', 'p.lat', 'p.lng', 'pr.region_name'])
|
||||
.select(['p.id', 'p.address', 'p.lat', 'p.lng', 'pr.region_name'])
|
||||
.distinct()
|
||||
.where((eb) => eb.or([eb('t.user_id', '=', user_id), eb('tm.user_id', '=', user_id)]))
|
||||
.execute();
|
||||
|
||||
@@ -136,8 +136,8 @@ export interface CalendarReservationRow extends ReservationAllColumnsRow {
|
||||
type CalendarReservationKyselyDB = Pick<DB, 'reservations' | 'places' | 'day_accommodations' | 'days'>;
|
||||
|
||||
/**
|
||||
* CL4 (`CalendarService.buildTripCalendar`'s assignment read, for every dated
|
||||
* day at once) — `SELECT da.*, p.name as place_name, p.address as
|
||||
* CL4 (`CalendarService.buildTripCalendar`'s assignment read, for every day
|
||||
* of the trip at once, undated ones for a linked booking's zone) — `SELECT da.*, p.name as place_name, p.address as
|
||||
* place_address, p.lat as place_lat, p.lng as place_lng, COALESCE(da.stay_minutes,
|
||||
* p.duration_minutes) as place_duration_minutes, COALESCE(da.assignment_time, p.place_time) as
|
||||
* effective_time, COALESCE(da.assignment_end_time, p.end_time) as
|
||||
|
||||
@@ -50,6 +50,12 @@ export class TrekPhotosRepository extends TrekRepository<TrekPhotos> {
|
||||
return row ? { id: row.id } : null;
|
||||
}
|
||||
|
||||
/** Whether some row holds one of `paths` as its file or its poster: the journey entry media. */
|
||||
async referencesLocalPath(paths: string[]): Promise<boolean> {
|
||||
const count = await this.count({ $or: [{ file_path: { $in: paths } }, { thumbnail_path: { $in: paths } }] });
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
/** PH5 — `INSERT INTO trek_photos (provider, file_path, thumbnail_path, width, height, media_type, duration_ms)`, always `provider = 'local'`. */
|
||||
async insertLocal(data: {
|
||||
file_path: string;
|
||||
|
||||
@@ -44,7 +44,6 @@ const ENTRY_FIELDS = [
|
||||
'location_lng',
|
||||
'mood',
|
||||
'weather',
|
||||
'visibility',
|
||||
'type',
|
||||
'is_draft',
|
||||
'tags',
|
||||
@@ -52,7 +51,7 @@ const ENTRY_FIELDS = [
|
||||
] as const;
|
||||
|
||||
/** The states of an entry an update can set, each a row of its own when it changes. */
|
||||
const STATE_FIELDS = ['visibility', 'mood', 'weather', 'type', 'is_draft', 'stats_excluded', 'dismissed'] as const;
|
||||
const STATE_FIELDS = ['mood', 'weather', 'type', 'is_draft', 'stats_excluded', 'dismissed'] as const;
|
||||
const FLAG_FIELDS: ReadonlySet<string> = new Set(['is_draft', 'stats_excluded', 'dismissed']);
|
||||
|
||||
/** The journal the open trip shows, as `get_trip_journal` answers. */
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
compareCodeUnits,
|
||||
JOURNEY_CARD_LIMITS,
|
||||
journeyEntryTypeSchema,
|
||||
journeyEntryVisibilitySchema,
|
||||
stripMarkdown,
|
||||
type JourneyEntriesCard,
|
||||
type JourneyEntryLook,
|
||||
@@ -113,7 +112,6 @@ export function lookOf(value: unknown, source: LookSource = {}): JourneyEntryLoo
|
||||
if (!date) return null;
|
||||
const photos = Array.isArray(row.photos) ? row.photos.map(recordOf) : [];
|
||||
const type = journeyEntryTypeSchema.safeParse(row.type);
|
||||
const visibility = journeyEntryVisibilitySchema.safeParse(row.visibility);
|
||||
const country = typeof row.country_code === 'string' ? row.country_code : '';
|
||||
const mood = typeof row.mood === 'string' ? row.mood.trim().toLowerCase() : '';
|
||||
const day = source.days?.indexOf(date) ?? -1;
|
||||
@@ -131,7 +129,6 @@ export function lookOf(value: unknown, source: LookSource = {}): JourneyEntryLoo
|
||||
weather: lineOf(row, 'weather', JOURNEY_CARD_LIMITS.weather, source),
|
||||
...coverOf(photos),
|
||||
photoCount: Math.min(photos.length, 1_000_000),
|
||||
visibility: visibility.success ? visibility.data : 'private',
|
||||
draft: row.is_draft === true || row.is_draft === 1,
|
||||
fromTripPlace: positiveId(row.source_place_id) !== null && row.type !== 'skeleton',
|
||||
dayIndex: day >= 0 && day <= 9_999 ? day : null,
|
||||
|
||||
@@ -394,30 +394,10 @@ export class AtlasService {
|
||||
status: c.status,
|
||||
}));
|
||||
|
||||
const citySet = new Set<string>();
|
||||
for (const place of places) {
|
||||
if (place.address) {
|
||||
const parts = place.address
|
||||
.split(',')
|
||||
.map((s: string) => s.trim())
|
||||
.filter(Boolean);
|
||||
// The last part is the country; the city is usually right before it, but a
|
||||
// full formatted address can have a postal code sitting between them
|
||||
// (e.g. "Bucharest, 010071, Romania"). Walk back from the country and take
|
||||
// the first part that still has letters once digits/postal noise is stripped.
|
||||
const candidates = parts.length >= 2 ? parts.slice(0, -1) : parts;
|
||||
let city = '';
|
||||
for (let i = candidates.length - 1; i >= 0; i--) {
|
||||
const cleaned = candidates[i].replace(/[\d\-−〒]+/g, '').trim();
|
||||
if (cleaned) {
|
||||
city = cleaned.toLowerCase();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (city) citySet.add(city);
|
||||
}
|
||||
}
|
||||
const totalCities = citySet.size;
|
||||
// Places and cities come from the same count as the dashboard card and
|
||||
// GET /api/v1/stats, so the three never show different totals (#3137).
|
||||
const footprint = await this.placeFootprint(userId);
|
||||
const totalCities = footprint.cities.length;
|
||||
|
||||
// Countries the user explicitly removed. Only the zero-count passes below are
|
||||
// suppressed — a country with real places isn't removable in the UI anyway, and once
|
||||
@@ -570,7 +550,7 @@ export class AtlasService {
|
||||
countries,
|
||||
stats: {
|
||||
totalTrips: trips.length,
|
||||
totalPlaces: places.length,
|
||||
totalPlaces: footprint.totalPlaces,
|
||||
totalCountries: visited.length,
|
||||
totalCountriesPlanned: planned.length,
|
||||
totalCountriesIdea: countries.length - visited.length - planned.length,
|
||||
@@ -1046,29 +1026,41 @@ export class AtlasService {
|
||||
.map(([code]) => code);
|
||||
}
|
||||
|
||||
/**
|
||||
* The places on every trip the user owns or is a member of, archived ones included,
|
||||
* with the cities and coordinates derived from them. The one count behind the Atlas
|
||||
* page, the dashboard card, GET /api/v1/stats and the MCP atlas tool (#3137).
|
||||
*
|
||||
* Every place counts once, even when two share an address and coordinates (the same
|
||||
* hotel saved on two trips). A city is read with cityFromAddress, which skips the
|
||||
* region named in the same address (#1115), and two spellings that differ only in
|
||||
* case are one city; the first spelling seen is the one listed.
|
||||
*/
|
||||
private async placeFootprint(
|
||||
userId: number,
|
||||
): Promise<{ totalPlaces: number; cities: string[]; coords: { lat: number; lng: number }[] }> {
|
||||
const places = await this.places.listAddressesForUser(userId); // AT41
|
||||
const cities = new Map<string, string>();
|
||||
const coords: { lat: number; lng: number }[] = [];
|
||||
for (const p of places) {
|
||||
// Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
|
||||
// are valid coordinates a falsy check would drop.
|
||||
if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
|
||||
const city = cityFromAddress(p.address, (part) => KNOWN_COUNTRIES.has(part), p.region_name);
|
||||
if (city && !cities.has(city.toLowerCase())) cities.set(city.toLowerCase(), city);
|
||||
}
|
||||
return { totalPlaces: places.length, cities: [...cities.values()], coords };
|
||||
}
|
||||
|
||||
async getTravelStats(userId: number) {
|
||||
const today = todayUtc();
|
||||
|
||||
// The resolved region rides along so cityFromAddress can tell the city apart from
|
||||
// the region sitting right above it in the same address (#1115).
|
||||
const places = await this.places.listAddressesForUser(userId); // AT41
|
||||
const { totalPlaces, cities, coords } = await this.placeFootprint(userId);
|
||||
|
||||
// Archived trips still count here, matching the places, countries and flight
|
||||
// distance widgets (which never filtered on is_archived) so the dashboard stats
|
||||
// stay consistent — archiving a trip no longer zeroes out trips/days.
|
||||
const tripStats = await this.trips.countTripsAndDaysForUser(userId); // AT42
|
||||
|
||||
const cities = new Set<string>();
|
||||
const coords: { lat: number; lng: number }[] = [];
|
||||
|
||||
places.forEach(p => {
|
||||
// Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
|
||||
// are valid coordinates the former falsy check silently dropped.
|
||||
if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
|
||||
const cityPart = cityFromAddress(p.address, part => KNOWN_COUNTRIES.has(part), p.region_name);
|
||||
if (cityPart) cities.add(cityPart);
|
||||
});
|
||||
|
||||
// Visited countries: the ones the user marked by hand, plus the countries of
|
||||
// their places, resolved the way the Atlas map resolves them (#2875). Each
|
||||
// reached country keeps the last day of its latest trip, for the order.
|
||||
@@ -1111,11 +1103,11 @@ export class AtlasService {
|
||||
|
||||
return {
|
||||
countries: visits.ordered(manualCountries).filter(code => !hidden.has(code)),
|
||||
cities: [...cities],
|
||||
cities,
|
||||
coords,
|
||||
totalTrips: tripStats.trips || 0,
|
||||
totalDays: tripStats.days || 0,
|
||||
totalPlaces: places.length,
|
||||
totalPlaces,
|
||||
totalDistanceKm: await this.flightDistanceKm(userId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* know the region: `place_regions.region_name` is filled by the geocoder, so it can
|
||||
* simply be skipped. For the address above, with the region resolved as Tokyo, walking
|
||||
* back past Japan (country), 150-0002 (digits) and Tokyo (the region) lands on Shibuya.
|
||||
* A city written beside its postcode ("10178 Berlin") counts without the postcode (#3137).
|
||||
*
|
||||
* This is still a heuristic over a formatted string. Structured `address.city` from the
|
||||
* geocoder would be exact, but the fast path for region resolution runs against bundled
|
||||
@@ -25,6 +26,36 @@ function hasDigits(part: string): boolean {
|
||||
return /\d/.test(part);
|
||||
}
|
||||
|
||||
/**
|
||||
* The postcodes geocoders write into the same part as the city: German, French or US
|
||||
* five digits ("10178 Berlin", "NY 10118"), Japanese "150-0002", Dutch "1012 LG", British
|
||||
* "SW1A 2AA" and Canadian "M5V 3L9". A house number ("Unter den Linden 77") or a numbered
|
||||
* district ("Shibuya 2") is none of these and keeps its part out of the running.
|
||||
*/
|
||||
const POSTCODES = [
|
||||
/\b\d{4}\s?[A-Z]{2}\b/g,
|
||||
/\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
|
||||
/\b[A-Z]\d[A-Z]\s?\d[A-Z]\d\b/g,
|
||||
/\b\d{3}-\d{4}\b/g,
|
||||
/\b\d{4,}(?:-\d{4})?\b/g,
|
||||
];
|
||||
|
||||
/**
|
||||
* The name left in a part once its postcode is taken out, or null when the part holds
|
||||
* no postcode or nothing but one. The short state or province code that stands beside
|
||||
* a postcode ("NY 10118", "Roma RM", "ON M5V 3L9") goes with it.
|
||||
*/
|
||||
function besidePostcode(part: string): string | null {
|
||||
let rest = part;
|
||||
for (const pattern of POSTCODES) rest = rest.replace(pattern, ' ');
|
||||
if (rest === part) return null;
|
||||
rest = rest
|
||||
.split(/\s+/)
|
||||
.filter((word) => word && !/^[A-Z]{2}$/.test(word))
|
||||
.join(' ');
|
||||
return rest && !hasDigits(rest) && /\p{L}/u.test(rest) ? rest : null;
|
||||
}
|
||||
|
||||
function normalize(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
@@ -53,8 +84,8 @@ export function cityFromAddress(
|
||||
|
||||
// Index 0 stays out of the running: geocoders lead with the place itself.
|
||||
for (let i = last; i >= 1; i--) {
|
||||
const part = parts[i];
|
||||
if (hasDigits(part)) continue;
|
||||
const part = hasDigits(parts[i]) ? besidePostcode(parts[i]) : parts[i];
|
||||
if (!part) continue;
|
||||
if (isKnownCountry(part)) continue;
|
||||
if (region && normalize(part) === region) continue;
|
||||
// Anything with no letter at all (stray punctuation, a lone dash) is not a name.
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* The time-zone half of the trip calendar: which zones an event may name, and
|
||||
* the VTIMEZONE block each named zone gets. Pure functions, kept apart from
|
||||
* CalendarService so the service stays about which events a trip has.
|
||||
*/
|
||||
import { offsetMinutesAt } from '../common/timezoneService';
|
||||
|
||||
// ── ICS time-zone helpers ────────────────────────────────────────────────────
|
||||
// Timed events must carry an explicit IANA zone; a bare "YYYYMMDDTHHMMSS" is an
|
||||
// RFC 5545 "floating" time that clients render in the *subscriber's* zone (#1453).
|
||||
|
||||
// A stored/plugin-provided timezone (e.g. a transport endpoint's `timezone`) is a
|
||||
// free string that need not be a real IANA zone. Intl.DateTimeFormat throws a
|
||||
// RangeError on an unknown zone, which (via buildVTimezone and offsetMinutesAt)
|
||||
// would crash the whole ICS export (and drop the trip from the all-trips feed).
|
||||
// Validate once so an invalid zone degrades to a floating local time instead.
|
||||
// Module-scoped on purpose (like the permissions/FX caches): the bridge instance
|
||||
// and the DI singleton share one cache.
|
||||
const _tzValidCache = new Map<string, boolean>();
|
||||
export function isValidTimeZone(zone: string): boolean {
|
||||
const cached = _tzValidCache.get(zone);
|
||||
if (cached !== undefined) return cached;
|
||||
let ok = false;
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-US', { timeZone: zone });
|
||||
ok = true;
|
||||
} catch {
|
||||
// Unknown/invalid zone → ok stays false.
|
||||
}
|
||||
// Bound the cache: the key is a free-form (plugin/importer-written) zone string,
|
||||
// so cap distinct entries rather than growing for the process lifetime.
|
||||
if (_tzValidCache.size >= 1000) _tzValidCache.clear();
|
||||
_tzValidCache.set(zone, ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** An offset in minutes as iCalendar writes it: "+0200", "-0330". */
|
||||
function formatOffset(minutes: number): string {
|
||||
const abs = Math.abs(minutes);
|
||||
return `${minutes < 0 ? '-' : '+'}${String(Math.floor(abs / 60)).padStart(2, '0')}${String(abs % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Midnight UTC of a YYYYMMDD date, or NaN when it is no date. */
|
||||
function utcDay(yyyymmdd: string): number {
|
||||
return Date.parse(`${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}T00:00:00Z`);
|
||||
}
|
||||
|
||||
interface ZoneTransition {
|
||||
/** The instant the new offset starts, ms since the epoch. */
|
||||
at: number;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
/** Ten years at most: a span longer than that is a typo, not a trip. */
|
||||
const MAX_SCAN_DAYS = 3660;
|
||||
|
||||
/** Every offset change in [startMs, endMs), to the minute. */
|
||||
function zoneTransitions(zone: string, startMs: number, endMs: number): ZoneTransition[] {
|
||||
const found: ZoneTransition[] = [];
|
||||
const stop = Math.min(endMs, startMs + MAX_SCAN_DAYS * DAY_MS);
|
||||
let before = offsetMinutesAt(zone, startMs);
|
||||
for (let t = startMs; t < stop; t += DAY_MS) {
|
||||
const after = offsetMinutesAt(zone, t + DAY_MS);
|
||||
if (after === before) continue;
|
||||
let lo = t;
|
||||
let hi = t + DAY_MS;
|
||||
while (hi - lo > 60_000) {
|
||||
const mid = lo + Math.floor((hi - lo) / 120_000) * 60_000;
|
||||
if (offsetMinutesAt(zone, mid) === before) lo = mid;
|
||||
else hi = mid;
|
||||
}
|
||||
found.push({ at: hi, from: before, to: after });
|
||||
before = after;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A local wall-clock time as iCalendar writes it, from an instant and the offset in force. */
|
||||
function localStamp(ms: number, offsetMinutes: number): string {
|
||||
return new Date(ms + offsetMinutes * 60_000).toISOString().slice(0, 19).replace(/[-:]/g, '');
|
||||
}
|
||||
|
||||
function observance(kind: 'STANDARD' | 'DAYLIGHT', dtstart: string, from: number, to: number, zone: string): string {
|
||||
return (
|
||||
`BEGIN:${kind}\r\n` +
|
||||
`DTSTART:${dtstart}\r\n` +
|
||||
`TZOFFSETFROM:${formatOffset(from)}\r\n` +
|
||||
`TZOFFSETTO:${formatOffset(to)}\r\n` +
|
||||
`TZNAME:${zone}\r\n` +
|
||||
`END:${kind}\r\n`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The zone's VTIMEZONE for the dates its events fall on (YYYYMMDD, inclusive).
|
||||
*
|
||||
* Smart clients replace it with their own IANA rules, but a client that reads
|
||||
* it literally shows every event at the offset written here. One fixed offset
|
||||
* put a June flight in Paris an hour off once the trip crossed the change to
|
||||
* summer time, so each change inside the span is written out as its own
|
||||
* observance, with the offset that held before it as the first one. A zone
|
||||
* without changes in the span, or a span with no readable date, keeps the one
|
||||
* fixed offset it always had.
|
||||
*/
|
||||
export function buildVTimezone(zone: string, firstDay: string, lastDay: string): string {
|
||||
const start = utcDay(firstDay);
|
||||
const end = utcDay(lastDay);
|
||||
let body: string;
|
||||
if (Number.isNaN(start)) {
|
||||
body = observance('STANDARD', '19700101T000000', 0, 0, zone);
|
||||
} else {
|
||||
// Whole calendar years around the events, so a client that expands the
|
||||
// rules a little past the last event still finds the offset in force.
|
||||
const from = Date.UTC(new Date(start).getUTCFullYear(), 0, 1);
|
||||
const to = Date.UTC(new Date(Number.isNaN(end) ? start : Math.max(start, end)).getUTCFullYear() + 1, 0, 1);
|
||||
const changes = zoneTransitions(zone, from, to);
|
||||
const initial = offsetMinutesAt(zone, from);
|
||||
if (changes.length === 0) {
|
||||
const at = offsetMinutesAt(zone, start + DAY_MS / 2);
|
||||
body = observance('STANDARD', '19700101T000000', at, at, zone);
|
||||
} else {
|
||||
const firstIsSummer = changes[0].to < changes[0].from;
|
||||
body = observance(firstIsSummer ? 'DAYLIGHT' : 'STANDARD', '19700101T000000', initial, initial, zone);
|
||||
for (const c of changes) {
|
||||
body += observance(c.to > c.from ? 'DAYLIGHT' : 'STANDARD', localStamp(c.at, c.from), c.from, c.to, zone);
|
||||
}
|
||||
}
|
||||
}
|
||||
return `BEGIN:VTIMEZONE\r\nTZID:${zone}\r\n${body}END:VTIMEZONE\r\n`;
|
||||
}
|
||||
@@ -5,13 +5,18 @@ import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { RESERVATION_METADATA } from '../../db/json-columns';
|
||||
import type { DayNotesRepository } from '../../db/repositories/DayNotes.repository';
|
||||
import type { DaysRepository } from '../../db/repositories/Days.repository';
|
||||
import type { ReservationsRepository } from '../../db/repositories/Reservations.repository';
|
||||
import type {
|
||||
CalendarReservationRow,
|
||||
CalendarStopRow,
|
||||
ReservationsRepository,
|
||||
} from '../../db/repositories/Reservations.repository';
|
||||
import type { TripsRepository } from '../../db/repositories/Trips.repository';
|
||||
import { decodeJson } from '../../utils/json-column';
|
||||
import { NotFoundError } from '../common/domain-errors';
|
||||
import { offsetMinutesAt, resolveTimeZone } from '../common/timezoneService';
|
||||
import { resolveTimeZone } from '../common/timezoneService';
|
||||
import { addDays } from '../days/days.service';
|
||||
import { ReservationsService } from '../reservations/reservations.service';
|
||||
import { buildVTimezone, isValidTimeZone } from './calendar-timezones.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { isTransportReservationType, type TripCalendarQuery } from '@trek/shared';
|
||||
@@ -70,55 +75,6 @@ export function foldICS(ics: string): string {
|
||||
return ics.split('\r\n').map(foldLine).join('\r\n');
|
||||
}
|
||||
|
||||
// ── ICS time-zone helpers ────────────────────────────────────────────────────
|
||||
// Timed events must carry an explicit IANA zone; a bare "YYYYMMDDTHHMMSS" is an
|
||||
// RFC 5545 "floating" time that clients render in the *subscriber's* zone (#1453).
|
||||
|
||||
// A stored/plugin-provided timezone (e.g. a transport endpoint's `timezone`) is a
|
||||
// free string that need not be a real IANA zone. Intl.DateTimeFormat throws a
|
||||
// RangeError on an unknown zone, which — via buildVTimezone → offsetMinutesAt —
|
||||
// would crash the whole ICS export (and drop the trip from the all-trips feed).
|
||||
// Validate once so an invalid zone degrades to a floating local time instead.
|
||||
// Module-scoped on purpose (like the permissions/FX caches): the bridge instance
|
||||
// and the DI singleton share one cache.
|
||||
const _tzValidCache = new Map<string, boolean>();
|
||||
function isValidTimeZone(zone: string): boolean {
|
||||
const cached = _tzValidCache.get(zone);
|
||||
if (cached !== undefined) return cached;
|
||||
let ok = false;
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-US', { timeZone: zone });
|
||||
ok = true;
|
||||
} catch {
|
||||
// Unknown/invalid zone → ok stays false.
|
||||
}
|
||||
// Bound the cache — the key is a free-form (plugin/importer-written) zone string,
|
||||
// so cap distinct entries rather than growing for the process lifetime.
|
||||
if (_tzValidCache.size >= 1000) _tzValidCache.clear();
|
||||
_tzValidCache.set(zone, ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** An offset in minutes as iCalendar writes it: "+0200", "-0330". */
|
||||
function formatOffset(minutes: number): string {
|
||||
const abs = Math.abs(minutes);
|
||||
return `${minutes < 0 ? '-' : '+'}${String(Math.floor(abs / 60)).padStart(2, '0')}${String(abs % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Midnight UTC of a YYYYMMDD date, or NaN when it is no date. */
|
||||
function utcDay(yyyymmdd: string): number {
|
||||
return Date.parse(`${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}T00:00:00Z`);
|
||||
}
|
||||
|
||||
interface ZoneTransition {
|
||||
/** The instant the new offset starts, ms since the epoch. */
|
||||
at: number;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
/** Rows of several days, by day id; each day keeps the order the rows came in. */
|
||||
function groupByDay<T extends { day_id: number }>(rows: T[]): Map<number, T[]> {
|
||||
const byDay = new Map<number, T[]>();
|
||||
@@ -142,83 +98,18 @@ function plusMinutes(date: string, time: string, minutes: number): { date: strin
|
||||
};
|
||||
}
|
||||
|
||||
/** Ten years at most: a span longer than that is a typo, not a trip. */
|
||||
const MAX_SCAN_DAYS = 3660;
|
||||
|
||||
/** Every offset change in [startMs, endMs), to the minute. */
|
||||
function zoneTransitions(zone: string, startMs: number, endMs: number): ZoneTransition[] {
|
||||
const found: ZoneTransition[] = [];
|
||||
const stop = Math.min(endMs, startMs + MAX_SCAN_DAYS * DAY_MS);
|
||||
let before = offsetMinutesAt(zone, startMs);
|
||||
for (let t = startMs; t < stop; t += DAY_MS) {
|
||||
const after = offsetMinutesAt(zone, t + DAY_MS);
|
||||
if (after === before) continue;
|
||||
let lo = t;
|
||||
let hi = t + DAY_MS;
|
||||
while (hi - lo > 60_000) {
|
||||
const mid = lo + Math.floor((hi - lo) / 120_000) * 60_000;
|
||||
if (offsetMinutesAt(zone, mid) === before) lo = mid;
|
||||
else hi = mid;
|
||||
}
|
||||
found.push({ at: hi, from: before, to: after });
|
||||
before = after;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A local wall-clock time as iCalendar writes it, from an instant and the offset in force. */
|
||||
function localStamp(ms: number, offsetMinutes: number): string {
|
||||
return new Date(ms + offsetMinutes * 60_000).toISOString().slice(0, 19).replace(/[-:]/g, '');
|
||||
}
|
||||
|
||||
function observance(kind: 'STANDARD' | 'DAYLIGHT', dtstart: string, from: number, to: number, zone: string): string {
|
||||
return (
|
||||
`BEGIN:${kind}\r\n` +
|
||||
`DTSTART:${dtstart}\r\n` +
|
||||
`TZOFFSETFROM:${formatOffset(from)}\r\n` +
|
||||
`TZOFFSETTO:${formatOffset(to)}\r\n` +
|
||||
`TZNAME:${zone}\r\n` +
|
||||
`END:${kind}\r\n`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The zone's VTIMEZONE for the dates its events fall on (YYYYMMDD, inclusive).
|
||||
*
|
||||
* Smart clients replace it with their own IANA rules, but a client that reads
|
||||
* it literally shows every event at the offset written here. One fixed offset
|
||||
* put a June flight in Paris an hour off once the trip crossed the change to
|
||||
* summer time, so each change inside the span is written out as its own
|
||||
* observance, with the offset that held before it as the first one. A zone
|
||||
* without changes in the span, or a span with no readable date, keeps the one
|
||||
* fixed offset it always had.
|
||||
* Where a timed stop ends. Without an end the event would have no length, and
|
||||
* clients put their own default (mostly an hour) in its place, so a 20 minute
|
||||
* stop came out as an hour (#2641). The place's duration says how long it lasts.
|
||||
*/
|
||||
function buildVTimezone(zone: string, firstDay: string, lastDay: string): string {
|
||||
const start = utcDay(firstDay);
|
||||
const end = utcDay(lastDay);
|
||||
let body: string;
|
||||
if (Number.isNaN(start)) {
|
||||
body = observance('STANDARD', '19700101T000000', 0, 0, zone);
|
||||
} else {
|
||||
// Whole calendar years around the events, so a client that expands the
|
||||
// rules a little past the last event still finds the offset in force.
|
||||
const from = Date.UTC(new Date(start).getUTCFullYear(), 0, 1);
|
||||
const to = Date.UTC(new Date(Number.isNaN(end) ? start : Math.max(start, end)).getUTCFullYear() + 1, 0, 1);
|
||||
const changes = zoneTransitions(zone, from, to);
|
||||
const initial = offsetMinutesAt(zone, from);
|
||||
if (changes.length === 0) {
|
||||
const at = offsetMinutesAt(zone, start + DAY_MS / 2);
|
||||
body = observance('STANDARD', '19700101T000000', at, at, zone);
|
||||
} else {
|
||||
const firstIsSummer = changes[0].to < changes[0].from;
|
||||
body = observance(firstIsSummer ? 'DAYLIGHT' : 'STANDARD', '19700101T000000', initial, initial, zone);
|
||||
for (const c of changes) {
|
||||
body += observance(c.to > c.from ? 'DAYLIGHT' : 'STANDARD', localStamp(c.at, c.from), c.from, c.to, zone);
|
||||
}
|
||||
}
|
||||
}
|
||||
return `BEGIN:VTIMEZONE\r\nTZID:${zone}\r\n${body}END:VTIMEZONE\r\n`;
|
||||
function stopEnd(a: CalendarStopRow, date: string): { date: string; time: string } | null {
|
||||
if (a.effective_end_time) return { date, time: a.effective_end_time };
|
||||
const start = a.effective_time ?? '';
|
||||
const minutes = a.place_duration_minutes;
|
||||
return minutes && minutes > 0 && /^\d{2}:\d{2}/.test(start) ? plusMinutes(date, start, minutes) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything TREK knows how to say in iCalendar. Moved out of TripsService
|
||||
* unchanged: same statements, same escaping, same folding, same VTIMEZONE
|
||||
@@ -297,6 +188,9 @@ export class CalendarService {
|
||||
// used on, the span the VTIMEZONE has to cover. Populated by dtLine; emitted
|
||||
// once as VTIMEZONE blocks.
|
||||
const usedZones = new Map<string, { first: string; last: string }>();
|
||||
// Off while the bookings are only looked at (see startsAtClock), so each zone
|
||||
// is recorded once, in the order the events are emitted.
|
||||
let recordZones = true;
|
||||
|
||||
// Emit a DTSTART/DTEND line, attaching TZID when the event's zone is known so
|
||||
// subscribers see the time in TREK's zone. Falls back to a floating local time
|
||||
@@ -306,8 +200,8 @@ export class CalendarService {
|
||||
if (zone && isValidTimeZone(zone) && /^\d{8}T\d{6}$/.test(val)) {
|
||||
const day = val.slice(0, 8);
|
||||
const span = usedZones.get(zone);
|
||||
if (!span) usedZones.set(zone, { first: day, last: day });
|
||||
else {
|
||||
if (recordZones && !span) usedZones.set(zone, { first: day, last: day });
|
||||
else if (recordZones && span) {
|
||||
if (day < span.first) span.first = day;
|
||||
if (day > span.last) span.last = day;
|
||||
}
|
||||
@@ -329,89 +223,24 @@ export class CalendarService {
|
||||
events.push(ev);
|
||||
}
|
||||
|
||||
// Days with assignments and notes, read for all dated days at once.
|
||||
// Days with their stops and notes, each read for all days at once.
|
||||
const days = await this.daysRepo.listByTrip(trip.id);
|
||||
const datedDayIds = days.filter((d) => d.date).map((d) => d.id);
|
||||
// A booked night puts a stop of its own on its check-in day, so the route
|
||||
// can reach the hotel. That stop is the booking, not a place the traveller
|
||||
// planned to visit, and the booking already comes through below as the
|
||||
// stay block or its check-in and check-out markers. Read here as well it
|
||||
// would put the hotel on the day a second time.
|
||||
const stopsByDay = groupByDay(await this.reservationsRepo.listCalendarStopsForDays(datedDayIds));
|
||||
// would put the hotel on the day a second time. The stops of undated days
|
||||
// are read too, since a booking linked to one takes its zone from it (#3150);
|
||||
// those days are skipped when emitting.
|
||||
const stops = await this.reservationsRepo.listCalendarStopsForDays(days.map((d) => d.id));
|
||||
const stopsByDay = groupByDay(stops);
|
||||
const notesByDay = groupByDay(await this.dayNotesRepo.listByDayIds(datedDayIds));
|
||||
for (const day of days) {
|
||||
if (!day.date) continue;
|
||||
const assignments = stopsByDay.get(day.id) ?? [];
|
||||
const notes = notesByDay.get(day.id) ?? [];
|
||||
|
||||
const timed = assignments.filter((a) => a.effective_time);
|
||||
const untimed = assignments.filter((a) => !a.effective_time);
|
||||
|
||||
// Timed assignments → individual events
|
||||
for (const a of timed) {
|
||||
const zone = resolveTimeZone(a.place_lat, a.place_lng);
|
||||
let ev = `BEGIN:VEVENT\r\nUID:${uid(a.id, 'assign')}\r\nDTSTAMP:${now}\r\n`;
|
||||
ev += dtLine('DTSTART', a.effective_time, zone, day.date + 'T00:00');
|
||||
if (a.effective_end_time) {
|
||||
ev += dtLine('DTEND', a.effective_end_time, zone, day.date + 'T00:00');
|
||||
} else if (a.place_duration_minutes && a.place_duration_minutes > 0) {
|
||||
// Without an end the event would have no length, and clients put their
|
||||
// own default (mostly an hour) in its place, so a 20 minute stop came out
|
||||
// as an hour (#2641). The place's duration says how long it lasts.
|
||||
const start = a.effective_time ?? '';
|
||||
if (/^\d{2}:\d{2}/.test(start)) {
|
||||
const stop = plusMinutes(day.date, start, a.place_duration_minutes);
|
||||
ev += dtLine('DTEND', stop.time, zone, stop.date + 'T00:00');
|
||||
}
|
||||
}
|
||||
ev += `SUMMARY:${esc(a.place_name)}\r\n`;
|
||||
let desc = '';
|
||||
if (a.notes) desc += a.notes;
|
||||
if (a.place_address) desc += (desc ? '\n' : '') + a.place_address;
|
||||
if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
|
||||
if (a.place_address) ev += `LOCATION:${esc(a.place_address)}\r\n`;
|
||||
ev += `END:VEVENT\r\n`;
|
||||
events.push(ev);
|
||||
}
|
||||
|
||||
// Build all-day summary event if there are untimed activities or notes,
|
||||
// unless the subscriber asked for a calendar without them: the summary
|
||||
// sits above every day and can crowd out everything else there (#2602).
|
||||
if (options.dayEvents !== false && (untimed.length > 0 || notes.length > 0)) {
|
||||
const dayTitle = day.title || `Day ${day.day_number}`;
|
||||
const endStr = fmtDate(addDays(day.date, 1));
|
||||
|
||||
let ev = `BEGIN:VEVENT\r\nUID:${uid(day.id, 'day')}\r\nDTSTAMP:${now}\r\n`;
|
||||
ev += `DTSTART;VALUE=DATE:${fmtDate(day.date)}\r\nDTEND;VALUE=DATE:${endStr}\r\n`;
|
||||
ev += `SUMMARY:${esc(dayTitle)}\r\n`;
|
||||
|
||||
let desc = '';
|
||||
if (untimed.length > 0) {
|
||||
desc += untimed
|
||||
.map((a) => {
|
||||
let line = `• ${a.place_name}`;
|
||||
if (a.place_address) line += ` (${a.place_address})`;
|
||||
if (a.notes) line += ` — ${a.notes}`;
|
||||
return line;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
if (notes.length > 0) {
|
||||
if (desc) desc += '\n\n';
|
||||
desc +=
|
||||
'Notes:\n' +
|
||||
notes
|
||||
.map((n) => {
|
||||
const line = n.time ? `${n.time} — ${n.text}` : `• ${n.text}`;
|
||||
return line;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
|
||||
ev += `END:VEVENT\r\n`;
|
||||
events.push(ev);
|
||||
}
|
||||
}
|
||||
const stopById = new Map(stops.map((a) => [a.id, a]));
|
||||
const linkedStop = (r: CalendarReservationRow) =>
|
||||
r.assignment_id == null ? undefined : stopById.get(Number(r.assignment_id));
|
||||
// The bookings whose event stands in for their linked stop, decided below.
|
||||
const stopOfBooking = new Map<number, CalendarStopRow>();
|
||||
|
||||
// Transport/flight reservations carry no top-level reservation_time; their
|
||||
// times live per endpoint (local_date + local_time) in reservation_endpoints.
|
||||
@@ -434,6 +263,27 @@ export class CalendarService {
|
||||
return t && isTime(t) ? t : null;
|
||||
};
|
||||
|
||||
// The one zone a set of stops agrees on, or null when they name none or several.
|
||||
const soleZone = (list: CalendarStopRow[]): string | null => {
|
||||
const zones = new Set(list.map((a) => resolveTimeZone(a.place_lat, a.place_lng)).filter((z) => z !== null));
|
||||
return zones.size === 1 ? [...zones][0] : null;
|
||||
};
|
||||
const tripZone = soleZone(stops);
|
||||
// A booking's own place gives its zone. One without, a restaurant booked
|
||||
// against a plan stop, takes the stop's instead of floating (#3150). One
|
||||
// with neither takes the zone its day's stops agree on, else the one the
|
||||
// whole trip agrees on. A transport is left out of that guess: its two
|
||||
// ends can sit in different zones, and its endpoints say which.
|
||||
const placeZoneOf = (r: CalendarReservationRow): string | null => {
|
||||
const stop = linkedStop(r);
|
||||
const own =
|
||||
resolveTimeZone(r.place_lat, r.place_lng) ?? (stop ? resolveTimeZone(stop.place_lat, stop.place_lng) : null);
|
||||
if (own || isTransportReservationType(r.type)) return own;
|
||||
const startDate = dateOf(r.reservation_time);
|
||||
const dayId = r.day_id ?? days.find((d) => startDate && d.date === startDate)?.id;
|
||||
return (dayId == null ? null : soleZone(stopsByDay.get(Number(dayId)) ?? [])) ?? tripZone;
|
||||
};
|
||||
|
||||
// Per stay, the booking whose all-day block its two markers replace. Decided
|
||||
// once here rather than twice, because the markers have to hand on exactly
|
||||
// what the block they replaced would have said (#2136).
|
||||
@@ -515,8 +365,8 @@ export class CalendarService {
|
||||
const datePart = r.reservation_time.includes('T') ? r.reservation_time.split('T')[0] : r.reservation_time;
|
||||
if (!isDate(datePart)) return null; // time-only (relative "Day N" trips)
|
||||
if (r.reservation_time.includes('T')) {
|
||||
// Hotels/restaurants: derive the zone from the linked place, if any.
|
||||
const zone = resolveTimeZone(r.place_lat, r.place_lng);
|
||||
// Hotels/restaurants: the zone of the booking's place, else its stop's.
|
||||
const zone = placeZoneOf(r);
|
||||
let out = dtLine('DTSTART', r.reservation_time, zone);
|
||||
if (r.reservation_end_time) {
|
||||
const endDt = fmtDateTime(r.reservation_end_time, r.reservation_time);
|
||||
@@ -604,7 +454,7 @@ export class CalendarService {
|
||||
? { date: ep.local_date!, time: ep.local_time!, zone: ep.timezone || resolveTimeZone(ep.lat, ep.lng) }
|
||||
: null;
|
||||
|
||||
const placeZone = resolveTimeZone(r.place_lat, r.place_lng);
|
||||
const placeZone = placeZoneOf(r);
|
||||
const start =
|
||||
fromEp(startEp) ??
|
||||
(() => {
|
||||
@@ -696,11 +546,116 @@ export class CalendarService {
|
||||
if (r.location) return `LOCATION:${esc(r.location)}\r\n`;
|
||||
const ep = isTransportReservationType(r.type) ? endpointOf(r.id, side) : undefined;
|
||||
const name = ep?.name || ep?.code;
|
||||
// A booking that replaced its plan stop is where the stop was (#3150), by
|
||||
// its address or, for a place without one, by its name.
|
||||
const stop = stopOfBooking.get(r.id);
|
||||
const stopAddress = stop ? stop.place_address || stop.place_name : null;
|
||||
if ((!ep || !name) && stopAddress) return `LOCATION:${esc(stopAddress)}\r\n`;
|
||||
if (!ep || !name) return '';
|
||||
const geo = Number.isFinite(ep.lat) && Number.isFinite(ep.lng) ? `GEO:${ep.lat};${ep.lng}\r\n` : '';
|
||||
return `LOCATION:${esc(name)}\r\n${geo}`;
|
||||
};
|
||||
|
||||
// A booking linked to a plan stop and the stop are one appointment (#3150).
|
||||
// Where the booking starts at a clock on the stop's own day, its event wins
|
||||
// and the stop is left out, as a booked night's stop is; the booking then
|
||||
// carries what the stop said and it does not (place, zone, notes, end). A
|
||||
// booking without a clock, or on another day, leaves the stop alone, since
|
||||
// the stop is then the only record of the visit on its day.
|
||||
const clockStartDate = (r: CalendarReservationRow): string | null => {
|
||||
const split = windowSplit.get(r.id);
|
||||
if (split) return split.start.time === null ? null : split.start.date;
|
||||
const legs = legsOf(r);
|
||||
if (legs) return legs[0].dep.date;
|
||||
const lines = buildReservationTimeLines(r);
|
||||
const start = lines ? /^DTSTART(?:;TZID=[^:]+)?:(\d{4})(\d{2})(\d{2})T/.exec(lines) : null;
|
||||
return start ? `${start[1]}-${start[2]}-${start[3]}` : null;
|
||||
};
|
||||
recordZones = false;
|
||||
for (const r of reservations) {
|
||||
const stop = linkedStop(r);
|
||||
const date = stop ? clockStartDate(r) : null;
|
||||
if (stop && date && date === dayDate.get(Number(stop.day_id))) stopOfBooking.set(r.id, stop);
|
||||
}
|
||||
recordZones = true;
|
||||
const replacedStops = new Set([...stopOfBooking.values()].map((a) => a.id));
|
||||
|
||||
// The stop's end for the booking that replaced it and records none, when
|
||||
// both start at the same moment; without it the booking is only a point.
|
||||
const borrowedEnd = (timeLines: string, a: CalendarStopRow): string => {
|
||||
const start = /^DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{4})/.exec(timeLines);
|
||||
const date = dayDate.get(Number(a.day_id));
|
||||
if (!start || timeLines.includes('DTEND') || !date || !a.effective_time) return '';
|
||||
if (start[2] !== `${fmtDate(date)}T${a.effective_time.slice(0, 5).replace(':', '')}`) return '';
|
||||
const end = stopEnd(a, date);
|
||||
return end ? dtLine('DTEND', end.time, start[1] || null, `${end.date}T00:00`) : '';
|
||||
};
|
||||
|
||||
// Each dated day: its timed stops as events, the rest in one all-day summary.
|
||||
for (const day of days) {
|
||||
if (!day.date) continue;
|
||||
const assignments = (stopsByDay.get(day.id) ?? []).filter((a) => !replacedStops.has(a.id));
|
||||
const notes = notesByDay.get(day.id) ?? [];
|
||||
|
||||
const timed = assignments.filter((a) => a.effective_time);
|
||||
const untimed = assignments.filter((a) => !a.effective_time);
|
||||
|
||||
// Timed assignments → individual events
|
||||
for (const a of timed) {
|
||||
const zone = resolveTimeZone(a.place_lat, a.place_lng);
|
||||
let ev = `BEGIN:VEVENT\r\nUID:${uid(a.id, 'assign')}\r\nDTSTAMP:${now}\r\n`;
|
||||
ev += dtLine('DTSTART', a.effective_time, zone, day.date + 'T00:00');
|
||||
const end = stopEnd(a, day.date);
|
||||
if (end) ev += dtLine('DTEND', end.time, zone, end.date + 'T00:00');
|
||||
ev += `SUMMARY:${esc(a.place_name)}\r\n`;
|
||||
let desc = '';
|
||||
if (a.notes) desc += a.notes;
|
||||
if (a.place_address) desc += (desc ? '\n' : '') + a.place_address;
|
||||
if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
|
||||
if (a.place_address) ev += `LOCATION:${esc(a.place_address)}\r\n`;
|
||||
ev += `END:VEVENT\r\n`;
|
||||
events.push(ev);
|
||||
}
|
||||
|
||||
// Build all-day summary event if there are untimed activities or notes,
|
||||
// unless the subscriber asked for a calendar without them: the summary
|
||||
// sits above every day and can crowd out everything else there (#2602).
|
||||
if (options.dayEvents !== false && (untimed.length > 0 || notes.length > 0)) {
|
||||
const dayTitle = day.title || `Day ${day.day_number}`;
|
||||
const endStr = fmtDate(addDays(day.date, 1));
|
||||
|
||||
let ev = `BEGIN:VEVENT\r\nUID:${uid(day.id, 'day')}\r\nDTSTAMP:${now}\r\n`;
|
||||
ev += `DTSTART;VALUE=DATE:${fmtDate(day.date)}\r\nDTEND;VALUE=DATE:${endStr}\r\n`;
|
||||
ev += `SUMMARY:${esc(dayTitle)}\r\n`;
|
||||
|
||||
let desc = '';
|
||||
if (untimed.length > 0) {
|
||||
desc += untimed
|
||||
.map((a) => {
|
||||
let line = `• ${a.place_name}`;
|
||||
if (a.place_address) line += ` (${a.place_address})`;
|
||||
if (a.notes) line += ` — ${a.notes}`;
|
||||
return line;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
if (notes.length > 0) {
|
||||
if (desc) desc += '\n\n';
|
||||
desc +=
|
||||
'Notes:\n' +
|
||||
notes
|
||||
.map((n) => {
|
||||
const line = n.time ? `${n.time} — ${n.text}` : `• ${n.text}`;
|
||||
return line;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
|
||||
ev += `END:VEVENT\r\n`;
|
||||
events.push(ev);
|
||||
}
|
||||
}
|
||||
|
||||
// Reservations as events
|
||||
for (const r of reservations) {
|
||||
// The two hand-over events below stand in for this booking entirely.
|
||||
@@ -732,7 +687,8 @@ export class CalendarService {
|
||||
if (!timeLines) continue;
|
||||
|
||||
let ev = `BEGIN:VEVENT\r\nUID:${uid(r.id, 'res')}\r\nDTSTAMP:${now}\r\n`;
|
||||
ev += timeLines;
|
||||
const stop = stopOfBooking.get(r.id);
|
||||
ev += timeLines + (stop ? borrowedEnd(timeLines, stop) : '');
|
||||
ev += `SUMMARY:${esc(r.title)}\r\n`;
|
||||
|
||||
const desc = describeReservation(r);
|
||||
@@ -780,6 +736,8 @@ export class CalendarService {
|
||||
}
|
||||
if (meta.train_number) desc += `\nTrain: ${meta.train_number}`;
|
||||
if (r.notes) desc += `\n${r.notes}`;
|
||||
const stopNotes = stopOfBooking.get(r.id)?.notes;
|
||||
if (stopNotes && stopNotes !== r.notes) desc += (desc ? '\n' : '') + stopNotes;
|
||||
return desc;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { JourneyEntryWire } from './journey-entry-row';
|
||||
import type { JourneyPublicEntry, JourneyPublicPhoto } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The public journey payload, built field by field.
|
||||
*
|
||||
* The share link used to spread whole rows into its answer, so every column
|
||||
* the reads selected went out to anyone holding the link: the storage keys of
|
||||
* local photos (`journey/<uuid>.jpg`), provider asset ids, the photo owner,
|
||||
* the entry author and its source ids. Each function below names what the
|
||||
* public page reads and nothing else, so a column added to a read later stays
|
||||
* on the server unless it is added here on purpose.
|
||||
*/
|
||||
|
||||
/** The photo columns the public reads select; only some of them go out. */
|
||||
interface PublicPhotoSource {
|
||||
id: number;
|
||||
photo_id: number;
|
||||
caption?: string | null;
|
||||
provider?: string | null;
|
||||
thumbnail_path?: string | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
media_type?: string | null;
|
||||
duration_ms?: number | null;
|
||||
taken_at?: string | null;
|
||||
lat?: number | null;
|
||||
lng?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A photo as the public page shows it. Capture coordinates go out only with
|
||||
* the map. `posterless` is worked out here, because the storage key it used to
|
||||
* be read from no longer leaves the server (#2341); a clip also keeps its
|
||||
* provider, which builds from before that flag still read.
|
||||
*/
|
||||
export function publicPhoto(photo: PublicPhotoSource, withLocation: boolean): JourneyPublicPhoto {
|
||||
const mediaType = photo.media_type ?? null;
|
||||
return {
|
||||
id: photo.id,
|
||||
photo_id: photo.photo_id,
|
||||
caption: photo.caption ?? null,
|
||||
media_type: mediaType,
|
||||
width: photo.width ?? null,
|
||||
height: photo.height ?? null,
|
||||
duration_ms: photo.duration_ms ?? null,
|
||||
taken_at: photo.taken_at ?? null,
|
||||
lat: withLocation ? (photo.lat ?? null) : null,
|
||||
lng: withLocation ? (photo.lng ?? null) : null,
|
||||
posterless: mediaType === 'video' && photo.provider === 'local' && !photo.thumbnail_path,
|
||||
// Older clients still work `posterless` out from the provider (see the schema).
|
||||
...(mediaType === 'video' ? { provider: photo.provider ?? null } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Just enough of an entry to plot its marker: a map-only share tells no story. */
|
||||
export function publicMapEntry(entry: JourneyEntryWire): JourneyPublicEntry {
|
||||
return {
|
||||
id: entry.id,
|
||||
type: entry.type,
|
||||
entry_date: entry.entry_date,
|
||||
sort_order: entry.sort_order ?? null,
|
||||
title: entry.title ?? null,
|
||||
location_name: entry.location_name ?? null,
|
||||
location_lat: entry.location_lat ?? null,
|
||||
location_lng: entry.location_lng ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An entry of a shared timeline with its photos. The coordinates follow the
|
||||
* map switch; the photos follow the gallery switch.
|
||||
*/
|
||||
export function publicTimelineEntry(
|
||||
entry: JourneyEntryWire,
|
||||
photos: readonly PublicPhotoSource[],
|
||||
share: { map: boolean; gallery: boolean },
|
||||
): JourneyPublicEntry {
|
||||
return {
|
||||
id: entry.id,
|
||||
type: entry.type,
|
||||
entry_date: entry.entry_date,
|
||||
entry_time: entry.entry_time ?? null,
|
||||
sort_order: entry.sort_order ?? null,
|
||||
title: entry.title ?? null,
|
||||
story: entry.story ?? null,
|
||||
location_name: entry.location_name ?? null,
|
||||
location_lat: share.map ? (entry.location_lat ?? null) : null,
|
||||
location_lng: share.map ? (entry.location_lng ?? null) : null,
|
||||
country_code: entry.country_code ?? null,
|
||||
mood: entry.mood ?? null,
|
||||
weather: entry.weather ?? null,
|
||||
tags: entry.tags,
|
||||
pros_cons: entry.pros_cons,
|
||||
photos: share.gallery ? photos.map((p) => publicPhoto(p, share.map)) : [],
|
||||
};
|
||||
}
|
||||
@@ -4,10 +4,11 @@ import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { Public } from '../auth-core/public.decorator';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { PublicMediaService } from '../memories/public-media.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JourneyService } from './journey.service';
|
||||
import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common';
|
||||
import { journeyPublicMapLayersResponseSchema } from '@trek/shared';
|
||||
import { journeyPublicMapLayersResponseSchema, journeyPublicResponseSchema } from '@trek/shared';
|
||||
|
||||
import type { Response } from 'express';
|
||||
import path from 'node:path';
|
||||
@@ -20,6 +21,8 @@ import path from 'node:path';
|
||||
* no authentication, every route validates the share token (404 on failure),
|
||||
* the unified proxy streams by trek_photo_id and the legacy proxy serves local
|
||||
* files (with the uploads-dir traversal guard) or proxies immich/synology.
|
||||
* A local file never leaves here as stored: both proxies send its
|
||||
* location-free copy (PublicMediaService), or nothing.
|
||||
*
|
||||
* The addon gate is the one guard here, and it has to be: turning the Journey
|
||||
* addon off is meant to take the feature away, and without it already-published
|
||||
@@ -34,9 +37,16 @@ export class JourneyPublicController {
|
||||
constructor(
|
||||
private readonly journey: JourneyService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly publicMedia: PublicMediaService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The shared journey. Its contract is strict: a column that is not named
|
||||
* there (a storage key, an asset id, an author) fails every test that reaches
|
||||
* this route instead of going out to the public.
|
||||
*/
|
||||
@Get(':token')
|
||||
@ResponseContract(journeyPublicResponseSchema)
|
||||
async get(@Param('token') token: string) {
|
||||
const data = await this.journey.getPublicJourney(token);
|
||||
if (!data) {
|
||||
@@ -96,11 +106,14 @@ export class JourneyPublicController {
|
||||
if (!(await this.storage.exists('journey', name).catch(() => false))) {
|
||||
throw new HttpException({ error: 'Not found' }, 404);
|
||||
}
|
||||
// The copy without GPS and place tags, never the stored original; a file
|
||||
// that cannot be cleaned is not served at all.
|
||||
const rendition = await this.publicMedia.renditionFor('journey', name).catch(() => null);
|
||||
if (!rendition) {
|
||||
throw new HttpException({ error: 'Not found' }, 404);
|
||||
}
|
||||
res.set('Cache-Control', 'public, max-age=86400');
|
||||
// The storage layer serves it, whichever driver is configured. dev's fix
|
||||
// for the absolute-path 404 under the Nest ExpressAdapter does not apply
|
||||
// here any more: nothing on this path calls sendFile.
|
||||
await this.storage.sendToResponse('journey', name, res);
|
||||
await this.storage.sendToResponse('journey', rendition, res);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,10 @@ import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import { decodeEntryRow } from './journey-entry-row';
|
||||
import { publicMapEntry, publicPhoto, publicTimelineEntry } from './journey-public-payload';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { JourneyPublicEntry, JourneyPublicResponse } from '@trek/shared';
|
||||
|
||||
import crypto from 'crypto';
|
||||
|
||||
@@ -231,7 +233,7 @@ export class JourneyShareService {
|
||||
return { ownerId: photo.owner_id || photo.journey_owner_id };
|
||||
}
|
||||
|
||||
async getPublicJourney(token: string) {
|
||||
async getPublicJourney(token: string): Promise<JourneyPublicResponse | null> {
|
||||
// JS11 — exact-match token lookup, no LIKE/COLLATE (R4).
|
||||
const row = await this.shareTokensRepo.findByToken(token);
|
||||
if (!row) return null;
|
||||
@@ -257,11 +259,6 @@ export class JourneyShareService {
|
||||
// A photo whose every entry is a draft stays off the public page (#696).
|
||||
const gallery = await this.photosRepo.galleryRead(row.journey_id, { hideDraftOnly: true });
|
||||
|
||||
const enrichedEntries = entries.map((e) => ({
|
||||
...decodeEntryRow(e),
|
||||
photos: photosByEntry[e.id] || [],
|
||||
}));
|
||||
|
||||
// Stats are derived from the full data so the overview pills stay accurate
|
||||
// even when a section is hidden.
|
||||
const stats = {
|
||||
@@ -276,33 +273,16 @@ export class JourneyShareService {
|
||||
|
||||
// Honour the share flags server-side so the API only returns the sections the
|
||||
// owner enabled (the client gates these too, but it must not rely on that).
|
||||
let publicEntries: Record<string, unknown>[] = [];
|
||||
// Every entry and photo is built field by field (journey-public-payload.ts):
|
||||
// a spread row sent storage keys and author ids to anyone with the link.
|
||||
let publicEntries: JourneyPublicEntry[] = [];
|
||||
if (shareTimeline) {
|
||||
// Include the full entry, but drop GPS unless the map is shared and inline
|
||||
// photos unless the gallery is shared.
|
||||
publicEntries = enrichedEntries.map((e) => {
|
||||
const projected: Record<string, unknown> = { ...e };
|
||||
if (!shareMap) {
|
||||
projected.location_lat = null;
|
||||
projected.location_lng = null;
|
||||
}
|
||||
if (!shareGallery) projected.photos = [];
|
||||
else if (!shareMap) projected.photos = stripPhotoGps(e.photos);
|
||||
return projected;
|
||||
});
|
||||
publicEntries = entries.map((e) =>
|
||||
publicTimelineEntry(decodeEntryRow(e), photosByEntry[e.id] || [], { map: shareMap, gallery: shareGallery }),
|
||||
);
|
||||
} else if (shareMap) {
|
||||
// Map-only share: just enough to plot markers, no story/photos/mood.
|
||||
publicEntries = enrichedEntries.map((e) => ({
|
||||
id: e.id,
|
||||
journey_id: e.journey_id,
|
||||
type: e.type,
|
||||
entry_date: e.entry_date,
|
||||
title: e.title,
|
||||
location_name: e.location_name,
|
||||
location_lat: e.location_lat,
|
||||
location_lng: e.location_lng,
|
||||
sort_order: e.sort_order,
|
||||
}));
|
||||
publicEntries = entries.map((e) => publicMapEntry(decodeEntryRow(e)));
|
||||
}
|
||||
|
||||
// Same reason as the trip share payload: CARTO watermarks every tile fetched
|
||||
@@ -318,9 +298,9 @@ export class JourneyShareService {
|
||||
return {
|
||||
journey: {
|
||||
title: journey.title,
|
||||
subtitle: journey.subtitle,
|
||||
cover_image: journey.cover_image,
|
||||
status: journey.status,
|
||||
subtitle: journey.subtitle ?? null,
|
||||
cover_image: journey.cover_image ?? null,
|
||||
status: journey.status ?? null,
|
||||
// The three "this journey does not use that field" switches. A public
|
||||
// reader was getting mood and weather chips on a journey that had them
|
||||
// turned off, because the phone card reads these and they were not here
|
||||
@@ -334,7 +314,7 @@ export class JourneyShareService {
|
||||
// owner never typed and may not expect to publish. It follows share_map, the
|
||||
// same switch the entry coordinates follow — otherwise a gallery-only share
|
||||
// would hand out places the map was deliberately turned off for.
|
||||
gallery: shareGallery ? (shareMap ? gallery : stripPhotoGps(gallery)) : [],
|
||||
gallery: shareGallery ? gallery.map((p) => publicPhoto(p, shareMap)) : [],
|
||||
stats,
|
||||
cartoApiKey,
|
||||
permissions: {
|
||||
@@ -346,8 +326,3 @@ export class JourneyShareService {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop capture coordinates from a photo list, keeping everything else. */
|
||||
function stripPhotoGps<T>(photos: T[] | undefined | null): T[] {
|
||||
return (photos ?? []).map((p) => ({ ...(p as Record<string, unknown>), lat: null, lng: null })) as T[];
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
type JourneyEntryVisibility,
|
||||
type JourneyReorderEntriesTool,
|
||||
type JourneyUpdateTool,
|
||||
JOURNEY_ENTRY_VISIBILITY_DEPRECATED,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
@@ -72,12 +73,13 @@ function jsonContent(uri: string, data: unknown) {
|
||||
}
|
||||
|
||||
/*
|
||||
* The entry types, visibilities and the verdict come from @trek/shared
|
||||
* (journey.schema.ts), where the assistant's cards read them too: a model that
|
||||
* invents "friends-only" would write a value nothing reads.
|
||||
* The entry types and the verdict come from @trek/shared (journey.schema.ts),
|
||||
* where the assistant's cards read them too: a model that invents "note" would
|
||||
* write a value nothing reads. The entry's stored visibility is deprecated:
|
||||
* still accepted so older callers are not refused, but read by nothing, and
|
||||
* is_draft is what keeps an entry off the share link.
|
||||
*/
|
||||
const ENTRY_TYPE = journeyEntryTypeSchema;
|
||||
const ENTRY_VISIBILITY = journeyEntryVisibilitySchema;
|
||||
const PROS_CONS = journeyEntryProsConsSchema;
|
||||
|
||||
/**
|
||||
@@ -378,9 +380,7 @@ export class JourneyMcp {
|
||||
.describe('Weather as the traveller recorded it (e.g. "sunny", "24C and windy")'),
|
||||
tags: z.array(z.string()).optional(),
|
||||
pros_cons: PROS_CONS.optional().describe('The verdict on the place: what was worth it and what was not'),
|
||||
visibility: ENTRY_VISIBILITY.optional().describe(
|
||||
'Stored with the entry, defaults to private. It does not decide the share link: every entry that is not a draft shows on the journey share link. Use is_draft to keep an entry to the contributors',
|
||||
),
|
||||
visibility: journeyEntryVisibilitySchema.optional().describe(JOURNEY_ENTRY_VISIBILITY_DEPRECATED),
|
||||
type: ENTRY_TYPE.optional().describe(
|
||||
'Defaults to "entry"; "skeleton" is the stub TREK derives from a trip place and hides behind the hide-skeletons preference',
|
||||
),
|
||||
@@ -388,7 +388,9 @@ export class JourneyMcp {
|
||||
is_draft: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe('True keeps the entry a draft: contributors see it, the journey share link does not'),
|
||||
.describe(
|
||||
'True keeps the entry a draft: contributors see it, the journey share link does not. Every entry that is not a draft shows on the share link',
|
||||
),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: journeyAddonOn,
|
||||
@@ -428,7 +430,7 @@ export class JourneyMcp {
|
||||
@Tool({
|
||||
name: 'update_journey_entry',
|
||||
description:
|
||||
'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, visibility, whether it is a draft, or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.',
|
||||
'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, whether it is a draft (is_draft, the one switch that keeps it off the share link), or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.',
|
||||
inputSchema: { entryId: idSchema, ...journeyEntryUpdateToolSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: journeyAddonOn,
|
||||
|
||||
@@ -188,8 +188,9 @@ export class JourneyService {
|
||||
validateShareTokenForAsset(token: string, assetId: string) {
|
||||
return this.share.validateShareTokenForAsset(token, assetId);
|
||||
}
|
||||
/** The public share's photo bytes: local files go out without their location. */
|
||||
streamPhoto(res: Response, ownerId: number, photoId: number, kind: 'thumbnail' | 'original') {
|
||||
return this.photoResolver.streamPhoto(res, ownerId, photoId, kind);
|
||||
return this.photoResolver.streamPublicPhoto(res, ownerId, photoId, kind);
|
||||
}
|
||||
/**
|
||||
* Stream a shared journey asset from whichever backend holds it.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { logInfo, logError } from '../audit/audit-log.logger';
|
||||
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
|
||||
import { PublicMediaService } from './public-media.service';
|
||||
import { ThumbnailService } from './thumbnail.service';
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
|
||||
@@ -8,12 +9,14 @@ import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
* photo row is gone (spec In-scope fix #2: delete sites only started removing
|
||||
* the derived thumb with this slice, so historical orphans need a sweeper).
|
||||
* The Journey addon gate lives inside sweepOrphanThumbs, so toggling the
|
||||
* addon takes effect without a restart.
|
||||
* addon takes effect without a restart. The same pass drops the location-free
|
||||
* copies (PublicMediaService) whose source is gone.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JourneyThumbsJob implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly thumbnails: ThumbnailService,
|
||||
private readonly publicMedia: PublicMediaService,
|
||||
private readonly registrar: CronRegistrarService,
|
||||
) {}
|
||||
|
||||
@@ -31,11 +34,23 @@ export class JourneyThumbsJob implements OnApplicationBootstrap {
|
||||
}
|
||||
|
||||
async sweep(): Promise<void> {
|
||||
try {
|
||||
await contained('Journey thumbnail cleanup', async () => {
|
||||
const removed = await this.thumbnails.sweepOrphanThumbs();
|
||||
if (removed > 0) logInfo(`Journey thumbnail cleanup: removed ${removed} orphaned thumbnail(s)`);
|
||||
} catch (err: unknown) {
|
||||
logError(`Journey thumbnail cleanup: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
});
|
||||
// Its own pass and log line, so one failing never hides or stops the other.
|
||||
await contained('Public media cleanup', async () => {
|
||||
const renditions = await this.publicMedia.sweepOrphans();
|
||||
if (renditions > 0) logInfo(`Public media cleanup: removed ${renditions} location-free copies of deleted media`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs one cleanup pass and logs its failure under `label` instead of throwing. */
|
||||
async function contained(label: string, pass: () => Promise<void>): Promise<void> {
|
||||
try {
|
||||
await pass();
|
||||
} catch (err: unknown) {
|
||||
logError(`${label}: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
import exifr from 'exifr';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
import fsPromises from 'node:fs/promises';
|
||||
import zlib from 'node:zlib';
|
||||
|
||||
/**
|
||||
* Location redaction for media that leaves the host without an account.
|
||||
*
|
||||
* Every edit is length preserving and happens on a copy: the GPS block of an
|
||||
* embedded EXIF/TIFF structure is emptied, location properties of an XMP packet
|
||||
* are overwritten with spaces, and the location atoms of a QuickTime/MP4 movie
|
||||
* are zeroed. Nothing is decoded or re-encoded, so the picture keeps its quality
|
||||
* and its orientation, and every container the format knows how to skip stays
|
||||
* valid. A file this cannot vouch for answers false, and the caller serves no
|
||||
* original in its place.
|
||||
*/
|
||||
|
||||
/** Images are cleaned in memory; a larger one is refused rather than read whole. */
|
||||
const MAX_IMAGE_BYTES = 128 * 1024 * 1024;
|
||||
|
||||
/** XMP boxes inside a movie are read whole as well. */
|
||||
const MAX_XMP_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
const GPS_IFD_TAG = 0x8825;
|
||||
|
||||
/** Bytes per value of each TIFF field type (index = type id 1..13). */
|
||||
const TIFF_TYPE_SIZES = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4];
|
||||
|
||||
const EXIF_MARK = Buffer.from('Exif\0\0', 'latin1');
|
||||
const RDF_OPEN = Buffer.from('<rdf:RDF', 'latin1');
|
||||
const RDF_CLOSE = Buffer.from('</rdf:RDF>', 'latin1');
|
||||
const SPACE = 0x20;
|
||||
|
||||
/** The uuid box Adobe's XMP spec gives MP4 files. */
|
||||
const XMP_UUID = Buffer.from('be7acfcb97a942e89c71999491e3afac', 'hex');
|
||||
|
||||
/** The QuickTime user-data atom holding an ISO 6709 location string. */
|
||||
const LOCATION_ATOM = '\u00a9xyz';
|
||||
|
||||
/**
|
||||
* ftyp major brands of a still HEIF/AVIF image. Only these may take the
|
||||
* in-memory image path; any other ISO BMFF file is a movie and has to be
|
||||
* walked as one, or it is refused.
|
||||
*/
|
||||
const STILL_IMAGE_BRANDS = new Set(['avif', 'heic', 'heim', 'heis', 'heix', 'miaf', 'mif1', 'mif2']);
|
||||
|
||||
/** Top-level atoms an old QuickTime file may start with instead of ftyp. */
|
||||
const QUICKTIME_LEAD_ATOMS = new Set(['free', 'mdat', 'moov', 'pnot', 'skip', 'wide']);
|
||||
|
||||
const MOOV = Buffer.from('moov', 'latin1');
|
||||
|
||||
const PHOTOSHOP_MARK = Buffer.from('Photoshop 3.0\0', 'latin1');
|
||||
|
||||
/** The Photoshop image resource that carries the IPTC-IIM record. */
|
||||
const IPTC_RESOURCE_ID = 0x0404;
|
||||
|
||||
/**
|
||||
* IPTC-IIM application record (2) datasets that name a place: content
|
||||
* location code and name, city, sublocation, province/state, country code
|
||||
* and country.
|
||||
*/
|
||||
const IPTC_LOCATION_DATASETS = new Set([26, 27, 90, 92, 95, 100, 101]);
|
||||
|
||||
/** Local names (prefix stripped, lower case) of the XMP properties that name a place. */
|
||||
const XMP_LOCATION_FIELDS = new Set([
|
||||
'altitude',
|
||||
'city',
|
||||
'country',
|
||||
'countrycode',
|
||||
'countryname',
|
||||
'latitude',
|
||||
'location',
|
||||
'locationcreated',
|
||||
'locationshown',
|
||||
'longitude',
|
||||
'provincestate',
|
||||
'state',
|
||||
'sublocation',
|
||||
'worldregion',
|
||||
]);
|
||||
|
||||
type MediaFormat = 'jpeg' | 'png' | 'webp' | 'gif' | 'tiff' | 'isobmff' | 'quicktime' | 'ebml' | 'unknown';
|
||||
|
||||
function sniffFormat(head: Buffer): MediaFormat {
|
||||
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpeg';
|
||||
if (head.length < 8) return 'unknown';
|
||||
if (head.readUInt32BE(0) === 0x89504e47) return 'png';
|
||||
if (head.toString('latin1', 0, 4) === 'GIF8') return 'gif';
|
||||
if (head.toString('latin1', 4, 8) === 'ftyp') return 'isobmff';
|
||||
if (QUICKTIME_LEAD_ATOMS.has(head.toString('latin1', 4, 8))) return 'quicktime';
|
||||
if (head.readUInt32BE(0) === 0x1a45dfa3) return 'ebml';
|
||||
if (readTiffByteOrder(head, 0, head.length) !== null) return 'tiff';
|
||||
if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP') {
|
||||
return 'webp';
|
||||
}
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// ── EXIF / TIFF ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** 'le' or 'be' for a TIFF header at `base`, null when there is none. */
|
||||
function readTiffByteOrder(buf: Buffer, base: number, limit: number): 'le' | 'be' | null {
|
||||
if (base + 8 > limit) return null;
|
||||
if (buf[base] === 0x49 && buf[base + 1] === 0x49 && buf.readUInt16LE(base + 2) === 42) return 'le';
|
||||
if (buf[base] === 0x4d && buf[base + 1] === 0x4d && buf.readUInt16BE(base + 2) === 42) return 'be';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Empties the GPS IFD of the TIFF structure at `base`: its out-of-line values
|
||||
* and its entries are zeroed and its entry count set to 0, which also reads
|
||||
* as "no next IFD". IFD0 (orientation included) is left as it was.
|
||||
* False when no plausible TIFF starts at `base`.
|
||||
*/
|
||||
function blankTiffGps(buf: Buffer, base: number, limit: number): boolean {
|
||||
const order = readTiffByteOrder(buf, base, limit);
|
||||
if (!order) return false;
|
||||
const u16 = (offset: number) => (order === 'le' ? buf.readUInt16LE(base + offset) : buf.readUInt16BE(base + offset));
|
||||
const u32 = (offset: number) => (order === 'le' ? buf.readUInt32LE(base + offset) : buf.readUInt32BE(base + offset));
|
||||
const entryCount = (offset: number) => {
|
||||
if (offset < 8 || base + offset + 2 > limit) return -1;
|
||||
const count = u16(offset);
|
||||
return base + offset + 2 + count * 12 + 4 <= limit ? count : -1;
|
||||
};
|
||||
|
||||
const blankGpsIfd = (offset: number) => {
|
||||
const count = entryCount(offset);
|
||||
if (count <= 0) return;
|
||||
for (let i = 0; i < count; i++) {
|
||||
const entry = offset + 2 + i * 12;
|
||||
const size = (TIFF_TYPE_SIZES[u16(entry + 2)] ?? 0) * u32(entry + 4);
|
||||
const valueAt = u32(entry + 8);
|
||||
if (size > 4 && valueAt >= 8 && base + valueAt + size <= limit)
|
||||
buf.fill(0, base + valueAt, base + valueAt + size);
|
||||
}
|
||||
buf.fill(0, base + offset, base + offset + 2 + count * 12);
|
||||
};
|
||||
|
||||
// IFD0 and the IFDs chained behind it; the GPS pointer lives in IFD0 in practice.
|
||||
const seen = new Set<number>();
|
||||
let ifd = u32(4);
|
||||
for (let depth = 0; depth < 4 && ifd !== 0 && !seen.has(ifd); depth++) {
|
||||
seen.add(ifd);
|
||||
const count = entryCount(ifd);
|
||||
if (count <= 0 || count > 1024) return depth > 0;
|
||||
for (let i = 0; i < count; i++) {
|
||||
const entry = ifd + 2 + i * 12;
|
||||
if (u16(entry) === GPS_IFD_TAG) blankGpsIfd(u32(entry + 8));
|
||||
}
|
||||
ifd = u32(ifd + 2 + count * 12);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Every "Exif\0\0"-prefixed TIFF in the buffer: JPEG APP1 (MPO frames too), HEIC/AVIF Exif items, WebP. */
|
||||
function blankAllExif(buf: Buffer): void {
|
||||
let at = buf.indexOf(EXIF_MARK);
|
||||
while (at !== -1) {
|
||||
blankTiffGps(buf, at + EXIF_MARK.length, buf.length);
|
||||
at = buf.indexOf(EXIF_MARK, at + EXIF_MARK.length);
|
||||
}
|
||||
}
|
||||
|
||||
// ── XMP ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function isXmpLocationName(qualifiedName: string): boolean {
|
||||
const colon = qualifiedName.indexOf(':');
|
||||
if (colon === -1) return false;
|
||||
const local = qualifiedName.slice(colon + 1).toLowerCase();
|
||||
return local.startsWith('gps') || XMP_LOCATION_FIELDS.has(local);
|
||||
}
|
||||
|
||||
function isXmlSpace(char: string | undefined): boolean {
|
||||
return char === ' ' || char === '\n' || char === '\r' || char === '\t';
|
||||
}
|
||||
|
||||
/** Index of the `>` closing the tag that starts before `from`, quotes respected. */
|
||||
function findTagEnd(text: string, from: number): number {
|
||||
let quote: string | null = null;
|
||||
for (let i = from; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
if (quote) {
|
||||
if (char === quote) quote = null;
|
||||
} else if (char === '"' || char === "'") {
|
||||
quote = char;
|
||||
} else if (char === '>') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Collects the location attributes between a tag's name and its `>`; false on a malformed tag. */
|
||||
function collectLocationAttributes(text: string, from: number, to: number, ranges: Array<[number, number]>): boolean {
|
||||
let i = from;
|
||||
while (i < to) {
|
||||
while (i < to && (isXmlSpace(text[i]) || text[i] === '/')) i++;
|
||||
if (i >= to) break;
|
||||
const start = i;
|
||||
while (i < to && text[i] !== '=' && !isXmlSpace(text[i])) i++;
|
||||
const name = text.slice(start, i);
|
||||
while (i < to && isXmlSpace(text[i])) i++;
|
||||
if (text[i] !== '=') return false;
|
||||
i++;
|
||||
while (i < to && isXmlSpace(text[i])) i++;
|
||||
const quote = text[i];
|
||||
if (quote !== '"' && quote !== "'") return false;
|
||||
const close = text.indexOf(quote, i + 1);
|
||||
if (close === -1 || close > to) return false;
|
||||
if (isXmpLocationName(name)) ranges.push([start, close + 1]);
|
||||
i = close + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The character ranges of an XMP packet that hold a location: whole elements
|
||||
* (exif:GPSLatitude, photoshop:City, Iptc4xmpExt:LocationShown …) and
|
||||
* attributes of the same names. Null when the packet does not parse.
|
||||
*/
|
||||
function xmpLocationRanges(text: string): Array<[number, number]> | null {
|
||||
const ranges: Array<[number, number]> = [];
|
||||
let i = text.indexOf('<');
|
||||
while (i !== -1) {
|
||||
const next = text[i + 1];
|
||||
if (next === '/' || next === '?' || next === '!') {
|
||||
i = text.indexOf('<', i + 1);
|
||||
continue;
|
||||
}
|
||||
let nameEnd = i + 1;
|
||||
while (nameEnd < text.length && !isXmlSpace(text[nameEnd]) && text[nameEnd] !== '>' && text[nameEnd] !== '/') {
|
||||
nameEnd++;
|
||||
}
|
||||
const name = text.slice(i + 1, nameEnd);
|
||||
const tagEnd = findTagEnd(text, nameEnd);
|
||||
if (tagEnd === -1) return null;
|
||||
if (isXmpLocationName(name)) {
|
||||
let end = tagEnd + 1;
|
||||
if (text[tagEnd - 1] !== '/') {
|
||||
const close = text.indexOf(`</${name}`, tagEnd);
|
||||
const closeEnd = close === -1 ? -1 : text.indexOf('>', close);
|
||||
if (closeEnd === -1) return null;
|
||||
end = closeEnd + 1;
|
||||
}
|
||||
ranges.push([i, end]);
|
||||
i = text.indexOf('<', end);
|
||||
continue;
|
||||
}
|
||||
if (!collectLocationAttributes(text, nameEnd, tagEnd, ranges)) return null;
|
||||
i = text.indexOf('<', tagEnd + 1);
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
/** Blanks the location properties of every XMP packet in [from, to); false when one does not parse. */
|
||||
function blankAllXmp(buf: Buffer, from = 0, to = buf.length): boolean {
|
||||
let at = buf.indexOf(RDF_OPEN, from);
|
||||
while (at !== -1 && at < to) {
|
||||
const close = buf.indexOf(RDF_CLOSE, at);
|
||||
if (close === -1 || close + RDF_CLOSE.length > to) return false;
|
||||
const end = close + RDF_CLOSE.length;
|
||||
// latin1 maps every byte to one character, so string indexes are byte offsets.
|
||||
const ranges = xmpLocationRanges(buf.toString('latin1', at, end));
|
||||
if (!ranges) return false;
|
||||
for (const [start, stop] of ranges) buf.fill(SPACE, at + start, at + stop);
|
||||
at = buf.indexOf(RDF_OPEN, end);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── IPTC-IIM (JPEG APP13) ───────────────────────────────────────────────────
|
||||
|
||||
/** Overwrites the place datasets of an IIM block with spaces; false when it does not parse. */
|
||||
function blankIimLocation(buf: Buffer, from: number, to: number): boolean {
|
||||
let pos = from;
|
||||
// Writers may pad the block with zeros after the last dataset.
|
||||
while (pos + 5 <= to && buf[pos] !== 0) {
|
||||
if (buf[pos] !== 0x1c) return false;
|
||||
const record = buf[pos + 1];
|
||||
const dataset = buf[pos + 2];
|
||||
let length = buf.readUInt16BE(pos + 3);
|
||||
let value = pos + 5;
|
||||
// Extended dataset: the low 15 bits give the byte count of the real length.
|
||||
if (length & 0x8000) {
|
||||
const lengthBytes = length & 0x7fff;
|
||||
if (lengthBytes < 1 || lengthBytes > 4 || value + lengthBytes > to) return false;
|
||||
length = buf.readUIntBE(value, lengthBytes);
|
||||
value += lengthBytes;
|
||||
}
|
||||
if (value + length > to) return false;
|
||||
if (record === 2 && IPTC_LOCATION_DATASETS.has(dataset)) buf.fill(SPACE, value, value + length);
|
||||
pos = value + length;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Walks the 8BIM resources of a Photoshop APP13 block and cleans its IPTC record. */
|
||||
function blankPhotoshopIptc(buf: Buffer, from: number, to: number): boolean {
|
||||
let pos = from;
|
||||
while (pos + 12 <= to) {
|
||||
if (buf.toString('latin1', pos, pos + 4) !== '8BIM') return false;
|
||||
const id = buf.readUInt16BE(pos + 4);
|
||||
// A Pascal name, padded so that its length byte and the name together are even.
|
||||
const nameLength = buf[pos + 6];
|
||||
const sizeAt = pos + 7 + nameLength + ((nameLength + 1) % 2);
|
||||
if (sizeAt + 4 > to) return false;
|
||||
const size = buf.readUInt32BE(sizeAt);
|
||||
const data = sizeAt + 4;
|
||||
if (data + size > to) return false;
|
||||
if (id === IPTC_RESOURCE_ID && !blankIimLocation(buf, data, data + size)) return false;
|
||||
pos = data + size + (size % 2);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Cleans the IPTC place fields of every Photoshop APP13 segment ahead of the image data. */
|
||||
function blankJpegIptc(buf: Buffer): boolean {
|
||||
let pos = 2;
|
||||
while (pos + 4 <= buf.length && buf[pos] === 0xff) {
|
||||
const marker = buf[pos + 1];
|
||||
// A fill byte ahead of the marker.
|
||||
if (marker === 0xff) {
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
// Start of scan or end of image: no metadata segment follows.
|
||||
if (marker === 0xda || marker === 0xd9) break;
|
||||
const end = pos + 2 + buf.readUInt16BE(pos + 2);
|
||||
if (end > buf.length) break;
|
||||
const markAt = pos + 4;
|
||||
const isPhotoshop = buf.subarray(markAt, markAt + PHOTOSHOP_MARK.length).equals(PHOTOSHOP_MARK);
|
||||
if (marker === 0xed && isPhotoshop && !blankPhotoshopIptc(buf, markAt + PHOTOSHOP_MARK.length, end)) return false;
|
||||
pos = end;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Containers held in memory ───────────────────────────────────────────────
|
||||
|
||||
/** WebP may carry its EXIF chunk without the "Exif\0\0" prefix the generic scan looks for. */
|
||||
function blankWebpExifChunk(buf: Buffer): void {
|
||||
let pos = 12;
|
||||
while (pos + 8 <= buf.length) {
|
||||
const size = buf.readUInt32LE(pos + 4);
|
||||
const data = pos + 8;
|
||||
if (buf.toString('latin1', pos, pos + 4) === 'EXIF') blankTiffGps(buf, data, Math.min(buf.length, data + size));
|
||||
pos = data + size + (size % 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PNG checksums every chunk, so it is walked rather than scanned: eXIf loses
|
||||
* its GPS block, an uncompressed XMP iTXt its location properties, and a text
|
||||
* chunk that carries metadata this cannot read in place (compressed XMP, an
|
||||
* ImageMagick "Raw profile") is renamed to a private ancillary type every
|
||||
* decoder skips, with its data zeroed. Each changed chunk gets a new CRC.
|
||||
*/
|
||||
function redactPng(buf: Buffer): boolean {
|
||||
let pos = 8;
|
||||
while (pos + 12 <= buf.length) {
|
||||
const length = buf.readUInt32BE(pos);
|
||||
const type = buf.toString('latin1', pos + 4, pos + 8);
|
||||
const data = pos + 8;
|
||||
const end = data + length;
|
||||
if (end + 4 > buf.length) return false;
|
||||
let changed = false;
|
||||
if (type === 'eXIf') {
|
||||
const tiff = buf.subarray(data, data + EXIF_MARK.length).equals(EXIF_MARK) ? data + EXIF_MARK.length : data;
|
||||
if (!blankTiffGps(buf, tiff, end)) return false;
|
||||
changed = true;
|
||||
} else if (type === 'iTXt' || type === 'tEXt' || type === 'zTXt') {
|
||||
const keywordEnd = buf.indexOf(0, data);
|
||||
const keyword = buf
|
||||
.toString('latin1', data, keywordEnd === -1 || keywordEnd > end ? end : keywordEnd)
|
||||
.toLowerCase();
|
||||
if (keyword.includes('xmp') || keyword.includes('exif') || keyword.startsWith('raw profile')) {
|
||||
const plainXmp = type === 'iTXt' && keyword === 'xml:com.adobe.xmp' && buf[keywordEnd + 1] === 0;
|
||||
if (plainXmp) {
|
||||
if (!blankAllXmp(buf, keywordEnd, end)) return false;
|
||||
} else {
|
||||
buf.write('prIv', pos + 4, 'latin1');
|
||||
buf.fill(0, data, end);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) buf.writeUInt32BE(zlib.crc32(buf.subarray(pos + 4, end)), end);
|
||||
if (type === 'IEND') break;
|
||||
pos = end + 4;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redacts an image held in memory, in place. False for a format this does not
|
||||
* know (BMP, a truncated file) or a metadata block it could not parse.
|
||||
*/
|
||||
export function redactLocationInBuffer(buf: Buffer): boolean {
|
||||
const format = sniffFormat(buf);
|
||||
switch (format) {
|
||||
case 'png':
|
||||
return redactPng(buf);
|
||||
case 'tiff':
|
||||
if (!blankTiffGps(buf, 0, buf.length)) return false;
|
||||
break;
|
||||
case 'webp':
|
||||
blankWebpExifChunk(buf);
|
||||
break;
|
||||
case 'jpeg':
|
||||
if (!blankJpegIptc(buf)) return false;
|
||||
break;
|
||||
case 'gif':
|
||||
case 'isobmff':
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
blankAllExif(buf);
|
||||
return blankAllXmp(buf);
|
||||
}
|
||||
|
||||
// ── Movies (QuickTime / MP4), patched on disk ───────────────────────────────
|
||||
|
||||
interface Box {
|
||||
type: string;
|
||||
start: number;
|
||||
body: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
async function readAt(handle: FileHandle, position: number, length: number): Promise<Buffer> {
|
||||
const buf = Buffer.alloc(length);
|
||||
const { bytesRead } = await handle.read(buf, 0, length, position);
|
||||
return buf.subarray(0, bytesRead);
|
||||
}
|
||||
|
||||
/** Runs `step` on each item in order, stopping at the first false. */
|
||||
function everyInOrder<T>(items: readonly T[], step: (item: T) => Promise<boolean>): Promise<boolean> {
|
||||
return items.reduce<Promise<boolean>>((done, item) => done.then((ok) => ok && step(item)), Promise.resolve(true));
|
||||
}
|
||||
|
||||
/** The boxes in [from, to), headers only; null when one overruns its parent. */
|
||||
async function readBoxes(handle: FileHandle, from: number, to: number, found: Box[] = []): Promise<Box[] | null> {
|
||||
if (from + 8 > to) return found;
|
||||
const head = await readAt(handle, from, 16);
|
||||
if (head.length < 8) return null;
|
||||
let size = head.readUInt32BE(0);
|
||||
let headerLength = 8;
|
||||
if (size === 1) {
|
||||
if (head.length < 16) return null;
|
||||
size = Number(head.readBigUInt64BE(8));
|
||||
headerLength = 16;
|
||||
} else if (size === 0) {
|
||||
size = to - from;
|
||||
}
|
||||
if (size < headerLength || from + size > to) return null;
|
||||
found.push({ type: head.toString('latin1', 4, 8), start: from, body: from + headerLength, end: from + size });
|
||||
return readBoxes(handle, from + size, to, found);
|
||||
}
|
||||
|
||||
async function blankXmpRegion(handle: FileHandle, from: number, to: number): Promise<boolean> {
|
||||
if (to - from > MAX_XMP_BYTES) return false;
|
||||
const buf = await readAt(handle, from, to - from);
|
||||
if (!blankAllXmp(buf)) return false;
|
||||
await handle.write(buf, 0, buf.length, from);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Zeroes the value of every `data` box inside an ilst item, keeping their headers. */
|
||||
async function zeroItemValues(handle: FileHandle, item: Box): Promise<boolean> {
|
||||
const values = await readBoxes(handle, item.body, item.end);
|
||||
if (!values) return false;
|
||||
// data box: size, 'data', type indicator (4), locale (4), then the value.
|
||||
const data = values.filter((value) => value.type === 'data' && value.end > value.body + 8);
|
||||
await Promise.all(
|
||||
data.map((value) =>
|
||||
handle.write(Buffer.alloc(value.end - value.body - 8), 0, value.end - value.body - 8, value.body + 8),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 1-based indexes of the `keys` entries that name a location (com.apple.quicktime.location.ISO6709 …). */
|
||||
async function locationKeyIndexes(handle: FileHandle, keys: Box): Promise<Set<number> | null> {
|
||||
if (keys.end - keys.body > MAX_XMP_BYTES) return null;
|
||||
const buf = await readAt(handle, keys.body, keys.end - keys.body);
|
||||
const found = new Set<number>();
|
||||
if (buf.length < 8) return found;
|
||||
const count = buf.readUInt32BE(4);
|
||||
let pos = 8;
|
||||
for (let index = 1; index <= count; index++) {
|
||||
if (pos + 8 > buf.length) return null;
|
||||
const size = buf.readUInt32BE(pos);
|
||||
if (size < 8 || pos + size > buf.length) return null;
|
||||
const name = buf.toString('latin1', pos + 8, pos + size).toLowerCase();
|
||||
if (name.includes('location')) found.add(index);
|
||||
pos += size;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
async function redactItemList(handle: FileHandle, ilst: Box, locationKeys: Set<number>): Promise<boolean> {
|
||||
const items = await readBoxes(handle, ilst.body, ilst.end);
|
||||
if (!items) return false;
|
||||
// An item's type is the 1-based index of its key, or an iTunes atom name.
|
||||
const located = items.filter(
|
||||
(item) => item.type === LOCATION_ATOM || locationKeys.has(Buffer.from(item.type, 'latin1').readUInt32BE(0)),
|
||||
);
|
||||
return everyInOrder(located, (item) => zeroItemValues(handle, item));
|
||||
}
|
||||
|
||||
async function redactMeta(handle: FileHandle, meta: Box): Promise<boolean> {
|
||||
// ISO meta is a full box (4 bytes of version and flags before its children);
|
||||
// QuickTime's moov/meta is not. The handler box always comes first.
|
||||
const peek = await readAt(handle, meta.body, 12);
|
||||
const childrenFrom = peek.toString('latin1', 4, 8) === 'hdlr' ? meta.body : meta.body + 4;
|
||||
const children = await readBoxes(handle, childrenFrom, meta.end);
|
||||
if (!children) return false;
|
||||
const keys = children.find((child) => child.type === 'keys');
|
||||
const locationKeys = keys ? await locationKeyIndexes(handle, keys) : new Set<number>();
|
||||
if (!locationKeys) return false;
|
||||
return everyInOrder(children, (child) =>
|
||||
child.type === 'ilst' ? redactItemList(handle, child, locationKeys) : redactMovieBox(handle, child),
|
||||
);
|
||||
}
|
||||
|
||||
const MOVIE_CONTAINERS = new Set(['moov', 'trak', 'udta']);
|
||||
|
||||
/** Whether the ftyp box at the start of `head` names a still HEIF/AVIF image. */
|
||||
function isStillImageBrand(head: Buffer): boolean {
|
||||
return head.length >= 12 && STILL_IMAGE_BRANDS.has(head.toString('latin1', 8, 12));
|
||||
}
|
||||
|
||||
async function redactMovieBox(handle: FileHandle, box: Box): Promise<boolean> {
|
||||
if (MOVIE_CONTAINERS.has(box.type)) {
|
||||
const children = await readBoxes(handle, box.body, box.end);
|
||||
return children !== null && everyInOrder(children, (child) => redactMovieBox(handle, child));
|
||||
}
|
||||
switch (box.type) {
|
||||
case 'meta':
|
||||
return redactMeta(handle, box);
|
||||
case LOCATION_ATOM:
|
||||
case 'loci':
|
||||
// The place atoms phones and cameras write into udta (ISO 6709 string,
|
||||
// 3GPP location). A free box of the same size is skipped by every
|
||||
// reader, and its content is zeroed with it.
|
||||
await handle.write(Buffer.from('free', 'latin1'), 0, 4, box.start + 4);
|
||||
await handle.write(Buffer.alloc(box.end - box.body), 0, box.end - box.body, box.body);
|
||||
return true;
|
||||
case 'XMP_':
|
||||
return blankXmpRegion(handle, box.body, box.end);
|
||||
case 'uuid': {
|
||||
const id = await readAt(handle, box.body, 16);
|
||||
return id.equals(XMP_UUID) ? blankXmpRegion(handle, box.body + 16, box.end) : true;
|
||||
}
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** exifr as a second opinion on an image: any GPS it still reads fails the file. */
|
||||
async function exifrFindsGps(buf: Buffer): Promise<boolean> {
|
||||
try {
|
||||
const gps = (await exifr.gps(buf)) as { latitude?: number } | undefined;
|
||||
return gps?.latitude !== undefined && Number.isFinite(gps.latitude);
|
||||
} catch {
|
||||
// A file exifr cannot read holds nothing it would hand out either.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Redacts the media file at `file` in place (the caller's own copy). True when
|
||||
* it now carries no location this knows of; false when the format is unknown
|
||||
* or a metadata block could not be cleaned, and the file must not be served.
|
||||
*/
|
||||
export async function redactLocationInFile(file: string): Promise<boolean> {
|
||||
const handle = await fsPromises.open(file, 'r+');
|
||||
try {
|
||||
const { size } = await handle.stat();
|
||||
const head = await readAt(handle, 0, 16);
|
||||
const format = sniffFormat(head);
|
||||
// WebM/Matroska has no location field a camera or phone writes.
|
||||
if (format === 'ebml') return true;
|
||||
let walked = true;
|
||||
if (format === 'isobmff' || format === 'quicktime') {
|
||||
const top = await readBoxes(handle, 0, size);
|
||||
if (top?.some((box) => box.type === 'moov')) return await everyInOrder(top, (box) => redactMovieBox(handle, box));
|
||||
// The image path never reaches udta atoms, so a movie this cannot walk
|
||||
// (truncated, junk after mdat) is refused. Only a still HEIF/AVIF image
|
||||
// goes on to be cleaned in memory.
|
||||
if (format === 'quicktime' || !isStillImageBrand(head)) return false;
|
||||
walked = top !== null;
|
||||
}
|
||||
if (format === 'unknown' || size > MAX_IMAGE_BYTES) return false;
|
||||
const buf = await readAt(handle, 0, size);
|
||||
// An image whose boxes did not parse may still hide a movie header.
|
||||
if (!walked && buf.includes(MOOV)) return false;
|
||||
if (!redactLocationInBuffer(buf)) return false;
|
||||
await handle.write(buf, 0, buf.length, 0);
|
||||
return !(await exifrFindsGps(buf));
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import { PhotoProviderRegistry } from './photo-provider.registry';
|
||||
import { PhotoResolverService } from './photo-resolver.service';
|
||||
import { ImmichPhotoProvider } from './providers/immich.provider';
|
||||
import { SynologyPhotoProvider } from './providers/synology.provider';
|
||||
import { PublicMediaService } from './public-media.service';
|
||||
import { SynologyCaptureRepairJob } from './synology-capture-repair.job';
|
||||
import { SynologyMemoriesController } from './synology.controller';
|
||||
import { SynologyService } from './synology.service';
|
||||
@@ -108,6 +109,7 @@ import { Module } from '@nestjs/common';
|
||||
UnifiedMemoriesService,
|
||||
PhotoResolverService,
|
||||
PhotoCaptureBackfillService,
|
||||
PublicMediaService,
|
||||
ThumbnailService,
|
||||
TrekPhotoCacheService,
|
||||
TrekPhotoCacheJob,
|
||||
@@ -127,6 +129,7 @@ import { Module } from '@nestjs/common';
|
||||
MemoriesAccessService,
|
||||
PhotoResolverService,
|
||||
PhotoCaptureBackfillService,
|
||||
PublicMediaService,
|
||||
ImmichService,
|
||||
SynologyService,
|
||||
PhotoProviderRegistry,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { StorageService } from '../storage/storage.service';
|
||||
import { fail, success, type AssetInfo, type ServiceResult } from './memories.helpers';
|
||||
import type { PhotoAssetRef } from './photo-provider';
|
||||
import { PhotoProviderRegistry } from './photo-provider.registry';
|
||||
import { PublicMediaService } from './public-media.service';
|
||||
import { ThumbnailService } from './thumbnail.service';
|
||||
import { TrekPhotoCacheService } from './trek-photo-cache.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -24,6 +25,12 @@ export type PhotoSignalSource =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'unavailable' };
|
||||
|
||||
/** Who a local file goes to: its owner or a member as stored, the public as a location-free copy. */
|
||||
type Audience = 'owner' | 'public';
|
||||
|
||||
const THUMB_CACHE = 'public, max-age=86400, immutable';
|
||||
const ORIGINAL_CACHE = 'public, max-age=86400';
|
||||
|
||||
/**
|
||||
* Resolves a stored trek_photo to bytes or metadata by asking whichever provider
|
||||
* owns it. The storage half of the old photoResolverService lives in
|
||||
@@ -42,6 +49,7 @@ export class PhotoResolverService {
|
||||
private readonly cache: TrekPhotoCacheService,
|
||||
private readonly providers: PhotoProviderRegistry,
|
||||
private readonly storage: StorageService,
|
||||
private readonly publicMedia: PublicMediaService,
|
||||
) {}
|
||||
|
||||
/** photos.file_path / thumbnail_path are uploads-relative 'journey/…' by
|
||||
@@ -83,12 +91,76 @@ export class PhotoResolverService {
|
||||
await fallback();
|
||||
}
|
||||
|
||||
/** An owner's or member's view: local files go out as stored. */
|
||||
async streamPhoto(
|
||||
res: Response,
|
||||
userId: number,
|
||||
photoId: number,
|
||||
kind: 'thumbnail' | 'original',
|
||||
range?: string,
|
||||
): Promise<void> {
|
||||
await this.stream(res, userId, photoId, kind, range, 'owner');
|
||||
}
|
||||
|
||||
/**
|
||||
* A public share's view. A local file goes out as its location-free copy
|
||||
* (PublicMediaService) and never as stored; one that cannot be cleaned falls
|
||||
* back to the thumbnail TREK re-encoded itself, else a 404. Provider assets
|
||||
* stream as for an owner.
|
||||
*/
|
||||
async streamPublicPhoto(
|
||||
res: Response,
|
||||
ownerId: number,
|
||||
photoId: number,
|
||||
kind: 'thumbnail' | 'original',
|
||||
): Promise<void> {
|
||||
await this.stream(res, ownerId, photoId, kind, undefined, 'public');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one local journey object. For the public a re-encoded thumbnail
|
||||
* (thumbs/, written by ThumbnailService, no metadata) goes out as is, anything
|
||||
* else as its location-free copy. False when there is nothing safe to send.
|
||||
*/
|
||||
private async sendLocal(res: Response, relPath: string, audience: Audience, cacheControl: string): Promise<boolean> {
|
||||
const name = this.storageName(relPath);
|
||||
if (!name || !(await this.storage.exists('journey', name).catch(() => false))) return false;
|
||||
let served = name;
|
||||
if (audience === 'public' && !name.startsWith('thumbs/')) {
|
||||
const rendition = await this.publicMedia.renditionFor('journey', name).catch(() => null);
|
||||
if (!rendition) return false;
|
||||
served = rendition;
|
||||
}
|
||||
res.set('Cache-Control', cacheControl);
|
||||
res.set('X-Content-Type-Options', 'nosniff');
|
||||
await this.storage.sendToResponse('journey', served, res);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The thumbnail row path, generated for a raster image that has none yet.
|
||||
*
|
||||
* @txStandalone an idempotent lazy provision: the row only records a
|
||||
* thumbnail that already exists in storage, whatever the caller does next.
|
||||
*/
|
||||
private async localThumbnail(photo: TrekPhoto): Promise<string | null> {
|
||||
if (photo.thumbnail_path) return photo.thumbnail_path;
|
||||
// Only raster images get a lazily-generated Jimp thumbnail; Jimp can't decode
|
||||
// video, so a video relies on the poster captured at upload (#823).
|
||||
if (photo.media_type === 'video' || !photo.file_path) return null;
|
||||
const result = await this.thumbnails.ensureLocalThumbnail(photo.file_path);
|
||||
if (!result) return null;
|
||||
await this.photos.recordLocalThumbnail(photo.id, result.thumbnailRelPath, result.width, result.height);
|
||||
return result.thumbnailRelPath;
|
||||
}
|
||||
|
||||
private async stream(
|
||||
res: Response,
|
||||
userId: number,
|
||||
photoId: number,
|
||||
kind: 'thumbnail' | 'original',
|
||||
range: string | undefined,
|
||||
audience: Audience,
|
||||
): Promise<void> {
|
||||
const photo = await this.photos.resolve(photoId);
|
||||
if (!photo) {
|
||||
@@ -98,41 +170,24 @@ export class PhotoResolverService {
|
||||
|
||||
if (photo.file_path) {
|
||||
if (kind === 'thumbnail') {
|
||||
const isVideo = photo.media_type === 'video';
|
||||
let thumbRel = photo.thumbnail_path ?? null;
|
||||
// Only raster images get a lazily-generated Jimp thumbnail; Jimp can't decode
|
||||
// video, so a video relies on the poster captured at upload (#823).
|
||||
if (!thumbRel && !isVideo) {
|
||||
const result = await this.thumbnails.ensureLocalThumbnail(photo.file_path);
|
||||
if (result) {
|
||||
thumbRel = result.thumbnailRelPath;
|
||||
await this.photos.recordLocalThumbnail(photo.id, thumbRel, result.width, result.height);
|
||||
}
|
||||
}
|
||||
if (thumbRel) {
|
||||
const thumbName = this.storageName(thumbRel);
|
||||
if (thumbName && (await this.storage.exists('journey', thumbName).catch(() => false))) {
|
||||
res.set('Cache-Control', 'public, max-age=86400, immutable');
|
||||
res.set('X-Content-Type-Options', 'nosniff');
|
||||
await this.storage.sendToResponse('journey', thumbName, res);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const thumbRel = await this.localThumbnail(photo);
|
||||
if (thumbRel && (await this.sendLocal(res, thumbRel, audience, THUMB_CACHE))) return;
|
||||
// A poster-less video must NOT fall through to streaming the whole file as a
|
||||
// "thumbnail"; let the client render its own placeholder instead.
|
||||
if (isVideo) {
|
||||
if (photo.media_type === 'video') {
|
||||
res.status(404).json({ error: 'No poster available' });
|
||||
return;
|
||||
}
|
||||
// Images fall through to original if the thumbnail is unavailable.
|
||||
}
|
||||
|
||||
const name = this.storageName(photo.file_path);
|
||||
if (name && (await this.storage.exists('journey', name).catch(() => false))) {
|
||||
res.set('Cache-Control', 'public, max-age=86400');
|
||||
res.set('X-Content-Type-Options', 'nosniff');
|
||||
await this.storage.sendToResponse('journey', name, res);
|
||||
return;
|
||||
if (await this.sendLocal(res, photo.file_path, audience, ORIGINAL_CACHE)) return;
|
||||
|
||||
// A public original that could not be cleaned is stood in for by the
|
||||
// re-encoded thumbnail, never by the stored bytes.
|
||||
if (audience === 'public' && kind === 'original' && photo.media_type !== 'video') {
|
||||
const thumbRel = await this.localThumbnail(photo);
|
||||
if (thumbRel && (await this.sendLocal(res, thumbRel, audience, THUMB_CACHE))) return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { Journeys } from '../../db/entities/Journeys.entity';
|
||||
import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
|
||||
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
|
||||
import type { TrekPhotosRepository } from '../../db/repositories/TrekPhotos.repository';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageNotFoundError, type ServedCategory } from '../storage/storage.types';
|
||||
import { redactLocationInFile } from './media-redact';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { Jimp } from 'jimp';
|
||||
import crypto from 'node:crypto';
|
||||
import fsPromises from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Location-free copies live beside their source, under this prefix, in the source's category. */
|
||||
const RENDITION_PREFIX = 'public/';
|
||||
|
||||
/** The categories whose objects reach a viewer without an account and so get renditions. */
|
||||
const RENDITION_CATEGORIES: readonly ServedCategory[] = ['avatars', 'covers', 'journey', 'places', 'photos'];
|
||||
|
||||
/** Image types Jimp both decodes and writes; it writes no metadata, so a re-encoded copy carries no location. */
|
||||
const REENCODABLE_EXTENSIONS = new Set(['.bmp', '.gif', '.jpeg', '.jpg', '.png', '.tif', '.tiff']);
|
||||
|
||||
/** How many copies the sweep checks at once, so a large instance does not open thousands of handles. */
|
||||
const SWEEP_BATCH = 32;
|
||||
|
||||
/** Runs `step` on each batch of `items` in turn and sums what it returns. */
|
||||
function sumInBatches<T>(items: readonly T[], size: number, step: (batch: readonly T[]) => Promise<number>) {
|
||||
const batches: T[][] = [];
|
||||
for (let i = 0; i < items.length; i += size) batches.push(items.slice(i, i + size));
|
||||
return batches.reduce<Promise<number>>(
|
||||
(done, batch) => done.then(async (sum) => sum + (await step(batch))),
|
||||
Promise.resolve(0),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What every byte path without an account serves instead of a stored
|
||||
* original: a copy with the location taken out (media-redact.ts), made on the
|
||||
* first request and kept as `public/<name>` in the same category until the
|
||||
* source changes. When the metadata cannot be cleaned in place, a raster image
|
||||
* is re-encoded instead, so an upload that rendered before keeps rendering.
|
||||
* Owners and members keep getting the original itself.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PublicMediaService {
|
||||
private readonly inFlight = new Map<string, Promise<string | null>>();
|
||||
|
||||
constructor(
|
||||
private readonly storage: StorageService,
|
||||
@InjectRepository(Journeys) private readonly journeys: JourneysRepository,
|
||||
@InjectRepository(TrekPhotos) private readonly trekPhotos: TrekPhotosRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The storage name of the location-free copy of `name`, or null when none
|
||||
* can be made safely (a movie or format that can be neither cleaned nor
|
||||
* re-encoded): the caller then serves nothing rather than the original. A
|
||||
* missing source throws StorageNotFoundError, an invalid name
|
||||
* StorageInvalidKeyError.
|
||||
*/
|
||||
async renditionFor(category: ServedCategory, name: string): Promise<string | null> {
|
||||
if (name.startsWith(RENDITION_PREFIX)) return null;
|
||||
const rendition = RENDITION_PREFIX + name;
|
||||
const [source, existing] = await Promise.all([
|
||||
this.storage.stat(category, name),
|
||||
this.storage.stat(category, rendition),
|
||||
]);
|
||||
if (!source) throw new StorageNotFoundError(`${category}/${name}`);
|
||||
if (existing && existing.mtimeMs >= source.mtimeMs) return rendition;
|
||||
|
||||
const key = `${category}/${name}`;
|
||||
let pending = this.inFlight.get(key);
|
||||
if (pending === undefined) {
|
||||
pending = this.build(category, name, rendition).finally(() => this.inFlight.delete(key));
|
||||
this.inFlight.set(key, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether /uploads/journey may answer for `name`. Journey entry media (a
|
||||
* trek_photos original or poster, and the thumbs/ TREK derives from them)
|
||||
* goes only through the token-checked and session-checked proxies, so
|
||||
* revoking a share link takes it away; a journey cover, and any other
|
||||
* object a trip cover or place image may point at, stays reachable.
|
||||
*/
|
||||
async servesFromJourneyMount(name: string): Promise<boolean> {
|
||||
const spellings = [`journey/${name}`, `/uploads/journey/${name}`];
|
||||
if (await this.journeys.isCoverImage(spellings)) return true;
|
||||
if (name.startsWith('thumbs/')) return false;
|
||||
return !(await this.trekPhotos.referencesLocalPath(spellings));
|
||||
}
|
||||
|
||||
/** Deletes the renditions whose source is gone. Returns how many went. */
|
||||
sweepOrphans(): Promise<number> {
|
||||
// One category after another, each in bounded batches.
|
||||
return RENDITION_CATEGORIES.reduce<Promise<number>>(
|
||||
(done, category) => done.then(async (sum) => sum + (await this.sweepCategory(category))),
|
||||
Promise.resolve(0),
|
||||
);
|
||||
}
|
||||
|
||||
private async sweepCategory(category: ServedCategory): Promise<number> {
|
||||
const keys: string[] = [];
|
||||
for await (const stat of this.storage.list(category, RENDITION_PREFIX)) keys.push(stat.key);
|
||||
return sumInBatches(keys, SWEEP_BATCH, async (batch) => {
|
||||
const removed = await Promise.all(batch.map((key) => this.dropIfOrphaned(category, key)));
|
||||
return removed.filter(Boolean).length;
|
||||
});
|
||||
}
|
||||
|
||||
private async dropIfOrphaned(category: ServedCategory, key: string): Promise<boolean> {
|
||||
// A source that cannot be checked right now counts as present.
|
||||
if (await this.storage.exists(category, key.slice(RENDITION_PREFIX.length)).catch(() => true)) return false;
|
||||
if (this.storage.keepsOnDelete(category, key)) return false;
|
||||
return this.storage.delete(category, key).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
|
||||
private async build(category: ServedCategory, name: string, rendition: string): Promise<string | null> {
|
||||
const extension = path.extname(name).toLowerCase();
|
||||
const spool = path.join(this.storage.spoolDirFor(category), `public-${crypto.randomUUID()}${extension}`);
|
||||
try {
|
||||
await this.storage.withLocalFile(category, name, (source) => fsPromises.copyFile(source, spool));
|
||||
if (!(await redactLocationInFile(spool)) && !(await this.reencode(category, name, spool, extension))) {
|
||||
logWarn(`Public media: ${category}/${name} could not be cleaned of its location and is not served publicly`);
|
||||
return null;
|
||||
}
|
||||
await this.storage.put(category, rendition, { tmpPath: spool });
|
||||
return rendition;
|
||||
} finally {
|
||||
await fsPromises.rm(spool, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a fresh, metadata-free encoding of the source to `spool`; false when Jimp cannot handle it. */
|
||||
private async reencode(category: ServedCategory, name: string, spool: string, extension: string): Promise<boolean> {
|
||||
if (!REENCODABLE_EXTENSIONS.has(extension)) return false;
|
||||
try {
|
||||
// Jimp applies the EXIF orientation on read, so the copy shows upright without it.
|
||||
const image = await this.storage.withLocalFile(category, name, (source) => Jimp.read(source));
|
||||
await image.write(spool as Parameters<typeof image.write>[0]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { UserSessionsRepository } from '../../db/repositories/UserSessions.
|
||||
import type { UsersRepository } from '../../db/repositories/Users.repository';
|
||||
import { verifyJwtAndLoadUser } from '../auth-core/jwt-verify';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
import type { PublicMediaService } from '../memories/public-media.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types';
|
||||
import { precompressedStatic } from './precompressed-static';
|
||||
@@ -67,6 +68,17 @@ export function answerUnmatchedGet(req: Request, res: Response, message = 'Not F
|
||||
res.sendFile('index.html', { root: PUBLIC_DIR });
|
||||
}
|
||||
|
||||
/**
|
||||
* What a public mount may serve and in which form: `allows` gates the name
|
||||
* (the journey mount refuses journey entry media), `rendition` names the
|
||||
* location-free copy to send instead of the stored object, or null when there
|
||||
* is none, which reads as a miss.
|
||||
*/
|
||||
interface PublicServing {
|
||||
allows?: (name: string) => Promise<boolean>;
|
||||
rendition: (name: string) => Promise<string | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* express.static replacement for the four public /uploads mounts (storage
|
||||
* slice 3). Parity contract (spec §Serving): identical ETag / Last-Modified /
|
||||
@@ -76,9 +88,14 @@ export function answerUnmatchedGet(req: Request, res: Response, message = 'Not F
|
||||
* next() so the request falls through to the Nest router's standard 404
|
||||
* envelope, exactly like express.static's fallthrough. 412/416/5xx go to
|
||||
* next(err) with send's own http-errors — the same finalhandler path
|
||||
* express.static uses.
|
||||
* express.static uses. With `serving`, the handler sends the location-free
|
||||
* copy it names instead of the object, and a name it refuses is a miss.
|
||||
*/
|
||||
export function storageStaticHandler(storage: StorageService, category: StorageCategory): express.RequestHandler {
|
||||
export function storageStaticHandler(
|
||||
storage: StorageService,
|
||||
category: StorageCategory,
|
||||
serving?: PublicServing,
|
||||
): express.RequestHandler {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
// serve-static fallthrough: non-GET/HEAD pass straight through (no 405).
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
@@ -96,27 +113,36 @@ export function storageStaticHandler(storage: StorageService, category: StorageC
|
||||
return;
|
||||
}
|
||||
const name = decoded.replace(/^\/+/, '');
|
||||
return storage.sendToResponse(category, name, res).catch((err: unknown) => {
|
||||
// MISS contract: unknown object, invalid key ('' at the mount root,
|
||||
// '..', dot segments, control chars) → Nest 404 envelope.
|
||||
if (err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const e = err as { status?: number; code?: string; syscall?: string };
|
||||
// stat→sendFile race (send 404) and directories: static falls through too.
|
||||
if (e.status === 404 || e.code === 'EISDIR') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
// Client gone / bytes already on the wire: nothing useful to send —
|
||||
// mirrors res.sendFile's own default callback (express response.js:454).
|
||||
if (e.code === 'ECONNABORTED' || e.syscall === 'write') return;
|
||||
next(err as Error);
|
||||
});
|
||||
return resolveServedName(name, serving)
|
||||
.then((served) => (served === null ? next() : storage.sendToResponse(category, served, res)))
|
||||
.catch((err: unknown) => {
|
||||
// MISS contract: unknown object, invalid key ('' at the mount root,
|
||||
// '..', dot segments, control chars) → Nest 404 envelope.
|
||||
if (err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const e = err as { status?: number; code?: string; syscall?: string };
|
||||
// stat→sendFile race (send 404) and directories: static falls through too.
|
||||
if (e.status === 404 || e.code === 'EISDIR') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
// Client gone / bytes already on the wire: nothing useful to send —
|
||||
// mirrors res.sendFile's own default callback (express response.js:454).
|
||||
if (e.code === 'ECONNABORTED' || e.syscall === 'write') return;
|
||||
next(err as Error);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/** The object name a static mount sends for `name`, or null for a miss. */
|
||||
async function resolveServedName(name: string, serving: PublicServing | undefined): Promise<string | null> {
|
||||
if (!serving) return name;
|
||||
if (serving.allows && !(await serving.allows(name))) return null;
|
||||
return serving.rendition(name);
|
||||
}
|
||||
|
||||
async function servePhoto(
|
||||
storage: StorageService,
|
||||
req: Request,
|
||||
@@ -125,6 +151,7 @@ async function servePhoto(
|
||||
shareTokens: ShareTokensRepository,
|
||||
photos: PhotosRepository,
|
||||
sessions: UserSessionsRepository,
|
||||
publicMedia: PublicMediaService | undefined,
|
||||
): Promise<void> {
|
||||
const safeName = path.basename(req.params.filename);
|
||||
// Parity: after basename(), the old resolve()+startsWith guard could only
|
||||
@@ -139,8 +166,8 @@ async function servePhoto(
|
||||
res.status(404).send('Not found');
|
||||
return;
|
||||
}
|
||||
const sendPhoto = () =>
|
||||
storage.sendToResponse('photos', safeName, res).catch((err: unknown) => {
|
||||
const sendPhoto = (name = safeName) =>
|
||||
storage.sendToResponse('photos', name, res).catch((err: unknown) => {
|
||||
// exists→send delete race: same 404 text as the miss branch.
|
||||
if ((err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) && !res.headersSent) {
|
||||
res.status(404).send('Not found');
|
||||
@@ -172,7 +199,15 @@ async function servePhoto(
|
||||
res.status(401).send('Authentication required');
|
||||
return;
|
||||
}
|
||||
return sendPhoto();
|
||||
// A share link is no account: it gets the copy without the location, and a
|
||||
// photo that cannot be cleaned is not sent at all (fail closed, also when no
|
||||
// PublicMediaService was wired).
|
||||
const rendition = publicMedia ? await publicMedia.renditionFor('photos', safeName).catch(() => null) : null;
|
||||
if (!rendition) {
|
||||
res.status(404).send('Not found');
|
||||
return;
|
||||
}
|
||||
return sendPhoto(rendition);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -221,29 +256,44 @@ export function applyPlatformUploads(
|
||||
app: express.Application,
|
||||
storage: StorageService,
|
||||
orm?: { em: EntityManager },
|
||||
publicMedia?: PublicMediaService,
|
||||
): void {
|
||||
// Static: avatars, covers, and journey photos.
|
||||
// Static: avatars, covers, journey covers and place images.
|
||||
//
|
||||
// Security model (audit SEC-M9): these paths are unauthenticated by
|
||||
// design. All filenames are server-chosen UUID v4 (see `uuid()` in
|
||||
// the multer storage config for avatars / covers / journey uploads),
|
||||
// which gives each asset >122 bits of namespace entropy — not
|
||||
// guessable via enumeration. An attacker would need to have already
|
||||
// seen the URL (email, shared journey, etc.) to request the file.
|
||||
//
|
||||
// Moving these behind auth would also break:
|
||||
// - Unauthenticated trip-card rendering on public share links
|
||||
// - Journey public-share pages (/public/journey/:token)
|
||||
// - Email-embedded avatars
|
||||
// Security model (audit SEC-M9): these paths are unauthenticated by design,
|
||||
// because share-link trip cards, journey public pages and email-embedded
|
||||
// avatars load them without a session. Filenames are server-chosen UUID v4
|
||||
// (>122 bits), so nothing can be enumerated, but a URL that was seen once
|
||||
// keeps working, so two rules bound what it can hand out:
|
||||
// - Every object goes out as its location-free copy (PublicMediaService:
|
||||
// EXIF GPS, IPTC and XMP place fields and movie location atoms blanked,
|
||||
// or a fresh re-encode of an image whose metadata cannot be cleaned),
|
||||
// never as uploaded; only what can be neither is a 404.
|
||||
// - /uploads/journey does not serve journey entry media (originals,
|
||||
// posters, thumbs/) unless a journey uses it as its cover. Those go
|
||||
// through the token-checked /api/public/journey proxy or the
|
||||
// session-checked ones, so revoking a share link takes them away.
|
||||
// Covers, and other objects a trip cover or place image points at,
|
||||
// stay reachable.
|
||||
// Without PublicMediaService (a partial test wiring) the four mounts serve
|
||||
// nothing rather than the raw bytes.
|
||||
//
|
||||
// The `/uploads/photos/...` route below is DIFFERENT: photo URLs are
|
||||
// not embedded in unauthenticated UI contexts, so that endpoint IS
|
||||
// gated (session JWT with pv, or a share token scoped to the photo's
|
||||
// trip).
|
||||
app.use('/uploads/avatars', storageStaticHandler(storage, 'avatars'));
|
||||
app.use('/uploads/covers', storageStaticHandler(storage, 'covers'));
|
||||
app.use('/uploads/journey', storageStaticHandler(storage, 'journey'));
|
||||
app.use('/uploads/places', storageStaticHandler(storage, 'places'));
|
||||
// trip, which gets the location-free copy too).
|
||||
const serving = (category: StorageCategory, allows?: PublicServing['allows']): PublicServing => ({
|
||||
allows,
|
||||
rendition: (name) => (publicMedia ? publicMedia.renditionFor(category, name) : Promise.resolve(null)),
|
||||
});
|
||||
const servesFromJourneyMount = (name: string): Promise<boolean> => {
|
||||
if (!publicMedia || !orm) return Promise.resolve(false);
|
||||
return withRequestContext(orm, () => publicMedia.servesFromJourneyMount(name));
|
||||
};
|
||||
app.use('/uploads/avatars', storageStaticHandler(storage, 'avatars', serving('avatars')));
|
||||
app.use('/uploads/covers', storageStaticHandler(storage, 'covers', serving('covers')));
|
||||
app.use('/uploads/journey', storageStaticHandler(storage, 'journey', serving('journey', servesFromJourneyMount)));
|
||||
app.use('/uploads/places', storageStaticHandler(storage, 'places', serving('places')));
|
||||
|
||||
// Photos require either a valid logged-in session (via JWT with the
|
||||
// password_version gate) OR a share token that covers the SPECIFIC
|
||||
@@ -264,6 +314,7 @@ export function applyPlatformUploads(
|
||||
orm.em.getRepository(ShareTokens),
|
||||
orm.em.getRepository(Photos),
|
||||
orm.em.getRepository(UserSessions),
|
||||
publicMedia,
|
||||
),
|
||||
).catch(next);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* What each block of the public share payload (GET /api/shared/:token) may
|
||||
* carry. The repositories hand over full rows; these allow-lists pick the
|
||||
* columns the shared page reads, so a column added to a table later never
|
||||
* becomes public by appearing. Names the page does not read stay behind:
|
||||
* owner and author ids, private notes, ticket data, bookkeeping timestamps.
|
||||
*/
|
||||
|
||||
/** A day as the shared page draws it: its number, date and title, never the owner's day notes. */
|
||||
export interface PublicDay {
|
||||
id: number;
|
||||
day_number: number;
|
||||
date: string | null;
|
||||
title: string | null;
|
||||
}
|
||||
|
||||
export function publicDay(d: PublicDay): PublicDay {
|
||||
return { id: d.id, day_number: d.day_number, date: d.date ?? null, title: d.title ?? null };
|
||||
}
|
||||
|
||||
/** A note on a day: its text, the detail line, the icon and colour, and where it sits among the stops. */
|
||||
export interface PublicDayNote {
|
||||
id: number;
|
||||
day_id: number;
|
||||
text: string;
|
||||
time: string | null;
|
||||
icon: string | null;
|
||||
color: string | null;
|
||||
sort_order: number | null;
|
||||
}
|
||||
|
||||
export function publicDayNote(n: PublicDayNote): PublicDayNote {
|
||||
return {
|
||||
id: n.id,
|
||||
day_id: n.day_id,
|
||||
text: n.text,
|
||||
time: n.time ?? null,
|
||||
icon: n.icon ?? null,
|
||||
color: n.color ?? null,
|
||||
sort_order: n.sort_order ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** A Common packing item: what it is, how many, and whether it is packed. Never whose it is. */
|
||||
interface PublicPackingItem {
|
||||
id: number;
|
||||
name: string;
|
||||
category: string | null;
|
||||
checked: number | null;
|
||||
quantity: number | null;
|
||||
sort_order: number | null;
|
||||
}
|
||||
|
||||
export function publicPackingItem(i: PublicPackingItem): PublicPackingItem {
|
||||
return {
|
||||
id: i.id,
|
||||
name: i.name,
|
||||
category: i.category ?? null,
|
||||
checked: i.checked ?? null,
|
||||
quantity: i.quantity ?? null,
|
||||
sort_order: i.sort_order ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An expense: its name, group and amount with the rate it was entered at, which
|
||||
* is all the Costs tab needs to convert it. The note, who paid, the linked
|
||||
* booking and the stored ticket stay with the trip.
|
||||
*/
|
||||
interface PublicBudgetItem {
|
||||
id: number;
|
||||
name: string;
|
||||
category: string;
|
||||
total_price: number;
|
||||
currency: string | null;
|
||||
exchange_rate: number;
|
||||
}
|
||||
|
||||
export function publicBudgetItem(i: PublicBudgetItem): PublicBudgetItem {
|
||||
return {
|
||||
id: i.id,
|
||||
name: i.name,
|
||||
category: i.category,
|
||||
total_price: i.total_price,
|
||||
currency: i.currency ?? null,
|
||||
exchange_rate: i.exchange_rate,
|
||||
};
|
||||
}
|
||||
|
||||
/** A chat message under its author's name and avatar, without the author's account id. */
|
||||
interface PublicCollabMessage {
|
||||
id: number;
|
||||
text: string;
|
||||
created_at: string | null;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
export function publicCollabMessage(m: PublicCollabMessage): PublicCollabMessage {
|
||||
return { id: m.id, text: m.text, created_at: m.created_at ?? null, username: m.username, avatar: m.avatar ?? null };
|
||||
}
|
||||
|
||||
/** A category as the page colours a pin or a stop with it. */
|
||||
interface PublicCategory {
|
||||
id: number;
|
||||
name: string;
|
||||
color: string | null;
|
||||
icon: string | null;
|
||||
}
|
||||
|
||||
interface CategorizedPlace {
|
||||
category_id?: number | null;
|
||||
category_name?: string | null;
|
||||
category_color?: string | null;
|
||||
category_icon?: string | null;
|
||||
}
|
||||
|
||||
interface CategorizedStop {
|
||||
place?: { category?: { id: number; name?: string | null; color?: string | null; icon?: string | null } | null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The categories the shared places use, and only those. Categories are a pool
|
||||
* across all users, so the payload used to carry every one of them, other
|
||||
* users' own included. Read from the places that actually go out, after the
|
||||
* narrowing options ran, so a hidden place does not leave its category behind.
|
||||
*/
|
||||
export function categoriesInUse(
|
||||
places: readonly CategorizedPlace[],
|
||||
assignments: Record<number, readonly CategorizedStop[]>,
|
||||
): PublicCategory[] {
|
||||
const byId = new Map<number, PublicCategory>();
|
||||
const add = (id: number | null | undefined, name: string | null | undefined, color: unknown, icon: unknown) => {
|
||||
// A dangling id or a category without a name has nothing to draw.
|
||||
if (id == null || name == null || byId.has(id)) return;
|
||||
byId.set(id, {
|
||||
id,
|
||||
name,
|
||||
color: typeof color === 'string' ? color : null,
|
||||
icon: typeof icon === 'string' ? icon : null,
|
||||
});
|
||||
};
|
||||
for (const p of places) add(p.category_id, p.category_name, p.category_color, p.category_icon);
|
||||
for (const rows of Object.values(assignments)) {
|
||||
for (const a of rows) {
|
||||
const c = a.place?.category;
|
||||
if (c) add(c.id, c.name, c.color, c.icon);
|
||||
}
|
||||
}
|
||||
return [...byId.values()].sort((a, b) => a.id - b.id);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ interface ShareSnapshot {
|
||||
Array<{ accommodation_id?: number | null; place?: { id: number; image_url?: string | null } }>
|
||||
>;
|
||||
dayNotes: Record<number, unknown[]>;
|
||||
days: Array<{ title?: string | null }>;
|
||||
places: Array<{ id: number; image_url?: string | null }>;
|
||||
reservations: Array<{ type?: unknown }>;
|
||||
}
|
||||
@@ -26,7 +27,8 @@ interface ShareSnapshot {
|
||||
* "Only travel and stays": what family or an emergency contact needs to know,
|
||||
* without the museum and the restaurant. A day keeps only the stop its night's
|
||||
* booking wrote, the notes go, the place pool shrinks to where the trip sleeps,
|
||||
* and the bookings to transport and hotels.
|
||||
* and the bookings to transport and hotels. Day titles go too ("Louvre and
|
||||
* lunch at Marie's" says what the link leaves out); the page then reads "Day N".
|
||||
*/
|
||||
export function travelOnly<T extends ShareSnapshot>(data: T, stayPlaceIds: ReadonlySet<number>): T {
|
||||
const assignments: T['assignments'] = {};
|
||||
@@ -38,6 +40,7 @@ export function travelOnly<T extends ShareSnapshot>(data: T, stayPlaceIds: Reado
|
||||
...data,
|
||||
assignments,
|
||||
dayNotes: {},
|
||||
days: data.days.map((d) => ({ ...d, title: null })),
|
||||
places: data.places.filter((p) => stayPlaceIds.has(p.id)),
|
||||
reservations: data.reservations.filter((r) => isTravelBooking(r.type)),
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
|
||||
import { Categories } from '../../db/entities/Categories.entity';
|
||||
import { CollabMessages } from '../../db/entities/CollabMessages.entity';
|
||||
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
|
||||
import { DayNotes } from '../../db/entities/DayNotes.entity';
|
||||
@@ -24,7 +23,7 @@ import { Module } from '@nestjs/common';
|
||||
// `MikroOrmModule.forFeature([Reservations, ...])` registers every repository
|
||||
// `ShareService`'s `@InjectRepository` constructor params need (Plan 3d Task 4
|
||||
// already registered `Reservations`; Plan 3h Task 6 adds `ShareTokens` — this
|
||||
// file's own table — plus the nine cross-domain tables its public-share reads
|
||||
// file's own table — plus the eight cross-domain tables its public-share reads
|
||||
// (SH7-9,11-16) touch, without importing each owning module: this file stays a
|
||||
// leaf the way `PublicApiModule`'s own `Trips`-only `forFeature` already does
|
||||
// for the same reason).
|
||||
@@ -46,7 +45,6 @@ import { Module } from '@nestjs/common';
|
||||
Places,
|
||||
PackingItems,
|
||||
BudgetItems,
|
||||
Categories,
|
||||
CollabMessages,
|
||||
]),
|
||||
],
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
|
||||
import { Categories } from '../../db/entities/Categories.entity';
|
||||
import { CollabMessages } from '../../db/entities/CollabMessages.entity';
|
||||
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
|
||||
import { DayNotes } from '../../db/entities/DayNotes.entity';
|
||||
@@ -10,7 +9,6 @@ import { Reservations } from '../../db/entities/Reservations.entity';
|
||||
import { ShareTokens } from '../../db/entities/ShareTokens.entity';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import type { BudgetItemsRepository } from '../../db/repositories/BudgetItems.repository';
|
||||
import type { CategoriesRepository } from '../../db/repositories/Categories.repository';
|
||||
import type { CollabMessagesRepository } from '../../db/repositories/CollabMessages.repository';
|
||||
import type { DayAssignmentsRepository } from '../../db/repositories/DayAssignments.repository';
|
||||
import type { DayNotesRepository } from '../../db/repositories/DayNotes.repository';
|
||||
@@ -26,6 +24,16 @@ import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
|
||||
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import {
|
||||
categoriesInUse,
|
||||
publicBudgetItem,
|
||||
publicCollabMessage,
|
||||
publicDay,
|
||||
publicDayNote,
|
||||
publicPackingItem,
|
||||
type PublicDay,
|
||||
type PublicDayNote,
|
||||
} from './share-public.helpers';
|
||||
import { travelOnly, withoutImages } from './share-view.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -205,7 +213,6 @@ export class ShareService {
|
||||
@InjectRepository(Places) private readonly places: PlacesRepository,
|
||||
@InjectRepository(PackingItems) private readonly packingItems: PackingItemsRepository,
|
||||
@InjectRepository(BudgetItems) private readonly budgetItems: BudgetItemsRepository,
|
||||
@InjectRepository(Categories) private readonly categories: CategoriesRepository,
|
||||
@InjectRepository(CollabMessages) private readonly collabMessages: CollabMessagesRepository,
|
||||
) {}
|
||||
|
||||
@@ -350,12 +357,14 @@ export class ShareService {
|
||||
};
|
||||
|
||||
// Itinerary — days with assignments/notes, and the place pool
|
||||
let days: any[] = [];
|
||||
let days: PublicDay[] = [];
|
||||
let assignments: Record<number, any[]> = {};
|
||||
let dayNotes: Record<number, any[]> = {};
|
||||
let dayNotes: Record<number, PublicDayNote[]> = {};
|
||||
let places: any[] = [];
|
||||
if (permissions.share_map) {
|
||||
days = await this.days.listByTrip(tripId);
|
||||
// Number, date and title only: the day's own notes are the planner's, and
|
||||
// the shared page never shows them.
|
||||
days = (await this.days.listByTrip(tripId)).map(publicDay);
|
||||
const dayIds = days.map((d) => d.id);
|
||||
|
||||
if (dayIds.length > 0) {
|
||||
@@ -402,10 +411,10 @@ export class ShareService {
|
||||
assignments = byDay;
|
||||
|
||||
const allNotes = await this.dayNotes.listByDayIds(dayIds);
|
||||
const notesByDay: Record<number, any[]> = {};
|
||||
const notesByDay: Record<number, PublicDayNote[]> = {};
|
||||
for (const n of allNotes) {
|
||||
if (!notesByDay[n.day_id]) notesByDay[n.day_id] = [];
|
||||
notesByDay[n.day_id].push(n);
|
||||
notesByDay[n.day_id].push(publicDayNote(n));
|
||||
}
|
||||
dayNotes = notesByDay;
|
||||
}
|
||||
@@ -453,17 +462,21 @@ export class ShareService {
|
||||
|
||||
// Packing — a public viewer is neither owner nor recipient, so only Common items
|
||||
// may surface; never a co-member's private/personal packing items (#858).
|
||||
const packing = permissions.share_packing ? await this.packingItems.listPublicForShare(tripId) : [];
|
||||
// The three lists below go out through their allow-lists (share-public.helpers):
|
||||
// the rows carry owner ids, private notes and ticket data the page never reads.
|
||||
const packing = permissions.share_packing
|
||||
? (await this.packingItems.listPublicForShare(tripId)).map(publicPackingItem)
|
||||
: [];
|
||||
|
||||
// Budget
|
||||
const budget = permissions.share_budget ? await this.budgetItems.listPublicForShare(tripId) : [];
|
||||
|
||||
// Categories are a shared global pool (the authed /api/categories list is
|
||||
// equally unscoped), so the public payload returns them all too.
|
||||
const categories = await this.categories.listAllUnordered();
|
||||
const budget = permissions.share_budget
|
||||
? (await this.budgetItems.listPublicForShare(tripId)).map(publicBudgetItem)
|
||||
: [];
|
||||
|
||||
// Collab messages (only if owner chose to share)
|
||||
const collabMessages = permissions.share_collab ? await this.collabMessages.listPublicForShare(tripId) : [];
|
||||
const collabMessages = permissions.share_collab
|
||||
? (await this.collabMessages.listPublicForShare(tripId)).map(publicCollabMessage)
|
||||
: [];
|
||||
|
||||
// Display currency the share owner sees in their Costs view. A public viewer has
|
||||
// no logged-in user, so the owner's per-user `default_currency` (with the admin
|
||||
@@ -494,7 +507,7 @@ export class ShareService {
|
||||
|
||||
// The owner's narrowing options (#1712) apply last, over what the flags
|
||||
// above already let through.
|
||||
let view = { assignments, dayNotes, places, reservations };
|
||||
let view = { assignments, days, dayNotes, places, reservations };
|
||||
if (permissions.share_travel_only) {
|
||||
const stayPlaceIds = new Set(await this.reservationsRepo.listPublicStayPlaceIdsForShare(tripId));
|
||||
view = travelOnly(view, stayPlaceIds);
|
||||
@@ -505,9 +518,10 @@ export class ShareService {
|
||||
trip,
|
||||
baseCurrency,
|
||||
cartoApiKey,
|
||||
categories,
|
||||
// Only the categories of the places that went out, read after the narrowing
|
||||
// above so a place the link hides does not leave its category behind.
|
||||
categories: categoriesInUse(view.places, view.assignments),
|
||||
permissions,
|
||||
days,
|
||||
...view,
|
||||
accommodations,
|
||||
packing,
|
||||
|
||||
@@ -119,6 +119,57 @@ const { backfillRun, backfillSchedule } = vi.hoisted(() => ({ backfillRun: vi.fn
|
||||
|
||||
const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() } }));
|
||||
|
||||
// What the share service answers for a link with every section on: the route
|
||||
// answers under a strict @ResponseContract, so this is also the allow-list.
|
||||
const publicPhoto = {
|
||||
id: 3,
|
||||
photo_id: 30,
|
||||
caption: null,
|
||||
media_type: 'image',
|
||||
width: 800,
|
||||
height: 600,
|
||||
duration_ms: null,
|
||||
taken_at: null,
|
||||
lat: null,
|
||||
lng: null,
|
||||
posterless: false,
|
||||
};
|
||||
const publicJourney = {
|
||||
journey: {
|
||||
title: 'J',
|
||||
subtitle: null,
|
||||
cover_image: null,
|
||||
status: 'draft',
|
||||
show_verdict: 1,
|
||||
show_mood: 1,
|
||||
show_weather: 1,
|
||||
},
|
||||
entries: [
|
||||
{
|
||||
id: 7,
|
||||
type: 'entry',
|
||||
entry_date: '2026-05-14',
|
||||
entry_time: null,
|
||||
sort_order: 0,
|
||||
title: 'Venice',
|
||||
story: null,
|
||||
location_name: null,
|
||||
location_lat: null,
|
||||
location_lng: null,
|
||||
country_code: null,
|
||||
mood: null,
|
||||
weather: null,
|
||||
tags: [],
|
||||
pros_cons: null,
|
||||
photos: [publicPhoto],
|
||||
},
|
||||
],
|
||||
gallery: [publicPhoto],
|
||||
stats: { entries: 1, photos: 1, places: 0 },
|
||||
cartoApiKey: '',
|
||||
permissions: { share_timeline: true, share_gallery: true, share_map: false, newest_first: false },
|
||||
};
|
||||
|
||||
const { mapsvc } = vi.hoisted(() => ({ mapsvc: { mapLayers: vi.fn(), publicMapLayers: vi.fn() } }));
|
||||
|
||||
const { booksvc } = vi.hoisted(() => ({
|
||||
@@ -169,7 +220,7 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
server = app.getHttpServer();
|
||||
jsvc.listJourneys.mockReturnValue([journeyListRow]);
|
||||
jsvc.createJourney.mockReturnValue(journeyRow(9));
|
||||
sharesvc.getPublicJourney.mockReturnValue({ id: 9 });
|
||||
sharesvc.getPublicJourney.mockReturnValue(publicJourney);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -442,7 +493,18 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
it('public journey read is unguarded (200 with a valid token, no cookie)', async () => {
|
||||
const res = await request(server).get('/api/public/journey/tok');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ id: 9 });
|
||||
expect(res.body).toEqual(publicJourney);
|
||||
});
|
||||
|
||||
it('public journey read refuses a storage key or an asset id in its answer (strict contract)', async () => {
|
||||
// The payload used to spread whole rows; the contract is what keeps a
|
||||
// column added to a read later from reaching the public.
|
||||
sharesvc.getPublicJourney.mockReturnValueOnce({
|
||||
...publicJourney,
|
||||
gallery: [{ ...publicPhoto, file_path: 'journey/abc.jpg', asset_id: 'abc' }],
|
||||
});
|
||||
const res = await request(server).get('/api/public/journey/tok');
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it('public journey read still answers the addon gate when Journey is off', async () => {
|
||||
|
||||
@@ -18,8 +18,11 @@ import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service';
|
||||
import { ShareModule } from '../../src/nest/share/share.module';
|
||||
import { makeBudgetItem } from '../helpers/factories/budget';
|
||||
import { makeDayAssignment, makeDayNote } from '../helpers/factories/itinerary';
|
||||
import { makeCategory, makePlace } from '../helpers/factories/places';
|
||||
import { deleteRows, findRow, insertRow } from '../helpers/factories/rows';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeDay, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
@@ -160,6 +163,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('carries the narrowing options through to the public read (#1712)', async () => {
|
||||
await makeDay(orm, tripId, { title: 'Museum day' });
|
||||
const created = await request(server)
|
||||
.post(`/api/trips/${tripId}/share-link`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
@@ -169,6 +173,7 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
const res = await request(server).get(`/api/shared/${created.body.token}`);
|
||||
expect(res.body.permissions).toEqual(expect.objectContaining({ share_travel_only: true, share_hide_images: true }));
|
||||
expect(res.body.dayNotes).toEqual({});
|
||||
expect(res.body.days.map((d: { title: string | null }) => d.title)).toEqual([null]);
|
||||
const bad = await request(server)
|
||||
.post(`/api/trips/${tripId}/share-link`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
@@ -187,6 +192,38 @@ describe('Share-link e2e (real auth guard + real SQL over temp SQLite)', () => {
|
||||
expect(res.body.permissions).toEqual(expect.objectContaining({ share_map: true, share_budget: false }));
|
||||
});
|
||||
|
||||
it('public shared read sends days, notes, categories and costs as allow-lists', async () => {
|
||||
const used = await makeCategory(orm, { name: 'Museums' });
|
||||
await makeCategory(orm, { name: 'Private stash', user: 1 });
|
||||
const day = await makeDay(orm, tripId, { title: 'Louvre day', notes: 'Owner day plan' });
|
||||
const place = await makePlace(orm, tripId, { name: 'Louvre', category: used.id });
|
||||
await makeDayAssignment(orm, day.id, place.id);
|
||||
await makeDayNote(orm, day.id, tripId, { text: 'Meet at noon' });
|
||||
await makeBudgetItem(orm, tripId, { name: 'Tickets', note: 'Card ending 4242', ticket_json: '{"seat":"12A"}' });
|
||||
const created = await request(server)
|
||||
.post(`/api/trips/${tripId}/share-link`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ share_budget: true });
|
||||
|
||||
const res = await request(server).get(`/api/shared/${created.body.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.days).toEqual([{ id: day.id, day_number: day.day_number, date: null, title: 'Louvre day' }]);
|
||||
expect(res.body.dayNotes[day.id]).toEqual([expect.objectContaining({ text: 'Meet at noon' })]);
|
||||
expect(res.body.dayNotes[day.id][0]).not.toHaveProperty('trip_id');
|
||||
expect(res.body.categories).toEqual([{ id: used.id, name: 'Museums', color: used.color, icon: used.icon }]);
|
||||
expect(res.body.budget).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
name: 'Tickets',
|
||||
category: 'Transport',
|
||||
total_price: 100,
|
||||
currency: null,
|
||||
exchange_rate: 1,
|
||||
},
|
||||
]);
|
||||
for (const secret of ['Owner day plan', '4242', '12A', 'Private stash']) expect(res.text).not.toContain(secret);
|
||||
});
|
||||
|
||||
it('public shared read 404 for an invalid token', async () => {
|
||||
const res = await request(server).get('/api/shared/bad');
|
||||
expect(res.status).toBe(404);
|
||||
|
||||
@@ -26,6 +26,7 @@ import { BudgetItemMembers } from '../../src/db/entities/BudgetItemMembers.entit
|
||||
import { Days } from '../../src/db/entities/Days.entity';
|
||||
import { JourneyEntries } from '../../src/db/entities/JourneyEntries.entity';
|
||||
import { Journeys } from '../../src/db/entities/Journeys.entity';
|
||||
import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import { Settings } from '../../src/db/entities/Settings.entity';
|
||||
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
@@ -382,6 +383,40 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('200 export.ics gives a booking linked to a stop the stop zone and exports the lunch once (#3150)', async () => {
|
||||
const tripId = await insertRow(orm, Trips, {
|
||||
user: 1,
|
||||
title: 'London',
|
||||
start_date: '2026-12-09',
|
||||
end_date: '2026-12-09',
|
||||
});
|
||||
const day = await makeDay(orm, tripId, { date: '2026-12-09' });
|
||||
const place = await makePlace(orm, tripId, { name: 'Restaurant X', lat: 51.5074, lng: -0.1278 });
|
||||
const stop = await makeDayAssignment(orm, day.id, place.id, {
|
||||
assignment_time: '14:00',
|
||||
assignment_end_time: '15:30',
|
||||
});
|
||||
await insertRow(orm, Reservations, {
|
||||
trip: tripId,
|
||||
title: 'Restaurant X',
|
||||
type: 'restaurant',
|
||||
assignment: stop.id,
|
||||
reservation_time: '2026-12-09T14:00',
|
||||
reservation_end_time: '2026-12-09T15:30',
|
||||
});
|
||||
|
||||
const res = await request(server).get(`/api/trips/${tripId}/export.ics`).set('Cookie', sessionCookie(1));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.text).toContain(
|
||||
'DTSTART;TZID=Europe/London:20261209T140000\r\nDTEND;TZID=Europe/London:20261209T153000\r\n',
|
||||
);
|
||||
// The booking used to float (no TZID) and repeat the stop as a second event.
|
||||
expect(res.text).not.toContain('DTSTART:20261209T140000');
|
||||
expect(res.text).not.toContain(`UID:trek-assign-${stop.id}@trek`);
|
||||
expect(res.text.match(/SUMMARY:Restaurant X/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('200 bundle for an accessible trip (real member list)', async () => {
|
||||
const tripId = await seedTrip('B');
|
||||
const res = await request(server).get(`/api/trips/${tripId}/bundle`).set('Cookie', sessionCookie(1));
|
||||
|
||||
@@ -23,12 +23,15 @@ export interface ExifJpegTags {
|
||||
OffsetTimeDigitized?: string;
|
||||
/** Decimal degrees, stored as the usual degree/minute/second rationals plus N/S and E/W. */
|
||||
gps?: { lat: number; lng: number };
|
||||
/** 0x0112 in IFD0, 1 to 8. */
|
||||
Orientation?: number;
|
||||
}
|
||||
|
||||
const BASE_JPEG = path.join(__dirname, '../fixtures/small-image.jpg');
|
||||
|
||||
const BYTE = 1;
|
||||
const ASCII = 2;
|
||||
const SHORT = 3;
|
||||
const LONG = 4;
|
||||
const RATIONAL = 5;
|
||||
|
||||
@@ -118,12 +121,18 @@ export function jpegWithExif(tags: ExifJpegTags): Buffer {
|
||||
gpsEntries.push(rationals(0x0004, dms(tags.gps.lng)));
|
||||
}
|
||||
|
||||
// IFD0 holds only the two pointers, so its size is known before the offsets are.
|
||||
const ifd0Count = (exifEntries.length ? 1 : 0) + (gpsEntries.length ? 1 : 0);
|
||||
// IFD0 holds the orientation and the two pointers, so its size is known before the offsets are.
|
||||
const ifd0Count =
|
||||
(tags.Orientation !== undefined ? 1 : 0) + (exifEntries.length ? 1 : 0) + (gpsEntries.length ? 1 : 0);
|
||||
const ifd0At = 8;
|
||||
const exifAt = ifd0At + 2 + ifd0Count * 12 + 4;
|
||||
const gpsAt = exifAt + (exifEntries.length ? ifdSize(exifEntries) : 0);
|
||||
const ifd0Entries: Entry[] = [];
|
||||
if (tags.Orientation !== undefined) {
|
||||
const data = Buffer.alloc(2);
|
||||
data.writeUInt16LE(tags.Orientation);
|
||||
ifd0Entries.push({ tag: 0x0112, type: SHORT, count: 1, data });
|
||||
}
|
||||
if (exifEntries.length) ifd0Entries.push(long(0x8769, exifAt));
|
||||
if (gpsEntries.length) ifd0Entries.push(long(0x8825, gpsAt));
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import { PluginUserErasureQueue } from '../../src/db/entities/PluginUserErasureQ
|
||||
import { Plugins } from '../../src/db/entities/Plugins.entity';
|
||||
import { ShareTokens } from '../../src/db/entities/ShareTokens.entity';
|
||||
import type { BudgetItemsRepository } from '../../src/db/repositories/BudgetItems.repository';
|
||||
import type { CategoriesRepository } from '../../src/db/repositories/Categories.repository';
|
||||
import type { CollabMessagesRepository } from '../../src/db/repositories/CollabMessages.repository';
|
||||
import type { DayAssignmentsRepository } from '../../src/db/repositories/DayAssignments.repository';
|
||||
import type { DayNotesRepository } from '../../src/db/repositories/DayNotes.repository';
|
||||
@@ -25,7 +24,6 @@ import {
|
||||
createTestDayAssignmentsRepo,
|
||||
createTestDayNotesRepo,
|
||||
createTestPlacesRepo,
|
||||
createTestCategoriesRepo,
|
||||
} from './test-uow';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
@@ -63,13 +61,13 @@ export function createTestPluginUserErasureQueueRepo(db: Database.Database): Pro
|
||||
}
|
||||
|
||||
/**
|
||||
* The 10 repository arguments `ShareService`'s constructor appends after
|
||||
* The 9 repository arguments `ShareService`'s constructor appends after
|
||||
* `uow` (`reservationsRepo`, `shareTokens`, `trips`, `days`, `dayAssignments`,
|
||||
* `dayNotes`, `places`, `packingItems`, `budgetItems`, `categories`,
|
||||
* `collabMessages` — 11 total, `reservationsRepo` already had its own 3d
|
||||
* `dayNotes`, `places`, `packingItems`, `budgetItems`, `collabMessages` —
|
||||
* 10 total, `reservationsRepo` already had its own 3d
|
||||
* factory), built over the SAME connection in one call — every hand-built
|
||||
* `new ShareService(...)` test call site spreads this
|
||||
* (`...(await shareServiceRepoArgs(conn))`) instead of repeating all 11
|
||||
* (`...(await shareServiceRepoArgs(conn))`) instead of repeating all 10
|
||||
* factories, the `budgetRepoArgs` precedent.
|
||||
*/
|
||||
export async function shareServiceRepoArgs(
|
||||
@@ -85,7 +83,6 @@ export async function shareServiceRepoArgs(
|
||||
PlacesRepository,
|
||||
PackingItemsRepository,
|
||||
BudgetItemsRepository,
|
||||
CategoriesRepository,
|
||||
CollabMessagesRepository,
|
||||
]
|
||||
> {
|
||||
@@ -99,7 +96,6 @@ export async function shareServiceRepoArgs(
|
||||
await createTestPlacesRepo(db),
|
||||
await createTestPackingItemsRepo(db),
|
||||
await createTestBudgetItemsRepo(db),
|
||||
await createTestCategoriesRepo(db),
|
||||
await createTestCollabMessagesRepo(db),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import type { ServedCategory } from '../../src/nest/storage/storage.types';
|
||||
|
||||
export interface StoredObjects {
|
||||
/** Every object stored through the facade since tracking began, in order. */
|
||||
readonly stored: ReadonlyArray<{ category: ServedCategory; name: string }>;
|
||||
/** Deletes exactly those objects and stops tracking. */
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records what a suite stores, so it can remove exactly that afterwards.
|
||||
*
|
||||
* Every suite that boots the app writes into the same server/uploads tree, and
|
||||
* on the Postgres lane several of them run at once. A suite that cleaned up by
|
||||
* removing a whole category folder (uploads/files, uploads/covers, ...) took
|
||||
* the files of whichever suite was running beside it, which then failed with
|
||||
* "storage object not found" halfway through a test. `put` is the facade's one
|
||||
* write path, so wrapping it on the app's own instance sees every upload,
|
||||
* thumbnail and derived copy the suite causes.
|
||||
*/
|
||||
export function trackStoredObjects(storage: StorageService): StoredObjects {
|
||||
const stored: Array<{ category: ServedCategory; name: string }> = [];
|
||||
const put = storage.put.bind(storage);
|
||||
storage.put = async (...args: Parameters<StorageService['put']>) => {
|
||||
const result = await put(...args);
|
||||
stored.push({ category: args[0], name: args[1] });
|
||||
return result;
|
||||
};
|
||||
return {
|
||||
stored,
|
||||
async cleanup() {
|
||||
storage.put = put;
|
||||
// Already gone is fine: a test may have deleted its own object.
|
||||
await Promise.all(
|
||||
stored.splice(0).map(({ category, name }) => storage.delete(category, name).catch(() => undefined)),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -10,11 +10,13 @@ import { buildApp } from '../../src/bootstrap';
|
||||
import { Addons } from '../../src/db/entities/Addons.entity';
|
||||
import { CollectionPlaces } from '../../src/db/entities/CollectionPlaces.entity';
|
||||
import { Collections } from '../../src/db/entities/Collections.entity';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import type { FactoryOrm } from '../helpers/factories/context';
|
||||
import { insertRow, upsertRow } from '../helpers/factories/rows';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { trackStoredObjects, type StoredObjects } from '../helpers/stored-objects';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
@@ -26,6 +28,8 @@ import request from 'supertest';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
let nestApp: INestApplication;
|
||||
// Only what this suite stored is removed: other suites share uploads/ and may run beside it.
|
||||
let stored: StoredObjects;
|
||||
let app: Application;
|
||||
let orm: FactoryOrm;
|
||||
const FIXTURE_IMG = path.join(__dirname, '../fixtures/small-image.jpg');
|
||||
@@ -42,6 +46,7 @@ async function createCollectionPlace(collectionId: number, ownerId: number): Pro
|
||||
|
||||
beforeAll(async () => {
|
||||
nestApp = await buildApp();
|
||||
stored = trackStoredObjects(nestApp.get(StorageService));
|
||||
app = nestApp.getHttpAdapter().getInstance();
|
||||
orm = nestApp.get(MikroORM);
|
||||
});
|
||||
@@ -62,9 +67,8 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await stored.cleanup();
|
||||
await nestApp.close();
|
||||
fs.rmSync(coversDir, { recursive: true, force: true });
|
||||
fs.rmSync(placesDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('Collection cover upload', () => {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* - FILE-009 (ephemeral token download) is covered via the /api/auth/resource-token endpoint
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { authCookie, generateToken } from '../helpers/auth';
|
||||
import type { FactoryOrm } from '../helpers/factories/context';
|
||||
import { makePlace } from '../helpers/factories/places';
|
||||
@@ -16,6 +17,7 @@ import { setAppSetting } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { trackStoredObjects, type StoredObjects } from '../helpers/stored-objects';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
@@ -27,6 +29,8 @@ import request from 'supertest';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
let nestApp: INestApplication;
|
||||
// Only what this suite stored is removed: other suites share uploads/ and may run beside it.
|
||||
let stored: StoredObjects;
|
||||
let app: Application;
|
||||
let orm: FactoryOrm;
|
||||
const FIXTURE_PDF = path.join(__dirname, '../fixtures/test.pdf');
|
||||
@@ -37,6 +41,7 @@ const uploadsDir = path.join(__dirname, '../../uploads/files');
|
||||
|
||||
beforeAll(async () => {
|
||||
nestApp = await buildApp();
|
||||
stored = trackStoredObjects(nestApp.get(StorageService));
|
||||
app = nestApp.getHttpAdapter().getInstance();
|
||||
orm = nestApp.get(MikroORM);
|
||||
if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
@@ -52,8 +57,8 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await stored.cleanup();
|
||||
await nestApp.close();
|
||||
fs.rmSync(uploadsDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Helper to upload a file and return the file object
|
||||
|
||||
@@ -6,6 +6,7 @@ import { buildApp } from '../../src/bootstrap';
|
||||
import { Addons } from '../../src/db/entities/Addons.entity';
|
||||
import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
|
||||
import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { jpegWithExif } from '../helpers/exif-jpeg';
|
||||
import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../helpers/factories/journeys';
|
||||
@@ -14,6 +15,7 @@ import { setAppSetting } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { trackStoredObjects, type StoredObjects } from '../helpers/stored-objects';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
@@ -1031,9 +1033,25 @@ describe('Journey upload parity', () => {
|
||||
const FIXTURE_IMG = pathMod.join(__dirname, '../fixtures/small-image.jpg');
|
||||
const journeyDir = pathMod.join(__dirname, '../../uploads/journey');
|
||||
|
||||
afterAll(() => {
|
||||
fsMod.rmSync(journeyDir, { recursive: true, force: true });
|
||||
// Only what these tests store is removed: other suites share uploads/ and may run beside them.
|
||||
let stored: StoredObjects;
|
||||
beforeAll(() => {
|
||||
stored = trackStoredObjects(nestApp.get(StorageService));
|
||||
});
|
||||
afterAll(async () => {
|
||||
await stored.cleanup();
|
||||
});
|
||||
|
||||
/**
|
||||
* The objects stored since `since` that still exist. Counting the files in
|
||||
* uploads/journey would also count what a suite beside this one writes there.
|
||||
*/
|
||||
async function stillStored(since: number): Promise<string[]> {
|
||||
const storage = nestApp.get(StorageService);
|
||||
const objects = stored.stored.slice(since);
|
||||
const exists = await Promise.all(objects.map(({ category, name }) => storage.exists(category, name)));
|
||||
return objects.filter((_, i) => exists[i]).map(({ name }) => name);
|
||||
}
|
||||
|
||||
it('JOURNEY-P01 — entry photo upload stores journey/<uuid> with a lowercased extension', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
@@ -1098,7 +1116,7 @@ describe('Journey upload parity', () => {
|
||||
const { user: other } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, owner.id);
|
||||
|
||||
const before = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
|
||||
const since = stored.stored.length;
|
||||
const res = await request(app)
|
||||
.post(`/api/journeys/${journey.id}/gallery/photos`)
|
||||
.set('Cookie', authCookie(other.id))
|
||||
@@ -1107,8 +1125,8 @@ describe('Journey upload parity', () => {
|
||||
expect(res.body.error).toBe('Not allowed');
|
||||
// The commit runs before the permission answer is known, so the refusal has
|
||||
// to delete the object again. Nothing sweeps orphans.
|
||||
const after = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
|
||||
expect(after).toBe(before);
|
||||
expect(stored.stored.length).toBeGreaterThan(since);
|
||||
expect(await stillStored(since)).toEqual([]);
|
||||
});
|
||||
|
||||
it('JOURNEY-P06 — video+poster upload: poster is ALWAYS stored as .jpg (stored-XSS pin)', async () => {
|
||||
@@ -1130,15 +1148,14 @@ describe('Journey upload parity', () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, user.id);
|
||||
|
||||
const before = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
|
||||
const since = stored.stored.length;
|
||||
const res = await request(app)
|
||||
.post(`/api/journeys/${journey.id}/gallery/video`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.attach('poster', fsMod.readFileSync(FIXTURE_IMG), { filename: 'poster.png', contentType: 'image/png' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toBe('No video uploaded');
|
||||
const after = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
|
||||
expect(after).toBe(before);
|
||||
expect(await stillStored(since)).toEqual([]);
|
||||
});
|
||||
|
||||
it('JOURNEY-P08 — non-contributor video upload is 403 and BOTH files are removed', async () => {
|
||||
@@ -1146,7 +1163,7 @@ describe('Journey upload parity', () => {
|
||||
const { user: other } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, owner.id);
|
||||
|
||||
const before = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
|
||||
const since = stored.stored.length;
|
||||
const res = await request(app)
|
||||
.post(`/api/journeys/${journey.id}/gallery/video`)
|
||||
.set('Cookie', authCookie(other.id))
|
||||
@@ -1154,8 +1171,9 @@ describe('Journey upload parity', () => {
|
||||
.attach('poster', fsMod.readFileSync(FIXTURE_IMG), { filename: 'poster.png', contentType: 'image/png' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toBe('Not allowed');
|
||||
const after = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
|
||||
expect(after).toBe(before);
|
||||
// The bytes were written before the refusal, and are gone again.
|
||||
expect(stored.stored.length).toBeGreaterThan(since);
|
||||
expect(await stillStored(since)).toEqual([]);
|
||||
});
|
||||
|
||||
it('JOURNEY-P09 — cover upload stores journey/<uuid> into cover_image', async () => {
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* Public byte paths and the location in a photo (PUBMEDIA-*).
|
||||
*
|
||||
* A phone photo carries the GPS fix it was taken at. A share link, a journey's
|
||||
* public page and the anonymous /uploads mounts used to hand out the stored
|
||||
* bytes, so the location left with them even where the owner had turned the
|
||||
* map off, and /uploads/journey served every entry photo to whoever had seen
|
||||
* its URL, share link revoked or not. Here the whole app answers over real
|
||||
* files: the public gets the location-free copy, the owner the original.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { Addons } from '../../src/db/entities/Addons.entity';
|
||||
import { Photos } from '../../src/db/entities/Photos.entity';
|
||||
import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
|
||||
import { authCookie, generateToken } from '../helpers/auth';
|
||||
import { jpegWithExif } from '../helpers/exif-jpeg';
|
||||
import { makeJourney } from '../helpers/factories/journeys';
|
||||
import { findRow, insertRow, upsertRow } from '../helpers/factories/rows';
|
||||
import { makeShareToken, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import exifr from 'exifr';
|
||||
import type { Application } from 'express';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
let nestApp: INestApplication;
|
||||
let app: Application;
|
||||
let orm: MikroORM;
|
||||
|
||||
const uploadsDir = path.join(__dirname, '../../uploads');
|
||||
// Every object this suite leaves behind, original and copy, removed one by one:
|
||||
// the uploads tree is shared with other integration workers.
|
||||
const created: string[] = [];
|
||||
|
||||
const GPS = { lat: 49.274523, lng: -0.703421 };
|
||||
const phonePhoto = () => jpegWithExif({ DateTimeOriginal: '2026:05:30 15:52:19', gps: GPS, Orientation: 6 });
|
||||
|
||||
function track(category: string, name: string): void {
|
||||
created.push(path.join(uploadsDir, category, name), path.join(uploadsDir, category, 'public', name));
|
||||
}
|
||||
|
||||
/** Reads any answer whole as bytes, whatever its content type. */
|
||||
function bytes(req: request.Test): request.Test {
|
||||
return req.buffer(true).parse((res, done) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
res.on('end', () => done(null, Buffer.concat(chunks)));
|
||||
});
|
||||
}
|
||||
|
||||
async function gpsOf(body: Buffer): Promise<number | undefined> {
|
||||
return (await exifr.gps(body).catch(() => undefined))?.latitude;
|
||||
}
|
||||
|
||||
async function uploadGalleryPhoto(userId: number, journeyId: number): Promise<{ name: string; photoId: number }> {
|
||||
const res = await request(app)
|
||||
.post(`/api/journeys/${journeyId}/gallery/photos`)
|
||||
.set('Cookie', authCookie(userId))
|
||||
.attach('photos', phonePhoto(), { filename: 'PXL_20260530_135219.jpg', contentType: 'image/jpeg' });
|
||||
expect(res.status).toBe(201);
|
||||
const filePath = res.body.photos[0].file_path as string;
|
||||
const name = filePath.replace(/^journey\//, '');
|
||||
track('journey', name);
|
||||
const row = await findRow(orm, TrekPhotos, { file_path: filePath });
|
||||
if (!row) throw new Error(`no trek_photos row for ${filePath}`);
|
||||
return { name, photoId: row.id };
|
||||
}
|
||||
|
||||
async function shareLink(userId: number, journeyId: number, flags: Record<string, boolean>): Promise<string> {
|
||||
const res = await request(app)
|
||||
.post(`/api/journeys/${journeyId}/share-link`)
|
||||
.set('Cookie', authCookie(userId))
|
||||
.send(flags);
|
||||
expect(res.status).toBe(200);
|
||||
return res.body.token as string;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
nestApp = await buildApp();
|
||||
app = nestApp.getHttpAdapter().getInstance();
|
||||
orm = nestApp.get(MikroORM);
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetDatabase(orm);
|
||||
await resetRateLimits(nestApp);
|
||||
await upsertRow(orm, Addons, {
|
||||
id: 'journey',
|
||||
name: 'Journey',
|
||||
description: 'Travel journal',
|
||||
type: 'global',
|
||||
icon: 'Compass',
|
||||
enabled: true,
|
||||
sort_order: 35,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await nestApp.close();
|
||||
for (const file of created) fs.rmSync(file, { force: true });
|
||||
});
|
||||
|
||||
describe('journey share link', () => {
|
||||
it('PUBMEDIA-001: with the map not shared, /original carries no GPS, orientation kept; the owner still gets the original', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, user.id);
|
||||
const { photoId } = await uploadGalleryPhoto(user.id, journey.id);
|
||||
const token = await shareLink(user.id, journey.id, { share_timeline: true, share_gallery: true, share_map: false });
|
||||
|
||||
const shared = await bytes(request(app).get(`/api/public/journey/${token}/photos/${photoId}/original`));
|
||||
expect(shared.status).toBe(200);
|
||||
const body = shared.body as Buffer;
|
||||
expect(await gpsOf(body)).toBeUndefined();
|
||||
expect(await exifr.orientation(body)).toBe(6);
|
||||
expect(body.length).toBe(phonePhoto().length);
|
||||
|
||||
const owned = await bytes(request(app).get(`/api/photos/${photoId}/original`).set('Cookie', authCookie(user.id)));
|
||||
expect(owned.status).toBe(200);
|
||||
expect(await gpsOf(owned.body as Buffer)).toBeCloseTo(GPS.lat, 5);
|
||||
});
|
||||
|
||||
it('PUBMEDIA-002: once the share link is deleted, no URL it handed out returns bytes', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, user.id);
|
||||
const { name, photoId } = await uploadGalleryPhoto(user.id, journey.id);
|
||||
const token = await shareLink(user.id, journey.id, { share_timeline: true, share_gallery: true, share_map: true });
|
||||
const original = `/api/public/journey/${token}/photos/${photoId}/original`;
|
||||
const thumbnail = `/api/public/journey/${token}/photos/${photoId}/thumbnail`;
|
||||
expect((await request(app).get(original)).status).toBe(200);
|
||||
|
||||
const revoke = await request(app)
|
||||
.delete(`/api/journeys/${journey.id}/share-link`)
|
||||
.set('Cookie', authCookie(user.id));
|
||||
expect(revoke.status).toBe(200);
|
||||
|
||||
expect((await request(app).get(original)).status).toBe(404);
|
||||
expect((await request(app).get(thumbnail)).status).toBe(404);
|
||||
expect(
|
||||
(await request(app).get(`/api/public/journey/${token}/photo/local/${name}/${user.id}/original`)).status,
|
||||
).toBe(404);
|
||||
// Nor does the static mount: an entry photo is no cover.
|
||||
expect((await request(app).get(`/uploads/journey/${name}`)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('/uploads/journey', () => {
|
||||
it('PUBMEDIA-010: serves a cover, location-free, and 404s an entry photo for everyone', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, user.id);
|
||||
const { name: entryPhoto } = await uploadGalleryPhoto(user.id, journey.id);
|
||||
const cover = await request(app)
|
||||
.post(`/api/journeys/${journey.id}/cover`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.attach('cover', phonePhoto(), { filename: 'cover.jpg', contentType: 'image/jpeg' });
|
||||
expect(cover.status).toBe(200);
|
||||
const coverName = (cover.body.cover_image as string).replace(/^journey\//, '');
|
||||
track('journey', coverName);
|
||||
|
||||
const hit = await bytes(request(app).get(`/uploads/journey/${coverName}`));
|
||||
expect(hit.status).toBe(200);
|
||||
expect(hit.headers['content-type']).toBe('image/jpeg');
|
||||
expect(await gpsOf(hit.body as Buffer)).toBeUndefined();
|
||||
expect(await exifr.orientation(hit.body as Buffer)).toBe(6);
|
||||
|
||||
expect((await request(app).get(`/uploads/journey/${entryPhoto}`)).status).toBe(404);
|
||||
expect((await request(app).get(`/uploads/journey/${entryPhoto}`).set('Cookie', authCookie(user.id))).status).toBe(
|
||||
404,
|
||||
);
|
||||
// The copies are not reachable by their own name either.
|
||||
expect((await request(app).get(`/uploads/journey/public/${coverName}`)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('/uploads/photos with a trip share token', () => {
|
||||
it('PUBMEDIA-020: the share token gets the copy without GPS, a session the stored photo', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
const name = 'pubmedia-trip-photo.integration.jpg';
|
||||
fs.mkdirSync(path.join(uploadsDir, 'photos'), { recursive: true });
|
||||
fs.writeFileSync(path.join(uploadsDir, 'photos', name), phonePhoto());
|
||||
track('photos', name);
|
||||
await insertRow(orm, Photos, { trip: trip.id, filename: name, original_name: name });
|
||||
await makeShareToken(orm, trip.id, user.id, { token: 'pubmedia-share-token' });
|
||||
|
||||
const shared = await bytes(request(app).get(`/uploads/photos/${name}?token=pubmedia-share-token`));
|
||||
expect(shared.status).toBe(200);
|
||||
expect(await gpsOf(shared.body as Buffer)).toBeUndefined();
|
||||
|
||||
const owned = await bytes(
|
||||
request(app)
|
||||
.get(`/uploads/photos/${name}`)
|
||||
.set('Authorization', `Bearer ${generateToken(user.id)}`),
|
||||
);
|
||||
expect(owned.status).toBe(200);
|
||||
expect(await gpsOf(owned.body as Buffer)).toBeCloseTo(GPS.lat, 5);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { TripFiles } from '../../src/db/entities/TripFiles.entity';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { authCookie, authHeader, generateToken } from '../helpers/auth';
|
||||
import type { FactoryOrm } from '../helpers/factories/context';
|
||||
import { findRows, updateRows } from '../helpers/factories/rows';
|
||||
@@ -17,6 +18,7 @@ import { setAppSetting } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser, readUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { trackStoredObjects, type StoredObjects } from '../helpers/stored-objects';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
@@ -28,6 +30,8 @@ import request from 'supertest';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
let nestApp: INestApplication;
|
||||
// Only what this suite stored is removed: other suites share uploads/ and may run beside it.
|
||||
let stored: StoredObjects;
|
||||
let app: Application;
|
||||
/** The app's own ORM, which the factories seed and read through. */
|
||||
let orm: FactoryOrm;
|
||||
@@ -36,6 +40,7 @@ const uploadsDir = path.join(__dirname, '../../uploads/files');
|
||||
|
||||
beforeAll(async () => {
|
||||
nestApp = await buildApp();
|
||||
stored = trackStoredObjects(nestApp.get(StorageService));
|
||||
orm = nestApp.get(MikroORM);
|
||||
app = nestApp.getHttpAdapter().getInstance();
|
||||
if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
@@ -49,8 +54,8 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await stored.cleanup();
|
||||
await nestApp.close();
|
||||
fs.rmSync(uploadsDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('Authentication security', () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { TripMembers } from '../../src/db/entities/TripMembers.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { Users } from '../../src/db/entities/Users.entity';
|
||||
import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { makeBudgetItem } from '../helpers/factories/budget';
|
||||
import type { FactoryOrm } from '../helpers/factories/context';
|
||||
@@ -32,6 +33,7 @@ import { setAppSetting } from '../helpers/factories/settings';
|
||||
import { addTripMember, makeTrip, readTripDays } from '../helpers/factories/trips';
|
||||
import { makeAdmin, makeUser, readUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { trackStoredObjects, type StoredObjects } from '../helpers/stored-objects';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
@@ -1271,8 +1273,13 @@ describe('Trip cover upload parity', () => {
|
||||
const FIXTURE_IMG = pathMod.join(__dirname, '../fixtures/small-image.jpg');
|
||||
const coversDir = pathMod.join(__dirname, '../../uploads/covers');
|
||||
|
||||
afterAll(() => {
|
||||
fsMod.rmSync(coversDir, { recursive: true, force: true });
|
||||
// Only what these tests store is removed: other suites share uploads/ and may run beside them.
|
||||
let stored: StoredObjects;
|
||||
beforeAll(() => {
|
||||
stored = trackStoredObjects(nestApp.get(StorageService));
|
||||
});
|
||||
afterAll(async () => {
|
||||
await stored.cleanup();
|
||||
});
|
||||
|
||||
it('TRIP-P01 — cover upload returns /uploads/covers/<uuid> and writes the file', async () => {
|
||||
|
||||
@@ -71,6 +71,8 @@ afterAll(async () => {
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// The location-free copy the share-token case made beside it.
|
||||
fs.rmSync(path.join(path.dirname(photoFile), 'public', photoName), { force: true });
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
* These routes are unauthenticated BY DESIGN (audit SEC-M9): server-chosen
|
||||
* UUIDv4 filenames; gating them would break share-link trip cards, journey
|
||||
* public pages, and email-embedded avatars. No auth setup here is deliberate.
|
||||
* Each hit is the object's location-free copy (PublicMediaService); the PNG
|
||||
* magic below holds no metadata, so the copy carries the same 8 bytes.
|
||||
* /uploads/journey refuses journey entry media and its thumbs/ unless a
|
||||
* journey uses it as its cover (PUBMEDIA-010 in public-media-privacy.test.ts).
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
@@ -58,7 +62,11 @@ beforeAll(async () => {
|
||||
|
||||
afterAll(async () => {
|
||||
await nestApp.close();
|
||||
for (const abs of created) fs.rmSync(abs, { force: true });
|
||||
for (const abs of created) {
|
||||
fs.rmSync(abs, { force: true });
|
||||
// The location-free copy the first hit made beside it.
|
||||
fs.rmSync(path.join(path.dirname(abs), 'public', path.basename(abs)), { force: true });
|
||||
}
|
||||
fs.rmSync(path.join(uploadsDir, 'avatars/.tmp'), { recursive: true, force: true });
|
||||
fs.rmSync(path.join(uploadsDir, 'journey/parity-subdir'), { recursive: true, force: true });
|
||||
});
|
||||
@@ -209,7 +217,7 @@ describe('/uploads static parity — miss falls through to the Nest 404 envelope
|
||||
});
|
||||
|
||||
describe('/uploads static parity — all four mounts', () => {
|
||||
it('UPLOADS-P21 — covers/journey(nested)/places each serve a hit and 404 a miss', async () => {
|
||||
it('UPLOADS-P21: covers/journey/places each serve a hit and 404 a miss, journey thumbs are refused', async () => {
|
||||
// Fixtures are (re)written immediately before each request: other suites
|
||||
// rm their whole category dir in afterAll (collections/trips → covers,
|
||||
// collections → places, journey.test → journey), so a beforeAll-written
|
||||
@@ -221,14 +229,19 @@ describe('/uploads static parity — all four mounts', () => {
|
||||
expect(coverMiss.status).toBe(404);
|
||||
expect(coverMiss.body.error).toBe('Cannot GET /uploads/covers/nope.png');
|
||||
|
||||
// Nested name — journey thumbs live at journey/thumbs/<hash>.jpg and are
|
||||
// served through the same mount; pins multi-segment storage keys.
|
||||
// Journey thumbs live at journey/thumbs/<hash>.jpg and go through the
|
||||
// share proxy, so the mount answers a miss for the object that exists
|
||||
// exactly as for one that does not.
|
||||
writeFixture('journey/thumbs/uploads-static-parity.jpg');
|
||||
const journeyHit = await request(app).get('/uploads/journey/thumbs/uploads-static-parity.jpg');
|
||||
expect(journeyHit.status).toBe(200);
|
||||
expect(journeyHit.headers['content-type']).toBe('image/jpeg');
|
||||
const journeyThumb = await request(app).get('/uploads/journey/thumbs/uploads-static-parity.jpg');
|
||||
expect(journeyThumb.status).toBe(404);
|
||||
expect(journeyThumb.body.error).toBe('Cannot GET /uploads/journey/thumbs/uploads-static-parity.jpg');
|
||||
const journeyMiss = await request(app).get('/uploads/journey/thumbs/nope.jpg');
|
||||
expect(journeyMiss.status).toBe(404);
|
||||
// An object no journey entry holds (a trip cover may point here) is served.
|
||||
writeFixture(`journey/${NAME}`);
|
||||
const journeyHit = await request(app).get(`/uploads/journey/${NAME}`);
|
||||
expect(journeyHit.status).toBe(200);
|
||||
|
||||
writeFixture(`places/${NAME}`);
|
||||
const placeHit = await request(app).get(`/uploads/places/${NAME}`);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user