Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(tracked-content): attach images to Reddit posts via Cloudinary
spacesdriveca713830011a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b5c52c..333012f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Added+**Images on tracked Reddit posts**+- Reddit's public JSON API carries no usable thumbnail, so a screenshot can now be uploaded per tracked Reddit post+- The browser posts the file directly to Cloudinary with the unsigned preset and sends only the returned `secure_url`, keeping the Worker free of binary uploads as the architecture requires+- `PUT /api/tracked-content/:id` accepts `imageUrl`: Reddit-only (400 for YouTube, which has a real thumbnail), must parse as an `https:` URL since the value is rendered into an `img src`, and `null` clears it+- Stored as `data.imageUrl` and merged through `patchTrackedPostData()`, so it survives a live refresh+- `components/ImageLightbox.jsx` added: a thumbnail that opens the full image in a shadcn `Dialog`, with `cursor-zoom-in`, keyboard focus ring, and an `sr-only` title+- Tracked Content: upload, preview, and remove controls in the edit dialog; 10MB and image-only client-side checks; the field explains itself when Cloudinary is not configured+- Tracked Content and Tracked Category tables: Reddit posts with an image show it at the left of the row, matching where YouTube thumbnails already sit, and clicking it opens the full size view+**Manual view counts for tracked Reddit posts**- Reddit removed `view_count` from its API in December 2018, so views for a tracked Reddit post can now be entered by hand- `PUT /api/tracked-content/:id` accepts `manualViews`: a whole number of 0 or more, `null` to clear, rejected with a 400 for YouTube items which report a real view count@@ -20,11 +29,13 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Changed+- Tracked Category "Post Views" subtitle now reads "across 9 posts" rather than "entered by hand on 9 of 9 posts"+**Views now include tracked content everywhere**- Overview Total Views tab: channel views plus tracked YouTube views plus manual Reddit views; tab subtitle breaks the two apart- Views tab gained Total Views, Channel Views, and Tracked Views stat cards, plus a "Views by Category" area chart- Tracked Category page: "YouTube Views" replaced with a combined "Total Views" card showing the YouTube and Reddit split-- Tracked Category Reddit section: "Post Views" stat card added showing how many posts have a figure recorded; "Avg Karma per Post" folded into the Post Karma subtitle to keep the grid at four cards+- Tracked Category Reddit section: "Post Views" stat card added; "Avg Karma per Post" folded into the Post Karma subtitle to keep the grid at four cards- Tracked Category Reddit table: Views column added- Overview Tracked Categories card: view figure is now the YouTube plus Reddit total rather than YouTube alonediff --git a/backend/routes/trackedContent.js b/backend/routes/trackedContent.jsindex 833c493..1430d48 100644--- a/backend/routes/trackedContent.js+++ b/backend/routes/trackedContent.js@@ -81,22 +81,24 @@ router.post('/tracked-content', async (c) => {}});-// Update label, category, account, or manually entered view count+// Update label, category, account, manually entered view count, or attached imagerouter.put('/tracked-content/:id', async (c) => {const id = c.req.param('id');const userId = c.get('userId');const supabase = c.get('supabase');const body = await c.req.json();- const { label, category, accountId, manualViews } = body;+ const { label, category, accountId, manualViews, imageUrl } = body;try {const existing = await getTrackedPostById(supabase, id, userId);if (!existing) return c.json({ error: 'Tracked content not found' }, 404);+ const isYouTube = (existing.contentType || 'reddit') === 'youtube';+// Reddit removed view_count from their API in 2018, so views can only be entered by hand.// YouTube returns a real view count, so accepting a manual one would silently override it.if (manualViews !== undefined) {- if ((existing.contentType || 'reddit') === 'youtube') {+ if (isYouTube) {return c.json({ error: 'YouTube view counts are fetched automatically and cannot be set by hand' }, 400);}if (manualViews === null || manualViews === '') {@@ -110,6 +112,27 @@ router.put('/tracked-content/:id', async (c) => {}}+ // Reddit posts carry no thumbnail in the public JSON API, so the user uploads one to+ // Cloudinary from the browser and only the resulting URL reaches the Worker. YouTube+ // items already have a real thumbnail and must not be overridden.+ if (imageUrl !== undefined) {+ if (isYouTube) {+ return c.json({ error: 'Images can only be attached to Reddit posts' }, 400);+ }+ if (imageUrl === null || imageUrl === '') {+ await patchTrackedPostData(supabase, id, { imageUrl: null }, userId);+ } else {+ let parsed = null;+ try { parsed = new URL(String(imageUrl)); } catch { parsed = null; }+ // https only - the value is rendered straight into an img src, so a+ // javascript: or data: URL must never be stored+ if (!parsed || parsed.protocol !== 'https:') {+ return c.json({ error: 'Image must be an https URL returned by the uploader' }, 400);+ }+ await patchTrackedPostData(supabase, id, { imageUrl: parsed.toString() }, userId);+ }+ }+const updates = {};if (label !== undefined) updates.label = label;if (category !== undefined) updates.category = category;diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex 5233e2c..0165a3e 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -100,6 +100,7 @@ Cloudflare scheduler fires cron trigger| Scheduled posts | `scheduled_posts` table | Queryable by status + scheduled_at || Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls || Media files (for publishing) | Cloudinary CDN | Instagram requires public URL |+| Tracked Reddit post images | Cloudinary CDN | Reddit's public JSON API carries no usable thumbnail || API secrets | Cloudflare Worker secrets | Encrypted at rest, never in responses |## Environment Configurationdiff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 5b11338..0ba0218 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -78,7 +78,7 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup|---|---|---|---|| GET | `/api/tracked-content` | `routes/trackedContent.js` | List all tracked items for the current user (Reddit posts and YouTube videos) || POST | `/api/tracked-content` | `routes/trackedContent.js` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately |-| PUT | `/api/tracked-content/:id` | `routes/trackedContent.js` | Update `label`, `category`, `accountId`, or `manualViews` for a tracked item. `manualViews` is Reddit-only (400 for YouTube), must be a whole number of 0 or more, and `null` clears it |+| PUT | `/api/tracked-content/:id` | `routes/trackedContent.js` | Update `label`, `category`, `accountId`, `manualViews`, or `imageUrl` for a tracked item. `manualViews` and `imageUrl` are Reddit-only (400 for YouTube) and `null` clears either. `manualViews` must be a whole number of 0 or more; `imageUrl` must parse as an `https:` URL || DELETE | `/api/tracked-content/:id` | `routes/trackedContent.js` | Remove a tracked item || POST | `/api/tracked-content/:id/refresh` | `routes/trackedContent.js` | Re-fetch live data from Reddit or YouTube API for one tracked item |diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex 228c029..954489c 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -173,20 +173,28 @@ Populated by `fetchTrackedPostData()` in `backend/services/reddit.js`:"numComments": 56,"permalink": "https://reddit.com/r/programming/comments/abc123/...","lastFetchedAt": "2026-08-04T10:00:00Z",- "manualViews": 12500+ "manualViews": 12500,+ "imageUrl": "https://res.cloudinary.com/mycloud/image/upload/v1/abc.jpg"}```-`manualViews` is the one key in `data` that is not fetched from Reddit. Reddit removed-`view_count` from its API in December 2018, so view counts can only be entered by hand-through `PUT /api/tracked-content/:id`. It is `null` or absent until the user sets one.+`manualViews` and `imageUrl` are the two keys in `data` that are not fetched from Reddit.+Both are set by the user through `PUT /api/tracked-content/:id` and are `null` or absent+until then.++- `manualViews` - Reddit removed `view_count` from its API in December 2018, so view counts+ can only be entered by hand.+- `imageUrl` - Reddit's public JSON API carries no usable thumbnail, so the user uploads a+ screenshot. The browser posts it directly to Cloudinary and only the returned `secure_url`+ reaches the Worker, which stores it after checking the URL parses and uses `https:`. That+ check matters because the value is rendered straight into an `img src`.Because of this, the refresh route calls `patchTrackedPostData()` rather than`updateTrackedPost({ data })` - the former merges freshly fetched keys into the existingblob so a manually entered view count survives a refresh. Anything writing to `data` for aReddit item must merge, never replace.-`manualViews` is rejected for YouTube items; YouTube returns a real `viewCount`.+Both keys are rejected for YouTube items, which already carry a real `viewCount` and `thumbnail`.### `data` jsonb shape for YouTube itemsdiff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex 0c46e70..a295ea8 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -112,8 +112,13 @@ refreshTrackedContent: (id) => request(`/tracked-content/${id}/refresh`, { metho`accountId` may be `null`. For YouTube items, `accountId` is always `null` (fetched via the server's `YOUTUBE_API_KEY`). For Reddit items, `accountId` is optional and refers to a Reddit account whose cookie improves datacenter IP access.`updateTrackedContent` takes a partial object, so only the keys present are changed. Accepted-keys are `label`, `category`, `accountId`, and `manualViews`. `manualViews` is Reddit-only and-sending it for a YouTube item returns a 400; pass `null` to clear a previously entered figure.+keys are `label`, `category`, `accountId`, `manualViews`, and `imageUrl`. `manualViews` and+`imageUrl` are Reddit-only and sending either for a YouTube item returns a 400; pass `null` to+clear a previously set value.++`imageUrl` must already be a hosted `https:` URL. The Worker never accepts binary uploads, so+the browser posts the file straight to Cloudinary with the unsigned preset from+`getCloudinaryConfig()` and sends only the returned `secure_url`.## Authenticationdiff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex 3f6d8fe..a367d71 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -6,7 +6,8 @@frontend/src/├── components/│ ├── MainCard.jsx <- Card wrapper with optional title/subheader/separator-│ └── MetricAreaChart.jsx <- Shared Recharts area chart for single-metric comparisons+│ ├── MetricAreaChart.jsx <- Shared Recharts area chart for single-metric comparisons+│ └── ImageLightbox.jsx <- Thumbnail that opens the full image in a Dialog├── features/│ ├── analytics/│ │ ├── channel/@@ -62,6 +63,20 @@ grid, gradient, and tooltip styling. Use it instead of hand-rolling a Recharts `Each instance generates its own gradient id via `useId()`, so multiple charts on one pagenever collide.+## Image Lightbox++`components/ImageLightbox.jsx` renders a thumbnail that opens the full image in a shadcn+`Dialog`. Used for tracked Reddit post images, which have no platform thumbnail:++```jsx+<ImageLightbox src={item.imageUrl} alt={item.title} thumbClassName="size-14" />+```++Base UI supports nested dialogs, so this works inside the Tracked Content edit dialog. Child+dialogs skip the backdrop and only the topmost one responds to Escape and outside clicks.++Note the Base UI composition rule: the trigger takes a `render` prop, not `asChild`.+## Feature Conventions### One directory per feature domaindiff --git a/frontend/src/components/ImageLightbox.jsx b/frontend/src/components/ImageLightbox.jsxnew file mode 100644index 0000000..581a3a1--- /dev/null+++ b/frontend/src/components/ImageLightbox.jsx@@ -0,0 +1,46 @@+import React, { useState } from 'react';+import { Dialog, DialogContent, DialogTitle, DialogTrigger } from '@/components/ui/dialog';+import { cn } from '@/lib/utils';++export default function ImageLightbox({+ src,+ alt = '',+ className = '',+ thumbClassName = 'h-10 w-16',+}) {+ const [open, setOpen] = useState(false);++ if (!src) return null;++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger+ render={+ <button+ type="button"+ title="View image"+ aria-label={alt ? `View image for ${alt}` : 'View image'}+ className={cn(+ 'group relative shrink-0 overflow-hidden rounded border border-border bg-muted',+ 'cursor-zoom-in transition-opacity hover:opacity-80',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ thumbClassName,+ className+ )}+ />+ }+ >+ <img src={src} alt={alt} loading="lazy" className="h-full w-full object-cover" />+ </DialogTrigger>++ <DialogContent className="sm:max-w-3xl p-2 gap-2">+ <DialogTitle className="sr-only">{alt || 'Image preview'}</DialogTitle>+ <img+ src={src}+ alt={alt}+ className="max-h-[75vh] w-full rounded-lg object-contain"+ />+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/src/features/analytics/tracked/TrackedCategory.jsx b/frontend/src/features/analytics/tracked/TrackedCategory.jsxindex 4581d2e..8d3e2f4 100644--- a/frontend/src/features/analytics/tracked/TrackedCategory.jsx+++ b/frontend/src/features/analytics/tracked/TrackedCategory.jsx@@ -11,6 +11,7 @@ import {import StatCard from '../../../components/ui/StatCard';import MainCard from '../../../components/MainCard';import MetricAreaChart from '../../../components/MetricAreaChart';+import ImageLightbox from '../../../components/ImageLightbox';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtNumFull, fmtDate } from '../../../utils/formatters';@@ -400,7 +401,7 @@ export default function TrackedCategory() {value={rdStats.withViews > 0 ? fmtNum(rdStats.views) : '-'}subtitle={rdStats.withViews > 0- ? `entered by hand on ${rdStats.withViews} of ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}`+ ? `across ${rdItems.length} post${rdItems.length !== 1 ? 's' : ''}`: 'Reddit does not report views - add them per post'}gradient="teal"@@ -459,17 +460,26 @@ export default function TrackedCategory() {<span className={`text-xs font-bold tabular-nums ${medalColor(i)}`}>{i + 1}</span></TableCell><TableCell>- <div className="min-w-0">- <p className="text-sm font-medium leading-snug line-clamp-2">- {item.title || item.url}- </p>- <div className="flex items-center gap-2 mt-0.5 flex-wrap">- {item.subredditPrefixed && (- <span className="text-xs text-muted-foreground">{item.subredditPrefixed}</span>- )}- {item.label && (- <span className="text-xs text-muted-foreground italic">{item.label}</span>- )}+ <div className="flex items-start gap-2.5">+ {item.imageUrl && (+ <ImageLightbox+ src={item.imageUrl}+ alt={item.title || 'Reddit post'}+ className="mt-0.5"+ />+ )}+ <div className="min-w-0">+ <p className="text-sm font-medium leading-snug line-clamp-2">+ {item.title || item.url}+ </p>+ <div className="flex items-center gap-2 mt-0.5 flex-wrap">+ {item.subredditPrefixed && (+ <span className="text-xs text-muted-foreground">{item.subredditPrefixed}</span>+ )}+ {item.label && (+ <span className="text-xs text-muted-foreground italic">{item.label}</span>+ )}+ </div></div></div></TableCell>diff --git a/frontend/src/features/analytics/tracked/TrackedContent.jsx b/frontend/src/features/analytics/tracked/TrackedContent.jsxindex 352d23e..a6c7c01 100644--- a/frontend/src/features/analytics/tracked/TrackedContent.jsx+++ b/frontend/src/features/analytics/tracked/TrackedContent.jsx@@ -1,4 +1,4 @@-import React, { useState, useEffect, useMemo, useCallback } from 'react';+import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Badge } from '@/components/ui/badge';@@ -7,14 +7,16 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { Skeleton } from '@/components/ui/skeleton';import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';+import { Spinner } from '@/components/ui/spinner';import StatCard from '../../../components/ui/StatCard';import MainCard from '../../../components/MainCard';+import ImageLightbox from '../../../components/ImageLightbox';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum, fmtDate } from '../../../utils/formatters';import { trackedViews, hasTrackedViews } from '../../../utils/trackedContent';import {- Plus, RefreshCw, Trash2, Pencil, ExternalLink,+ Plus, RefreshCw, Trash2, Pencil, ExternalLink, Upload, X,Tag, Bookmark, BookmarkCheck, CirclePlay, Flame, Eye,} from 'lucide-react';@@ -39,6 +41,8 @@ function isRedditItem(item) {return (item?.contentType || 'reddit') === 'reddit';}+const MAX_IMAGE_BYTES = 10 * 1024 * 1024;+function ContentTypeBadge({ type }) {if (type === 'youtube') {return (@@ -84,8 +88,13 @@ export default function TrackedContent() {const [editLabel, setEditLabel] = useState('');const [editCategory, setEditCategory] = useState('');const [editViews, setEditViews] = useState('');+ const [editImageUrl, setEditImageUrl] = useState(null);+ const [uploading, setUploading] = useState(false);const [saving, setSaving] = useState(false);+ const [cloudConfig, setCloudConfig] = useState(null);+ const imageInputRef = useRef(null);+const load = useCallback(async () => {try {const data = await api.getTrackedContent();@@ -99,6 +108,13 @@ export default function TrackedContent() {useEffect(() => { load(); }, [load]);+ // Cloudinary config is only needed for Reddit image uploads; a missing config disables that field+ useEffect(() => {+ api.getCloudinaryConfig()+ .then(res => { if (res?.success) setCloudConfig(res); })+ .catch(() => {});+ }, []);+function handleUrlChange(val) {setAddUrl(val);setDetectedType(detectContentType(val));@@ -181,6 +197,51 @@ export default function TrackedContent() {setEditLabel(item.label || '');setEditCategory(item.category || '');setEditViews(item.manualViews != null ? String(item.manualViews) : '');+ setEditImageUrl(item.imageUrl || null);+ if (imageInputRef.current) imageInputRef.current.value = '';+ }++ // The Worker never handles binary uploads - the browser posts straight to Cloudinary with the+ // unsigned preset and only the returned URL is saved on the tracked item+ async function handleImageSelect(e) {+ const file = e.target.files?.[0];+ if (!file) return;++ if (!cloudConfig) {+ showToast('Cloudinary is not configured on this server, so images cannot be uploaded', 'error');+ return;+ }+ if (!file.type.startsWith('image/')) {+ showToast('Choose an image file', 'error');+ return;+ }+ if (file.size > MAX_IMAGE_BYTES) {+ showToast(`Images must be under ${MAX_IMAGE_BYTES / 1024 / 1024}MB`, 'error');+ return;+ }++ setUploading(true);+ try {+ const formData = new FormData();+ formData.append('file', file);+ formData.append('upload_preset', cloudConfig.uploadPreset);++ const res = await fetch(+ `https://api.cloudinary.com/v1_1/${cloudConfig.cloudName}/image/upload`,+ { method: 'POST', body: formData }+ );+ const json = await res.json();+ if (!res.ok || !json.secure_url) {+ throw new Error(json.error?.message || 'Upload failed');+ }+ setEditImageUrl(json.secure_url);+ showToast('Image uploaded');+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setUploading(false);+ if (imageInputRef.current) imageInputRef.current.value = '';+ }}async function handleSaveEdit() {@@ -200,6 +261,7 @@ export default function TrackedContent() {}updates.manualViews = views;}+ updates.imageUrl = editImageUrl || null;}setSaving(true);@@ -443,6 +505,12 @@ export default function TrackedContent() {<div className="max-w-sm flex items-start gap-2.5">{isYT && item.thumbnail ? (<img src={item.thumbnail} alt="" className="h-10 w-16 rounded object-cover flex-shrink-0 mt-0.5" />+ ) : !isYT && item.imageUrl ? (+ <ImageLightbox+ src={item.imageUrl}+ alt={item.title || item.label || 'Reddit post'}+ className="mt-0.5"+ />) : null}<div className="min-w-0"><p className="text-sm font-medium leading-snug line-clamp-2">@@ -701,6 +769,64 @@ export default function TrackedContent() {</p></div>)}++ {editItem && isRedditItem(editItem) && (+ <div className="flex flex-col gap-1.5">+ <label className="text-sm font-medium">+ Image <span className="text-muted-foreground font-normal">(optional)</span>+ </label>++ <input+ ref={imageInputRef}+ type="file"+ accept="image/*"+ onChange={handleImageSelect}+ className="hidden"+ />++ {editImageUrl ? (+ <div className="flex items-center gap-3 rounded-lg border border-border p-2">+ <ImageLightbox+ src={editImageUrl}+ alt={editItem.title || 'Reddit post'}+ thumbClassName="size-14"+ />+ <div className="flex-1 min-w-0">+ <p className="text-xs text-muted-foreground">+ Click the image to view it full size+ </p>+ </div>+ <Button+ variant="ghost"+ size="icon"+ className="size-7 shrink-0"+ onClick={() => setEditImageUrl(null)}+ title="Remove image"+ disabled={uploading}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>+ ) : (+ <Button+ variant="outline"+ size="sm"+ className="justify-start gap-2"+ onClick={() => imageInputRef.current?.click()}+ disabled={uploading || !cloudConfig}+ >+ {uploading ? <Spinner /> : <Upload className="h-3.5 w-3.5" />}+ {uploading ? 'Uploading...' : 'Upload image'}+ </Button>+ )}++ <p className="text-xs text-muted-foreground">+ {cloudConfig+ ? 'Reddit posts have no thumbnail in the public API. Upload a screenshot to recognise the post at a glance.'+ : 'Image uploads need Cloudinary configured on the server. Check Settings.'}+ </p>+ </div>+ )}</div><DialogFooter><Button variant="outline" onClick={() => setEditItem(null)} disabled={saving}>Cancel</Button>