-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
469 lines (390 loc) · 13.6 KB
/
Copy pathapp.js
File metadata and controls
469 lines (390 loc) · 13.6 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// ====== CONFIGURAZIONE ======
// Cambia questi valori con i tuoi
const GITHUB_OWNER = "Mobrius";
const GITHUB_REPO = "ephemeral-social-test"; // o il nome del repo
const MAX_POSTS_CLIENT = 50; // quanti post mostrare al massimo nel feed
// ====== CLEANUP CLIENT-SIDE THROTTLING ======
const CLEANUP_LOCAL_KEY = "es_last_cleanup_run";
const CLEANUP_INTERVAL_HOURS = 48; // tienilo uguale a CLEAN_TIMER su Vercel
// ====== THEME (classic / military) ======
const THEME_KEY = "es_theme_v1";
function applyTheme(theme) {
const body = document.body;
if (theme === "military") {
body.classList.add("military");
} else {
body.classList.remove("military");
}
const btn = document.getElementById("themeToggleBtn");
if (btn) {
btn.textContent = theme === "military" ? "Ops" : "Classic";
}
}
function initTheme() {
let theme = localStorage.getItem(THEME_KEY);
if (theme !== "military" && theme !== "classic") {
theme = "classic";
}
applyTheme(theme);
}
function toggleTheme() {
const isMilitary = document.body.classList.contains("military");
const next = isMilitary ? "classic" : "military";
localStorage.setItem(THEME_KEY, next);
applyTheme(next);
}
// ====== AUTHOR ID LOCALE ======
const AUTHOR_ID_KEY = "es_author_id_v1";
function getOrCreateAuthorId() {
let id = localStorage.getItem(AUTHOR_ID_KEY);
if (!id) {
// crea ID tipo esuser-8f3a29c1
const rand =
Math.random().toString(36).substring(2, 8) +
Math.random().toString(36).substring(2, 6);
id = "esuser-" + rand;
localStorage.setItem(AUTHOR_ID_KEY, id);
}
return id;
}
// Estrarre l'author id dal body del post, es. [es-author]:esuser-xxxx
function extractAuthorIdFromBody(body) {
if (!body) return null;
const match = body.match(/\[es-author\]:(\S+)/);
return match ? match[1].trim() : null;
}
// ====== UTIL ======
const interestsKey = "es_interests_v1";
const defaultTopics = [
"ai",
"freedom",
"school",
"coding",
"art",
"politics",
"science",
"games",
];
function getLocalInterests() {
try {
const raw = localStorage.getItem(interestsKey);
if (!raw) {
const base = {};
defaultTopics.forEach((t) => (base[t] = 0.0));
return base;
}
return JSON.parse(raw);
} catch {
const base = {};
defaultTopics.forEach((t) => (base[t] = 0.0));
return base;
}
}
function setLocalInterests(map) {
localStorage.setItem(interestsKey, JSON.stringify(map));
}
function extractTopicsFromLabels(labels) {
// label names come from GitHub issue labels
return labels
.map((l) => l.name || l)
.map((n) => n.toLowerCase())
.filter((n) => !n.startsWith("meta:")); // puoi usare label meta se vuoi
}
function relevanceScoreForIssue(issue, interests) {
const topics = extractTopicsFromLabels(issue.labels || []);
if (!topics.length) return 0;
let sum = 0;
let count = 0;
topics.forEach((t) => {
if (interests[t] !== undefined) {
sum += interests[t];
count++;
}
});
if (!count) return 0;
return sum / count;
}
function formatDate(dateStr) {
const d = new Date(dateStr);
return d.toLocaleString();
}
async function maybeRunCleanup() {
try {
const now = Date.now();
const lastRun = parseInt(localStorage.getItem(CLEANUP_LOCAL_KEY) || "0", 10);
const intervalMs = CLEANUP_INTERVAL_HOURS * 60 * 60 * 1000;
// se non è ancora passato abbastanza tempo, non fare nulla
if (now - lastRun < intervalMs) {
return;
}
// prova a chiamare l'API di cleanup (best effort, senza UI)
const res = await fetch("/api/cleanup");
// possiamo anche ignorare la risposta, ma se vuoi debug:
// const data = await res.json();
// console.log("Cleanup result:", data);
// aggiorna il timestamp locale
localStorage.setItem(CLEANUP_LOCAL_KEY, String(now));
} catch (e) {
console.warn("Cleanup call failed (ignored):", e);
// in caso di errore NON aggiorniamo lastRun, così ritenterà al prossimo caricamento
}
}
// ====== UI: interessi ======
function renderInterestsChips() {
const interests = getLocalInterests();
const container = document.getElementById("interestsChips");
if (!container) return;
container.innerHTML = "";
const allTopics = new Set(defaultTopics);
// potremmo aggiungere in futuro topics dinamici dalle issue
allTopics.forEach((topic) => {
if (interests[topic] === undefined) {
interests[topic] = 0.0;
}
});
Object.entries(interests).forEach(([topic, weight]) => {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "es-chip" + (weight > 0 ? " es-chip--active" : "");
chip.textContent = topic;
chip.addEventListener("click", () => {
const newWeight = weight > 0 ? 0 : 1.0;
interests[topic] = newWeight;
setLocalInterests(interests);
renderInterestsChips();
loadFeed(); // ricalcola ordinamento
});
container.appendChild(chip);
});
}
// ====== API: lettura issue ======
async function fetchIssues() {
// ora chiamiamo il nostro backend, non direttamente GitHub
const res = await fetch("/api/feed");
if (!res.ok) {
throw new Error("Error fetching issues from backend");
}
const data = await res.json();
// Filtra solo "issue vere" e non PR (di solito hanno field pull_request)
return data.filter((item) => !item.pull_request);
}
// ====== FEED ======
// ====== FEED ======
async function loadFeed() {
const feedEl = document.getElementById("feed");
const infoEl = document.getElementById("feedInfo");
if (!feedEl) return;
// Se il feed è vuoto, mostriamo la scritta "Loading..."
const hadContent = feedEl.children.length > 0;
if (!hadContent) {
feedEl.innerHTML = "<p class='es-help-text'>Loading feed...</p>";
}
if (infoEl) {
infoEl.textContent = "Updating feed...";
}
try {
const issues = await fetchIssues();
const interests = getLocalInterests();
// Calcola score e ordina
const scored = issues.map((iss) => ({
issue: iss,
score: relevanceScoreForIssue(iss, interests),
}));
scored.sort((a, b) => {
// prima per score, poi per data
if (b.score !== a.score) return b.score - a.score;
return new Date(b.issue.created_at) - new Date(a.issue.created_at);
});
const limited = scored.slice(0, MAX_POSTS_CLIENT);
// Costruiamo il nuovo contenuto in un fragment, così non c'è flicker
const fragment = document.createDocumentFragment();
limited.forEach(({ issue, score }) => {
const postEl = document.createElement("article");
postEl.className = "es-post";
const rawBody = issue.body || "";
const authorId = extractAuthorIdFromBody(rawBody);
const header = document.createElement("div");
header.className = "es-post-header";
const leftSpan = document.createElement("span");
leftSpan.textContent = authorId ? authorId : `@${issue.user.login}`;
const rightSpan = document.createElement("span");
rightSpan.textContent = formatDate(issue.created_at);
header.appendChild(leftSpan);
header.appendChild(rightSpan);
const title = document.createElement("div");
title.className = "es-post-title";
title.textContent = issue.title || "(no title)";
const bodyEl = document.createElement("div");
bodyEl.className = "es-post-body";
const cleanedBody = rawBody
.replace(/\[es-author\]:\S+/, "")
.replace(/\n?_Posted via Ephemeral Social_/, "")
.trim();
bodyEl.textContent = cleanedBody;
const tagsWrap = document.createElement("div");
tagsWrap.className = "es-post-tags";
const topics = extractTopicsFromLabels(issue.labels || []);
topics.forEach((t) => {
const span = document.createElement("span");
const active = interests[t] > 0;
span.className = "es-tag-pill" + (active ? " es-tag-pill--match" : "");
span.textContent = "#" + t;
tagsWrap.appendChild(span);
});
if (topics.length) {
const scoreSpan = document.createElement("span");
scoreSpan.className = "es-tag-pill";
scoreSpan.textContent = `score: ${score.toFixed(2)}`;
tagsWrap.appendChild(scoreSpan);
}
postEl.appendChild(header);
postEl.appendChild(title);
postEl.appendChild(bodyEl);
if (topics.length) postEl.appendChild(tagsWrap);
fragment.appendChild(postEl);
});
// Sostituiamo il contenuto tutto in una volta (niente "vuoto" visibile)
feedEl.innerHTML = "";
feedEl.appendChild(fragment);
if (infoEl) {
const now = new Date();
infoEl.textContent = `Showing ${limited.length} posts · last update: ${now.toLocaleTimeString()}`;
}
} catch (err) {
console.error(err);
// Mostriamo errore solo se non avevamo già contenuto
if (!hadContent) {
feedEl.innerHTML = `<p class="es-help-text">Error loading feed. Please try again later.</p>`;
if (infoEl) infoEl.textContent = "";
} else if (infoEl) {
infoEl.textContent = "Error updating feed (showing cached posts).";
}
}
}
// ====== COMPOSER (overlay stile X) ======
function openComposer() {
const overlay = document.getElementById("composerOverlay");
if (!overlay) return;
overlay.classList.remove("es-hidden");
const titleInput = document.getElementById("postTitle");
if (titleInput) {
setTimeout(() => titleInput.focus(), 10);
}
const statusEl = document.getElementById("publishStatus");
if (statusEl) {
statusEl.textContent = "";
statusEl.className = "es-status";
}
}
function closeComposer() {
const overlay = document.getElementById("composerOverlay");
if (!overlay) return;
overlay.classList.add("es-hidden");
}
// ====== PUBBLICAZIONE POST ======
async function publishPost() {
const titleInput = document.getElementById("postTitle");
const bodyInput = document.getElementById("postBody");
const tagsInput = document.getElementById("postTags");
const statusEl = document.getElementById("publishStatus");
if (!titleInput || !bodyInput || !tagsInput || !statusEl) return;
const title = titleInput.value.trim();
const body = bodyInput.value.trim();
const tags = tagsInput.value
.split(",")
.map((t) => t.trim().toLowerCase())
.filter((t) => t.length > 0);
if (!title || !body) {
statusEl.textContent = "Please write a title and a text.";
statusEl.className = "es-status es-status--err";
return;
}
const authorId = getOrCreateAuthorId();
// Corpo che andrà nell'issue
let fullBody = body;
if (tags.length) {
fullBody += "\n\n---\nTags: " + tags.map((t) => `#${t}`).join(" ");
}
// Riga tecnica per identificare l'autore
fullBody += `\n\n[es-author]:${authorId}`;
fullBody += "\n_Posted via Ephemeral Social_";
statusEl.textContent = "Publishing...";
statusEl.className = "es-status";
try {
const res = await fetch("/api/new-post", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body: fullBody, labels: tags }),
});
if (!res.ok) {
const txt = await res.text();
throw new Error(txt || "Error from API");
}
statusEl.textContent = "Post published! It will appear in the feed soon.";
statusEl.className = "es-status es-status--ok";
titleInput.value = "";
bodyInput.value = "";
tagsInput.value = "";
// chiudi il composer dopo il publish
closeComposer();
// Ricarica feed dopo un attimo
setTimeout(loadFeed, 1000);
} catch (err) {
console.error(err);
statusEl.textContent = "Error publishing. Please try again.";
statusEl.className = "es-status es-status--err";
}
}
// ====== INIT ======
window.addEventListener("DOMContentLoaded", () => {
// Tema
initTheme();
const themeBtn = document.getElementById("themeToggleBtn");
if (themeBtn) {
themeBtn.addEventListener("click", toggleTheme);
}
// Interessi + feed
renderInterestsChips();
loadFeed();
// Mostra il tuo Author ID
const myAuthorId = getOrCreateAuthorId();
const badge = document.getElementById("authorIdBadge");
if (badge) {
badge.textContent = `Your ID: ${myAuthorId}`;
}
const publishBtn = document.getElementById("publishBtn");
if (publishBtn) {
publishBtn.addEventListener("click", publishPost);
}
const newPostBtn = document.getElementById("newPostBtn");
if (newPostBtn) {
newPostBtn.addEventListener("click", openComposer);
}
const fabNewPost = document.getElementById("fabNewPost");
if (fabNewPost) {
fabNewPost.addEventListener("click", openComposer);
}
const fabRefresh = document.getElementById("fabRefresh");
if (fabRefresh) {
fabRefresh.addEventListener("click", loadFeed);
}
const closeComposerBtn = document.getElementById("closeComposerBtn");
if (closeComposerBtn) {
closeComposerBtn.addEventListener("click", closeComposer);
}
const overlay = document.getElementById("composerOverlay");
if (overlay) {
overlay.addEventListener("click", (e) => {
// chiudi se clicchi fuori dal box
if (e.target === overlay) {
closeComposer();
}
});
}
// Prova a lanciare cleanup, ma solo se sono passate almeno CLEANUP_INTERVAL_HOURS ore
maybeRunCleanup();
// Aggiorna automaticamente il feed ogni 10 secondi
setInterval(() => {
loadFeed();
}, 10000);
});