Fix security issues, bugs, and convoluted code across the stack

Security:
- Token revocation. User gains a TokenVersion counter embedded in both
  tokens as a "tv" claim; AuthenticateToken rejects a token whose version
  no longer matches the row. Logout bumps it, so logging out now kills
  outstanding tokens rather than only clearing cookies. Costs one
  primary-key SELECT per authenticated request, which is the price of
  having revocation at all.
- Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by
  a per-request one-shot nonce, verified and consumed on callback.
- Private chat attachments. Attachments on private messages are written to
  /backend/uploads/private/ and served at /uploads/private/, gated by the
  same nginx auth_request admin check used for /hasura/ and /notes/.
  Private uploads are rejected from non-admin callers.
- The icecast admin UI (/radio/admin/) is behind the admin gate; listener
  traffic is untouched.
- Store caches are mutex-guarded, so -race is clean.

Bugs:
- The email pipeline no longer drops emails permanently on transient
  failure. Failures record an attempt counter and are retried up to 3
  times; the fetch window rewinds to the oldest retryable email's
  ReceivedAt, without which a retry could never re-fetch it.
- Rowing duplicate detection distinguishes ErrRecordNotFound from a real
  DB error, so a transient failure no longer causes a duplicate insert
  plus a paid Claude call.
- DeletePost propagates its delete error instead of reporting success.
- RecentlyPlayed populates the cache it reads.
- main.go exits non-zero if r.Run fails, so a port conflict is visible.
- Python: the scan truncation flag is set on every deadline path;
  timed_out is reported by the worker rather than inferred from the clock;
  date validation uses Europe/London rather than server-local time.
- Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue
  guards a missing author; Timer.vue gets an explicit state machine and
  compares total elapsed seconds; Elle.vue's comma-operator call and
  per-frame console.log are fixed.

Simplification:
- One TTLCache replaces three near-identical cache implementations, with
  the differing eviction rules as explicit parameters.
- run_scan's transport index no longer uses one object as both ordering
  record and live output; its three phases are separate functions.
- _price_hotels submits all work to a single pool, so the nested-executor
  deadlock hazard is gone by construction.
- The NDJSON event generators share one implementation.
- IMAP FETCH responses pair each line with its literal in the type, so
  callers no longer hand-skip alternate entries.
- Shared helpers for slice-of-pointers, markdown fences and auth cookies.
- Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm,
  useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks.
- nginx dev config's duplicated :80/:443 bodies share one partial.

Infra: certbot passes --deploy-hook touching a sentinel that nginx's
watcher reloads on, so renewed certs are served without a restart, and the
watcher also removes the manual restart after first issuance. db is gated
on service_healthy, autoheal is pinned, and the unused envsubst entries
are dropped.

Verified: go build/vet, npx vite build, py_compile, docker compose config
for both overlays, bash -n on all scripts, and an envsubst render of every
nginx template (no leftover placeholders, runtime vars preserved, braces
balanced).

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
2026-09-16 16:12:21 +01:00
co-authored by Claude Opus 5
parent 64df70e5d2
commit 25ac1cde1c
69 changed files with 2381 additions and 1607 deletions
+1 -8
View File
@@ -1,11 +1,6 @@
<script setup>
/**
* Decorative animated colour bars. STATUS: not imported anywhere.
*
* Two known problems if it is ever revived: the call
* `generateOffsets((150, 15, 10))` uses the comma operator, so it passes a single
* argument 10 as `width` and the other two defaults apply; and animate() logs to
* the console on every frame.
*/
import { ref, onMounted, useTemplateRef, onUnmounted } from "vue";
import { getRandomColor } from "@/js/utils";
@@ -20,7 +15,7 @@ function generateOffsets(width = 100, step = 10, n = 20) {
color: getRandomColor(),
}));
}
const offsets = ref(generateOffsets((150, 15, 10)));
const offsets = ref(generateOffsets(150, 15, 10));
let rafId;
const speed = 0.5; // pixels per frame
@@ -30,8 +25,6 @@ function animate() {
for (const item of offsets.value) {
const width = Math.max(ctnr.offsetWidth, item.width);
console.log(ctnr.offsetWidth);
item.offset -= speed;
if (item.offset <= -width) {
item.color = getRandomColor();
+5 -13
View File
@@ -1,22 +1,14 @@
<script setup>
/**
* Link styled to sit inside running prose (bold italic, no underline). Same
* `to` vs `href` and auto-`rel` behaviour as Link.vue.
* `to` vs `href` and auto-`rel` behaviour as Link.vue, shared through
* useLinkAttrs.js.
*/
import { computed } from "vue";
import { linkProps, useComputedRel } from "@/components/text/useLinkAttrs";
const props = defineProps({
href: { type: String, default: "" },
to: { type: String, default: "" },
target: { type: String, default: undefined },
rel: { type: String, default: undefined },
});
const props = defineProps({ ...linkProps });
const computedRel = computed(() => {
if (props.rel !== undefined) return props.rel;
if (props.target === "_blank") return "noopener noreferrer";
return undefined;
});
const computedRel = useComputedRel(props);
</script>
<template>
+5 -11
View File
@@ -2,23 +2,17 @@
/**
* Standard link. Renders a <RouterLink> when given `to`, a plain <a> when given
* `href`. `bare` drops the styling (used where the parent styles the anchor).
* External `target="_blank"` links get rel="noopener noreferrer" automatically.
* External `target="_blank"` links get rel="noopener noreferrer" automatically
* (shared with InlineLink.vue via useLinkAttrs.js).
*/
import { computed } from "vue";
import { linkProps, useComputedRel } from "@/components/text/useLinkAttrs";
const props = defineProps({
href: { type: String, default: "" },
to: { type: String, default: "" },
target: { type: String, default: undefined },
rel: { type: String, default: undefined },
...linkProps,
bare: { type: Boolean, default: false },
});
const computedRel = computed(() => {
if (props.rel !== undefined) return props.rel;
if (props.target === "_blank") return "noopener noreferrer";
return undefined;
});
const computedRel = useComputedRel(props);
</script>
<template>
+26
View File
@@ -0,0 +1,26 @@
// Shared link behaviour for components/text/Link.vue and InlineLink.vue, which
// render the same thing (a <RouterLink> for `to`, an <a> for `href`) and differ
// only in styling.
import { computed } from "vue";
/** Props every link component accepts. Spread into defineProps(). */
export const linkProps = {
href: { type: String, default: "" },
to: { type: String, default: "" },
target: { type: String, default: undefined },
rel: { type: String, default: undefined },
};
/**
* `rel` for the rendered <a>: an explicit `rel` prop wins, otherwise
* target="_blank" links get noopener/noreferrer so the opened page cannot
* reach back through window.opener.
*/
export function useComputedRel(props) {
return computed(() => {
if (props.rel !== undefined) return props.rel;
if (props.target === "_blank") return "noopener noreferrer";
return undefined;
});
}
+13 -2
View File
@@ -87,6 +87,8 @@ async function onFileSelected(e) {
const file = e.target.files[0];
if (!file) return;
isNearBottom.value = true;
// The private flag both routes the upload to /uploads/private/ and marks the
// message itself private; the two must agree.
await messagesStore.uploadAndSendFile(
file,
isAdmin.value && sendPrivate.value,
@@ -102,10 +104,19 @@ function isVideoUrl(url) {
return /\.(mp4|webm|ogg|mov)$/i.test(url);
}
// Public attachments live under /uploads/; attachments on private messages are
// written under /uploads/private/, which nginx gates behind an admin check.
const UPLOAD_PREFIXES = ["/uploads/", "/uploads/private/"];
/** Only render attachments the backend served from its own upload directory —
* the fileUrl arrives over the socket and is otherwise attacker-controlled. */
* the fileUrl arrives over the socket and is otherwise attacker-controlled.
* A strict prefix allowlist, so absolute ("https://evil/uploads/x") and
* protocol-relative ("//evil/uploads/x") URLs are rejected; "..", which could
* otherwise escape the directory, is rejected outright. */
function isSafeFileUrl(url) {
return typeof url === "string" && url.startsWith("/uploads/");
if (typeof url !== "string") return false;
if (url.includes("..")) return false;
return UPLOAD_PREFIXES.some((prefix) => url.startsWith(prefix));
}
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
+6 -41
View File
@@ -3,11 +3,13 @@
* Renders a list of {name, link, type} either as stacked link buttons
* (variant="list") or as a two-column table (variant="table").
*
* Passing `title` wraps the whole thing in a collapsible <ToggleHeader>.
* Passing `title` wraps the whole thing in a collapsible <ToggleHeader> (and a
* .h-fit.w-full div); without a title the items are rendered bare. The items
* themselves live in LinkTableItems.vue so both branches share one copy.
* Used by the Bookmarks, Favorites, Consumption and Links widgets.
*/
import { ref } from "vue";
import Link from "@/components/text/Link.vue";
import LinkTableItems from "@/components/util/LinkTableItems.vue";
import ToggleHeader from "@/components/text/ToggleHeader.vue";
const props = defineProps({
@@ -33,44 +35,7 @@ const show = ref(false);
<ToggleHeader v-model="show" class="justify-between flex items-center">
{{ title }}
</ToggleHeader>
<template v-if="show">
<Link
v-if="variant === 'list'"
v-for="(item, i) in items"
:key="i"
:href="item.link"
>
<p class="bdr-2 bg-surface-tint">{{ item.name }}</p>
</Link>
<table class="w-full" v-else>
<tbody>
<tr v-for="item in items" :key="item.id">
<th>{{ item.type }}</th>
<td v-if="item.link">
<Link :href="item.link">{{ item.name }}</Link>
</td>
<td v-else>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<LinkTableItems v-if="show" :items="items" :variant="variant" />
</div>
<template v-else>
<template v-if="variant === 'list'">
<Link v-for="(item, i) in items" :key="i" :href="item.link">
<p class="bdr-2 bg-surface-tint">{{ item.name }}</p>
</Link>
</template>
<table class="w-full" v-else>
<tbody>
<tr v-for="item in items" :key="item.id">
<th>{{ item.type }}</th>
<td v-if="item.link">
<Link :href="item.link">{{ item.name }}</Link>
</td>
<td v-else>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<LinkTableItems v-else :items="items" :variant="variant" />
</template>
@@ -0,0 +1,41 @@
<script setup>
/**
* The body of LinkTable.vue: the items rendered either as stacked link buttons
* (variant="list") or as a two-column table (variant="table").
*
* Split out only so LinkTable can render the same markup inside and outside its
* collapsible <ToggleHeader> wrapper without duplicating it. A component adds no
* DOM of its own, so the rendered output is unchanged.
*/
import Link from "@/components/text/Link.vue";
defineProps({
items: {
type: Array,
required: true,
},
variant: {
type: String,
default: "list",
},
});
</script>
<template>
<template v-if="variant === 'list'">
<Link v-for="(item, i) in items" :key="i" :href="item.link">
<p class="bdr-2 bg-surface-tint">{{ item.name }}</p>
</Link>
</template>
<table class="w-full" v-else>
<tbody>
<tr v-for="item in items" :key="item.id">
<th>{{ item.type }}</th>
<td v-if="item.link">
<Link :href="item.link">{{ item.name }}</Link>
</td>
<td v-else>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
+5 -8
View File
@@ -21,10 +21,7 @@ const resolvedColumns = computed(() => {
Object.keys(obj).forEach((key) => keys.add(key));
}
return Array.from(keys).map((key) => ({
key,
label: key,
}));
return Array.from(keys);
});
</script>
@@ -32,16 +29,16 @@ const resolvedColumns = computed(() => {
<table>
<thead>
<tr>
<th v-for="col in resolvedColumns" :key="col.key">
{{ col.label }}
<th v-for="col in resolvedColumns" :key="col">
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in objArr" :key="rowIndex">
<td v-for="col in resolvedColumns" :key="col.key">
{{ row[col.key] ?? "" }}
<td v-for="col in resolvedColumns" :key="col">
{{ row[col] ?? "" }}
</td>
</tr>
</tbody>
+8 -2
View File
@@ -25,7 +25,7 @@
*/
import Button from "@/components/input/Button.vue";
import Header from "@/components/text/Header.vue";
import { ref, useTemplateRef, onMounted, nextTick } from "vue";
import { ref, useTemplateRef, onMounted, onUnmounted, nextTick } from "vue";
import axios from "axios";
const POLL_INTERVAL_MS = 120000; // re-probe the stream every 2 minutes
@@ -54,9 +54,15 @@ async function checkStream() {
}
}
let pollId;
onMounted(() => {
checkStream();
setInterval(checkStream, POLL_INTERVAL_MS);
pollId = setInterval(checkStream, POLL_INTERVAL_MS);
});
onUnmounted(() => {
clearInterval(pollId);
});
</script>
+12 -4
View File
@@ -1,11 +1,11 @@
<script setup>
/**
* Clock and date widget. updateDateTime() runs once immediately and then every
* minute. Note the interval is module-level and never cleared — harmless because
* the widget lives for the life of the home page, but it would leak if reused.
* minute, with the interval owned by the component lifecycle so it is cleared
* on unmount.
*/
import Header from "@/components/text/Header.vue";
import { ref } from "vue";
import { ref, onMounted, onUnmounted } from "vue";
const time = ref("");
const weekday = ref("");
@@ -25,7 +25,15 @@ function updateDateTime() {
updateDateTime();
setInterval(updateDateTime, 60000);
let intervalId;
onMounted(() => {
intervalId = setInterval(updateDateTime, 60000);
});
onUnmounted(() => {
clearInterval(intervalId);
});
</script>
<template>
+29 -23
View File
@@ -2,18 +2,20 @@
/**
* Countdown widget with minute/second sliders and a sound on completion.
*
* The four mutually exclusive v-if blocks are a state machine over
* (finished, paused): set/idle, finished, paused, running.
* `state` is an explicit state machine — "idle" (sliders), "running",
* "paused" and "finished" — one screen per state. Completion is decided by
* comparing total elapsed seconds with the total target, so it does not depend
* on the minute and second fields crossing their targets independently.
*/
import Button from "@/components/input/Button.vue";
import Header from "@/components/text/Header.vue";
import { ref } from "vue";
import { ref, onUnmounted } from "vue";
const timer = ref(null);
const finished = ref(true);
const paused = ref(true);
/** "idle" | "running" | "paused" | "finished" */
const state = ref("idle");
const minutesInput = ref(0);
const secondsInput = ref(0);
@@ -30,41 +32,45 @@ function tick() {
seconds.value = 0;
}
if (minutes.value >= minutesInput.value) {
if (seconds.value >= secondsInput.value) {
finished.value = true;
playFinishedSound();
clearInterval(timer.value);
}
const elapsed = minutes.value * 60 + seconds.value;
const target = Number(minutesInput.value) * 60 + Number(secondsInput.value);
if (elapsed >= target) {
state.value = "finished";
playFinishedSound();
clearInterval(timer.value);
}
}
function startTimer() {
finished.value = false;
paused.value = false;
state.value = "running";
timer.value = setInterval(tick, 1000);
}
function pauseTimer() {
if (finished.value) return;
if (state.value === "finished") return;
if (paused.value) {
if (state.value === "paused") {
timer.value = setInterval(tick, 1000);
paused.value = false;
state.value = "running";
} else {
clearInterval(timer.value);
paused.value = true;
state.value = "paused";
}
}
/** Back to the slider screen, ready to set a new countdown. */
function resetTimer() {
finished.value = true;
paused.value = true;
state.value = "idle";
clearInterval(timer.value);
minutes.value = 0;
seconds.value = 0;
}
onUnmounted(() => {
clearInterval(timer.value);
});
function playFinishedSound() {
audio.play();
}
@@ -73,7 +79,7 @@ function playFinishedSound() {
<template>
<div class="timer-root flex flex-col gap-1 p-1 items-center">
<Header>Timer</Header>
<div v-if="finished && paused" class="flex flex-col">
<div v-if="state === 'idle'" class="flex flex-col">
<div class="flex flex-row p-2 place-content-around">
<input
class="w-2/3"
@@ -98,15 +104,15 @@ function playFinishedSound() {
</div>
<Button @click="startTimer">Proceed</Button>
</div>
<div v-if="finished && !paused" class="flex flex-col">
<div v-if="state === 'finished'" class="flex flex-col">
<h1>Timer finished!</h1>
<Button @click="resetTimer">Reset</Button>
</div>
<div v-if="!finished && paused" class="flex flex-col">
<div v-if="state === 'paused'" class="flex flex-col">
<h1>Paused</h1>
<Button @click="resetTimer">Reset</Button>
</div>
<div v-if="!finished && !paused" class="flex flex-col">
<div v-if="state === 'running'" class="flex flex-col">
<p>
{{ minutes.toString().padStart(2, "0") }}:{{
seconds.toString().padStart(2, "0")
+46
View File
@@ -0,0 +1,46 @@
// The shared body of the admin "create X" forms (CreatePost, CreateFavorite,
// CreateActivity, CreateBookmark): a ref per field, a GraphQL mutation taking a
// single `input`, clear the fields on success, then emit "done" so the host
// modal can close. Failures are logged and leave the fields alone, exactly as
// the hand-written versions did.
import { ref } from "vue";
import { gql } from "@/graphql";
/**
* @param {object} options
* @param {string} options.mutation GraphQL mutation with one $input variable
* @param {string[]} options.fields input field names, one text ref each
* @param {(event: string) => void} options.emit the component's emit
* @param {string[]} [options.optional] fields sent as undefined when blank,
* so the backend sees "not set" rather than an empty string
* @param {string} [options.resultKey] mutation field to log on success
* @returns {{ values: Record<string, import("vue").Ref<string>>, submit: () => Promise<void> }}
*/
export function useCreateForm({
mutation,
fields,
emit,
optional = [],
resultKey,
}) {
const values = Object.fromEntries(fields.map((name) => [name, ref("")]));
async function submit() {
try {
const input = {};
for (const name of fields) {
const value = values[name].value;
input[name] = optional.includes(name) ? value || undefined : value;
}
const data = await gql(mutation, { input });
for (const name of fields) values[name].value = "";
if (resultKey) console.log(data[resultKey]);
emit("done");
} catch (err) {
console.error(err);
}
}
return { values, submit };
}
+47
View File
@@ -0,0 +1,47 @@
// Rotate through a list on a timer, as the Listening and Steam widgets do.
//
// A self-rearming setTimeout rather than setInterval, so clicking to advance
// manually restarts the full delay instead of leaving whatever was left of the
// current tick. An optional periodic refresh callback covers the "re-poll the
// source every few minutes" half of the same pattern. Both timers are cleared
// on unmount.
import { ref, unref, onMounted, onUnmounted } from "vue";
/**
* @param {import("vue").Ref<Array>|(() => Array)} items the list being rotated
* @param {number} ms delay between rotations
* @param {object} [options]
* @param {() => void} [options.refresh] called every refreshMs
* @param {number} [options.refreshMs] refresh interval
* @returns {{ idx: import("vue").Ref<number>, next: () => void }}
*/
export function useRotation(items, ms, { refresh, refreshMs } = {}) {
const idx = ref(0);
let nextId = null;
let refreshId = null;
function list() {
return (typeof items === "function" ? items() : unref(items)) ?? [];
}
/** Advance one step and re-arm. Leaves the index alone on an empty list. */
function next() {
clearTimeout(nextId);
nextId = setTimeout(next, ms);
const count = list().length;
if (count) idx.value = (idx.value + 1) % count;
}
onMounted(() => {
nextId = setTimeout(next, ms);
if (refresh && refreshMs) refreshId = setInterval(refresh, refreshMs);
});
onUnmounted(() => {
clearTimeout(nextId);
clearInterval(refreshId);
});
return { idx, next };
}
+11 -30
View File
@@ -1,11 +1,11 @@
/**
* Media/activity log for the Consumption widget. A view over homeData.activities;
* see stores/posts.js for the placeholder-then-overwrite pattern.
* Media/activity log for the Consumption widget. A view over homeData.activities,
* built by createMirrorStore(); see stores/createMirrorStore.js for the
* placeholder-then-overwrite pattern.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
import { createMirrorStore } from "@/stores/createMirrorStore";
const activity_template = {
type: "activity",
@@ -14,33 +14,14 @@ const activity_template = {
};
export const useActivityStore = defineStore("activity", () => {
const activity = ref([activity_template]);
const activityCount = computed(() => activity.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.activities,
(newActivities) => {
if (newActivities.length > 0) {
activity.value = newActivities;
}
},
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchActivity() {
await homeData.fetchAll();
}
const { items, count, fetch } = createMirrorStore({
slice: "activities",
template: activity_template,
});
return {
activity,
activityCount,
fetchActivity,
activity: items,
activityCount: count,
fetchActivity: fetch,
};
});
+49
View File
@@ -0,0 +1,49 @@
/**
* Factory for the "mirror store" pattern shared by stores/posts.js,
* favorites.js and activity.js.
*
* Each of those is a thin view over one slice of the shared home query
* (stores/homeData.js): a ref seeded with placeholder content, an `immediate`
* watch that copies the homeData slice in, a count computed and a fetch
* function that just re-runs the whole home query.
*
* The state/getter/action names differ per store and components import them by
* name, so the caller supplies them explicitly rather than having them derived.
*/
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
/**
* @param {object} options
* @param {string} options.slice key on the homeData store to mirror
* @param {*} options.template placeholder item shown before a successful fetch
* @returns {{ items: import("vue").Ref, count: import("vue").ComputedRef, fetch: () => Promise<void>, homeData: object }}
*/
export function createMirrorStore({ slice, template }) {
const items = ref([template]);
const count = computed(() => items.value.length);
const homeData = useHomeDataStore();
// `immediate` matters: homeData may already have loaded by the time this
// store is first used, and a plain watch would never fire for that existing
// value. The `length > 0` test keeps the placeholder on screen when the
// backend returns nothing.
watch(
() => homeData[slice],
(newItems) => {
if (newItems.length > 0) {
items.value = newItems;
}
},
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetch() {
await homeData.fetchAll();
}
return { items, count, fetch, homeData };
}
+11 -30
View File
@@ -1,11 +1,11 @@
/**
* Favourites for the Favorites widget. A view over homeData.favorites; see
* stores/posts.js for the placeholder-then-overwrite pattern.
* Favourites for the Favorites widget. A view over homeData.favorites, built by
* createMirrorStore(); see stores/createMirrorStore.js for the
* placeholder-then-overwrite pattern.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
import { createMirrorStore } from "@/stores/createMirrorStore";
const favorite_template = {
type: "favorite",
@@ -14,33 +14,14 @@ const favorite_template = {
};
export const useFavoritesStore = defineStore("favorites", () => {
const favorites = ref([favorite_template]);
const favoritesCount = computed(() => favorites.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.favorites,
(newFavorites) => {
if (newFavorites.length > 0) {
favorites.value = newFavorites;
}
},
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchFavorites() {
await homeData.fetchAll();
}
const { items, count, fetch } = createMirrorStore({
slice: "favorites",
template: favorite_template,
});
return {
favorites,
favoritesCount,
fetchFavorites,
favorites: items,
favoritesCount: count,
fetchFavorites: fetch,
};
});
+5
View File
@@ -136,11 +136,16 @@ export const useMessagesStore = defineStore("messages", () => {
* POST a file to the REST upload endpoint, then send its returned URL over
* the socket as a normal message. Two steps because the socket carries JSON
* text only. Errors surface via `lastError`.
*
* `private` is sent with the upload as well as with the message: the backend
* stores private attachments under /uploads/private/, which nginx gates
* behind an admin check.
*/
async function uploadAndSendFile(file, isPrivate = false) {
try {
const formData = new FormData();
formData.append("file", file);
formData.append("private", isPrivate ? "true" : "false");
const res = await axios.post("/api/messages/upload", formData);
const { url } = res.data;
if (!socket.value || !isConnected.value) return;
+12 -31
View File
@@ -1,15 +1,15 @@
/**
* Blog posts for the Feed widget. A view over homeData.posts.
* Blog posts for the Feed widget. A view over homeData.posts, built by
* createMirrorStore(); see stores/createMirrorStore.js for the
* placeholder-then-overwrite pattern.
*
* `post_template` is placeholder content rendered before (or instead of) a
* successful fetch — the watch only overwrites `posts` when the fetch returned a
* non-empty list, so the widget never flashes empty.
* successful fetch, so the widget never flashes empty.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { gql } from "@/graphql";
import { useHomeDataStore } from "@/stores/homeData";
import { createMirrorStore } from "@/stores/createMirrorStore";
const post_template = {
title: "Can't fetch from the db yo",
@@ -22,29 +22,10 @@ const post_template = {
};
export const usePostsStore = defineStore("posts", () => {
const posts = ref([post_template]);
const postsCount = computed(() => posts.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.posts,
(newPosts) => {
if (newPosts.length > 0) {
posts.value = newPosts;
}
},
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchPosts() {
await homeData.fetchAll();
}
const { items, count, fetch, homeData } = createMirrorStore({
slice: "posts",
template: post_template,
});
/** Soft-delete a post, then refetch so every widget sees the new list. */
async function deletePost(post) {
@@ -61,11 +42,11 @@ export const usePostsStore = defineStore("posts", () => {
}
return {
posts,
posts: items,
postsCount,
postsCount: count,
fetchPosts,
fetchPosts: fetch,
deletePost,
};
});
+9 -27
View File
@@ -3,37 +3,19 @@
* Admin form: log a consumed book/film/game. Emits "done"/"cancel".
*/
import Button from "@/components/input/Button.vue";
import { useCreateForm } from "@/js/useCreateForm";
import { ref } from "vue";
import { gql } from "@/graphql";
const emit = defineEmits(["done", "cancel"]);
const type = ref("");
const name = ref("");
const link = ref("");
async function post() {
try {
const data = await gql(
`mutation CreateActivity($input: CreateActivityInput!) { createActivity(input: $input) { id } }`,
{
input: {
type: type.value,
name: name.value,
link: link.value || undefined,
},
},
);
type.value = "";
name.value = "";
link.value = "";
console.log(data.createActivity);
emit("done");
} catch (err) {
console.error(err);
}
}
const { values, submit: post } = useCreateForm({
mutation: `mutation CreateActivity($input: CreateActivityInput!) { createActivity(input: $input) { id } }`,
fields: ["type", "name", "link"],
optional: ["link"],
resultKey: "createActivity",
emit,
});
const { type, name, link } = values;
</script>
<template>
+8 -22
View File
@@ -3,31 +3,17 @@
* Admin form: create a categorised bookmark. Emits "done"/"cancel".
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { gql } from "@/graphql";
import { useCreateForm } from "@/js/useCreateForm";
const emit = defineEmits(["done", "cancel"]);
const category = ref("");
const name = ref("");
const link = ref("");
async function submit() {
try {
await gql(
`mutation CreateBookmark($input: CreateBookmarkInput!) { createBookmark(input: $input) { id } }`,
{
input: { category: category.value, name: name.value, link: link.value },
},
);
category.value = "";
name.value = "";
link.value = "";
emit("done");
} catch (err) {
console.error(err);
}
}
const { values, submit } = useCreateForm({
mutation: `mutation CreateBookmark($input: CreateBookmarkInput!) { createBookmark(input: $input) { id } }`,
fields: ["category", "name", "link"],
emit,
});
const { category, name, link } = values;
</script>
<template>
+9 -27
View File
@@ -3,37 +3,19 @@
* Admin form: create a favourite. Emits "done"/"cancel" (see CreatePost.vue).
*/
import Button from "@/components/input/Button.vue";
import { useCreateForm } from "@/js/useCreateForm";
import { ref } from "vue";
import { gql } from "@/graphql";
const emit = defineEmits(["done", "cancel"]);
const type = ref("");
const name = ref("");
const link = ref("");
async function post() {
try {
const data = await gql(
`mutation CreateFavorite($input: CreateFavoriteInput!) { createFavorite(input: $input) { id } }`,
{
input: {
type: type.value,
name: name.value,
link: link.value || undefined,
},
},
);
type.value = "";
name.value = "";
link.value = "";
console.log(data.createFavorite);
emit("done");
} catch (err) {
console.error(err);
}
}
const { values, submit: post } = useCreateForm({
mutation: `mutation CreateFavorite($input: CreateFavoriteInput!) { createFavorite(input: $input) { id } }`,
fields: ["type", "name", "link"],
optional: ["link"],
resultKey: "createFavorite",
emit,
});
const { type, name, link } = values;
</script>
<template>
+10 -20
View File
@@ -2,31 +2,21 @@
/**
* Admin form: create a blog post. Emits "done" on success and "cancel" when
* dismissed, so the host (the Feed widget's modal, or Admin.vue) decides what to
* close or refresh.
* close or refresh. The submit plumbing is shared via useCreateForm().
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { gql } from "@/graphql";
import { useCreateForm } from "@/js/useCreateForm";
const emit = defineEmits(["done", "cancel"]);
const title = ref("");
const content = ref("");
async function post() {
try {
const data = await gql(
`mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id } }`,
{ input: { title: title.value, content: content.value } },
);
title.value = "";
content.value = "";
console.log(data.createPost);
emit("done");
} catch (err) {
console.error(err);
}
}
const { values, submit: post } = useCreateForm({
mutation: `mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id } }`,
fields: ["title", "content"],
resultKey: "createPost",
emit,
});
const { title, content } = values;
</script>
<template>
+8 -27
View File
@@ -1,15 +1,11 @@
<script setup>
/**
* "Consumption" widget on /stp (books/films/games logged as activities). Same
* shape as Favorites.vue: AutoScroll list + admin-only lazy create form.
* shape as Favorites.vue — both are ListWidget.vue with a different store.
*/
import AutoScroll from "@/components/util/AutoScroll.vue";
import Modal from "@/components/util/Modal.vue";
import LinkTable from "@/components/util/LinkTable.vue";
import Header from "@/components/text/Header.vue";
import CreateToggle from "@/components/input/CreateToggle.vue";
import ListWidget from "@/views/home/ListWidget.vue";
import { ref, defineAsyncComponent } from "vue";
import { defineAsyncComponent } from "vue";
import { useActivityStore } from "@/stores/activity";
const CreateActivity = defineAsyncComponent(
@@ -17,27 +13,12 @@ const CreateActivity = defineAsyncComponent(
);
const activityStore = useActivityStore();
const showCreate = ref(false);
</script>
<template>
<div class="flex flex-col items-center">
<Header>
Consumption
<template #action><CreateToggle v-model="showCreate" /></template>
</Header>
<AutoScroll class="flex-1 w-full">
<LinkTable
variant="table"
class="w-full"
:items="activityStore.activity"
/>
</AutoScroll>
<Modal v-model="showCreate">
<CreateActivity
@done="showCreate = false"
@cancel="showCreate = false"
/>
</Modal>
</div>
<ListWidget
title="Consumption"
:items="activityStore.activity"
:create-form="CreateActivity"
/>
</template>
+9 -28
View File
@@ -1,15 +1,11 @@
<script setup>
/**
* "Favorites" widget on /stp: a self-scrolling <AutoScroll> list, plus an
* admin-only create form in a <Modal> (lazily imported).
* "Favorites" widget on /stp. All of the markup lives in ListWidget.vue; this
* file only binds the favourites store and the (lazily imported) create form.
*/
import Header from "@/components/text/Header.vue";
import CreateToggle from "@/components/input/CreateToggle.vue";
import LinkTable from "@/components/util/LinkTable.vue";
import AutoScroll from "@/components/util/AutoScroll.vue";
import Modal from "@/components/util/Modal.vue";
import ListWidget from "@/views/home/ListWidget.vue";
import { ref, defineAsyncComponent } from "vue";
import { defineAsyncComponent } from "vue";
import { useFavoritesStore } from "@/stores/favorites";
const CreateFavorite = defineAsyncComponent(
@@ -17,27 +13,12 @@ const CreateFavorite = defineAsyncComponent(
);
const favoritesStore = useFavoritesStore();
const showCreate = ref(false);
</script>
<template>
<div class="flex flex-col items-center">
<Header>
favs
<template #action><CreateToggle v-model="showCreate" /></template>
</Header>
<AutoScroll class="w-full flex-1">
<LinkTable
variant="table"
class="w-full"
:items="favoritesStore.favorites"
/>
</AutoScroll>
<Modal v-model="showCreate">
<CreateFavorite
@done="showCreate = false"
@cancel="showCreate = false"
/>
</Modal>
</div>
<ListWidget
title="favs"
:items="favoritesStore.favorites"
:create-form="CreateFavorite"
/>
</template>
+2 -1
View File
@@ -28,8 +28,9 @@ const leftCap = computed(() => idx.value === 0);
const rightCap = computed(() => idx.value === postsStore.postsCount - 1);
const post = computed(() => postsStore.posts[idx.value]);
// Guarded: `post` can be a placeholder or a row fetched without an author.
const userOwnsPost = computed(
() => post.value.author.username == authStore.user.username,
() => post.value?.author?.username == authStore.user?.username,
);
function nextPost() {
+45
View File
@@ -0,0 +1,45 @@
<script setup>
/**
* Shared shape of the "favs" and "Consumption" widgets on /stp: a header with a
* create toggle, a self-scrolling <AutoScroll> list rendered through
* <LinkTable>, and an admin-only create form in a <Modal>.
*
* `createForm` is the component to show in the modal. The hosts pass a
* defineAsyncComponent() so the admin form is still only fetched when a widget
* is actually opened.
*/
import Header from "@/components/text/Header.vue";
import CreateToggle from "@/components/input/CreateToggle.vue";
import LinkTable from "@/components/util/LinkTable.vue";
import AutoScroll from "@/components/util/AutoScroll.vue";
import Modal from "@/components/util/Modal.vue";
import { ref } from "vue";
defineProps({
title: { type: String, required: true },
items: { type: Array, required: true },
createForm: { type: [Object, Function], required: true },
});
const showCreate = ref(false);
</script>
<template>
<div class="flex flex-col items-center">
<Header>
{{ title }}
<template #action><CreateToggle v-model="showCreate" /></template>
</Header>
<AutoScroll class="flex-1 w-full">
<LinkTable variant="table" class="w-full" :items="items" />
</AutoScroll>
<Modal v-model="showCreate">
<component
:is="createForm"
@done="showCreate = false"
@cancel="showCreate = false"
/>
</Modal>
</div>
</template>
+13 -23
View File
@@ -2,38 +2,28 @@
/**
* "Listening" widget on /stp: rotates through recent Spotify plays.
*
* Two timers: a 5s rotation (self-rearming setTimeout, so a manual change would
* reset the full interval) and a 2-minute re-poll of Spotify. Both are cleared on
* unmount.
* Two timers, both owned by useRotation(): a 5s rotation and a 2-minute re-poll
* of Spotify.
*/
import Header from "@/components/text/Header.vue";
import { ref, computed, onMounted, onUnmounted } from "vue";
import { computed, onMounted } from "vue";
import { useSongsStore } from "@/stores/songs";
import { useRotation } from "@/js/useRotation";
const ROTATE_MS = 5000;
const REFRESH_MS = 120000;
const songsStore = useSongsStore();
const idx = ref(0);
const { idx, next: nextSong } = useRotation(() => songsStore.songs, ROTATE_MS, {
refresh: () => songsStore.fetchSongs(),
refreshMs: REFRESH_MS,
});
const song = computed(() => songsStore.songs[idx.value]);
let nextId = null;
let refreshId = null;
// Self-rearming timeout rather than setInterval, so the full 5s is restarted
// whenever the song changes rather than leaving a short remainder.
function nextSong() {
clearTimeout(nextId);
nextId = setTimeout(nextSong, 5000);
idx.value = (idx.value + 1) % songsStore.songsCount;
}
onMounted(() => {
songsStore.fetchSongs();
nextId = setTimeout(nextSong, 5000);
refreshId = setInterval(songsStore.fetchSongs, 120000);
});
onUnmounted(() => {
clearTimeout(nextId);
clearInterval(refreshId);
});
</script>
+14 -24
View File
@@ -1,43 +1,33 @@
<script setup>
/**
* Steam widget on /stp: online status plus a rotation through recent games
* (5s rotation, 5-minute re-poll). `loaded` comes from homeData so the widget can
* tell "not fetched yet" from "fetched, nothing to show".
* (5s rotation, 5-minute re-poll, both from useRotation()). `loaded` comes from
* homeData so the widget can tell "not fetched yet" from "fetched, nothing to
* show".
*/
import { ref, computed, onMounted, onUnmounted } from "vue";
import { computed } from "vue";
import { storeToRefs } from "pinia";
import { useSteamStore } from "@/stores/steam";
import { useHomeDataStore } from "@/stores/homeData";
import Header from "@/components/text/Header.vue";
import { useRotation } from "@/js/useRotation";
const ROTATE_MS = 5000;
const REFRESH_MS = 5 * 60 * 1000;
const steamStore = useSteamStore();
const { steamStatus } = storeToRefs(steamStore);
const homeData = useHomeDataStore();
const { loaded } = storeToRefs(homeData);
const idx = ref(0);
const { idx, next: nextGame } = useRotation(
() => steamStatus.value.recentGames,
ROTATE_MS,
{ refresh: () => steamStore.fetchSteam(), refreshMs: REFRESH_MS },
);
const game = computed(() => steamStatus.value.recentGames[idx.value]);
let nextId = null;
let refreshId = null;
function nextGame() {
clearTimeout(nextId);
nextId = setTimeout(nextGame, 5000);
if (steamStatus.value.recentGames.length) {
idx.value = (idx.value + 1) % steamStatus.value.recentGames.length;
}
}
onMounted(() => {
nextId = setTimeout(nextGame, 5000);
refreshId = setInterval(() => steamStore.fetchSteam(), 5 * 60 * 1000);
});
onUnmounted(() => {
clearTimeout(nextId);
clearInterval(refreshId);
});
function formatHours(minutes) {
const hrs = (minutes / 60).toFixed(1);
return `${hrs}h`;
+25 -47
View File
@@ -2,12 +2,13 @@
/**
* "Cheapest night" tab of /hotels: scans a date range (capped at MAX_SPAN_DAYS,
* optionally filtered to particular weekdays) and reports the best hotel per
* night. Same streaming/abort/ticker mechanics as SingleStayPanel.vue.
* night. Shares the streaming/abort/ticker lifecycle with SingleStayPanel.vue
* through useHotelSearch(); only the event shapes differ.
*/
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { ref, computed, onMounted } from "vue";
import SharedFields from "./SharedFields.vue";
import HotelRows from "./HotelRows.vue";
import { runStream } from "./hotelsStream.js";
import { useHotelSearch } from "./useHotelSearch.js";
import { todayIso, addDays, loadFrom, saveTo } from "./useHotelForm.js";
import {
gbp,
@@ -53,29 +54,33 @@ function setDays(list) {
}
// ---------------------------------------------------------------------------
// Scan state
// Scan state (searching/errorMsg/summary/done/elapsed come from the
// composable; the night rows and their transport cache are this panel's own)
// ---------------------------------------------------------------------------
const searching = ref(false);
const errorMsg = ref("");
const summary = ref(null);
const nightRows = ref([]);
const cached = ref(false);
const done = ref(false);
const elapsed = ref(0);
const expanded = ref(new Set());
let transportByCode = {};
let ticker = null;
let aborter = null;
const statusText = computed(() => {
if (errorMsg.value) return "Error";
if (searching.value) return "Scanning";
if (done.value) return "Done";
return "Idle";
const {
searching,
errorMsg,
summary,
done,
elapsed,
statusText,
hasResults,
run: onScan,
} = useHotelSearch({
url: "/py/hotels/scan/stream",
buildRequest,
applyEvent,
onStart,
busyLabel: "Scanning",
failMessage: "Scan failed.",
earlyMessage: "The scan ended early; showing what came back.",
});
const hasResults = computed(() => summary.value !== null);
const fetchedCount = computed(() => {
const s = summary.value;
return s ? s.nights_fetched + s.nights_failed + s.nights_skipped : 0;
@@ -306,43 +311,16 @@ function applyEvent(ev) {
}
}
async function onScan() {
if (searching.value) return;
errorMsg.value = "";
summary.value = null;
/** Reset this panel's own result state before a run. */
function onStart() {
nightRows.value = [];
transportByCode = {};
expanded.value = new Set();
cached.value = false;
done.value = false;
searching.value = true;
elapsed.value = 0;
saveConfig();
ticker = setInterval(() => elapsed.value++, 1000);
aborter = new AbortController();
try {
await runStream("/py/hotels/scan/stream", buildRequest(), {
signal: aborter.signal,
onEvent: applyEvent,
});
if (!done.value && !errorMsg.value)
errorMsg.value = "The scan ended early; showing what came back.";
} catch (e) {
if (e.name !== "AbortError") errorMsg.value = e.message || "Scan failed.";
} finally {
clearInterval(ticker);
ticker = null;
aborter = null;
searching.value = false;
}
}
onMounted(loadConfig);
onBeforeUnmount(() => {
if (ticker) clearInterval(ticker);
if (aborter) aborter.abort();
});
</script>
<template>
+25 -50
View File
@@ -7,13 +7,13 @@
* are patched in place by hotel `code` so the table fills in rather than
* reloading, and PENDING_ROUTE marks the not-yet-priced ones.
*
* An AbortController cancels an in-flight stream; a 1s ticker drives the elapsed
* counter. Both are torn down in the `finally` and on unmount.
* The abort/ticker/stream lifecycle lives in useHotelSearch(); this panel only
* supplies the request body and how to apply each streamed event.
*/
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { ref, computed, onMounted } from "vue";
import SharedFields from "./SharedFields.vue";
import HotelRows from "./HotelRows.vue";
import { runStream } from "./hotelsStream.js";
import { useHotelSearch } from "./useHotelSearch.js";
import { nextFriday, todayIso } from "./useHotelForm.js";
import {
gbp,
@@ -47,31 +47,35 @@ const top = ref(20);
const rankBy = ref("total");
// ---------------------------------------------------------------------------
// Search state
// Search state (searching/errorMsg/summary/done/elapsed come from the
// composable; rows and `cached` are this panel's own)
// ---------------------------------------------------------------------------
const searching = ref(false);
const errorMsg = ref("");
const summary = ref(null);
const rows = ref([]);
const cached = ref(false);
const done = ref(false);
const elapsed = ref(0);
let ticker = null;
let aborter = null;
const statusText = computed(() => {
if (errorMsg.value) return "Error";
if (searching.value) return "Searching";
if (done.value) return "Done";
return "Idle";
const {
searching,
errorMsg,
summary,
done,
elapsed,
statusText,
hasResults,
run: onSearch,
} = useHotelSearch({
url: "/py/hotels/search/stream",
buildRequest,
applyEvent,
onStart,
busyLabel: "Searching",
failMessage: "Search failed.",
earlyMessage: "The search ended early; showing what came back.",
});
const pricedCount = computed(
() => rows.value.filter((r) => r.total != null || r.route !== PENDING_ROUTE).length,
);
const hasResults = computed(() => summary.value !== null);
const sortedRows = computed(() => {
const cmp = { total: byTotal, room: byRoom, cycle: byCycle, minutes: byMinutes }[
rankBy.value
@@ -204,43 +208,14 @@ function applyEvent(ev) {
}
}
async function onSearch() {
if (searching.value) return;
errorMsg.value = "";
summary.value = null;
/** Reset this panel's own result state before a run. */
function onStart() {
rows.value = [];
cached.value = false;
done.value = false;
searching.value = true;
elapsed.value = 0;
saveConfig();
// 1s elapsed counter plus an AbortController to cancel the stream; both
// are torn down in the finally below and on unmount.
ticker = setInterval(() => elapsed.value++, 1000);
aborter = new AbortController();
try {
await runStream("/py/hotels/search/stream", buildRequest(), {
signal: aborter.signal,
onEvent: applyEvent,
});
if (!done.value && !errorMsg.value)
errorMsg.value = "The search ended early; showing what came back.";
} catch (e) {
if (e.name !== "AbortError") errorMsg.value = e.message || "Search failed.";
} finally {
clearInterval(ticker);
ticker = null;
aborter = null;
searching.value = false;
}
}
onMounted(loadConfig);
onBeforeUnmount(() => {
if (ticker) clearInterval(ticker);
if (aborter) aborter.abort();
});
</script>
<template>
+84
View File
@@ -0,0 +1,84 @@
// Search lifecycle shared by the "Single stay" and "Cheapest night" panels.
//
// Both panels run the same routine: reset the result state, start a 1s elapsed
// ticker and an AbortController, stream NDJSON events from a Python endpoint,
// then tear everything down in a `finally` (and again on unmount, so leaving
// the page cancels an in-flight request). Only the events themselves differ,
// so each panel supplies its own applyEvent().
import { ref, computed, onBeforeUnmount } from "vue";
import { runStream } from "./hotelsStream.js";
/**
* @param {object} options
* @param {string} options.url NDJSON streaming endpoint to POST to
* @param {() => object} options.buildRequest request body for one run
* @param {(ev: object) => void} options.applyEvent apply one streamed event.
* Called for every event; it is the panel's job to write into
* `summary` / `done` / `errorMsg` from the returned object. Declare it
* as a hoisted `function` so it can reference that object.
* @param {() => void} [options.onStart] reset panel-local state before a run
* @param {string} [options.busyLabel] status chip text while running
* @param {string} [options.failMessage] fallback message for a thrown error
* @param {string} [options.earlyMessage] shown when the stream ends without `done`
*/
export function useHotelSearch({
url,
buildRequest,
applyEvent,
onStart,
busyLabel = "Searching",
failMessage = "Search failed.",
earlyMessage = "The search ended early; showing what came back.",
}) {
const searching = ref(false);
const errorMsg = ref("");
const summary = ref(null);
const done = ref(false);
const elapsed = ref(0);
let ticker = null;
let aborter = null;
const statusText = computed(() => {
if (errorMsg.value) return "Error";
if (searching.value) return busyLabel;
if (done.value) return "Done";
return "Idle";
});
const hasResults = computed(() => summary.value !== null);
async function run() {
if (searching.value) return;
errorMsg.value = "";
summary.value = null;
done.value = false;
searching.value = true;
elapsed.value = 0;
if (onStart) onStart();
ticker = setInterval(() => elapsed.value++, 1000);
aborter = new AbortController();
try {
await runStream(url, buildRequest(), {
signal: aborter.signal,
onEvent: applyEvent,
});
if (!done.value && !errorMsg.value) errorMsg.value = earlyMessage;
} catch (e) {
// An abort is the user leaving or restarting, not a failure.
if (e.name !== "AbortError") errorMsg.value = e.message || failMessage;
} finally {
clearInterval(ticker);
ticker = null;
aborter = null;
searching.value = false;
}
}
onBeforeUnmount(() => {
if (ticker) clearInterval(ticker);
if (aborter) aborter.abort();
});
return { searching, errorMsg, summary, done, elapsed, statusText, hasResults, run };
}