-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.js
More file actions
389 lines (335 loc) · 13.1 KB
/
Copy pathadmin.js
File metadata and controls
389 lines (335 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
* The "WordPress side" of the demo, done entirely in the browser.
*
* The model is deliberately flat: once an episode is published it is just a row
* we own, with no memory of which fields came from RSS.com. Fetch is only a
* convenience that prefills the form -- press it again on a different URL and
* the form simply refills. Nothing keeps syncing afterwards.
*
* There is no server. The feed is served with `access-control-allow-origin: *`,
* so the browser reads it directly -- which is why this could ship later as a
* WordPress admin script rather than PHP.
*/
(function () {
"use strict";
const FEED = (slug) => `https://media.rss.com/${slug}/feed.xml`;
const STORAGE_KEY = "episode-demo:v2";
const DEMO_SLUG = "podcasting101"; // only used to expand a bare episode id
const SEED_IDS = ["1253951", "1207269", "1057374", "1057231"];
let records = [];
let editingId = null;
// identifiers that live on the record but are not edited in the form
let pendingSource = null;
const $ = (sel) => document.querySelector(sel);
/* ---------- feed ---------------------------------------------------- */
const ITUNES = "http://www.itunes.com/dtds/podcast-1.0.dtd";
function parseFeed(xmlText) {
const doc = new DOMParser().parseFromString(xmlText, "application/xml");
if (doc.querySelector("parsererror")) throw new Error("feed did not parse as XML");
const pick = (item, tag) => {
const n = item.getElementsByTagName(tag)[0];
return n ? (n.textContent || "").trim() : "";
};
const pickNS = (item, tag) => {
const n = item.getElementsByTagNameNS(ITUNES, tag)[0];
return n ? (n.textContent || "").trim() : "";
};
const channel = doc.querySelector("channel");
const channelArtNode = channel && channel.getElementsByTagNameNS(ITUNES, "image")[0];
const channelArt = channelArtNode ? channelArtNode.getAttribute("href") : "";
const out = new Map();
[...doc.querySelectorAll("item")].forEach((item) => {
const link = pick(item, "link");
const m = /\/(\d+)\/?$/.exec(link || "");
if (!m) return;
const enc = item.getElementsByTagName("enclosure")[0];
const artNode = item.getElementsByTagNameNS(ITUNES, "image")[0];
const pub = pick(item, "pubDate");
const pubDate = pub ? new Date(pub) : null;
out.set(m[1], {
episode_id: m[1],
title: pick(item, "title"),
permalink: link,
// the stable, unsigned URL -- this is what we store and play
audio_url: enc ? enc.getAttribute("url") : "",
duration_seconds: parseInt(pickNS(item, "duration") || "0", 10) || 0,
season: parseInt(pickNS(item, "season") || "0", 10) || null,
number: parseInt(pickNS(item, "episode") || "0", 10) || null,
published: pubDate && !isNaN(pubDate) ? pubDate.toISOString() : "",
artwork: artNode ? artNode.getAttribute("href") : channelArt,
summary: stripHtml(pick(item, "description")),
});
});
return out;
}
function stripHtml(html, limit = 240) {
const txt = (html || "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
return txt.length > limit ? txt.slice(0, limit).trimEnd() + "…" : txt;
}
/* No cache. Each fetch pulls the whole feed and keeps only the episode asked
* for; the rest is discarded. The feed is ~66 KB gzipped and served
* `no-cache`, so holding onto it would buy little and go stale. */
async function fetchFeed(slug) {
const res = await fetch(FEED(slug), { mode: "cors" });
if (!res.ok) throw new Error(`feed for "${slug}" returned ${res.status}`);
return parseFeed(await res.text());
}
/* A full episode URL carries both the show and the episode. A bare number is
* also accepted and assumes the demo show, so the sample links stay short. */
function parseRef(raw) {
const value = (raw || "").trim();
if (!value) return null;
if (/^\d+$/.test(value)) return { slug: DEMO_SLUG, id: value };
try {
const u = new URL(value);
const parts = u.pathname.split("/").filter(Boolean);
const id = [...parts].reverse().find((p) => /^\d+$/.test(p));
const slug = parts.find((p) => !/^\d+$/.test(p) && p !== "podcasts");
return id && slug ? { slug, id } : null;
} catch (e) {
return null;
}
}
/* ---------- persistence --------------------------------------------- */
function save() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
} catch (e) {
note("Could not save to this browser (storage full). The demo still works until you reload.", true);
}
}
function load() {
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || "null");
return Array.isArray(parsed) && parsed.length ? parsed : null;
} catch (e) {
return null;
}
}
/* ---------- rendering ------------------------------------------------ */
function renderFront() {
EpisodePlayer.renderGrid($("#grid"), records);
$("#front-count").textContent =
records.length + (records.length === 1 ? " episode" : " episodes");
}
function renderList() {
const list = $("#records");
list.innerHTML = "";
if (!records.length) {
list.innerHTML = '<li class="empty">Nothing published yet.</li>';
return;
}
records.forEach((rec) => {
const li = document.createElement("li");
li.className = "rec" + (editingId === rec.id ? " editing" : "");
const head = document.createElement("div");
head.className = "rec-head";
const title = document.createElement("span");
title.className = "rec-title";
title.textContent = rec.title || "(untitled)";
const idTag = document.createElement("code");
idTag.className = "rec-id";
idTag.textContent = "#" + (rec.episode_id || "—");
head.append(title, idTag);
const badges = document.createElement("div");
badges.className = "rec-badges";
if (rec.show_slug) {
const b = document.createElement("span");
b.className = "badge show";
b.textContent = rec.show_slug;
badges.appendChild(b);
}
const actions = document.createElement("div");
actions.className = "rec-actions";
const edit = document.createElement("button");
edit.type = "button";
edit.className = "link-btn";
edit.textContent = editingId === rec.id ? "editing…" : "Edit";
edit.addEventListener("click", () => beginEdit(rec.id));
const del = document.createElement("button");
del.type = "button";
del.className = "link-btn danger";
del.textContent = "Delete";
del.addEventListener("click", () => {
records = records.filter((r) => r.id !== rec.id);
if (editingId === rec.id) resetForm();
save(); renderAll();
});
actions.append(edit, del);
const inspect = document.createElement("details");
inspect.className = "inspect";
const sum = document.createElement("summary");
sum.textContent = "Stored record";
const pre = document.createElement("pre");
const shown = Object.assign({}, rec);
pre.textContent = JSON.stringify(shown, null, 2);
inspect.append(sum, pre);
li.append(head, badges, actions, inspect);
list.appendChild(li);
});
}
function renderAll() {
renderList();
renderFront();
}
/* ---------- form ------------------------------------------------------ */
function note(msg, isError) {
const el = $("#fetch-note");
el.textContent = msg || "";
el.className = "note" + (isError ? " error" : msg ? " ok" : "");
}
function parseDuration(raw) {
const v = (raw || "").trim();
if (!v) return 0;
if (/^\d+$/.test(v)) return parseInt(v, 10);
const parts = v.split(":").map((p) => parseInt(p, 10));
if (parts.some(isNaN)) return 0;
return parts.reduce((acc, p) => acc * 60 + p, 0);
}
/* Fetching prefills these; re-fetching a different episode just refills. */
function fillForm(v) {
$("#title").value = v.title || "";
$("#summary").value = v.summary || "";
$("#season").value = v.season || "";
$("#number").value = v.number || "";
$("#duration").value = v.duration_seconds
? EpisodePlayer.clock(v.duration_seconds) : "";
$("#published").value = v.published ? v.published.slice(0, 10) : "";
$("#audio_url").value = v.audio_url || "";
$("#artwork").value = v.artwork || "";
}
/* Fetching is optional: a title is the only thing required to publish. */
function updateFormState() {
$("#publish").disabled = !$("#title").value.trim();
}
function resetForm() {
editingId = null;
pendingSource = null;
$("#form").reset();
$("#publish").textContent = "Publish episode";
$("#cancel-edit").hidden = true;
$("#ref").disabled = false;
note("Fetch an episode to prefill the fields, or just type them in.");
updateFormState();
renderList();
}
function beginEdit(id) {
const rec = records.find((r) => r.id === id);
if (!rec) return;
editingId = id;
pendingSource = {
episode_id: rec.episode_id,
show_slug: rec.show_slug,
permalink: rec.permalink,
audio_url: rec.audio_url,
artwork: rec.artwork,
};
$("#ref").value = rec.permalink || rec.episode_id || "";
$("#ref").disabled = true;
fillForm(rec);
$("#publish").textContent = "Save changes";
$("#cancel-edit").hidden = false;
note("Editing a published episode.");
updateFormState();
renderList();
$("#title").focus();
}
/* ---------- wiring ---------------------------------------------------- */
document.addEventListener("DOMContentLoaded", () => {
$("#fetch").addEventListener("click", async () => {
const ref = parseRef($("#ref").value);
if (!ref) {
note("That does not look like an RSS.com episode URL.", true);
return;
}
$("#fetch").disabled = true;
note(`Fetching ${ref.slug}…`);
try {
const map = await fetchFeed(ref.slug);
const found = map.get(ref.id);
if (!found) {
note(`Episode ${ref.id} is not in "${ref.slug}" (${map.size} episodes checked).`, true);
pendingSource = null;
} else if (!editingId && records.some((r) => r.episode_id === ref.id)) {
note(`Episode ${ref.id} is already published. Edit it in the list below.`, true);
pendingSource = null;
} else {
pendingSource = {
episode_id: found.episode_id,
show_slug: ref.slug,
permalink: found.permalink,
audio_url: found.audio_url,
artwork: found.artwork,
};
fillForm(found);
note(`Prefilled from "${ref.slug}". Edit anything below, then publish.`);
$("#title").focus();
}
} catch (err) {
pendingSource = null;
note("Could not read the feed: " + err.message, true);
} finally {
$("#fetch").disabled = false;
updateFormState();
}
});
$("#title").addEventListener("input", updateFormState);
$("#ref").addEventListener("keydown", (e) => {
if (e.key === "Enter") { e.preventDefault(); $("#fetch").click(); }
});
$("#cancel-edit").addEventListener("click", resetForm);
$("#form").addEventListener("submit", (e) => {
e.preventDefault();
if (!$("#title").value.trim()) return;
// an episode typed in by hand simply has no RSS.com identifiers
const source = pendingSource || {
episode_id: "", show_slug: "", permalink: "", audio_url: "", artwork: "",
};
const fields = {
title: $("#title").value.trim(),
summary: $("#summary").value.trim(),
season: parseInt($("#season").value, 10) || null,
number: parseInt($("#number").value, 10) || null,
duration_seconds: parseDuration($("#duration").value),
published: $("#published").value
? new Date($("#published").value + "T12:00:00Z").toISOString() : "",
audio_url: $("#audio_url").value.trim(),
artwork: $("#artwork").value.trim(),
};
if (editingId) {
const rec = records.find((r) => r.id === editingId);
Object.assign(rec, source, fields);
} else {
records.unshift(Object.assign({ id: "rec-" + Date.now() }, source, fields));
}
resetForm();
save();
renderAll();
$("#right").scrollTop = 0;
});
$("#reset").addEventListener("click", () => {
localStorage.removeItem(STORAGE_KEY);
records = [];
renderAll();
seed();
});
const stored = load();
if (stored) { records = stored; renderAll(); }
else { renderAll(); seed(); }
});
async function seed() {
note("Seeding from the RSS.com feed…");
try {
const map = await fetchFeed(DEMO_SLUG);
records = SEED_IDS
.map((id) => map.get(id))
.filter(Boolean)
.map((f, i) => Object.assign({ id: "seed-" + i, show_slug: DEMO_SLUG }, f));
save();
note(`Seeded ${records.length} episodes. They are ours now — edit freely.`);
} catch (err) {
note("Could not seed from the feed: " + err.message, true);
}
renderAll();
}
})();