﻿# Pixify

Pixify is a lightweight, Pixiv-inspired web app for storing and browsing your personal anime and NSFW fanart collection. It runs on Cloudflare Pages and keeps gallery data in a shared Cloudflare D1 database, with browser local storage used as a local cache.

This folder contains **only the website**. The companion applications live separately:

- `D:\Hostmost\pixify-extension` — Chrome extension (Manifest V3)
- `D:\Hostmost\pixify-desktop` — Tauri desktop client and its installers

The website starts empty and has no bundled artworks, sample images, or API keys. Gallery data is shared through Cloudflare D1 via Pages Functions:

- `GET /api/gallery` — read collections and artwork metadata
- `POST /api/gallery` — upsert-only artwork metadata; never deletes or writes collections
- `POST /api/gallery/collections` — create/upsert one collection
- `DELETE /api/gallery/collections/:id` — delete one collection
- `POST /api/gallery/artworks` — create/upsert artwork metadata and its collection membership
- `DELETE /api/gallery/artworks/:id` — delete one artwork, its memberships, and its media mapping
- `GET /api/media?url=...` — fetch an image at request time from the allow-listed external host
- `GET /api/media/:id` — legacy resolver for unmigrated rows; new rows use `/api/media?url=...`
- `GET /api/gallery/media-index` — saved source URL index used by the collector to skip duplicates
- `GET|POST /api/gallery/cache/rebuild` — seed the D1 snapshot table from D1 in one pass
- `POST /api/pixhost-upload` — upload a local file or a remote source URL to Pixhost v2

The separate Chrome extension uses the same API for its collection list and artwork metadata, so the website and extension stay in sync. Collections are D1-only: an old `pixify-state-v2` collection list is cleared on load and is never imported back into D1. Artwork metadata (including external image/source URLs) lives in `pixify_artworks` / `pixify_media`; the gallery renders `/api/media?url=...` proxy URLs, and the serving snapshot lives in `pixify_gallery_cache` so ordinary browsing costs only three small D1 rows. Browser local storage is only a UI cache. See `migrations/0001_pixify_gallery.sql`, `0002_remove_image_urls.sql`, and `0003_gallery_cache.sql`.

## Features

- Pixiv-style UI theme with **dark mode by default** and a simple light/dark toggle switch
- Masonry illustration grid with artwork detail view, tags, and search
- **NSFW section** for R-18 works (automatically hidden when "Show NSFW" is turned off)
- Organize works with **Collections** (create, edit, rename/describe, and manage artworks)
- Save and preview **Links** (websites/videos/posts) inside collections with embed previews when available
- **Add** artworks by direct/page URL with best-effort original-image resolution where available
- **Optional Pixhost upload** — upload a local image (max 10 MB) to pixhost.to from the Add dialog; the returned URL is kept only in browser state and served through the media API
- Search by title, artist, or tag, plus tag/popularity/newest filters
- Static build with Pages Functions, ready for **Cloudflare Pages + D1**

## Local development

```bash
npm install
npm run dev
```

## Build

```bash
npm run build
```

The production build is output to `dist/`.

## Deploy to Cloudflare Pages

- **Framework preset:** Vite (or None)
- **Build command:** `npm run build`
- **Build output directory:** `dist`

A `public/_redirects` file is included for SPA routing fallback.

## D1 row-read protection

D1's free tier has a daily row-read quota. This project now uses a **cache-first**
design so one person browsing, opening popups, uploading, or auditing images
does not consume that quota:

- All gallery/collection/media-index GET handlers serve one gallery snapshot
  from the `pixify_gallery_cache` D1 table (three rows, no expiry). Collection
  counts and the source index are derived from that snapshot, so they can never
  drift behind it. Old `cache:*` KV values are only a cold-start fallback.
- Write handlers update that snapshot incrementally in the same D1 batch. A
  daily KV write quota (1,000 writes) can no longer make the gallery stale.
- `/api/media?url=...` streams images directly from the URL in the query string,
  so the site and auditor no longer read one D1 row per image. Static images are
  capped at 25 MB; Hostux GIFs are allowed up to 80 MB so the 64 MB upload cap
  is actually usable in the viewer.
- A tiny separate Worker (`workers/cache-rebuild.ts`, config
  `wrangler.cache.toml`) rebuilds the snapshot from D1 **once per day at 00:05
  UTC**. Manual equivalent:
  `POST https://pixified.pages.dev/api/gallery/cache/rebuild`.
- Rebuilds are strict: if the snapshot cannot be written the endpoint reports an
  error instead of falsely reporting success with a stale cache.

Normal reads now cost a few D1 rows per request, not thousands, and do not
depend on KV write availability at all.

### GitHub read-only fallback (optional)

D1 stays the source of truth. A public GitHub repo can hold plain JSON snapshots
that are used **only** when the D1 cache is empty and D1 itself cannot be read.
The fallback response is never written back into D1.

1. In a **public** repo, copy `scripts/export_github_snapshot.py` and
   `scripts/gallery-snapshot.workflow.yml` (as
   `.github/workflows/gallery-snapshot.yml`). Add a `CLOUDFLARE_API_TOKEN`
   secret with D1 read access.
2. The workflow exports D1, writes `data/gallery.json`, `data/collections.json`
   and `data/media-index.json`, and commits them daily.
3. Point the site at the raw prefix:

```powershell
npx wrangler pages secret put GITHUB_SNAPSHOT_BASE --project-name=pixified
# value: https://cdn.jsdelivr.net/gh/OWNER/REPO@main/data
```

`raw.githubusercontent.com/OWNER/REPO/main/data` also works. jsDelivr is
preferred because it is a real CDN with CORS and caching. Files are ~3.8 MB,
~2.7 KB and ~364 KB, well under jsDelivr's 20 MB/file limit.

**Capacity:** the repo holds the *text index*, not images. jsDelivr can absorb
thousands of metadata requests, but every cold fetch downloads ~3.8 MB, so
10,000 cold fetches means ~38 GB of transfer. Versioned URLs and browser caching
keep this tiny in practice. GitHub is **not** an image host: keep image bytes on
Pixhost/Hostux and serve them through `/api/media?url=...`.

### High-volume direct viewing (additive)

For heavy browsing, every artwork now also carries a separate `directImage`
field for Pixhost/Hostux URLs. The browser loads that URL directly from the
image host, so an image view costs **zero** Cloudflare Worker requests. The
existing `image` field is unchanged (`/api/media?url=...`), and a global image
error handler swaps any failed direct load back to that proxy. Right-clicking a
direct image also swaps its `src` to the proxy before the native menu opens, so
**“Open image in new tab” shows the `pixified.pages.dev` URL, not the image host
URL**; middle-click and Ctrl/Cmd-click open that proxy URL too. The modal’s
**Download** button also streams through `/api/media?url=...&download=1` (with
`Content-Disposition: attachment`), so saving a file never redirects to the
external host. Auditors, collectors and old clients continue to use `image` and
are unaffected.

This removes the Worker request cap from normal viewing: 1,000 viewers × 150
pages × 20 images would have been ~3,000,000 proxy requests/day; with direct
loading it is ~1,000 gallery metadata requests/day. The tradeoff is that the
external URL is visible and Hostux/Pixhost must allow hotlinking.

Deploy both pieces (only the `pixified` Pages project is touched):

```powershell
npm run build
npx wrangler pages deploy dist --project-name=pixified
npx wrangler deploy --config wrangler.cache.toml
```

## Notes

- Gallery metadata and external image/source URLs are stored in the `pixify-db` D1 database through the `DB` binding (`pixify_artworks`, `pixify_media`). The `MEDIA` KV namespace is kept only for legacy URL mappings. Browser local storage (`pixify-state-v2`, `pixify-theme`) caches artwork URLs and theme only. The collections list always comes from D1; pre-existing browser-only collections are removed on first load.
- Local `npm run dev` uses the deployed Pixify gallery API because Pages Functions are not available on Vite's dev server.
- There are no mock/sample images included; start by using **Add** to create artworks or collections/links.
- Page-URL resolution for Pixiv, Reddit, Pinterest, and Twitter/X is best-effort and depends on the source site; direct image URLs are the most reliable option.
