-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathscript.js
687 lines (557 loc) · 29.8 KB
/
script.js
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
// const apiDomain = "https://betterbluesky.nemtudo.me"; //production
const apiDomain = "https://apibetterbluesky.nemtudo.me"; //production
// const apiDomain = "http://localhost:3692"; //dev
let trendsUpdatesCounts = 0;
const sessionID = `${Date.now()}_${randomString(10)}` //gera um ID para fins de uso no backend
console.log(`[BetterBluesky] SessionID: ${sessionID}`)
const defaultConfig = { loaded: true, trendingTopics: true, telemetry: true, videos: true, likes: true, polls: true, updatenotes: true, bookmarks: true, easter_egg_tremdetopicos: false, use_betterbluesky_icons: true, trends_language: "pt" };
let betterblueskystorage = JSON.parse(localStorage.getItem("BETTERBLUESKY")) || defaultConfig;
window.betterblueskystorage = betterblueskystorage;
function loadBetterbluesky() {
if (!localStorage.getItem("BETTERBLUESKY")) {
localStorage.setItem("BETTERBLUESKY", JSON.stringify(defaultConfig));
alert("Seja muito bem-vindo ao BetterBluesky! Ajude mais pessoas a conhecerem o nosso trabalho curtindo e repostando o post de onde você nos conheceu! Siga @nemtudo.me para atualizações <3")
}
if (localStorage.getItem("BETTERBLUESKY") === '{loaded: true}') localStorage.setItem("BETTERBLUESKY", JSON.stringify(defaultConfig)); //convert old version to new
const storage = JSON.parse(localStorage.getItem("BETTERBLUESKY"));
betterblueskystorage = storage;
for (const key of Object.keys(defaultConfig)) {
if (typeof betterblueskystorage[key] === "undefined") {
betterblueskystorage[key] = defaultConfig[key];
}
}
localStorage.setItem("BETTERBLUESKY", JSON.stringify(betterblueskystorage))
betterblueskystorage = storage;
//REGISTER USER - NO CONFIDENTIAL INFORMATION IS COLLECTED
//Why?
//I plan to add future updates about users, such as trending topics based on location.
//is currently used in polls
//In addition to, of course, preventing spam users and bad actors
//It is worth remembering that no confidential data is collected.
//Handle is public to everyone.
//did is the user ID, which is also public.
//What SessionID? SessionID is an ID generated by BetterBluesky whenever it is loaded. Its usefulness is for internal statistical purposes, such as estimating the number of online users.
//Furthermore, it is worth remembering that the entire extension (backend and frontend) are open source and can be revised whenever necessary! :)
//Backend: https://github.com/Nem-Tudo/betterbluesky_api
const blueskyStorage = JSON.parse(localStorage.getItem("BSKY_STORAGE"));
fetch(`${apiDomain}/api/users?sessionID=${sessionID}&handle=${blueskyStorage.session.currentAccount.handle}&did=${blueskyStorage.session.currentAccount.did}`, {
method: "POST",
}).then(() => {
replaceBetterBlueSkyPolls()
setInterval(() => {
if (betterblueskystorage.bookmarks == true) {
addBookmarkButton();
}
}, 200)
})
setInterval(() => {
replaceBetterBlueSkyVideos()
addDownloadVideoButton()
}, 1000)
replaceBetterBlueSkyVideos()
}
function setFavicon() {
if (!betterblueskystorage.use_betterbluesky_icons) return;
document.querySelectorAll('link[rel*="icon"]').forEach(element => {
element.href = "https://nemtudo.me/cdn/betterblueskylogo.png";
})
}
function updateCheckBoxes() {
// Check the checkboxes if their value is true in localStorage
// try & catch to avoid crashes
try {
document.querySelectorAll('[type="checkbox"]').forEach(item => {
// We check if item is undefined so when a user upgrades to this version, its set to true
if (betterblueskystorage[item.name] == true || betterblueskystorage[item.name] == undefined) {
item.checked = true;
}
});
} catch (error) {
console.warn(error);
}
}
function updatePreferences(preference, value) {
function updateStorage() {
betterblueskystorage = JSON.parse(localStorage.getItem("BETTERBLUESKY"));
}
const object = JSON.parse(localStorage.getItem("BETTERBLUESKY"));
if (typeof value != "undefined") {
object[preference] = value;
} else {
object[preference] = !object[preference];
}
localStorage.setItem("BETTERBLUESKY", JSON.stringify(object));
updateStorage();
}
async function getTrends(count) {
if (betterblueskystorage.trendingTopics == false) return; // No unnecessary requests
const trends = await fetch(`${apiDomain}/api/trends?updateCount=${count}&lang=${betterblueskystorage.trends_language}&sessionID=${sessionID}`).then(r => r.json());
return trends.data;
}
async function updateTrends(replaceAll = false) {
if (betterblueskystorage.trendingTopics == false) return; // Avoid updating trends when they are disabled.
console.log("[BetterBluesky] Trends Atualizado", trendsUpdatesCounts, betterblueskystorage.trends_language)
const trends = await getTrends(trendsUpdatesCounts);
trendsUpdatesCounts++;
let html = "";
for (const trend in trends) {
html += `<li><a class="trend_item" trend_data='{"text": "${encodeURIComponent(trends[trend].text)}", "position": ${trend}, "count": ${trends[trend].count}}' href='${`https://bsky.app/search?q=${encodeURIComponent(trends[trend].text)}`}'><span class="counter">${Number(trend) + 1}</span>
<div class="content"><span class="trend">${escapeHTML(trends[trend].text)}</span>${`${trends[trend].message ? `<span class="trendmessage">${trends[trend].count ? `<span class="trendcount">${formatNumber(trends[trend].count)} posts</span>` : ""}・${escapeHTML(trends[trend].message)}</span>` : (trends[trend].count ? `<span class="trendcount">${formatNumber(trends[trend].count)} posts</span>` : "")}`}</div></a>
</li>`
}
html += `<span class="apoie">Gostou? Apoie o projeto! <a id="apoieurl" target="_blank" href='https://livepix.gg/nemtudo'>livepix.gg/nemtudo</a></span>`
html += `<span class="sourcecode">Código fonte: <a id="sourcecode" target="_blank" href='https://bsky.app/profile/nemtudo.me/post/3l3dwh7m4bj27'>acessar</a></span>`
if (document.querySelector("#trendsarea")) replaceAll ? document.querySelector("#trendsarea").innerHTML = html : document.querySelector("#trendsarea").innerHTML += html;
}
function settingsPopup() {
document.body.insertAdjacentHTML("beforeend", `
<div id="popup-overlay" class="overlay">
<div class="pugpup">
<div class="preference-div">
<p class="preference-text">Trending Topics</p>
<span class="preference-description">Visualize os Trending Topics do Bluesky</span>
</div>
<input type="checkbox" id="preferences" class="pugbox" name="trendingTopics" />
<div class="preference-div">
<p class="preference-text">User Likes</p>
<span class="preference-description">Veja um botão de coração, ao lado do perfil do usuário, que mostra o que foi curtido</span>
</div>
<input type="checkbox" id="preferences" class="pugbox" name="likes" />
<div class="preference-div">
<p class="preference-text">Enquetes</p>
<span class="preference-description">Envie e veja enquetes de usuários do BetterBluesky!</span>
</div>
<input type="checkbox" id="preferences" class="pugbox" name="polls" />
<div class="preference-div">
<p class="preference-text">Itens Salvos</p>
<span class="preference-description">Salve posts e veja diretamente no feed: <a href="https://bit.ly/bookmarksfeed">Bookmarks</a>!</span>
</div>
<input type="checkbox" id="preferences" class="pugbox" name="bookmarks" />
<div class="preference-div">
<p class="preference-text">Notas de atualização</p>
<span class="preference-description">Receba uma mensagem sempre que houver atualizações importantes na extensão!</span>
</div>
<input type="checkbox" id="preferences" class="pugbox" name="updatenotes" />
<div class="preference-div">
<p class="preference-text">Ícone do BetterBluesky</p>
<span class="preference-description">Use o ícone do BetterBluesky para sempre lembrar que seu Bluesky tem mais funções! 😎</span>
</div>
<input type="checkbox" id="preferences" class="pugbox" name="use_betterbluesky_icons" />
<button id="refresh-btn" class="refresh-page">Salvar ✨</button>
</div>
</div>`)
}
setInterval(() => {
updateTrends(true);
}, 1000 * 30)
setInterval(() => {
if (betterblueskystorage.videos == true) {
replaceBetterBlueSkyVideos();
}
}, 1000)
//eventos
window.addEventListener('load', () => setTimeout(() => { loadBetterbluesky(); setFavicon() }, 3000));
window.addEventListener('load', setFavicon);
window.addEventListener('load', () => setTimeout(() => { addBookmarksSidebarButton(); addSettingsButton() }, 2000));
window.addEventListener('load', () => setTimeout(() => { addTrendsHTML(); }, 3200));
//atualizador de eventos
document.addEventListener('click', () => {
addTrendsHTML();
addPollButton();
setTimeout(() => {
addLikedButton();
addBookmarksSidebarButton();
addSettingsButton();
}, 1000)
})
//eventos especificos
document.addEventListener('click', (event) => {
if (event.target.id === "betterblueskypollbutton") {
const title = prompt("[BetterBluesky] Qual o título da enquete?")
if (!title) return;
const options = [];
const maxOptions = 5;
addOption(0)
function addOption(currentOptionNumber) {
if (currentOptionNumber >= maxOptions) return createPoll({ title, options })
const option = prompt(`[BetterBluesky] Qual a ${currentOptionNumber + 1}º opção? ${(currentOptionNumber != 0) ? "[Cancele para não adicionar mais]" : ""}`);
if (!option) {
if (currentOptionNumber === 0) return;
return createPoll({ title, options })
}
options.push(option)
addOption(currentOptionNumber + 1)
}
}
if (event.target.classList.contains("betterbluesky_poll_option")) {
const optionData = JSON.parse(event.target.getAttribute("betterbluesky_poll_option_data"));
if (!optionData.voted) {
votePoll(optionData.pollid, optionData.option)
}
}
if (event.target.classList.contains("betterbluesky_setting")) {
updateSetting(event.target.getAttribute("betterbluesky_update", e.target.checked))
}
if (event.target.id === "bookmarks-btn") {
location.href = "https://bit.ly/bookmarksfeed"
}
if (event.target.classList.contains("bookmarkbutton")) {
const data = extractHandleAndPostIdFromUrl(window.location.href);
fetch(`${apiDomain}/api/bookmarks?postid=${encodeURIComponent(data.postId)}&postuserhandle=${encodeURIComponent(data.handle)}&sessionID=${sessionID}`, {
method: (event.target.getAttribute("marked") === "true") ? "DELETE" : "POST"
})
if (event.target.getAttribute("marked") === "true") {
event.target.setAttribute("marked", false);
console.log(`[BetterBluesky] Post bookmark ${data.postId} set to false`)
} else {
event.target.setAttribute("marked", true);
console.log(`[BetterBluesky] Post bookmark ${data.postId} set to true`)
}
}
if (event.target.id === "userlikedbutton") {
window.open(`https://likedbetterbluesky.nemtudo.me/?defaultHandle=${encodeURIComponent(getLastURLParam())}`)
}
if (event.target.id === "settings-btn") {
settingsPopup();
updateCheckBoxes();
}
if (event.target.id === "refresh-btn") {
document.querySelector('.overlay').remove();
location.reload();
}
if (event.target.id === "popup-overlay") {
document.querySelector('.overlay').remove();
}
if (event.target.id === "preferences") {
updatePreferences(event.target.name);
}
})
//funções gerais
async function createPoll(poll) {
const request = await fetch(`${apiDomain}/api/polls?polldata=${encodeURIComponent(JSON.stringify(poll))}&sessionID=${sessionID}`, {
method: "POST",
})
const response = await request.json();
if (request.status != 200) return alert(`Erro ao criar enquete: ${response.message}`);
console.log(`[BetterBluesky] Enquete criada: ${response.id}`)
document.querySelector('div[contenteditable="true"]').innerHTML += `https://nemtudo.me/betterbluesky/polls/${response.id}`
}
function addLikedButton() {
if (betterblueskystorage.likes == false) return; // Respect user preference
document.querySelectorAll('div[style="flex-direction: row; gap: 4px; align-items: center;"]').forEach(element => {
if (element) {
if (!element.querySelector('#userlikedbutton')) {
element.innerHTML += `<button id="userlikedbutton">❤</button>`
}
}
})
}
function formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace('.0', '') + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1).replace('.0', '') + ' mil';
} else {
return num.toString();
}
}
function escapeHTML(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function addTrendsHTML() {
if (betterblueskystorage.trendingTopics == false) return; // Respect user preference
if (document.querySelector("#trendsarea")) return;
const languages = [
{
id: "global",
name: "Global"
},
{
id: "pt",
name: "Português"
},
{
id: "en",
name: "English"
},
{
id: "fr",
name: "Français"
},
{
id: "es",
name: "Español"
},
{
id: "ja",
name: "日本語"
}
]
const selectLanguage = `<select name="select_trends_language" id="select_trends_language">
${languages.map(language => `<option ${(betterblueskystorage.trends_language === language.id) ? "selected" : ""} value="${language.id}">${language.name}</option>`)}
</select>`;
const element = document.querySelector("div[class='css-175oi2r r-qklmqi r-5kkj8d r-le4sbl r-1444osr']") || document.querySelector('div[class="css-175oi2r r-196lrry r-pm9dpa r-1rnoaur r-1xcajam r-1ipicw7"]')
if (element) element.insertAdjacentHTML("afterbegin", `<div class="trends">
<div class="trends_title">
<h2 id="trendingsname">${betterblueskystorage.easter_egg_tremdetopicos ? "Trem de tópicos" : "Trending Topics"}</h2> ${selectLanguage}
</div>
<div class='description'>
<span>Fornecido por <a style="color: #FF9325;" target="_blank" role="link" href='https://nemtudo.me/betterbluesky'>BetterBluesky</a>.<br> Desenvolvido por <a id="devcredits" target="_blank" href='https://bsky.app/profile/nemtudo.me'>@nemtudo.me</a>. Siga!</span>
</div>
<ul id="trendsarea">
<span class="loadingtrends">Carregando...</span>
</ul>
</div>`)
updateTrends(true);
document.querySelectorAll(`#select_trends_language`).forEach(select => {
select.addEventListener('change', function (event) {
const selectedLanguage = event.target.value;
updatePreferences("trends_language", selectedLanguage)
updateTrends(true)
});
});
}
function addPollButton() {
if (betterblueskystorage.polls == false) return; // Respect user preference
// dark
if ((!document.querySelector("#betterblueskypollbutton")) && (document.querySelector('div[style="flex-direction: row; padding: 8px; background-color: rgb(0, 0, 0); border-top-width: 1px; border-color: rgba(0, 0, 0, 0);"]'))) document.querySelector('div[style="flex-direction: row; padding: 8px; background-color: rgb(0, 0, 0); border-top-width: 1px; border-color: rgba(0, 0, 0, 0);"]').insertAdjacentHTML("beforeend", `<button id='betterblueskypollbutton'>Enquete</button>`) //+ document.querySelector("div[class='css-175oi2r r-1awozwy r-5kkj8d r-18u37iz r-cnw61z r-16lhzmz r-i023vh']").innerHTML;
// menos dark
if ((!document.querySelector("#betterblueskypollbutton")) && (document.querySelector('div[style="flex-direction: row; padding: 8px; background-color: rgb(255, 255, 255); border-top-width: 1px; border-color: rgba(0, 0, 0, 0);"]'))) document.querySelector('div[style="flex-direction: row; padding: 8px; background-color: rgb(255, 255, 255); border-top-width: 1px; border-color: rgba(0, 0, 0, 0);"]').insertAdjacentHTML("beforeend", `<button id='betterblueskypollbutton'>Enquete</button>`) //+ document.querySelector("div[class='css-175oi2r r-1awozwy r-5kkj8d r-18u37iz r-cnw61z r-16lhzmz r-i023vh']").innerHTML;
//claro
if ((!document.querySelector("#betterblueskypollbutton")) && (document.querySelector('div[style="flex-direction: row; padding: 8px; background-color: rgb(22, 30, 39); border-top-width: 1px; border-color: rgba(0, 0, 0, 0);"]'))) document.querySelector('div[style="flex-direction: row; padding: 8px; background-color: rgb(22, 30, 39); border-top-width: 1px; border-color: rgba(0, 0, 0, 0);"]').insertAdjacentHTML("beforeend", `<button id='betterblueskypollbutton'>Enquete</button>`) //+ document.querySelector("div[class='css-175oi2r r-1awozwy r-5kkj8d r-18u37iz r-cnw61z r-16lhzmz r-i023vh']").innerHTML;
}
function addDownloadVideoButton() {
return;
document.querySelectorAll("div[style='flex: 1 1 0%; padding: 8px 4px 12px; gap: 12px; flex-direction: row; align-items: center;']").forEach(element => {
if (!element.querySelector(".betterbluesky_downloadvideobutton")) element.insertAdjacentHTML("beforeend", `<button class="betterbluesky_downloadvideobutton"><img src="https://cdn-icons-png.flaticon.com/512/724/724933.png"/></button>`)
})
}
async function addBookmarkButton() {
const elements = document.querySelectorAll('div[class="css-175oi2r r-1loqt21 r-1hfyk0a r-ry3cjt"] div[style="flex-direction: row; justify-content: space-between; align-items: center;"], div[style="padding-top: 8px; padding-bottom: 2px; margin-left: -5px;"] > div')
const data = extractHandleAndPostIdFromUrl(window.location.href);
for (const element of elements) {
if (!element.querySelector("#bookmarkbutton")) {
const id = randomString(5);
element.insertAdjacentHTML("beforeend", `<button id="bookmarkbutton" marked="false" class="bookmarkbutton" data_bookmarkbutton_id="${id}" ><img class="bookmarkbutton_unmarkedimage" src="https://cdn-icons-png.flaticon.com/512/494/494568.png"/><img class="bookmarkbutton_markedimage" src="https://cdn-icons-png.flaticon.com/512/786/786352.png"/></button>`);
if (!data) return;
const response = await fetch(`${apiDomain}/api/bookmarks?postid=${encodeURIComponent(data.postId)}&sessionID=${sessionID}`).then(r => r.json());
if (response.exists) {
document.querySelector(`.bookmarkbutton[data_bookmarkbutton_id="${id}"]`).setAttribute("marked", "true")
}
}
}
}
function addSettingsButton() {
// Settings / preferences by pugdev :D
if (document.querySelector("#settings-btn")) return;
const sidebar = document.querySelector("div[class='css-175oi2r r-c4unlt r-pgf20v r-1rnoaur r-1xcajam r-1ki14p2 r-1w88a7h']") || document.querySelector("div[class='css-175oi2r r-pgf20v r-1rnoaur r-1xcajam r-1awozwy r-13l2t4g r-1pi2tsx r-1d2f490 r-12ijkx4 r-ipm5af r-z2g584']");
if (sidebar) {
const buttonContainer = document.createElement("div");
buttonContainer.id = "settings-btn";
buttonContainer.classList.add("settings_btn")
// Adds the settings button and an icon version for smaller screens.
buttonContainer.innerHTML = `
<button id='settings-btn' class='bb-settings-icon'>🦋</button>
<button id='settings-btn' class='bb-settings-button'><p id='settings-btn' class="bb-settings-text">🦋 BetterBluesky</p></button>
`;
var lastChild = sidebar.lastChild;
sidebar.insertBefore(buttonContainer, lastChild);
}
if (!sidebar) console.warn("Nenhuma sidebar encontrada. o CSS mudou? 0_0");
}
function addBookmarksSidebarButton() {
// Bookmarks button
if (!betterblueskystorage.bookmarks) return; //respect user preference
if (document.querySelector("#bookmarks-btn")) return;
const sidebar = document.querySelector("div[class='css-175oi2r r-c4unlt r-pgf20v r-1rnoaur r-1xcajam r-1ki14p2 r-1w88a7h']") || document.querySelector("div[class='css-175oi2r r-pgf20v r-1rnoaur r-1xcajam r-1awozwy r-13l2t4g r-1pi2tsx r-1d2f490 r-12ijkx4 r-ipm5af r-z2g584']");
if (sidebar) {
const buttonContainer = document.createElement("div");
buttonContainer.id = "bookmarks-btn";
// Adds the settings button and an icon version for smaller screens.
buttonContainer.innerHTML = `
<button id='bookmarks-btn' class='bb-settings-icon'>📌</button>
<button id='bookmarks-btn' class='bb-settings-button'><p id='bookmarks-btn' class="bb-settings-text">📌 Bookmarks</p></button>
`;
var lastChild = sidebar.lastChild;
sidebar.insertBefore(buttonContainer, lastChild);
}
if (!sidebar) console.warn("Nenhuma sidebar encontrada. o CSS mudou? 0_0");
}
function replaceBetterBlueSkyVideos() {
if (betterblueskystorage.videos == false) return; // Respect user preference
// Seleciona todo o conteúdo da página
const pageContents = document.querySelectorAll('div[data-testid="contentHider-post"],div[class="css-146c3p1 r-1xnzce8"]');
// Regex para capturar o link no formato <betterblueskyvideo:link>
const regex = /<BetterBlueSky_video:(https?:\/\/[^\s>]+)>/g;
pageContents.forEach(element => {
// Substitui pelo elemento de vídeo
if (!element.innerHTML.match(regex)) return;
const html = element.innerHTML.replace(regex, function (match, url) {
if (!validURL(url)) return;
const videoElement = `<video class="betterblueskyvideo" controls>
<source src="${escapeHTML(url)}" type="video/mp4">
Seu navegador não suporta tags de vídeos.
</video>`;
return videoElement;
});
// Atualiza o conteúdo da página
element.innerHTML = html;
})
}
async function replaceBetterBlueSkyPolls() {
if (betterblueskystorage.polls == false) return; // Respect user preference
// Seleciona todo o conteúdo da página
const pageContents = document.querySelectorAll('div[class="css-146c3p1 r-1xnzce8"],div[data-testid="contentHider-post"],div[class="css-175oi2r r-1awozwy r-18u37iz r-1w6e6rj r-1udh08x"],div[class="css-175oi2r r-18u37iz r-is05cd"]');
// Regex para capturar o link no formato https://nemtudo.me/betterbluesky/polls/(id da poll a-zA-Z0-9)
const regex = /<a\s+[^>]*href=["']https:\/\/nemtudo\.me\/betterbluesky\/polls\/([a-zA-Z0-9]+)["'][^>]*>(.*?)<\/a>/g;
// Usando for...of para processar as substituições de forma assíncrona
for (const element of pageContents) {
let html = element.innerHTML;
// Cria um array para armazenar as substituições
const matches = [...html.matchAll(regex)];
// Faz a substituição de cada match de forma assíncrona
for (const match of matches) {
const pollID = match[1];
if (!element.innerHTML.match(regex)) return;
await replaceBetterBlueSkyPoll(pollID, [element], match[0])
}
}
setTimeout(() => {
replaceBetterBlueSkyPolls()
}, 1000)
}
async function replaceBetterBlueSkyPoll(pollID, elements, match) {
const poll = await getPoll(pollID);
elements.forEach((element) => {
let html = element.innerHTML;
if (!poll) {
const pollElement = `<div class="betterbluesky_pollnotfound"><span>Enquete excluída</span><span class="betterbluesky_pollnotfound_description"><a target="_blank" href="https://nemtudo.me/betterbluesky">BetterBluesky</a>・Veja os trendings topics, envie enquetes & mais.</span></div>`;
// Substitui o match atual pelo elemento
if (match) {
html = html.replace(match, pollElement);
} else {
html = pollElement;
}
// Atualiza o conteúdo da página
return element.innerHTML = html;
}
const totalVotes = poll.options.reduce((c, a) => a.voteCount + c, 0);
const pollElement = `<div betterbluesky_poll_id="${poll.id}"><div class="betterbluesky_poll" voted="${poll.voted}">
<span class="betterbluesky_poll_title">${escapeHTML(poll.title)}</span>
<div class="betterbluesky_poll_options">
${poll.options.map((option, index) => `
<button class="betterbluesky_poll_option" betterbluesky_poll_option_data='${JSON.stringify({ pollid: poll.id, option: index, voted: poll.voted })}' option_selected="${option.selected}">
<div class="betterbluesky_poll_votebackground" style="width: ${Math.round((option.voteCount / totalVotes) * 100)}%;"></div>
<span class="betterbluesky_poll_option_text">${escapeHTML(option.text)}</span>
<img class="betterbluesky_poll_option_votedicon" src="https://cdn-icons-png.flaticon.com/512/1442/1442912.png"/>
<span class="betterbluesky_poll_votecount">${option.voteCount} voto${option.voteCount === 1 ? "" : "s"}</span>
</button>`).join(" ")}
</div>
<span class="betterbluesky_poll_totalvotescount">${totalVotes} voto${(totalVotes === 1) ? "" : "s"}</span>
<span class="betterbluesky_poll_bybetterbluesky">Fornecido por <a target="_blank" href="https://nemtudo.me/betterbluesky">BetterBluesky</a></span>
</div></div>`;
// Substitui o match atual pelo elemento
if (match) {
html = html.replace(match, pollElement);
} else {
html = pollElement;
}
// Atualiza o conteúdo da página
element.innerHTML = html;
})
}
async function getPoll(pollID) {
const request = await fetch(`${apiDomain}/api/polls/${pollID}?sessionID=${sessionID}`);
if (request.status != 200) {
return null
}
const poll = await request.json();
return poll
}
async function votePoll(pollID, option) {
console.log(`[BetterBluesky] Voting poll ${pollID}: ${option}`)
const request = await fetch(`${apiDomain}/api/polls/${pollID}/votes?option=${option}&sessionID=${sessionID}`, {
method: "POST"
});
const response = await request.json();
if (request.status != 200) {
console.log(request, response)
alert(`Erro ao votar: ${response.message}`)
return null
}
const pollElements = document.querySelectorAll(`div[betterbluesky_poll_id="${response.pollId}"]`);
replaceBetterBlueSkyPoll(response.pollId, pollElements)
return response
}
(function () { //easter egg trem de tópicos
let typed = ""; // String para armazenar as teclas pressionadas
const target = "tremdetopicos"; // A sequência que você quer detectar
const maxLength = target.length; // Tamanho da sequência alvo
document.addEventListener("keydown", function (event) {
if (betterblueskystorage.trendingTopics == false) return; // There is no point for this easter egg if trending topics are disabled.
// Adiciona a tecla pressionada à string
typed += event.key.toLowerCase(); // Converte para minúscula para comparação
// Mantém a string com no máximo o tamanho da sequência alvo
if (typed.length > maxLength) {
typed = typed.slice(-maxLength);
}
// Verifica se a sequência alvo foi digitada
if (typed === target) {
if (!betterblueskystorage.easter_egg_tremdetopicos) {
if (document.querySelector("#trendingsname")) document.querySelector("#trendingsname").innerHTML = "Trem de Tópicos"
updatePreferences("easter_egg_tremdetopicos", true)
} else {
if (document.querySelector("#trendingsname")) document.querySelector("#trendingsname").innerHTML = "Trending Topics"
updatePreferences("easter_egg_tremdetopicos", false)
}
}
});
})();
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
return !!pattern.test(str);
}
function randomString(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}
function updateSetting(setting, value) {
const storage = JSON.parse(localStorage.getItem("BETTERBLUESKY"));
storage[setting] = value;
localStorage.setItem("BETTERBLUESKY", JSON.stringify(storage));
betterblueskystorage = storage;
}
function getLastURLParam() {
const url = window.location.href;
const parts = url.split(/[?#]/)[0].split('/').filter(part => part); // Remove strings vazias
return parts[parts.length - 1]; // Retorna o último segmento
}
function extractHandleAndPostIdFromUrl(url) {
const regex = /\/profile\/([^\/\.]+(?:\.[^\/\.]+)*)\/post\/([^\/\?#]+)/;
const match = url.match(regex);
if (match) {
return {
handle: match[1],
postId: match[2]
};
} else {
return null;
}
}