mirror of
https://github.com/PR0M3TH3AN/bitvid.git
synced 2026-10-27 16:02:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79e5267524 | ||
|
|
344089cd39 | ||
|
|
1dbfa9b802 | ||
|
|
7e8d5f2fef | ||
|
|
6a3bc50066 | ||
|
|
83a9947611 | ||
|
|
0bf3ce8e8a | ||
|
|
fe39e65aa5 | ||
|
|
8de0ecc47d | ||
|
|
b438564b64 | ||
|
|
37a5ee3b7b | ||
|
|
23a8eacad4 | ||
|
|
1f191e2b90 | ||
|
|
2d0ddd0d3a | ||
|
|
db8178e573 | ||
|
|
3f293f77fa | ||
|
|
ebb289a80c | ||
|
|
d5551fd6a9 | ||
|
|
622c829b46 | ||
|
|
5f33aeea79 | ||
|
|
8d2f32c62b | ||
|
|
dd60ff07e9 | ||
|
|
5f20f1eb56 | ||
|
|
4cf6294591 | ||
|
|
d01fa93689 | ||
|
|
e92e681860 | ||
|
|
cdf0b5f08c | ||
|
|
7e3acdfd68 | ||
|
|
9c537ba7c7 | ||
|
|
6f5a931caa | ||
|
|
62cbc2a2eb | ||
|
|
511a016db4 | ||
|
|
bd345f99d2 | ||
|
|
169f0c952c | ||
|
|
d39ed45c5a | ||
|
|
a0356967ce | ||
|
|
57552dcfe1 | ||
|
|
bc08598237 | ||
|
|
c9dff9d436 | ||
|
|
84b5ef77c0 | ||
|
|
c6c297e16b | ||
|
|
66595edaf6 | ||
|
|
a56568e3c7 | ||
|
|
014b1369b0 | ||
|
|
c8afe45545 | ||
|
|
875cee4428 | ||
|
|
2eb00740fd | ||
|
|
7e8db028eb | ||
|
|
a53bded07f | ||
|
|
0d5a8f4017 | ||
|
|
468444a454 | ||
|
|
a677683205 | ||
|
|
e5f05f362c | ||
|
|
0041e24c87 | ||
|
|
de2d6c409f | ||
|
|
5365fad888 | ||
|
|
8966b426f8 | ||
|
|
92a7576fcb | ||
|
|
dd2f3768db | ||
|
|
b4e11cdce2 | ||
|
|
c39fb6ffe2 | ||
|
|
f3293a8c29 | ||
|
|
546fb4d1d2 | ||
|
|
c638b273fe | ||
|
|
3e083336b3 | ||
|
|
c851abc989 | ||
|
|
1c101266a6 | ||
|
|
30c260aa82 | ||
|
|
fa638e08a5 | ||
|
|
3da14ee174 | ||
|
|
875094c800 | ||
|
|
f1e0c63e01 | ||
|
|
c773a07cdc | ||
|
|
9de3592293 | ||
|
|
1b4bf696b7 | ||
|
|
b5987c5923 | ||
|
|
538526fbf5 | ||
|
|
c95e911f76 | ||
|
|
e297bd7bb3 | ||
|
|
cc627c1e65 | ||
|
|
f6612236f0 | ||
|
|
e0e1eb381c | ||
|
|
5d0f122e48 | ||
|
|
0461d06834 | ||
|
|
f07ca9966c | ||
|
|
62b770eff0 | ||
|
|
12aaf63d3d | ||
|
|
55cae181df | ||
|
|
2b0f3547cb | ||
|
|
2dfe20907b | ||
|
|
0b4523b0be | ||
|
|
866e4f11fb | ||
|
|
f6fa9daaad | ||
|
|
0217009752 | ||
|
|
1985b16064 | ||
|
|
854216f331 | ||
|
|
cbdab9f011 | ||
|
|
801bcd2345 | ||
|
|
c6a838ebc2 | ||
|
|
2b1d0ca26e | ||
|
|
5ef94c03ba | ||
|
|
e6b6522f6f | ||
|
|
742dd12915 | ||
|
|
1684c7070b | ||
|
|
8a278ca0ac | ||
|
|
c32d2fce12 | ||
|
|
46c2b39aae | ||
|
|
67f80787d0 | ||
|
|
1b720b92d3 | ||
|
|
7890a94949 | ||
|
|
3fa08631ea | ||
|
|
9da4e40ec9 | ||
|
|
34d4895799 | ||
|
|
7f70270889 | ||
|
|
9b4dd2a6ff | ||
|
|
f121a17cd9 | ||
|
|
7d73a8c594 | ||
|
|
ea300b47bf | ||
|
|
8d5d79e96f | ||
|
|
b52be2ab42 | ||
|
|
97c4ccff50 | ||
|
|
a9ffddf679 | ||
|
|
bc085ad3be | ||
|
|
a05e0c77fd | ||
|
|
27e45f56b5 | ||
|
|
069fcb1b7f | ||
|
|
54a6e05285 | ||
|
|
9a44112c88 | ||
|
|
836509e2f0 | ||
|
|
b51a8010d0 | ||
|
|
83184bd32f | ||
|
|
40f87167b9 | ||
|
|
84e3da0a87 | ||
|
|
1e388757ff | ||
|
|
dda977b91a | ||
|
|
61750bbbca | ||
|
|
b3b85b6323 | ||
|
|
6a0692c3e3 | ||
|
|
ddd8a393f4 | ||
|
|
0ad6d53ebb | ||
|
|
c1da7dbb39 | ||
|
|
4d0731fe6e | ||
|
|
614847c99b | ||
|
|
df6878aef6 | ||
|
|
059112eab9 | ||
|
|
58f564d1b2 | ||
|
|
cb67c55753 | ||
|
|
eb989bee89 | ||
|
|
ebcb402569 | ||
|
|
7e63771651 | ||
|
|
1238de1d71 | ||
|
|
b3b0ca7979 | ||
|
|
0153965fdf | ||
|
|
65d7950932 | ||
|
|
8ea130fb22 | ||
|
|
93493815fb | ||
|
|
3b6aef5dfd | ||
|
|
61df14b2e4 | ||
|
|
96c9707113 | ||
|
|
457c80b1e7 | ||
|
|
35969b0fc6 | ||
|
|
9e3ca0b273 | ||
|
|
6f0dca0d62 | ||
|
|
e90f903b01 | ||
|
|
0de68cbd6b | ||
|
|
efa68321df | ||
|
|
90a3bf97fe | ||
|
|
c5668bfc3b | ||
|
|
ab1eaaa5a1 | ||
|
|
6fb9f91a34 | ||
|
|
32f652e7a8 | ||
|
|
7c1675805e | ||
|
|
67b8caa623 | ||
|
|
1d0100619e | ||
|
|
b7ebed9843 | ||
|
|
237724b8ac | ||
|
|
ac0777534e | ||
|
|
4cbcfcfbf4 | ||
|
|
a593ea0f5b | ||
|
|
52553165d6 | ||
|
|
ddd6e40696 | ||
|
|
2d48f89f45 | ||
|
|
6e5c73f731 | ||
|
|
c56ffdfee6 | ||
|
|
0557014986 | ||
|
|
6c6641c961 | ||
|
|
77936e7656 | ||
|
|
69ca1f1d58 | ||
|
|
f9f9c8149c | ||
|
|
9629ef01ed | ||
|
|
fa738b9cb7 | ||
|
|
7bdf93cb63 | ||
|
|
e58c16ab83 | ||
|
|
dbe4563bb7 | ||
|
|
73e5a6bc83 | ||
|
|
109f5e0746 | ||
|
|
c5b30921ae | ||
|
|
c9ebc80ab4 | ||
|
|
c488f3fa16 | ||
|
|
1a6371fee3 | ||
|
|
72f3e4f8fd | ||
|
|
adf6bd56cd | ||
|
|
d89b38006a | ||
|
|
9bf283c2d4 | ||
|
|
02de05e31a | ||
|
|
447aea3d4b | ||
|
|
b617648136 | ||
|
|
8a9e325c22 | ||
|
|
d511757473 | ||
|
|
0af08f60b0 | ||
|
|
ce8a2aab87 | ||
|
|
fbd6fa4121 | ||
|
|
d6a34571a9 | ||
|
|
e85831bbf6 | ||
|
|
ff4fd71cbe | ||
|
|
aaf9066666 | ||
|
|
72db5396b4 | ||
|
|
16d4578ead | ||
|
|
14589b571c | ||
|
|
f482124411 | ||
|
|
f61291f75b | ||
|
|
42bfde21d5 | ||
|
|
8e0a5e0034 | ||
|
|
b031e98c4a | ||
|
|
5bf3112436 | ||
|
|
3b4bb7f0df | ||
|
|
5795a7e7d4 | ||
|
|
b66d6e1080 | ||
|
|
8c730e772b | ||
|
|
8e42816ec5 | ||
|
|
e7d895f123 | ||
|
|
04127bc22a | ||
|
|
996647f23d | ||
|
|
b52076cc26 | ||
|
|
940d9e66f7 | ||
|
|
5211897412 | ||
|
|
4456719bc9 | ||
|
|
96e1679618 | ||
|
|
82bd833594 | ||
|
|
9b11fe720c | ||
|
|
6ecd625fce | ||
|
|
9342c967ba | ||
|
|
9927b7e4ec | ||
|
|
2542e97398 | ||
|
|
5d0003c13d | ||
|
|
713cc909c7 | ||
|
|
02a1b5121d | ||
|
|
c94eb928e1 | ||
|
|
c384fc515f | ||
|
|
c5f67bc31e | ||
|
|
f0f1a7cf8f | ||
|
|
8a10a7cfc8 | ||
|
|
2ae9f01cb5 | ||
|
|
48a1f24ac9 | ||
|
|
b29ee486f0 | ||
|
|
9229f0fe80 | ||
|
|
e0da106442 | ||
|
|
532ce8e2d2 | ||
|
|
86928b8e8c | ||
|
|
b52e767f86 | ||
|
|
1be2c124b7 | ||
|
|
0d56082c54 | ||
|
|
d3f42b6eb3 | ||
|
|
2150ac0f0b | ||
|
|
e4ae6fadef | ||
|
|
eb9b50b572 | ||
|
|
8188b9f71a | ||
|
|
52ecb76ac9 | ||
|
|
80263bdba5 | ||
|
|
57496969d7 | ||
|
|
d9afdabe6c | ||
|
|
621465c538 | ||
|
|
1450e09697 | ||
|
|
dd47fbed93 | ||
|
|
548e0fd3c0 | ||
|
|
ed6b69b2e0 | ||
|
|
ee4ceb95b7 | ||
|
|
7742e3968c | ||
|
|
2442be4e77 | ||
|
|
3593fdd0ef | ||
|
|
873d1065e4 | ||
|
|
0d622bdb8d | ||
|
|
fc0bae85af | ||
|
|
db43e3634b | ||
|
|
c88bc404b6 | ||
|
|
d271bd335c | ||
|
|
fea5835a62 | ||
|
|
985acf6456 | ||
|
|
3e7eab1c92 | ||
|
|
bfee3b7a2a | ||
|
|
88eaff3107 | ||
|
|
33f29380f5 | ||
|
|
ef2fad74f8 | ||
|
|
167691d256 | ||
|
|
e3ee938f8d | ||
|
|
0569755901 | ||
|
|
a84f635539 | ||
|
|
c6891ca57c | ||
|
|
9f3f42181c | ||
|
|
0e0249ff91 | ||
|
|
fe0b89697f | ||
|
|
1e77d617ec | ||
|
|
56b478454c | ||
|
|
867e111a48 | ||
|
|
1256610429 | ||
|
|
4107796639 | ||
|
|
c84dc1e812 | ||
|
|
02ee898923 | ||
|
|
bd1c68d202 | ||
|
|
886b02a5ff | ||
|
|
0e5b871488 | ||
|
|
2ed1cc50db | ||
|
|
ad5f8958c5 | ||
|
|
9014371263 | ||
|
|
7350f43ca7 | ||
|
|
ba9bba517a | ||
|
|
811e1e30e1 | ||
|
|
7812034f0d | ||
|
|
b51b692f31 | ||
|
|
3ca66c7288 | ||
|
|
fe0245e30c | ||
|
|
2a26ef58f6 | ||
|
|
c4289161e1 | ||
|
|
0373859ad3 |
No files matched your search
+2
-1
@@ -1,3 +1,4 @@
|
||||
saved_config.yaml
|
||||
repo-context.txt
|
||||
src/webtorrent-docs/
|
||||
node_modules/
|
||||
src/webtorrent-docs/
|
||||
@@ -0,0 +1,84 @@
|
||||
# Bitvid — AI Agent Guide
|
||||
|
||||
This guide tells AI agents how to keep Bitvid aligned with the current product direction. Follow it whenever you touch code, content, or documentation inside this repository.
|
||||
|
||||
---
|
||||
|
||||
## 1. Release Channels: Main vs. Unstable
|
||||
|
||||
* **Main** is the production track. Anything merged here must preserve today’s UX and magnet safety guarantees. Rollbacks should be painless: keep commits atomic, avoid destructive migrations, and leave feature flags in a known-good default (`false` unless product explicitly flips them).
|
||||
* **Unstable** is our experimentation lane. Gate risky behavior behind feature flags defined in `js/constants.js` and document the toggle/rollback plan in PR descriptions.
|
||||
* **Emergency response:** If a change regresses URL-first playback or breaks magnet parsing, revert immediately and annotate the AGENTS.md changelog with remediation tips so future agents do not repeat the mistake.
|
||||
|
||||
## 2. Mission: URL‑First Playback with WebTorrent Fallback
|
||||
|
||||
* **Goal:** Always deliver smooth playback while keeping hosting costs low.
|
||||
* **Primary transport:** A hosted video URL (MP4/WebM/HLS/DASH) that the `<video>` element can stream directly.
|
||||
* **Fallback transport:** A WebTorrent magnet that includes browser‑safe trackers plus optional HTTP hints.
|
||||
* **Runtime behavior:** Call `playVideoWithFallback({ url, magnet })` (see `js/playbackUtils.js`). It probes the URL first; only when that fails should WebTorrent start.
|
||||
* **Content contract:** Bitvid posts (Nostr kind `30078`) must include a `title` and at least one of `url` or `magnet`. Prefer to publish both along with optional `thumbnail`, `description`, and `mode` fields. When mirroring to NIP‑94 (`kind 1063`), copy the hosted URL and (optionally) the magnet so other clients can discover the same asset.
|
||||
|
||||
---
|
||||
|
||||
## 3. Magnet Handling — Do’s & Don’ts
|
||||
|
||||
* **Use the helpers every time:** Always run inbound values through `safeDecodeMagnet()` before playback or normalization, and call `normalizeAndAugmentMagnet()` (see `js/magnetUtils.js`) to append `ws=` / `xs=` hints without mutating hashes.
|
||||
* **Keep magnets raw:** Persist the literal `magnet:?xt=urn:btih:...` string. Decode once, then feed that exact value to WebTorrent or storage. Never rely on re-encoding helpers that might alter casing.
|
||||
* **Never call `new URL()` on magnets:** URL constructors/`URLSearchParams` percent-encode the `xt` payload and corrupt legacy hashes. Manipulate magnets with the helper utilities or string functions that respect the raw hash.
|
||||
* **HTTP hints:** Encourage HTTPS `ws=` web seeds (file roots only) and HTTPS `xs=` pointers to `.torrent` files so fallback peers warm quickly.
|
||||
* **Tracker policy:** Browser code must ship WSS trackers only. Pull the canonical list from `js/constants.js`; do not add UDP or plaintext HTTP trackers.
|
||||
|
||||
---
|
||||
|
||||
## 4. Upload Modal Troubleshooting
|
||||
|
||||
1. **Required fields:** Validation must ensure a title exists and that either a hosted URL or a magnet (or both) is supplied. Optional `ws` / `xs` inputs should be appended only when a magnet is present.
|
||||
2. **Magnet parsing errors:** When a user pastes encoded magnets, run `safeDecodeMagnet()` before normalizing. Show inline errors if decoding fails and confirm the raw `magnet:?xt=` string survives the round trip.
|
||||
3. **URL-first promise:** After submission, confirm the resulting feed item carries `data-play-url` and `data-play-magnet` attributes so playback utilities can attempt the URL first.
|
||||
4. **Mixed-content warnings:** If the page is served over HTTPS, reject `ws=` or `xs=` hints that begin with `http://` and show guidance to upgrade to HTTPS. Document the copy in README/UX strings so operators can align messaging.
|
||||
5. **Telemetry hooks:** Keep existing analytics/logging untouched unless instructed. If you add new modal states, annotate them clearly in code comments.
|
||||
6. **Modal regressions:** If validation or helper wiring breaks in Main, disable new feature flags and ship a revert PR immediately. Note the rollback steps in AGENTS.md for posterity.
|
||||
|
||||
---
|
||||
|
||||
## 5. Manual QA Checklist
|
||||
|
||||
Run this script before shipping notable UI changes, especially around upload/playback flows. Automate when possible, but manual verification is required for releases.
|
||||
|
||||
1. **Smoke test the modal**
|
||||
* Launch the site, open the Upload modal, and confirm required-field validation (title + one of URL/magnet).
|
||||
* Submit with URL only, magnet only, and both; ensure success states are clear.
|
||||
2. **URL-first playback**
|
||||
* Publish a post with both URL and magnet. Load the card and verify the player fetches the hosted URL first (check network tab or logs).
|
||||
* Temporarily block the URL (e.g., devtools throttling or offline). Confirm playback seamlessly falls back to the magnet.
|
||||
3. **Magnet hygiene**
|
||||
* Paste an encoded magnet; ensure `safeDecodeMagnet()` returns the raw value and the final string still includes the original `xt` hash.
|
||||
* Confirm `normalizeAndAugmentMagnet()` appends `ws=`/`xs=` hints without corrupting parameters.
|
||||
4. **P2P hints**
|
||||
* Verify magnets authored through the modal include HTTPS `ws=` and optional `xs=` values when provided.
|
||||
* Ensure tracker lists come from `js/constants.js` and remain WSS-only.
|
||||
5. **Cross-browser sanity**
|
||||
* Spot-check playback in Chromium and Firefox (desktop) to ensure no console errors related to CORS, Range requests, or tracker connections.
|
||||
|
||||
Document the run in PR descriptions so QA can cross-reference results.
|
||||
|
||||
---
|
||||
|
||||
## 6. Additional Notes for Agents
|
||||
|
||||
* **Nostr interoperability:** Keep kind `30078` events as the source of truth and optionally mirror to kind `1063` so external clients see the hosted URL.
|
||||
* **Probing:** Lightweight `HEAD`/`GET` requests should back `probeUrl()` so dead URLs can be hidden or flagged without blocking the UI.
|
||||
* **Extensibility:** Future work (live streams, NIP-96 uploads, analytics) should preserve the URL-first strategy and magnet safety rules above.
|
||||
|
||||
---
|
||||
|
||||
## 7. Content Schema v3 & Playback Rules
|
||||
|
||||
* **Event payloads:** New video notes serialize as version `3` with the JSON shape:
|
||||
`{ "version": 3, "title": string, "url"?: string, "magnet"?: string, "thumbnail"?: string, "description"?: string, "mode": "live"|"dev", "isPrivate": boolean, "deleted": boolean, "videoRootId": string }`.
|
||||
* **Validation:** Every note must include a non-empty `title` plus at least one playable source (`url` or `magnet`). URL-only and magnet-only posts are both valid. Legacy v2 magnet notes stay readable.
|
||||
* **Upload UX:** The modal collects a hosted HTTPS URL and/or magnet. Enforce HTTPS for direct playback while keeping magnets optional when a URL is supplied.
|
||||
* **Playback orchestration:** `playVideoWithFallback` probes and plays the HTTPS URL first, watches for stalls/errors, and then falls back to WebTorrent. When both sources exist, pass the hosted URL through to WebTorrent as a webseed hint.
|
||||
* **Status messaging:** Update modal copy to reflect whether playback is direct or via P2P so regressions surface quickly during QA.
|
||||
|
||||
**End of AGENTS.md**
|
||||
@@ -26,11 +26,25 @@
|
||||
1. **Visit the Site**: Navigate to the live instance of **bitvid** (e.g., `[https://bitvid.network](https://bitvid.network)`).
|
||||
2. **Login with Nostr**:
|
||||
- Use a compatible Nostr browser extension or manually input your public key.
|
||||
3. **Upload Videos**:
|
||||
- Provide a title, magnet link, and optional thumbnail or description.
|
||||
- Toggle "Private" for encrypted listings.
|
||||
4. **Stream Videos**:
|
||||
- Play videos directly in the browser using WebTorrent technology.
|
||||
|
||||
### Post a video
|
||||
|
||||
The upload modal enforces **Title + (URL or Magnet)**. Hosted URLs are strongly recommended so the player can start instantly, and you may also add a magnet for resilience.
|
||||
|
||||
- **Title**: Required. Matches the in-app validation copy.
|
||||
- **Hosted URL (recommended)**: Supply an HTTPS MP4/WebM/HLS/DASH asset. This is the primary playback path.
|
||||
- **Magnet (optional but encouraged)**: Paste the literal `magnet:?xt=urn:btih:...` string. The form decodes it with `safeDecodeMagnet()` to prevent hash corruption. Never wrap magnets in `new URL()`—store them raw or decode then pass directly to the helpers.
|
||||
- **Web seeds (`ws=`)**: HTTPS only. Point to a file root (e.g., `https://cdn.example.com/video/`). Mixed-content (`http://`) hints are rejected just like the modal message explains.
|
||||
- **Additional sources (`xs=`)**: Recommend adding an HTTPS `.torrent` link so WebTorrent peers can bootstrap faster.
|
||||
- **Trackers**: Bitvid’s browser client only connects to WSS trackers shipped in `js/constants.js`. Do not add UDP or plaintext HTTP trackers to published magnets.
|
||||
- **Private toggle**: Encrypts the listing for invited viewers.
|
||||
|
||||
### How playback works
|
||||
|
||||
1. **URL-first**: `playVideoWithFallback({ url, magnet })` attempts the hosted URL immediately. Healthy URLs deliver the full experience without touching P2P resources.
|
||||
2. **WebTorrent fallback**: If the URL probe fails or returns an error status, Bitvid falls back to WebTorrent using the raw magnet. The helpers append HTTPS `ws=`/`xs=` hints so peers seed quickly.
|
||||
3. **Safety checks**: Magnets are decoded with `safeDecodeMagnet()` and normalized via `normalizeAndAugmentMagnet()` before reaching WebTorrent. Trackers remain WSS-only to satisfy browser constraints.
|
||||
4. **Operator playbook**: If a deployment causes playback regressions, flip the relevant feature flags back to their default values in `js/constants.js` and redeploy. Capture the rollback steps in AGENTS.md and the PR description so the Main channel stays stable.
|
||||
|
||||
---
|
||||
|
||||
@@ -59,14 +73,39 @@ To run **bitvid** locally:
|
||||
```
|
||||
|
||||
3. Open the site in your browser:
|
||||
```
|
||||
http://localhost:8000
|
||||
```
|
||||
```
|
||||
http://localhost:8000
|
||||
```
|
||||
|
||||
### CSS build pipeline
|
||||
|
||||
Tailwind utilities are generated from `css/tailwind.source.css` using the build
|
||||
script below. Run this whenever you add or remove classes in HTML or JavaScript
|
||||
so the purged output stays in sync:
|
||||
|
||||
```bash
|
||||
npm install # first run only
|
||||
npm run build:css
|
||||
```
|
||||
|
||||
The command compiles Tailwind with `tailwind.config.cjs`, runs it through the
|
||||
PostCSS pipeline defined in `postcss.config.cjs` (for autoprefixing), and emits
|
||||
the purged, minified stylesheet at `css/tailwind.generated.css`. Commit the
|
||||
regenerated file alongside any template changes so deployments pick up the
|
||||
latest styles.
|
||||
|
||||
### Configuration
|
||||
|
||||
- **`config/instance-config.js`**:
|
||||
- Central place for instance-specific values like the Super Admin npub and the
|
||||
default whitelist-only mode setting. Update the documented exports here when
|
||||
preparing a new deployment.
|
||||
- **`config.js`**:
|
||||
- Toggle `isDevMode` for development (`true`) or production (`false`).
|
||||
- **`js/constants.js`**:
|
||||
- Source for browser-safe tracker lists and feature flags that govern WebTorrent behavior.
|
||||
- **Magnet helpers**:
|
||||
- Use `safeDecodeMagnet()` and `normalizeAndAugmentMagnet()` from `js/magnetUtils.js` to preserve hashes and add `ws=` / `xs=` hints safely.
|
||||
|
||||
### Adding Features
|
||||
|
||||
@@ -101,6 +140,21 @@ To run **bitvid** locally:
|
||||
- Follow the [MIT License](https://opensource.org/licenses/MIT).
|
||||
- Use clear, concise commit messages.
|
||||
- Respect the existing coding style and architecture.
|
||||
- Run the manual QA script (see below) and note results in PR descriptions for changes that affect upload or playback.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
Use the manual QA checklist before releases or when altering upload/playback flows:
|
||||
|
||||
1. Open the Upload modal, confirm validation (title plus URL or magnet), and test submissions for URL-only, magnet-only, and combined entries.
|
||||
2. Publish a post with both URL and magnet, verify the player streams the hosted URL, then simulate a URL failure and confirm WebTorrent playback.
|
||||
3. Paste encoded magnets to ensure `safeDecodeMagnet()` returns the raw string and `normalizeAndAugmentMagnet()` adds `ws=` / `xs=` hints without corruption.
|
||||
4. Confirm magnets include HTTPS `ws=` / optional `xs=` hints and use the WSS tracker list from `js/constants.js`.
|
||||
5. Spot-check Chromium and Firefox for console warnings (CORS, Range requests, tracker connectivity).
|
||||
|
||||
See [`docs/qa.md`](docs/qa.md) for the copy/paste-friendly checklist we share with QA.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<circle cx="5" cy="12" r="2" fill="#ffffff" />
|
||||
<circle cx="12" cy="12" r="2" fill="#ffffff" />
|
||||
<circle cx="19" cy="12" r="2" fill="#ffffff" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 263 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="white"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 263 B |
@@ -33,7 +33,13 @@
|
||||
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title></title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Explore Bitvid release notes, roadmap updates, and community highlights across the decentralized video network."
|
||||
/>
|
||||
<meta name="robots" content="index,follow" />
|
||||
<title>Bitvid Blog</title>
|
||||
<script src="./js/tracking.js" defer></script>
|
||||
<script type="module" crossorigin>
|
||||
var pv = Object.defineProperty;
|
||||
var gv = (e, t, n) =>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Application Form</title>
|
||||
<!-- Include Tailwind CSS -->
|
||||
<link href="css/tailwind.min.css" rel="stylesheet" />
|
||||
<link href="css/tailwind.generated.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body class="bg-gray-900 text-gray-100">
|
||||
<!-- Application Form Modal -->
|
||||
|
||||
+14
-17
@@ -20,21 +20,18 @@
|
||||
>
|
||||
<!-- The .modal-content, same classes: bg-gray-900, w-full max-w-[90%], etc. -->
|
||||
<div
|
||||
class="modal-content bg-gray-900 w-full max-w-[90%] lg:max-w-6xl my-0 rounded-lg overflow-hidden relative"
|
||||
class="modal-content bg-gray-900 w-full max-w-[90%] lg:max-w-6xl my-0 rounded-lg overflow-hidden relative flex flex-col"
|
||||
>
|
||||
<!-- Sticky top bar, if you want a top heading or 'X' button up here -->
|
||||
<div
|
||||
class="sticky top-0 bg-gradient-to-b from-black/80 to-transparent p-4 flex items-center justify-between"
|
||||
>
|
||||
class="modal-header sticky top-0 bg-gradient-to-b from-black/80 to-transparent p-4 flex items-center justify-between"
|
||||
>
|
||||
</div>
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="p-6">
|
||||
<div class="modal-body flex-1 overflow-y-auto">
|
||||
<!-- Scrollable disclaimers area -->
|
||||
<div
|
||||
class="space-y-6 text-gray-300"
|
||||
style="max-height: 70vh; overflow-y: auto"
|
||||
>
|
||||
<div class="space-y-6 text-gray-300">
|
||||
<!-- Example: Insert your disclaimers here -->
|
||||
|
||||
<div class="flex justify-center mb-8">
|
||||
@@ -114,16 +111,16 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Button at bottom -->
|
||||
<div class="mt-6">
|
||||
<button
|
||||
id="acceptDisclaimer"
|
||||
class="w-full bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-black transition-colors duration-200"
|
||||
>
|
||||
I Understand
|
||||
</button>
|
||||
</div>
|
||||
<!-- Button at bottom -->
|
||||
<div class="modal-footer">
|
||||
<button
|
||||
id="acceptDisclaimer"
|
||||
class="w-full bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-black transition-colors duration-200"
|
||||
>
|
||||
I Understand
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
<!-- components/edit-video-modal.html -->
|
||||
<div
|
||||
id="editVideoModal"
|
||||
class="fixed inset-0 z-50 hidden"
|
||||
style="background: transparent"
|
||||
>
|
||||
<div
|
||||
id="editVideoModalOverlay"
|
||||
class="absolute inset-0 z-10"
|
||||
style="
|
||||
background-color: rgba(0, 0, 0, 0.9);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
"
|
||||
></div>
|
||||
|
||||
<div
|
||||
class="relative modal-container h-full w-full flex items-start md:items-center justify-center overflow-y-auto z-20"
|
||||
>
|
||||
<div
|
||||
class="modal-content bg-gray-900 w-full max-w-[90%] lg:max-w-4xl my-0 rounded-lg overflow-y-auto relative"
|
||||
style="max-height: 90vh"
|
||||
>
|
||||
<div
|
||||
class="sticky top-0 bg-gradient-to-b from-black/80 to-transparent transition-transform duration-150 p-4 flex items-center justify-between"
|
||||
>
|
||||
<h2 class="text-xl font-bold text-white">Edit Video Note</h2>
|
||||
<button
|
||||
id="closeEditVideoModal"
|
||||
class="flex items-center justify-center w-10 h-10 rounded-full bg-black/50 hover:bg-black/70 transition-all duration-200 backdrop-blur focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-black focus:ring-blue-500"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="w-6 h-6 text-gray-300"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="p-6 space-y-6">
|
||||
<p class="text-sm text-gray-400">
|
||||
Fields that already have values are locked. Click <strong>Edit field</strong> to make changes.
|
||||
</p>
|
||||
|
||||
<form id="editVideoForm" class="space-y-5">
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoTitle" class="block text-sm font-medium text-gray-200">
|
||||
Title
|
||||
</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
type="text"
|
||||
id="editVideoTitle"
|
||||
class="flex-1 rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="Video title"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editVideoTitle"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoUrl" class="block text-sm font-medium text-gray-200">
|
||||
Hosted video URL (https)
|
||||
</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
type="url"
|
||||
id="editVideoUrl"
|
||||
class="flex-1 rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="https://cdn.example.com/video.mp4"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editVideoUrl"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoWs" class="block text-sm font-medium text-gray-200">
|
||||
Web seed (ws=)
|
||||
</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
type="url"
|
||||
id="editVideoWs"
|
||||
class="flex-1 rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="https://cdn.example.com/video.mp4"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editVideoWs"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoXs" class="block text-sm font-medium text-gray-200">
|
||||
.torrent URL (xs=)
|
||||
</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
type="url"
|
||||
id="editVideoXs"
|
||||
class="flex-1 rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="https://cdn.example.com/video.torrent"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editVideoXs"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoMagnet" class="block text-sm font-medium text-gray-200">
|
||||
Magnet link
|
||||
</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
type="text"
|
||||
id="editVideoMagnet"
|
||||
class="flex-1 rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="magnet:?xt=urn:btih:..."
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editVideoMagnet"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoThumbnail" class="block text-sm font-medium text-gray-200">
|
||||
Thumbnail URL
|
||||
</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
type="url"
|
||||
id="editVideoThumbnail"
|
||||
class="flex-1 rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="https://cdn.example.com/preview.jpg"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editVideoThumbnail"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editVideoDescription" class="block text-sm font-medium text-gray-200">
|
||||
Description
|
||||
</label>
|
||||
<div class="flex flex-col gap-2">
|
||||
<textarea
|
||||
id="editVideoDescription"
|
||||
rows="4"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="What is this video about?"
|
||||
></textarea>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button self-start hidden"
|
||||
data-edit-target="editVideoDescription"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for="editEnableComments" class="block text-sm font-medium text-gray-200">
|
||||
Enable comments
|
||||
</label>
|
||||
<div
|
||||
class="flex flex-col gap-2 rounded-md border border-gray-800 bg-black/30 p-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="editEnableComments"
|
||||
class="h-5 w-5 rounded border-gray-600 bg-gray-800 text-blue-500 focus:ring-blue-500"
|
||||
/>
|
||||
<span class="text-sm text-gray-300">
|
||||
Allow replies once comment threads are available.
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-field-button hidden"
|
||||
data-edit-target="editEnableComments"
|
||||
>
|
||||
Edit field
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:justify-end">
|
||||
<button
|
||||
type="button"
|
||||
id="cancelEditVideo"
|
||||
class="w-full sm:w-auto px-4 py-2 rounded-md bg-gray-800 text-gray-200 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-900 focus:ring-gray-500"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
id="submitEditVideo"
|
||||
class="w-full sm:w-auto px-4 py-2 rounded-md bg-blue-600 text-white hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-900 focus:ring-blue-500"
|
||||
>
|
||||
Save changes
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -112,16 +112,19 @@
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #3b82f6;
|
||||
background-color: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
/* Custom Scrollbar styling for Firefox */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #3b82f6 transparent;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
|
||||
}
|
||||
</style>
|
||||
<!-- Load nostr‑tools v2.10.4 -->
|
||||
|
||||
@@ -112,16 +112,19 @@
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #3b82f6;
|
||||
background-color: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
/* Custom Scrollbar styling for Firefox */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #3b82f6 transparent;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
|
||||
}
|
||||
</style>
|
||||
<!-- Load nostr‑tools v2.10.4 -->
|
||||
|
||||
@@ -105,16 +105,19 @@
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #3b82f6;
|
||||
background-color: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
/* Custom Scrollbar styling for Firefox */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #3b82f6 transparent;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
|
||||
}
|
||||
</style>
|
||||
<!-- Load nostr‑tools v2.10.4 -->
|
||||
|
||||
@@ -119,16 +119,19 @@
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #3b82f6;
|
||||
background-color: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
/* Custom Scrollbar styling for Firefox */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #3b82f6 transparent;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
|
||||
}
|
||||
</style>
|
||||
<!-- Load nostr‑tools v2.10.4 -->
|
||||
|
||||
@@ -112,15 +112,18 @@
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #3b82f6;
|
||||
background-color: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #3b82f6 transparent;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
|
||||
}
|
||||
</style>
|
||||
<!-- Load nostr‑tools v2.10.4 -->
|
||||
|
||||
+286
-16
@@ -2,6 +2,10 @@
|
||||
<div
|
||||
id="profileModal"
|
||||
class="fixed inset-0 z-50 hidden"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="profileModalTitle"
|
||||
tabindex="-1"
|
||||
style="background: transparent"
|
||||
>
|
||||
<!-- Overlay Layer with dark background and blur -->
|
||||
@@ -27,7 +31,7 @@
|
||||
<div
|
||||
class="sticky top-0 bg-gradient-to-b from-black/80 to-transparent p-4 flex items-center justify-between"
|
||||
>
|
||||
<h2 class="text-xl font-bold text-white">Profile</h2>
|
||||
<h2 id="profileModalTitle" class="text-xl font-bold text-white">Profile</h2>
|
||||
<button
|
||||
id="closeProfileModal"
|
||||
class="flex items-center justify-center w-10 h-10 rounded-full bg-black/50 hover:bg-black/70 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-black focus:ring-blue-500"
|
||||
@@ -50,28 +54,294 @@
|
||||
</div>
|
||||
|
||||
<!-- Modal Body -->
|
||||
<div class="p-6 flex-1 text-gray-200 space-y-4">
|
||||
<div class="flex items-center space-x-4">
|
||||
<img
|
||||
id="profileModalAvatar"
|
||||
src="assets/svg/default-profile.svg"
|
||||
alt="Profile"
|
||||
class="w-16 h-16 object-cover rounded-full"
|
||||
/>
|
||||
<p id="profileModalName" class="text-lg font-semibold truncate">
|
||||
Loading...
|
||||
</p>
|
||||
<div class="p-6 flex-1 overflow-hidden">
|
||||
<div class="flex flex-col lg:flex-row gap-6 h-full">
|
||||
<!-- Left navigation column -->
|
||||
<nav
|
||||
class="flex lg:flex-col gap-2 flex-shrink-0"
|
||||
aria-label="Profile sections"
|
||||
>
|
||||
<button
|
||||
id="profileNavAccount"
|
||||
type="button"
|
||||
class="profile-nav-button px-4 py-2 rounded-md text-sm font-medium text-white bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
aria-controls="profilePaneAccount"
|
||||
aria-selected="true"
|
||||
>
|
||||
Account
|
||||
</button>
|
||||
<button
|
||||
id="profileNavRelays"
|
||||
type="button"
|
||||
class="profile-nav-button px-4 py-2 rounded-md text-sm font-medium text-gray-400 hover:text-white hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
aria-controls="profilePaneRelays"
|
||||
aria-selected="false"
|
||||
>
|
||||
Relays
|
||||
</button>
|
||||
<button
|
||||
id="profileNavBlocked"
|
||||
type="button"
|
||||
class="profile-nav-button px-4 py-2 rounded-md text-sm font-medium text-gray-400 hover:text-white hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
aria-controls="profilePaneBlocked"
|
||||
aria-selected="false"
|
||||
>
|
||||
Blocked
|
||||
</button>
|
||||
<button
|
||||
id="profileNavAdmin"
|
||||
type="button"
|
||||
class="profile-nav-button px-4 py-2 rounded-md text-sm font-medium text-gray-400 hover:text-white hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 hidden"
|
||||
aria-controls="profilePaneAdmin"
|
||||
aria-selected="false"
|
||||
>
|
||||
Admin (Moderation)
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<!-- Right content panes -->
|
||||
<div class="flex-1 min-h-[320px] overflow-y-auto pr-1">
|
||||
<section
|
||||
id="profilePaneAccount"
|
||||
class="profile-pane space-y-6"
|
||||
role="tabpanel"
|
||||
aria-labelledby="profileNavAccount"
|
||||
>
|
||||
<div class="flex items-center space-x-4">
|
||||
<img
|
||||
id="profileModalAvatar"
|
||||
src="assets/svg/default-profile.svg"
|
||||
alt="Profile"
|
||||
class="w-16 h-16 object-cover rounded-full"
|
||||
/>
|
||||
<p id="profileModalName" class="text-lg font-semibold truncate">
|
||||
Loading...
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
id="profileChannelLink"
|
||||
href="#"
|
||||
class="inline-flex items-center text-sm text-blue-400 hover:text-blue-300 transition-colors hidden"
|
||||
>
|
||||
View your channel
|
||||
</a>
|
||||
<p class="text-sm text-gray-400">
|
||||
Manage your account details and upcoming preferences here.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section
|
||||
id="profilePaneRelays"
|
||||
class="profile-pane hidden space-y-6"
|
||||
role="tabpanel"
|
||||
aria-labelledby="profileNavRelays"
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<p class="text-sm text-gray-400">
|
||||
Configure the relays Bitvid will use to discover and publish your videos.
|
||||
</p>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<label class="flex-1 text-sm text-gray-300" for="relayInput">
|
||||
<span class="mb-2 block font-medium">Add a relay</span>
|
||||
<input
|
||||
id="relayInput"
|
||||
type="url"
|
||||
placeholder="wss://relay.example.com"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
id="addRelayBtn"
|
||||
type="button"
|
||||
class="px-4 py-2 rounded-md bg-blue-600 text-sm font-medium text-white hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Add relay
|
||||
</button>
|
||||
<button
|
||||
id="restoreRelaysBtn"
|
||||
type="button"
|
||||
class="px-4 py-2 rounded-md bg-gray-800 text-sm font-medium text-gray-200 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Restore defaults
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ul id="relayList" class="space-y-3"></ul>
|
||||
</section>
|
||||
|
||||
<section
|
||||
id="profilePaneBlocked"
|
||||
class="profile-pane hidden space-y-4"
|
||||
role="tabpanel"
|
||||
aria-labelledby="profileNavBlocked"
|
||||
>
|
||||
<p class="text-sm text-gray-400">
|
||||
Creators you block are hidden from your BitVid experience. This
|
||||
list is private to your account.
|
||||
</p>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<label class="flex-1 text-sm text-gray-300" for="blockedInput">
|
||||
<span class="mb-2 block font-medium">Creator npub</span>
|
||||
<input
|
||||
id="blockedInput"
|
||||
type="text"
|
||||
inputmode="text"
|
||||
autocomplete="off"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="npub1..."
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
id="addBlockedBtn"
|
||||
type="button"
|
||||
class="px-4 py-2 rounded-md bg-blue-600 text-sm font-medium text-white hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Block creator
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
id="blockedEmpty"
|
||||
class="rounded-lg border border-dashed border-gray-700 p-6 text-center text-sm text-gray-400"
|
||||
>
|
||||
You haven’t blocked any creators yet.
|
||||
</div>
|
||||
<ul id="blockedList" class="space-y-3"></ul>
|
||||
</section>
|
||||
<section
|
||||
id="profilePaneAdmin"
|
||||
class="profile-pane hidden space-y-6"
|
||||
role="tabpanel"
|
||||
aria-labelledby="profileNavAdmin"
|
||||
>
|
||||
<div class="space-y-2">
|
||||
<h3 class="text-lg font-semibold text-white">Platform moderation</h3>
|
||||
<p class="text-sm text-gray-400">
|
||||
Manage BitVid’s moderator roles and creator allow/block lists. Changes apply instantly across the app.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div id="adminModeratorsSection" class="space-y-4 hidden" aria-hidden="true">
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h4 class="text-base font-semibold text-white">Moderators</h4>
|
||||
<p class="text-xs uppercase tracking-wide text-gray-400">
|
||||
Super Admin only
|
||||
</p>
|
||||
</div>
|
||||
<p class="text-sm text-gray-400">
|
||||
Moderators can edit the whitelist and blacklist but cannot manage other moderators or whitelist mode.
|
||||
</p>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<label class="flex-1 text-sm text-gray-300" for="adminModeratorInput">
|
||||
<span class="mb-2 block font-medium">Moderator npub</span>
|
||||
<input
|
||||
id="adminModeratorInput"
|
||||
type="text"
|
||||
inputmode="text"
|
||||
autocomplete="off"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="npub1..."
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
id="adminAddModeratorBtn"
|
||||
type="button"
|
||||
class="px-4 py-2 rounded-md bg-blue-600 text-sm font-medium text-white hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Add moderator
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
id="adminModeratorsEmpty"
|
||||
class="rounded-lg border border-dashed border-gray-700 p-4 text-center text-sm text-gray-400"
|
||||
>
|
||||
No moderators configured yet.
|
||||
</div>
|
||||
<ul id="adminModeratorList" class="space-y-3"></ul>
|
||||
</div>
|
||||
|
||||
<div id="adminWhitelistSection" class="space-y-4">
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h4 class="text-base font-semibold text-white">Whitelist</h4>
|
||||
</div>
|
||||
<p class="text-sm text-gray-400">
|
||||
Creators listed here remain visible when whitelist mode is enabled. Adding someone removes them from the blacklist.
|
||||
</p>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<label class="flex-1 text-sm text-gray-300" for="adminWhitelistInput">
|
||||
<span class="mb-2 block font-medium">Creator npub</span>
|
||||
<input
|
||||
id="adminWhitelistInput"
|
||||
type="text"
|
||||
inputmode="text"
|
||||
autocomplete="off"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="npub1..."
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
id="adminAddWhitelistBtn"
|
||||
type="button"
|
||||
class="px-4 py-2 rounded-md bg-blue-600 text-sm font-medium text-white hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Add to whitelist
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
id="adminWhitelistEmpty"
|
||||
class="rounded-lg border border-dashed border-gray-700 p-4 text-center text-sm text-gray-400"
|
||||
>
|
||||
No whitelisted creators yet.
|
||||
</div>
|
||||
<ul id="adminWhitelistList" class="space-y-3"></ul>
|
||||
</div>
|
||||
|
||||
<div id="adminBlacklistSection" class="space-y-4">
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h4 class="text-base font-semibold text-white">Blacklist</h4>
|
||||
</div>
|
||||
<p class="text-sm text-gray-400">
|
||||
Creators on the blacklist are hidden from BitVid everywhere. Adding someone removes them from the whitelist.
|
||||
</p>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<label class="flex-1 text-sm text-gray-300" for="adminBlacklistInput">
|
||||
<span class="mb-2 block font-medium">Creator npub</span>
|
||||
<input
|
||||
id="adminBlacklistInput"
|
||||
type="text"
|
||||
inputmode="text"
|
||||
autocomplete="off"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="npub1..."
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
id="adminAddBlacklistBtn"
|
||||
type="button"
|
||||
class="px-4 py-2 rounded-md bg-blue-600 text-sm font-medium text-white hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Add to blacklist
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
id="adminBlacklistEmpty"
|
||||
class="rounded-lg border border-dashed border-gray-700 p-4 text-center text-sm text-gray-400"
|
||||
>
|
||||
No blacklisted creators yet.
|
||||
</div>
|
||||
<ul id="adminBlacklistList" class="space-y-3"></ul>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-sm text-gray-400">
|
||||
Some future profile details or settings could go here.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Modal Footer -->
|
||||
<div class="p-4 border-t border-gray-700 flex items-center justify-end">
|
||||
<button
|
||||
id="profileLogoutBtn"
|
||||
class="bg-red-500 text-white px-4 py-2 rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
|
||||
class="bg-red-500 text-white px-4 py-2 rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<!-- components/revert-video-modal.html -->
|
||||
<div
|
||||
id="revertVideoModal"
|
||||
class="fixed inset-0 z-50 hidden"
|
||||
style="background: transparent"
|
||||
>
|
||||
<div
|
||||
id="revertVideoModalOverlay"
|
||||
class="absolute inset-0 z-10"
|
||||
style="
|
||||
background-color: rgba(0, 0, 0, 0.9);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
"
|
||||
></div>
|
||||
|
||||
<div
|
||||
class="relative modal-container h-full w-full flex items-start md:items-center justify-center overflow-y-auto z-20"
|
||||
>
|
||||
<div
|
||||
class="modal-content bg-gray-900 w-full max-w-[95%] lg:max-w-5xl my-0 rounded-lg overflow-hidden relative"
|
||||
style="max-height: 92vh"
|
||||
>
|
||||
<div
|
||||
class="sticky top-0 bg-gradient-to-b from-black/80 to-transparent transition-transform duration-150 p-4 flex items-center justify-between"
|
||||
>
|
||||
<div class="flex flex-col">
|
||||
<h2 id="revertModalTitle" class="text-xl font-bold text-white">
|
||||
Revert Video Note
|
||||
</h2>
|
||||
<p id="revertModalSubtitle" class="text-xs text-gray-400">
|
||||
Review previous versions before restoring an older state.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
id="closeRevertVideoModal"
|
||||
class="flex items-center justify-center w-10 h-10 rounded-full bg-black/50 hover:bg-black/70 transition-all duration-200 backdrop-blur focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-black focus:ring-blue-500"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="w-6 h-6 text-gray-300"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="p-6 space-y-6 overflow-y-auto" style="max-height: calc(92vh - 4rem)">
|
||||
<div class="rounded-md border border-gray-700 bg-gray-800/60 p-4 text-sm text-gray-300">
|
||||
<p>
|
||||
Selecting an older version will mark any newer edits as reverted.
|
||||
The previous revision will become the active note on the relays.
|
||||
</p>
|
||||
<p class="mt-2 text-xs text-gray-400">
|
||||
Versions are grouped by their <code class="px-1 py-0.5 bg-gray-900/60 rounded border border-gray-700 text-[0.7rem]">d</code>
|
||||
tag or shared <code class="px-1 py-0.5 bg-gray-900/60 rounded border border-gray-700 text-[0.7rem]">videoRootId</code>. This ensures legacy
|
||||
clients see consistent history when multiple edits were published.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-[minmax(240px,280px)_1fr]">
|
||||
<aside class="space-y-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-sm font-semibold text-gray-200">Revision history</h3>
|
||||
<span
|
||||
id="revertHistoryCount"
|
||||
class="rounded-full bg-gray-800 px-2 py-0.5 text-xs text-gray-400"
|
||||
></span>
|
||||
</div>
|
||||
<div
|
||||
id="revertVersionsList"
|
||||
class="space-y-2 overflow-y-auto pr-1"
|
||||
style="max-height: 48vh"
|
||||
></div>
|
||||
</aside>
|
||||
|
||||
<section
|
||||
id="revertVersionDetails"
|
||||
class="rounded-lg border border-gray-800 bg-gray-900/70 p-4 text-sm text-gray-200"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div id="revertVersionPlaceholder" class="flex h-full items-center justify-center text-center text-gray-500">
|
||||
Select an earlier revision to inspect its metadata.
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<p
|
||||
id="revertSelectionStatus"
|
||||
class="text-xs text-gray-400"
|
||||
></p>
|
||||
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:justify-end">
|
||||
<button
|
||||
type="button"
|
||||
id="cancelRevertVideo"
|
||||
class="w-full sm:w-auto px-4 py-2 rounded-md bg-gray-800 text-gray-200 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-900 focus:ring-gray-500"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
id="confirmRevertVideo"
|
||||
class="w-full sm:w-auto px-4 py-2 rounded-md bg-red-600 text-white hover:bg-red-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-900 focus:ring-red-500 disabled:opacity-60 disabled:cursor-not-allowed"
|
||||
disabled
|
||||
>
|
||||
Revert to selected version
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+186
-180
@@ -1,6 +1,11 @@
|
||||
<!--
|
||||
Sidebar fades in once when hydrated on the client. js/index.js removes the
|
||||
helper classes after the initial animation to avoid flashes each time we
|
||||
re-render navigation links.
|
||||
-->
|
||||
<aside
|
||||
id="sidebar"
|
||||
class="bg-gray-900 text-white transition-transform duration-300 ease-in-out fixed top-0 left-0 w-64 h-screen overflow-y-auto"
|
||||
class="bg-gray-900 text-white transition-transform duration-300 ease-in-out fixed top-0 left-0 w-64 h-screen overflow-y-auto fade-in fade-in-delay-100"
|
||||
>
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- Top Navigation Links -->
|
||||
@@ -45,178 +50,182 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mobile Dropdown Button for Footer Links -->
|
||||
<!-- Added p-4 around the button for spacing, and styling consistent with top links -->
|
||||
<div class="md:hidden p-4">
|
||||
<button
|
||||
id="footerDropdownButton"
|
||||
class="flex items-center w-full py-2 px-4 bg-gray-800 hover:bg-gray-700 text-sm font-semibold text-gray-100 rounded shadow-md focus:outline-none transition-colors duration-200"
|
||||
>
|
||||
<!-- Arrow on the left side -->
|
||||
<svg
|
||||
id="footerDropdownIcon"
|
||||
class="w-4 h-4 mr-2 transform transition-transform duration-300"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
<span id="footerDropdownText">More</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Footer Links Container -->
|
||||
<!-- On mobile: hidden by default; on desktop: visible and pushed to the bottom -->
|
||||
<div id="footerLinksContainer" class="hidden md:block md:mt-auto">
|
||||
<hr class="border-gray-700" />
|
||||
<!-- Footer Links Toggle -->
|
||||
<div class="md:mt-auto">
|
||||
<div class="p-4">
|
||||
<nav class="space-y-2 text-sm opacity-70">
|
||||
<a
|
||||
href="#view=about"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
<button
|
||||
id="footerDropdownButton"
|
||||
type="button"
|
||||
class="flex items-center w-full py-2 px-4 bg-gray-800 hover:bg-gray-700 text-sm font-semibold text-gray-100 rounded shadow-md focus:outline-none transition-colors duration-200"
|
||||
aria-expanded="false"
|
||||
aria-controls="footerLinksContainer"
|
||||
>
|
||||
<!-- Arrow on the left side -->
|
||||
<svg
|
||||
id="footerDropdownIcon"
|
||||
class="w-4 h-4 mr-2 transform transition-transform duration-300"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/about-icon.svg"
|
||||
alt="About"
|
||||
class="w-5 h-5 mr-3"
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
<span class="sidebar-text">About</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=community-guidelines"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/guidelines-icon.svg"
|
||||
alt="Guidelines"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Guidelines</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=getting-started"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/getting-started-icon.svg"
|
||||
alt="Getting Started"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Getting Started</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=roadmap"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/roadmap-icon.svg"
|
||||
alt="Roadmap"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Roadmap</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=blog"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/blog-icon.svg"
|
||||
alt="Blog"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Blog</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://primal.net/p/npub13yarr7j6vjqjjkahd63dmr27curypehx45ucue286ac7sft27y0srnpmpe"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/nostr-icon.svg"
|
||||
alt="Nostr"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Nostr</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/PR0M3TH3AN/bitvid"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/github-icon.svg"
|
||||
alt="GitHub"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">GitHub</span>
|
||||
</a>
|
||||
<a
|
||||
href="torrent/beacon.html"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/beacon-icon.svg"
|
||||
alt="βeacon"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">βeacon</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://beta.bitvid.network/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/beta-icon.svg"
|
||||
alt="Beta"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Beta</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=links"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/links-icon.svg"
|
||||
alt="Links"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Links</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=ipns"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/ipns-icon.svg"
|
||||
alt="IPNS"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">IPNS</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://bitvid.network/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img src="assets/svg/dns-icon.svg" alt="DNS" class="w-5 h-5 mr-3" />
|
||||
<span class="sidebar-text">DNS</span>
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
</svg>
|
||||
<span id="footerDropdownText">More</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Footer Links Container -->
|
||||
<div id="footerLinksContainer" class="hidden">
|
||||
<hr class="border-gray-700" />
|
||||
<div class="p-4">
|
||||
<nav class="space-y-2 text-sm opacity-70">
|
||||
<a
|
||||
href="#view=about"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/about-icon.svg"
|
||||
alt="About"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">About</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=community-guidelines"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/guidelines-icon.svg"
|
||||
alt="Guidelines"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Guidelines</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=getting-started"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/getting-started-icon.svg"
|
||||
alt="Getting Started"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Getting Started</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=roadmap"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/roadmap-icon.svg"
|
||||
alt="Roadmap"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Roadmap</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=blog"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/blog-icon.svg"
|
||||
alt="Blog"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Blog</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://primal.net/p/npub13yarr7j6vjqjjkahd63dmr27curypehx45ucue286ac7sft27y0srnpmpe"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/nostr-icon.svg"
|
||||
alt="Nostr"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Nostr</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/PR0M3TH3AN/bitvid"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/github-icon.svg"
|
||||
alt="GitHub"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">GitHub</span>
|
||||
</a>
|
||||
<a
|
||||
href="torrent/beacon.html"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/beacon-icon.svg"
|
||||
alt="βeacon"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">βeacon</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://beta.bitvid.network/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/beta-icon.svg"
|
||||
alt="Beta"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Beta</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=links"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/links-icon.svg"
|
||||
alt="Links"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">Links</span>
|
||||
</a>
|
||||
<a
|
||||
href="#view=ipns"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/ipns-icon.svg"
|
||||
alt="IPNS"
|
||||
class="w-5 h-5 mr-3"
|
||||
/>
|
||||
<span class="sidebar-text">IPNS</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://bitvid.network/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center hover:bg-gray-800 px-4 py-2 rounded"
|
||||
>
|
||||
<img src="assets/svg/dns-icon.svg" alt="DNS" class="w-5 h-5 mr-3" />
|
||||
<span class="sidebar-text">DNS</span>
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -228,18 +237,15 @@
|
||||
if (btn && footerLinks) {
|
||||
btn.addEventListener("click", function () {
|
||||
footerLinks.classList.toggle("hidden");
|
||||
var isHidden = footerLinks.classList.contains("hidden");
|
||||
btn.setAttribute("aria-expanded", String(!isHidden));
|
||||
var icon = document.getElementById("footerDropdownIcon");
|
||||
var textSpan = document.getElementById("footerDropdownText");
|
||||
if (footerLinks.classList.contains("hidden")) {
|
||||
textSpan.textContent = "More";
|
||||
if (icon) {
|
||||
icon.classList.remove("rotate-180");
|
||||
}
|
||||
} else {
|
||||
textSpan.textContent = "Less";
|
||||
if (icon) {
|
||||
icon.classList.add("rotate-180");
|
||||
}
|
||||
if (textSpan) {
|
||||
textSpan.textContent = isHidden ? "More" : "Less";
|
||||
}
|
||||
if (icon) {
|
||||
icon.classList.toggle("rotate-180", !isHidden);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
class="relative modal-container h-full w-full flex items-start md:items-center justify-center overflow-y-auto z-20"
|
||||
>
|
||||
<div
|
||||
class="modal-content bg-gray-900 w-full max-w-[90%] lg:max-w-6xl my-0 rounded-lg overflow-hidden relative"
|
||||
class="modal-content bg-gray-900 w-full max-w-[90%] lg:max-w-6xl my-0 rounded-lg overflow-y-auto relative"
|
||||
style="max-height: 90vh"
|
||||
>
|
||||
<!-- Top Bar (similar to video-modal) -->
|
||||
<div
|
||||
class="sticky top-0 bg-gradient-to-b from-black/80 to-transparent transition-transform duration-300 p-4 flex items-center justify-between"
|
||||
class="sticky top-0 bg-gradient-to-b from-black/80 to-transparent transition-transform duration-150 p-4 flex items-center justify-between"
|
||||
>
|
||||
<h2 class="text-xl font-bold text-white">Share a Video</h2>
|
||||
<button
|
||||
@@ -50,8 +50,37 @@
|
||||
</div>
|
||||
|
||||
<!-- Form Content -->
|
||||
<div class="p-6 space-y-4">
|
||||
<form id="uploadForm" class="space-y-4">
|
||||
<div class="p-6 space-y-6">
|
||||
<div class="flex justify-center">
|
||||
<div
|
||||
class="inline-flex items-center rounded-full bg-gray-800/80 p-1 text-sm"
|
||||
role="group"
|
||||
aria-label="Upload mode selector"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="upload-mode-toggle flex-1 rounded-full px-4 py-2 font-medium text-gray-300 transition-colors hover:bg-gray-700/70 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 focus-visible:ring-offset-gray-900"
|
||||
data-upload-mode="custom"
|
||||
aria-pressed="true"
|
||||
>
|
||||
Custom
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="upload-mode-toggle flex-1 rounded-full px-4 py-2 font-medium text-gray-300 transition-colors hover:bg-gray-700/70 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 focus-visible:ring-offset-gray-900"
|
||||
data-upload-mode="cloudflare"
|
||||
aria-pressed="false"
|
||||
>
|
||||
Cloudflare
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="customUploadSection">
|
||||
<form id="uploadForm" class="space-y-4">
|
||||
<p class="text-sm text-gray-400">
|
||||
Share a title plus either a hosted video URL or a magnet link. Providing both helps Bitvid fall back gracefully.
|
||||
</p>
|
||||
<div>
|
||||
<label
|
||||
for="uploadTitle"
|
||||
@@ -66,20 +95,58 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Hosted video URL -->
|
||||
<div class="form-group">
|
||||
<label
|
||||
for="uploadUrl"
|
||||
class="block text-sm font-medium text-gray-200"
|
||||
>Hosted video URL (https)</label
|
||||
>
|
||||
<input
|
||||
id="uploadUrl"
|
||||
type="url"
|
||||
class="mt-1 block w-full rounded-md border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="https://cdn.example.com/video.mp4"
|
||||
/>
|
||||
<small class="mt-1 block text-xs text-gray-400"
|
||||
>Optional but preferred. We will play this first and fall back to
|
||||
P2P.</small
|
||||
>
|
||||
</div>
|
||||
|
||||
<!-- Optional: seed bootstraps for magnet -->
|
||||
<div class="grid grid-cols-1 gap-3 mb-2 text-xs">
|
||||
<input
|
||||
id="uploadWs"
|
||||
type="url"
|
||||
class="w-full p-2 rounded"
|
||||
placeholder="Web seed (ws=) e.g., https://cdn.example.com/video.mp4"
|
||||
>
|
||||
<input
|
||||
id="uploadXs"
|
||||
type="url"
|
||||
class="w-full p-2 rounded"
|
||||
placeholder=".torrent URL (xs=) e.g., https://cdn.example.com/video.torrent"
|
||||
>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
for="uploadMagnet"
|
||||
class="block text-sm font-medium text-gray-200"
|
||||
>Magnet Link</label
|
||||
>Magnet link (optional if URL provided)</label
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
id="uploadMagnet"
|
||||
required
|
||||
class="mt-1 block w-full rounded-md border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
placeholder="magnet:?xt=urn:btih:..."
|
||||
class="mt-1 block w-full rounded-md border border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-400">
|
||||
Provide a hosted URL for instant playback. Add a magnet for P2P
|
||||
cost control.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
for="uploadThumbnail"
|
||||
@@ -105,6 +172,23 @@
|
||||
class="mt-1 block w-full rounded-md border-gray-700 bg-gray-800 text-gray-100 focus:border-blue-500 focus:ring-blue-500"
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-3 rounded-md border border-gray-800 bg-black/30 p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="uploadEnableComments"
|
||||
class="mt-1 h-5 w-5 rounded border-gray-600 bg-gray-800 text-blue-500 focus:ring-blue-500"
|
||||
checked
|
||||
/>
|
||||
<div>
|
||||
<label for="uploadEnableComments" class="text-sm font-medium text-gray-200"
|
||||
>Enable comments</label
|
||||
>
|
||||
<p class="mt-1 text-xs text-gray-400">
|
||||
Keep this on to let viewers discuss the video once comment threads launch.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<!--
|
||||
<div class="flex items-center space-x-2">
|
||||
<input
|
||||
@@ -124,6 +208,300 @@
|
||||
Publish
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="cloudflareUploadSection" class="hidden">
|
||||
<div class="space-y-8">
|
||||
<p class="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">
|
||||
This feature is experimental and may not be working correctly.
|
||||
</p>
|
||||
<section class="rounded-lg border border-gray-800 bg-gray-900/60 p-5">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h3 class="text-lg font-semibold text-gray-100">
|
||||
Cloudflare R2 credentials
|
||||
</h3>
|
||||
<span class="text-xs uppercase tracking-wide text-gray-500">
|
||||
stored locally
|
||||
</span>
|
||||
</div>
|
||||
<p class="mb-4 text-sm text-gray-400">
|
||||
Paste your Cloudflare R2 API credentials. We keep them in your
|
||||
browser so uploads happen client-side.
|
||||
</p>
|
||||
<form id="cloudflareSettingsForm" class="space-y-4">
|
||||
<div class="grid gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<label for="r2AccountId" class="block text-sm font-medium text-gray-200"
|
||||
>Account ID</label
|
||||
>
|
||||
<input
|
||||
id="r2AccountId"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="r2AccessKeyId" class="block text-sm font-medium text-gray-200"
|
||||
>S3 Access Key ID</label
|
||||
>
|
||||
<input
|
||||
id="r2AccessKeyId"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="AKIA..."
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="r2SecretAccessKey" class="block text-sm font-medium text-gray-200"
|
||||
>S3 Secret Access Key</label
|
||||
>
|
||||
<input
|
||||
id="r2SecretAccessKey"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="border-t border-gray-800 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
id="cloudflareAdvancedToggle"
|
||||
class="flex items-center gap-2 text-sm font-medium text-gray-300 transition-colors hover:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900"
|
||||
aria-expanded="false"
|
||||
aria-controls="cloudflareAdvancedFields"
|
||||
>
|
||||
<svg
|
||||
id="cloudflareAdvancedToggleIcon"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-4 w-4 text-gray-300 transition-transform duration-150 transform"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
<span id="cloudflareAdvancedToggleLabel">Show advanced options</span>
|
||||
</button>
|
||||
<div
|
||||
id="cloudflareAdvancedFields"
|
||||
class="mt-3 space-y-4 hidden"
|
||||
>
|
||||
<div>
|
||||
<label for="r2ApiToken" class="block text-sm font-medium text-gray-200"
|
||||
>Cloudflare API Token (optional)</label
|
||||
>
|
||||
<input
|
||||
id="r2ApiToken"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="Token with Workers R2 Storage Write"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">
|
||||
Used to create buckets, configure CORS, and attach domains automatically.
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<label for="r2ZoneId" class="block text-sm font-medium text-gray-200"
|
||||
>Zone ID (optional)</label
|
||||
>
|
||||
<input
|
||||
id="r2ZoneId"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">
|
||||
Required when you want us to attach a custom domain on your behalf.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="r2BaseDomain" class="block text-sm font-medium text-gray-200"
|
||||
>Base domain (optional)</label
|
||||
>
|
||||
<input
|
||||
id="r2BaseDomain"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="cdn.example.com"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">
|
||||
We'll attach <code class="rounded bg-gray-800 px-1 py-0.5">npub.<baseDomain></code>.
|
||||
Leave blank to use the managed <code class="rounded bg-gray-800 px-1 py-0.5">*.r2.dev</code> domain.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded-md bg-blue-500 px-4 py-2 text-sm font-semibold text-white transition hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
Save settings
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
id="cloudflareClearSettings"
|
||||
class="rounded-md border border-gray-600 px-4 py-2 text-sm font-semibold text-gray-200 transition hover:border-gray-500 hover:text-white focus:outline-none focus:ring-2 focus:ring-gray-500"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
<span
|
||||
id="cloudflareSettingsStatus"
|
||||
class="text-xs text-gray-400"
|
||||
role="status"
|
||||
></span>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="rounded-lg border border-gray-800 bg-gray-900/60 p-5">
|
||||
<div class="mb-4">
|
||||
<h3 class="text-lg font-semibold text-gray-100">
|
||||
Upload & publish
|
||||
</h3>
|
||||
<p class="mt-1 text-sm text-gray-400">
|
||||
Choose a file, we will upload it to R2, fill the hosted URL,
|
||||
and publish your note automatically.
|
||||
</p>
|
||||
</div>
|
||||
<form id="cloudflareUploadForm" class="space-y-4">
|
||||
<div>
|
||||
<label for="cloudflareTitle" class="block text-sm font-medium text-gray-200"
|
||||
>Title</label
|
||||
>
|
||||
<input
|
||||
id="cloudflareTitle"
|
||||
type="text"
|
||||
required
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="cloudflareDescription" class="block text-sm font-medium text-gray-200"
|
||||
>Description (optional)</label
|
||||
>
|
||||
<textarea
|
||||
id="cloudflareDescription"
|
||||
rows="3"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
></textarea>
|
||||
</div>
|
||||
<div class="grid gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<label for="cloudflareThumbnail" class="block text-sm font-medium text-gray-200"
|
||||
>Thumbnail URL (optional)</label
|
||||
>
|
||||
<input
|
||||
id="cloudflareThumbnail"
|
||||
type="url"
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="cloudflareMagnet" class="block text-sm font-medium text-gray-200"
|
||||
>Magnet link (optional)</label
|
||||
>
|
||||
<input
|
||||
id="cloudflareMagnet"
|
||||
type="text"
|
||||
placeholder="magnet:?xt=urn:btih:..."
|
||||
class="mt-1 w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid gap-3 md:grid-cols-2">
|
||||
<input
|
||||
id="cloudflareWs"
|
||||
type="url"
|
||||
placeholder="Web seed (ws=)"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<input
|
||||
id="cloudflareXs"
|
||||
type="url"
|
||||
placeholder=".torrent URL (xs=)"
|
||||
class="w-full rounded-md border border-gray-700 bg-gray-800 px-3 py-2 text-gray-100 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 rounded-md border border-gray-800 bg-black/30 p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="cloudflareEnableComments"
|
||||
class="mt-1 h-5 w-5 rounded border-gray-600 bg-gray-800 text-blue-500 focus:ring-blue-500"
|
||||
checked
|
||||
/>
|
||||
<div>
|
||||
<label for="cloudflareEnableComments" class="text-sm font-medium text-gray-200"
|
||||
>Enable comments</label
|
||||
>
|
||||
<p class="mt-1 text-xs text-gray-400">
|
||||
Publish with comments switched on. Toggle off to quietly disable replies on this video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="cloudflareFile" class="block text-sm font-medium text-gray-200"
|
||||
>Video or HLS file</label
|
||||
>
|
||||
<input
|
||||
id="cloudflareFile"
|
||||
type="file"
|
||||
accept="video/*,.m3u8,.ts,.mp4,.webm,.mov,.mkv,.mpg,.mpeg"
|
||||
class="mt-1 w-full rounded-md border border-dashed border-gray-600 bg-gray-900 px-3 py-4 text-sm text-gray-300 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
required
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">
|
||||
We use multipart uploads with automatic bucket creation.
|
||||
Large files are supported.
|
||||
</p>
|
||||
</div>
|
||||
<div class="rounded-md border border-gray-800 bg-black/40 p-3 text-xs text-gray-400">
|
||||
<p>
|
||||
<strong class="text-gray-200">Bucket preview:</strong>
|
||||
<span id="cloudflareBucketPreview" class="ml-1">We'll show your
|
||||
bucket and public domain after setup.</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
id="cloudflareProgressBar"
|
||||
class="hidden h-2 w-full overflow-hidden rounded-full bg-gray-800"
|
||||
>
|
||||
<div
|
||||
id="cloudflareProgressFill"
|
||||
class="h-full w-0 bg-blue-500 transition-all duration-150"
|
||||
></div>
|
||||
</div>
|
||||
<p
|
||||
id="cloudflareUploadStatus"
|
||||
class="text-xs text-gray-400"
|
||||
role="status"
|
||||
></p>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
id="cloudflareUploadButton"
|
||||
class="w-full rounded-md bg-blue-500 px-4 py-2 text-sm font-semibold text-white transition hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:cursor-not-allowed disabled:bg-blue-900"
|
||||
>
|
||||
Upload to R2 & publish
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+89
-22
@@ -1,15 +1,11 @@
|
||||
<!-- components/video-modal.html -->
|
||||
<div id="playerModal" class="fixed inset-0 bg-black/90 z-50 hidden">
|
||||
<div
|
||||
class="modal-container h-full w-full flex items-start justify-center overflow-y-auto"
|
||||
>
|
||||
<div
|
||||
class="modal-content bg-gray-900 w-full max-w-[90%] lg:max-w-6xl my-0 rounded-lg overflow-hidden relative"
|
||||
>
|
||||
<div id="playerModal" class="player-modal hidden">
|
||||
<div class="player-modal__container">
|
||||
<div class="player-modal__content">
|
||||
<!-- Navigation bar - sliding at top -->
|
||||
<div
|
||||
id="modalNav"
|
||||
class="sticky top-0 z-60 bg-gradient-to-b from-black/80 to-transparent transition-transform duration-300"
|
||||
class="modal-nav sticky top-0 z-60 transition-transform duration-150"
|
||||
>
|
||||
<div class="flex items-center px-6 py-4">
|
||||
<button
|
||||
@@ -31,19 +27,7 @@
|
||||
<path d="M15 18l-6-6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="video-container w-full bg-black">
|
||||
<video id="modalVideo" class="w-full aspect-video" controls></video>
|
||||
</div>
|
||||
|
||||
<div class="video-info p-6">
|
||||
<!-- Title and icons row -->
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h2 id="videoTitle" class="text-2xl font-bold text-white"></h2>
|
||||
<div class="flex items-center space-x-2">
|
||||
<!-- Copy Magnet Button (circular) -->
|
||||
<div class="modal-actions">
|
||||
<button id="copyMagnetBtn" class="icon-button">
|
||||
<img
|
||||
src="assets/svg/copy-magnet.svg"
|
||||
@@ -51,7 +35,18 @@
|
||||
class="icon-image"
|
||||
/>
|
||||
</button>
|
||||
<!-- Share Button (circular) -->
|
||||
<button
|
||||
id="modalZapBtn"
|
||||
type="button"
|
||||
class="icon-button"
|
||||
aria-label="Send a zap"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/lightning-bolt.svg"
|
||||
alt="Zap"
|
||||
class="icon-image"
|
||||
/>
|
||||
</button>
|
||||
<button id="shareBtn" class="icon-button">
|
||||
<img
|
||||
src="assets/svg/share-video.svg"
|
||||
@@ -59,8 +54,80 @@
|
||||
class="icon-image"
|
||||
/>
|
||||
</button>
|
||||
<div
|
||||
class="modal-actions__overflow"
|
||||
data-more-menu-wrapper="true"
|
||||
>
|
||||
<button
|
||||
id="modalMoreBtn"
|
||||
type="button"
|
||||
class="icon-button"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-label="More"
|
||||
data-more-dropdown="modal"
|
||||
>
|
||||
<img src="assets/svg/ellipsis.svg" alt="More" class="w-5 h-5" />
|
||||
</button>
|
||||
<div
|
||||
id="moreDropdown-modal"
|
||||
class="hidden absolute right-0 top-14 w-44 rounded-md shadow-lg bg-gray-800 ring-1 ring-black ring-opacity-5 z-50"
|
||||
role="menu"
|
||||
data-more-menu="true"
|
||||
>
|
||||
<div class="py-1">
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700"
|
||||
data-action="open-channel"
|
||||
data-context="modal"
|
||||
>
|
||||
Open channel
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700"
|
||||
data-action="copy-link"
|
||||
data-context="modal"
|
||||
>
|
||||
Copy link
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white"
|
||||
data-action="blacklist-author"
|
||||
data-context="modal"
|
||||
data-blacklist-menu="true"
|
||||
>
|
||||
Blacklist creator
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white"
|
||||
data-action="block-author"
|
||||
data-context="modal"
|
||||
>
|
||||
Block creator
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700"
|
||||
data-action="report"
|
||||
data-context="modal"
|
||||
>
|
||||
Report
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="player-modal__video modal-video-shell">
|
||||
<video id="modalVideo" class="w-full aspect-video" controls></video>
|
||||
</div>
|
||||
|
||||
<div class="player-modal__info modal-info-panel">
|
||||
<!-- Title and icons row -->
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h2 id="videoTitle" class="text-2xl font-bold text-white"></h2>
|
||||
</div>
|
||||
|
||||
<!-- Video Timestamp -->
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// config/instance-config.js
|
||||
// -----------------------------------------------------------------------------
|
||||
// BitVid instance configuration
|
||||
// -----------------------------------------------------------------------------
|
||||
//
|
||||
// This file consolidates the values that operators usually customize when they
|
||||
// deploy their own BitVid instance. Update the exports below to match your
|
||||
// environment, commit the changes, and redeploy. Leaving this file in the repo
|
||||
// (instead of hidden in environment variables) makes it easy for future
|
||||
// maintainers to understand how your instance is configured.
|
||||
//
|
||||
// Each setting includes guidance about how BitVid uses the value and what
|
||||
// adjustments are safe. When in doubt, mirror the structure shown here so other
|
||||
// contributors can follow along.
|
||||
|
||||
/**
|
||||
* The primary administrator for this BitVid instance.
|
||||
*
|
||||
* BitVid treats this Nostr public key (npub) as the "Super Admin". This user
|
||||
* cannot be removed from moderator lists, and only they can promote new
|
||||
* moderators or toggle whitelist-only mode. Replace the string below with the
|
||||
* npub of the account you want to act as the ultimate authority for your
|
||||
* deployment.
|
||||
*/
|
||||
export const ADMIN_SUPER_NPUB =
|
||||
"npub15jnttpymeytm80hatjqcvhhqhzrhx6gxp8pq0wn93rhnu8s9h9dsha32lx";
|
||||
|
||||
/**
|
||||
* Storage key used to persist whitelist-only mode in the browser.
|
||||
*
|
||||
* You usually do not need to change this, but the export lives here so that all
|
||||
* whitelist-related knobs are grouped together. If you do change the key, make
|
||||
* sure to migrate any previously stored values in localStorage.
|
||||
*/
|
||||
export const ADMIN_WHITELIST_MODE_STORAGE_KEY = "bitvid_admin_whitelist_mode";
|
||||
|
||||
/**
|
||||
* Whether whitelist-only mode should be enabled the first time an operator
|
||||
* loads the admin dashboard.
|
||||
*
|
||||
* Set this to `true` if you want BitVid to start with whitelist-only access and
|
||||
* require an explicit opt-out. Set to `false` to allow all creators by default.
|
||||
* Operators can still toggle the mode at runtime; this value only controls the
|
||||
* default state when no preference has been stored in localStorage yet.
|
||||
*/
|
||||
export const DEFAULT_WHITELIST_MODE_ENABLED = true;
|
||||
+3
-3
@@ -46,9 +46,9 @@
|
||||
- Add zaps to videos, profiles, and comments.
|
||||
- Create a VRR (View, Rating, and Retention) Penalty Scoring system. [Click for more details](https://github.com/PR0M3TH3AN/bitvid/blob/main/content/roadmap/07_bitvid_Enhanced_View_Rating_%26_Retention_Penalty_Scoring.md)
|
||||
- Implement visibility filtering for videos:
|
||||
- Show only videos whose magnet links have at least **one active peer online**.
|
||||
- Integrate the filtering mechanism into the video list rendering process.
|
||||
- Update the video list dynamically based on real-time peer availability. (this may not be possible)
|
||||
- Run lightweight URL-health probes so cards stay visible when the hosted playback link responds.
|
||||
- When a URL is unreachable, fall back to WebTorrent and surface items only if their magnets can stream via peers or web seeds.
|
||||
- Align the filtering logic with the player’s URL-first, WebTorrent-fallback behavior during list rendering.
|
||||
- Dynamic Home Page and Video Tracking Specification. [Click for more details](https://github.com/PR0M3TH3AN/bitvid/blob/main/content/roadmap/08_bitvid_Enhanced_Dynamic_Home_Page_%26_Video_Tracking_Specification.md)
|
||||
- Add multi-language support for content and filtration. (v4?)
|
||||
- Create a settings menu for local account preferences, including relay, adult content, theme, and language.
|
||||
|
||||
+433
-94
@@ -3,11 +3,51 @@
|
||||
--color-card: #1e293b;
|
||||
--color-primary: #fe0032;
|
||||
--color-secondary: #ff93a5;
|
||||
--color-card-critical: #3f0b13;
|
||||
--color-text: #f8fafc;
|
||||
--color-muted: #94a3b8;
|
||||
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
|
||||
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
|
||||
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
|
||||
--shadow-sm: 0 0.0625rem 0.125rem 0 rgb(0 0 0 / 0.05);
|
||||
--shadow-md: 0 0.25rem 0.375rem -0.0625rem rgb(0 0 0 / 0.1);
|
||||
--shadow-lg: 0 0.625rem 0.9375rem -0.1875rem rgb(0 0 0 / 0.1);
|
||||
--modal-motion-duration: 160ms;
|
||||
--scrollbar-width: 0.5rem;
|
||||
--scrollbar-track: rgba(255, 255, 255, 0.1);
|
||||
--scrollbar-thumb: rgba(255, 255, 255, 0.3);
|
||||
--scrollbar-thumb-hover: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
html {
|
||||
font-size: 100%;
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
html {
|
||||
font-size: 75%;
|
||||
}
|
||||
}
|
||||
|
||||
/* Global scrollbar styling */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--scrollbar-thumb) transparent;
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar {
|
||||
width: var(--scrollbar-width);
|
||||
height: var(--scrollbar-width);
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-track {
|
||||
background: var(--scrollbar-track);
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-thumb {
|
||||
background: var(--scrollbar-thumb);
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
*::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--scrollbar-thumb-hover);
|
||||
}
|
||||
|
||||
/* Core Styles */
|
||||
@@ -35,7 +75,7 @@ header img {
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1480px;
|
||||
max-width: 92.5rem;
|
||||
margin: 0 auto;
|
||||
padding: 1rem;
|
||||
}
|
||||
@@ -43,7 +83,7 @@ header img {
|
||||
/* Video Grids */
|
||||
#videoList {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr));
|
||||
gap: 2rem;
|
||||
padding: 1.5rem 0;
|
||||
}
|
||||
@@ -51,7 +91,7 @@ header img {
|
||||
/* Subscriptions grid: same pattern as #videoList */
|
||||
#subscriptionsVideoList {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr));
|
||||
gap: 2rem;
|
||||
padding: 1.5rem 0;
|
||||
}
|
||||
@@ -59,7 +99,7 @@ header img {
|
||||
/* Now also match for channelVideoList (channel profile) */
|
||||
#channelVideoList {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr));
|
||||
gap: 2rem;
|
||||
padding: 1.5rem 0;
|
||||
}
|
||||
@@ -73,8 +113,107 @@ header img {
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.video-card[data-owner-is-viewer="false"][data-url-health-state="offline"][data-stream-health-state="unhealthy"] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.video-card[data-owner-is-viewer="true"][data-url-health-state="offline"][data-stream-health-state="unhealthy"] {
|
||||
background-color: var(--color-card-critical);
|
||||
box-shadow: 0 0 0 0.0625rem rgba(239, 68, 68, 0.35), var(--shadow-md);
|
||||
}
|
||||
|
||||
.video-card[data-owner-is-viewer="true"][data-url-health-state="offline"][data-stream-health-state="unhealthy"]:hover {
|
||||
box-shadow: 0 0 0 0.0625rem rgba(239, 68, 68, 0.45), var(--shadow-lg);
|
||||
}
|
||||
|
||||
.video-card--enter {
|
||||
opacity: 0;
|
||||
animation: video-card-fade-in 220ms ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes video-card-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(0.5rem);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Thumbnails start transparent and fade in the first time they finish loading.
|
||||
`data-thumbnail-loaded` is cleared by js/index.js once the animation completes
|
||||
so re-rendering the same element later does not replay the transition and cause
|
||||
a distracting flash.
|
||||
*/
|
||||
[data-video-thumbnail][data-thumbnail-loaded="true"] {
|
||||
animation: video-thumbnail-fade-in 220ms ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes video-thumbnail-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Generic fade-in utility for chrome elements (sidebar, header controls, etc.).
|
||||
js/index.js listens for the `interface-fade-in` animation finishing and removes
|
||||
the temporary classes so that once an element has gracefully appeared it stays
|
||||
opaque even if the DOM is re-used or re-parented later.
|
||||
*/
|
||||
|
||||
.fade-in {
|
||||
opacity: 0;
|
||||
animation: interface-fade-in 280ms ease-out forwards;
|
||||
animation-delay: var(--fade-in-delay, 0ms);
|
||||
}
|
||||
|
||||
.fade-in-delay-100 {
|
||||
--fade-in-delay: 100ms;
|
||||
}
|
||||
|
||||
.fade-in-delay-200 {
|
||||
--fade-in-delay: 200ms;
|
||||
}
|
||||
|
||||
.fade-in-delay-300 {
|
||||
--fade-in-delay: 300ms;
|
||||
}
|
||||
|
||||
.fade-in-delay-400 {
|
||||
--fade-in-delay: 400ms;
|
||||
}
|
||||
|
||||
@keyframes interface-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.video-card--enter,
|
||||
.fade-in {
|
||||
opacity: 1;
|
||||
animation: none;
|
||||
}
|
||||
|
||||
[data-video-thumbnail][data-thumbnail-loaded="true"] {
|
||||
animation: none;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.video-card:hover {
|
||||
transform: translateY(-4px);
|
||||
transform: translateY(-0.25rem);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
@@ -108,21 +247,26 @@ header img {
|
||||
#playerModal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background-color: rgb(0 0 0 / 0.9); /* You can adjust opacity if needed */
|
||||
z-index: 50;
|
||||
display: none; /* Hidden by default */
|
||||
z-index: 100;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
justify-content: stretch;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background-color: #0f172a;
|
||||
color: #e2e8f0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px); /* For Safari support */
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
#nostrFormModal,
|
||||
#profileModal,
|
||||
#uploadModal {
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px); /* For Safari */
|
||||
backdrop-filter: blur(0.625rem);
|
||||
-webkit-backdrop-filter: blur(0.625rem); /* For Safari */
|
||||
}
|
||||
|
||||
/* If you ever want to show it, add ".flex" class dynamically */
|
||||
@@ -130,6 +274,82 @@ header img {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
#playerModal .player-modal__container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 100vh;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#playerModal .player-modal__content {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 100%;
|
||||
max-width: none;
|
||||
background-color: #0f172a;
|
||||
overflow: visible;
|
||||
box-shadow: none;
|
||||
animation: fadeIn var(--modal-motion-duration) ease-out;
|
||||
}
|
||||
|
||||
#playerModal .player-modal__video {
|
||||
width: 100%;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 51;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: clamp(0.75rem, 3.5vw, 2.5rem);
|
||||
background-color: var(--color-bg);
|
||||
border-bottom: 0.0625rem solid rgba(148, 163, 184, 0.18);
|
||||
}
|
||||
|
||||
#playerModal .player-modal__video video {
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
background-color: #000;
|
||||
border-radius: 0.75rem;
|
||||
display: block;
|
||||
box-shadow: 0 1.125rem 2.75rem rgba(8, 11, 30, 0.55);
|
||||
max-height: min(80vh, calc(100vw * 9 / 16));
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
#playerModal .player-modal__info {
|
||||
flex: 0 0 auto;
|
||||
padding: clamp(1.5rem, 3vw, 2.5rem);
|
||||
padding-bottom: clamp(2.5rem, 6vw, 4rem);
|
||||
background-color: var(--color-bg);
|
||||
border-top: 0.0625rem solid rgba(148, 163, 184, 0.16);
|
||||
box-shadow: inset 0 1px 0 rgba(15, 23, 42, 0.35);
|
||||
}
|
||||
|
||||
html.modal-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body.modal-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
html.modal-open,
|
||||
body.modal-open {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body.modal-open #app {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Modal Content Container */
|
||||
.modal-content {
|
||||
width: 100%;
|
||||
@@ -137,13 +357,13 @@ header img {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: #0f172a;
|
||||
animation: fadeIn 0.3s ease-in-out;
|
||||
animation: fadeIn var(--modal-motion-duration) ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
transform: translateY(1.25rem);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
@@ -151,13 +371,10 @@ header img {
|
||||
}
|
||||
}
|
||||
|
||||
/* Video Container */
|
||||
.video-container {
|
||||
width: 100%;
|
||||
background-color: black;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 51;
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.modal-content {
|
||||
animation-duration: 1ms;
|
||||
}
|
||||
}
|
||||
|
||||
/* Modal Video */
|
||||
@@ -167,33 +384,74 @@ header img {
|
||||
background-color: black;
|
||||
}
|
||||
|
||||
/* Video Info Section */
|
||||
.video-info {
|
||||
padding: 1rem;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Responsive Adjustments */
|
||||
@media (min-width: 768px) {
|
||||
#playerModal {
|
||||
padding: 2rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
max-width: 64rem;
|
||||
max-height: calc(100vh - 4rem); /* Account for padding */
|
||||
border-radius: 0.5rem;
|
||||
overflow: hidden;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.video-container {
|
||||
position: relative;
|
||||
#playerModal .player-modal__content {
|
||||
max-width: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
|
||||
#modalNav.modal-nav,
|
||||
.modal-nav {
|
||||
background-color: var(--color-bg);
|
||||
border-bottom: 0.0625rem solid rgba(148, 163, 184, 0.25);
|
||||
box-shadow: 0 0.75rem 2rem rgba(8, 11, 30, 0.45);
|
||||
}
|
||||
|
||||
.modal-nav .flex {
|
||||
position: relative;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.modal-nav .icon-button {
|
||||
background-color: rgba(30, 41, 59, 0.85);
|
||||
border: 0.0625rem solid rgba(148, 163, 184, 0.4);
|
||||
color: #f8fafc;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.modal-nav .icon-button:hover {
|
||||
background-color: rgba(51, 65, 85, 0.95);
|
||||
border-color: rgba(148, 163, 184, 0.55);
|
||||
}
|
||||
|
||||
.modal-nav .icon-button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 0.1875rem rgba(148, 163, 184, 0.45);
|
||||
}
|
||||
|
||||
#modalNav {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 60;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.modal-actions__overflow {
|
||||
position: relative;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-more-menu="true"] {
|
||||
z-index: 70;
|
||||
}
|
||||
|
||||
/* Mobile-specific styles */
|
||||
@media (max-width: 767px) {
|
||||
#playerModal {
|
||||
@@ -205,24 +463,6 @@ header img {
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom Scrollbar */
|
||||
.video-info::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.video-info::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.video-info::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.video-info::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
/* Progress Bars */
|
||||
.progress-bar {
|
||||
width: 100%;
|
||||
@@ -244,7 +484,7 @@ textarea {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
background-color: var(--color-bg);
|
||||
border: 1px solid rgb(255 255 255 / 0.1);
|
||||
border: 0.0625rem solid rgb(255 255 255 / 0.1);
|
||||
border-radius: 0.5rem;
|
||||
color: var(--color-text);
|
||||
transition: border-color 0.2s;
|
||||
@@ -254,7 +494,7 @@ input:focus,
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--color-primary);
|
||||
ring: 2px var(--color-primary);
|
||||
ring: 0.125rem var(--color-primary);
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
@@ -273,12 +513,12 @@ button:not(.icon-button) {
|
||||
|
||||
button:not(.icon-button):hover {
|
||||
background-color: var(--color-secondary);
|
||||
transform: translateY(-1px);
|
||||
transform: translateY(-0.0625rem);
|
||||
}
|
||||
|
||||
button:not(.icon-button):focus {
|
||||
outline: none;
|
||||
ring: 2px var(--color-primary);
|
||||
ring: 0.125rem var(--color-primary);
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -323,7 +563,7 @@ button:not(.icon-button):focus {
|
||||
}
|
||||
|
||||
footer {
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-top: 0.0625rem solid rgba(255, 255, 255, 0.1);
|
||||
margin-top: 4rem;
|
||||
padding-top: 2rem;
|
||||
}
|
||||
@@ -343,47 +583,39 @@ footer a:hover {
|
||||
background-color: rgb(0 0 0 / 0.9);
|
||||
z-index: 50;
|
||||
/* remove display: none; */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
#disclaimerModal.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-content {
|
||||
width: 100%;
|
||||
width: min(60rem, calc(100% - 2rem));
|
||||
max-height: min(90vh, 51.25rem);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: var(--color-bg);
|
||||
box-shadow: 0 1.5625rem 3.125rem -0.75rem rgb(0 0 0 / 0.45);
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-scroll {
|
||||
#disclaimerModal .modal-header {
|
||||
min-height: 1.5rem;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-body {
|
||||
padding: 1.5rem;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Disclaimer Modal Scrollbar */
|
||||
#disclaimerModal .modal-scroll::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-scroll::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-scroll::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-scroll::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
/* Disclaimer Modal Button Container */
|
||||
#disclaimerModal .button-container {
|
||||
padding: 1rem 1.5rem;
|
||||
#disclaimerModal .modal-footer {
|
||||
padding: 1.25rem 1.5rem 1.75rem;
|
||||
background-color: #1a2234;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-top: 0.0625rem solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
/* Responsive Adjustments for Disclaimer Modal */
|
||||
@@ -394,9 +626,14 @@ footer a:hover {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-scroll {
|
||||
#disclaimerModal .modal-body {
|
||||
padding: 2rem 2.5rem 1.5rem;
|
||||
max-height: calc(90vh - 5rem);
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-footer {
|
||||
padding: 1.5rem 2.5rem 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Mobile-specific styles for Disclaimer Modal */
|
||||
@@ -408,20 +645,34 @@ footer a:hover {
|
||||
#disclaimerModal .modal-content {
|
||||
min-height: 100vh;
|
||||
border-radius: 0;
|
||||
max-height: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-body {
|
||||
padding: 1.5rem 1.5rem 1rem;
|
||||
max-height: none;
|
||||
}
|
||||
|
||||
#disclaimerModal .modal-footer {
|
||||
padding: 1rem 1.5rem 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Override default button styles for back button */
|
||||
.back-button {
|
||||
background: rgba(0, 0, 0, 0.5) !important;
|
||||
background: rgba(15, 23, 42, 0.75) !important;
|
||||
padding: 0 !important;
|
||||
color: rgb(209 213 219) !important;
|
||||
color: rgb(226 232 240) !important;
|
||||
transform: none !important;
|
||||
border: 0.0625rem solid rgba(148, 163, 184, 0.4) !important;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.back-button:hover {
|
||||
background: rgba(0, 0, 0, 0.7) !important;
|
||||
background: rgba(51, 65, 85, 0.95) !important;
|
||||
color: white !important;
|
||||
border-color: rgba(148, 163, 184, 0.55) !important;
|
||||
}
|
||||
|
||||
/* Modal Container */
|
||||
@@ -436,9 +687,9 @@ footer a:hover {
|
||||
}
|
||||
|
||||
/* Video info cards */
|
||||
.video-info .bg-gray-800\/50 {
|
||||
.player-modal__info .bg-gray-800\/50 {
|
||||
background-color: rgb(31 41 55 / 0.5);
|
||||
backdrop-filter: blur(4px);
|
||||
backdrop-filter: blur(0.25rem);
|
||||
}
|
||||
|
||||
/* Circular Icon Buttons */
|
||||
@@ -464,7 +715,7 @@ footer a:hover {
|
||||
.icon-button:focus,
|
||||
.icon-button:active {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.6);
|
||||
box-shadow: 0 0 0 0.1875rem rgba(220, 38, 38, 0.6);
|
||||
}
|
||||
|
||||
.icon-image {
|
||||
@@ -541,3 +792,91 @@ footer a:hover {
|
||||
#sidebar hr {
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
/* Sidebar drop-up menu styling */
|
||||
.sidebar-dropup {
|
||||
display: flex;
|
||||
flex-direction: column-reverse;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.sidebar-dropup-panel {
|
||||
background-color: #1f2937; /* gray-800 */
|
||||
border: 0.0625rem solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 1.125rem 2.1875rem rgba(15, 23, 42, 0.45);
|
||||
max-height: 0;
|
||||
opacity: 0;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
transform: translateY(1rem);
|
||||
transition: max-height 0.35s ease, opacity 0.25s ease, transform 0.35s ease;
|
||||
}
|
||||
|
||||
.sidebar-dropup-panel__inner {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.sidebar-dropup-panel--expanded {
|
||||
max-height: 40rem;
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.sidebar-dropup-trigger {
|
||||
align-items: center;
|
||||
background: linear-gradient(135deg, rgba(59, 130, 246, 0.25), rgba(14, 116, 144, 0.35));
|
||||
border: 0.0625rem solid rgba(148, 163, 184, 0.35);
|
||||
border-radius: 9999px;
|
||||
color: #f8fafc;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 0.75rem 1.25rem;
|
||||
transition: box-shadow 0.2s ease, transform 0.2s ease, border-color 0.2s ease;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar-dropup-trigger:hover,
|
||||
.sidebar-dropup-trigger:focus {
|
||||
border-color: rgba(148, 163, 184, 0.6);
|
||||
box-shadow: 0 0.75rem 1.875rem rgba(37, 99, 235, 0.25);
|
||||
outline: none;
|
||||
transform: translateY(-0.0625rem);
|
||||
}
|
||||
|
||||
.sidebar-dropup-trigger__content {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
}
|
||||
.edit-field-button {
|
||||
align-items: center;
|
||||
background-color: #1f2937;
|
||||
border-radius: 0.5rem;
|
||||
color: #e2e8f0;
|
||||
display: inline-flex;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
justify-content: center;
|
||||
padding: 0.5rem 0.85rem;
|
||||
transition: background-color 0.2s ease, color 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.edit-field-button:hover,
|
||||
.edit-field-button:focus {
|
||||
background-color: #334155;
|
||||
color: #f8fafc;
|
||||
transform: translateY(-0.0625rem);
|
||||
}
|
||||
|
||||
.locked-input {
|
||||
background-color: rgba(31, 41, 55, 0.75) !important;
|
||||
border-color: rgba(55, 65, 81, 0.9) !important;
|
||||
color: #94a3b8 !important;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.locked-input:focus {
|
||||
outline: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media (min-width:640px){.\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width:768px){.\!container{max-width:768px!important}.container{max-width:768px}}@mediLine truncated
|
||||
@@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
# Bitvid Manual QA Script
|
||||
|
||||
Run this checklist before publishing releases or merging changes that touch upload or playback flows. Copy/paste the steps into QA tickets when requesting validation.
|
||||
|
||||
1. **Upload Modal Smoke Test**
|
||||
- Open the Upload modal, verify title is required, and ensure either a hosted URL or a magnet (or both) must be supplied.
|
||||
- Submit three variants: URL-only, magnet-only, and both URL + magnet. Confirm success messaging or event publication in each case.
|
||||
2. **URL-First Playback**
|
||||
- For a post with both URL and magnet, play the video and confirm the hosted URL loads first (inspect network requests or logs).
|
||||
- Simulate a dead URL (offline mode or request blocker) and confirm playback falls back to WebTorrent without breaking the UI.
|
||||
3. **Magnet Safety**
|
||||
- Paste an encoded magnet and confirm `safeDecodeMagnet()` outputs the raw string before playback.
|
||||
- Ensure `normalizeAndAugmentMagnet()` adds provided `ws=` / `xs=` hints while keeping the original `xt` hash intact.
|
||||
4. **P2P Hints & Trackers**
|
||||
- Confirm magnets generated through the modal include HTTPS `ws=` seeds and optional HTTPS `xs=` torrent URLs when supplied.
|
||||
- Check that tracker arrays originate from `js/constants.js` and only include WSS endpoints.
|
||||
5. **Cross-Browser Verification**
|
||||
- Spot-check Chromium and Firefox (desktop) for console warnings about CORS, Range requests, or tracker connectivity.
|
||||
- Optionally validate on mobile Safari/Chrome if the change targets mobile UX.
|
||||
|
||||
Document findings (pass/fail notes plus relevant screenshots or logs) so they can be attached to release or PR notes.
|
||||
+41
-10
@@ -5,6 +5,12 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>bitvid | Decentralized Video Sharing</title>
|
||||
|
||||
<meta
|
||||
name="description"
|
||||
content="Bitvid is a decentralized video hub that prioritizes URL-first playback with WebTorrent fallback so your audience can stream reliably."
|
||||
/>
|
||||
<meta name="robots" content="index,follow" />
|
||||
|
||||
<!-- Open Graph Meta Tags -->
|
||||
<meta property="og:title" content="BitVid - Decentralized Video Sharing" />
|
||||
<meta
|
||||
@@ -39,7 +45,8 @@
|
||||
<meta name="theme-color" content="#0f172a" />
|
||||
|
||||
<!-- Styles -->
|
||||
<link href="css/tailwind.min.css" rel="stylesheet" />
|
||||
<script src="js/tracking.js" defer></script>
|
||||
<link href="css/tailwind.generated.css" rel="stylesheet" />
|
||||
<link href="css/style.css" rel="stylesheet" />
|
||||
<link href="css/markdown.css" rel="stylesheet" />
|
||||
</head>
|
||||
@@ -58,14 +65,25 @@
|
||||
md:ml-64 ensures content is shifted on desktop so the pinned sidebar doesn't overlap.
|
||||
On mobile, we also toggle .sidebar-open to shift the entire content.
|
||||
-->
|
||||
<div id="app" class="md:ml-64 px-4 py-8 min-h-screen flex flex-col">
|
||||
<!--
|
||||
`fade-in` is scrubbed by js/index.js after the first animation so that
|
||||
re-rendering views does not cause the shell to flicker. Only apply it to
|
||||
elements that should animate exactly once on initial paint.
|
||||
-->
|
||||
|
||||
<div id="app" class="md:ml-64 px-4 py-8 min-h-screen flex flex-col fade-in">
|
||||
<!-- Header -->
|
||||
<header class="mb-8 flex items-center w-full">
|
||||
<!-- Mobile hamburger button (hidden on md+) -->
|
||||
<!-- New button -->
|
||||
<!--
|
||||
Mobile menu button: uses `fade-in` to match the rest of the chrome.
|
||||
The JS animation cleanup removes the helper classes once the entrance
|
||||
finishes to prevent flashes on future sidebar toggles.
|
||||
-->
|
||||
<button
|
||||
id="mobileMenuBtn"
|
||||
class="md:hidden ml-2 mr-4 flex items-center justify-center w-10 h-10 rounded-full bg-transparent hover:bg-transparent focus:outline-none focus:ring-2 focus:ring-[#0f172a] z-[60]"
|
||||
class="md:hidden ml-2 mr-4 flex items-center justify-center w-10 h-10 rounded-full bg-transparent hover:bg-transparent focus:outline-none focus:ring-2 focus:ring-[#0f172a] z-[60] fade-in"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/mobile-sidebar-menu-icon.svg"
|
||||
@@ -74,14 +92,24 @@
|
||||
/>
|
||||
</button>
|
||||
<!-- Logo -->
|
||||
<img
|
||||
src="assets/svg/bitvid-logo-light-mode.svg"
|
||||
alt="BitVid Logo"
|
||||
class="h-16"
|
||||
/>
|
||||
<!-- Logo fades in once on initial load. -->
|
||||
<a
|
||||
href="index.html"
|
||||
aria-label="Return to the bitvid home page"
|
||||
class="fade-in fade-in-delay-100"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/bitvid-logo-light-mode.svg"
|
||||
alt="BitVid Logo"
|
||||
class="h-16"
|
||||
/>
|
||||
</a>
|
||||
|
||||
<!-- Buttons on the far right -->
|
||||
<div class="ml-auto flex items-center space-x-4">
|
||||
|
||||
<!-- Header action buttons share the fade-in treatment for consistency. -->
|
||||
|
||||
<div class="ml-auto flex items-center space-x-4 fade-in fade-in-delay-200">
|
||||
<!-- Login Button -->
|
||||
<button
|
||||
id="loginButton"
|
||||
@@ -140,7 +168,10 @@
|
||||
<div id="modalContainer"></div>
|
||||
|
||||
<!-- Tagline / Slogan -->
|
||||
<div class="text-center mb-8">
|
||||
|
||||
<!-- Tagline fade matches the cards. -->
|
||||
|
||||
<div class="text-center mb-8 fade-in fade-in-delay-300">
|
||||
<h2 class="text-2xl font-bold text-gray-500 tracking-wide">
|
||||
seed. zap. subscribe.
|
||||
</h2>
|
||||
|
||||
+380
-133
@@ -1,154 +1,401 @@
|
||||
// js/accessControl.js
|
||||
|
||||
import { isDevMode, isWhitelistEnabled } from "./config.js";
|
||||
import { initialWhitelist, initialBlacklist } from "./lists.js";
|
||||
import {
|
||||
ADMIN_EDITORS_NPUBS,
|
||||
ADMIN_SUPER_NPUB,
|
||||
getWhitelistMode,
|
||||
setWhitelistMode as persistWhitelistMode,
|
||||
ADMIN_WHITELIST_MODE_STORAGE_KEY,
|
||||
} from "./config.js";
|
||||
import { loadAdminState, persistAdminState } from "./adminListStore.js";
|
||||
|
||||
function normalizeNpub(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function dedupeNpubs(values) {
|
||||
const normalized = Array.isArray(values) ? values.map(normalizeNpub) : [];
|
||||
return Array.from(
|
||||
normalized.reduce((set, npub) => {
|
||||
if (npub) {
|
||||
set.add(npub);
|
||||
}
|
||||
return set;
|
||||
}, new Set())
|
||||
);
|
||||
}
|
||||
|
||||
function isValidNpub(npub) {
|
||||
if (typeof npub !== "string") {
|
||||
return false;
|
||||
}
|
||||
const trimmed = npub.trim();
|
||||
if (!trimmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = window?.NostrTools?.nip19?.decode(trimmed);
|
||||
return decoded?.type === "npub";
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class AccessControl {
|
||||
constructor() {
|
||||
// Debug logging for initialization
|
||||
console.log("DEBUG: AccessControl constructor called");
|
||||
console.log("DEBUG: initialWhitelist from import:", initialWhitelist);
|
||||
console.log("DEBUG: typeof initialWhitelist:", typeof initialWhitelist);
|
||||
console.log("DEBUG: initialWhitelist length:", initialWhitelist.length);
|
||||
|
||||
// Initialize empty sets
|
||||
this.whitelist = new Set(initialWhitelist);
|
||||
this.blacklist = new Set(initialBlacklist.filter((x) => x)); // Filter out empty strings
|
||||
|
||||
// Debug the sets
|
||||
console.log("DEBUG: Whitelist after Set creation:", [...this.whitelist]);
|
||||
console.log("DEBUG: Blacklist after Set creation:", [...this.blacklist]);
|
||||
|
||||
// Save to localStorage
|
||||
this.saveWhitelist();
|
||||
this.saveBlacklist();
|
||||
}
|
||||
|
||||
// Rest of the class remains the same...
|
||||
loadWhitelist() {
|
||||
try {
|
||||
const stored = localStorage.getItem("bitvid_whitelist");
|
||||
return stored ? JSON.parse(stored) : [];
|
||||
} catch (error) {
|
||||
console.error("Error loading whitelist:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
loadBlacklist() {
|
||||
try {
|
||||
const stored = localStorage.getItem("bitvid_blacklist");
|
||||
return stored ? JSON.parse(stored) : [];
|
||||
} catch (error) {
|
||||
console.error("Error loading blacklist:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
saveWhitelist() {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
"bitvid_whitelist",
|
||||
JSON.stringify([...this.whitelist])
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error saving whitelist:", error);
|
||||
}
|
||||
}
|
||||
|
||||
saveBlacklist() {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
"bitvid_blacklist",
|
||||
JSON.stringify([...this.blacklist])
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error saving blacklist:", error);
|
||||
}
|
||||
}
|
||||
|
||||
addToWhitelist(npub) {
|
||||
if (!this.isValidNpub(npub)) {
|
||||
throw new Error("Invalid npub format");
|
||||
}
|
||||
this.whitelist.add(npub);
|
||||
this.saveWhitelist();
|
||||
if (isDevMode) console.log(`Added ${npub} to whitelist`);
|
||||
}
|
||||
|
||||
removeFromWhitelist(npub) {
|
||||
this.whitelist.delete(npub);
|
||||
this.saveWhitelist();
|
||||
if (isDevMode) console.log(`Removed ${npub} from whitelist`);
|
||||
}
|
||||
|
||||
addToBlacklist(npub) {
|
||||
if (!this.isValidNpub(npub)) {
|
||||
throw new Error("Invalid npub format");
|
||||
}
|
||||
this.blacklist.add(npub);
|
||||
this.saveBlacklist();
|
||||
if (isDevMode) console.log(`Added ${npub} to blacklist`);
|
||||
}
|
||||
|
||||
removeFromBlacklist(npub) {
|
||||
this.blacklist.delete(npub);
|
||||
this.saveBlacklist();
|
||||
if (isDevMode) console.log(`Removed ${npub} from blacklist`);
|
||||
}
|
||||
|
||||
isWhitelisted(npub) {
|
||||
const result = this.whitelist.has(npub);
|
||||
if (isDevMode)
|
||||
console.log(
|
||||
`Checking if ${npub} is whitelisted:`,
|
||||
result,
|
||||
"Current whitelist:",
|
||||
[...this.whitelist]
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
isBlacklisted(npub) {
|
||||
return this.blacklist.has(npub);
|
||||
}
|
||||
|
||||
canAccess(npub) {
|
||||
if (this.isBlacklisted(npub)) {
|
||||
return false;
|
||||
}
|
||||
const canAccess = !isWhitelistEnabled || this.isWhitelisted(npub);
|
||||
if (isDevMode) console.log(`Checking access for ${npub}:`, canAccess);
|
||||
return canAccess;
|
||||
}
|
||||
|
||||
filterVideos(videos) {
|
||||
return videos.filter((video) => {
|
||||
try {
|
||||
const npub = window.NostrTools.nip19.npubEncode(video.pubkey);
|
||||
return !this.isBlacklisted(npub);
|
||||
} catch (error) {
|
||||
console.error("Error filtering video:", error);
|
||||
return false;
|
||||
}
|
||||
this.editors = new Set();
|
||||
this.whitelist = new Set();
|
||||
this.blacklist = new Set();
|
||||
this.whitelistEnabled = getWhitelistMode();
|
||||
this.hasLoaded = false;
|
||||
this.lastError = null;
|
||||
this._isRefreshing = false;
|
||||
this._refreshPromise = this._performRefresh();
|
||||
this._refreshPromise.catch((error) => {
|
||||
console.error("Failed to load admin lists:", error);
|
||||
});
|
||||
}
|
||||
|
||||
isValidNpub(npub) {
|
||||
async _performRefresh() {
|
||||
if (this._isRefreshing) {
|
||||
return this._refreshPromise;
|
||||
}
|
||||
|
||||
this._isRefreshing = true;
|
||||
try {
|
||||
return npub.startsWith("npub1") && npub.length === 63;
|
||||
const state = await loadAdminState();
|
||||
const editors = Array.isArray(state?.editors) ? state.editors : [];
|
||||
const whitelist = Array.isArray(state?.whitelist)
|
||||
? state.whitelist
|
||||
: [];
|
||||
const blacklist = Array.isArray(state?.blacklist)
|
||||
? state.blacklist
|
||||
: [];
|
||||
|
||||
this.editors = new Set(
|
||||
dedupeNpubs([...ADMIN_EDITORS_NPUBS, ...editors])
|
||||
);
|
||||
const normalizedWhitelist = dedupeNpubs(whitelist);
|
||||
this.whitelist = new Set(normalizedWhitelist);
|
||||
|
||||
const blacklistDedupe = dedupeNpubs(blacklist);
|
||||
const whitelistSet = new Set(normalizedWhitelist.map(normalizeNpub));
|
||||
const adminGuardSet = new Set([
|
||||
normalizeNpub(ADMIN_SUPER_NPUB),
|
||||
...Array.from(this.editors),
|
||||
]);
|
||||
const sanitizedBlacklist = blacklistDedupe.filter((npub) => {
|
||||
const normalized = normalizeNpub(npub);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
if (whitelistSet.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
if (adminGuardSet.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
this.blacklist = new Set(sanitizedBlacklist);
|
||||
|
||||
this.whitelistEnabled = getWhitelistMode();
|
||||
this.hasLoaded = true;
|
||||
this.lastError = null;
|
||||
} catch (error) {
|
||||
return false;
|
||||
this.lastError = error;
|
||||
if (!this.hasLoaded) {
|
||||
this.editors.clear();
|
||||
this.whitelist.clear();
|
||||
this.blacklist.clear();
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
this._isRefreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
refresh() {
|
||||
const promise = this._performRefresh();
|
||||
this._refreshPromise = promise;
|
||||
promise.catch((error) => {
|
||||
console.error("Failed to refresh admin lists:", error);
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
async ensureReady() {
|
||||
try {
|
||||
await this._refreshPromise;
|
||||
} catch (error) {
|
||||
if (!this.hasLoaded) {
|
||||
await this.refresh();
|
||||
await this._refreshPromise;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
whitelistMode() {
|
||||
return this.whitelistEnabled;
|
||||
}
|
||||
|
||||
isSuperAdmin(npub) {
|
||||
const normalized = normalizeNpub(npub);
|
||||
return normalized ? normalized === ADMIN_SUPER_NPUB : false;
|
||||
}
|
||||
|
||||
isAdminEditor(npub) {
|
||||
const normalized = normalizeNpub(npub);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
if (this.isSuperAdmin(normalized)) {
|
||||
return true;
|
||||
}
|
||||
return this.editors.has(normalized);
|
||||
}
|
||||
|
||||
canEditAdminLists(npub) {
|
||||
return this.isAdminEditor(npub);
|
||||
}
|
||||
|
||||
getWhitelist() {
|
||||
return [...this.whitelist];
|
||||
return Array.from(this.whitelist);
|
||||
}
|
||||
|
||||
getBlacklist() {
|
||||
return [...this.blacklist];
|
||||
return Array.from(this.blacklist);
|
||||
}
|
||||
|
||||
getEditors() {
|
||||
return Array.from(this.editors);
|
||||
}
|
||||
|
||||
async addModerator(requestorNpub, moderatorNpub) {
|
||||
if (!this.isSuperAdmin(requestorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
if (!isValidNpub(moderatorNpub)) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(moderatorNpub);
|
||||
if (!normalized || normalized === ADMIN_SUPER_NPUB) {
|
||||
return { ok: false, error: "immutable" };
|
||||
}
|
||||
|
||||
const nextEditors = dedupeNpubs([...this.getEditors(), normalized]);
|
||||
|
||||
try {
|
||||
await persistAdminState(requestorNpub, { editors: nextEditors });
|
||||
await this.refresh();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error?.code || "storage-error" };
|
||||
}
|
||||
}
|
||||
|
||||
async removeModerator(requestorNpub, moderatorNpub) {
|
||||
if (!this.isSuperAdmin(requestorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(moderatorNpub);
|
||||
if (!normalized || normalized === ADMIN_SUPER_NPUB) {
|
||||
return { ok: false, error: "immutable" };
|
||||
}
|
||||
const nextEditors = this.getEditors().filter((value) => value !== normalized);
|
||||
|
||||
try {
|
||||
await persistAdminState(requestorNpub, { editors: nextEditors });
|
||||
await this.refresh();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error?.code || "storage-error" };
|
||||
}
|
||||
}
|
||||
|
||||
async addToWhitelist(actorNpub, targetNpub) {
|
||||
if (!this.canEditAdminLists(actorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
if (!isValidNpub(targetNpub)) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(targetNpub);
|
||||
if (!normalized) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
|
||||
const nextWhitelist = dedupeNpubs([...this.getWhitelist(), normalized]);
|
||||
const nextBlacklist = this.getBlacklist().filter(
|
||||
(value) => value !== normalized
|
||||
);
|
||||
|
||||
try {
|
||||
await persistAdminState(actorNpub, {
|
||||
whitelist: nextWhitelist,
|
||||
blacklist: nextBlacklist,
|
||||
});
|
||||
await this.refresh();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error?.code || "storage-error" };
|
||||
}
|
||||
}
|
||||
|
||||
async removeFromWhitelist(actorNpub, targetNpub) {
|
||||
if (!this.canEditAdminLists(actorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(targetNpub);
|
||||
if (!normalized) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
const nextWhitelist = this.getWhitelist().filter(
|
||||
(value) => value !== normalized
|
||||
);
|
||||
|
||||
try {
|
||||
await persistAdminState(actorNpub, { whitelist: nextWhitelist });
|
||||
await this.refresh();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error?.code || "storage-error" };
|
||||
}
|
||||
}
|
||||
|
||||
async addToBlacklist(actorNpub, targetNpub) {
|
||||
if (!this.canEditAdminLists(actorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
if (!isValidNpub(targetNpub)) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(targetNpub);
|
||||
if (!normalized) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
|
||||
const normalizedActor = normalizeNpub(actorNpub);
|
||||
if (normalizedActor && normalized === normalizedActor) {
|
||||
return { ok: false, error: "self" };
|
||||
}
|
||||
|
||||
if (this.isSuperAdmin(normalized) || this.isAdminEditor(normalized)) {
|
||||
return { ok: false, error: "immutable" };
|
||||
}
|
||||
|
||||
const nextBlacklist = dedupeNpubs([...this.getBlacklist(), normalized]);
|
||||
const nextWhitelist = this.getWhitelist().filter(
|
||||
(value) => value !== normalized
|
||||
);
|
||||
|
||||
try {
|
||||
await persistAdminState(actorNpub, {
|
||||
blacklist: nextBlacklist,
|
||||
whitelist: nextWhitelist,
|
||||
});
|
||||
await this.refresh();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error?.code || "storage-error" };
|
||||
}
|
||||
}
|
||||
|
||||
async removeFromBlacklist(actorNpub, targetNpub) {
|
||||
if (!this.canEditAdminLists(actorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(targetNpub);
|
||||
if (!normalized) {
|
||||
return { ok: false, error: "invalid npub" };
|
||||
}
|
||||
const nextBlacklist = this.getBlacklist().filter(
|
||||
(value) => value !== normalized
|
||||
);
|
||||
|
||||
try {
|
||||
await persistAdminState(actorNpub, { blacklist: nextBlacklist });
|
||||
await this.refresh();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: error?.code || "storage-error" };
|
||||
}
|
||||
}
|
||||
|
||||
setWhitelistMode(actorNpub, enabled) {
|
||||
if (!this.isSuperAdmin(actorNpub)) {
|
||||
return { ok: false, error: "forbidden" };
|
||||
}
|
||||
persistWhitelistMode(!!enabled);
|
||||
this.whitelistEnabled = !!enabled;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
isBlacklisted(npub) {
|
||||
const normalized = normalizeNpub(npub);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
if (this.whitelist.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
return this.blacklist.has(normalized);
|
||||
}
|
||||
|
||||
canAccess(candidate) {
|
||||
let npub = "";
|
||||
|
||||
if (typeof candidate === "string") {
|
||||
npub = candidate;
|
||||
} else if (candidate && typeof candidate === "object") {
|
||||
if (typeof candidate.npub === "string") {
|
||||
npub = candidate.npub;
|
||||
} else if (typeof candidate.pubkey === "string") {
|
||||
try {
|
||||
npub = window.NostrTools.nip19.npubEncode(candidate.pubkey);
|
||||
} catch (error) {
|
||||
npub = candidate.pubkey;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const normalized = normalizeNpub(npub);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.isAdminEditor(normalized)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.whitelist.has(normalized)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.blacklist.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.whitelistEnabled && !this.whitelist.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export const accessControl = new AccessControl();
|
||||
export {
|
||||
ADMIN_WHITELIST_MODE_STORAGE_KEY,
|
||||
normalizeNpub,
|
||||
isValidNpub,
|
||||
};
|
||||
@@ -0,0 +1,558 @@
|
||||
// js/adminListStore.js
|
||||
|
||||
import {
|
||||
ADMIN_LIST_MODE,
|
||||
ADMIN_LIST_NAMESPACE,
|
||||
ADMIN_SUPER_NPUB,
|
||||
ADMIN_EDITORS_NPUBS,
|
||||
isDevMode,
|
||||
} from "./config.js";
|
||||
import { nostrClient } from "./nostr.js";
|
||||
|
||||
const LIST_IDENTIFIERS = {
|
||||
editors: "editors",
|
||||
whitelist: "whitelist",
|
||||
blacklist: "blacklist",
|
||||
};
|
||||
|
||||
const LEGACY_STORAGE_KEYS = {
|
||||
editors: "bitvid_admin_editors",
|
||||
whitelist: "bitvid_admin_whitelist",
|
||||
whitelistLegacy: "bitvid_whitelist",
|
||||
blacklist: "bitvid_admin_blacklist",
|
||||
blacklistLegacy: "bitvid_blacklist",
|
||||
};
|
||||
|
||||
const PUBLISH_TIMEOUT_MS = 7000;
|
||||
|
||||
function createError(code, message, cause) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
if (cause) {
|
||||
error.cause = cause;
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
function normalizeNpub(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function dedupeNpubs(values) {
|
||||
const normalized = Array.isArray(values) ? values.map(normalizeNpub) : [];
|
||||
return Array.from(
|
||||
normalized.reduce((set, npub) => {
|
||||
if (npub) {
|
||||
set.add(npub);
|
||||
}
|
||||
return set;
|
||||
}, new Set())
|
||||
);
|
||||
}
|
||||
|
||||
function canDecodeNpub() {
|
||||
return !!(
|
||||
typeof window !== "undefined" &&
|
||||
window?.NostrTools?.nip19 &&
|
||||
typeof window.NostrTools.nip19.decode === "function"
|
||||
);
|
||||
}
|
||||
|
||||
function isLikelyNpub(value) {
|
||||
if (typeof value !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!canDecodeNpub()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = window.NostrTools.nip19.decode(trimmed);
|
||||
return decoded?.type === "npub";
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeNpubList(values) {
|
||||
return dedupeNpubs(values).filter(isLikelyNpub);
|
||||
}
|
||||
|
||||
function sanitizeAdminState(state = {}) {
|
||||
const sanitizedEditors = sanitizeNpubList(state.editors || []);
|
||||
const sanitizedWhitelist = sanitizeNpubList(state.whitelist || []);
|
||||
const whitelistSet = new Set(sanitizedWhitelist.map(normalizeNpub));
|
||||
|
||||
const adminGuardSet = new Set([
|
||||
normalizeNpub(ADMIN_SUPER_NPUB),
|
||||
...ADMIN_EDITORS_NPUBS.map(normalizeNpub),
|
||||
...sanitizedEditors.map(normalizeNpub),
|
||||
]);
|
||||
|
||||
const sanitizedBlacklist = sanitizeNpubList(state.blacklist || []).filter(
|
||||
(npub) => {
|
||||
const normalized = normalizeNpub(npub);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
if (whitelistSet.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
if (adminGuardSet.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
editors: sanitizedEditors,
|
||||
whitelist: sanitizedWhitelist,
|
||||
blacklist: sanitizedBlacklist,
|
||||
};
|
||||
}
|
||||
|
||||
function hasAnyEntries(state = {}) {
|
||||
return Boolean(
|
||||
(Array.isArray(state.editors) && state.editors.length) ||
|
||||
(Array.isArray(state.whitelist) && state.whitelist.length) ||
|
||||
(Array.isArray(state.blacklist) && state.blacklist.length)
|
||||
);
|
||||
}
|
||||
|
||||
function readJsonListFromStorage(key) {
|
||||
if (typeof localStorage === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : null;
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn(`[adminListStore] Failed to parse legacy list for ${key}:`, error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function loadLegacyAdminState() {
|
||||
const editors = readJsonListFromStorage(LEGACY_STORAGE_KEYS.editors) || [];
|
||||
const whitelist =
|
||||
readJsonListFromStorage(LEGACY_STORAGE_KEYS.whitelist) ||
|
||||
readJsonListFromStorage(LEGACY_STORAGE_KEYS.whitelistLegacy) ||
|
||||
[];
|
||||
const blacklist =
|
||||
readJsonListFromStorage(LEGACY_STORAGE_KEYS.blacklist) ||
|
||||
readJsonListFromStorage(LEGACY_STORAGE_KEYS.blacklistLegacy) ||
|
||||
[];
|
||||
|
||||
const sanitized = sanitizeAdminState({ editors, whitelist, blacklist });
|
||||
return hasAnyEntries(sanitized) ? sanitized : null;
|
||||
}
|
||||
|
||||
function clearLegacyStorageFor(listKey) {
|
||||
if (typeof localStorage === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
const keyGroups = {
|
||||
editors: [LEGACY_STORAGE_KEYS.editors],
|
||||
whitelist: [
|
||||
LEGACY_STORAGE_KEYS.whitelist,
|
||||
LEGACY_STORAGE_KEYS.whitelistLegacy,
|
||||
],
|
||||
blacklist: [
|
||||
LEGACY_STORAGE_KEYS.blacklist,
|
||||
LEGACY_STORAGE_KEYS.blacklistLegacy,
|
||||
],
|
||||
};
|
||||
|
||||
const keys = keyGroups[listKey];
|
||||
if (!Array.isArray(keys)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of keys) {
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn(`[adminListStore] Failed to clear legacy storage for ${key}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ensureNostrReady() {
|
||||
if (!nostrClient || !nostrClient.pool) {
|
||||
throw createError(
|
||||
"nostr-unavailable",
|
||||
"Nostr relay pool is not initialized."
|
||||
);
|
||||
}
|
||||
|
||||
const relays = Array.isArray(nostrClient.relays) ? nostrClient.relays : [];
|
||||
if (!relays.length) {
|
||||
throw createError("nostr-unavailable", "No Nostr relays configured.");
|
||||
}
|
||||
|
||||
return relays;
|
||||
}
|
||||
|
||||
function decodeNpubToHex(npub) {
|
||||
const trimmed = normalizeNpub(npub);
|
||||
if (!trimmed) {
|
||||
throw createError("invalid npub", "Empty npub provided.");
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = window?.NostrTools?.nip19?.decode(trimmed);
|
||||
if (decoded?.type !== "npub" || !decoded?.data) {
|
||||
throw new Error("Invalid npub format");
|
||||
}
|
||||
return typeof decoded.data === "string"
|
||||
? decoded.data
|
||||
: decoded.data?.pubkey || "";
|
||||
} catch (error) {
|
||||
throw createError("invalid npub", "Unable to decode npub.", error);
|
||||
}
|
||||
}
|
||||
|
||||
function encodeHexToNpub(hex) {
|
||||
try {
|
||||
return window?.NostrTools?.nip19?.npubEncode(hex) || "";
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn("Failed to encode hex pubkey to npub:", error);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function extractNpubsFromEvent(event) {
|
||||
if (!event || !Array.isArray(event.tags)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const hexKeys = event.tags
|
||||
.filter((tag) => Array.isArray(tag) && tag[0] === "p" && tag[1])
|
||||
.map((tag) => tag[1]);
|
||||
|
||||
const npubs = hexKeys
|
||||
.map((hex) => encodeHexToNpub(hex))
|
||||
.filter((npub) => typeof npub === "string" && npub);
|
||||
|
||||
return dedupeNpubs(npubs);
|
||||
}
|
||||
|
||||
async function loadNostrList(identifier) {
|
||||
const relays = ensureNostrReady();
|
||||
const dTagValue = `${ADMIN_LIST_NAMESPACE}:${identifier}`;
|
||||
const filter = {
|
||||
kinds: [30000],
|
||||
"#d": [dTagValue],
|
||||
limit: 50,
|
||||
};
|
||||
|
||||
let events = [];
|
||||
try {
|
||||
const combined = await nostrClient.pool.list(relays, [filter]);
|
||||
if (Array.isArray(combined)) {
|
||||
events = combined;
|
||||
}
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn(
|
||||
`[adminListStore] Combined relay fetch failed for ${identifier}:`,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!events.length) {
|
||||
const perRelay = await Promise.all(
|
||||
relays.map(async (url) => {
|
||||
try {
|
||||
const result = await nostrClient.pool.list([url], [filter]);
|
||||
return Array.isArray(result) ? result : [];
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn(
|
||||
`[adminListStore] Relay fetch failed for ${identifier} on ${url}:`,
|
||||
error
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
})
|
||||
);
|
||||
events = perRelay.flat();
|
||||
}
|
||||
|
||||
if (!events.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const newest = events.reduce((latest, event) => {
|
||||
if (!latest) {
|
||||
return event;
|
||||
}
|
||||
if (event.created_at === latest.created_at) {
|
||||
return event.id > latest.id ? event : latest;
|
||||
}
|
||||
return event.created_at > latest.created_at ? event : latest;
|
||||
}, null);
|
||||
|
||||
return extractNpubsFromEvent(newest);
|
||||
}
|
||||
|
||||
async function loadNostrState() {
|
||||
const [editors, whitelist, blacklist] = await Promise.all([
|
||||
loadNostrList(LIST_IDENTIFIERS.editors),
|
||||
loadNostrList(LIST_IDENTIFIERS.whitelist),
|
||||
loadNostrList(LIST_IDENTIFIERS.blacklist),
|
||||
]);
|
||||
|
||||
return sanitizeAdminState({ editors, whitelist, blacklist });
|
||||
}
|
||||
|
||||
function buildListEvent(listKey, npubs, actorHex) {
|
||||
const identifier = LIST_IDENTIFIERS[listKey];
|
||||
const dTagValue = `${ADMIN_LIST_NAMESPACE}:${identifier}`;
|
||||
|
||||
const hexPubkeys = Array.from(
|
||||
new Set(npubs.map((npub) => {
|
||||
try {
|
||||
return decodeNpubToHex(npub);
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn(
|
||||
`[adminListStore] Failed to decode npub while publishing ${listKey}:`,
|
||||
error
|
||||
);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}).filter((hex) => !!hex))
|
||||
);
|
||||
|
||||
if (listKey === "whitelist" || listKey === "editors") {
|
||||
try {
|
||||
const superHex = decodeNpubToHex(ADMIN_SUPER_NPUB);
|
||||
if (superHex && !hexPubkeys.includes(superHex)) {
|
||||
hexPubkeys.push(superHex);
|
||||
}
|
||||
} catch (error) {
|
||||
if (isDevMode) {
|
||||
console.warn("Failed to ensure super admin presence:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const tags = [["d", dTagValue]];
|
||||
hexPubkeys.forEach((hex) => {
|
||||
tags.push(["p", hex]);
|
||||
});
|
||||
|
||||
return {
|
||||
kind: 30000,
|
||||
pubkey: actorHex,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags,
|
||||
content: "",
|
||||
};
|
||||
}
|
||||
|
||||
function publishToRelay(url, signedEvent, listKey) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const timeout = setTimeout(() => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve({ url, success: false, error: new Error("timeout") });
|
||||
}
|
||||
}, PUBLISH_TIMEOUT_MS);
|
||||
|
||||
const finalize = (success, error) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolve({ url, success, error });
|
||||
};
|
||||
|
||||
try {
|
||||
const pub = nostrClient.pool.publish([url], signedEvent);
|
||||
if (!pub) {
|
||||
finalize(false, new Error("publish returned no result"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof pub.on === "function") {
|
||||
pub.on("ok", () => finalize(true));
|
||||
pub.on("seen", () => finalize(true));
|
||||
pub.on("failed", (reason) => {
|
||||
const error =
|
||||
reason instanceof Error ? reason : new Error(String(reason || "failed"));
|
||||
finalize(false, error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof pub.then === "function") {
|
||||
pub.then(() => finalize(true)).catch((error) => finalize(false, error));
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
finalize(false, error);
|
||||
return;
|
||||
}
|
||||
|
||||
finalize(true);
|
||||
}).then((result) => {
|
||||
if (!result.success && isDevMode) {
|
||||
console.warn(
|
||||
`[adminListStore] Publish failed for ${listKey} on ${result.url}:`,
|
||||
result.error
|
||||
);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
async function persistNostrState(actorNpub, updates = {}) {
|
||||
ensureNostrReady();
|
||||
const extension = window?.nostr;
|
||||
if (!extension || typeof extension.signEvent !== "function") {
|
||||
throw createError(
|
||||
"nostr-extension-missing",
|
||||
"A Nostr extension with signEvent support is required."
|
||||
);
|
||||
}
|
||||
|
||||
const actorHex = decodeNpubToHex(actorNpub);
|
||||
if (!actorHex) {
|
||||
throw createError("invalid npub", "Unable to decode the actor npub.");
|
||||
}
|
||||
|
||||
const sanitizedUpdates = {};
|
||||
const actorNormalized = normalizeNpub(actorNpub);
|
||||
|
||||
if (Array.isArray(updates.editors)) {
|
||||
sanitizedUpdates.editors = sanitizeNpubList(updates.editors).filter((npub) => {
|
||||
const normalized = normalizeNpub(npub);
|
||||
return normalized && normalized !== normalizeNpub(ADMIN_SUPER_NPUB);
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(updates.whitelist)) {
|
||||
sanitizedUpdates.whitelist = sanitizeNpubList(updates.whitelist);
|
||||
}
|
||||
|
||||
if (Array.isArray(updates.blacklist)) {
|
||||
const whitelistSet = new Set(
|
||||
(sanitizedUpdates.whitelist || []).map(normalizeNpub)
|
||||
);
|
||||
const editorGuard = new Set([
|
||||
normalizeNpub(ADMIN_SUPER_NPUB),
|
||||
...ADMIN_EDITORS_NPUBS.map(normalizeNpub),
|
||||
...((sanitizedUpdates.editors || []).map(normalizeNpub) || []),
|
||||
]);
|
||||
|
||||
if (actorNormalized) {
|
||||
editorGuard.add(actorNormalized);
|
||||
}
|
||||
|
||||
sanitizedUpdates.blacklist = sanitizeNpubList(updates.blacklist).filter(
|
||||
(npub) => {
|
||||
const normalized = normalizeNpub(npub);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
if (whitelistSet.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
if (editorGuard.has(normalized)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const entries = Object.entries(sanitizedUpdates).filter(([, value]) =>
|
||||
Array.isArray(value)
|
||||
);
|
||||
|
||||
if (!entries.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [listKey, npubs] of entries) {
|
||||
const event = buildListEvent(listKey, npubs, actorHex);
|
||||
|
||||
let signedEvent;
|
||||
try {
|
||||
signedEvent = await extension.signEvent(event);
|
||||
} catch (error) {
|
||||
throw createError("signature-failed", "Failed to sign admin list event.", error);
|
||||
}
|
||||
|
||||
const relays = ensureNostrReady();
|
||||
const publishResults = await Promise.all(
|
||||
relays.map((url) => publishToRelay(url, signedEvent, listKey))
|
||||
);
|
||||
|
||||
if (!publishResults.some((result) => result.success)) {
|
||||
throw createError(
|
||||
"publish-failed",
|
||||
`Failed to publish ${listKey} list to any relay.`
|
||||
);
|
||||
}
|
||||
|
||||
clearLegacyStorageFor(listKey);
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadAdminState() {
|
||||
if (ADMIN_LIST_MODE !== "nostr" && isDevMode) {
|
||||
console.warn(
|
||||
`[adminListStore] ADMIN_LIST_MODE "${ADMIN_LIST_MODE}" is deprecated. Defaulting to remote Nostr lists.`
|
||||
);
|
||||
}
|
||||
|
||||
const state = await loadNostrState();
|
||||
if (!hasAnyEntries(state)) {
|
||||
const legacy = loadLegacyAdminState();
|
||||
if (legacy && isDevMode) {
|
||||
console.warn(
|
||||
"[adminListStore] Ignoring legacy admin lists because remote mode is enforced. Publish them to Nostr to retain access.",
|
||||
legacy
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export async function persistAdminState(actorNpub, updates) {
|
||||
if (ADMIN_LIST_MODE !== "nostr" && isDevMode) {
|
||||
console.warn(
|
||||
`[adminListStore] ADMIN_LIST_MODE "${ADMIN_LIST_MODE}" is deprecated. Remote lists are enforced.`
|
||||
);
|
||||
}
|
||||
|
||||
return persistNostrState(actorNpub, updates);
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
// js/analytics.js
|
||||
import { ANALYTICS_CONFIG } from "./analyticsConfig.js";
|
||||
|
||||
const SCRIPT_ATTR = "data-bitvid-analytics";
|
||||
const SCRIPT_IDENTIFIER = "umami";
|
||||
const pendingCalls = [];
|
||||
let flushTimerId = null;
|
||||
let scriptLoadedOnce = false;
|
||||
|
||||
function isBrowserEnvironment() {
|
||||
return typeof window !== "undefined" && typeof document !== "undefined";
|
||||
}
|
||||
|
||||
function flushPendingCalls() {
|
||||
if (!isBrowserEnvironment()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const umami = window.umami;
|
||||
if (!umami) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (pendingCalls.length > 0) {
|
||||
const { method, args } = pendingCalls.shift();
|
||||
const fn = typeof umami[method] === "function" ? umami[method] : null;
|
||||
if (!fn) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
fn.apply(umami, args);
|
||||
} catch (err) {
|
||||
console.warn("[analytics] Failed to call", method, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleFlush() {
|
||||
if (!isBrowserEnvironment()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (flushTimerId !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 🔧 merged conflicting changes from codex/add-tracking-script-to-all-pages vs unstable
|
||||
flushTimerId = window.setInterval(() => {
|
||||
if (window.umami && typeof window.umami.track === "function") {
|
||||
window.clearInterval(flushTimerId);
|
||||
flushTimerId = null;
|
||||
flushPendingCalls();
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
export function ensureAnalyticsLoaded(doc = typeof document !== "undefined" ? document : null) {
|
||||
if (!doc) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let script = doc.querySelector(`script[${SCRIPT_ATTR}]`);
|
||||
if (script) {
|
||||
if (!scriptLoadedOnce) {
|
||||
// If a server rendered script already exists, make sure we flush asap.
|
||||
scriptLoadedOnce = true;
|
||||
flushPendingCalls();
|
||||
}
|
||||
return script;
|
||||
}
|
||||
|
||||
script = doc.createElement("script");
|
||||
script.defer = true;
|
||||
script.src = ANALYTICS_CONFIG.scriptSrc;
|
||||
script.setAttribute(SCRIPT_ATTR, SCRIPT_IDENTIFIER);
|
||||
script.dataset.websiteId = ANALYTICS_CONFIG.websiteId;
|
||||
// Allow Umami to handle automatic pageview tracking by default.
|
||||
script.addEventListener("load", () => {
|
||||
scriptLoadedOnce = true;
|
||||
flushPendingCalls();
|
||||
});
|
||||
doc.head.appendChild(script);
|
||||
|
||||
scheduleFlush();
|
||||
|
||||
return script;
|
||||
}
|
||||
|
||||
function queueCall(method, args) {
|
||||
pendingCalls.push({ method, args });
|
||||
scheduleFlush();
|
||||
}
|
||||
|
||||
function invokeUmami(method, args) {
|
||||
if (!isBrowserEnvironment()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureAnalyticsLoaded();
|
||||
|
||||
const umami = window.umami;
|
||||
if (umami && typeof umami[method] === "function") {
|
||||
try {
|
||||
umami[method].apply(umami, args);
|
||||
} catch (err) {
|
||||
console.warn("[analytics] Failed to call", method, err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
queueCall(method, args);
|
||||
}
|
||||
|
||||
export function trackPageView(path, referrer) {
|
||||
if (!isBrowserEnvironment()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resolvedPath =
|
||||
typeof path === "string" && path.length > 0
|
||||
? path
|
||||
: `${window.location.pathname}${window.location.hash || ""}`;
|
||||
|
||||
const resolvedReferrer =
|
||||
typeof referrer === "string" ? referrer : document.referrer || "";
|
||||
|
||||
// 🔧 merged conflicting changes from codex/add-tracking-script-to-all-pages vs unstable
|
||||
let absoluteUrl = resolvedPath;
|
||||
try {
|
||||
absoluteUrl = new URL(resolvedPath, window.location.origin).toString();
|
||||
} catch (err) {
|
||||
// Fall back to the provided path if it cannot be resolved.
|
||||
}
|
||||
|
||||
let absoluteReferrer = resolvedReferrer;
|
||||
if (resolvedReferrer) {
|
||||
try {
|
||||
absoluteReferrer = new URL(resolvedReferrer, window.location.origin).toString();
|
||||
} catch (err) {
|
||||
// Keep original referrer if it cannot be normalized.
|
||||
}
|
||||
}
|
||||
|
||||
invokeUmami("track", [
|
||||
(basePayload = {}) => ({
|
||||
...basePayload,
|
||||
url: absoluteUrl || basePayload.url,
|
||||
referrer: absoluteReferrer || basePayload.referrer,
|
||||
}),
|
||||
"pageview",
|
||||
]);
|
||||
}
|
||||
|
||||
export function trackVideoView({
|
||||
videoId,
|
||||
title,
|
||||
source,
|
||||
hasMagnet,
|
||||
hasUrl,
|
||||
} = {}) {
|
||||
if (!isBrowserEnvironment()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {};
|
||||
|
||||
if (videoId) {
|
||||
payload.videoId = String(videoId);
|
||||
}
|
||||
|
||||
if (title) {
|
||||
payload.title = String(title);
|
||||
}
|
||||
|
||||
if (source) {
|
||||
payload.source = String(source);
|
||||
}
|
||||
|
||||
if (typeof hasMagnet === "boolean") {
|
||||
payload.hasMagnet = hasMagnet;
|
||||
}
|
||||
|
||||
if (typeof hasUrl === "boolean") {
|
||||
payload.hasUrl = hasUrl;
|
||||
}
|
||||
|
||||
// 🔧 merged conflicting changes from codex/add-tracking-script-to-all-pages vs unstable
|
||||
invokeUmami("track", [ANALYTICS_CONFIG.videoViewEventName, payload]);
|
||||
}
|
||||
|
||||
// Immediately queue the analytics script so page views are captured early.
|
||||
if (isBrowserEnvironment()) {
|
||||
ensureAnalyticsLoaded();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// js/analyticsConfig.js
|
||||
// Central configuration for site-wide analytics tracking.
|
||||
|
||||
export const ANALYTICS_CONFIG = Object.freeze({
|
||||
/**
|
||||
* Hosted Umami script that powers analytics.
|
||||
* Update this value if the tracker is relocated.
|
||||
*/
|
||||
scriptSrc: "https://umami.malin.onl/script.js",
|
||||
/**
|
||||
* The Umami website identifier for this deployment.
|
||||
*/
|
||||
websiteId: "1f8eead2-79f0-4dba-8c3b-ed9b08b6e877",
|
||||
/**
|
||||
* Event name used when recording individual video views.
|
||||
*/
|
||||
videoViewEventName: "video_view",
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Buffer } from "https://esm.sh/[email protected]?bundle";
|
||||
|
||||
const globalScope = typeof globalThis !== "undefined" ? globalThis : window;
|
||||
|
||||
if (globalScope && !globalScope.Buffer) {
|
||||
globalScope.Buffer = Buffer;
|
||||
}
|
||||
|
||||
if (globalScope && !globalScope.global) {
|
||||
globalScope.global = globalScope;
|
||||
}
|
||||
|
||||
if (globalScope && !globalScope.process) {
|
||||
globalScope.process = { env: {} };
|
||||
}
|
||||
|
||||
export { Buffer };
|
||||
+511
-81
@@ -1,10 +1,212 @@
|
||||
// js/channelProfile.js
|
||||
|
||||
import { nostrClient } from "./nostr.js";
|
||||
import {
|
||||
nostrClient,
|
||||
convertEventToVideo as sharedConvertEventToVideo,
|
||||
} from "./nostr.js";
|
||||
import { app } from "./app.js";
|
||||
import { subscriptions } from "./subscriptions.js"; // <-- NEW import
|
||||
import { initialBlacklist, initialWhitelist } from "./lists.js";
|
||||
import { isWhitelistEnabled } from "./config.js";
|
||||
import { attachHealthBadges } from "./gridHealth.js";
|
||||
import { attachUrlHealthBadges } from "./urlHealthObserver.js";
|
||||
import { accessControl } from "./accessControl.js";
|
||||
|
||||
let currentChannelHex = null;
|
||||
let currentChannelNpub = null;
|
||||
|
||||
let cachedZapButton = null;
|
||||
let cachedChannelShareButton = null;
|
||||
let cachedChannelMenu = null;
|
||||
|
||||
function getChannelZapButton() {
|
||||
if (cachedZapButton && !document.body.contains(cachedZapButton)) {
|
||||
cachedZapButton = null;
|
||||
}
|
||||
if (!cachedZapButton) {
|
||||
cachedZapButton = document.getElementById("zapButton");
|
||||
}
|
||||
return cachedZapButton;
|
||||
}
|
||||
|
||||
function setChannelZapVisibility(visible) {
|
||||
const zapButton = getChannelZapButton();
|
||||
if (!zapButton) {
|
||||
return;
|
||||
}
|
||||
const shouldShow = !!visible;
|
||||
zapButton.classList.toggle("hidden", !shouldShow);
|
||||
zapButton.disabled = !shouldShow;
|
||||
zapButton.setAttribute("aria-disabled", (!shouldShow).toString());
|
||||
zapButton.setAttribute("aria-hidden", (!shouldShow).toString());
|
||||
if (shouldShow) {
|
||||
zapButton.removeAttribute("tabindex");
|
||||
} else {
|
||||
zapButton.setAttribute("tabindex", "-1");
|
||||
}
|
||||
}
|
||||
|
||||
function getChannelShareButton() {
|
||||
if (cachedChannelShareButton && !document.body.contains(cachedChannelShareButton)) {
|
||||
cachedChannelShareButton = null;
|
||||
}
|
||||
if (!cachedChannelShareButton) {
|
||||
cachedChannelShareButton = document.getElementById("channelShareBtn");
|
||||
}
|
||||
return cachedChannelShareButton;
|
||||
}
|
||||
|
||||
function getChannelMenuElement() {
|
||||
if (cachedChannelMenu && !document.body.contains(cachedChannelMenu)) {
|
||||
cachedChannelMenu = null;
|
||||
}
|
||||
if (!cachedChannelMenu) {
|
||||
cachedChannelMenu = document.getElementById("moreDropdown-channel-profile");
|
||||
}
|
||||
return cachedChannelMenu;
|
||||
}
|
||||
|
||||
function buildChannelShareUrl() {
|
||||
if (!currentChannelNpub) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const base = typeof app.getShareUrlBase === "function" ? app.getShareUrlBase() : "";
|
||||
if (base) {
|
||||
return `${base}#view=channel-profile&npub=${encodeURIComponent(currentChannelNpub)}`;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
url.search = "";
|
||||
url.hash = `#view=channel-profile&npub=${currentChannelNpub}`;
|
||||
return url.toString();
|
||||
} catch (error) {
|
||||
console.warn("Falling back to basic channel share URL:", error);
|
||||
const origin = window.location?.origin || "";
|
||||
const pathname = window.location?.pathname || "";
|
||||
if (!origin && !pathname) {
|
||||
return "";
|
||||
}
|
||||
return `${origin}${pathname}#view=channel-profile&npub=${currentChannelNpub}`;
|
||||
}
|
||||
}
|
||||
|
||||
function syncChannelShareButtonState() {
|
||||
const shareBtn = getChannelShareButton();
|
||||
if (!shareBtn) {
|
||||
return;
|
||||
}
|
||||
const hasNpub = typeof currentChannelNpub === "string" && currentChannelNpub;
|
||||
shareBtn.disabled = !hasNpub;
|
||||
shareBtn.setAttribute("aria-disabled", (!hasNpub).toString());
|
||||
shareBtn.classList.toggle("opacity-50", !hasNpub);
|
||||
shareBtn.classList.toggle("cursor-not-allowed", !hasNpub);
|
||||
}
|
||||
|
||||
function setupChannelShareButton() {
|
||||
const shareBtn = getChannelShareButton();
|
||||
if (!shareBtn) {
|
||||
return;
|
||||
}
|
||||
|
||||
syncChannelShareButtonState();
|
||||
|
||||
if (shareBtn.dataset.initialized === "true") {
|
||||
return;
|
||||
}
|
||||
|
||||
shareBtn.addEventListener("click", () => {
|
||||
const shareUrl = buildChannelShareUrl();
|
||||
if (!shareUrl) {
|
||||
app.showError("Could not generate channel link.");
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.clipboard
|
||||
.writeText(shareUrl)
|
||||
.then(() => app.showSuccess("Channel link copied to clipboard!"))
|
||||
.catch(() => app.showError("Failed to copy the link."));
|
||||
});
|
||||
|
||||
shareBtn.dataset.initialized = "true";
|
||||
}
|
||||
|
||||
function setupChannelMoreMenu() {
|
||||
const container = document.querySelector(".channel-profile-container");
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
app.attachMoreMenuHandlers(container);
|
||||
}
|
||||
|
||||
async function updateChannelMenuState() {
|
||||
const menu = getChannelMenuElement();
|
||||
if (!menu) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await accessControl.ensureReady();
|
||||
} catch (error) {
|
||||
console.warn("Failed to refresh moderation lists for channel menu:", error);
|
||||
}
|
||||
|
||||
const canBlacklist =
|
||||
typeof app.canCurrentUserManageBlacklist === "function"
|
||||
? app.canCurrentUserManageBlacklist()
|
||||
: false;
|
||||
|
||||
const buttons = menu.querySelectorAll("button[data-action]");
|
||||
buttons.forEach((button) => {
|
||||
if (!(button instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const action = button.dataset.action || "";
|
||||
if (action === "copy-npub") {
|
||||
if (currentChannelNpub) {
|
||||
button.dataset.npub = currentChannelNpub;
|
||||
button.classList.remove("hidden");
|
||||
button.setAttribute("aria-hidden", "false");
|
||||
} else {
|
||||
delete button.dataset.npub;
|
||||
button.classList.add("hidden");
|
||||
button.setAttribute("aria-hidden", "true");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "block-author") {
|
||||
if (currentChannelHex) {
|
||||
button.dataset.author = currentChannelHex;
|
||||
button.classList.remove("hidden");
|
||||
button.setAttribute("aria-hidden", "false");
|
||||
} else {
|
||||
delete button.dataset.author;
|
||||
button.classList.add("hidden");
|
||||
button.setAttribute("aria-hidden", "true");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "blacklist-author") {
|
||||
if (canBlacklist && currentChannelHex) {
|
||||
button.dataset.author = currentChannelHex;
|
||||
if (currentChannelNpub) {
|
||||
button.dataset.npub = currentChannelNpub;
|
||||
} else {
|
||||
delete button.dataset.npub;
|
||||
}
|
||||
button.classList.remove("hidden");
|
||||
button.setAttribute("aria-hidden", "false");
|
||||
} else {
|
||||
delete button.dataset.author;
|
||||
delete button.dataset.npub;
|
||||
button.classList.add("hidden");
|
||||
button.setAttribute("aria-hidden", "true");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the channel profile view.
|
||||
@@ -21,6 +223,9 @@ export async function initChannelProfileView() {
|
||||
return;
|
||||
}
|
||||
|
||||
currentChannelHex = null;
|
||||
currentChannelNpub = null;
|
||||
|
||||
// 2) Decode npub => hex pubkey
|
||||
let hexPub;
|
||||
try {
|
||||
@@ -35,6 +240,13 @@ export async function initChannelProfileView() {
|
||||
return;
|
||||
}
|
||||
|
||||
currentChannelHex = hexPub;
|
||||
currentChannelNpub = npub;
|
||||
|
||||
setupChannelShareButton();
|
||||
setupChannelMoreMenu();
|
||||
await updateChannelMenuState();
|
||||
|
||||
// 3) If user is logged in, load subscriptions and show sub/unsub button
|
||||
if (app.pubkey) {
|
||||
await subscriptions.loadSubscriptions(app.pubkey);
|
||||
@@ -44,13 +256,36 @@ export async function initChannelProfileView() {
|
||||
if (btn) btn.classList.add("hidden");
|
||||
}
|
||||
|
||||
setupZapButton();
|
||||
syncChannelShareButtonState();
|
||||
|
||||
// 4) Load user’s profile (banner, avatar, etc.)
|
||||
await loadUserProfile(hexPub);
|
||||
await updateChannelMenuState();
|
||||
syncChannelShareButtonState();
|
||||
|
||||
// 5) Load user’s videos (filtered + rendered like the home feed)
|
||||
await loadUserVideos(hexPub);
|
||||
}
|
||||
|
||||
function setupZapButton() {
|
||||
const zapButton = getChannelZapButton();
|
||||
if (!zapButton) {
|
||||
return;
|
||||
}
|
||||
|
||||
setChannelZapVisibility(false);
|
||||
|
||||
if (zapButton.dataset.initialized === "true") {
|
||||
return;
|
||||
}
|
||||
|
||||
zapButton.addEventListener("click", () => {
|
||||
window.alert("Zaps coming soon.");
|
||||
});
|
||||
zapButton.dataset.initialized = "true";
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a Subscribe / Unsubscribe button with an icon,
|
||||
* using color #fe0032 and the subscribe-button-icon.svg on the left.
|
||||
@@ -159,15 +394,27 @@ async function loadUserProfile(pubkey) {
|
||||
|
||||
// Lightning Address
|
||||
const lnEl = document.getElementById("channelLightning");
|
||||
const lightningAddress = (meta.lud16 || meta.lud06 || "").trim();
|
||||
if (lnEl) {
|
||||
lnEl.textContent =
|
||||
meta.lud16 || meta.lud06 || "No lightning address found.";
|
||||
lightningAddress || "No lightning address found.";
|
||||
}
|
||||
setChannelZapVisibility(!!lightningAddress);
|
||||
} else {
|
||||
console.warn("No metadata found for this user.");
|
||||
setChannelZapVisibility(false);
|
||||
const lnEl = document.getElementById("channelLightning");
|
||||
if (lnEl) {
|
||||
lnEl.textContent = "No lightning address found.";
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch user profile data:", err);
|
||||
setChannelZapVisibility(false);
|
||||
const lnEl = document.getElementById("channelLightning");
|
||||
if (lnEl) {
|
||||
lnEl.textContent = "No lightning address found.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +424,12 @@ async function loadUserProfile(pubkey) {
|
||||
*/
|
||||
async function loadUserVideos(pubkey) {
|
||||
try {
|
||||
try {
|
||||
await accessControl.ensureReady();
|
||||
} catch (error) {
|
||||
console.warn("Failed to ensure admin lists were loaded before channel fetch:", error);
|
||||
}
|
||||
|
||||
// 1) Build filter for videos from this pubkey
|
||||
const filter = {
|
||||
kinds: [30078],
|
||||
@@ -196,29 +449,24 @@ async function loadUserVideos(pubkey) {
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Convert to "video" objects
|
||||
let videos = [];
|
||||
for (const evt of events) {
|
||||
const vid = localConvertEventToVideo(evt);
|
||||
if (!vid.invalid && !vid.deleted) {
|
||||
videos.push(vid);
|
||||
}
|
||||
}
|
||||
// 3) Convert to "video" objects and keep everything (including tombstones)
|
||||
const convertedVideos = events
|
||||
.map((evt) => sharedConvertEventToVideo(evt))
|
||||
.filter((vid) => !vid.invalid);
|
||||
|
||||
// 4) Deduplicate older overshadowed versions => newest only
|
||||
videos = dedupeToNewestByRoot(videos);
|
||||
const newestByRoot =
|
||||
app?.dedupeVideosByRoot?.(convertedVideos) ??
|
||||
dedupeToNewestByRoot(convertedVideos);
|
||||
|
||||
// 5) Filter out blacklisted IDs / authors
|
||||
// 5) Filter out tombstones, blacklisted IDs / authors
|
||||
let videos = newestByRoot.filter((video) => !video.deleted);
|
||||
videos = videos.filter((video) => {
|
||||
// Event-level blacklisting
|
||||
if (app.blacklistedEventIds.has(video.id)) return false;
|
||||
|
||||
// Author-level
|
||||
const authorNpub = app.safeEncodeNpub(video.pubkey) || video.pubkey;
|
||||
if (initialBlacklist.includes(authorNpub)) return false;
|
||||
if (isWhitelistEnabled && !initialWhitelist.includes(authorNpub)) {
|
||||
return false;
|
||||
}
|
||||
if (!accessControl.canAccess(video)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -251,6 +499,10 @@ async function loadUserVideos(pubkey) {
|
||||
video.alreadyDecrypted = true;
|
||||
}
|
||||
|
||||
// Ensure the global videos map is kept up to date so delegated handlers
|
||||
// have the freshest metadata for this event.
|
||||
window.app?.videosMap?.set(video.id, video);
|
||||
|
||||
// Check if user can edit
|
||||
const canEdit = video.pubkey === app.pubkey;
|
||||
let hasOlder = false;
|
||||
@@ -264,6 +516,7 @@ async function loadUserVideos(pubkey) {
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400
|
||||
hover:bg-red-700 hover:text-white"
|
||||
data-revert-index="${index}"
|
||||
data-revert-event-id="${video.id}"
|
||||
>
|
||||
Revert
|
||||
</button>
|
||||
@@ -298,6 +551,7 @@ async function loadUserVideos(pubkey) {
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100
|
||||
hover:bg-gray-700"
|
||||
data-edit-index="${index}"
|
||||
data-edit-event-id="${video.id}"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
@@ -306,6 +560,7 @@ async function loadUserVideos(pubkey) {
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400
|
||||
hover:bg-red-700 hover:text-white"
|
||||
data-delete-all-index="${index}"
|
||||
data-delete-all-event-id="${video.id}"
|
||||
>
|
||||
Delete All
|
||||
</button>
|
||||
@@ -315,6 +570,48 @@ async function loadUserVideos(pubkey) {
|
||||
`;
|
||||
}
|
||||
|
||||
const moreMenu = `
|
||||
<div class="relative inline-block ml-1 overflow-visible" data-more-menu-wrapper="true">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center w-10 h-10 p-2 rounded-full text-gray-400 hover:text-gray-200 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
data-more-dropdown="${index}"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-label="More options"
|
||||
>
|
||||
<img src="assets/svg/ellipsis.svg" alt="More" class="w-5 h-5 object-contain" />
|
||||
</button>
|
||||
<div
|
||||
id="moreDropdown-${index}"
|
||||
class="hidden absolute right-0 bottom-full mb-2 w-40 rounded-md shadow-lg bg-gray-800 ring-1 ring-black ring-opacity-5 z-50"
|
||||
role="menu"
|
||||
data-more-menu="true"
|
||||
>
|
||||
<div class="py-1">
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700" data-action="open-channel" data-author="${video.pubkey || ""}">
|
||||
Open channel
|
||||
</button>
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700" data-action="copy-link" data-event-id="${video.id || ""}">
|
||||
Copy link
|
||||
</button>
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white" data-action="block-author" data-author="${video.pubkey || ""}">
|
||||
Block creator
|
||||
</button>
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700" data-action="report" data-event-id="${video.id || ""}">
|
||||
Report
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const cardControls = `
|
||||
<div class="flex items-center">
|
||||
${moreMenu}${gearMenu}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Fallback thumbnail
|
||||
const fallbackThumb = "assets/jpg/video-thumbnail-fallback.jpg";
|
||||
const safeThumb = video.thumbnail || fallbackThumb;
|
||||
@@ -322,6 +619,7 @@ async function loadUserVideos(pubkey) {
|
||||
|
||||
const cardEl = document.createElement("div");
|
||||
cardEl.classList.add(
|
||||
"video-card",
|
||||
"bg-gray-900",
|
||||
"rounded-lg",
|
||||
"overflow-hidden",
|
||||
@@ -331,8 +629,49 @@ async function loadUserVideos(pubkey) {
|
||||
"duration-300"
|
||||
);
|
||||
|
||||
cardEl.dataset.ownerIsViewer = canEdit ? "true" : "false";
|
||||
if (typeof video.pubkey === "string" && video.pubkey) {
|
||||
cardEl.dataset.ownerPubkey = video.pubkey;
|
||||
} else if (cardEl.dataset.ownerPubkey) {
|
||||
delete cardEl.dataset.ownerPubkey;
|
||||
}
|
||||
|
||||
const rawMagnet =
|
||||
typeof video.magnet === "string" ? video.magnet : "";
|
||||
const trimmedMagnet = rawMagnet ? rawMagnet.trim() : "";
|
||||
const legacyInfoHash =
|
||||
typeof video.infoHash === "string" ? video.infoHash.trim() : "";
|
||||
const playbackUrl =
|
||||
typeof video.url === "string" ? video.url : "";
|
||||
const trimmedUrl = playbackUrl ? playbackUrl.trim() : "";
|
||||
const playbackMagnet = trimmedMagnet || legacyInfoHash || "";
|
||||
const magnetProvided = playbackMagnet.length > 0;
|
||||
const magnetSupported = app.isMagnetUriSupported(playbackMagnet);
|
||||
const showUnsupportedTorrentBadge =
|
||||
!trimmedUrl && magnetProvided && !magnetSupported;
|
||||
const urlBadgeHtml = trimmedUrl
|
||||
? app.getUrlHealthPlaceholderMarkup({ includeMargin: false })
|
||||
: "";
|
||||
const torrentHealthBadgeHtml =
|
||||
magnetSupported && magnetProvided
|
||||
? app.getTorrentHealthBadgeMarkup({ includeMargin: false })
|
||||
: "";
|
||||
const connectionBadgesHtml =
|
||||
urlBadgeHtml || torrentHealthBadgeHtml
|
||||
? `
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2">
|
||||
${urlBadgeHtml}${torrentHealthBadgeHtml}
|
||||
</div>
|
||||
`
|
||||
: "";
|
||||
|
||||
cardEl.innerHTML = `
|
||||
<div class="cursor-pointer relative group">
|
||||
<div
|
||||
class="cursor-pointer relative group"
|
||||
data-video-id="${video.id}"
|
||||
data-play-url=""
|
||||
data-play-magnet=""
|
||||
>
|
||||
<div class="ratio-16-9">
|
||||
<img
|
||||
src="${fallbackThumb}"
|
||||
@@ -341,36 +680,129 @@ async function loadUserVideos(pubkey) {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h3
|
||||
class="text-lg font-bold text-white mb-2 line-clamp-2"
|
||||
data-play-magnet="${encodeURIComponent(video.magnet)}"
|
||||
>
|
||||
${safeTitle}
|
||||
</h3>
|
||||
<p class="text-sm text-gray-500">
|
||||
${new Date(video.created_at * 1000).toLocaleString()}
|
||||
</p>
|
||||
<div class="p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h3
|
||||
class="text-lg font-bold text-white mb-2 line-clamp-2"
|
||||
data-video-id="${video.id}"
|
||||
data-play-url=""
|
||||
data-play-magnet=""
|
||||
>
|
||||
${safeTitle}
|
||||
</h3>
|
||||
<p class="text-sm text-gray-500">
|
||||
${new Date(video.created_at * 1000).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
${cardControls}
|
||||
</div>
|
||||
${gearMenu}
|
||||
${connectionBadgesHtml}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Clicking the card => open the video modal
|
||||
cardEl.addEventListener("click", () => {
|
||||
app.playVideoByEventId(video.id);
|
||||
if (showUnsupportedTorrentBadge) {
|
||||
cardEl.dataset.torrentSupported = "false";
|
||||
} else if (magnetProvided && magnetSupported) {
|
||||
cardEl.dataset.torrentSupported = "true";
|
||||
} else if (cardEl.dataset.torrentSupported) {
|
||||
delete cardEl.dataset.torrentSupported;
|
||||
}
|
||||
|
||||
if (trimmedUrl) {
|
||||
cardEl.dataset.urlHealthState = "checking";
|
||||
if (cardEl.dataset.urlHealthReason) {
|
||||
delete cardEl.dataset.urlHealthReason;
|
||||
}
|
||||
cardEl.dataset.urlHealthEventId = video.id || "";
|
||||
cardEl.dataset.urlHealthUrl = encodeURIComponent(trimmedUrl);
|
||||
} else {
|
||||
cardEl.dataset.urlHealthState = "offline";
|
||||
cardEl.dataset.urlHealthReason = "missing-source";
|
||||
if (cardEl.dataset.urlHealthEventId) {
|
||||
delete cardEl.dataset.urlHealthEventId;
|
||||
}
|
||||
if (cardEl.dataset.urlHealthUrl) {
|
||||
delete cardEl.dataset.urlHealthUrl;
|
||||
}
|
||||
}
|
||||
if (magnetProvided && magnetSupported) {
|
||||
cardEl.dataset.streamHealthState = "checking";
|
||||
if (cardEl.dataset.streamHealthReason) {
|
||||
delete cardEl.dataset.streamHealthReason;
|
||||
}
|
||||
} else {
|
||||
cardEl.dataset.streamHealthState = "unhealthy";
|
||||
cardEl.dataset.streamHealthReason = magnetProvided
|
||||
? "unsupported"
|
||||
: "missing-source";
|
||||
}
|
||||
|
||||
if (magnetProvided) {
|
||||
cardEl.dataset.magnet = playbackMagnet;
|
||||
} else if (cardEl.dataset.magnet) {
|
||||
delete cardEl.dataset.magnet;
|
||||
}
|
||||
|
||||
// Leave the data-play-* attributes empty in the template markup so the raw
|
||||
// URL/magnet strings can be assigned after parsing without HTML entity
|
||||
// escaping, keeping this renderer consistent with app.js. The stored URL is
|
||||
// encoded so it stays intact within data-* attributes, and the click
|
||||
// handler decodes it while leaving magnets untouched until
|
||||
// safeDecodeMagnet() runs.
|
||||
const interactiveEls = cardEl.querySelectorAll("[data-video-id]");
|
||||
interactiveEls.forEach((el) => {
|
||||
if (!el.dataset) return;
|
||||
|
||||
if (trimmedUrl) {
|
||||
el.dataset.playUrl = encodeURIComponent(trimmedUrl);
|
||||
} else {
|
||||
delete el.dataset.playUrl;
|
||||
}
|
||||
|
||||
el.dataset.playMagnet = playbackMagnet || "";
|
||||
if (magnetProvided) {
|
||||
el.dataset.torrentSupported = magnetSupported ? "true" : "false";
|
||||
} else if (el.dataset.torrentSupported) {
|
||||
delete el.dataset.torrentSupported;
|
||||
}
|
||||
});
|
||||
|
||||
const badgeEl = cardEl.querySelector("[data-url-health-state]");
|
||||
if (badgeEl) {
|
||||
if (trimmedUrl) {
|
||||
badgeEl.dataset.urlHealthEventId = video.id || "";
|
||||
badgeEl.dataset.urlHealthUrl = encodeURIComponent(trimmedUrl);
|
||||
} else {
|
||||
if (badgeEl.dataset.urlHealthEventId) {
|
||||
delete badgeEl.dataset.urlHealthEventId;
|
||||
}
|
||||
if (badgeEl.dataset.urlHealthUrl) {
|
||||
delete badgeEl.dataset.urlHealthUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fragment.appendChild(cardEl);
|
||||
});
|
||||
|
||||
container.appendChild(fragment);
|
||||
|
||||
attachHealthBadges(container);
|
||||
attachUrlHealthBadges(container, ({ badgeEl, url, eventId }) => {
|
||||
const video = app.videosMap.get(eventId) || { id: eventId };
|
||||
app.handleUrlHealthBadge({ video, url, badgeEl });
|
||||
});
|
||||
|
||||
window.app.videoList = container;
|
||||
window.app.attachVideoListHandler();
|
||||
|
||||
// Lazy-load images
|
||||
const lazyEls = container.querySelectorAll("[data-lazy]");
|
||||
lazyEls.forEach((el) => app.mediaLoader.observe(el));
|
||||
|
||||
app.attachMoreMenuHandlers(container);
|
||||
|
||||
// Gear menu toggles
|
||||
const gearButtons = container.querySelectorAll("[data-settings-dropdown]");
|
||||
gearButtons.forEach((btn) => {
|
||||
@@ -389,10 +821,15 @@ async function loadUserVideos(pubkey) {
|
||||
editBtns.forEach((btn) => {
|
||||
btn.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const idx = parseInt(btn.getAttribute("data-edit-index"), 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idx}`);
|
||||
const idxAttr = btn.getAttribute("data-edit-index");
|
||||
const idx = Number.parseInt(idxAttr, 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idxAttr}`);
|
||||
if (dropdown) dropdown.classList.add("hidden");
|
||||
app.handleEditVideo(idx);
|
||||
const eventId = btn.getAttribute("data-edit-event-id") || "";
|
||||
app.handleEditVideo({
|
||||
eventId,
|
||||
index: Number.isNaN(idx) ? null : idx,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -401,10 +838,15 @@ async function loadUserVideos(pubkey) {
|
||||
revertBtns.forEach((btn) => {
|
||||
btn.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const idx = parseInt(btn.getAttribute("data-revert-index"), 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idx}`);
|
||||
const idxAttr = btn.getAttribute("data-revert-index");
|
||||
const idx = Number.parseInt(idxAttr, 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idxAttr}`);
|
||||
if (dropdown) dropdown.classList.add("hidden");
|
||||
app.handleRevertVideo(idx);
|
||||
const eventId = btn.getAttribute("data-revert-event-id") || "";
|
||||
app.handleRevertVideo({
|
||||
eventId,
|
||||
index: Number.isNaN(idx) ? null : idx,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -413,10 +855,15 @@ async function loadUserVideos(pubkey) {
|
||||
deleteAllBtns.forEach((btn) => {
|
||||
btn.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const idx = parseInt(btn.getAttribute("data-delete-all-index"), 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idx}`);
|
||||
const idxAttr = btn.getAttribute("data-delete-all-index");
|
||||
const idx = Number.parseInt(idxAttr, 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idxAttr}`);
|
||||
if (dropdown) dropdown.classList.add("hidden");
|
||||
app.handleFullDeleteVideo(idx);
|
||||
const eventId = btn.getAttribute("data-delete-all-event-id") || "";
|
||||
app.handleFullDeleteVideo({
|
||||
eventId,
|
||||
index: Number.isNaN(idx) ? null : idx,
|
||||
});
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -424,6 +871,26 @@ async function loadUserVideos(pubkey) {
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("bitvid:access-control-updated", () => {
|
||||
const hashParams = new URLSearchParams(window.location.hash.slice(1));
|
||||
if (hashParams.get("view") !== "channel-profile") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentChannelHex) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeNpub = hashParams.get("npub");
|
||||
if (currentChannelNpub && activeNpub && activeNpub !== currentChannelNpub) {
|
||||
return;
|
||||
}
|
||||
|
||||
loadUserVideos(currentChannelHex).catch((error) => {
|
||||
console.error("Failed to refresh channel videos after admin update:", error);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Minimal placeholder for private video decryption.
|
||||
*/
|
||||
@@ -446,43 +913,6 @@ function dedupeToNewestByRoot(videos) {
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert raw event => "video" object.
|
||||
*/
|
||||
function localConvertEventToVideo(event) {
|
||||
try {
|
||||
const content = JSON.parse(event.content || "{}");
|
||||
const isSupportedVersion = content.version >= 2;
|
||||
const hasRequiredFields = !!(content.title && content.magnet);
|
||||
|
||||
if (!isSupportedVersion) {
|
||||
return { id: event.id, invalid: true, reason: "version <2" };
|
||||
}
|
||||
if (!hasRequiredFields) {
|
||||
return { id: event.id, invalid: true, reason: "missing title/magnet" };
|
||||
}
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
videoRootId: content.videoRootId || event.id,
|
||||
version: content.version,
|
||||
isPrivate: content.isPrivate ?? false,
|
||||
title: content.title ?? "",
|
||||
magnet: content.magnet ?? "",
|
||||
thumbnail: content.thumbnail ?? "",
|
||||
description: content.description ?? "",
|
||||
mode: content.mode ?? "live",
|
||||
deleted: content.deleted === true,
|
||||
pubkey: event.pubkey,
|
||||
created_at: event.created_at,
|
||||
tags: event.tags,
|
||||
invalid: false,
|
||||
};
|
||||
} catch (err) {
|
||||
return { id: event.id, invalid: true, reason: "json parse error" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic escaping to avoid XSS.
|
||||
*/
|
||||
|
||||
+41
-1
@@ -1,4 +1,44 @@
|
||||
// js/config.js
|
||||
|
||||
import {
|
||||
ADMIN_SUPER_NPUB,
|
||||
ADMIN_WHITELIST_MODE_STORAGE_KEY,
|
||||
DEFAULT_WHITELIST_MODE_ENABLED,
|
||||
} from "../config/instance-config.js";
|
||||
|
||||
export const isDevMode = true; // Set to false for production
|
||||
export const isWhitelistEnabled = true; // Set to false to allow all non-blacklisted users
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Admin governance — production defaults rely on remote Nostr lists
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
export const ADMIN_LIST_MODE = "nostr";
|
||||
export { ADMIN_SUPER_NPUB };
|
||||
export const ADMIN_EDITORS_NPUBS = []; // Default moderators (optional)
|
||||
export const ADMIN_LIST_NAMESPACE = "bitvid:admin"; // Reserved for Nostr lists
|
||||
|
||||
const WHITELIST_MODE_KEY = ADMIN_WHITELIST_MODE_STORAGE_KEY;
|
||||
const DEFAULT_WHITELIST_ENABLED = DEFAULT_WHITELIST_MODE_ENABLED;
|
||||
|
||||
export function getWhitelistMode() {
|
||||
try {
|
||||
const raw = localStorage.getItem(WHITELIST_MODE_KEY);
|
||||
if (raw === null) {
|
||||
return DEFAULT_WHITELIST_ENABLED;
|
||||
}
|
||||
return raw === "true";
|
||||
} catch (error) {
|
||||
console.warn("Failed to read whitelist mode from storage:", error);
|
||||
return DEFAULT_WHITELIST_ENABLED;
|
||||
}
|
||||
}
|
||||
|
||||
export function setWhitelistMode(enabled) {
|
||||
try {
|
||||
localStorage.setItem(WHITELIST_MODE_KEY, enabled ? "true" : "false");
|
||||
} catch (error) {
|
||||
console.warn("Failed to persist whitelist mode to storage:", error);
|
||||
}
|
||||
}
|
||||
|
||||
export { ADMIN_WHITELIST_MODE_STORAGE_KEY };
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
const DEFAULT_FLAGS = Object.freeze({
|
||||
URL_FIRST_ENABLED: true, // try URL before magnet in the player
|
||||
ACCEPT_LEGACY_V1: true, // accept v1 magnet-only notes
|
||||
WSS_TRACKERS: Object.freeze([
|
||||
"wss://tracker.openwebtorrent.com",
|
||||
"wss://tracker.btorrent.xyz",
|
||||
"wss://tracker.webtorrent.dev",
|
||||
]),
|
||||
});
|
||||
|
||||
const globalScope = typeof globalThis === "object" && globalThis ? globalThis : undefined;
|
||||
|
||||
const runtimeFlags = (() => {
|
||||
if (globalScope && typeof globalScope.__BITVID_RUNTIME_FLAGS__ === "object") {
|
||||
return globalScope.__BITVID_RUNTIME_FLAGS__;
|
||||
}
|
||||
const initial = {
|
||||
URL_FIRST_ENABLED: DEFAULT_FLAGS.URL_FIRST_ENABLED,
|
||||
ACCEPT_LEGACY_V1: DEFAULT_FLAGS.ACCEPT_LEGACY_V1,
|
||||
WSS_TRACKERS: [...DEFAULT_FLAGS.WSS_TRACKERS],
|
||||
};
|
||||
if (globalScope) {
|
||||
globalScope.__BITVID_RUNTIME_FLAGS__ = initial;
|
||||
}
|
||||
return initial;
|
||||
})();
|
||||
|
||||
function coerceBoolean(value, fallback) {
|
||||
if (typeof value === "boolean") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return fallback;
|
||||
}
|
||||
if (["false", "0", "off", "no"].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
if (["true", "1", "on", "yes"].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
return Boolean(value);
|
||||
}
|
||||
|
||||
function sanitizeTrackerList(candidate) {
|
||||
const input = Array.isArray(candidate) ? candidate : DEFAULT_FLAGS.WSS_TRACKERS;
|
||||
const seen = new Set();
|
||||
const sanitized = [];
|
||||
|
||||
for (const tracker of input) {
|
||||
if (typeof tracker !== "string") {
|
||||
continue;
|
||||
}
|
||||
const trimmed = tracker.trim();
|
||||
if (!trimmed) {
|
||||
continue;
|
||||
}
|
||||
if (!/^wss:\/\//i.test(trimmed)) {
|
||||
continue;
|
||||
}
|
||||
const normalized = trimmed.toLowerCase();
|
||||
if (seen.has(normalized)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(normalized);
|
||||
sanitized.push(trimmed);
|
||||
}
|
||||
|
||||
if (!sanitized.length) {
|
||||
return [...DEFAULT_FLAGS.WSS_TRACKERS];
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
function freezeTrackers(list) {
|
||||
return Object.freeze([...list]);
|
||||
}
|
||||
|
||||
export let URL_FIRST_ENABLED = coerceBoolean(
|
||||
runtimeFlags.URL_FIRST_ENABLED,
|
||||
DEFAULT_FLAGS.URL_FIRST_ENABLED
|
||||
);
|
||||
|
||||
export let ACCEPT_LEGACY_V1 = coerceBoolean(
|
||||
runtimeFlags.ACCEPT_LEGACY_V1,
|
||||
DEFAULT_FLAGS.ACCEPT_LEGACY_V1
|
||||
);
|
||||
|
||||
export let WSS_TRACKERS = freezeTrackers(
|
||||
sanitizeTrackerList(runtimeFlags.WSS_TRACKERS)
|
||||
);
|
||||
|
||||
Object.defineProperty(runtimeFlags, "URL_FIRST_ENABLED", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get() {
|
||||
return URL_FIRST_ENABLED;
|
||||
},
|
||||
set(next) {
|
||||
URL_FIRST_ENABLED = coerceBoolean(next, DEFAULT_FLAGS.URL_FIRST_ENABLED);
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(runtimeFlags, "ACCEPT_LEGACY_V1", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get() {
|
||||
return ACCEPT_LEGACY_V1;
|
||||
},
|
||||
set(next) {
|
||||
ACCEPT_LEGACY_V1 = coerceBoolean(next, DEFAULT_FLAGS.ACCEPT_LEGACY_V1);
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(runtimeFlags, "WSS_TRACKERS", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get() {
|
||||
return [...WSS_TRACKERS];
|
||||
},
|
||||
set(next) {
|
||||
WSS_TRACKERS = freezeTrackers(sanitizeTrackerList(next));
|
||||
},
|
||||
});
|
||||
|
||||
// Ensure the runtime object reflects the sanitized defaults immediately.
|
||||
runtimeFlags.URL_FIRST_ENABLED = URL_FIRST_ENABLED;
|
||||
runtimeFlags.ACCEPT_LEGACY_V1 = ACCEPT_LEGACY_V1;
|
||||
runtimeFlags.WSS_TRACKERS = WSS_TRACKERS;
|
||||
|
||||
export function setUrlFirstEnabled(next) {
|
||||
runtimeFlags.URL_FIRST_ENABLED = next;
|
||||
return URL_FIRST_ENABLED;
|
||||
}
|
||||
|
||||
export function setAcceptLegacyV1(next) {
|
||||
runtimeFlags.ACCEPT_LEGACY_V1 = next;
|
||||
return ACCEPT_LEGACY_V1;
|
||||
}
|
||||
|
||||
export function setWssTrackers(next) {
|
||||
runtimeFlags.WSS_TRACKERS = next;
|
||||
return WSS_TRACKERS;
|
||||
}
|
||||
|
||||
export function resetRuntimeFlags() {
|
||||
setUrlFirstEnabled(DEFAULT_FLAGS.URL_FIRST_ENABLED);
|
||||
setAcceptLegacyV1(DEFAULT_FLAGS.ACCEPT_LEGACY_V1);
|
||||
setWssTrackers(DEFAULT_FLAGS.WSS_TRACKERS);
|
||||
}
|
||||
|
||||
export const RUNTIME_FLAGS = runtimeFlags;
|
||||
|
||||
+18
-6
@@ -2,17 +2,29 @@
|
||||
|
||||
class DisclaimerModal {
|
||||
constructor() {
|
||||
// Initialize elements when the disclaimer HTML is in the DOM.
|
||||
this.init();
|
||||
this.modal = null;
|
||||
this.acceptButton = null;
|
||||
this.acceptHandler = null;
|
||||
}
|
||||
|
||||
init() {
|
||||
this.modal = document.getElementById("disclaimerModal");
|
||||
this.acceptButton = document.getElementById("acceptDisclaimer");
|
||||
if (this.acceptButton) {
|
||||
this.acceptButton.addEventListener("click", () => {
|
||||
const nextAcceptButton = document.getElementById("acceptDisclaimer");
|
||||
|
||||
if (!this.acceptHandler) {
|
||||
this.acceptHandler = () => {
|
||||
this.hide();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
if (this.acceptButton && this.acceptHandler) {
|
||||
this.acceptButton.removeEventListener("click", this.acceptHandler);
|
||||
}
|
||||
|
||||
this.acceptButton = nextAcceptButton || null;
|
||||
|
||||
if (this.acceptButton && this.acceptHandler) {
|
||||
this.acceptButton.addEventListener("click", this.acceptHandler);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,625 @@
|
||||
import { infoHashFromMagnet } from "./magnets.js";
|
||||
import { TorrentClient, torrentClient } from "./webtorrent.js";
|
||||
|
||||
const containerState = new WeakMap();
|
||||
const ROOT_MARGIN = "200px 0px";
|
||||
|
||||
function now() {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function getCacheEntry(key) {
|
||||
if (!key) {
|
||||
return null;
|
||||
}
|
||||
const entry = probeCache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
if (now() - entry.ts > PROBE_CACHE_TTL_MS) {
|
||||
probeCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
function setCacheEntry(key, value) {
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
probeCache.set(key, { ts: now(), value });
|
||||
}
|
||||
|
||||
function formatTime(ts) {
|
||||
if (!Number.isFinite(ts)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return new Date(ts).toLocaleTimeString([], { hour12: false });
|
||||
} catch (err) {
|
||||
return new Date(ts).toLocaleTimeString();
|
||||
}
|
||||
}
|
||||
|
||||
function buildTooltip({ peers = 0, checkedAt, reason } = {}) {
|
||||
const parts = [];
|
||||
if (Number.isFinite(peers)) {
|
||||
parts.push(`Peers: ${Math.max(0, peers)}`);
|
||||
}
|
||||
if (Number.isFinite(checkedAt)) {
|
||||
const formatted = formatTime(checkedAt);
|
||||
if (formatted) {
|
||||
parts.push(`Checked ${formatted}`);
|
||||
}
|
||||
}
|
||||
if (typeof reason === "string" && reason && reason !== "peer") {
|
||||
let normalizedReason;
|
||||
if (reason === "timeout") {
|
||||
normalizedReason = "Timed out";
|
||||
} else if (reason === "no-trackers") {
|
||||
normalizedReason = "No WSS trackers";
|
||||
} else if (reason === "invalid") {
|
||||
normalizedReason = "Invalid magnet";
|
||||
} else {
|
||||
normalizedReason = reason.charAt(0).toUpperCase() + reason.slice(1);
|
||||
}
|
||||
parts.push(normalizedReason);
|
||||
}
|
||||
if (!parts.length) {
|
||||
return "WebTorrent status unknown";
|
||||
}
|
||||
return `WebTorrent • ${parts.join(" • ")}`;
|
||||
}
|
||||
|
||||
function normalizeResult(result) {
|
||||
const fallback = {
|
||||
healthy: false,
|
||||
peers: 0,
|
||||
reason: "error",
|
||||
appendedTrackers: false,
|
||||
hasProbeTrackers: false,
|
||||
usedTrackers: Array.isArray(TorrentClient.PROBE_TRACKERS)
|
||||
? [...TorrentClient.PROBE_TRACKERS]
|
||||
: [],
|
||||
durationMs: 0,
|
||||
};
|
||||
if (!result || typeof result !== "object") {
|
||||
return { ...fallback, checkedAt: now() };
|
||||
}
|
||||
const peers = Number.isFinite(result.peers)
|
||||
? Math.max(0, Number(result.peers))
|
||||
: 0;
|
||||
const healthy = Boolean(result.healthy) && peers > 0;
|
||||
const reason = typeof result.reason === "string" ? result.reason : "error";
|
||||
return {
|
||||
healthy,
|
||||
peers: healthy ? Math.max(1, peers) : peers,
|
||||
reason,
|
||||
appendedTrackers: Boolean(result.appendedTrackers),
|
||||
hasProbeTrackers:
|
||||
typeof result.hasProbeTrackers === "boolean"
|
||||
? result.hasProbeTrackers
|
||||
: healthy || Boolean(result.appendedTrackers),
|
||||
usedTrackers: Array.isArray(result.usedTrackers)
|
||||
? result.usedTrackers.slice()
|
||||
: fallback.usedTrackers,
|
||||
durationMs: Number.isFinite(result.durationMs)
|
||||
? Math.max(0, Number(result.durationMs))
|
||||
: 0,
|
||||
checkedAt: now(),
|
||||
};
|
||||
}
|
||||
|
||||
function queueProbe(magnet, cacheKey, priority = 0) {
|
||||
if (!magnet) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
const cached = getCacheEntry(cacheKey);
|
||||
if (cached) {
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
|
||||
if (probeInflight.has(cacheKey)) {
|
||||
return probeInflight.get(cacheKey);
|
||||
}
|
||||
|
||||
const job = probeQueue
|
||||
.run(
|
||||
() =>
|
||||
torrentClient
|
||||
.probePeers(magnet, {
|
||||
timeoutMs: PROBE_TIMEOUT_MS,
|
||||
maxWebConns: 2,
|
||||
polls: PROBE_POLL_COUNT,
|
||||
})
|
||||
.catch((err) => ({
|
||||
healthy: false,
|
||||
peers: 0,
|
||||
reason: "error",
|
||||
error: err,
|
||||
appendedTrackers: false,
|
||||
hasProbeTrackers: false,
|
||||
})),
|
||||
priority
|
||||
)
|
||||
.then((result) => {
|
||||
const normalized = normalizeResult(result);
|
||||
if (cacheKey) {
|
||||
setCacheEntry(cacheKey, normalized);
|
||||
}
|
||||
return normalized;
|
||||
})
|
||||
.finally(() => {
|
||||
if (cacheKey) {
|
||||
probeInflight.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
|
||||
if (cacheKey) {
|
||||
probeInflight.set(cacheKey, job);
|
||||
}
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
const PROBE_CACHE_TTL_MS = 5 * 60 * 1000;
|
||||
const PROBE_TIMEOUT_MS = 8000;
|
||||
const PROBE_CONCURRENCY = 96;
|
||||
const PROBE_POLL_COUNT = 3;
|
||||
const PRIORITY_BASELINE = 1_000_000;
|
||||
|
||||
class ProbeQueue {
|
||||
constructor(max = 2) {
|
||||
this.max = Math.max(1, Number(max) || 1);
|
||||
this.running = 0;
|
||||
this.queue = [];
|
||||
}
|
||||
|
||||
run(task, priority = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const normalizedPriority = Number.isFinite(priority) ? priority : 0;
|
||||
const job = {
|
||||
task,
|
||||
resolve,
|
||||
reject,
|
||||
priority: normalizedPriority,
|
||||
};
|
||||
this.enqueue(job);
|
||||
this.drain();
|
||||
});
|
||||
}
|
||||
|
||||
enqueue(job) {
|
||||
if (!this.queue.length) {
|
||||
this.queue.push(job);
|
||||
return;
|
||||
}
|
||||
const index = this.queue.findIndex(
|
||||
(existing) => existing.priority < job.priority
|
||||
);
|
||||
if (index === -1) {
|
||||
this.queue.push(job);
|
||||
} else {
|
||||
this.queue.splice(index, 0, job);
|
||||
}
|
||||
}
|
||||
|
||||
drain() {
|
||||
while (this.running < this.max && this.queue.length > 0) {
|
||||
const job = this.queue.shift();
|
||||
if (!job) {
|
||||
return;
|
||||
}
|
||||
this.running += 1;
|
||||
let finished = false;
|
||||
const finalize = () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
this.running -= 1;
|
||||
this.drain();
|
||||
};
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = job.task();
|
||||
} catch (err) {
|
||||
job.reject(err);
|
||||
finalize();
|
||||
continue;
|
||||
}
|
||||
|
||||
Promise.resolve(result)
|
||||
.then((value) => {
|
||||
job.resolve(value);
|
||||
})
|
||||
.catch((err) => {
|
||||
job.reject(err);
|
||||
})
|
||||
.finally(() => {
|
||||
finalize();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const probeQueue = new ProbeQueue(PROBE_CONCURRENCY);
|
||||
const probeCache = new Map();
|
||||
const probeInflight = new Map();
|
||||
|
||||
function ensureState(container) {
|
||||
let state = containerState.get(container);
|
||||
if (state) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const pendingByCard = new WeakMap();
|
||||
const observedCards = new WeakSet();
|
||||
state = { observer: null, pendingByCard, observedCards };
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
processObserverEntries(entries, state);
|
||||
},
|
||||
{ root: null, rootMargin: ROOT_MARGIN, threshold: 0.01 }
|
||||
);
|
||||
|
||||
state.observer = observer;
|
||||
containerState.set(container, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
function getViewportCenter() {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
const width = Number(window.innerWidth) || 0;
|
||||
const height = Number(window.innerHeight) || 0;
|
||||
if (width <= 0 && height <= 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
x: width > 0 ? width / 2 : 0,
|
||||
y: height > 0 ? height / 2 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function prioritizeEntries(entries, viewportCenter) {
|
||||
if (!Array.isArray(entries) || entries.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const filtered = entries
|
||||
.filter((entry) => entry.isIntersecting && entry.target instanceof HTMLElement)
|
||||
.map((entry) => {
|
||||
const rect = getIntersectionRect(entry);
|
||||
if (!rect) {
|
||||
return null;
|
||||
}
|
||||
const ratio =
|
||||
typeof entry.intersectionRatio === "number" ? entry.intersectionRatio : 0;
|
||||
const centerY = rect.top + rect.height / 2;
|
||||
const verticalDistance = viewportCenter
|
||||
? Math.abs(centerY - viewportCenter.y)
|
||||
: Number.POSITIVE_INFINITY;
|
||||
return { entry, ratio, centerY, verticalDistance };
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!viewportCenter) {
|
||||
return filtered
|
||||
.sort((a, b) => {
|
||||
if (b.ratio !== a.ratio) {
|
||||
return b.ratio - a.ratio;
|
||||
}
|
||||
return a.centerY - b.centerY;
|
||||
})
|
||||
.map((item, index) => ({
|
||||
entry: item.entry,
|
||||
priority: PRIORITY_BASELINE - index,
|
||||
}));
|
||||
}
|
||||
|
||||
const ordered = filtered
|
||||
.slice()
|
||||
.sort((a, b) => a.centerY - b.centerY);
|
||||
|
||||
let centerIndex = 0;
|
||||
let minDistance = Number.POSITIVE_INFINITY;
|
||||
for (let i = 0; i < ordered.length; i += 1) {
|
||||
const candidate = ordered[i];
|
||||
if (candidate.verticalDistance < minDistance) {
|
||||
minDistance = candidate.verticalDistance;
|
||||
centerIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
const prioritized = [];
|
||||
const pushCandidate = (candidate) => {
|
||||
if (!candidate) {
|
||||
return;
|
||||
}
|
||||
prioritized.push(candidate);
|
||||
};
|
||||
|
||||
pushCandidate(ordered[centerIndex]);
|
||||
|
||||
let left = centerIndex - 1;
|
||||
let right = centerIndex + 1;
|
||||
while (left >= 0 || right < ordered.length) {
|
||||
const leftCandidate = left >= 0 ? ordered[left] : null;
|
||||
const rightCandidate = right < ordered.length ? ordered[right] : null;
|
||||
|
||||
if (leftCandidate && rightCandidate) {
|
||||
const leftDistance = leftCandidate.verticalDistance;
|
||||
const rightDistance = rightCandidate.verticalDistance;
|
||||
const distanceDelta = Math.abs(leftDistance - rightDistance);
|
||||
if (distanceDelta <= 0.5) {
|
||||
if (rightCandidate.ratio > leftCandidate.ratio) {
|
||||
pushCandidate(rightCandidate);
|
||||
right += 1;
|
||||
} else {
|
||||
pushCandidate(leftCandidate);
|
||||
left -= 1;
|
||||
}
|
||||
} else if (leftDistance < rightDistance) {
|
||||
pushCandidate(leftCandidate);
|
||||
left -= 1;
|
||||
} else {
|
||||
pushCandidate(rightCandidate);
|
||||
right += 1;
|
||||
}
|
||||
} else if (rightCandidate) {
|
||||
pushCandidate(rightCandidate);
|
||||
right += 1;
|
||||
} else if (leftCandidate) {
|
||||
pushCandidate(leftCandidate);
|
||||
left -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
return prioritized.map((candidate, index) => ({
|
||||
entry: candidate.entry,
|
||||
priority: PRIORITY_BASELINE - index,
|
||||
}));
|
||||
}
|
||||
|
||||
function processObserverEntries(entries, state) {
|
||||
if (!state || !entries || entries.length === 0) {
|
||||
return;
|
||||
}
|
||||
const viewportCenter = getViewportCenter();
|
||||
const prioritized = prioritizeEntries(entries, viewportCenter);
|
||||
prioritized.forEach(({ entry, priority }) => {
|
||||
const card = entry.target;
|
||||
handleCardVisible({ card, pendingByCard: state.pendingByCard, priority });
|
||||
});
|
||||
}
|
||||
|
||||
function getIntersectionRect(entry) {
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
const rect = entry.intersectionRect;
|
||||
if (rect && rect.width > 0 && rect.height > 0) {
|
||||
return rect;
|
||||
}
|
||||
const fallback = entry.boundingClientRect;
|
||||
if (fallback && fallback.width > 0 && fallback.height > 0) {
|
||||
return fallback;
|
||||
}
|
||||
return rect || fallback || null;
|
||||
}
|
||||
|
||||
function setBadge(card, state, details) {
|
||||
if (!(card instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedState =
|
||||
typeof state === "string" && state ? state : "unknown";
|
||||
const peersValue =
|
||||
details && Number.isFinite(details.peers)
|
||||
? Math.max(0, Number(details.peers))
|
||||
: 0;
|
||||
const hasPeerCount = details ? Number.isFinite(details.peers) : false;
|
||||
const peersTextValue = hasPeerCount ? String(peersValue) : "";
|
||||
|
||||
card.dataset.streamHealthState = normalizedState;
|
||||
if (hasPeerCount) {
|
||||
card.dataset.streamHealthPeers = peersTextValue;
|
||||
} else if (card.dataset.streamHealthPeers) {
|
||||
delete card.dataset.streamHealthPeers;
|
||||
}
|
||||
|
||||
if (details && typeof details.reason === "string" && details.reason) {
|
||||
card.dataset.streamHealthReason = details.reason;
|
||||
} else if (card.dataset.streamHealthReason) {
|
||||
delete card.dataset.streamHealthReason;
|
||||
}
|
||||
|
||||
const badge = card.querySelector(".torrent-health-badge");
|
||||
if (!badge) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hadMargin = badge.classList.contains("mt-3");
|
||||
|
||||
const baseClasses = [
|
||||
"torrent-health-badge",
|
||||
"text-xs",
|
||||
"font-semibold",
|
||||
"px-2",
|
||||
"py-1",
|
||||
"rounded",
|
||||
"inline-flex",
|
||||
"items-center",
|
||||
"gap-1",
|
||||
"transition-colors",
|
||||
"duration-200",
|
||||
];
|
||||
if (hadMargin) {
|
||||
baseClasses.unshift("mt-3");
|
||||
}
|
||||
badge.className = baseClasses.join(" ");
|
||||
|
||||
const map = {
|
||||
healthy: {
|
||||
icon: "🟢",
|
||||
aria: "WebTorrent peers available",
|
||||
classes: ["bg-green-900", "text-green-200"],
|
||||
role: "status",
|
||||
},
|
||||
unhealthy: {
|
||||
icon: "🔴",
|
||||
aria: "WebTorrent peers unavailable",
|
||||
classes: ["bg-red-900", "text-red-200"],
|
||||
role: "alert",
|
||||
},
|
||||
checking: {
|
||||
icon: "⏳",
|
||||
aria: "Checking WebTorrent peers",
|
||||
classes: ["bg-gray-800", "text-gray-300"],
|
||||
role: "status",
|
||||
},
|
||||
unknown: {
|
||||
icon: "⚪",
|
||||
aria: "WebTorrent status unknown",
|
||||
classes: ["bg-gray-800", "text-gray-300"],
|
||||
role: "status",
|
||||
},
|
||||
};
|
||||
|
||||
const entry = map[normalizedState] || map.unknown;
|
||||
entry.classes.forEach((cls) => badge.classList.add(cls));
|
||||
|
||||
const peersText =
|
||||
normalizedState === "healthy" && peersValue > 0 ? ` (${peersValue})` : "";
|
||||
|
||||
const iconPrefix = entry.icon ? `${entry.icon} ` : "";
|
||||
badge.textContent = `${iconPrefix}WebTorrent${peersText}`;
|
||||
const tooltip =
|
||||
normalizedState === "checking" || normalizedState === "unknown"
|
||||
? entry.aria
|
||||
: buildTooltip({
|
||||
peers: peersValue,
|
||||
checkedAt: details?.checkedAt,
|
||||
reason: details?.reason,
|
||||
});
|
||||
badge.setAttribute("aria-label", tooltip);
|
||||
badge.setAttribute("title", tooltip);
|
||||
badge.setAttribute("aria-live", entry.role === "alert" ? "assertive" : "polite");
|
||||
badge.setAttribute("role", entry.role);
|
||||
badge.dataset.streamHealthState = normalizedState;
|
||||
if (hasPeerCount) {
|
||||
badge.dataset.streamHealthPeers = peersTextValue;
|
||||
} else if (badge.dataset.streamHealthPeers) {
|
||||
delete badge.dataset.streamHealthPeers;
|
||||
}
|
||||
}
|
||||
|
||||
function handleCardVisible({ card, pendingByCard, priority = 0 }) {
|
||||
if (!(card instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const magnet = card.dataset.magnet || "";
|
||||
if (!magnet) {
|
||||
setBadge(card, "unhealthy", { reason: "missing-source" });
|
||||
return;
|
||||
}
|
||||
|
||||
const infoHash = infoHashFromMagnet(magnet);
|
||||
if (!infoHash) {
|
||||
setBadge(card, "unhealthy", { reason: "invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pendingByCard.has(card)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = getCacheEntry(infoHash);
|
||||
if (cached) {
|
||||
const cachedState = cached.healthy
|
||||
? "healthy"
|
||||
: cached.hasProbeTrackers
|
||||
? "unhealthy"
|
||||
: "unknown";
|
||||
setBadge(card, cachedState, cached);
|
||||
return;
|
||||
}
|
||||
|
||||
setBadge(card, "checking");
|
||||
|
||||
const probePromise = queueProbe(magnet, infoHash, priority);
|
||||
|
||||
pendingByCard.set(card, probePromise);
|
||||
|
||||
probePromise
|
||||
.then((result) => {
|
||||
pendingByCard.delete(card);
|
||||
if (!card.isConnected) {
|
||||
return;
|
||||
}
|
||||
if (!result) {
|
||||
setBadge(card, "unknown");
|
||||
return;
|
||||
}
|
||||
if (!result.hasProbeTrackers) {
|
||||
setBadge(card, "unknown", result);
|
||||
return;
|
||||
}
|
||||
if (result.healthy) {
|
||||
setBadge(card, "healthy", result);
|
||||
return;
|
||||
}
|
||||
setBadge(card, "unhealthy", result);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn("[gridHealth] probe failed", err);
|
||||
pendingByCard.delete(card);
|
||||
if (!card.isConnected) {
|
||||
return;
|
||||
}
|
||||
setBadge(card, "unhealthy");
|
||||
});
|
||||
}
|
||||
|
||||
export function attachHealthBadges(container) {
|
||||
if (!(container instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const state = ensureState(container);
|
||||
const cards = container.querySelectorAll(".video-card");
|
||||
cards.forEach((card) => {
|
||||
if (!(card instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
if (state.observedCards.has(card)) {
|
||||
return;
|
||||
}
|
||||
state.observedCards.add(card);
|
||||
state.observer.observe(card);
|
||||
if (!card.dataset.magnet) {
|
||||
setBadge(card, "unhealthy", { reason: "missing-source" });
|
||||
}
|
||||
});
|
||||
processObserverEntries(state.observer.takeRecords(), state);
|
||||
}
|
||||
|
||||
export function refreshHealthBadges(container) {
|
||||
if (!(container instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const state = containerState.get(container);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
const records = state.observer.takeRecords();
|
||||
processObserverEntries(records, state);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import PQueue from "https://esm.sh/[email protected]";
|
||||
import { trackerPing } from "./trackerPing.js";
|
||||
import { infoHashFromMagnet } from "./magnets.js";
|
||||
import { HEALTH_TTL_MS, CONCURRENCY } from "./trackerConfig.js";
|
||||
|
||||
const queue = new PQueue({ concurrency: CONCURRENCY });
|
||||
const cache = new Map();
|
||||
const inflight = new Map();
|
||||
|
||||
export function getDefaultHealth() {
|
||||
return {
|
||||
ok: false,
|
||||
seeders: 0,
|
||||
leechers: 0,
|
||||
responded: false,
|
||||
from: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function getHealthCached(infoHash) {
|
||||
if (!infoHash) {
|
||||
return null;
|
||||
}
|
||||
const entry = cache.get(infoHash);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
if (Date.now() - entry.ts > HEALTH_TTL_MS) {
|
||||
cache.delete(infoHash);
|
||||
return null;
|
||||
}
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
export function setHealthCache(infoHash, value) {
|
||||
if (!infoHash) {
|
||||
return;
|
||||
}
|
||||
cache.set(infoHash, { ts: Date.now(), value });
|
||||
}
|
||||
|
||||
export function queueHealthCheck(magnet, onResult) {
|
||||
const infoHash = infoHashFromMagnet(magnet);
|
||||
if (!infoHash) {
|
||||
const fallback = getDefaultHealth();
|
||||
if (typeof onResult === "function") {
|
||||
onResult(fallback);
|
||||
}
|
||||
return Promise.resolve(fallback);
|
||||
}
|
||||
|
||||
const cached = getHealthCached(infoHash);
|
||||
if (cached) {
|
||||
if (typeof onResult === "function") {
|
||||
onResult(cached);
|
||||
}
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
|
||||
if (inflight.has(infoHash)) {
|
||||
const pending = inflight.get(infoHash);
|
||||
if (typeof onResult === "function") {
|
||||
pending.then(onResult).catch(() => {});
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
const jobPromise = queue
|
||||
.add(async () => {
|
||||
try {
|
||||
const health = await trackerPing(magnet);
|
||||
setHealthCache(infoHash, health);
|
||||
return health;
|
||||
} catch (err) {
|
||||
console.warn("trackerPing failed", err);
|
||||
return getDefaultHealth();
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(infoHash);
|
||||
});
|
||||
|
||||
inflight.set(infoHash, jobPromise);
|
||||
if (typeof onResult === "function") {
|
||||
jobPromise.then(onResult).catch(() => {});
|
||||
}
|
||||
return jobPromise;
|
||||
}
|
||||
|
||||
export function purgeHealthCache() {
|
||||
const now = Date.now();
|
||||
Array.from(cache.keys()).forEach((infoHash) => {
|
||||
const entry = cache.get(infoHash);
|
||||
if (!entry || now - entry.ts > HEALTH_TTL_MS) {
|
||||
cache.delete(infoHash);
|
||||
}
|
||||
});
|
||||
}
|
||||
+78
-10
@@ -1,5 +1,64 @@
|
||||
// js/index.js
|
||||
|
||||
import "./bufferPolyfill.js";
|
||||
import { trackPageView } from "./analytics.js";
|
||||
|
||||
const INTERFACE_FADE_IN_ANIMATION = "interface-fade-in";
|
||||
const VIDEO_THUMBNAIL_FADE_IN_ANIMATION = "video-thumbnail-fade-in";
|
||||
|
||||
//
|
||||
// Centralized animation cleanup
|
||||
// ------------------------------
|
||||
// We attach a single capture-phase listener for animation events so that any
|
||||
// chrome element or thumbnail using our fade-in helpers can automatically shed
|
||||
// the temporary classes/data attributes that trigger the transition. This is
|
||||
// critical because these DOM nodes frequently persist while the surrounding
|
||||
// lists re-render; if the classes stick around, future layout shuffles would
|
||||
// replay the fade and make the UI flicker. Clearing the hooks immediately after
|
||||
// the first animation keeps the graceful entrance without introducing future
|
||||
// flashes.
|
||||
const handleFadeInAnimationComplete = (event) => {
|
||||
const { animationName, target } = event;
|
||||
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (animationName === INTERFACE_FADE_IN_ANIMATION) {
|
||||
if (!target.classList.contains("fade-in")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove the transient fade-in class so future renders keep the element
|
||||
// visible. The delays piggyback on `fade-in`, so we strip those too.
|
||||
target.classList.remove("fade-in");
|
||||
Array.from(target.classList).forEach((className) => {
|
||||
if (className.startsWith("fade-in-delay-")) {
|
||||
target.classList.remove(className);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (animationName !== VIDEO_THUMBNAIL_FADE_IN_ANIMATION) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
target.dataset &&
|
||||
target.dataset.videoThumbnail === "true" &&
|
||||
target.dataset.thumbnailLoaded === "true"
|
||||
) {
|
||||
// Thumbnails use the same pattern: once the fade finishes we clear the flag
|
||||
// so a later `load` event (or template reuse) does not restart the
|
||||
// animation.
|
||||
delete target.dataset.thumbnailLoaded;
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("animationend", handleFadeInAnimationComplete, true);
|
||||
document.addEventListener("animationcancel", handleFadeInAnimationComplete, true);
|
||||
|
||||
// 1) Load modals (login, application, etc.)
|
||||
async function loadModal(url) {
|
||||
try {
|
||||
@@ -8,9 +67,14 @@ async function loadModal(url) {
|
||||
throw new Error("Failed to load " + url);
|
||||
}
|
||||
const html = await response.text();
|
||||
// Remove analytics loader tags from modal partials to avoid duplicate pageview events.
|
||||
const sanitizedHtml = html.replace(
|
||||
/<script\b[^>]*src=["'][^"']*tracking\.js[^"']*["'][^>]*>\s*<\/script>/gi,
|
||||
""
|
||||
);
|
||||
document
|
||||
.getElementById("modalContainer")
|
||||
.insertAdjacentHTML("beforeend", html);
|
||||
.insertAdjacentHTML("beforeend", sanitizedHtml);
|
||||
console.log(url, "loaded");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -171,6 +235,12 @@ Promise.all([
|
||||
|
||||
// Also run once on initial load
|
||||
handleHashChange();
|
||||
|
||||
return import("./disclaimer.js");
|
||||
})
|
||||
.then(({ default: disclaimerModal }) => {
|
||||
disclaimerModal.init();
|
||||
disclaimerModal.show();
|
||||
});
|
||||
|
||||
/* -------------------------------------------
|
||||
@@ -292,9 +362,6 @@ function handleQueryParams() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle #view=... in the hash and load the correct partial view.
|
||||
*/
|
||||
function handleHashChange() {
|
||||
console.log("handleHashChange called, current hash =", window.location.hash);
|
||||
|
||||
@@ -311,6 +378,7 @@ function handleHashChange() {
|
||||
if (typeof initFn === "function") {
|
||||
initFn();
|
||||
}
|
||||
recordView("most-recent-videos");
|
||||
});
|
||||
});
|
||||
return;
|
||||
@@ -321,11 +389,11 @@ function handleHashChange() {
|
||||
|
||||
// Now dynamically load that partial, then call its init function
|
||||
import("./viewManager.js").then(({ loadView, viewInitRegistry }) => {
|
||||
loadView(viewUrl).then(() => {
|
||||
const initFn = viewInitRegistry[viewName];
|
||||
if (typeof initFn === "function") {
|
||||
initFn();
|
||||
}
|
||||
});
|
||||
loadView(viewUrl).then(() => {
|
||||
const initFn = viewInitRegistry[viewName];
|
||||
if (typeof initFn === "function") {
|
||||
initFn();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
+6
-21
@@ -1,25 +1,10 @@
|
||||
// js/lists.js
|
||||
|
||||
// Whitelist of npubs that can access the video upload functions
|
||||
const npubs = [
|
||||
"npub13yarr7j6vjqjjkahd63dmr27curypehx45ucue286ac7sft27y0srnpmpe", // bitvid
|
||||
"npub15jnttpymeytm80hatjqcvhhqhzrhx6gxp8pq0wn93rhnu8s9h9dsha32lx", // thePR0M3TH3AN
|
||||
"npub1j37gc05qpqzyrmdc5vetsc9h5qtstas7tr25j0n9sdpqxghz6m4q2ej6n8", // Ghost Grid Network
|
||||
"npub1epvnvv3kskvpnmpqgnm2atevsmdferhp7dg2s0yc7uc0hdmqmgssx09tu2", // Chain Reaction
|
||||
"npub1qny3tkh0acurzla8x3zy4nhrjz5zd8l9sy9jys09umwng00manysew95gx", // ODELL
|
||||
"npub1qxduthz4p8v5zsux524df569pt7lj0d36dyqadnta2val64dtnhsr50h64", // NosToons
|
||||
"npub19ma2w9dmk3kat0nt0k5dwuqzvmg3va9ezwup0zkakhpwv0vcwvcsg8axkl", // vinney
|
||||
"npub1rcr8h76csgzhdhea4a7tq5w5gydcpg9clgf0cffu6z45rnc6yp5sj7cfuz", // djmeistro
|
||||
"npub1m5s9w4t03znyetxswhgq0ud7fq8ef8y3l4kscn2e8wkvmv42hh3qujgjl3", // mister_monster
|
||||
"npub13qexjtmajssuhz8gdchgx65dwsnr705drse294zz5vt4e78ya2vqzyg8lv", // SatoshiSignal
|
||||
"npub1da7m2ksdj24995hm8afv88pjpvzt6t9vh70mg8t52yjwtxza3vjszyar58", // GoblinBox
|
||||
];
|
||||
|
||||
console.log("DEBUG: lists.js loaded, npubs:", npubs);
|
||||
|
||||
// Blacklist of npubs that events will not be displayed in the bitvid official client
|
||||
export const initialWhitelist = npubs;
|
||||
export const initialBlacklist = [""];
|
||||
// Operators must manage admin lists through the Admin panel UI or remote
|
||||
// adapters. These legacy constants are intentionally empty so new installs do
|
||||
// not ship with hard-coded accounts.
|
||||
export const ADMIN_INITIAL_WHITELIST = [];
|
||||
export const ADMIN_INITIAL_BLACKLIST = [];
|
||||
|
||||
// Block specific events with the nevent
|
||||
export const initialEventBlacklist = [""];
|
||||
export const ADMIN_INITIAL_EVENT_BLACKLIST = [];
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
import { WSS_TRACKERS } from "./constants.js";
|
||||
|
||||
const HEX_INFO_HASH = /^[0-9a-f]{40}$/i;
|
||||
const ENCODED_BTih_PATTERN = /xt=urn%3Abtih%3A([0-9a-z]+)/gi;
|
||||
|
||||
function getOriginProtocol() {
|
||||
if (typeof window !== "undefined" && window.location?.protocol) {
|
||||
return window.location.protocol.toLowerCase();
|
||||
}
|
||||
return "https:";
|
||||
}
|
||||
|
||||
function decodeLoose(value) {
|
||||
if (typeof value !== "string") {
|
||||
return "";
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(trimmed);
|
||||
} catch (err) {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeForComparison(value) {
|
||||
if (typeof value !== "string") {
|
||||
return "";
|
||||
}
|
||||
return value.trim().replace(/\/+$/, "").toLowerCase();
|
||||
}
|
||||
|
||||
function tryFormatAbsoluteUrl(candidate) {
|
||||
if (typeof candidate !== "string") {
|
||||
return "";
|
||||
}
|
||||
const trimmed = candidate.trim();
|
||||
if (!trimmed) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
return parsed.toString();
|
||||
} catch (err) {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize and enrich a magnet string entered in the upload form so that it
|
||||
* always produces a WebTorrent-friendly URI. The logic mirrors the behaviour of
|
||||
* the legacy magnetUtils helper but returns a plain string for ease of use.
|
||||
*/
|
||||
export function normalizeAndAugmentMagnet(rawValue, { ws = "", xs = "" } = {}) {
|
||||
const initial = typeof rawValue === "string" ? rawValue.trim() : "";
|
||||
if (!initial) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let working = initial;
|
||||
|
||||
if (HEX_INFO_HASH.test(working)) {
|
||||
working = `magnet:?xt=urn:btih:${working.toLowerCase()}`;
|
||||
}
|
||||
|
||||
working = working.replace(ENCODED_BTih_PATTERN, (_, hash) => `xt=urn:btih:${hash}`);
|
||||
|
||||
if (!/^magnet:/i.test(working)) {
|
||||
return working;
|
||||
}
|
||||
|
||||
let fragment = "";
|
||||
const hashIndex = working.indexOf("#");
|
||||
if (hashIndex !== -1) {
|
||||
fragment = working.slice(hashIndex);
|
||||
working = working.slice(0, hashIndex);
|
||||
}
|
||||
|
||||
const [, queryPart = ""] = working.split("?", 2);
|
||||
const normalizedScheme = "magnet:";
|
||||
const rawParams = queryPart
|
||||
.split("&")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const params = [];
|
||||
|
||||
for (const rawParam of rawParams) {
|
||||
const [rawKey, rawVal = ""] = rawParam.split("=", 2);
|
||||
const key = rawKey.trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
let value = rawVal.trim();
|
||||
if (key.toLowerCase() === "xt" && value) {
|
||||
const decoded = decodeLoose(value);
|
||||
if (decoded) {
|
||||
value = decoded;
|
||||
}
|
||||
}
|
||||
params.push({
|
||||
key,
|
||||
value,
|
||||
lowerKey: key.toLowerCase(),
|
||||
compareValue: normalizeForComparison(value),
|
||||
});
|
||||
}
|
||||
|
||||
const appendUniqueParam = (key, value) => {
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
const trimmedValue = value.trim();
|
||||
if (!trimmedValue) {
|
||||
return;
|
||||
}
|
||||
const lowerKey = key.toLowerCase();
|
||||
const compareValue = normalizeForComparison(trimmedValue);
|
||||
if (compareValue) {
|
||||
const exists = params.some(
|
||||
(param) => param.lowerKey === lowerKey && param.compareValue === compareValue
|
||||
);
|
||||
if (exists) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
params.push({
|
||||
key,
|
||||
value: trimmedValue,
|
||||
lowerKey,
|
||||
compareValue,
|
||||
});
|
||||
};
|
||||
|
||||
for (const tracker of WSS_TRACKERS) {
|
||||
if (typeof tracker !== "string") {
|
||||
continue;
|
||||
}
|
||||
const trimmedTracker = tracker.trim();
|
||||
if (!/^wss:\/\//i.test(trimmedTracker)) {
|
||||
continue;
|
||||
}
|
||||
appendUniqueParam("tr", trimmedTracker);
|
||||
}
|
||||
|
||||
const normalizedXs = typeof xs === "string" ? xs.trim() : "";
|
||||
if (normalizedXs) {
|
||||
appendUniqueParam("xs", normalizedXs);
|
||||
}
|
||||
|
||||
const originProtocol = getOriginProtocol();
|
||||
const rawWs = typeof ws === "string" ? ws.trim() : "";
|
||||
if (rawWs) {
|
||||
const formattedWs = tryFormatAbsoluteUrl(rawWs);
|
||||
const lowerWs = formattedWs.toLowerCase();
|
||||
const isHttpSeed = lowerWs.startsWith("http://");
|
||||
const allowHttpSeed = originProtocol === "http:";
|
||||
if (!isHttpSeed || allowHttpSeed) {
|
||||
appendUniqueParam("ws", formattedWs);
|
||||
}
|
||||
}
|
||||
|
||||
const queryString = params
|
||||
.map(({ key, value }) => (value ? `${key}=${value}` : key))
|
||||
.join("&");
|
||||
|
||||
return `${normalizedScheme}${queryString ? `?${queryString}` : ""}${fragment}`;
|
||||
}
|
||||
|
||||
export function extractMagnetHints(rawValue) {
|
||||
const hints = { ws: "", xs: "" };
|
||||
if (typeof rawValue !== "string") {
|
||||
return hints;
|
||||
}
|
||||
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed || !trimmed.toLowerCase().startsWith("magnet:")) {
|
||||
return hints;
|
||||
}
|
||||
|
||||
const queryIndex = trimmed.indexOf("?");
|
||||
if (queryIndex === -1 || queryIndex === trimmed.length - 1) {
|
||||
return hints;
|
||||
}
|
||||
|
||||
const query = trimmed.slice(queryIndex + 1);
|
||||
if (!query) {
|
||||
return hints;
|
||||
}
|
||||
|
||||
const parts = query.split("&");
|
||||
for (const part of parts) {
|
||||
if (!part) {
|
||||
continue;
|
||||
}
|
||||
const [rawKey, rawValue = ""] = part.split("=", 2);
|
||||
if (!rawKey) {
|
||||
continue;
|
||||
}
|
||||
const lowerKey = rawKey.trim().toLowerCase();
|
||||
if (lowerKey !== "ws" && lowerKey !== "xs") {
|
||||
continue;
|
||||
}
|
||||
if (hints[lowerKey]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let decoded = rawValue;
|
||||
try {
|
||||
decoded = decodeURIComponent(rawValue);
|
||||
} catch (err) {
|
||||
// Ignore decode errors and use the raw value.
|
||||
}
|
||||
const clean = typeof decoded === "string" ? decoded.trim() : "";
|
||||
if (!clean) {
|
||||
continue;
|
||||
}
|
||||
hints[lowerKey] = clean;
|
||||
}
|
||||
|
||||
return hints;
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
// js/magnetUtils.js
|
||||
|
||||
import { WSS_TRACKERS } from "./constants.js";
|
||||
|
||||
export { WSS_TRACKERS };
|
||||
|
||||
const HEX_INFO_HASH = /^[0-9a-f]{40}$/i;
|
||||
const BTIH_PREFIX = "urn:btih:";
|
||||
const ENCODED_BTih_PATTERN = /xt=urn%3Abtih%3A([0-9a-z]+)/gi;
|
||||
|
||||
function normalizeForComparison(value) {
|
||||
if (typeof value !== "string") {
|
||||
return "";
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
const pathname = parsed.pathname.replace(/\/?$/, "");
|
||||
const normalizedPath = pathname ? pathname : "";
|
||||
return (
|
||||
`${parsed.protocol}//${parsed.host}${normalizedPath}${parsed.search}${parsed.hash}`
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
);
|
||||
} catch (err) {
|
||||
return trimmed.replace(/\/?$/, "").toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeHttpUrl(candidate) {
|
||||
if (typeof candidate !== "string") {
|
||||
return "";
|
||||
}
|
||||
const trimmed = candidate.trim();
|
||||
if (!trimmed) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
if (parsed.protocol === "http:" || parsed.protocol === "https:") {
|
||||
return parsed.toString();
|
||||
}
|
||||
} catch (err) {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function safeDecodeMagnet(value) {
|
||||
if (typeof value !== "string") {
|
||||
return "";
|
||||
}
|
||||
|
||||
let decoded = value.trim();
|
||||
if (!decoded) {
|
||||
return "";
|
||||
}
|
||||
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
if (!decoded.includes("%")) {
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const candidate = decodeURIComponent(decoded);
|
||||
if (!candidate) {
|
||||
break;
|
||||
}
|
||||
if (candidate === decoded) {
|
||||
break;
|
||||
}
|
||||
decoded = candidate.trim();
|
||||
} catch (err) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a magnet URI while preserving legacy payload quirks and augmenting it
|
||||
* for browser playback.
|
||||
*
|
||||
* Key behaviors:
|
||||
* - Accepts bare info-hash strings and promotes them to full `magnet:?xt=urn:btih:` links.
|
||||
* - Leaves the existing `xt` payload untouched—no percent re-encoding or normalization
|
||||
* beyond decoding legacy `%3A` segments.
|
||||
* - Only appends browser-safe WSS trackers in addition to whatever the caller provides.
|
||||
* - Skips insecure `http:` web seeds unless the application itself is running over HTTP.
|
||||
*
|
||||
* Note: `didChange` may be reported even if the resulting magnet string is textually
|
||||
* identical to the input. Callers should not rely on `didChange` to detect a modified
|
||||
* URI.
|
||||
*/
|
||||
export function normalizeAndAugmentMagnet(
|
||||
rawValue,
|
||||
{
|
||||
webSeed,
|
||||
torrentUrl,
|
||||
xs,
|
||||
extraTrackers = [],
|
||||
logger,
|
||||
appProtocol,
|
||||
} = {}
|
||||
) {
|
||||
const log = typeof logger === "function" ? logger : () => {};
|
||||
const initial = typeof rawValue === "string" ? rawValue.trim() : "";
|
||||
if (!initial) {
|
||||
return { magnet: "", didChange: false };
|
||||
}
|
||||
|
||||
let working = initial;
|
||||
let didMutate = false;
|
||||
const bareHashMatch = HEX_INFO_HASH.test(working);
|
||||
if (bareHashMatch) {
|
||||
working = `magnet:?xt=${BTIH_PREFIX}${working.toLowerCase()}`;
|
||||
didMutate = true;
|
||||
}
|
||||
|
||||
const hashIndex = working.indexOf("#");
|
||||
let fragment = "";
|
||||
if (hashIndex !== -1) {
|
||||
fragment = working.slice(hashIndex);
|
||||
working = working.slice(0, hashIndex);
|
||||
}
|
||||
|
||||
const decodedXt = working.replace(ENCODED_BTih_PATTERN, (_, hash) => {
|
||||
didMutate = true;
|
||||
return `xt=${BTIH_PREFIX}${hash}`;
|
||||
});
|
||||
working = decodedXt;
|
||||
|
||||
if (!/^magnet:/i.test(working)) {
|
||||
return {
|
||||
magnet: working,
|
||||
didChange: didMutate || working !== initial,
|
||||
};
|
||||
}
|
||||
|
||||
const [schemePart, queryPart = ""] = working.split("?", 2);
|
||||
const normalizedScheme = "magnet:";
|
||||
if (schemePart !== normalizedScheme) {
|
||||
didMutate = true;
|
||||
}
|
||||
|
||||
const rawParams = queryPart
|
||||
.split("&")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const params = [];
|
||||
|
||||
const decodeLoose = (value) => {
|
||||
if (typeof value !== "string" || !value) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch (err) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
for (const rawParam of rawParams) {
|
||||
const [rawKey, rawValue = ""] = rawParam.split("=", 2);
|
||||
const key = rawKey.trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
let value = rawValue.trim();
|
||||
if (key.toLowerCase() === "xt" && value) {
|
||||
const decoded = decodeLoose(value);
|
||||
if (decoded !== value) {
|
||||
value = decoded;
|
||||
didMutate = true;
|
||||
}
|
||||
}
|
||||
params.push({
|
||||
key,
|
||||
value,
|
||||
decoded: decodeLoose(value),
|
||||
});
|
||||
}
|
||||
|
||||
const torrentHint = typeof torrentUrl === "string" && torrentUrl.trim()
|
||||
? torrentUrl
|
||||
: typeof xs === "string"
|
||||
? xs.trim()
|
||||
: "";
|
||||
|
||||
const safeTorrentHint = sanitizeHttpUrl(torrentHint);
|
||||
const seedInputs = Array.isArray(webSeed)
|
||||
? webSeed
|
||||
: typeof webSeed === "string"
|
||||
? [webSeed]
|
||||
: [];
|
||||
|
||||
const resolvedProtocol = typeof appProtocol === "string" && appProtocol
|
||||
? appProtocol.toLowerCase()
|
||||
: typeof window !== "undefined" && window.location && window.location.protocol
|
||||
? window.location.protocol.toLowerCase()
|
||||
: "https:";
|
||||
|
||||
const existingTrackers = new Set(
|
||||
params
|
||||
.filter((param) => param.key.toLowerCase() === "tr")
|
||||
.map((param) => normalizeForComparison(param.decoded))
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const trackerCandidates = [
|
||||
...WSS_TRACKERS,
|
||||
...extraTrackers,
|
||||
];
|
||||
|
||||
for (const tracker of trackerCandidates) {
|
||||
if (typeof tracker !== "string") {
|
||||
continue;
|
||||
}
|
||||
const trimmedTracker = tracker.trim();
|
||||
if (!trimmedTracker) {
|
||||
continue;
|
||||
}
|
||||
if (!/^wss:\/\//i.test(trimmedTracker)) {
|
||||
continue;
|
||||
}
|
||||
const normalizedTracker = normalizeForComparison(trimmedTracker);
|
||||
if (!normalizedTracker || existingTrackers.has(normalizedTracker)) {
|
||||
continue;
|
||||
}
|
||||
params.push({ key: "tr", value: trimmedTracker, decoded: trimmedTracker });
|
||||
existingTrackers.add(normalizedTracker);
|
||||
didMutate = true;
|
||||
}
|
||||
|
||||
if (safeTorrentHint) {
|
||||
const existingXs = new Set(
|
||||
params
|
||||
.filter((param) => param.key.toLowerCase() === "xs")
|
||||
.map((param) => normalizeForComparison(param.decoded))
|
||||
.filter(Boolean)
|
||||
);
|
||||
const normalizedXs = normalizeForComparison(safeTorrentHint);
|
||||
if (normalizedXs && !existingXs.has(normalizedXs)) {
|
||||
params.push({
|
||||
key: "xs",
|
||||
value: safeTorrentHint,
|
||||
decoded: safeTorrentHint,
|
||||
});
|
||||
didMutate = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (seedInputs.length) {
|
||||
const existingWs = new Set(
|
||||
params
|
||||
.filter((param) => param.key.toLowerCase() === "ws")
|
||||
.map((param) => normalizeForComparison(param.decoded))
|
||||
.filter(Boolean)
|
||||
);
|
||||
for (const seedInput of seedInputs) {
|
||||
if (typeof seedInput !== "string") {
|
||||
continue;
|
||||
}
|
||||
const trimmedSeed = seedInput.trim();
|
||||
if (!trimmedSeed) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const parsedSeed = new URL(trimmedSeed);
|
||||
const seedProtocol = parsedSeed.protocol;
|
||||
const allowHttpSeed = resolvedProtocol === "http:";
|
||||
if (
|
||||
seedProtocol === "https:" ||
|
||||
(seedProtocol === "http:" && allowHttpSeed)
|
||||
) {
|
||||
const seedValue = parsedSeed.toString();
|
||||
const normalizedSeed = normalizeForComparison(seedValue);
|
||||
if (normalizedSeed && !existingWs.has(normalizedSeed)) {
|
||||
params.push({ key: "ws", value: seedValue, decoded: seedValue });
|
||||
existingWs.add(normalizedSeed);
|
||||
didMutate = true;
|
||||
}
|
||||
} else if (seedProtocol === "http:") {
|
||||
log(
|
||||
`[normalizeAndAugmentMagnet] Skipping insecure web seed: ${trimmedSeed}`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
// Ignore invalid web seed values silently.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const queryString = params
|
||||
.map(({ key, value }) => (value ? `${key}=${value}` : key))
|
||||
.join("&");
|
||||
|
||||
const finalMagnet = `${normalizedScheme}${queryString ? `?${queryString}` : ""}${fragment}`;
|
||||
|
||||
return {
|
||||
magnet: finalMagnet,
|
||||
didChange: didMutate || finalMagnet !== initial,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import parseMagnet from "https://esm.sh/[email protected]";
|
||||
|
||||
function normalizeInfoHash(candidate) {
|
||||
const trimmed = typeof candidate === "string" ? candidate.trim() : "";
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
if (/^[0-9a-f]{40}$/i.test(trimmed)) {
|
||||
return trimmed.toLowerCase();
|
||||
}
|
||||
if (/^[a-z2-7]{32}$/i.test(trimmed)) {
|
||||
try {
|
||||
const parsed = parseMagnet(`magnet:?xt=urn:btih:${trimmed}`);
|
||||
const hash = typeof parsed.infoHash === "string" ? parsed.infoHash : "";
|
||||
return hash ? hash.toLowerCase() : null;
|
||||
} catch (err) {
|
||||
console.warn("Failed to normalize base32 info hash", err);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function infoHashFromMagnet(magnet) {
|
||||
if (typeof magnet !== "string") {
|
||||
return null;
|
||||
}
|
||||
const direct = normalizeInfoHash(magnet);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
try {
|
||||
const parsed = parseMagnet(magnet);
|
||||
const hash = typeof parsed.infoHash === "string" ? parsed.infoHash : "";
|
||||
return hash ? hash.toLowerCase() : null;
|
||||
} catch (err) {
|
||||
console.warn("Failed to parse magnet for info hash", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function trackersFromMagnet(magnet) {
|
||||
if (typeof magnet !== "string") {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const parsed = parseMagnet(magnet);
|
||||
if (!parsed || !Array.isArray(parsed.announce)) {
|
||||
return [];
|
||||
}
|
||||
const deduped = new Set();
|
||||
parsed.announce.forEach((url) => {
|
||||
if (typeof url !== "string") {
|
||||
return;
|
||||
}
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
deduped.add(trimmed);
|
||||
});
|
||||
return Array.from(deduped);
|
||||
} catch (err) {
|
||||
console.warn("Failed to parse magnet trackers", err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
+968
-78
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,102 @@
|
||||
// js/playbackUtils.js
|
||||
|
||||
import {
|
||||
normalizeAndAugmentMagnet,
|
||||
safeDecodeMagnet,
|
||||
} from "./magnetUtils.js";
|
||||
|
||||
const HEX_INFO_HASH = /^[0-9a-f]{40}$/i;
|
||||
const MAGNET_URI = /^magnet:\?/i;
|
||||
|
||||
/**
|
||||
* Normalizes torrent related playback inputs into a canonical magnet payload.
|
||||
*
|
||||
* The function first trims and safely decodes the incoming `magnet` string so
|
||||
* that URL encoded magnets become plain text before processing. Bare info hash
|
||||
* strings are tolerated: whenever the caller supplies an info hash (either via
|
||||
* the `infoHash` field or a magnet that looks like one) it gets promoted to a
|
||||
* full magnet URI so downstream WebTorrent code can consume it directly.
|
||||
*
|
||||
* When the normalized output differs from the original magnet input (for
|
||||
* example due to whitespace/encoding fixes or tracker augmentation) the
|
||||
* original candidate is exposed through `fallbackMagnet`. Callers can surface
|
||||
* that value if a later refactor breaks magnet normalization.
|
||||
*
|
||||
* The returned flags communicate provenance: `provided` indicates that some
|
||||
* torrent-related input was supplied, while `usedInfoHash` is only `true` when
|
||||
* the normalized magnet was derived from an info hash instead of an already
|
||||
* well-formed magnet URI.
|
||||
*
|
||||
* Web seeds coming from the `url` parameter are forwarded to
|
||||
* `normalizeAndAugmentMagnet` via the `webSeed` option. Refactors must preserve
|
||||
* that flow (even if the parameter name changes) so hosted URLs continue to
|
||||
* populate `ws=` hints automatically.
|
||||
*/
|
||||
export function deriveTorrentPlaybackConfig({
|
||||
magnet = "",
|
||||
infoHash = "",
|
||||
url = "",
|
||||
logger,
|
||||
appProtocol,
|
||||
} = {}) {
|
||||
const trimmedMagnet = typeof magnet === "string" ? magnet.trim() : "";
|
||||
const decodedMagnet = safeDecodeMagnet(trimmedMagnet);
|
||||
const magnetCandidate = decodedMagnet || trimmedMagnet;
|
||||
const trimmedInfoHash =
|
||||
typeof infoHash === "string" ? infoHash.trim().toLowerCase() : "";
|
||||
const sanitizedUrl = typeof url === "string" ? url.trim() : "";
|
||||
|
||||
const magnetIsUri = MAGNET_URI.test(magnetCandidate);
|
||||
const magnetLooksLikeInfoHash = HEX_INFO_HASH.test(magnetCandidate);
|
||||
const resolvedInfoHash = trimmedInfoHash || (magnetLooksLikeInfoHash
|
||||
? magnetCandidate.toLowerCase()
|
||||
: "");
|
||||
|
||||
const normalizationInput = magnetIsUri ? magnetCandidate : resolvedInfoHash;
|
||||
const provided = Boolean(trimmedMagnet || trimmedInfoHash);
|
||||
const decodeChanged = magnetCandidate !== trimmedMagnet;
|
||||
|
||||
if (!normalizationInput) {
|
||||
return {
|
||||
magnet: "",
|
||||
fallbackMagnet: "",
|
||||
provided,
|
||||
usedInfoHash: false,
|
||||
originalInput: "",
|
||||
didMutate: false,
|
||||
infoHash: resolvedInfoHash,
|
||||
};
|
||||
}
|
||||
|
||||
const normalization = normalizeAndAugmentMagnet(normalizationInput, {
|
||||
webSeed: sanitizedUrl ? [sanitizedUrl] : [],
|
||||
logger,
|
||||
appProtocol,
|
||||
});
|
||||
|
||||
let normalizedMagnet = normalization.magnet;
|
||||
if (!normalizedMagnet || !MAGNET_URI.test(normalizedMagnet)) {
|
||||
if (magnetIsUri) {
|
||||
normalizedMagnet = normalizationInput;
|
||||
} else if (resolvedInfoHash) {
|
||||
normalizedMagnet = `magnet:?xt=urn:btih:${resolvedInfoHash}`;
|
||||
} else {
|
||||
normalizedMagnet = "";
|
||||
}
|
||||
}
|
||||
|
||||
const usedInfoHash = !magnetIsUri && Boolean(resolvedInfoHash);
|
||||
const fallbackMagnet = magnetIsUri && normalization.didChange
|
||||
? normalizationInput
|
||||
: "";
|
||||
|
||||
return {
|
||||
magnet: normalizedMagnet,
|
||||
fallbackMagnet,
|
||||
provided,
|
||||
usedInfoHash,
|
||||
originalInput: normalizationInput,
|
||||
didMutate: normalization.didChange || usedInfoHash || decodeChanged,
|
||||
infoHash: resolvedInfoHash,
|
||||
};
|
||||
}
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
import { buildR2Key, buildPublicUrl } from "./r2.js";
|
||||
import {
|
||||
sanitizeBucketName,
|
||||
ensureBucket,
|
||||
putCors,
|
||||
attachCustomDomainAndWait,
|
||||
setManagedDomain,
|
||||
} from "./storage/r2-mgmt.js";
|
||||
import { makeR2Client, multipartUpload } from "./storage/r2-s3.js";
|
||||
|
||||
const STORAGE_KEY = "bitvid:quickR2Settings";
|
||||
const STATUS_CLASSNAMES = [
|
||||
"text-gray-400",
|
||||
"text-green-400",
|
||||
"text-red-400",
|
||||
"text-yellow-400",
|
||||
];
|
||||
const STATUS_TONES = {
|
||||
info: "text-gray-400",
|
||||
success: "text-green-400",
|
||||
error: "text-red-400",
|
||||
warning: "text-yellow-400",
|
||||
};
|
||||
|
||||
function sanitizeDomain(value) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return String(value)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^https?:\/\//, "")
|
||||
.replace(/\/.*$/, "");
|
||||
}
|
||||
|
||||
function loadSavedSettings() {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
} catch (err) {
|
||||
console.warn("Failed to read quick R2 settings:", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistSettings(settings) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
} catch (err) {
|
||||
console.warn("Failed to store quick R2 settings:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function clearSavedSettings() {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (err) {
|
||||
console.warn("Failed to clear quick R2 settings:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(el, message, tone = "info") {
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
STATUS_CLASSNAMES.forEach((cls) => el.classList.remove(cls));
|
||||
const className = STATUS_TONES[tone] || STATUS_TONES.info;
|
||||
if (className) {
|
||||
el.classList.add(className);
|
||||
}
|
||||
el.textContent = message || "";
|
||||
}
|
||||
|
||||
function setUploadingState(elements, uploading) {
|
||||
const disabled = Boolean(uploading);
|
||||
elements.forEach((el) => {
|
||||
if (el) {
|
||||
el.disabled = disabled;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getCorsOrigins() {
|
||||
const origins = new Set();
|
||||
if (typeof window !== "undefined" && window.location) {
|
||||
const origin = window.location.origin;
|
||||
if (origin && origin !== "null") {
|
||||
origins.add(origin);
|
||||
}
|
||||
if (origin && origin.startsWith("http://")) {
|
||||
origins.add(origin.replace("http://", "https://"));
|
||||
}
|
||||
}
|
||||
origins.add("http://localhost:8000");
|
||||
origins.add("http://127.0.0.1:8000");
|
||||
return Array.from(origins);
|
||||
}
|
||||
|
||||
function buildQuickKey(title, file, npub) {
|
||||
const now = new Date();
|
||||
const datePart = now.toISOString().slice(0, 10);
|
||||
const baseName = (title || file?.name || "video")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9.-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
const safeBase = baseName || "video";
|
||||
const originalName = typeof file?.name === "string" ? file.name : "";
|
||||
const extMatch = originalName.match(/\.([^.]+)$/);
|
||||
const ext = extMatch ? extMatch[1].toLowerCase() : "mp4";
|
||||
const sanitizedNpub = String(npub || "user").replace(/[^a-z0-9]/gi, "");
|
||||
return `videos/${datePart}/${sanitizedNpub || "user"}-${safeBase}.${ext}`;
|
||||
}
|
||||
|
||||
export function initQuickR2Upload(app) {
|
||||
const section = document.getElementById("quickR2Section");
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
const elements = {
|
||||
accountId: document.getElementById("quickR2AccountId"),
|
||||
accessKeyId: document.getElementById("quickR2AccessKeyId"),
|
||||
secretAccessKey: document.getElementById("quickR2SecretAccessKey"),
|
||||
apiToken: document.getElementById("quickR2ApiToken"),
|
||||
customDomain: document.getElementById("quickR2CustomDomain"),
|
||||
zoneId: document.getElementById("quickR2ZoneId"),
|
||||
remember: document.getElementById("quickR2Remember"),
|
||||
allowManaged: document.getElementById("quickR2AllowManaged"),
|
||||
file: document.getElementById("quickR2File"),
|
||||
uploadButton: document.getElementById("quickR2UploadButton"),
|
||||
status: document.getElementById("quickR2Status"),
|
||||
hostedUrl: document.getElementById("uploadUrl"),
|
||||
titleInput: document.getElementById("uploadTitle"),
|
||||
form: document.getElementById("uploadForm"),
|
||||
};
|
||||
|
||||
const saved = loadSavedSettings();
|
||||
if (saved && saved.remember) {
|
||||
if (elements.accountId) elements.accountId.value = saved.accountId || "";
|
||||
if (elements.accessKeyId)
|
||||
elements.accessKeyId.value = saved.accessKeyId || "";
|
||||
if (elements.secretAccessKey)
|
||||
elements.secretAccessKey.value = saved.secretAccessKey || "";
|
||||
if (elements.apiToken) elements.apiToken.value = saved.apiToken || "";
|
||||
if (elements.customDomain)
|
||||
elements.customDomain.value = saved.customDomain || "";
|
||||
if (elements.zoneId) elements.zoneId.value = saved.zoneId || "";
|
||||
if (elements.allowManaged)
|
||||
elements.allowManaged.checked = Boolean(saved.allowManaged ?? true);
|
||||
if (elements.remember) elements.remember.checked = true;
|
||||
}
|
||||
|
||||
function maybePersist() {
|
||||
if (!elements.remember) {
|
||||
return;
|
||||
}
|
||||
if (elements.remember.checked) {
|
||||
persistSettings({
|
||||
remember: true,
|
||||
accountId: elements.accountId?.value?.trim() || "",
|
||||
accessKeyId: elements.accessKeyId?.value?.trim() || "",
|
||||
secretAccessKey: elements.secretAccessKey?.value?.trim() || "",
|
||||
apiToken: elements.apiToken?.value?.trim() || "",
|
||||
customDomain: elements.customDomain?.value?.trim() || "",
|
||||
zoneId: elements.zoneId?.value?.trim() || "",
|
||||
allowManaged: Boolean(elements.allowManaged?.checked ?? true),
|
||||
});
|
||||
} else {
|
||||
clearSavedSettings();
|
||||
}
|
||||
}
|
||||
|
||||
elements.remember?.addEventListener("change", () => {
|
||||
if (!elements.remember.checked) {
|
||||
clearSavedSettings();
|
||||
}
|
||||
});
|
||||
|
||||
async function handleUpload() {
|
||||
const file = elements.file?.files?.[0] || null;
|
||||
if (!file) {
|
||||
setStatus(elements.status, "Choose a file to upload.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const accountId = elements.accountId?.value?.trim();
|
||||
const accessKeyId = elements.accessKeyId?.value?.trim();
|
||||
const secretAccessKey = elements.secretAccessKey?.value?.trim();
|
||||
const apiToken = elements.apiToken?.value?.trim();
|
||||
const customDomain = sanitizeDomain(
|
||||
elements.customDomain?.value || ""
|
||||
);
|
||||
const zoneId = elements.zoneId?.value?.trim();
|
||||
const allowManaged = Boolean(elements.allowManaged?.checked ?? true);
|
||||
|
||||
if (!accountId || !accessKeyId || !secretAccessKey) {
|
||||
setStatus(
|
||||
elements.status,
|
||||
"Account ID and S3 keys are required for Cloudflare R2.",
|
||||
"error"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const npub =
|
||||
typeof app?.safeEncodeNpub === "function" ? app.safeEncodeNpub(app.pubkey) : null;
|
||||
if (!npub) {
|
||||
setStatus(
|
||||
elements.status,
|
||||
"Unable to derive your npub. Connect a Nostr key first.",
|
||||
"error"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
maybePersist();
|
||||
|
||||
const bucket = sanitizeBucketName(npub);
|
||||
const inputsToDisable = [
|
||||
elements.accountId,
|
||||
elements.accessKeyId,
|
||||
elements.secretAccessKey,
|
||||
elements.apiToken,
|
||||
elements.customDomain,
|
||||
elements.zoneId,
|
||||
elements.remember,
|
||||
elements.allowManaged,
|
||||
elements.file,
|
||||
elements.uploadButton,
|
||||
];
|
||||
|
||||
setUploadingState(inputsToDisable, true);
|
||||
setStatus(elements.status, `Preparing bucket ${bucket}…`, "info");
|
||||
|
||||
try {
|
||||
if (apiToken) {
|
||||
try {
|
||||
await ensureBucket({ accountId, bucket, token: apiToken });
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
err?.message ? `Bucket setup failed: ${err.message}` : "Bucket setup failed."
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await putCors({
|
||||
accountId,
|
||||
bucket,
|
||||
token: apiToken,
|
||||
origins: getCorsOrigins(),
|
||||
});
|
||||
} catch (corsErr) {
|
||||
console.warn("Quick R2 CORS update failed:", corsErr);
|
||||
}
|
||||
}
|
||||
|
||||
let publicBaseUrl = "";
|
||||
let usedManagedFallback = false;
|
||||
|
||||
if (customDomain) {
|
||||
if (apiToken && zoneId) {
|
||||
try {
|
||||
setStatus(
|
||||
elements.status,
|
||||
`Attaching ${customDomain}…`,
|
||||
"info"
|
||||
);
|
||||
const custom = await attachCustomDomainAndWait({
|
||||
accountId,
|
||||
bucket,
|
||||
token: apiToken,
|
||||
zoneId,
|
||||
domain: customDomain,
|
||||
pollInterval: 1500,
|
||||
timeoutMs: 120000,
|
||||
});
|
||||
if (custom?.active && custom?.url) {
|
||||
publicBaseUrl = custom.url;
|
||||
try {
|
||||
await setManagedDomain({
|
||||
accountId,
|
||||
bucket,
|
||||
token: apiToken,
|
||||
enabled: false,
|
||||
});
|
||||
} catch (disableErr) {
|
||||
console.warn("Quick R2 managed domain disable failed:", disableErr);
|
||||
}
|
||||
} else {
|
||||
setStatus(
|
||||
elements.status,
|
||||
`Custom domain pending (${custom?.status || "unknown"}).`,
|
||||
"warning"
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Quick R2 custom domain error:", err);
|
||||
setStatus(
|
||||
elements.status,
|
||||
err?.message
|
||||
? `Custom domain setup failed: ${err.message}`
|
||||
: "Custom domain setup failed.",
|
||||
"warning"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!publicBaseUrl) {
|
||||
publicBaseUrl = `https://${customDomain}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!publicBaseUrl && apiToken && allowManaged) {
|
||||
try {
|
||||
setStatus(elements.status, "Enabling managed r2.dev domain…", "info");
|
||||
const managed = await setManagedDomain({
|
||||
accountId,
|
||||
bucket,
|
||||
token: apiToken,
|
||||
enabled: true,
|
||||
});
|
||||
if (managed?.url) {
|
||||
publicBaseUrl = managed.url;
|
||||
usedManagedFallback = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Quick R2 managed domain enable failed:", err);
|
||||
setStatus(
|
||||
elements.status,
|
||||
err?.message
|
||||
? `Managed domain failed: ${err.message}`
|
||||
: "Managed domain failed.",
|
||||
"warning"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!publicBaseUrl) {
|
||||
throw new Error(
|
||||
"No public domain configured. Provide a custom domain or allow the managed r2.dev fallback."
|
||||
);
|
||||
}
|
||||
|
||||
const s3 = makeR2Client({ accountId, accessKeyId, secretAccessKey });
|
||||
const title = elements.titleInput?.value?.trim() || "";
|
||||
const key = buildQuickKey(title, file, npub) || buildR2Key(npub, file);
|
||||
const hostedUrl = buildPublicUrl(publicBaseUrl, key);
|
||||
|
||||
let lastPercent = -1;
|
||||
setStatus(elements.status, `Uploading… 0%`, usedManagedFallback ? "warning" : "info");
|
||||
|
||||
await multipartUpload({
|
||||
s3,
|
||||
bucket,
|
||||
key,
|
||||
file,
|
||||
contentType: file.type,
|
||||
onProgress: (fraction) => {
|
||||
if (typeof fraction !== "number" || !isFinite(fraction)) {
|
||||
return;
|
||||
}
|
||||
const percent = Math.max(0, Math.min(100, Math.round(fraction * 100)));
|
||||
if (percent !== lastPercent) {
|
||||
lastPercent = percent;
|
||||
setStatus(
|
||||
elements.status,
|
||||
`Uploading… ${percent}%`,
|
||||
usedManagedFallback ? "warning" : "info"
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (elements.hostedUrl) {
|
||||
elements.hostedUrl.value = hostedUrl;
|
||||
}
|
||||
|
||||
setStatus(
|
||||
elements.status,
|
||||
`Upload complete. Hosted URL set to ${hostedUrl}.`,
|
||||
"success"
|
||||
);
|
||||
|
||||
if (elements.form && typeof elements.form.requestSubmit === "function") {
|
||||
elements.form.requestSubmit();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Quick R2 upload failed:", err);
|
||||
setStatus(
|
||||
elements.status,
|
||||
err?.message ? `Upload failed: ${err.message}` : "Upload failed.",
|
||||
"error"
|
||||
);
|
||||
} finally {
|
||||
setUploadingState(inputsToDisable, false);
|
||||
}
|
||||
}
|
||||
|
||||
elements.uploadButton?.addEventListener("click", () => {
|
||||
handleUpload();
|
||||
});
|
||||
}
|
||||
|
||||
export default initQuickR2Upload;
|
||||
@@ -0,0 +1,258 @@
|
||||
const DB_NAME = "bitvidSettings";
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = "kv";
|
||||
const SETTINGS_KEY = "r2Settings";
|
||||
const LOCALSTORAGE_FALLBACK_KEY = "bitvid:r2Settings";
|
||||
|
||||
function sanitizeBaseDomain(domain) {
|
||||
if (!domain) {
|
||||
return "";
|
||||
}
|
||||
let value = String(domain).trim().toLowerCase();
|
||||
value = value.replace(/^https?:\/\//, "");
|
||||
value = value.replace(/\/.*$/, "");
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeBucketEntry(entry) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return null;
|
||||
}
|
||||
const bucket = String(entry.bucket || "").toLowerCase();
|
||||
if (!bucket) {
|
||||
return null;
|
||||
}
|
||||
const publicBaseUrl = String(entry.publicBaseUrl || "");
|
||||
const domainType = entry.domainType === "custom" ? "custom" : "managed";
|
||||
const lastUpdated = Number.isFinite(entry.lastUpdated)
|
||||
? entry.lastUpdated
|
||||
: Date.now();
|
||||
return { bucket, publicBaseUrl, domainType, lastUpdated };
|
||||
}
|
||||
|
||||
function normalizeSettings(raw) {
|
||||
const base = raw && typeof raw === "object" ? raw : {};
|
||||
const buckets = {};
|
||||
if (base.buckets && typeof base.buckets === "object") {
|
||||
for (const [npub, value] of Object.entries(base.buckets)) {
|
||||
const normalizedEntry = normalizeBucketEntry(value);
|
||||
if (normalizedEntry) {
|
||||
buckets[String(npub)] = normalizedEntry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
accountId: String(base.accountId || ""),
|
||||
accessKeyId: String(base.accessKeyId || ""),
|
||||
secretAccessKey: String(base.secretAccessKey || ""),
|
||||
apiToken: String(base.apiToken || ""),
|
||||
zoneId: String(base.zoneId || ""),
|
||||
baseDomain: sanitizeBaseDomain(base.baseDomain || ""),
|
||||
buckets,
|
||||
};
|
||||
}
|
||||
|
||||
function isIndexedDbAvailable() {
|
||||
try {
|
||||
return typeof indexedDB !== "undefined";
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function openSettingsDb() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!isIndexedDbAvailable()) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
db.createObjectStore(STORE_NAME);
|
||||
}
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(request.error || new Error("Failed to open settings DB"));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadR2Settings() {
|
||||
try {
|
||||
const db = await openSettingsDb();
|
||||
if (db) {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE_NAME, "readonly");
|
||||
const store = tx.objectStore(STORE_NAME);
|
||||
const req = store.get(SETTINGS_KEY);
|
||||
req.onsuccess = () => {
|
||||
resolve(normalizeSettings(req.result));
|
||||
};
|
||||
req.onerror = () => {
|
||||
reject(req.error || new Error("Failed to load settings"));
|
||||
};
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to open IndexedDB for settings, falling back:", err);
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof localStorage !== "undefined") {
|
||||
const raw = localStorage.getItem(LOCALSTORAGE_FALLBACK_KEY);
|
||||
if (raw) {
|
||||
return normalizeSettings(JSON.parse(raw));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to read fallback settings:", err);
|
||||
}
|
||||
|
||||
return normalizeSettings(null);
|
||||
}
|
||||
|
||||
export async function saveR2Settings(settings) {
|
||||
const normalized = normalizeSettings(settings);
|
||||
|
||||
let db = null;
|
||||
try {
|
||||
db = await openSettingsDb();
|
||||
} catch (err) {
|
||||
console.warn("Unable to open IndexedDB, continuing with fallback:", err);
|
||||
}
|
||||
|
||||
if (db) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE_NAME, "readwrite");
|
||||
const store = tx.objectStore(STORE_NAME);
|
||||
const req = store.put(normalized, SETTINGS_KEY);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () =>
|
||||
reject(req.error || new Error("Failed to save R2 settings"));
|
||||
});
|
||||
} else if (typeof localStorage !== "undefined") {
|
||||
localStorage.setItem(
|
||||
LOCALSTORAGE_FALLBACK_KEY,
|
||||
JSON.stringify(normalized)
|
||||
);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export async function clearR2Settings() {
|
||||
let cleared = false;
|
||||
try {
|
||||
const db = await openSettingsDb();
|
||||
if (db) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE_NAME, "readwrite");
|
||||
const store = tx.objectStore(STORE_NAME);
|
||||
const req = store.delete(SETTINGS_KEY);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error || new Error("Failed to clear"));
|
||||
});
|
||||
cleared = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to clear IndexedDB settings:", err);
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof localStorage !== "undefined") {
|
||||
localStorage.removeItem(LOCALSTORAGE_FALLBACK_KEY);
|
||||
cleared = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to clear fallback settings:", err);
|
||||
}
|
||||
|
||||
return cleared;
|
||||
}
|
||||
|
||||
export function mergeBucketEntry(settings, npub, entry) {
|
||||
if (!settings || typeof settings !== "object") {
|
||||
return settings;
|
||||
}
|
||||
const normalizedEntry = normalizeBucketEntry(entry);
|
||||
if (!normalizedEntry) {
|
||||
return settings;
|
||||
}
|
||||
return {
|
||||
...settings,
|
||||
buckets: {
|
||||
...(settings.buckets || {}),
|
||||
[npub]: normalizedEntry,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function guessExtension(file) {
|
||||
if (!file) {
|
||||
return "mp4";
|
||||
}
|
||||
|
||||
const name = typeof file.name === "string" ? file.name : "";
|
||||
const dotIndex = name.lastIndexOf(".");
|
||||
if (dotIndex > -1 && dotIndex < name.length - 1) {
|
||||
return name.slice(dotIndex + 1).toLowerCase();
|
||||
}
|
||||
|
||||
const type = typeof file.type === "string" ? file.type : "";
|
||||
switch (type) {
|
||||
case "video/webm":
|
||||
return "webm";
|
||||
case "application/vnd.apple.mpegurl":
|
||||
return "m3u8";
|
||||
case "video/mp2t":
|
||||
return "ts";
|
||||
case "video/quicktime":
|
||||
return "mov";
|
||||
case "video/x-matroska":
|
||||
return "mkv";
|
||||
default:
|
||||
return "mp4";
|
||||
}
|
||||
}
|
||||
|
||||
export function buildR2Key(npub, file) {
|
||||
const now = new Date();
|
||||
const year = now.getUTCFullYear();
|
||||
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
|
||||
const safeNpub = String(npub || "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]/g, "");
|
||||
const baseName = typeof file?.name === "string" ? file.name : "video";
|
||||
const withoutExt = baseName.replace(/\.[^/.]+$/, "");
|
||||
const slug = withoutExt
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
const safeSlug = slug || "video";
|
||||
const ext = guessExtension(file);
|
||||
return `u/${safeNpub}/${year}/${month}/${safeSlug}.${ext}`;
|
||||
}
|
||||
|
||||
export function buildPublicUrl(baseUrl, key) {
|
||||
if (!baseUrl) {
|
||||
return "";
|
||||
}
|
||||
const sanitizedBase = String(baseUrl).replace(/\/$/, "");
|
||||
const encodedKey = key
|
||||
.split("/")
|
||||
.map((segment) => encodeURIComponent(segment))
|
||||
.join("/");
|
||||
return `${sanitizedBase}/${encodedKey}`;
|
||||
}
|
||||
|
||||
export { sanitizeBaseDomain };
|
||||
@@ -0,0 +1,293 @@
|
||||
// js/storage/r2-mgmt.js
|
||||
function computeSlugHash(input) {
|
||||
const text = String(input || "");
|
||||
let hash = 0;
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
hash = Math.imul(31, hash) + text.charCodeAt(i);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
}
|
||||
|
||||
export function sanitizeBucketName(npub) {
|
||||
const raw = String(npub || "");
|
||||
let value = raw
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]/g, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^-+|[-]+$/g, "");
|
||||
|
||||
if (!value) {
|
||||
value = "bitvid-user";
|
||||
}
|
||||
|
||||
if (value.length > 32) {
|
||||
const prefix = value.slice(0, 20).replace(/-+$/g, "");
|
||||
const hash = computeSlugHash(raw).slice(0, 8);
|
||||
value = [prefix, hash].filter(Boolean).join("-");
|
||||
}
|
||||
|
||||
value = value.replace(/-+/g, "-").replace(/^-+|[-]+$/g, "");
|
||||
|
||||
if (!/^[a-z0-9]/.test(value)) {
|
||||
value = `bv-${value}`;
|
||||
}
|
||||
|
||||
if (!/[a-z0-9]$/.test(value)) {
|
||||
value = `${value}0`;
|
||||
}
|
||||
|
||||
if (value.length > 63) {
|
||||
value = value.slice(0, 63).replace(/-+$/g, "");
|
||||
}
|
||||
|
||||
while (value.length < 3) {
|
||||
value += "0";
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function deriveShortSubdomain(npub) {
|
||||
const bucketSlug = sanitizeBucketName(npub);
|
||||
const hash = computeSlugHash(npub).slice(0, 6);
|
||||
|
||||
const prefix = bucketSlug
|
||||
.replace(/^bv-/, "")
|
||||
.slice(0, 18)
|
||||
.replace(/-+$/g, "");
|
||||
|
||||
let candidate = [prefix, hash].filter(Boolean).join("-");
|
||||
candidate = candidate
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]/g, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^-+|[-]+$/g, "");
|
||||
|
||||
if (!candidate) {
|
||||
candidate = "user";
|
||||
}
|
||||
|
||||
if (candidate.length > 32) {
|
||||
candidate = candidate.slice(0, 32).replace(/-+$/g, "");
|
||||
}
|
||||
|
||||
if (!/^[a-z0-9]/.test(candidate)) {
|
||||
candidate = `u${candidate}`;
|
||||
}
|
||||
|
||||
if (!/[a-z0-9]$/.test(candidate)) {
|
||||
candidate = `${candidate}0`;
|
||||
}
|
||||
|
||||
while (candidate.length < 3) {
|
||||
candidate += "0";
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function buildError(error, fallbackMessage) {
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
}
|
||||
const err = new Error(fallbackMessage || "Cloudflare request failed");
|
||||
err.original = error;
|
||||
return err;
|
||||
}
|
||||
|
||||
// --- Cloudflare API helpers (Bearer token) ---
|
||||
async function cfFetch(path, { token, method = "GET", body, headers = {} }) {
|
||||
if (!token) {
|
||||
throw new Error("Cloudflare API token is required");
|
||||
}
|
||||
const res = await fetch(`https://api.cloudflare.com/client/v4${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
const text = await res.text();
|
||||
let data = {};
|
||||
if (text) {
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch (parseErr) {
|
||||
if (!res.ok) {
|
||||
const err = new Error(text || `Cloudflare API error ${res.status}`);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
throw parseErr;
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.ok || data?.success === false) {
|
||||
const errorMessage =
|
||||
data?.errors?.[0]?.message ||
|
||||
data?.message ||
|
||||
text ||
|
||||
`Cloudflare API error ${res.status}`;
|
||||
const err = new Error(errorMessage);
|
||||
err.status = res.status;
|
||||
err.response = data;
|
||||
throw err;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// 1) Create bucket (idempotent-ish: treat 409 as success)
|
||||
export async function ensureBucket({ accountId, bucket, token }) {
|
||||
try {
|
||||
await cfFetch(`/accounts/${accountId}/r2/buckets`, {
|
||||
token,
|
||||
method: "POST",
|
||||
body: { name: bucket },
|
||||
});
|
||||
} catch (error) {
|
||||
const err = buildError(error);
|
||||
if (err.status === 409 || /already exists/i.test(err.message || "")) {
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Set CORS so browser PUT/GETs work from your app origins
|
||||
export async function putCors({ accountId, bucket, token, origins }) {
|
||||
const filteredOrigins = (origins || []).filter(Boolean);
|
||||
if (filteredOrigins.length === 0) {
|
||||
return;
|
||||
}
|
||||
const rules = [
|
||||
{
|
||||
id: "bitvid-default",
|
||||
allowed: {
|
||||
origins: filteredOrigins,
|
||||
methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "OPTIONS"],
|
||||
headers: ["*"],
|
||||
},
|
||||
expose_headers: ["ETag", "Content-Length", "Content-Range", "Accept-Ranges"],
|
||||
max_age_seconds: 3600,
|
||||
},
|
||||
];
|
||||
await cfFetch(`/accounts/${accountId}/r2/buckets/${bucket}/cors`, {
|
||||
token,
|
||||
method: "PUT",
|
||||
body: { rules },
|
||||
});
|
||||
}
|
||||
|
||||
function extractStatus(payload) {
|
||||
return (
|
||||
payload?.result?.status ||
|
||||
payload?.result?.result?.status ||
|
||||
payload?.status ||
|
||||
payload?.result?.statusText ||
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
async function pollCustomDomain({
|
||||
accountId,
|
||||
bucket,
|
||||
token,
|
||||
domain,
|
||||
pollInterval = 2500,
|
||||
timeoutMs = 120000,
|
||||
}) {
|
||||
const path = `/accounts/${accountId}/r2/buckets/${bucket}/domains/custom/${encodeURIComponent(
|
||||
domain
|
||||
)}`;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastPayload = null;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
lastPayload = await cfFetch(path, { token, method: "GET" }).catch((err) => {
|
||||
if (err?.status === 404) {
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (!lastPayload) {
|
||||
break;
|
||||
}
|
||||
|
||||
const status = extractStatus(lastPayload);
|
||||
if (status === "active") {
|
||||
return { status, payload: lastPayload };
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
return {
|
||||
status: extractStatus(lastPayload) || "unknown",
|
||||
payload: lastPayload,
|
||||
};
|
||||
}
|
||||
|
||||
// 3) Attach custom domain to bucket (auto-provisions on Cloudflare)
|
||||
export async function attachCustomDomainAndWait({
|
||||
accountId,
|
||||
bucket,
|
||||
token,
|
||||
zoneId,
|
||||
domain,
|
||||
pollInterval,
|
||||
timeoutMs,
|
||||
}) {
|
||||
let shouldPoll = true;
|
||||
try {
|
||||
await cfFetch(`/accounts/${accountId}/r2/buckets/${bucket}/domains/custom`, {
|
||||
token,
|
||||
method: "POST",
|
||||
body: { domain, zoneId, enabled: true },
|
||||
});
|
||||
} catch (error) {
|
||||
const err = buildError(error);
|
||||
if (err.status === 409 || /already exists/i.test(err.message || "")) {
|
||||
shouldPoll = true;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
let status = "unknown";
|
||||
if (shouldPoll) {
|
||||
const pollResult = await pollCustomDomain({
|
||||
accountId,
|
||||
bucket,
|
||||
token,
|
||||
domain,
|
||||
pollInterval,
|
||||
timeoutMs,
|
||||
});
|
||||
status = pollResult.status;
|
||||
}
|
||||
|
||||
const url = `https://${domain}`;
|
||||
return {
|
||||
url,
|
||||
status,
|
||||
active: status === "active",
|
||||
};
|
||||
}
|
||||
|
||||
// 4) Toggle managed r2.dev domain for the bucket
|
||||
export async function setManagedDomain({ accountId, bucket, token, enabled }) {
|
||||
const { result } = await cfFetch(
|
||||
`/accounts/${accountId}/r2/buckets/${bucket}/domains/managed`,
|
||||
{ token, method: "PUT", body: { enabled: Boolean(enabled) } }
|
||||
);
|
||||
const domain = result?.domain || result?.result?.domain || "";
|
||||
return {
|
||||
enabled: Boolean(result?.enabled ?? enabled),
|
||||
url: domain ? `https://${domain}` : "",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
// js/storage/r2-s3.js
|
||||
import {
|
||||
S3Client,
|
||||
CreateBucketCommand,
|
||||
CreateMultipartUploadCommand,
|
||||
UploadPartCommand,
|
||||
CompleteMultipartUploadCommand,
|
||||
AbortMultipartUploadCommand,
|
||||
HeadBucketCommand,
|
||||
PutBucketCorsCommand,
|
||||
} from "https://esm.sh/@aws-sdk/[email protected]?target=es2022&bundle";
|
||||
|
||||
function computeCacheControl(key) {
|
||||
if (!key) {
|
||||
return "public, max-age=3600";
|
||||
}
|
||||
|
||||
const lower = String(key).toLowerCase();
|
||||
if (/(?:\.)(m3u8|mpd)$/.test(lower)) {
|
||||
return "public, max-age=60, must-revalidate";
|
||||
}
|
||||
|
||||
if (
|
||||
/\.(m4s|ts|mp4|webm|mov|mkv|png|jpg|jpeg|gif|svg|vtt|srt|mpg|mpeg)$/.test(
|
||||
lower
|
||||
)
|
||||
) {
|
||||
return "public, max-age=31536000, immutable";
|
||||
}
|
||||
|
||||
return "public, max-age=3600";
|
||||
}
|
||||
|
||||
export function makeR2Client({ accountId, accessKeyId, secretAccessKey }) {
|
||||
if (!accountId || !accessKeyId || !secretAccessKey) {
|
||||
throw new Error("Missing Cloudflare R2 credentials");
|
||||
}
|
||||
|
||||
return new S3Client({
|
||||
region: "auto",
|
||||
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
||||
credentials: { accessKeyId, secretAccessKey },
|
||||
forcePathStyle: true,
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureBucketExists({ s3, bucket }) {
|
||||
try {
|
||||
await s3.send(new HeadBucketCommand({ Bucket: bucket }));
|
||||
return;
|
||||
} catch (error) {
|
||||
const status = error?.$metadata?.httpStatusCode || 0;
|
||||
const code = error?.name || error?.Code || "";
|
||||
if (status !== 404 && code !== "NotFound" && code !== "NoSuchBucket") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await s3.send(new CreateBucketCommand({ Bucket: bucket }));
|
||||
} catch (error) {
|
||||
const status = error?.$metadata?.httpStatusCode || 0;
|
||||
const code = error?.name || error?.Code || "";
|
||||
if (
|
||||
status === 409 ||
|
||||
code === "BucketAlreadyOwnedByYou" ||
|
||||
code === "BucketAlreadyExists"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureBucketCors({ s3, bucket, origins }) {
|
||||
if (!s3) {
|
||||
throw new Error("S3 client is required to configure CORS");
|
||||
}
|
||||
if (!bucket) {
|
||||
throw new Error("Bucket name is required to configure CORS");
|
||||
}
|
||||
|
||||
const allowedOrigins = (origins || []).filter(Boolean);
|
||||
if (allowedOrigins.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await ensureBucketExists({ s3, bucket });
|
||||
|
||||
const command = new PutBucketCorsCommand({
|
||||
Bucket: bucket,
|
||||
CORSConfiguration: {
|
||||
CORSRules: [
|
||||
{
|
||||
AllowedHeaders: ["*"],
|
||||
AllowedMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "OPTIONS"],
|
||||
AllowedOrigins: allowedOrigins,
|
||||
ExposeHeaders: [
|
||||
"ETag",
|
||||
"Content-Length",
|
||||
"Content-Range",
|
||||
"Accept-Ranges",
|
||||
],
|
||||
MaxAgeSeconds: 3600,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await s3.send(command);
|
||||
}
|
||||
|
||||
export async function multipartUpload({
|
||||
s3,
|
||||
bucket,
|
||||
key,
|
||||
file,
|
||||
contentType,
|
||||
onProgress,
|
||||
}) {
|
||||
if (!s3) {
|
||||
throw new Error("S3 client is required");
|
||||
}
|
||||
if (!bucket) {
|
||||
throw new Error("Bucket is required");
|
||||
}
|
||||
if (!key) {
|
||||
throw new Error("Object key is required");
|
||||
}
|
||||
if (!file) {
|
||||
throw new Error("File is required");
|
||||
}
|
||||
|
||||
const createCommand = new CreateMultipartUploadCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
ContentType: contentType || file.type || "application/octet-stream",
|
||||
CacheControl: computeCacheControl(key),
|
||||
});
|
||||
|
||||
createCommand.middlewareStack.add(
|
||||
(next) => async (args) => {
|
||||
if (args?.request?.headers) {
|
||||
args.request.headers["cf-create-bucket-if-missing"] = "true";
|
||||
}
|
||||
return next(args);
|
||||
},
|
||||
{ step: "build" }
|
||||
);
|
||||
|
||||
const { UploadId } = await s3.send(createCommand);
|
||||
|
||||
if (!UploadId) {
|
||||
throw new Error("Failed to start multipart upload");
|
||||
}
|
||||
|
||||
const MIN_PART = 5 * 1024 * 1024;
|
||||
const maxParts = 10000;
|
||||
const calculated = Math.ceil(file.size / maxParts);
|
||||
const partSize = Math.max(MIN_PART, calculated);
|
||||
const total = file.size;
|
||||
const parts = [];
|
||||
let uploadedBytes = 0;
|
||||
let partNumber = 1;
|
||||
|
||||
if (typeof onProgress === "function") {
|
||||
onProgress(0);
|
||||
}
|
||||
|
||||
try {
|
||||
while (uploadedBytes < total) {
|
||||
const start = uploadedBytes;
|
||||
const end = Math.min(start + partSize, total);
|
||||
const chunk = file.slice(start, end);
|
||||
|
||||
const { ETag } = await s3.send(
|
||||
new UploadPartCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
UploadId,
|
||||
PartNumber: partNumber,
|
||||
Body: chunk,
|
||||
})
|
||||
);
|
||||
|
||||
parts.push({ ETag, PartNumber: partNumber });
|
||||
uploadedBytes = end;
|
||||
partNumber += 1;
|
||||
|
||||
if (typeof onProgress === "function") {
|
||||
onProgress(uploadedBytes / total);
|
||||
}
|
||||
}
|
||||
|
||||
await s3.send(
|
||||
new CompleteMultipartUploadCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
UploadId,
|
||||
MultipartUpload: { Parts: parts },
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
await s3
|
||||
.send(
|
||||
new AbortMultipartUploadCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
UploadId,
|
||||
})
|
||||
)
|
||||
.catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
+269
-44
@@ -1,5 +1,37 @@
|
||||
// js/subscriptions.js
|
||||
import { nostrClient } from "./nostr.js";
|
||||
import {
|
||||
nostrClient,
|
||||
convertEventToVideo as sharedConvertEventToVideo,
|
||||
} from "./nostr.js";
|
||||
import { attachHealthBadges } from "./gridHealth.js";
|
||||
import { attachUrlHealthBadges } from "./urlHealthObserver.js";
|
||||
|
||||
function getAbsoluteShareUrl(nevent) {
|
||||
if (!nevent) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (window.app?.buildShareUrlFromNevent) {
|
||||
const candidate = window.app.buildShareUrlFromNevent(nevent);
|
||||
if (candidate) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
const origin = window.location?.origin || "";
|
||||
const pathname = window.location?.pathname || "";
|
||||
let base = origin || pathname ? `${origin}${pathname}` : "";
|
||||
if (!base) {
|
||||
const href = window.location?.href || "";
|
||||
base = href ? href.split(/[?#]/)[0] : "";
|
||||
}
|
||||
|
||||
if (!base) {
|
||||
return `?v=${encodeURIComponent(nevent)}`;
|
||||
}
|
||||
|
||||
return `${base}?v=${encodeURIComponent(nevent)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages the user's subscription list (kind=30002) *privately*,
|
||||
@@ -120,6 +152,14 @@ class SubscriptionsManager {
|
||||
const plainObj = { subPubkeys: Array.from(this.subscribedPubkeys) };
|
||||
const plainStr = JSON.stringify(plainObj);
|
||||
|
||||
/*
|
||||
* The subscription list is stored as a NIP-04 message to self, so both
|
||||
* encryption and decryption intentionally use the user's own pubkey.
|
||||
* Extensions are expected to support this encrypt-to-self flow; altering
|
||||
* the target would break loadSubscriptions, which decrypts with the same
|
||||
* pubkey. Any future sharing model (e.g., sharing with another user) will
|
||||
* need a parallel read path and should not overwrite this behavior.
|
||||
*/
|
||||
let cipherText = "";
|
||||
try {
|
||||
cipherText = await window.nostr.nip04.encrypt(userPubkey, plainStr);
|
||||
@@ -234,7 +274,27 @@ class SubscriptionsManager {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
|
||||
if (!videos.length) {
|
||||
const safeVideos = Array.isArray(videos) ? videos : [];
|
||||
const dedupedVideos =
|
||||
window.app?.dedupeVideosByRoot?.(safeVideos) ??
|
||||
this.dedupeToNewestByRoot(safeVideos);
|
||||
|
||||
const filteredVideos = dedupedVideos.filter((video) => {
|
||||
if (!video || typeof video !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
window.app?.isAuthorBlocked &&
|
||||
window.app.isAuthorBlocked(video.pubkey)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!filteredVideos.length) {
|
||||
container.innerHTML = `
|
||||
<p class="flex justify-center items-center h-full w-full text-center text-gray-500">
|
||||
No videos available yet.
|
||||
@@ -243,25 +303,27 @@ class SubscriptionsManager {
|
||||
}
|
||||
|
||||
// Sort newest first
|
||||
videos.sort((a, b) => b.created_at - a.created_at);
|
||||
filteredVideos.sort((a, b) => b.created_at - a.created_at);
|
||||
|
||||
const fullAllEventsArray = Array.from(nostrClient.allEvents.values());
|
||||
const fragment = document.createDocumentFragment();
|
||||
// Only declare localAuthorSet once
|
||||
const localAuthorSet = new Set();
|
||||
|
||||
videos.forEach((video, index) => {
|
||||
filteredVideos.forEach((video, index) => {
|
||||
if (!video.id || !video.title) {
|
||||
console.error("Missing ID or title:", video);
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the global videos map up to date so delegated playback handlers
|
||||
// can reuse the already fetched metadata for this event.
|
||||
window.app?.videosMap?.set(video.id, video);
|
||||
|
||||
localAuthorSet.add(video.pubkey);
|
||||
|
||||
const nevent = window.NostrTools.nip19.neventEncode({ id: video.id });
|
||||
const shareUrl = `${window.location.pathname}?v=${encodeURIComponent(
|
||||
nevent
|
||||
)}`;
|
||||
const shareUrl = getAbsoluteShareUrl(nevent);
|
||||
const canEdit = window.app?.pubkey === video.pubkey;
|
||||
|
||||
const highlightClass =
|
||||
@@ -283,6 +345,7 @@ class SubscriptionsManager {
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white"
|
||||
data-revert-index="${index}"
|
||||
data-revert-event-id="${video.id}"
|
||||
>
|
||||
Revert
|
||||
</button>
|
||||
@@ -311,6 +374,7 @@ class SubscriptionsManager {
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700"
|
||||
data-edit-index="${index}"
|
||||
data-edit-event-id="${video.id}"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
@@ -318,6 +382,7 @@ class SubscriptionsManager {
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white"
|
||||
data-delete-all-index="${index}"
|
||||
data-delete-all-event-id="${video.id}"
|
||||
>
|
||||
Delete All
|
||||
</button>
|
||||
@@ -327,13 +392,87 @@ class SubscriptionsManager {
|
||||
`
|
||||
: "";
|
||||
|
||||
const moreMenu = `
|
||||
<div class="relative inline-block ml-1 overflow-visible" data-more-menu-wrapper="true">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center w-10 h-10 p-2 rounded-full text-gray-400 hover:text-gray-200 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
data-more-dropdown="${index}"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-label="More options"
|
||||
>
|
||||
<img src="assets/svg/ellipsis.svg" alt="More" class="w-5 h-5 object-contain" />
|
||||
</button>
|
||||
<div
|
||||
id="moreDropdown-${index}"
|
||||
class="hidden absolute right-0 bottom-full mb-2 w-40 rounded-md shadow-lg bg-gray-800 ring-1 ring-black ring-opacity-5 z-50"
|
||||
role="menu"
|
||||
data-more-menu="true"
|
||||
>
|
||||
<div class="py-1">
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700" data-action="open-channel" data-author="${video.pubkey || ""}">
|
||||
Open channel
|
||||
</button>
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700" data-action="copy-link" data-event-id="${video.id || ""}">
|
||||
Copy link
|
||||
</button>
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white" data-action="block-author" data-author="${video.pubkey || ""}">
|
||||
Block creator
|
||||
</button>
|
||||
<button class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700" data-action="report" data-event-id="${video.id || ""}">
|
||||
Report
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const cardControls = `
|
||||
<div class="flex items-center">
|
||||
${moreMenu}${gearMenu}
|
||||
</div>
|
||||
`;
|
||||
|
||||
const safeTitle = window.app?.escapeHTML(video.title) || "Untitled";
|
||||
const safeThumb = window.app?.escapeHTML(video.thumbnail) || "";
|
||||
const playbackUrl =
|
||||
typeof video.url === "string" ? video.url : "";
|
||||
const trimmedUrl = playbackUrl ? playbackUrl.trim() : "";
|
||||
const trimmedMagnet =
|
||||
typeof video.magnet === "string" ? video.magnet.trim() : "";
|
||||
const legacyInfoHash =
|
||||
typeof video.infoHash === "string" ? video.infoHash.trim() : "";
|
||||
const magnetCandidate = trimmedMagnet || legacyInfoHash;
|
||||
const playbackMagnet = magnetCandidate;
|
||||
const magnetProvided = magnetCandidate.length > 0;
|
||||
const magnetSupported =
|
||||
window.app?.isMagnetUriSupported?.(magnetCandidate) ?? false;
|
||||
const urlBadgeHtml = trimmedUrl
|
||||
? window.app?.getUrlHealthPlaceholderMarkup?.({ includeMargin: false }) ??
|
||||
""
|
||||
: "";
|
||||
const torrentHealthBadgeHtml =
|
||||
magnetProvided && magnetSupported
|
||||
? window.app?.getTorrentHealthBadgeMarkup?.({
|
||||
includeMargin: false,
|
||||
}) ?? ""
|
||||
: "";
|
||||
const connectionBadgesHtml =
|
||||
urlBadgeHtml || torrentHealthBadgeHtml
|
||||
? `
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2">
|
||||
${urlBadgeHtml}${torrentHealthBadgeHtml}
|
||||
</div>
|
||||
`
|
||||
: "";
|
||||
const cardHtml = `
|
||||
<div class="video-card bg-gray-900 rounded-lg overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 ${highlightClass}">
|
||||
<a
|
||||
href="${shareUrl}"
|
||||
data-play-magnet="${encodeURIComponent(video.magnet)}"
|
||||
data-video-id="${video.id}"
|
||||
data-play-url=""
|
||||
data-play-magnet=""
|
||||
class="block cursor-pointer relative group"
|
||||
>
|
||||
<div class="ratio-16-9">
|
||||
@@ -347,7 +486,9 @@ class SubscriptionsManager {
|
||||
<div class="p-4">
|
||||
<h3
|
||||
class="text-lg font-bold text-white line-clamp-2 hover:text-blue-400 cursor-pointer mb-3"
|
||||
data-play-magnet="${encodeURIComponent(video.magnet)}"
|
||||
data-video-id="${video.id}"
|
||||
data-play-url=""
|
||||
data-play-magnet=""
|
||||
>
|
||||
${safeTitle}
|
||||
</h3>
|
||||
@@ -373,8 +514,9 @@ class SubscriptionsManager {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
${gearMenu}
|
||||
${cardControls}
|
||||
</div>
|
||||
${connectionBadgesHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -382,15 +524,107 @@ class SubscriptionsManager {
|
||||
const t = document.createElement("template");
|
||||
t.innerHTML = cardHtml.trim();
|
||||
const cardEl = t.content.firstElementChild;
|
||||
if (cardEl) {
|
||||
cardEl.dataset.ownerIsViewer = canEdit ? "true" : "false";
|
||||
if (typeof video.pubkey === "string" && video.pubkey) {
|
||||
cardEl.dataset.ownerPubkey = video.pubkey;
|
||||
} else if (cardEl.dataset.ownerPubkey) {
|
||||
delete cardEl.dataset.ownerPubkey;
|
||||
}
|
||||
|
||||
if (trimmedUrl) {
|
||||
cardEl.dataset.urlHealthState = "checking";
|
||||
if (cardEl.dataset.urlHealthReason) {
|
||||
delete cardEl.dataset.urlHealthReason;
|
||||
}
|
||||
cardEl.dataset.urlHealthEventId = video.id || "";
|
||||
cardEl.dataset.urlHealthUrl = encodeURIComponent(trimmedUrl);
|
||||
} else {
|
||||
cardEl.dataset.urlHealthState = "offline";
|
||||
cardEl.dataset.urlHealthReason = "missing-source";
|
||||
if (cardEl.dataset.urlHealthEventId) {
|
||||
delete cardEl.dataset.urlHealthEventId;
|
||||
}
|
||||
if (cardEl.dataset.urlHealthUrl) {
|
||||
delete cardEl.dataset.urlHealthUrl;
|
||||
}
|
||||
}
|
||||
if (magnetProvided && magnetSupported) {
|
||||
cardEl.dataset.streamHealthState = "checking";
|
||||
if (cardEl.dataset.streamHealthReason) {
|
||||
delete cardEl.dataset.streamHealthReason;
|
||||
}
|
||||
} else {
|
||||
cardEl.dataset.streamHealthState = "unhealthy";
|
||||
cardEl.dataset.streamHealthReason = magnetProvided
|
||||
? "unsupported"
|
||||
: "missing-source";
|
||||
}
|
||||
|
||||
// Leave the data-play-* attributes empty in the literal markup so we can
|
||||
// assign the raw URL/magnet strings post-parsing without HTML entity
|
||||
// escaping, mirroring the approach in app.js. The URL is encoded so that
|
||||
// special characters survive storage in data-* attributes; the click
|
||||
// handler decodes it right before playback while keeping the magnet raw.
|
||||
const interactiveEls = cardEl.querySelectorAll("[data-video-id]");
|
||||
interactiveEls.forEach((el) => {
|
||||
if (!el.dataset) return;
|
||||
|
||||
if (trimmedUrl) {
|
||||
el.dataset.playUrl = encodeURIComponent(trimmedUrl);
|
||||
} else {
|
||||
delete el.dataset.playUrl;
|
||||
}
|
||||
|
||||
el.dataset.playMagnet = playbackMagnet || "";
|
||||
});
|
||||
|
||||
if (magnetProvided) {
|
||||
cardEl.dataset.magnet = playbackMagnet;
|
||||
} else if (cardEl.dataset.magnet) {
|
||||
delete cardEl.dataset.magnet;
|
||||
}
|
||||
|
||||
const badgeEl = cardEl.querySelector("[data-url-health-state]");
|
||||
if (badgeEl) {
|
||||
if (trimmedUrl) {
|
||||
badgeEl.dataset.urlHealthEventId = video.id || "";
|
||||
badgeEl.dataset.urlHealthUrl = encodeURIComponent(trimmedUrl);
|
||||
} else {
|
||||
if (badgeEl.dataset.urlHealthEventId) {
|
||||
delete badgeEl.dataset.urlHealthEventId;
|
||||
}
|
||||
if (badgeEl.dataset.urlHealthUrl) {
|
||||
delete badgeEl.dataset.urlHealthUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fragment.appendChild(cardEl);
|
||||
});
|
||||
|
||||
container.appendChild(fragment);
|
||||
attachHealthBadges(container);
|
||||
attachUrlHealthBadges(container, ({ badgeEl, url, eventId }) => {
|
||||
if (!window.app?.handleUrlHealthBadge) {
|
||||
return;
|
||||
}
|
||||
const video =
|
||||
window.app.videosMap?.get?.(eventId) || { id: eventId };
|
||||
window.app.handleUrlHealthBadge({ video, url, badgeEl });
|
||||
});
|
||||
|
||||
if (window.app) {
|
||||
window.app.videoList = container;
|
||||
window.app.attachVideoListHandler?.();
|
||||
}
|
||||
|
||||
// Lazy-load
|
||||
const lazyEls = container.querySelectorAll("[data-lazy]");
|
||||
lazyEls.forEach((el) => window.app?.mediaLoader.observe(el));
|
||||
|
||||
window.app?.attachMoreMenuHandlers?.(container);
|
||||
|
||||
// Gear menus
|
||||
const gearButtons = container.querySelectorAll("[data-settings-dropdown]");
|
||||
gearButtons.forEach((btn) => {
|
||||
@@ -407,10 +641,15 @@ class SubscriptionsManager {
|
||||
editButtons.forEach((btn) => {
|
||||
btn.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const idx = btn.getAttribute("data-edit-index");
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idx}`);
|
||||
const idxAttr = btn.getAttribute("data-edit-index");
|
||||
const idx = Number.parseInt(idxAttr, 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idxAttr}`);
|
||||
if (dropdown) dropdown.classList.add("hidden");
|
||||
window.app?.handleEditVideo(idx);
|
||||
const eventId = btn.getAttribute("data-edit-event-id") || "";
|
||||
window.app?.handleEditVideo({
|
||||
eventId,
|
||||
index: Number.isNaN(idx) ? null : idx,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -419,10 +658,15 @@ class SubscriptionsManager {
|
||||
revertButtons.forEach((btn) => {
|
||||
btn.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const idx = btn.getAttribute("data-revert-index");
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idx}`);
|
||||
const idxAttr = btn.getAttribute("data-revert-index");
|
||||
const idx = Number.parseInt(idxAttr, 10);
|
||||
const dropdown = document.getElementById(`settingsDropdown-${idxAttr}`);
|
||||
if (dropdown) dropdown.classList.add("hidden");
|
||||
window.app?.handleRevertVideo(idx);
|
||||
const eventId = btn.getAttribute("data-revert-event-id") || "";
|
||||
window.app?.handleRevertVideo({
|
||||
eventId,
|
||||
index: Number.isNaN(idx) ? null : idx,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -433,10 +677,15 @@ class SubscriptionsManager {
|
||||
deleteAllButtons.forEach((btn) => {
|
||||
btn.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const idx = btn.getAttribute("data-delete-all-index");
|
||||
const dd = document.getElementById(`settingsDropdown-${idx}`);
|
||||
const idxAttr = btn.getAttribute("data-delete-all-index");
|
||||
const idx = Number.parseInt(idxAttr, 10);
|
||||
const dd = document.getElementById(`settingsDropdown-${idxAttr}`);
|
||||
if (dd) dd.classList.add("hidden");
|
||||
window.app?.handleFullDeleteVideo(idx);
|
||||
const eventId = btn.getAttribute("data-delete-all-event-id") || "";
|
||||
window.app?.handleFullDeleteVideo({
|
||||
eventId,
|
||||
index: Number.isNaN(idx) ? null : idx,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -480,31 +729,7 @@ class SubscriptionsManager {
|
||||
}
|
||||
|
||||
convertEventToVideo(evt) {
|
||||
try {
|
||||
const content = JSON.parse(evt.content || "{}");
|
||||
const hasFields = !!(content.title && content.magnet);
|
||||
const versionOk = content.version >= 2;
|
||||
if (!versionOk || !hasFields) {
|
||||
return { id: evt.id, invalid: true };
|
||||
}
|
||||
return {
|
||||
id: evt.id,
|
||||
pubkey: evt.pubkey,
|
||||
created_at: evt.created_at,
|
||||
videoRootId: content.videoRootId || evt.id,
|
||||
version: content.version,
|
||||
deleted: content.deleted === true,
|
||||
isPrivate: content.isPrivate === true,
|
||||
title: content.title || "",
|
||||
magnet: content.magnet || "",
|
||||
thumbnail: content.thumbnail || "",
|
||||
description: content.description || "",
|
||||
tags: evt.tags || [],
|
||||
invalid: false,
|
||||
};
|
||||
} catch (err) {
|
||||
return { id: evt.id, invalid: true };
|
||||
}
|
||||
return sharedConvertEventToVideo(evt);
|
||||
}
|
||||
|
||||
dedupeToNewestByRoot(videos) {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { WSS_TRACKERS as DEFAULT_WSS_TRACKERS } from "./constants.js";
|
||||
|
||||
export const TRACKER_TIMEOUT_MS = 3000;
|
||||
export const TRACKER_PER_MAGNET = 3;
|
||||
export const HEALTH_TTL_MS = 2 * 60 * 1000;
|
||||
export const CONCURRENCY = 3;
|
||||
export const TRACKER_ERROR_COOLDOWN_MS = 60 * 1000;
|
||||
|
||||
export function resolveTrackerList({ magnetTrackers } = {}) {
|
||||
const combined = [];
|
||||
const seen = new Set();
|
||||
|
||||
const pushUnique = (url) => {
|
||||
if (typeof url !== "string") {
|
||||
return;
|
||||
}
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
if (!/^wss:\/\//i.test(trimmed)) {
|
||||
return;
|
||||
}
|
||||
const normalized = trimmed.toLowerCase();
|
||||
if (seen.has(normalized)) {
|
||||
return;
|
||||
}
|
||||
seen.add(normalized);
|
||||
combined.push(trimmed);
|
||||
};
|
||||
|
||||
if (Array.isArray(magnetTrackers)) {
|
||||
magnetTrackers.forEach(pushUnique);
|
||||
}
|
||||
|
||||
DEFAULT_WSS_TRACKERS.forEach(pushUnique);
|
||||
|
||||
return combined.slice(0, TRACKER_PER_MAGNET);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import "./bufferPolyfill.js";
|
||||
import Client from "https://esm.sh/[email protected]/client?bundle";
|
||||
import { infoHashFromMagnet, trackersFromMagnet } from "./magnets.js";
|
||||
import {
|
||||
resolveTrackerList,
|
||||
TRACKER_TIMEOUT_MS,
|
||||
TRACKER_ERROR_COOLDOWN_MS,
|
||||
} from "./trackerConfig.js";
|
||||
|
||||
const trackerState = new Map();
|
||||
|
||||
function now() {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function randomPeerId() {
|
||||
const bytes = new Uint8Array(20);
|
||||
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
|
||||
crypto.getRandomValues(bytes);
|
||||
} else {
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
bytes[i] = Math.floor(Math.random() * 256);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function getDefaultHealth() {
|
||||
return {
|
||||
ok: false,
|
||||
seeders: 0,
|
||||
leechers: 0,
|
||||
responded: false,
|
||||
from: [],
|
||||
};
|
||||
}
|
||||
|
||||
function getTrackerEntry(url) {
|
||||
const existing = trackerState.get(url);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const entry = {
|
||||
consecutiveErrors: 0,
|
||||
lastErrorAt: 0,
|
||||
cooldownUntil: 0,
|
||||
};
|
||||
trackerState.set(url, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function markTrackerSuccess(url) {
|
||||
const entry = getTrackerEntry(url);
|
||||
entry.consecutiveErrors = 0;
|
||||
entry.cooldownUntil = 0;
|
||||
}
|
||||
|
||||
function markTrackerError(url) {
|
||||
const entry = getTrackerEntry(url);
|
||||
const nowTs = now();
|
||||
if (entry.lastErrorAt && nowTs - entry.lastErrorAt < TRACKER_ERROR_COOLDOWN_MS) {
|
||||
entry.consecutiveErrors += 1;
|
||||
} else {
|
||||
entry.consecutiveErrors = 1;
|
||||
}
|
||||
entry.lastErrorAt = nowTs;
|
||||
if (entry.consecutiveErrors >= 2) {
|
||||
entry.cooldownUntil = nowTs + TRACKER_ERROR_COOLDOWN_MS;
|
||||
}
|
||||
}
|
||||
|
||||
function isTrackerUsable(url) {
|
||||
const entry = getTrackerEntry(url);
|
||||
return entry.cooldownUntil === 0 || entry.cooldownUntil <= now();
|
||||
}
|
||||
|
||||
export async function trackerPing(magnet, trackers) {
|
||||
const infoHash = infoHashFromMagnet(magnet);
|
||||
if (!infoHash) {
|
||||
return getDefaultHealth();
|
||||
}
|
||||
|
||||
const magnetTrackers = trackers || trackersFromMagnet(magnet);
|
||||
const announceList = resolveTrackerList({ magnetTrackers });
|
||||
const usable = announceList.filter(isTrackerUsable);
|
||||
const announces = usable.length ? usable : announceList;
|
||||
|
||||
if (!announces.length) {
|
||||
return getDefaultHealth();
|
||||
}
|
||||
|
||||
const peerId = randomPeerId();
|
||||
const result = getDefaultHealth();
|
||||
const clients = new Set();
|
||||
let settled = false;
|
||||
let timeoutId = null;
|
||||
|
||||
const finalize = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
clients.forEach((client) => {
|
||||
try {
|
||||
client.destroy();
|
||||
} catch (err) {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
clients.clear();
|
||||
};
|
||||
|
||||
return new Promise((resolve) => {
|
||||
if (Number.isFinite(TRACKER_TIMEOUT_MS) && TRACKER_TIMEOUT_MS > 0) {
|
||||
timeoutId = setTimeout(() => {
|
||||
finalize();
|
||||
resolve(result);
|
||||
}, TRACKER_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
let remaining = announces.length;
|
||||
|
||||
const handleComplete = (client, url) => {
|
||||
if (clients.has(client)) {
|
||||
clients.delete(client);
|
||||
}
|
||||
if (url && result.from.includes(url) && result.ok) {
|
||||
markTrackerSuccess(url);
|
||||
}
|
||||
remaining -= 1;
|
||||
if (remaining <= 0 && !settled) {
|
||||
finalize();
|
||||
resolve(result);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResult = (url, data) => {
|
||||
result.responded = true;
|
||||
if (url && !result.from.includes(url)) {
|
||||
result.from.push(url);
|
||||
}
|
||||
const seeders = Number.isFinite(data?.complete)
|
||||
? Number(data.complete)
|
||||
: 0;
|
||||
const leechers = Number.isFinite(data?.incomplete)
|
||||
? Number(data.incomplete)
|
||||
: 0;
|
||||
if (seeders > result.seeders) {
|
||||
result.seeders = seeders;
|
||||
}
|
||||
if (leechers > result.leechers) {
|
||||
result.leechers = leechers;
|
||||
}
|
||||
if (seeders > 0) {
|
||||
result.ok = true;
|
||||
}
|
||||
};
|
||||
|
||||
announces.forEach((url) => {
|
||||
let client;
|
||||
try {
|
||||
client = new Client({
|
||||
infoHash,
|
||||
peerId,
|
||||
announce: [url],
|
||||
});
|
||||
} catch (err) {
|
||||
markTrackerError(url);
|
||||
remaining -= 1;
|
||||
if (remaining <= 0 && !settled) {
|
||||
finalize();
|
||||
resolve(result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
clients.add(client);
|
||||
|
||||
const cleanupAndResolve = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
finalize();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
client.once("update", (data) => {
|
||||
handleResult(url, data);
|
||||
markTrackerSuccess(url);
|
||||
if (result.ok) {
|
||||
cleanupAndResolve();
|
||||
return;
|
||||
}
|
||||
handleComplete(client, url);
|
||||
});
|
||||
|
||||
client.once("error", () => {
|
||||
markTrackerError(url);
|
||||
handleComplete(client, url);
|
||||
});
|
||||
|
||||
client.once("warning", () => {
|
||||
handleComplete(client, url);
|
||||
});
|
||||
|
||||
try {
|
||||
client.start();
|
||||
} catch (err) {
|
||||
markTrackerError(url);
|
||||
handleComplete(client, url);
|
||||
}
|
||||
});
|
||||
|
||||
if (announces.length === 0) {
|
||||
finalize();
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function getTrackerStateSnapshot() {
|
||||
const snapshot = {};
|
||||
trackerState.forEach((value, key) => {
|
||||
snapshot[key] = { ...value };
|
||||
});
|
||||
return snapshot;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// js/tracking.js
|
||||
// Centralized configuration and loader for the site's analytics script.
|
||||
// Update `bitvidTrackingConfig` to change the tracking provider or settings.
|
||||
window.bitvidTrackingConfig = window.bitvidTrackingConfig || {
|
||||
src: "https://umami.malin.onl/script.js",
|
||||
websiteId: "1f8eead2-79f0-4dba-8c3b-ed9b08b6e877",
|
||||
};
|
||||
|
||||
(function loadTrackingScript(config) {
|
||||
if (!config || !config.src) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (document.querySelector(`script[src="${config.src}"]`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const script = document.createElement("script");
|
||||
script.src = config.src;
|
||||
script.defer = true;
|
||||
|
||||
if (config.websiteId) {
|
||||
script.setAttribute("data-website-id", config.websiteId);
|
||||
}
|
||||
|
||||
const additionalAttributes = config.attributes || {};
|
||||
Object.entries(additionalAttributes).forEach(([key, value]) => {
|
||||
if (key === "defer") {
|
||||
script.defer = Boolean(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (value === false || value === null || typeof value === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
script.setAttribute(key, value);
|
||||
});
|
||||
|
||||
document.head.appendChild(script);
|
||||
})(window.bitvidTrackingConfig);
|
||||
@@ -0,0 +1,124 @@
|
||||
const containerState = new WeakMap();
|
||||
const ROOT_MARGIN = "0px";
|
||||
const THRESHOLD = 0.25;
|
||||
|
||||
function decodeUrl(value) {
|
||||
if (typeof value !== "string" || !value) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch (err) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureState(container) {
|
||||
let state = containerState.get(container);
|
||||
if (state) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const observedCards = new WeakSet();
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
processEntries(entries, state);
|
||||
},
|
||||
{ root: null, rootMargin: ROOT_MARGIN, threshold: THRESHOLD }
|
||||
);
|
||||
|
||||
state = {
|
||||
observer,
|
||||
observedCards,
|
||||
onCheck: null,
|
||||
};
|
||||
containerState.set(container, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
function processEntries(entries, state) {
|
||||
if (!state?.onCheck || !Array.isArray(entries) || !entries.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting || entry.intersectionRatio <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const card = entry.target;
|
||||
if (!(card instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const badgeEl = card.querySelector("[data-url-health-state]");
|
||||
if (!(badgeEl instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const encodedUrl =
|
||||
card.dataset.urlHealthUrl || badgeEl.dataset.urlHealthUrl || "";
|
||||
const eventId =
|
||||
card.dataset.urlHealthEventId || badgeEl.dataset.urlHealthEventId || "";
|
||||
|
||||
if (!encodedUrl || !eventId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentState =
|
||||
card.dataset.urlHealthState || badgeEl.dataset.urlHealthState;
|
||||
if (currentState && currentState !== "checking") {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = decodeUrl(encodedUrl);
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
state.onCheck({ card, badgeEl, url, eventId });
|
||||
} catch (err) {
|
||||
console.warn("[urlHealthObserver] onCheck handler failed", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function attachUrlHealthBadges(container, onCheck) {
|
||||
if (!(container instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = ensureState(container);
|
||||
if (typeof onCheck === "function") {
|
||||
state.onCheck = onCheck;
|
||||
}
|
||||
|
||||
const cards = container.querySelectorAll(".video-card");
|
||||
cards.forEach((card) => {
|
||||
if (!(card instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
if (state.observedCards.has(card)) {
|
||||
return;
|
||||
}
|
||||
state.observedCards.add(card);
|
||||
state.observer.observe(card);
|
||||
});
|
||||
|
||||
const records = state.observer.takeRecords();
|
||||
if (records.length) {
|
||||
processEntries(records, state);
|
||||
}
|
||||
}
|
||||
|
||||
export function refreshUrlHealthBadges(container) {
|
||||
const state = containerState.get(container);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
const records = state.observer.takeRecords();
|
||||
if (records.length) {
|
||||
processEntries(records, state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// js/userBlocks.js
|
||||
import { nostrClient } from "./nostr.js";
|
||||
|
||||
const BLOCK_LIST_IDENTIFIER = "user-blocks";
|
||||
|
||||
function normalizeHex(pubkey) {
|
||||
if (typeof pubkey !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = pubkey.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (/^[0-9a-f]{64}$/i.test(trimmed)) {
|
||||
return trimmed.toLowerCase();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
class UserBlockListManager {
|
||||
constructor() {
|
||||
this.blockedPubkeys = new Set();
|
||||
this.blockEventId = null;
|
||||
this.loaded = false;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.blockedPubkeys.clear();
|
||||
this.blockEventId = null;
|
||||
this.loaded = false;
|
||||
}
|
||||
|
||||
getBlockedPubkeys() {
|
||||
return Array.from(this.blockedPubkeys);
|
||||
}
|
||||
|
||||
isBlocked(pubkey) {
|
||||
const normalized = normalizeHex(pubkey);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
return this.blockedPubkeys.has(normalized);
|
||||
}
|
||||
|
||||
async ensureLoaded(userPubkey) {
|
||||
if (this.loaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = normalizeHex(userPubkey);
|
||||
if (!normalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.loadBlocks(normalized);
|
||||
}
|
||||
|
||||
async loadBlocks(userPubkey) {
|
||||
const normalized = normalizeHex(userPubkey);
|
||||
if (!normalized) {
|
||||
this.reset();
|
||||
this.loaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window?.nostr?.nip04?.decrypt) {
|
||||
console.warn(
|
||||
"[UserBlockList] nip04.decrypt is unavailable; treating block list as empty."
|
||||
);
|
||||
this.reset();
|
||||
this.loaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const filter = {
|
||||
kinds: [30002],
|
||||
authors: [normalized],
|
||||
"#d": [BLOCK_LIST_IDENTIFIER],
|
||||
limit: 1,
|
||||
};
|
||||
|
||||
const events = [];
|
||||
for (const relay of nostrClient.relays) {
|
||||
try {
|
||||
const res = await nostrClient.pool.list([relay], [filter]);
|
||||
if (Array.isArray(res) && res.length) {
|
||||
events.push(...res);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[UserBlockList] Relay error at ${relay}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!events.length) {
|
||||
this.blockedPubkeys.clear();
|
||||
this.blockEventId = null;
|
||||
this.loaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
events.sort((a, b) => b.created_at - a.created_at);
|
||||
const newest = events[0];
|
||||
this.blockEventId = newest.id;
|
||||
|
||||
let decrypted = "";
|
||||
try {
|
||||
decrypted = await window.nostr.nip04.decrypt(
|
||||
normalized,
|
||||
newest.content
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[UserBlockList] Failed to decrypt block list:", err);
|
||||
this.blockedPubkeys.clear();
|
||||
this.loaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(decrypted);
|
||||
const list = Array.isArray(parsed?.blockedPubkeys)
|
||||
? parsed.blockedPubkeys
|
||||
: [];
|
||||
const sanitized = list
|
||||
.map((entry) => normalizeHex(entry))
|
||||
.filter((candidate) => {
|
||||
if (!candidate) {
|
||||
return false;
|
||||
}
|
||||
if (candidate === normalized) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
this.blockedPubkeys = new Set(sanitized);
|
||||
} catch (err) {
|
||||
console.error("[UserBlockList] Failed to parse block list:", err);
|
||||
this.blockedPubkeys.clear();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[UserBlockList] loadBlocks failed:", error);
|
||||
this.blockedPubkeys.clear();
|
||||
} finally {
|
||||
this.loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
async addBlock(targetPubkey, userPubkey) {
|
||||
const actorHex = normalizeHex(userPubkey);
|
||||
if (!actorHex) {
|
||||
throw new Error("Invalid user pubkey.");
|
||||
}
|
||||
|
||||
const targetHex = normalizeHex(targetPubkey);
|
||||
if (!targetHex) {
|
||||
const err = new Error("Invalid target pubkey.");
|
||||
err.code = "invalid";
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (actorHex === targetHex) {
|
||||
const err = new Error("Cannot block yourself.");
|
||||
err.code = "self";
|
||||
throw err;
|
||||
}
|
||||
|
||||
await this.ensureLoaded(actorHex);
|
||||
|
||||
if (this.blockedPubkeys.has(targetHex)) {
|
||||
return { ok: true, already: true };
|
||||
}
|
||||
|
||||
const snapshot = new Set(this.blockedPubkeys);
|
||||
this.blockedPubkeys.add(targetHex);
|
||||
|
||||
try {
|
||||
await this.publishBlockList(actorHex);
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
this.blockedPubkeys = snapshot;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async removeBlock(targetPubkey, userPubkey) {
|
||||
const actorHex = normalizeHex(userPubkey);
|
||||
if (!actorHex) {
|
||||
throw new Error("Invalid user pubkey.");
|
||||
}
|
||||
|
||||
const targetHex = normalizeHex(targetPubkey);
|
||||
if (!targetHex) {
|
||||
return { ok: true, already: true };
|
||||
}
|
||||
|
||||
await this.ensureLoaded(actorHex);
|
||||
|
||||
if (!this.blockedPubkeys.has(targetHex)) {
|
||||
return { ok: true, already: true };
|
||||
}
|
||||
|
||||
const snapshot = new Set(this.blockedPubkeys);
|
||||
this.blockedPubkeys.delete(targetHex);
|
||||
|
||||
try {
|
||||
await this.publishBlockList(actorHex);
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
this.blockedPubkeys = snapshot;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async publishBlockList(userPubkey) {
|
||||
if (!window?.nostr?.nip04?.encrypt) {
|
||||
const err = new Error(
|
||||
"NIP-04 encryption is required to update the block list."
|
||||
);
|
||||
err.code = "nip04-missing";
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (typeof window.nostr.signEvent !== "function") {
|
||||
const err = new Error("Nostr extension missing signEvent support.");
|
||||
err.code = "nip04-missing";
|
||||
throw err;
|
||||
}
|
||||
|
||||
const normalized = normalizeHex(userPubkey);
|
||||
if (!normalized) {
|
||||
throw new Error("Invalid user pubkey.");
|
||||
}
|
||||
|
||||
const payload = {
|
||||
blockedPubkeys: Array.from(this.blockedPubkeys).filter(
|
||||
(candidate) => candidate && candidate !== normalized
|
||||
),
|
||||
};
|
||||
const plaintext = JSON.stringify(payload);
|
||||
|
||||
let cipherText = "";
|
||||
try {
|
||||
cipherText = await window.nostr.nip04.encrypt(normalized, plaintext);
|
||||
} catch (error) {
|
||||
const err = new Error("Failed to encrypt block list.");
|
||||
err.code = "nip04-missing";
|
||||
throw err;
|
||||
}
|
||||
|
||||
const event = {
|
||||
kind: 30002,
|
||||
pubkey: normalized,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [["d", BLOCK_LIST_IDENTIFIER]],
|
||||
content: cipherText,
|
||||
};
|
||||
|
||||
const signedEvent = await window.nostr.signEvent(event);
|
||||
|
||||
await Promise.all(
|
||||
nostrClient.relays.map(async (relay) => {
|
||||
try {
|
||||
await nostrClient.pool.publish([relay], signedEvent);
|
||||
} catch (err) {
|
||||
console.error(`[UserBlockList] Failed to publish to ${relay}:`, err);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
this.blockEventId = signedEvent.id;
|
||||
return signedEvent;
|
||||
}
|
||||
}
|
||||
|
||||
export const userBlocks = new UserBlockListManager();
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.userBlocks = userBlocks;
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
// js/videoEventUtils.js
|
||||
|
||||
/**
|
||||
* Extracts normalized fields from a Bitvid video event while
|
||||
* tolerating legacy payloads that may omit version >= 2 metadata.
|
||||
*/
|
||||
const MAGNET_URI_PATTERN = /^magnet:\?/i;
|
||||
const HEX_INFO_HASH_PATTERN = /\b[0-9a-f]{40}\b/gi;
|
||||
const LEGACY_MAGNET_PATTERN = /magnet:\?xt=urn:btih:[0-9a-z]{40,}[^\s"'<>]*/i;
|
||||
|
||||
function safeTrim(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function pickFirstString(values = []) {
|
||||
if (!Array.isArray(values)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
for (const value of values) {
|
||||
const trimmed = safeTrim(value);
|
||||
if (trimmed) {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
export function deriveTitleFromEvent({
|
||||
parsedContent = {},
|
||||
tags = [],
|
||||
primaryTitle = "",
|
||||
} = {}) {
|
||||
const initial = safeTrim(primaryTitle);
|
||||
if (initial) {
|
||||
return initial;
|
||||
}
|
||||
|
||||
const directCandidates = pickFirstString([
|
||||
parsedContent?.title,
|
||||
parsedContent?.name,
|
||||
parsedContent?.filename,
|
||||
parsedContent?.fileName,
|
||||
parsedContent?.subject,
|
||||
parsedContent?.caption,
|
||||
]);
|
||||
if (directCandidates) {
|
||||
return directCandidates;
|
||||
}
|
||||
|
||||
const metaTitle = safeTrim(parsedContent?.meta?.title);
|
||||
if (metaTitle) {
|
||||
return metaTitle;
|
||||
}
|
||||
|
||||
if (Array.isArray(tags)) {
|
||||
for (const tag of tags) {
|
||||
if (!Array.isArray(tag) || tag.length < 2) {
|
||||
continue;
|
||||
}
|
||||
const key = safeTrim(tag[0]).toLowerCase();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
if (["title", "subject", "caption", "name"].includes(key)) {
|
||||
const candidate = safeTrim(tag[1]);
|
||||
if (candidate) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractInfoHashesFromString(value, pushInfoHash) {
|
||||
if (typeof value !== "string") {
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const matches = trimmed.match(HEX_INFO_HASH_PATTERN);
|
||||
if (!matches) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const match of matches) {
|
||||
const normalized = match.toLowerCase();
|
||||
pushInfoHash(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
function traverseForInfoHashes(value, pushInfoHash) {
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
extractInfoHashesFromString(value, pushInfoHash);
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
traverseForInfoHashes(item, pushInfoHash);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
for (const nested of Object.values(value)) {
|
||||
traverseForInfoHashes(nested, pushInfoHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseVideoEventPayload(event = {}) {
|
||||
const rawContent = typeof event.content === "string" ? event.content : "";
|
||||
|
||||
let parsedContent = {};
|
||||
let parseError = null;
|
||||
if (rawContent) {
|
||||
try {
|
||||
const parsed = JSON.parse(rawContent);
|
||||
if (parsed && typeof parsed === "object") {
|
||||
parsedContent = parsed;
|
||||
}
|
||||
} catch (err) {
|
||||
parseError = err;
|
||||
parsedContent = {};
|
||||
}
|
||||
}
|
||||
|
||||
const title = typeof parsedContent.title === "string"
|
||||
? parsedContent.title.trim()
|
||||
: "";
|
||||
const thumbnail = typeof parsedContent.thumbnail === "string"
|
||||
? parsedContent.thumbnail.trim()
|
||||
: "";
|
||||
|
||||
const magnetCandidates = [];
|
||||
const infoHashCandidates = [];
|
||||
const urlCandidates = [];
|
||||
|
||||
const pushUnique = (arr, value) => {
|
||||
if (!value || typeof value !== "string") return;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || arr.includes(trimmed)) return;
|
||||
arr.push(trimmed);
|
||||
};
|
||||
|
||||
const pushInfoHash = (candidate) => {
|
||||
if (!candidate) return;
|
||||
const normalized = candidate.toLowerCase();
|
||||
if (!/^[0-9a-f]{40}$/.test(normalized)) {
|
||||
return;
|
||||
}
|
||||
if (infoHashCandidates.includes(normalized)) {
|
||||
return;
|
||||
}
|
||||
infoHashCandidates.push(normalized);
|
||||
};
|
||||
|
||||
const collectMagnetOrInfoHash = (value) => {
|
||||
if (typeof value !== "string") {
|
||||
return;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (MAGNET_URI_PATTERN.test(trimmed)) {
|
||||
pushUnique(magnetCandidates, trimmed);
|
||||
}
|
||||
|
||||
extractInfoHashesFromString(trimmed, pushInfoHash);
|
||||
|
||||
const urnMatch = trimmed.match(/^urn:btih:([0-9a-z]+)$/i);
|
||||
if (urnMatch) {
|
||||
pushInfoHash(urnMatch[1]);
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof parsedContent.magnet === "string") {
|
||||
collectMagnetOrInfoHash(parsedContent.magnet);
|
||||
}
|
||||
if (typeof parsedContent.url === "string") {
|
||||
const parsedUrl = parsedContent.url.trim();
|
||||
if (parsedUrl && parsedUrl !== thumbnail) {
|
||||
// Keep this guard so we don't duplicate thumbnail URLs in the playable URL list.
|
||||
pushUnique(urlCandidates, parsedUrl);
|
||||
}
|
||||
// Legacy Bitvid events sometimes embedded magnets/info-hashes in the URL field, so treat it accordingly.
|
||||
collectMagnetOrInfoHash(parsedUrl);
|
||||
}
|
||||
|
||||
const tags = Array.isArray(event.tags) ? event.tags : [];
|
||||
const urlTagKeys = new Set(["r", "url", "u"]);
|
||||
for (const tag of tags) {
|
||||
if (!Array.isArray(tag) || tag.length < 2) continue;
|
||||
const key = typeof tag[0] === "string" ? tag[0] : "";
|
||||
const value = typeof tag[1] === "string" ? tag[1] : "";
|
||||
if (!value) continue;
|
||||
|
||||
if (value.toLowerCase().startsWith("magnet:")) {
|
||||
collectMagnetOrInfoHash(value);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (urlTagKeys.has(key) && /^https?:\/\//i.test(value)) {
|
||||
pushUnique(urlCandidates, value);
|
||||
}
|
||||
|
||||
collectMagnetOrInfoHash(value);
|
||||
}
|
||||
|
||||
const magnetMatch = rawContent.match(/magnet:\?xt=urn:[^"'\s<>]+/i);
|
||||
if (magnetMatch) {
|
||||
collectMagnetOrInfoHash(magnetMatch[0]);
|
||||
}
|
||||
|
||||
extractInfoHashesFromString(rawContent, pushInfoHash);
|
||||
traverseForInfoHashes(parsedContent, pushInfoHash);
|
||||
|
||||
const magnet = magnetCandidates.find(Boolean) || "";
|
||||
const infoHash = infoHashCandidates.find(Boolean) || "";
|
||||
const url =
|
||||
urlCandidates.find(
|
||||
(candidate) => candidate && !candidate.toLowerCase().startsWith("magnet:")
|
||||
) || "";
|
||||
|
||||
const rawVersion = parsedContent.version;
|
||||
let version = 0;
|
||||
if (typeof rawVersion === "number" && Number.isFinite(rawVersion)) {
|
||||
version = rawVersion;
|
||||
} else if (typeof rawVersion === "string") {
|
||||
const parsedVersion = Number(rawVersion);
|
||||
if (!Number.isNaN(parsedVersion)) {
|
||||
version = parsedVersion;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
parsedContent,
|
||||
parseError,
|
||||
title,
|
||||
url,
|
||||
magnet,
|
||||
infoHash,
|
||||
version,
|
||||
};
|
||||
}
|
||||
|
||||
export function magnetFromText(value) {
|
||||
if (typeof value !== "string") {
|
||||
return "";
|
||||
}
|
||||
const match = value.match(LEGACY_MAGNET_PATTERN);
|
||||
return match ? match[0] : "";
|
||||
}
|
||||
|
||||
export function findLegacyMagnetInEvent(event = {}) {
|
||||
const fromContent = magnetFromText(event?.content);
|
||||
if (fromContent) {
|
||||
return fromContent.trim();
|
||||
}
|
||||
|
||||
const tags = Array.isArray(event?.tags) ? event.tags : [];
|
||||
for (const tag of tags) {
|
||||
if (!Array.isArray(tag) || tag.length < 2) {
|
||||
continue;
|
||||
}
|
||||
const key = typeof tag[0] === "string" ? tag[0].trim().toLowerCase() : "";
|
||||
const value = typeof tag[1] === "string" ? tag[1].trim() : "";
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
if (key === "magnet" && value) {
|
||||
return value;
|
||||
}
|
||||
const fromTag = magnetFromText(value);
|
||||
if (fromTag) {
|
||||
return fromTag.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
@@ -2,11 +2,17 @@
|
||||
import { initChannelProfileView } from "./channelProfile.js";
|
||||
import { subscriptions } from "./subscriptions.js";
|
||||
|
||||
const TRACKING_SCRIPT_PATTERN = /(?:^|\/)tracking\.js(?:$|\?)/;
|
||||
|
||||
/**
|
||||
* Load a partial view by URL into the #viewContainer.
|
||||
*/
|
||||
export async function loadView(viewUrl) {
|
||||
try {
|
||||
if (window.app && typeof window.app.prepareForViewLoad === "function") {
|
||||
window.app.prepareForViewLoad();
|
||||
}
|
||||
|
||||
const res = await fetch(viewUrl);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load view: ${res.status}`);
|
||||
@@ -23,6 +29,10 @@ export async function loadView(viewUrl) {
|
||||
// Copy and execute any inline scripts
|
||||
const scriptTags = doc.querySelectorAll("script");
|
||||
scriptTags.forEach((oldScript) => {
|
||||
const src = oldScript.getAttribute("src") || "";
|
||||
if (src && TRACKING_SCRIPT_PATTERN.test(src)) {
|
||||
return;
|
||||
}
|
||||
const newScript = document.createElement("script");
|
||||
Array.from(oldScript.attributes).forEach((attr) => {
|
||||
newScript.setAttribute(attr.name, attr.value);
|
||||
@@ -44,6 +54,9 @@ export const viewInitRegistry = {
|
||||
"most-recent-videos": () => {
|
||||
if (window.app && window.app.loadVideos) {
|
||||
window.app.videoList = document.getElementById("videoList");
|
||||
if (window.app.attachVideoListHandler) {
|
||||
window.app.attachVideoListHandler();
|
||||
}
|
||||
window.app.loadVideos();
|
||||
}
|
||||
// Force profile updates after the new view is in place.
|
||||
|
||||
+570
-22
@@ -2,11 +2,145 @@
|
||||
|
||||
import WebTorrent from "./webtorrent.min.js";
|
||||
|
||||
const DEFAULT_PROBE_TRACKERS = Object.freeze([
|
||||
"wss://tracker.btorrent.xyz",
|
||||
"wss://tracker.openwebtorrent.com",
|
||||
]);
|
||||
|
||||
function decodeComponentSafe(value) {
|
||||
if (typeof value !== "string") {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch (err) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTrackerList(trackers) {
|
||||
const normalized = [];
|
||||
const seen = new Set();
|
||||
if (!Array.isArray(trackers)) {
|
||||
return normalized;
|
||||
}
|
||||
trackers.forEach((tracker) => {
|
||||
if (typeof tracker !== "string") {
|
||||
return;
|
||||
}
|
||||
const trimmed = tracker.trim();
|
||||
if (!trimmed || !/^wss:\/\//i.test(trimmed)) {
|
||||
return;
|
||||
}
|
||||
const lower = trimmed.toLowerCase();
|
||||
if (seen.has(lower)) {
|
||||
return;
|
||||
}
|
||||
seen.add(lower);
|
||||
normalized.push(trimmed);
|
||||
});
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function appendProbeTrackers(magnetURI, trackers) {
|
||||
if (typeof magnetURI !== "string") {
|
||||
return { magnet: "", appended: false, hasProbeTrackers: false };
|
||||
}
|
||||
|
||||
const trimmedMagnet = magnetURI.trim();
|
||||
if (!trimmedMagnet) {
|
||||
return { magnet: "", appended: false, hasProbeTrackers: false };
|
||||
}
|
||||
|
||||
const probeTrackers = normalizeTrackerList(trackers);
|
||||
if (!probeTrackers.length) {
|
||||
return {
|
||||
magnet: trimmedMagnet,
|
||||
appended: false,
|
||||
hasProbeTrackers: false,
|
||||
};
|
||||
}
|
||||
|
||||
const trackerSet = new Set();
|
||||
const [withoutFragment, fragment = ""] = trimmedMagnet.split("#", 2);
|
||||
const [, queryPart = ""] = withoutFragment.split("?", 2);
|
||||
|
||||
if (queryPart) {
|
||||
queryPart
|
||||
.split("&")
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean)
|
||||
.forEach((segment) => {
|
||||
const [rawKey, rawValue = ""] = segment.split("=", 2);
|
||||
if (!rawKey || rawKey.trim().toLowerCase() !== "tr") {
|
||||
return;
|
||||
}
|
||||
const decoded = decodeComponentSafe(rawValue).trim().toLowerCase();
|
||||
if (decoded) {
|
||||
trackerSet.add(decoded);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedProbe = probeTrackers.map((url) => url.toLowerCase());
|
||||
const hadProbeTracker = normalizedProbe.some((url) => trackerSet.has(url));
|
||||
|
||||
const toAppend = [];
|
||||
probeTrackers.forEach((tracker, index) => {
|
||||
const normalizedTracker = normalizedProbe[index];
|
||||
if (trackerSet.has(normalizedTracker)) {
|
||||
return;
|
||||
}
|
||||
trackerSet.add(normalizedTracker);
|
||||
toAppend.push(`tr=${encodeURIComponent(tracker)}`);
|
||||
});
|
||||
|
||||
if (!toAppend.length) {
|
||||
return {
|
||||
magnet: trimmedMagnet,
|
||||
appended: false,
|
||||
hasProbeTrackers: hadProbeTracker,
|
||||
};
|
||||
}
|
||||
|
||||
const separator = queryPart ? "&" : "?";
|
||||
const augmented = `${withoutFragment}${separator}${toAppend.join("&")}`;
|
||||
const finalMagnet = fragment
|
||||
? `${augmented}#${fragment}`
|
||||
: augmented;
|
||||
|
||||
return {
|
||||
magnet: finalMagnet,
|
||||
appended: true,
|
||||
hasProbeTrackers: true,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeNumber(value, fallback = 0) {
|
||||
const coerced = Number(value);
|
||||
if (Number.isFinite(coerced)) {
|
||||
return coerced;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function toError(err) {
|
||||
if (err instanceof Error) {
|
||||
return err;
|
||||
}
|
||||
try {
|
||||
return new Error(String(err));
|
||||
} catch (stringifyError) {
|
||||
return new Error("Unknown error");
|
||||
}
|
||||
}
|
||||
|
||||
export class TorrentClient {
|
||||
constructor() {
|
||||
// Reusable objects and flags
|
||||
this.client = null;
|
||||
this.currentTorrent = null;
|
||||
this.probeClient = null;
|
||||
|
||||
// Service worker registration is cached
|
||||
this.swRegistration = null;
|
||||
@@ -16,6 +150,155 @@ export class TorrentClient {
|
||||
this.TIMEOUT_DURATION = 60000;
|
||||
}
|
||||
|
||||
ensureClientForProbe() {
|
||||
if (!this.probeClient) {
|
||||
this.probeClient = new WebTorrent();
|
||||
}
|
||||
return this.probeClient;
|
||||
}
|
||||
|
||||
async probePeers(
|
||||
magnetURI,
|
||||
{ timeoutMs = 8000, maxWebConns = 2, polls = 3 } = {}
|
||||
) {
|
||||
const magnet = typeof magnetURI === "string" ? magnetURI.trim() : "";
|
||||
if (!magnet) {
|
||||
return {
|
||||
healthy: false,
|
||||
peers: 0,
|
||||
reason: "invalid",
|
||||
appendedTrackers: false,
|
||||
hasProbeTrackers: false,
|
||||
usedTrackers: [...TorrentClient.PROBE_TRACKERS],
|
||||
durationMs: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const trackers = normalizeTrackerList(TorrentClient.PROBE_TRACKERS);
|
||||
const { magnet: augmentedMagnet, appended, hasProbeTrackers } =
|
||||
appendProbeTrackers(magnet, trackers);
|
||||
|
||||
if (!hasProbeTrackers) {
|
||||
return {
|
||||
healthy: false,
|
||||
peers: 0,
|
||||
reason: "no-trackers",
|
||||
appendedTrackers: false,
|
||||
hasProbeTrackers: false,
|
||||
usedTrackers: trackers,
|
||||
durationMs: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const client = this.ensureClientForProbe();
|
||||
const safeTimeout = Math.max(0, normalizeNumber(timeoutMs, 8000));
|
||||
const safePolls = Math.max(1, Math.floor(normalizeNumber(polls, 3)));
|
||||
const safeMaxWebConns = Math.max(1, Math.floor(normalizeNumber(maxWebConns, 2)));
|
||||
const pollInterval = Math.max(
|
||||
250,
|
||||
Math.floor(safeTimeout / Math.max(1, safePolls))
|
||||
);
|
||||
|
||||
const startedAt =
|
||||
typeof performance !== "undefined" && performance?.now
|
||||
? performance.now()
|
||||
: Date.now();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
let torrent = null;
|
||||
let timeoutId = null;
|
||||
let pollId = null;
|
||||
|
||||
const finalize = (overrides = {}) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = null;
|
||||
}
|
||||
if (pollId) {
|
||||
clearInterval(pollId);
|
||||
pollId = null;
|
||||
}
|
||||
if (torrent) {
|
||||
try {
|
||||
torrent.destroy({ destroyStore: true });
|
||||
} catch (err) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const endedAt =
|
||||
typeof performance !== "undefined" && performance?.now
|
||||
? performance.now()
|
||||
: Date.now();
|
||||
|
||||
resolve({
|
||||
healthy: false,
|
||||
peers: 0,
|
||||
reason: "timeout",
|
||||
appendedTrackers: appended,
|
||||
hasProbeTrackers,
|
||||
usedTrackers: trackers,
|
||||
durationMs: Math.max(0, endedAt - startedAt),
|
||||
...overrides,
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
torrent = client.add(augmentedMagnet, {
|
||||
announce: trackers,
|
||||
maxWebConns: safeMaxWebConns,
|
||||
});
|
||||
} catch (err) {
|
||||
finalize({
|
||||
reason: "error",
|
||||
error: toError(err),
|
||||
peers: 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const settleHealthy = () => {
|
||||
const peers = Math.max(1, Math.floor(normalizeNumber(torrent?.numPeers, 1)));
|
||||
finalize({ healthy: true, peers, reason: "peer" });
|
||||
};
|
||||
|
||||
torrent.once("wire", settleHealthy);
|
||||
|
||||
torrent.once("error", (err) => {
|
||||
finalize({
|
||||
healthy: false,
|
||||
reason: "error",
|
||||
error: toError(err),
|
||||
peers: Math.max(0, Math.floor(normalizeNumber(torrent?.numPeers, 0))),
|
||||
});
|
||||
});
|
||||
|
||||
if (safeTimeout > 0) {
|
||||
timeoutId = setTimeout(() => {
|
||||
finalize({
|
||||
healthy: false,
|
||||
peers: Math.max(0, Math.floor(normalizeNumber(torrent?.numPeers, 0))),
|
||||
});
|
||||
}, safeTimeout);
|
||||
}
|
||||
|
||||
pollId = setInterval(() => {
|
||||
if (!torrent || settled) {
|
||||
return;
|
||||
}
|
||||
const peers = Math.max(0, Math.floor(normalizeNumber(torrent.numPeers, 0)));
|
||||
if (peers > 0) {
|
||||
finalize({ healthy: true, peers, reason: "peer" });
|
||||
}
|
||||
}, pollInterval);
|
||||
});
|
||||
}
|
||||
|
||||
log(msg) {
|
||||
console.log(msg);
|
||||
}
|
||||
@@ -43,6 +326,13 @@ export class TorrentClient {
|
||||
// 2) If we haven’t registered the service worker yet, do it now
|
||||
if (!this.swRegistration) {
|
||||
this.swRegistration = await this.setupServiceWorker();
|
||||
} else {
|
||||
// Even with an existing registration we still wait for control so that a
|
||||
// transient controller drop (e.g. Chrome devtools unregister/reload) does
|
||||
// not resurrect the grey-screen regression mentioned in
|
||||
// waitForActiveController().
|
||||
this.requestClientsClaim(this.swRegistration);
|
||||
await this.waitForActiveController(this.swRegistration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +371,117 @@ export class TorrentClient {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a live service worker is actively controlling the page before we
|
||||
* start WebTorrent streaming.
|
||||
*
|
||||
* This regression has bitten us repeatedly: the first playback attempt after
|
||||
* a cold load would get stuck on a grey frame because `navigator.serviceWorker`
|
||||
* had finished installing but never claimed the page yet. WebTorrent's
|
||||
* service-worker proxy never attached, so `file.streamTo(videoElement)` fed
|
||||
* data into the void. Refreshing the page “fixed” it because the worker became
|
||||
* the controller during navigation. Future refactors **must not** remove this
|
||||
* guard — wait for `controllerchange` whenever `controller` is still null.
|
||||
*/
|
||||
requestClientsClaim(registration = this.swRegistration) {
|
||||
if (!("serviceWorker" in navigator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const activeWorker = registration?.active;
|
||||
if (!activeWorker) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Some Chromium builds require an explicit startMessages() call before a
|
||||
// yet-to-claim worker will accept postMessage traffic. Calling it is a
|
||||
// harmless no-op elsewhere.
|
||||
if (navigator.serviceWorker.startMessages) {
|
||||
navigator.serviceWorker.startMessages();
|
||||
}
|
||||
|
||||
activeWorker.postMessage({ type: "ENSURE_CLIENTS_CLAIM" });
|
||||
} catch (err) {
|
||||
this.log("Failed to request clients.claim():", err);
|
||||
}
|
||||
}
|
||||
|
||||
async waitForActiveController(registration = this.swRegistration) {
|
||||
if (!("serviceWorker" in navigator)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (navigator.serviceWorker.controller) {
|
||||
return navigator.serviceWorker.controller;
|
||||
}
|
||||
|
||||
this.requestClientsClaim(registration);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let timeoutId = null;
|
||||
let pollId = null;
|
||||
|
||||
const cleanup = () => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = null;
|
||||
}
|
||||
if (pollId) {
|
||||
clearInterval(pollId);
|
||||
pollId = null;
|
||||
}
|
||||
navigator.serviceWorker.removeEventListener(
|
||||
"controllerchange",
|
||||
onControllerChange
|
||||
);
|
||||
};
|
||||
|
||||
const maybeResolve = () => {
|
||||
const controller = navigator.serviceWorker.controller;
|
||||
if (controller) {
|
||||
cleanup();
|
||||
resolve(controller);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const onControllerChange = () => {
|
||||
if (maybeResolve()) {
|
||||
return;
|
||||
}
|
||||
// If we received a controllerchange event but still don't have a
|
||||
// controller it usually means the new worker hasn't claimed this page
|
||||
// yet. Ask it again to be safe.
|
||||
this.requestClientsClaim(registration);
|
||||
};
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("Service worker controller claim timeout"));
|
||||
}, this.TIMEOUT_DURATION);
|
||||
|
||||
pollId = setInterval(() => {
|
||||
if (maybeResolve()) {
|
||||
return;
|
||||
}
|
||||
this.requestClientsClaim(registration);
|
||||
}, 500);
|
||||
|
||||
navigator.serviceWorker.addEventListener(
|
||||
"controllerchange",
|
||||
onControllerChange
|
||||
);
|
||||
|
||||
// One last check in case the controller appeared between the earlier
|
||||
// synchronous guard and the promise wiring above.
|
||||
if (!maybeResolve()) {
|
||||
this.requestClientsClaim(registration);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async setupServiceWorker() {
|
||||
try {
|
||||
const isBraveBrowser = await this.isBrave();
|
||||
@@ -92,7 +493,15 @@ export class TorrentClient {
|
||||
throw new Error("Service Worker not supported or disabled");
|
||||
}
|
||||
|
||||
// Brave-specific logic
|
||||
// Brave-specific logic: Brave Shields has a long-standing bug where
|
||||
// stale service worker registrations linger even after we ship fixes.
|
||||
// When that happens, the outdated worker keeps intercepting requests
|
||||
// and WebTorrent fails to spin up, leaving playback broken until the
|
||||
// user manually nukes the registration. To guarantee a clean slate we
|
||||
// blanket-unregister every worker, then pause briefly so Brave can
|
||||
// finish tearing down the old instance before we register the fresh
|
||||
// one again. That delay is intentional—future tweaks should not shorten
|
||||
// or remove it without understanding the regression risk.
|
||||
if (isBraveBrowser) {
|
||||
this.log("Checking Brave configuration...");
|
||||
if (!navigator.serviceWorker) {
|
||||
@@ -160,6 +569,16 @@ export class TorrentClient {
|
||||
throw new Error("Service worker not active after ready state");
|
||||
}
|
||||
|
||||
// Give the newly activated worker an explicit nudge to claim the page
|
||||
// before we continue. This keeps Chromium's occasionally sluggish claim
|
||||
// hand-offs from derailing the subsequent wait below.
|
||||
this.requestClientsClaim(registration);
|
||||
|
||||
// See waitForActiveController() docstring for why this must remain in
|
||||
// place. We intentionally wait here instead of racing with playback so a
|
||||
// newly installed worker claims the page before WebTorrent spins up.
|
||||
await this.waitForActiveController(registration);
|
||||
|
||||
// Force the SW to check for updates
|
||||
registration.update();
|
||||
this.log("Service worker ready");
|
||||
@@ -171,8 +590,30 @@ export class TorrentClient {
|
||||
}
|
||||
}
|
||||
|
||||
attemptAutoplay(videoElement, context = "webtorrent") {
|
||||
if (!videoElement || typeof videoElement.play !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
videoElement
|
||||
.play()
|
||||
.catch((err) => {
|
||||
this.log(`Autoplay failed (${context} path):`, err);
|
||||
if (videoElement.muted) {
|
||||
return;
|
||||
}
|
||||
this.log(`Retrying with muted autoplay (${context} path).`);
|
||||
videoElement.muted = true;
|
||||
videoElement.play().catch((err2) => {
|
||||
this.log(`Muted autoplay also failed (${context} path):`, err2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Handle Chrome-based browsers
|
||||
handleChromeTorrent(torrent, videoElement, resolve, reject) {
|
||||
// Prune demo web seeds/trackers that chronically trip Chromium CORS and
|
||||
// deliberately mutate `torrent._opts` as a sanctioned WebTorrent workaround.
|
||||
torrent.on("warning", (err) => {
|
||||
if (err && typeof err.message === "string") {
|
||||
if (
|
||||
@@ -203,18 +644,20 @@ export class TorrentClient {
|
||||
return reject(new Error("No compatible video file found in torrent"));
|
||||
}
|
||||
|
||||
videoElement.muted = true;
|
||||
// Satisfy autoplay requirements and keep cross-origin chunks usable (e.g., for snapshots).
|
||||
videoElement.crossOrigin = "anonymous";
|
||||
|
||||
videoElement.addEventListener("error", (e) => {
|
||||
this.log("Video error:", e.target.error);
|
||||
});
|
||||
|
||||
videoElement.addEventListener("canplay", () => {
|
||||
videoElement.play().catch((err) => {
|
||||
this.log("Autoplay failed:", err);
|
||||
});
|
||||
});
|
||||
videoElement.addEventListener(
|
||||
"canplay",
|
||||
() => {
|
||||
this.attemptAutoplay(videoElement, "chrome");
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
|
||||
try {
|
||||
file.streamTo(videoElement);
|
||||
@@ -240,18 +683,20 @@ export class TorrentClient {
|
||||
return reject(new Error("No compatible video file found in torrent"));
|
||||
}
|
||||
|
||||
videoElement.muted = true;
|
||||
// Satisfy autoplay requirements and keep cross-origin chunks usable (e.g., for snapshots).
|
||||
videoElement.crossOrigin = "anonymous";
|
||||
|
||||
videoElement.addEventListener("error", (e) => {
|
||||
this.log("Video error (Firefox path):", e.target.error);
|
||||
});
|
||||
|
||||
videoElement.addEventListener("canplay", () => {
|
||||
videoElement.play().catch((err) => {
|
||||
this.log("Autoplay failed:", err);
|
||||
});
|
||||
});
|
||||
videoElement.addEventListener(
|
||||
"canplay",
|
||||
() => {
|
||||
this.attemptAutoplay(videoElement, "firefox");
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
|
||||
try {
|
||||
file.streamTo(videoElement, { highWaterMark: 256 * 1024 });
|
||||
@@ -268,11 +713,79 @@ export class TorrentClient {
|
||||
});
|
||||
}
|
||||
|
||||
async destroyWithTimeout(
|
||||
target,
|
||||
{ label = "resource", args = [], timeoutMs = 8000 } = {}
|
||||
) {
|
||||
if (!target || typeof target.destroy !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
const safeTimeout = Math.max(
|
||||
1000,
|
||||
Math.min(
|
||||
Number.isFinite(timeoutMs) ? timeoutMs : 8000,
|
||||
this.TIMEOUT_DURATION
|
||||
)
|
||||
);
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
const finalize = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
clearTimeout(timeoutId);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const logError = (error) => {
|
||||
if (error) {
|
||||
this.log(`[cleanup] ${label} destroy error:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
this.log(
|
||||
`[cleanup] ${label} destroy timed out after ${safeTimeout}ms; forcing resolution.`
|
||||
);
|
||||
finalize();
|
||||
}, safeTimeout);
|
||||
|
||||
const callback = (error) => {
|
||||
logError(error);
|
||||
finalize();
|
||||
};
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = target.destroy(...args, callback);
|
||||
} catch (error) {
|
||||
logError(error);
|
||||
finalize();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result && typeof result.then === "function") {
|
||||
result
|
||||
.then(() => {
|
||||
finalize();
|
||||
})
|
||||
.catch((error) => {
|
||||
logError(error);
|
||||
finalize();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates streaming of a torrent magnet to a <video> element.
|
||||
* Ensures the service worker is set up only once and the client is reused.
|
||||
*/
|
||||
async streamVideo(magnetURI, videoElement) {
|
||||
async streamVideo(magnetURI, videoElement, opts = {}) {
|
||||
try {
|
||||
// 1) Make sure we have a WebTorrent client and a valid SW registration.
|
||||
await this.init();
|
||||
@@ -288,6 +801,16 @@ export class TorrentClient {
|
||||
}
|
||||
|
||||
const isFirefoxBrowser = this.isFirefox();
|
||||
const candidateUrls = Array.isArray(opts?.urlList)
|
||||
? opts.urlList
|
||||
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
||||
.filter((entry) => /^https?:\/\//i.test(entry))
|
||||
: [];
|
||||
|
||||
const chromeOptions = { strategy: "sequential" };
|
||||
if (candidateUrls.length) {
|
||||
chromeOptions.urlList = candidateUrls;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 3) Add the torrent to the client and handle accordingly.
|
||||
@@ -295,7 +818,7 @@ export class TorrentClient {
|
||||
this.log("Starting torrent download (Firefox path)");
|
||||
this.client.add(
|
||||
magnetURI,
|
||||
{ strategy: "sequential", maxWebConns: 4 },
|
||||
{ ...chromeOptions, maxWebConns: 4 },
|
||||
(torrent) => {
|
||||
this.log("Torrent added (Firefox path):", torrent.name);
|
||||
this.handleFirefoxTorrent(torrent, videoElement, resolve, reject);
|
||||
@@ -303,7 +826,7 @@ export class TorrentClient {
|
||||
);
|
||||
} else {
|
||||
this.log("Starting torrent download (Chrome path)");
|
||||
this.client.add(magnetURI, { strategy: "sequential" }, (torrent) => {
|
||||
this.client.add(magnetURI, chromeOptions, (torrent) => {
|
||||
this.log("Torrent added (Chrome path):", torrent.name);
|
||||
this.handleChromeTorrent(torrent, videoElement, resolve, reject);
|
||||
});
|
||||
@@ -323,19 +846,44 @@ export class TorrentClient {
|
||||
async cleanup() {
|
||||
try {
|
||||
if (this.currentTorrent) {
|
||||
this.currentTorrent.destroy();
|
||||
try {
|
||||
await this.destroyWithTimeout(this.currentTorrent, {
|
||||
label: "current torrent",
|
||||
args: [{ destroyStore: true }],
|
||||
});
|
||||
} finally {
|
||||
this.currentTorrent = null;
|
||||
}
|
||||
}
|
||||
// Destroy client entirely and set to null so a future streamVideo call starts fresh
|
||||
|
||||
if (this.client) {
|
||||
await this.client.destroy();
|
||||
this.client = null;
|
||||
try {
|
||||
await this.destroyWithTimeout(this.client, {
|
||||
label: "WebTorrent client",
|
||||
});
|
||||
} finally {
|
||||
this.client = null;
|
||||
this.serverCreated = false;
|
||||
}
|
||||
} else {
|
||||
this.serverCreated = false;
|
||||
}
|
||||
|
||||
if (this.probeClient) {
|
||||
try {
|
||||
await this.destroyWithTimeout(this.probeClient, {
|
||||
label: "probe client",
|
||||
});
|
||||
} finally {
|
||||
this.probeClient = null;
|
||||
}
|
||||
}
|
||||
this.currentTorrent = null;
|
||||
this.serverCreated = false;
|
||||
} catch (error) {
|
||||
this.log("Cleanup error:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TorrentClient.PROBE_TRACKERS = DEFAULT_PROBE_TRACKERS;
|
||||
|
||||
export const torrentClient = new TorrentClient();
|
||||
Generated
+1672
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "bitvid",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"build:css": "npx tailwindcss -c tailwind.config.cjs -i css/tailwind.source.css -o css/tailwind.generated.css --minify"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autoprefixer": "^10.4.19",
|
||||
"postcss": "^8.4.41",
|
||||
"tailwindcss": "^3.4.13"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -15,6 +15,9 @@
|
||||
Promise.all(cacheNames.map((cacheName) => caches.delete(cacheName)))
|
||||
);
|
||||
}
|
||||
if (event.data && event.data.type === "ENSURE_CLIENTS_CLAIM") {
|
||||
event.waitUntil(clients.claim());
|
||||
}
|
||||
});
|
||||
|
||||
// Immediately install and skip waiting
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
module.exports = {
|
||||
content: [
|
||||
'./index.html',
|
||||
'./blog.html',
|
||||
'./components/**/*.html',
|
||||
'./views/**/*.html',
|
||||
'./js/**/*.js'
|
||||
],
|
||||
theme: {
|
||||
extend: {}
|
||||
},
|
||||
plugins: []
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
import "./test-helpers/setup-localstorage.mjs";
|
||||
import assert from "node:assert/strict";
|
||||
import { parseVideoEventPayload } from "../js/videoEventUtils.js";
|
||||
import { convertEventToVideo } from "../js/nostr.js";
|
||||
import { deriveTorrentPlaybackConfig } from "../js/playbackUtils.js";
|
||||
|
||||
const LEGACY_INFO_HASH = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
(function testParseDetectsBareInfoHashInJson() {
|
||||
const event = {
|
||||
id: "evt-json",
|
||||
content: JSON.stringify({
|
||||
version: 1,
|
||||
title: "Legacy note",
|
||||
magnet: LEGACY_INFO_HASH,
|
||||
}),
|
||||
tags: [],
|
||||
};
|
||||
|
||||
const parsed = parseVideoEventPayload(event);
|
||||
assert.equal(parsed.magnet, "", "Bare info hash should not be treated as a magnet URI");
|
||||
assert.equal(parsed.infoHash, LEGACY_INFO_HASH);
|
||||
})();
|
||||
|
||||
(function testParseDetectsInfoHashInRawContentAndTags() {
|
||||
const event = {
|
||||
id: "evt-tag",
|
||||
content: JSON.stringify({ title: "tag-sourced" }),
|
||||
tags: [["magnet", LEGACY_INFO_HASH]],
|
||||
};
|
||||
|
||||
const parsed = parseVideoEventPayload(event);
|
||||
assert.equal(parsed.infoHash, LEGACY_INFO_HASH);
|
||||
})();
|
||||
|
||||
(function testParseDetectsInfoHashInRawString() {
|
||||
const event = {
|
||||
id: "evt-raw",
|
||||
content: `legacy magnet ${LEGACY_INFO_HASH} broken json`,
|
||||
tags: [],
|
||||
};
|
||||
|
||||
const parsed = parseVideoEventPayload(event);
|
||||
assert.equal(parsed.infoHash, LEGACY_INFO_HASH);
|
||||
})();
|
||||
|
||||
(function testConvertFlagsBareInfoHashAsInvalid() {
|
||||
const event = {
|
||||
id: "evt-convert",
|
||||
pubkey: "pk",
|
||||
created_at: 1,
|
||||
tags: [],
|
||||
content: JSON.stringify({
|
||||
version: 1,
|
||||
title: "Legacy conversion",
|
||||
magnet: LEGACY_INFO_HASH,
|
||||
}),
|
||||
};
|
||||
|
||||
const video = convertEventToVideo(event);
|
||||
assert.equal(video.invalid, true, "Bare info-hash payloads should be flagged");
|
||||
assert.equal(video.reason, "missing playable source");
|
||||
})();
|
||||
|
||||
(function testLegacyEventWithoutTitleStillLoads() {
|
||||
const event = {
|
||||
id: "evt-no-title",
|
||||
pubkey: "pk2",
|
||||
created_at: 2,
|
||||
tags: [],
|
||||
content: JSON.stringify({
|
||||
version: 1,
|
||||
magnet: `magnet:?xt=urn:btih:${LEGACY_INFO_HASH}`,
|
||||
}),
|
||||
};
|
||||
|
||||
const video = convertEventToVideo(event);
|
||||
assert.equal(video.invalid, false, "Legacy events without title should fallback");
|
||||
assert.ok(video.title && video.title.length > 0, "Fallback title should be provided");
|
||||
})();
|
||||
|
||||
(function testConvertRecoversMagnetFromMagnetTag() {
|
||||
const magnetUri =
|
||||
`magnet:?xt=urn:btih:${LEGACY_INFO_HASH}&dn=legacy-tag&tr=wss://tracker.openwebtorrent.com`;
|
||||
const event = {
|
||||
id: "evt-magnet-tag",
|
||||
pubkey: "pk3",
|
||||
created_at: 3,
|
||||
// Deliberately invalid JSON so the converter must rely on scavenging.
|
||||
content: "{not valid json}",
|
||||
tags: [["magnet", magnetUri]],
|
||||
};
|
||||
|
||||
const video = convertEventToVideo(event);
|
||||
assert.equal(video.invalid, false, "Magnet in tag should still be playable");
|
||||
assert.equal(video.magnet, magnetUri);
|
||||
assert.equal(video.rawMagnet, magnetUri);
|
||||
})();
|
||||
|
||||
(function testPlaybackConfigNormalizesInfoHash() {
|
||||
const result = deriveTorrentPlaybackConfig({
|
||||
magnet: "",
|
||||
infoHash: LEGACY_INFO_HASH,
|
||||
url: "",
|
||||
});
|
||||
|
||||
assert.ok(result.magnet.startsWith("magnet:?"));
|
||||
const xtValues = new URL(result.magnet).searchParams.getAll("xt");
|
||||
assert.deepEqual(xtValues, [`urn:btih:${LEGACY_INFO_HASH}`]);
|
||||
assert.equal(result.usedInfoHash, true);
|
||||
assert.equal(result.fallbackMagnet, "");
|
||||
assert.equal(result.provided, true);
|
||||
})();
|
||||
|
||||
(function testPlaybackConfigDecodesEncodedMagnet() {
|
||||
const rawMagnet =
|
||||
`magnet:?xt=urn:btih:${LEGACY_INFO_HASH}&dn=Legacy+Example`;
|
||||
const encodedMagnet = encodeURIComponent(rawMagnet);
|
||||
const result = deriveTorrentPlaybackConfig({
|
||||
magnet: encodedMagnet,
|
||||
infoHash: "",
|
||||
url: "",
|
||||
});
|
||||
|
||||
assert.ok(result.magnet.startsWith("magnet:?"));
|
||||
const parsed = new URL(result.magnet);
|
||||
assert.equal(
|
||||
parsed.searchParams.get("xt"),
|
||||
`urn:btih:${LEGACY_INFO_HASH}`,
|
||||
"Expected encoded magnet to be normalized"
|
||||
);
|
||||
assert.equal(result.provided, true);
|
||||
assert.equal(result.usedInfoHash, false);
|
||||
})();
|
||||
|
||||
console.log("legacy infohash tests passed");
|
||||
@@ -0,0 +1,160 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { WSS_TRACKERS } from "../js/constants.js";
|
||||
import { normalizeAndAugmentMagnet, safeDecodeMagnet } from "../js/magnetUtils.js";
|
||||
import { normalizeAndAugmentMagnet as formNormalize } from "../js/magnet.js";
|
||||
|
||||
function getParamValues(magnet, key) {
|
||||
const parsed = new URL(magnet);
|
||||
return parsed.searchParams.getAll(key);
|
||||
}
|
||||
|
||||
(function testBareInfoHashNormalization() {
|
||||
const infoHash = "0123456789abcdef0123456789abcdef01234567";
|
||||
const result = normalizeAndAugmentMagnet(infoHash);
|
||||
assert.ok(result.didChange, "Bare info hash should mark didChange true");
|
||||
const xtValues = getParamValues(result.magnet, "xt");
|
||||
assert.deepEqual(xtValues, [`urn:btih:${infoHash}`]);
|
||||
const trackerValues = getParamValues(result.magnet, "tr");
|
||||
for (const tracker of WSS_TRACKERS) {
|
||||
assert.ok(
|
||||
trackerValues.includes(tracker),
|
||||
`Expected tracker ${tracker} to be appended`
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
(function testEncodedXtDecoding() {
|
||||
const infoHash = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";
|
||||
const encodedMagnet = `magnet:?xt=urn%3Abtih%3A${infoHash}&dn=Example`;
|
||||
const result = normalizeAndAugmentMagnet(encodedMagnet);
|
||||
const xtValues = getParamValues(result.magnet, "xt");
|
||||
assert.deepEqual(xtValues, [`urn:btih:${infoHash}`]);
|
||||
})();
|
||||
|
||||
(function testDuplicateTrackerFiltering() {
|
||||
const infoHash = "fedcba9876543210fedcba9876543210fedcba98";
|
||||
const baseMagnet =
|
||||
`magnet:?xt=urn:btih:${infoHash}` +
|
||||
"&tr=wss://tracker.openwebtorrent.com" +
|
||||
"&tr=WsS://tracker.openwebtorrent.com/" +
|
||||
"&tr=https://not-allowed.example";
|
||||
const result = normalizeAndAugmentMagnet(baseMagnet, {
|
||||
extraTrackers: [
|
||||
"wss://tracker.fastcast.nz",
|
||||
"http://tracker.invalid",
|
||||
"wss://tracker.openwebtorrent.com",
|
||||
],
|
||||
});
|
||||
const trackers = getParamValues(result.magnet, "tr");
|
||||
const openwebCount = trackers.filter(
|
||||
(value) => value === "wss://tracker.openwebtorrent.com"
|
||||
).length;
|
||||
assert.equal(openwebCount, 1, "Duplicate WSS tracker should be collapsed");
|
||||
assert.ok(
|
||||
trackers.includes("wss://tracker.fastcast.nz"),
|
||||
"Expected extra WSS tracker to be preserved"
|
||||
);
|
||||
assert.ok(
|
||||
!trackers.includes("http://tracker.invalid"),
|
||||
"Non-WSS tracker candidates should be ignored"
|
||||
);
|
||||
})();
|
||||
|
||||
(function testWebSeedHandlingWithLogging() {
|
||||
const infoHash = "0123456789abcdef0123456789abcdef01234567";
|
||||
const messages = [];
|
||||
const result = normalizeAndAugmentMagnet(`magnet:?xt=urn:btih:${infoHash}`, {
|
||||
webSeed: [
|
||||
"https://cdn.example.com/video.mp4",
|
||||
"http://cdn.example.com/legacy.mp4",
|
||||
"https://cdn.example.com/video.mp4",
|
||||
],
|
||||
logger: (msg) => messages.push(msg),
|
||||
appProtocol: "https:",
|
||||
});
|
||||
const seeds = getParamValues(result.magnet, "ws");
|
||||
assert.deepEqual(seeds, ["https://cdn.example.com/video.mp4"]);
|
||||
assert.equal(messages.length, 1, "HTTP seed should have been skipped with a log");
|
||||
assert.ok(
|
||||
messages[0].includes("Skipping insecure web seed"),
|
||||
"Expected skip message for HTTP seed"
|
||||
);
|
||||
})();
|
||||
|
||||
(function testHttpWebSeedAllowedOnHttpOrigin() {
|
||||
const infoHash = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";
|
||||
const result = normalizeAndAugmentMagnet(`magnet:?xt=urn:btih:${infoHash}`, {
|
||||
webSeed: "http://cdn.example.com/video.mp4",
|
||||
appProtocol: "http:",
|
||||
});
|
||||
const seeds = getParamValues(result.magnet, "ws");
|
||||
assert.deepEqual(seeds, ["http://cdn.example.com/video.mp4"]);
|
||||
})();
|
||||
|
||||
(function testSafeDecodeMagnetHandlesEncodedValues() {
|
||||
const rawMagnet =
|
||||
"magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=Example";
|
||||
const encodedMagnet = encodeURIComponent(rawMagnet);
|
||||
assert.equal(
|
||||
safeDecodeMagnet(encodedMagnet),
|
||||
rawMagnet,
|
||||
"Expected percent-encoded magnet to be decoded"
|
||||
);
|
||||
})();
|
||||
|
||||
(function testSafeDecodeMagnetLeavesPlainStringsUntouched() {
|
||||
const rawMagnet =
|
||||
"magnet:?xt=urn:btih:abcdefabcdefabcdefabcdefabcdefabcdefabcd";
|
||||
assert.equal(
|
||||
safeDecodeMagnet(rawMagnet),
|
||||
rawMagnet,
|
||||
"Plain magnet strings should pass through unchanged"
|
||||
);
|
||||
})();
|
||||
|
||||
(function testFormHelperAugmentsWsXsAndDecodesXt() {
|
||||
const infoHash = "abcdef0123456789abcdef0123456789abcdef01";
|
||||
const encodedMagnet = `magnet:?xt=urn%3Abtih%3A${infoHash}`;
|
||||
const normalized = formNormalize(encodedMagnet, {
|
||||
ws: "https://cdn.example.com/video-base/",
|
||||
xs: "https://cdn.example.com/video.torrent",
|
||||
});
|
||||
const parsed = new URL(normalized);
|
||||
assert.equal(
|
||||
parsed.searchParams.get("xt"),
|
||||
`urn:btih:${infoHash}`,
|
||||
"Form helper should decode encoded xt payloads"
|
||||
);
|
||||
assert.deepEqual(
|
||||
parsed.searchParams.getAll("ws"),
|
||||
["https://cdn.example.com/video-base/"],
|
||||
"Expected ws hint to be appended"
|
||||
);
|
||||
assert.deepEqual(
|
||||
parsed.searchParams.getAll("xs"),
|
||||
["https://cdn.example.com/video.torrent"],
|
||||
"Expected xs hint to be appended"
|
||||
);
|
||||
const trackers = parsed.searchParams.getAll("tr");
|
||||
for (const tracker of WSS_TRACKERS) {
|
||||
assert.ok(
|
||||
trackers.includes(tracker),
|
||||
`Expected helper to append tracker ${tracker}`
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
(function testFormHelperSkipsInsecureWsOnHttpsOrigin() {
|
||||
const infoHash = "0123456789abcdef0123456789abcdef01234567";
|
||||
const normalized = formNormalize(`magnet:?xt=urn:btih:${infoHash}`, {
|
||||
ws: "http://cdn.example.com/video-base/",
|
||||
});
|
||||
const parsed = new URL(normalized);
|
||||
assert.equal(
|
||||
parsed.searchParams.getAll("ws").length,
|
||||
0,
|
||||
"HTTP ws value should be skipped on HTTPS origins"
|
||||
);
|
||||
})();
|
||||
|
||||
console.log("magnet-utils tests passed");
|
||||
@@ -3,6 +3,7 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Nostr Ephemeral DM Tester (Using finalizeEvent)</title>
|
||||
<script src="../js/tracking.js" defer></script>
|
||||
<style>
|
||||
/* Basic styling for the demo page */
|
||||
body {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
if (typeof globalThis.localStorage === "undefined") {
|
||||
const store = new Map();
|
||||
globalThis.localStorage = {
|
||||
getItem(key) {
|
||||
return store.has(key) ? store.get(key) : null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
store.set(String(key), String(value));
|
||||
},
|
||||
removeItem(key) {
|
||||
store.delete(key);
|
||||
},
|
||||
clear() {
|
||||
store.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
+8
-5
@@ -17,6 +17,7 @@
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
||||
|
||||
<!-- Scripts: webtorrent, angular, etc. -->
|
||||
<script src="../js/tracking.js" defer></script>
|
||||
<script src="bundle.min.js"></script>
|
||||
<!--<script src="https://cdn.jsdelivr.net/combine/npm/webtorrent/webtorrent.min.js,npm/moment@2,npm/[email protected]/angular.min.js,npm/angular-[email protected]/angular-route.min.js,npm/angular-[email protected]/angular-sanitize.min.js,npm/angular-ui-grid@3/ui-grid.min.js,gh/matowens/ng-notify/dist/ng-notify.min.js,npm/ng-file-[email protected]/dist/ng-file-upload.min.js"></script>-->
|
||||
|
||||
@@ -43,11 +44,13 @@
|
||||
<header class="header-torrent">
|
||||
<div class="container">
|
||||
<div class="logo-container">
|
||||
<img
|
||||
src="../assets/svg/bitvid-logo-light-mode.svg"
|
||||
alt="bitvid Logo"
|
||||
class="bitvid-logo"
|
||||
/>
|
||||
<a href="../index.html" aria-label="Return to the bitvid home page">
|
||||
<img
|
||||
src="../assets/svg/bitvid-logo-light-mode.svg"
|
||||
alt="bitvid Logo"
|
||||
class="bitvid-logo"
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
+98
-16
@@ -1,29 +1,111 @@
|
||||
<section class="channel-profile-container">
|
||||
<!-- Modified banner wrapper for taller, rounded style -->
|
||||
<div
|
||||
class="profile-banner relative mb-6 rounded-lg overflow-hidden shadow-lg"
|
||||
>
|
||||
<div class="profile-banner relative mb-6 rounded-lg shadow-lg">
|
||||
<!-- Increase the default height classes -->
|
||||
<img
|
||||
id="channelBanner"
|
||||
class="w-full h-48 md:h-64 object-cover"
|
||||
class="w-full h-48 md:h-64 object-cover rounded-lg"
|
||||
src=""
|
||||
alt="Banner"
|
||||
/>
|
||||
<div class="absolute inset-0 bg-black bg-opacity-50"></div>
|
||||
<div class="absolute inset-0 bg-black bg-opacity-50 rounded-lg"></div>
|
||||
|
||||
<div class="absolute bottom-4 left-4 flex items-center">
|
||||
<div class="w-16 h-16 rounded-full overflow-hidden border-2 border-white">
|
||||
<img
|
||||
id="channelAvatar"
|
||||
src="assets/svg/default-profile.svg"
|
||||
alt="Avatar"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
<div
|
||||
class="absolute bottom-4 left-4 right-4 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between"
|
||||
>
|
||||
<div class="flex items-center">
|
||||
<div class="w-16 h-16 rounded-full overflow-hidden border-2 border-white">
|
||||
<img
|
||||
id="channelAvatar"
|
||||
src="assets/svg/default-profile.svg"
|
||||
alt="Avatar"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div class="ml-4 text-white">
|
||||
<h2 id="channelName" class="text-xl font-bold">User Name</h2>
|
||||
<p id="channelNpub" class="text-sm opacity-80">npub...</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ml-4 text-white">
|
||||
<h2 id="channelName" class="text-xl font-bold">User Name</h2>
|
||||
<p id="channelNpub" class="text-sm opacity-80">npub...</p>
|
||||
<div class="flex items-center gap-2 self-start sm:self-end">
|
||||
<button
|
||||
id="zapButton"
|
||||
type="button"
|
||||
class="icon-button"
|
||||
aria-label="Send a zap"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/lightning-bolt.svg"
|
||||
alt="Zap"
|
||||
class="icon-image"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
id="channelShareBtn"
|
||||
type="button"
|
||||
class="icon-button"
|
||||
aria-label="Share channel"
|
||||
>
|
||||
<img
|
||||
src="assets/svg/share-video.svg"
|
||||
alt="Share channel"
|
||||
class="icon-image"
|
||||
/>
|
||||
</button>
|
||||
<div
|
||||
class="relative inline-block overflow-visible"
|
||||
data-more-menu-wrapper="true"
|
||||
>
|
||||
<button
|
||||
id="channelMoreBtn"
|
||||
type="button"
|
||||
class="icon-button"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
aria-label="Channel options"
|
||||
data-more-dropdown="channel-profile"
|
||||
>
|
||||
<img src="assets/svg/ellipsis.svg" alt="More" class="w-5 h-5" />
|
||||
</button>
|
||||
<div
|
||||
id="moreDropdown-channel-profile"
|
||||
class="hidden absolute right-0 top-12 w-48 rounded-md shadow-lg bg-gray-800 ring-1 ring-black ring-opacity-5 z-50"
|
||||
role="menu"
|
||||
data-more-menu="true"
|
||||
>
|
||||
<div class="py-1">
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700"
|
||||
data-action="copy-npub"
|
||||
data-context="channel-profile"
|
||||
>
|
||||
Copy npub
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white"
|
||||
data-action="blacklist-author"
|
||||
data-context="channel-profile"
|
||||
data-blacklist-menu="true"
|
||||
>
|
||||
Blacklist channel
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-red-700 hover:text-white"
|
||||
data-action="block-author"
|
||||
data-context="channel-profile"
|
||||
>
|
||||
Block channel
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-left px-4 py-2 text-sm text-gray-100 hover:bg-gray-700"
|
||||
data-action="report"
|
||||
data-context="channel-profile"
|
||||
>
|
||||
Report
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user