-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1402 lines (1289 loc) · 55.8 KB
/
content.js
File metadata and controls
1402 lines (1289 loc) · 55.8 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Skool Helper – Content Script (v0.6.2)
*
* v0.6.2: Robuste Community-Name-Erkennung — `currentCommunityName()` liest
* jetzt primaer aus `<meta property="og:title">`, dann aus
* `<title>`. Skool setzt beide auf Community-Root zuverlaessig auf
* den Community-Namen. Die alte H1-Heuristik bleibt als drittes
* Safety-Net. Damit endet die Pollution-Quelle endgueltig: ab jetzt
* werden korrekte Namen direkt beim ersten Visit erfasst.
* v0.6.1: Manuelle Namens-Korrektur — Community-Namen in den Optionen jetzt
* direkt editierbar (Inline-Input). Plus "Namen leeren"-Bulk-Reset:
* loescht alle Namen, behaelt Besuchshistorie/Sprache/Punkte/
* Mitgliedschaft. Naechster Skool-Visit fuellt Namen aus Nav.
* v0.6.0: Update-Check (opt-in, default an) — Background-Worker prueft 1x
* taeglich gegen die GitHub-Releases-API, ob ein neueres Release
* verfuegbar ist. Bei Update wird die Versionsnummer im Footer
* fett+gelb und klickbar (oeffnet Release-Seite). Per Toggle in
* den Options abschaltbar. Neue Permissions: alarms +
* host_permission api.github.com.
* v0.5.3: Versionsnummer sichtbar — im Sidebar-Footer (klein, rechts neben
* dem Standardtext) und im Options-Header (neben "Einstellungen").
* Liest aus chrome.runtime.getManifest().version, damit nur die
* manifest.json bei Releases angefasst werden muss.
* v0.5.2: Bugfix — Community-Namen wurden auf Detail-/Settings-/Leaderboard-
* Seiten mit dem Seitentitel ueberschrieben (Folge: "Change password",
* Post-Titel etc. tauchten als Community-Namen im Round-Robin auf).
* Fix: Namen nur noch auf der Community-Root-Seite erfassen.
* Selbstheilung: Nav-Scan ueberschreibt jetzt aggressiv aus der
* zuverlaessigen Skool-Drawer-Komponente, alte falsche Namen
* korrigieren sich beim naechsten Skool-Besuch automatisch.
* Plus: ?p= URL-Pattern wird jetzt auch als Post-Detail erkannt
* (Skool nutzt sowohl ?c= als auch ?p= fuer Post-Detail-URLs).
* v0.5.1: Polish — Transliterationen (Oeffnen, Loeschen, fuer, naechsten, ...)
* in user-sichtbaren Strings durch echte Umlaute ersetzt.
* Markdown-Export-Filename transliteriert Umlaute jetzt sauber zu
* ue/oe/ae/ss statt sie durch Bindestriche zu zerstoeren.
* v0.5.0: Gamification — liest Level + Punkte zum naechsten Level pro
* Community aus der Leaderboard-Card und zeigt sie als dezentes
* Badge im Round-Robin (z. B. "L5 · 332P"). Stand wird gecached und
* als veraltet markiert (gestrichelt) wenn aelter als 24 h.
* Refresh automatisch bei jedem Besuch der Leaderboard-Seite.
* v0.4.10: Code-Hygiene (Pfad D) — Defaults zentralisiert in defaults.js
* (vorher 3x dupliziert in background.js, content.js, options.js
* mit abweichendem Umfang in background.js). Single Source of Truth
* via globalThis.SKOOL_HELPER_DEFAULTS.
* v0.4.9: Detection-Sprint (Pfad C) — extractPostData nutzt jetzt die echten
* Skool-styled-component-Klassen (TitleText, UserNameText) statt
* Heading/erstes-Link-Heuristik. Damit greift die Author-Erkennung
* nicht mehr versehentlich den Community-Link. ID nutzt Skools
* `?c=<post-id>`-Parameter fuer eindeutige Post-Identifikation.
* Zentrale SKOOL_SEL-Konstante fuer alle Skool-Selektoren.
* v0.4.8: UX-Sprint (Pfad B) — Section-Counter in Headern, persistente Suchfelder
* in Bookmarks und Cross-Community-Feed, Tastatur-Shortcut Alt+Shift+S
* fuer Sidebar-Toggle (chrome.commands), JSON-Backup-Export/-Import
* in Options.
* v0.4.7: Performance-Sprint — Nav-Scan/Visit-Record gedrosselt, Storage-Writes
* coalesced, SPA-URL-Hook statt Polling, postHistory mit Hard-Cap,
* Footer-Timer auf 1s, Comment-Container von Post-Detection ausgeschlossen.
* v0.4.6: Keyword-Chips Trennung, Sidebar-Fingerprint im postHistory-Pruning.
* v0.4.5: Dreifache Absicherung gegen Selbst-Scan der Sidebar.
* v0.4.4: Post-Detection ignoriert die eigene Sidebar.
* v0.4.3: Community-Name auf Detail-Seiten nicht durch Post-Titel ueberschrieben.
* v0.4.2: "Noch offen heute (0)" unterscheidet "alle besucht" vs. "gefiltert".
* v0.4.1: "Heute" beginnt ab Mitternacht (Kalendertag).
* v0.4.0: Post-History (14 Tage), Cross-Community-Feed (7 Tage), Markdown-Export, Anti-Autoren-Filter.
* v0.3.0: Read-Later/Bookmarks, Ausschluss-Keywords, Session-Timer, Engagement-Log.
* v0.2.x: Round-Robin, Sprachfilter, Mitgliedschafts-Erkennung, robustere Post-Erkennung.
* v0.1.0: Erstes Release.
*/
(() => {
"use strict";
if (window.__SKOOL_HELPER_LOADED__) return;
window.__SKOOL_HELPER_LOADED__ = true;
// Defaults aus defaults.js (Single Source of Truth, geteilt mit Service
// Worker und Options Page). defaults.js wird vor content.js geladen
// (siehe manifest.json content_scripts.js).
const DEFAULTS = globalThis.SKOOL_HELPER_DEFAULTS;
if (!DEFAULTS) {
console.error("[Skool Helper] defaults.js wurde nicht geladen — Extension neu installieren oder manifest.json pruefen.");
return;
}
const DEFAULT_KEYWORDS = DEFAULTS.keywords;
const DEFAULT_COMMENT_TEMPLATES = DEFAULTS.commentTemplates;
const VISIT_WINDOW_MS = 24 * 60 * 60 * 1000;
const RESERVED_SLUGS = new Set([
"", "about", "login", "signup", "auth", "settings", "password", "notifications",
"invite", "billing", "explore", "search", "new", "help", "legal", "privacy",
"terms", "careers", "press", "api", "docs", "blog"
]);
const state = {
keywords: [],
matchedPostIds: new Set(),
posts: new Map(),
sidebarVisible: true,
commentTemplates: DEFAULT_COMMENT_TEMPLATES.slice(),
notifyOnMatch: true,
languageFilter: "all",
membersOnly: false,
excludedKeywords: [],
excludedAuthors: [],
showTimer: false,
showEngagement: false,
bookmarks: {},
postHistory: {},
communities: {},
sessionCounts: {},
sessionStart: Date.now()
};
let __extensionDead = false;
function isExtensionAlive() {
if (__extensionDead) return false;
try {
return typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.id;
} catch (e) {
return false;
}
}
function markExtensionDead() {
if (__extensionDead) return;
__extensionDead = true;
try { mo.disconnect(); } catch (e) {}
console.info("[Skool Helper] Extension wurde reloaded, dieser Content-Script ist stumm. Bitte Skool-Tab neu laden.");
}
async function loadConfig() {
try {
const sync = await chrome.storage.sync.get(DEFAULTS);
state.keywords = (sync.keywords || []).map(k => k.toLowerCase().trim()).filter(Boolean);
state.commentTemplates = Array.isArray(sync.commentTemplates) && sync.commentTemplates.length
? sync.commentTemplates
: DEFAULT_COMMENT_TEMPLATES.slice();
state.sidebarVisible = sync.sidebarVisible !== false;
state.notifyOnMatch = sync.notifyOnMatch !== false;
state.languageFilter = sync.languageFilter || "all";
state.membersOnly = sync.membersOnly === true;
state.excludedKeywords = (sync.excludedKeywords || []).map(k => k.toLowerCase().trim()).filter(Boolean);
state.excludedAuthors = (sync.excludedAuthors || []).map(a => a.toLowerCase().trim()).filter(Boolean);
state.showTimer = sync.showTimer === true;
state.showEngagement = sync.showEngagement === true;
const local = await chrome.storage.local.get({ communities: {}, bookmarks: {}, postHistory: {}, updateInfo: null });
state.communities = local.communities || {};
state.bookmarks = local.bookmarks || {};
state.postHistory = local.postHistory || {};
state.updateInfo = local.updateInfo || null;
prunePostHistory();
} catch (err) {
console.warn("[Skool Helper] Konnte Config nicht laden:", err);
state.keywords = DEFAULT_KEYWORDS.slice();
state.commentTemplates = DEFAULT_COMMENT_TEMPLATES.slice();
}
}
// Coalesced Storage-Writes: max. 1 Schreibvorgang pro Schluessel pro 2s.
// Verhindert Storage-Spam bei jedem MutationObserver-Tick.
const COALESCE_DELAY_MS = 2000;
let saveCommunitiesTimer = null;
let savePostHistoryTimer = null;
function saveCommunities() {
if (!isExtensionAlive()) { markExtensionDead(); return; }
if (saveCommunitiesTimer) return; // schon geplant, neuer Stand wird beim Flush mitgenommen
saveCommunitiesTimer = setTimeout(async () => {
saveCommunitiesTimer = null;
if (!isExtensionAlive()) return;
try {
await chrome.storage.local.set({ communities: state.communities });
} catch (e) {
if (e && String(e).includes("Extension context invalidated")) {
markExtensionDead();
} else {
console.warn("[Skool Helper] Konnte Communities nicht speichern:", e);
}
}
}, COALESCE_DELAY_MS);
}
async function saveBookmarks() {
if (!isExtensionAlive()) { markExtensionDead(); return; }
try {
await chrome.storage.local.set({ bookmarks: state.bookmarks });
} catch (e) {
if (e && String(e).includes("Extension context invalidated")) markExtensionDead();
}
}
function toggleBookmark(post) {
if (!post || !post.id) return;
if (state.bookmarks[post.id]) {
delete state.bookmarks[post.id];
} else {
state.bookmarks[post.id] = {
id: post.id,
title: post.title || "",
author: post.author || "",
snippet: post.snippet || "",
url: post.url || "",
community: currentCommunityName() || currentCommunitySlug() || "",
savedAt: Date.now()
};
}
saveBookmarks();
renderSidebar();
}
function savePostHistory() {
if (!isExtensionAlive()) { markExtensionDead(); return; }
if (savePostHistoryTimer) return;
savePostHistoryTimer = setTimeout(async () => {
savePostHistoryTimer = null;
if (!isExtensionAlive()) return;
try {
await chrome.storage.local.set({ postHistory: state.postHistory });
} catch (e) {
if (e && String(e).includes("Extension context invalidated")) markExtensionDead();
}
}, COALESCE_DELAY_MS);
}
// Hard-Cap: postHistory bleibt bei sehr aktiver Nutzung handhabbar.
// chrome.storage.local hat 5 MB Limit ohne Permission, dazu kommt die Render-Last.
const MAX_POST_HISTORY = 2000;
function prunePostHistory() {
const cutoff = Date.now() - 14 * 24 * 60 * 60 * 1000;
let changed = false;
for (const [id, p] of Object.entries(state.postHistory || {})) {
const tooOld = (p.firstSeen || 0) < cutoff;
const title = (p.title || "").toLowerCase();
const snippet = (p.snippet || "").toLowerCase();
// Sidebar-Fingerprints: unsere eigenen Labels/Texte
const looksLikeSidebar =
title.includes("skool helper") ||
snippet.includes("community-rundlauf") ||
snippet.includes("priority-posts") ||
snippet.includes("youtubebildervideostodoprompt") ||
snippet.includes("noch offen heute") ||
snippet.includes("heute besucht");
if (tooOld || looksLikeSidebar) {
delete state.postHistory[id];
changed = true;
}
}
// Hard-Cap nach Zeit-Pruning: aelteste lastSeen rauswerfen.
const remaining = Object.entries(state.postHistory);
if (remaining.length > MAX_POST_HISTORY) {
remaining.sort((a, b) => (b[1].lastSeen || 0) - (a[1].lastSeen || 0));
for (let i = MAX_POST_HISTORY; i < remaining.length; i++) {
delete state.postHistory[remaining[i][0]];
}
changed = true;
}
if (changed) savePostHistory();
}
function recordPostToHistory(data) {
if (!data || !data.id) return;
const existing = state.postHistory[data.id];
const now = Date.now();
state.postHistory[data.id] = {
id: data.id,
title: (data.title || "").slice(0, 200),
author: (data.author || "").slice(0, 100),
snippet: (data.snippet || "").slice(0, 300),
url: data.url || "",
community: currentCommunityName() || currentCommunitySlug() || "",
communitySlug: currentCommunitySlug() || "",
matchedKeywords: data.matchedKeywords || [],
firstSeen: existing ? existing.firstSeen : now,
lastSeen: now
};
}
chrome.storage.onChanged.addListener((changes, area) => {
if (area === "sync") {
if (changes.keywords) {
state.keywords = (changes.keywords.newValue || []).map(k => k.toLowerCase().trim()).filter(Boolean);
rescan();
}
if (changes.commentTemplates) {
state.commentTemplates = changes.commentTemplates.newValue || DEFAULT_COMMENT_TEMPLATES.slice();
}
if (changes.membersOnly !== undefined) {
state.membersOnly = changes.membersOnly.newValue === true;
renderRoundRobin();
}
if (changes.sidebarVisible !== undefined) {
state.sidebarVisible = changes.sidebarVisible.newValue !== false;
toggleSidebar(state.sidebarVisible);
}
}
if (area === "local" && changes.postHistory) {
state.postHistory = changes.postHistory.newValue || {};
renderSidebar();
}
if (area === "local" && changes.bookmarks) {
state.bookmarks = changes.bookmarks.newValue || {};
renderSidebar();
}
if (area === "local" && changes.communities) {
state.communities = changes.communities.newValue || {};
renderRoundRobin();
}
if (area === "local" && changes.updateInfo) {
state.updateInfo = changes.updateInfo.newValue || null;
renderFooterStats();
}
});
function currentCommunitySlug() {
const parts = location.pathname.split("/").filter(Boolean);
const slug = (parts[0] || "").toLowerCase();
if (!slug || RESERVED_SLUGS.has(slug)) return null;
if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) return null;
return slug;
}
function currentCommunityName() {
// 1. <meta property="og:title"> — Skool setzt das auf Community-Root
// zuverlaessig auf den Community-Namen. Auf Post-Detail-Seiten waere
// der og:title gleich dem Post-Titel; der Aufrufer (recordCurrentVisit)
// gated bereits auf Community-Root, also unkritisch.
const ogTitle = document.querySelector('meta[property="og:title"]');
if (ogTitle) {
const t = (ogTitle.getAttribute("content") || "").trim();
if (t && t.length > 0 && t.length < 100) return t;
}
// 2. <title>: auf Community-Root ebenfalls nur der Name (kein "X | Y").
let docTitle = (document.title || "").trim();
if (docTitle) {
docTitle = docTitle.split("|")[0].trim();
docTitle = docTitle.split(/[·•]/)[0].trim();
if (docTitle && docTitle.length < 100) return docTitle;
}
// 3. Fallback: alte Heuristik mit Headings + nav-aria-current.
// Mit dem Path-Gating in recordCurrentVisit selten noetig, aber bleibt
// als Safety-Net falls ein Skool-Build die meta-Tags mal vergisst.
const headerCandidates = document.querySelectorAll('h1, h2, [class*="community"] [class*="name"], [class*="community"] h1, nav [aria-current="page"]');
for (const el of headerCandidates) {
let t = (el.textContent || "").trim();
if (!t) continue;
t = t.split(/[·•|]/)[0].trim();
t = t.replace(/\s+(Community|Classroom|Calendar|Members|Map|Leaderboards|About|Prompts|Chat|Gold|Erfolge).*$/i, "").trim();
if (t && t.length > 0 && t.length < 60) return t;
}
return null;
}
function recordCurrentVisit() {
const slug = currentCommunitySlug();
if (!slug) return;
const entry = state.communities[slug] || { manuallyAdded: false };
// Namen nur auf der Community-Root-Seite erfassen. Auf Post-Detail-,
// Settings-, Leaderboard- und sonstigen Sub-Seiten wuerde der erste <h1>
// den Post-Titel/Seitentitel zeigen — das hatte vor v0.5.2 zu polluteten
// Community-Namen wie "Change password" gefuehrt.
const pathParts = location.pathname.split("/").filter(Boolean);
const isOnCommunityRoot = pathParts.length === 1
&& !/[?&]p=/.test(location.search)
&& !/[?&]c=/.test(location.search);
if (isOnCommunityRoot) {
const currentName = currentCommunityName();
if (currentName) entry.name = currentName;
}
if (!entry.name) entry.name = slug;
entry.lastVisit = Date.now();
if (!entry.language || entry.languageSource !== "manual") {
const lang = detectLanguage();
if (lang) {
entry.language = lang;
entry.languageSource = "auto";
}
}
state.communities[slug] = entry;
saveCommunities();
}
function scanSkoolNavForCommunities() {
const navSelectors = [
"nav",
"aside",
'[role="navigation"]',
'[class*="drawer" i]',
'[class*="sidebar" i]',
'[class*="sidenav" i]',
'[data-testid*="drawer" i]',
'[data-testid*="sidebar" i]'
];
const memberSlugs = new Set();
for (const sel of navSelectors) {
document.querySelectorAll(sel).forEach(container => {
container.querySelectorAll('a[href^="/"], a[href*="skool.com/"]').forEach(a => {
try {
const url = new URL(a.href, location.origin);
if (!/(^|\.)skool\.com$/.test(url.hostname)) return;
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length !== 1) return;
const slug = parts[0].toLowerCase();
if (RESERVED_SLUGS.has(slug) || !/^[a-z0-9][a-z0-9-]*$/.test(slug)) return;
memberSlugs.add(slug);
} catch (e) {}
});
});
}
const links = document.querySelectorAll('a[href^="/"], a[href*="skool.com/"]');
let added = false;
links.forEach(a => {
let href;
try {
href = new URL(a.href, location.origin);
} catch { return; }
if (!/(^|\.)skool\.com$/.test(href.hostname)) return;
const parts = href.pathname.split("/").filter(Boolean);
if (parts.length !== 1) return;
const slug = parts[0].toLowerCase();
if (RESERVED_SLUGS.has(slug) || !/^[a-z0-9][a-z0-9-]*$/.test(slug)) return;
let name = (a.textContent || "").trim().split("\n")[0].slice(0, 60);
if (!name) {
const img = a.querySelector("img[alt]");
if (img && img.alt) name = img.alt.trim().slice(0, 60);
}
if (!name) name = slug;
const existing = state.communities[slug];
const isMemberNow = memberSlugs.has(slug);
if (!existing) {
state.communities[slug] = { name, lastVisit: 0, manuallyAdded: false, isMember: isMemberNow };
added = true;
} else {
// Nav-Namen sind die zuverlaessigste Quelle (kommen aus Skool's
// eigener Drawer-Komponente). Aggressiv ueberschreiben, damit
// alte falsche Werte (z. B. Post-Titel aus pre-v0.5.2-Bug) sich
// automatisch selbst heilen, sobald der User irgendeine Skool-
// Seite besucht und die Nav geladen ist.
if (existing.name !== name) { existing.name = name; added = true; }
if (isMemberNow && existing.isMember !== true) { existing.isMember = true; added = true; }
}
});
const currentSlug = currentCommunitySlug();
if (currentSlug && state.communities[currentSlug] && !state.communities[currentSlug].isMember) {
state.communities[currentSlug].isMember = true;
added = true;
}
if (added) saveCommunities();
}
function detectLanguage() {
// 1) <html lang="...">
const htmlLang = (document.documentElement.getAttribute("lang") || "").toLowerCase();
if (htmlLang.startsWith("de")) return "de";
if (htmlLang.startsWith("en")) return "en";
// 2) Heuristik auf Body-Text (Umlaute + haeufige DE-Woerter)
const sample = (document.body && document.body.innerText || "").slice(0, 5000).toLowerCase();
if (!sample) return null;
const deChars = (sample.match(/[äöüß]/g) || []).length;
const deWords = (sample.match(/\b(und|der|die|das|nicht|ein|eine|ist|für|auch|mit|wird|sind|oder|über|bei)\b/g) || []).length;
const enWords = (sample.match(/\b(the|and|for|with|that|this|have|from|your|about|which)\b/g) || []).length;
const deScore = deChars * 2 + deWords;
if (deScore >= 10 && deScore > enWords * 1.3) return "de";
if (enWords >= 10 && enWords > deScore * 1.3) return "en";
return null;
}
function findPostContainers() {
const candidates = new Set();
const seen = new WeakSet();
const TIME_PATTERN = /\b(\d+\s?(d|h|m|s|min|mins|sec|hrs?|hours?|minutes?|seconds?|days?|weeks?|months?)(\s+ago)?|(vor\s+\d+)|(gerade eben)|(just now)|(edited))\b/i;
const isPostLike = (el) => {
const text = el.textContent || "";
const hasLikeText = /\b(Like|Liked|Gefällt)\b/i.test(text);
const hasCommentsText = /\d+\s*(comments?|Kommentare?)/i.test(text);
const hasPostLink = el.querySelector('a[href*="/post/"], a[href*="/-/"]') !== null;
const hasAvatar = el.querySelector('img[alt], img[src*="avatar" i], img[src*="profile" i]') !== null;
const hasAriaLike = el.querySelector('[aria-label*="like" i], [aria-label*="gefäll" i], [aria-label*="react" i]') !== null;
const hasAriaComment = el.querySelector('[aria-label*="comment" i], [aria-label*="kommentar" i], [aria-label*="reply" i]') !== null;
const hasHeading = el.querySelector("h1, h2, h3") !== null;
const hasTimePattern = TIME_PATTERN.test(text);
const textLen = text.length;
return (
(hasLikeText && hasCommentsText) ||
(hasPostLink && hasHeading && hasAvatar) ||
(hasAriaLike && hasAriaComment && hasHeading) ||
(hasPostLink && hasAriaComment && hasHeading) ||
(hasPostLink && hasAvatar && hasTimePattern && textLen > 40) ||
(hasAvatar && hasTimePattern && (hasAriaLike || hasAriaComment) && textLen > 40)
);
};
const rectOk = (el) => {
const rect = el.getBoundingClientRect();
return rect.height >= 80 && rect.height <= window.innerHeight * 5;
};
const considerContainer = (el) => {
if (!el || seen.has(el)) return;
if (!rectOk(el)) return;
if (isPostLike(el)) {
candidates.add(el);
seen.add(el);
}
};
document.querySelectorAll("h1, h2, h3").forEach(heading => {
let el = heading;
for (let i = 0; i < 15; i++) {
if (!el || el === document.body) break;
if (seen.has(el)) break;
if (isPostLike(el) && rectOk(el)) {
candidates.add(el);
seen.add(el);
break;
}
el = el.parentElement;
}
});
document.querySelectorAll('article, [role="article"]').forEach(considerContainer);
document.querySelectorAll('a[href*="/post/"], a[href*="/-/"]').forEach(a => {
let el = a;
for (let i = 0; i < 12; i++) {
if (!el || el === document.body) break;
if (seen.has(el)) break;
if (isPostLike(el) && rectOk(el)) {
candidates.add(el);
seen.add(el);
break;
}
el = el.parentElement;
}
});
Array.from(document.querySelectorAll("button, div, span"))
.filter(n => {
const t = (n.textContent || "").trim();
if (!t) return false;
return /^(Like|Liked|Gefällt mir|Gefällt dir)$/i.test(t.split("\n")[0].trim());
})
.forEach(node => {
let el = node;
for (let i = 0; i < 15; i++) {
if (!el || el === document.body) break;
if (seen.has(el)) break;
if (isPostLike(el) && rectOk(el)) {
candidates.add(el);
seen.add(el);
break;
}
el = el.parentElement;
}
});
const arr = Array.from(candidates).filter(el => {
if (el.closest("#skool-helper-sidebar")) return false;
// Skool-spezifisch: Kommentare auf Post-Detail-Seiten haben Klassen wie
// "styled__CommentItemContainer-..." und sollen NICHT als eigenstaendige
// Posts indiziert werden. Der Hauptpost selbst ist nicht in einem
// CommentItemContainer.
if (el.closest(SKOOL_SEL.commentItem)) return false;
return true;
});
const filtered = arr.filter(a => !arr.some(b => b !== a && b.contains(a)));
if (window.__SKOOL_HELPER_DEBUG) {
console.info("[Skool Helper] Gefundene Post-Container:", filtered.length, filtered);
}
return filtered;
}
// Skool-spezifische Selektoren (styled-components, Klassen-Substrings stabil
// ueber lange Zeit — Hash-Suffix wechselt pro Build).
const SKOOL_SEL = {
title: '[class*="TitleText"]',
userName: '[class*="UserNameText"]',
postedDate: '[class*="PostedDate"]',
dateLabel: '[class*="DateAndLabelWrapper"]',
detailHeader: '[class*="PostDetailHeader"]',
commentItem: '[class*="CommentItemContainer"]',
// Gamification (Leaderboard-Seite): zeigt Level und Punkte zum naechsten
// Level fuer den eingeloggten User in der jeweiligen Community.
gamificationProgress: '[class*="GamificationProgress"]',
pointsToGoWrapper: '[class*="PointsToGoWrapper"]',
userInfoTitle: '[class*="UserInfoTitle"]'
};
function isPostDetailPage() {
return !!document.querySelector(SKOOL_SEL.detailHeader);
}
/**
* Extrahiert die eigenen Gamification-Daten (Level + Punkte zum naechsten
* Level) aus der GamificationProgress-Card. Sichtbar nur auf Leaderboard-
* Seiten (`/<community>/-/leaderboards`). Returns null falls die Card nicht
* im DOM ist oder die Werte nicht parsbar sind.
*
* Beispiel-Output: { level: 5, toNext: 332 }
*/
function extractMyPoints() {
const card = document.querySelector(SKOOL_SEL.gamificationProgress);
if (!card) return null;
let level = null;
const titleEl = card.querySelector(SKOOL_SEL.userInfoTitle);
if (titleEl) {
const m = (titleEl.textContent || "").match(/Level\s+(\d+)/i);
if (m) level = parseInt(m[1], 10);
}
let toNext = null;
const ptsEl = card.querySelector(SKOOL_SEL.pointsToGoWrapper);
if (ptsEl) {
// Erste Zahl im Wrapper ist die Punkt-Zahl (z. B. "332 points to level up").
const m = (ptsEl.textContent || "").match(/(\d[\d.,]*)/);
if (m) toNext = parseInt(m[1].replace(/[^\d]/g, ""), 10);
}
if (level === null && toNext === null) return null;
return { level, toNext };
}
function maybeRecordMyPoints() {
const slug = currentCommunitySlug();
if (!slug || !state.communities[slug]) return;
const pts = extractMyPoints();
if (!pts) return;
const prev = state.communities[slug].points || {};
// Nur speichern wenn sich was geaendert hat oder wir noch nichts haben.
if (prev.level !== pts.level || prev.toNext !== pts.toNext) {
state.communities[slug].points = {
level: pts.level,
toNext: pts.toNext,
capturedAt: Date.now()
};
saveCommunities();
renderRoundRobin();
} else if (!prev.capturedAt) {
// Identische Werte, aber Zeitstempel fehlt — einmalig setzen.
state.communities[slug].points = { ...prev, capturedAt: Date.now() };
saveCommunities();
}
}
function extractPostData(el) {
const rawAll = (el.textContent || "").replace(/\s+/g, " ").trim();
// Title: zuerst Skool-spezifisch, dann Heading-Fallback, dann Text-Slice.
let title = "";
const titleNode = el.querySelector(SKOOL_SEL.title);
if (titleNode) title = titleNode.textContent.trim();
if (!title) {
const firstHeading = el.querySelector("h1, h2, h3");
if (firstHeading) title = firstHeading.textContent.trim();
}
if (!title) {
const strong = el.querySelector("strong, b");
if (strong) title = strong.textContent.trim();
}
if (!title) title = rawAll.slice(0, 80);
// Author: Skool-Klasse zuerst — vermeidet, dass der Community-Link
// (z. B. "News & Talk") faelschlich als Autor erkannt wird.
let author = "";
const userNameNode = el.querySelector(SKOOL_SEL.userName);
if (userNameNode) {
author = userNameNode.textContent.replace(/\s+/g, " ").trim().slice(0, 60);
}
if (!author) {
const firstHeading = el.querySelector("h1, h2, h3");
const headingBlock = firstHeading ? firstHeading.closest("header, div") : null;
const authorScope = headingBlock || el;
const avatar = authorScope.querySelector('img[alt], img[src*="avatar"], img[src*="profile"]');
if (avatar) {
const nearbyLink = avatar.closest("a") || avatar.parentElement?.querySelector("a, span, div");
if (nearbyLink) author = nearbyLink.textContent.trim().split("\n")[0].slice(0, 60);
}
}
if (!author) {
const firstLink = el.querySelector("a");
if (firstLink) author = firstLink.textContent.trim().split("\n")[0].slice(0, 60);
}
// Snippet: rawAll ohne Author-Praefix (sonst steht im Snippet "Felix Hoberg
// 2d News & Talk Verrueckte KI-Geschaeftsideen ..."), und ohne Like-/
// Comment-Counts am Ende.
let snippet = rawAll;
if (author && snippet.startsWith(author)) {
snippet = snippet.slice(author.length).trim();
}
if (title && snippet.includes(title)) {
snippet = snippet.slice(snippet.indexOf(title) + title.length).trim();
}
snippet = snippet.replace(/\s*(Liked|Like|\d+\s*(comments?|Kommentare?))[\s\S]*$/i, "").trim();
snippet = snippet.slice(0, 240);
// URL: Post-Link oder aktuelle Detail-URL. Skool nutzt mehrere Schemata
// fuer Post-Detail-URLs: `/post/<id>`, `/-/<slug>`, `?c=<id>`, `?p=<id>`.
let url = "";
const postLink = el.querySelector('a[href*="/post/"], a[href*="/-/"], a[href*="?c="], a[href*="?p="]');
if (postLink) url = postLink.href;
if (!url && (
location.pathname.includes("/post") ||
location.pathname.includes("/-/") ||
/[?&]c=/.test(location.search) ||
/[?&]p=/.test(location.search)
)) {
url = location.href;
}
// ID-Normalisierung: Skool's Post-Detail-URLs haben den Post-Identifier
// entweder als `?c=<id>` oder als `?p=<id>`. Wir normalisieren auf
// `path?c=<id>` bzw. `path?p=<id>` und werfen alle anderen Query-Params
// raus, damit derselbe Post nie zwei IDs bekommt (z. B. mit Tracking-
// Parametern dahinter).
let id;
if (url) {
try {
const u = new URL(url, location.origin);
const c = u.searchParams.get("c");
const p = u.searchParams.get("p");
if (c) id = `${u.origin}${u.pathname}?c=${c}`;
else if (p) id = `${u.origin}${u.pathname}?p=${p}`;
else id = url.split("?")[0];
} catch (e) {
id = url.split("?")[0];
}
} else {
id = `local:${hashString((title + "|" + author).slice(0, 200))}`;
}
const searchText = rawAll.toLowerCase();
const matchedKeywords = state.keywords.filter(k => searchText.includes(k));
return { id, el, title, author, snippet, url, matchedKeywords };
}
function hashString(s) {
let h = 0;
for (let i = 0; i < s.length; i++) {
h = ((h << 5) - h) + s.charCodeAt(i);
h |= 0;
}
return Math.abs(h).toString(36);
}
// Drosselung: Nav-Scan und Visit-Record sind teuer und mussten frueher pro
// MutationObserver-Tick laufen. Jetzt: Nav-Scan max. alle 10s ODER bei
// URL-Slug-Wechsel; Visit-Record nur bei Slug-Wechsel.
const NAV_SCAN_INTERVAL_MS = 10_000;
let lastNavScanAt = 0;
let lastNavScanSlug = null;
let lastVisitSlug = null;
function maybeScanNav() {
const slug = currentCommunitySlug();
const now = Date.now();
if (slug !== lastNavScanSlug || now - lastNavScanAt > NAV_SCAN_INTERVAL_MS) {
scanSkoolNavForCommunities();
lastNavScanSlug = slug;
lastNavScanAt = now;
}
}
function maybeRecordVisit() {
const slug = currentCommunitySlug();
if (slug && slug !== lastVisitSlug) {
recordCurrentVisit();
lastVisitSlug = slug;
}
}
function scan() {
if (!isExtensionAlive()) { markExtensionDead(); return; }
// Alte "Posts" entfernen, die in Wahrheit unsere eigene Sidebar sind (aus altem State)
for (const [id, p] of Array.from(state.posts)) {
if (p.el && typeof p.el.closest === "function" && p.el.closest("#skool-helper-sidebar")) {
state.posts.delete(id);
state.matchedPostIds.delete(id);
}
}
maybeScanNav();
maybeRecordVisit();
maybeRecordMyPoints();
if (!state.keywords.length) {
renderSidebar();
return;
}
const containers = findPostContainers();
const newMatchIds = [];
const currentSlug = currentCommunitySlug();
if (currentSlug && !state.sessionCounts[currentSlug]) state.sessionCounts[currentSlug] = 0;
for (const el of containers) {
if (el && typeof el.closest === "function" && el.closest("#skool-helper-sidebar")) continue;
if (el && typeof el.closest === "function" && el.closest(SKOOL_SEL.commentItem)) continue;
const data = extractPostData(el);
if (!data) continue;
const txt = (el.textContent || "").toLowerCase();
const excluded = state.excludedKeywords.length > 0 && state.excludedKeywords.some(k => txt.includes(k));
if (excluded) {
el.classList.add("skool-helper-excluded");
el.classList.remove("skool-helper-match");
continue;
} else {
el.classList.remove("skool-helper-excluded");
}
// Anti-Autor Check
const authorLower = (data.author || "").toLowerCase();
const authorExcluded = state.excludedAuthors.length > 0 && state.excludedAuthors.some(a => authorLower.includes(a));
if (authorExcluded) {
el.classList.add("skool-helper-excluded");
el.classList.remove("skool-helper-match");
continue;
}
if (data.matchedKeywords.length > 0) {
el.classList.add("skool-helper-match");
el.setAttribute("data-skool-helper-id", data.id);
ensureBadge(el, data.matchedKeywords);
if (!state.matchedPostIds.has(data.id)) {
newMatchIds.push(data.id);
state.matchedPostIds.add(data.id);
if (currentSlug) state.sessionCounts[currentSlug]++;
}
state.posts.set(data.id, data);
recordPostToHistory(data);
} else {
el.classList.remove("skool-helper-match");
}
}
if (newMatchIds.length > 0) savePostHistory();
renderSidebar();
if (state.notifyOnMatch && newMatchIds.length > 0 && document.visibilityState !== "visible") {
chrome.runtime.sendMessage({
type: "notify",
title: `Skool Helper: ${newMatchIds.length} neue relevante Posts`,
message: newMatchIds
.map(id => state.posts.get(id))
.filter(Boolean)
.map(p => `• ${p.title.slice(0, 60)}`)
.slice(0, 3)
.join("\n")
}).catch(() => {});
}
}
function ensureBadge(el, keywords) {
if (el.querySelector(":scope > .skool-helper-badge")) return;
const badge = document.createElement("div");
badge.className = "skool-helper-badge";
badge.textContent = "⭐ " + keywords.join(", ");
badge.title = "Match wegen: " + keywords.join(", ");
const cs = getComputedStyle(el);
if (cs.position === "static") el.style.position = "relative";
el.appendChild(badge);
}
function rescan() {
document.querySelectorAll(".skool-helper-match").forEach(e => e.classList.remove("skool-helper-match"));
document.querySelectorAll(".skool-helper-badge").forEach(e => e.remove());
state.matchedPostIds.clear();
state.posts.clear();
scan();
}
let sidebarEl = null;
function ensureSidebar() {
if (sidebarEl) return sidebarEl;
sidebarEl = document.createElement("div");
sidebarEl.id = "skool-helper-sidebar";
sidebarEl.innerHTML = `
<div class="sh-header">
<strong>Skool Helper</strong>
<div class="sh-actions">
<button class="sh-btn" id="sh-settings" title="Einstellungen">⚙</button>
<button class="sh-btn" id="sh-toggle" title="Sidebar ein-/ausklappen">–</button>
</div>
</div>
<div class="sh-keywords" id="sh-keywords"></div>
<div class="sh-section sh-rr">
<div class="sh-section-header" data-target="sh-rr-body">
<span>🔄 Community-Rundlauf</span>
<span class="sh-caret">▾</span>
</div>
<div class="sh-section-body" id="sh-rr-body"></div>
</div>
<div class="sh-section sh-priority">
<div class="sh-section-header" data-target="sh-list">
<span>⭐ Priority-Posts <span class="sh-section-count" id="sh-priority-count"></span></span>
<span class="sh-caret">▾</span>
</div>
<div class="sh-section-body" id="sh-list"><div class="sh-empty">Noch keine Treffer. Scrolle durch den Feed.</div></div>
</div>
<div class="sh-section sh-cross">
<div class="sh-section-header" data-target="sh-cross-body">
<span>🌐 Alle Treffer (7 Tage) <span class="sh-section-count" id="sh-cross-count"></span></span>
<span class="sh-caret">▸</span>
</div>
<div class="sh-section-body" id="sh-cross-body" style="display:none"></div>
</div>
<div class="sh-section sh-bookmarks">
<div class="sh-section-header" data-target="sh-bookmarks-body">
<span>📌 Gemerkt <span class="sh-section-count" id="sh-bookmarks-count"></span></span>
<span class="sh-caret">▾</span>
</div>
<div class="sh-section-body" id="sh-bookmarks-body"></div>
</div>
<div class="sh-footer" id="sh-footer">Keywords & Communities in den Einstellungen</div>
`;
document.documentElement.appendChild(sidebarEl);
sidebarEl.querySelector("#sh-settings").addEventListener("click", () => {
chrome.runtime.sendMessage({ type: "open-options" }).catch(() => {});
});
sidebarEl.querySelector("#sh-toggle").addEventListener("click", () => {
const collapsed = sidebarEl.classList.toggle("sh-collapsed");
sidebarEl.querySelector("#sh-toggle").textContent = collapsed ? "+" : "–";
});
sidebarEl.querySelectorAll(".sh-section-header").forEach(h => {
h.addEventListener("click", () => {
const target = h.getAttribute("data-target");
const body = sidebarEl.querySelector("#" + target);
const caret = h.querySelector(".sh-caret");
if (!body) return;
const hidden = body.style.display === "none";
body.style.display = hidden ? "" : "none";
if (caret) caret.textContent = hidden ? "▾" : "▸";
});
});
return sidebarEl;
}
function toggleSidebar(visible) {
ensureSidebar();
sidebarEl.style.display = visible ? "flex" : "none";
}
function formatRelativeTime(ts) {
if (!ts) return "noch nie";
const diff = Date.now() - ts;
const m = Math.floor(diff / 60000);
if (m < 1) return "gerade eben";
if (m < 60) return `vor ${m} min`;
const h = Math.floor(m / 60);
if (h < 24) return `vor ${h} h`;
const d = Math.floor(h / 24);
if (d < 7) return `vor ${d} ${d === 1 ? "Tag" : "Tagen"}`;
const w = Math.floor(d / 7);
return `vor ${w} ${w === 1 ? "Woche" : "Wochen"}`;
}
function startOfToday() {
const d = new Date();
d.setHours(0, 0, 0, 0);
return d.getTime();
}
function renderRoundRobin() {
if (!sidebarEl) return;
const body = sidebarEl.querySelector("#sh-rr-body");
if (!body) return;
const now = Date.now();
const entries = Object.entries(state.communities || {})
.map(([slug, c]) => ({ slug, ...c }))
.sort((a, b) => (a.name || a.slug).localeCompare(b.name || b.slug));
if (!entries.length) {
body.innerHTML = '<div class="sh-empty">Noch keine Communities erfasst. Öffne eine deiner Communities, oder pflege sie in den Einstellungen.</div>';
return;
}
function passesLangFilter(c) {
const f = state.languageFilter || "all";
if (f === "all") return true;
if (f === "de") return c.language === "de";
if (f === "en") return c.language === "en";
if (f === "de_unknown") return c.language === "de" || !c.language;
return true;
}
function passesMemberFilter(c) {
if (!state.membersOnly) return true;
return c.isMember === true;