This repository was archived by the owner on Aug 28, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReddit-Distributed-Top-Posts.user.js
More file actions
518 lines (409 loc) · 19.3 KB
/
Copy pathReddit-Distributed-Top-Posts.user.js
File metadata and controls
518 lines (409 loc) · 19.3 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
// ==UserScript==
// @name Reddit Distributed Top Posts
// @version 0.1.0
// @description An alternative, account-less, media-only and minimalist feed for Reddit that lists the top posts from all the specified subreddits equally, regardless of the community's size. Even if the sub is small it will appear in the same frequency as all other subs.
// @author BLBC (github.com/hjk789, greasyfork.org/users/679182-hjk789)
// @copyright 2022+, BLBC (github.com/hjk789, greasyfork.org/users/679182-hjk789)
// @homepage https://github.com/hjk789/Userscripts/tree/master/Reddit-Distributed-Top-Posts
// @license https://github.com/hjk789/Userscripts/tree/master/Reddit-Distributed-Top-Posts#license
// @match https://*.reddit.com/
// @include /https://\w+\.reddit\.com/(r|user)/[-\w]+/?$/
// @grant none
// ==/UserScript==
//*********** SETTINGS ***********
let subs = ["memes", "gifs", "aww"] // The list of subreddits to gather the posts from. You must use the sub's id (the one after the r/).
// You can specify as many communities as you want, you just need to follow the syntax ["Sub1", "Sub2"]
let users = [] // Same as above, but for user pages (the ones at reddit.com/user/<username>).
let timeWindow = "day" // The default time frame to get the top posts from. Accepted values are "hour", "day", "week", "month", "year" and "alltime".
const maxVideoQuality = 720 // Reddit provides multiple resolutions for the same video. The script will load the videos in
// the quality you specified (if available). Accepted qualities are 240, 360, 480, 720 and 1080.
const maxImageHeight = 1000 // Reddit provides multiple resolutions for the same image. You can specify
// any size and the script will load the image in the closest size available.
const filterNSFW = true // When true, posts set as NSFW are filtered from the list and won't be included. Set to false to disable the filtering.
const loopVideos = true // Whether videos should replay after reaching the end.
//********************************
const responsesPerSource = {}
let loading = false
const duplicateMediaSamples = []
const container = document.createElement("div")
container.style = "position: fixed; z-index: 999; inset: 0px; margin: auto; height: 100vh; width: min(900px,100vw); overflow-y: scroll; background: white; text-align: center;"
container.onscroll = async function()
{
if (!loading && this.scrollTop > this.scrollHeight - window.innerHeight * 3)
{
loading = true
loadNextPage()
}
}
const timeFrames = ["hour", "day", "week", "month", "year", "alltime"]
const timeWindowContainer = document.createElement("div")
timeWindowContainer.style = "position: sticky; top: 25px; background: white; padding: 3px;"
const label = document.createElement("span")
label.innerText = "Top posts since a "
timeWindowContainer.appendChild(label)
const timeWindowDropdown = document.createElement("select")
timeWindowDropdown.onchange = function()
{
timeWindow = this.value
duplicateMediaSamples.length = 0
sourceNames = subs.concat(users)
container.innerHTML = ""
container.appendChild(timeWindowContainer)
timeWindowDropdown.value = timeWindow
loadPosts()
}
for (let i=0; i < timeFrames.length; i++)
{
const option = document.createElement("option")
option.value = timeFrames[i]
option.innerText = timeFrames[i].charAt(0).toUpperCase() + timeFrames[i].slice(1)
timeWindowDropdown.appendChild(option)
}
timeWindowDropdown.value = timeWindow
timeWindowContainer.appendChild(timeWindowDropdown)
container.appendChild(timeWindowContainer)
document.body.appendChild(container)
const onViewObserver = new IntersectionObserver((entries) => // when the user actually sees them on the screen, instead of when they are loaded.
{
entries.forEach(entry =>
{
if (entry.isIntersecting)
entry.target.play()
else
entry.target.pause()
})
}, {threshold: 0.8})
if (/\/(r|user)\//.test(location.pathname))
{
const subOrUserName = location.pathname.split("/")[2]
if (location.pathname.includes("/user/"))
{
subs = []
users = [subOrUserName]
}
else
{
subs = [subOrUserName]
users = []
}
}
let sourceNames = subs.concat(users)
const pageSize = sourceNames.length == 1 ? 10 : 3
loadPosts()
async function loadPosts()
{
let prefixSub, prefixUser
if (filterNSFW)
prefixSub = "subreddit:", prefixUser = "author:"
else
prefixSub = "/r/", prefixUser = "/u/"
for (let i=0; i < subs.length; i++)
responsesPerSource[subs[i]] = { type: prefixSub, response: await fetchSubredditPostsPromise(prefixSub+subs[i]) }
for (let i=0; i < users.length; i++)
responsesPerSource[users[i]] = { type: prefixUser, response: await fetchSubredditPostsPromise(prefixUser+users[i]) }
processPosts()
}
function fetchSubredditPostsPromise(sourceUrlString, after)
{
return new_Promise(resolve => fetchSubredditPosts(sourceUrlString, after, resolve))
}
function fetchSubredditPosts(sourceUrlString, after, resolve)
{
let requestUrl
const params = "limit="+pageSize+"&sort=top&t="+timeWindow+"&after="+after
if (filterNSFW)
requestUrl = "/search.json?q=nsfw:no+"+sourceUrlString+"&"+params
else
{
requestUrl = sourceUrlString
if (/\br\b|subreddit:/.test(sourceUrlString))
requestUrl += "/top/"
else
requestUrl += "/submitted/"
requestUrl += ".json?" + params.replace("time", "")
}
const xhr = new XMLHttpRequest()
xhr.open("GET", requestUrl)
xhr.onload = ()=> resolve(JSON.parse(xhr.responseText.replaceAll("&", "&")))
xhr.onerror = ()=> setTimeout(()=> fetchSubredditPosts(sourceUrlString, after, resolve), 5000)
xhr.send()
}
function processPosts()
{
const style = "max-width: calc(100% - 6px); max-height: min(92vh,720px); object-fit: contain; inset: 0; margin: 15px auto; border: 3px lightgray solid; border-radius: 25px; display: block;"
let postPromises = []
for (let i=0; i < pageSize; i++)
{
for (let j=0; j < sourceNames.length; j++)
{
postPromises.push(new_Promise((resolve)=>
{
const response = responsesPerSource[sourceNames[j]].response
let post = response.data.children[i]?.data
let crosspost
if (post && post.crosspost_parent_list)
{
crosspost = post
post = post.crosspost_parent_list[0]
}
if (!post || post.is_self && !post.preview && !post.media || post.media && ["twitter.com", "youtube.com"].includes(post.media.type))
return resolve()
if (post.media?.reddit_video || post.preview?.reddit_video_preview || post.preview?.images[0].variants.mp4 || post.url.includes("gfycat.com") && post.media?.oembed || post.url.includes(".gifv"))
{
const videoRoot = post.preview.reddit_video_preview || post.media?.reddit_video
let videoUrl
if (videoRoot)
videoUrl = videoRoot.height > maxVideoQuality ? videoRoot.scrubber_media_url.replace("_96.", "_"+maxVideoQuality+".") : videoRoot.fallback_url
else
videoUrl = post.preview?.images[0].variants.mp4?.source.url || post.media?.oembed.thumbnail_url.replace("size_restricted.gif", "mobile.mp4") || post.url.includes(".gifv") && post.url.replace(".gifv", ".mp4")
if (!videoUrl)
return resolve()
const xhr = new XMLHttpRequest()
xhr.open('GET', videoUrl)
xhr.onload = function()
{
const hash = stringToHash(this.response)
if (duplicateMediaSamples.includes(hash))
return resolve()
duplicateMediaSamples.push(hash)
const video = document.createElement("video")
video.src = videoUrl
video.style = style
video.controls = true
video.loop = loopVideos
video.onloadeddata = function() { checkAndResize(this, true) }
container.appendChild(video)
if (post.is_video)
{
const audio = document.createElement("audio")
audio.src = videoRoot.scrubber_media_url.replace("_96.", "_audio.")
container.appendChild(audio)
video.onplay = ()=> { audio.play(); audio.currentTime = video.currentTime }
video.onpause = ()=> audio.pause()
}
onViewObserver.observe(video)
createPostMetadata(post, crosspost, container)
resolve()
}
xhr.send()
}
else if (post.url && /\.(jpe?g|png)/.test(post.url) || post.domain == "imgur.com" || post.post_hint == "rich:video" || post.url.includes("gfycat.com") && post.preview)
{
if (post.preview)
{
const image = post.preview.images[0]
let mediaUrl = image.source.url
if (image.source.height > maxImageHeight)
{
for (let k=0; k < image.resolutions.length; k++)
{
if (image.resolutions[k].height > maxImageHeight)
{
mediaUrl = image.resolutions[k].url
break
}
}
}
const xhr = new XMLHttpRequest()
xhr.open('GET', mediaUrl)
xhr.onload = function()
{
const hash = stringToHash(this.response)
if (duplicateMediaSamples.includes(hash))
return resolve()
duplicateMediaSamples.push(hash)
const img = document.createElement("img")
img.src = mediaUrl
img.style = style
img.onload = function()
{
if (this.naturalHeight > 60)
checkAndResize(this)
else
{
while (this.nextSibling.tagname == "A")
this.nextSibling.remove()
this.remove()
}
}
container.appendChild(img)
createPostMetadata(post, crosspost, container)
resolve()
}
xhr.send()
}
else
{
const imageExtensions = ["jpg", "png", "gif"]
const videoExtensions = ["gifv", "mp4"]
const sourceUrlSplit = post.url.split(".")
const sourceExtension = sourceUrlSplit[sourceUrlSplit.length-1]
post.url = post.url.replace("https://imgur", "https://i.imgur")
const xhr = new XMLHttpRequest()
xhr.open('GET', post.url)
xhr.onload = function()
{
const hash = stringToHash(this.response)
if (duplicateMediaSamples.includes(hash))
return resolve()
duplicateMediaSamples.push(hash)
if (imageExtensions.includes(sourceExtension))
{
const img = document.createElement("img")
img.src = post.url
img.style = style
img.onload = function() { checkAndResize(this) }
container.appendChild(img)
}
else if (videoExtensions.includes(sourceExtension))
{
const video = document.createElement("video")
video.src = post.url.replace("gifv", "mp4")
video.style = style
video.controls = true
video.loop = loopVideos
video.onloadeddata = function() { checkAndResize(this, true) }
container.appendChild(video)
onViewObserver.observe(video)
}
createPostMetadata(post, crosspost, container)
resolve()
}
xhr.send()
}
}
else if (post.is_gallery || post.url.includes("/gallery/"))
{
const mediaUrls = []
Object.getOwnPropertyNames(post.media_metadata).forEach((p)=>
{
const mediaMetadata = post.media_metadata[p]
let mediaUrl = mediaMetadata.s.u
if (mediaMetadata.s.y > maxImageHeight)
{
for (let k=0; k < mediaMetadata.p.length; k++)
{
if (mediaMetadata.p[k].y > maxImageHeight)
{
mediaUrl = mediaMetadata.p[k].u
break
}
}
}
mediaUrls.push(mediaUrl)
})
const imagesPromises = []
for (let k=0; k < mediaUrls.length; k++)
{
imagesPromises.push(new_Promise((resolveImg,reject) =>
{
const xhr = new XMLHttpRequest()
xhr.open('GET', mediaUrls[k])
xhr.onload = function()
{
const hash = stringToHash(this.response)
if (duplicateMediaSamples.includes(hash))
return reject()
duplicateMediaSamples.push(hash)
resolveImg()
}
xhr.send()
}))
}
Promise_all(imagesPromises).then(()=>
{
for (let k=0; k < mediaUrls.length; k++)
{
const img = document.createElement("img")
img.src = mediaUrls[k]
img.style = style
img.onload = function() { checkAndResize(this) }
container.appendChild(img)
}
createPostMetadata(post, crosspost, container)
resolve()
})
}
else{
console.log(post)
resolve()
}
}))
}
}
}
function checkAndResize(element, isVideo)
{
if (screen.width + screen.height > 1400)
{
if ((isVideo ? element.videoWidth + element.videoHeight : element.naturalWidth + element.naturalHeight) < 1090)
{
if ((isVideo ? element.videoHeight / element.videoWidth : element.naturalHeight / element.naturalWidth) > 0.6)
element.style.height = "65vh"
else
element.style.width = "98%"
}
}
else if (screen.width < screen.height)
element.style.width = "98%"
}
async function loadNextPage()
{
for (let i=0; i < sourceNames.length; i++)
{
const response = responsesPerSource[sourceNames[i]]
if (!response.response.data.after)
{
delete responsesPerSource[sourceNames[i]]
sourceNames.splice(i, 1)
i--
continue
}
response.response = await fetchSubredditPostsPromise(response.type + sourceNames[i], response.response.data.after)
}
if (sourceNames.length)
processPosts()
loading = false
}
function createPostMetadata(post, crosspost, container)
{
if (crosspost)
post = crosspost
if (post.subreddit_name_prefixed != "u/"+post.author)
{
const subname = document.createElement("a")
subname.style = "margin-top: -10px; margin-right: 50px; display: ruby-text;"
subname.innerText = post.subreddit_name_prefixed
subname.href = "/./"+subname.innerText
container.appendChild(subname)
}
const username = document.createElement("a")
username.style = "margin-top: -10px; margin-right: 50px; display: ruby-text;"
username.innerText = "u/"+post.author
username.href = "/"+username.innerText
container.appendChild(username)
const commentCount = document.createElement("a")
commentCount.style = "margin-top: -10px; display: ruby-text;"
commentCount.innerText = post.num_comments +" comments"
commentCount.href = post.permalink
container.appendChild(commentCount)
}
function stringToHash(string)
{
let hash = 0
for (let i=0; i < string.length; i++)
{
const char = string.charCodeAt(i)
hash = (hash << 5) - hash + char
hash &= hash
}
return new Uint32Array([hash])[0].toString(36)
}
function new_Promise(promiseFunction)
{
return new Promise(promiseFunction).catch((e)=> console.log(e))
}
function Promise_all(promises)
{
return Promise.all(promises).catch((e)=> console.log(e))
}