-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathSubscriptionsVideos.vue
More file actions
447 lines (374 loc) · 12.9 KB
/
SubscriptionsVideos.vue
File metadata and controls
447 lines (374 loc) · 12.9 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
<template>
<SubscriptionsTabUi
:is-loading="isLoading"
:video-list="videoList"
:error-channels="errorChannels"
:last-refresh-timestamp="lastVideoRefreshTimestamp"
:attempted-fetch="attemptedFetch"
:title="t('Global.Videos')"
@refresh="loadVideosForSubscriptionsFromRemote"
/>
</template>
<script setup>
import { computed, onMounted, ref, shallowRef, watch } from 'vue'
import { useI18n } from '../composables/use-i18n-polyfill'
import SubscriptionsTabUi from './SubscriptionsTabUi/SubscriptionsTabUi.vue'
import store from '../store/index'
import {
copyToClipboard,
getRelativeTimeFromDate,
showToast,
getChannelPlaylistId
} from '../helpers/utils'
import { getInvidiousChannelVideos, invidiousFetch } from '../helpers/api/invidious'
import { getLocalChannelVideos } from '../helpers/api/local'
import { parseYouTubeRSSFeed, updateVideoListAfterProcessing } from '../helpers/subscriptions'
const { t } = useI18n()
const isLoading = ref(true)
const videoList = shallowRef([])
const errorChannels = ref([])
const attemptedFetch = ref(false)
/** @type {import('vue').Ref<number | null>} */
const lastRemoteRefreshSuccessTimestamp = ref(null)
let alreadyLoadedRemotely = false
/** @type {import('vue').ComputedRef<'local' | 'invidious'>} */
const backendPreference = computed(() => store.getters.getBackendPreference)
/** @type {import('vue').ComputedRef<'local' | 'invidious'>} */
const backendFallback = computed(() => store.getters.getBackendFallback)
/** @type {import('vue').ComputedRef<string>} */
const currentInvidiousInstanceUrl = computed(() => store.getters.getCurrentInvidiousInstanceUrl)
/** @type {import('vue').ComputedRef<boolean>} */
const subscriptionCacheReady = computed(() => store.getters.getSubscriptionCacheReady)
/** @type {import('vue').ComputedRef<boolean>} */
const useRssFeeds = computed(() => store.getters.getUseRssFeeds)
/** @type {import('vue').ComputedRef<boolean>} */
const fetchSubscriptionsAutomatically = computed(() => store.getters.getFetchSubscriptionsAutomatically)
const activeSubscriptionList = computed(() => store.getters.getActiveProfile.subscriptions)
const cacheEntriesForAllActiveProfileChannels = computed(() => {
const videoCache = store.getters.getVideoCache
const entries = []
activeSubscriptionList.value.forEach((channel) => {
const cacheEntry = videoCache[channel.id]
if (cacheEntry != null) {
entries.push(cacheEntry)
}
})
return entries
})
const videoCacheForAllActiveProfileChannelsPresent = computed(() => {
if (
cacheEntriesForAllActiveProfileChannels.value.length === 0 ||
cacheEntriesForAllActiveProfileChannels.value.length < activeSubscriptionList.value.length
) {
return false
}
return cacheEntriesForAllActiveProfileChannels.value.every((cacheEntry) => {
return cacheEntry.videos != null
})
})
const lastVideoRefreshTimestamp = computed(() => {
// Cache is not ready when data is just loaded from remote
if (lastRemoteRefreshSuccessTimestamp.value) {
return getRelativeTimeFromDate(lastRemoteRefreshSuccessTimestamp.value, true)
}
if (
!videoCacheForAllActiveProfileChannelsPresent.value ||
cacheEntriesForAllActiveProfileChannels.value.length === 0
) {
return ''
}
let minTimestamp = null
cacheEntriesForAllActiveProfileChannels.value.forEach((cacheEntry) => {
if (!minTimestamp || cacheEntry.timestamp.getTime() < minTimestamp.getTime()) {
minTimestamp = cacheEntry.timestamp
}
})
return getRelativeTimeFromDate(minTimestamp.getTime(), true)
})
watch(activeSubscriptionList, () => {
lastRemoteRefreshSuccessTimestamp.value = null
isLoading.value = true
loadVideosFromCacheSometimes()
}, { deep: true })
if (!subscriptionCacheReady.value) {
watch(subscriptionCacheReady, () => {
if (!alreadyLoadedRemotely) {
loadVideosFromCacheSometimes()
}
})
}
onMounted(() => {
loadVideosFromRemoteFirstPerWindowSometimes()
})
function loadVideosFromRemoteFirstPerWindowSometimes() {
if (
!fetchSubscriptionsAutomatically.value ||
// Only auto fetch once per window
store.getters.getSubscriptionForVideosFirstAutoFetchRun
) {
loadVideosFromCacheSometimes()
return
}
alreadyLoadedRemotely = true
loadVideosForSubscriptionsFromRemote()
store.commit('setSubscriptionForVideosFirstAutoFetchRun')
}
function loadVideosFromCacheSometimes() {
// Can only load reliably when cache ready
if (!subscriptionCacheReady.value) { return }
// This method is called on view visible
if (videoCacheForAllActiveProfileChannelsPresent.value) {
loadVideosFromCacheForAllActiveProfileChannels()
return
}
if (fetchSubscriptionsAutomatically.value) {
// `isLoading.value = false` is called inside `loadVideosForSubscriptionsFromRemote` when needed
loadVideosForSubscriptionsFromRemote()
return
}
// Auto fetch disabled, not enough cache for profile = show nothing
videoList.value = []
attemptedFetch.value = false
isLoading.value = false
}
function loadVideosFromCacheForAllActiveProfileChannels() {
const videoList_ = cacheEntriesForAllActiveProfileChannels.value.flatMap((cacheEntry) => {
return cacheEntry.videos
})
videoList.value = updateVideoListAfterProcessing(videoList_)
isLoading.value = false
}
async function loadVideosForSubscriptionsFromRemote() {
if (activeSubscriptionList.value.length === 0) {
isLoading.value = false
videoList.value = []
return
}
const channelsToLoadFromRemote = activeSubscriptionList.value
let channelCount = 0
isLoading.value = true
let useRss = useRssFeeds.value
if (channelsToLoadFromRemote.length >= 125 && !useRss) {
showToast(
t('Subscriptions["This profile has a large number of subscriptions. Forcing RSS to avoid rate limiting"]'),
10000
)
useRss = true
}
store.commit('setShowProgressBar', true)
store.commit('setProgressBarPercentage', 0)
attemptedFetch.value = true
errorChannels.value = []
const subscriptionUpdates = []
const videoListFromRemote = (await Promise.all(channelsToLoadFromRemote.map(async (channel) => {
let videos, name, thumbnailUrl
if (!process.env.SUPPORTS_LOCAL_API || backendPreference.value === 'invidious') {
if (useRss) {
({ videos, name, thumbnailUrl } = await getChannelVideosInvidiousRSS(channel))
} else {
({ videos, name, thumbnailUrl } = await getChannelVideosInvidiousScraper(channel))
}
} else {
if (useRss) {
({ videos, name, thumbnailUrl } = await getChannelVideosLocalRSS(channel))
} else {
({ videos, name, thumbnailUrl } = await getChannelVideosLocalScraper(channel))
}
}
channelCount++
const percentageComplete = (channelCount / channelsToLoadFromRemote.length) * 100
store.commit('setProgressBarPercentage', percentageComplete)
if (videos != null) {
store.dispatch('updateSubscriptionVideosCacheByChannel', {
channelId: channel.id,
videos: videos
})
}
if (name || thumbnailUrl) {
subscriptionUpdates.push({
channelId: channel.id,
channelName: name,
channelThumbnailUrl: thumbnailUrl
})
}
return videos ?? []
}))).flat()
videoList.value = updateVideoListAfterProcessing(videoListFromRemote)
isLoading.value = false
store.commit('setShowProgressBar', false)
lastRemoteRefreshSuccessTimestamp.value = Date.now()
store.dispatch('batchUpdateSubscriptionDetails', subscriptionUpdates)
}
async function getChannelVideosLocalScraper(channel, failedAttempts = 0) {
try {
const result = await getLocalChannelVideos(channel.id)
if (result === null) {
errorChannels.value.push(channel)
return {
videos: []
}
}
return result
} catch (err) {
console.error(err)
const errorMessage = t('Local API Error (Click to copy)')
showToast(`${errorMessage}: ${err}`, 10000, () => {
copyToClipboard(err)
})
switch (failedAttempts) {
case 0:
return await getChannelVideosLocalRSS(channel, failedAttempts + 1)
case 1:
if (backendFallback.value) {
showToast(t('Falling back to Invidious API'))
return await getChannelVideosInvidiousScraper(channel, failedAttempts + 1)
} else {
return {
videos: []
}
}
case 2:
return await getChannelVideosLocalRSS(channel, failedAttempts + 1)
default:
return {
videos: []
}
}
}
}
async function getChannelVideosLocalRSS(channel, failedAttempts = 0) {
const playlistId = getChannelPlaylistId(channel.id, 'videos', 'newest')
const feedUrl = `https://www.youtube.com/feeds/videos.xml?playlist_id=${playlistId}`
try {
const response = await fetch(feedUrl)
if (response.status === 403) {
return {
videos: null
}
}
if (response.status === 404) {
// playlists don't exist if the channel was terminated but also if it doesn't have the tab,
// so we need to check the channel feed too before deciding it errored, as that only 404s if the channel was terminated
const response2 = await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channel.id}`, {
method: 'HEAD'
})
if (response2.status === 404) {
errorChannels.value.push(channel)
}
return {
videos: []
}
}
return await parseYouTubeRSSFeed(await response.text(), channel.id)
} catch (error) {
console.error(error)
const errorMessage = t('Local API Error (Click to copy)')
showToast(`${errorMessage}: ${error}`, 10000, () => {
copyToClipboard(error)
})
switch (failedAttempts) {
case 0:
return await getChannelVideosLocalScraper(channel, failedAttempts + 1)
case 1:
if (backendFallback.value) {
showToast(t('Falling back to Invidious API'))
return await getChannelVideosInvidiousRSS(channel, failedAttempts + 1)
} else {
return {
videos: []
}
}
case 2:
return await getChannelVideosLocalScraper(channel, failedAttempts + 1)
default:
return {
videos: []
}
}
}
}
async function getChannelVideosInvidiousScraper(channel, failedAttempts = 0) {
try {
const result = await getInvidiousChannelVideos(channel.id)
let name
if (result.videos.length > 0) {
name = result.videos.find(video => video.type === 'video' && video.author).author
}
return {
name,
videos: result.videos
}
} catch (err) {
console.error(err)
const errorMessage = t('Invidious API Error (Click to copy)')
showToast(`${errorMessage}: ${err}`, 10000, () => {
copyToClipboard(err)
})
switch (failedAttempts) {
case 0:
return await getChannelVideosInvidiousRSS(channel, failedAttempts + 1)
case 1:
if (process.env.SUPPORTS_LOCAL_API && backendFallback.value) {
showToast(t('Falling back to Local API'))
return await getChannelVideosLocalScraper(channel, failedAttempts + 1)
} else {
return {
videos: []
}
}
case 2:
return await getChannelVideosInvidiousRSS(channel, failedAttempts + 1)
default:
return {
videos: []
}
}
}
}
async function getChannelVideosInvidiousRSS(channel, failedAttempts = 0) {
const playlistId = getChannelPlaylistId(channel.id, 'videos', 'newest')
const feedUrl = `${currentInvidiousInstanceUrl.value}/feed/playlist/${playlistId}`
try {
const response = await invidiousFetch(feedUrl)
if (response.status === 404) {
// playlists don't exist if the channel was terminated but also if it doesn't have the tab,
// so we need to check the channel feed too before deciding it errored, as that only 404s if the channel was terminated
const response2 = await fetch(`${currentInvidiousInstanceUrl.value}/feed/channel/${channel.id}`, {
method: 'GET'
})
if (response2.status === 404) {
errorChannels.value.push(channel)
}
return {
videos: []
}
}
return await parseYouTubeRSSFeed(await response.text(), channel.id)
} catch (error) {
console.error(error)
const errorMessage = t('Invidious API Error (Click to copy)')
showToast(`${errorMessage}: ${error}`, 10000, () => {
copyToClipboard(error)
})
switch (failedAttempts) {
case 0:
return await getChannelVideosInvidiousScraper(channel, failedAttempts + 1)
case 1:
if (process.env.SUPPORTS_LOCAL_API && backendFallback.value) {
showToast(t('Falling back to Local API'))
return await getChannelVideosLocalRSS(channel, failedAttempts + 1)
} else {
return {
videos: []
}
}
case 2:
return await getChannelVideosInvidiousScraper(channel, failedAttempts + 1)
default:
return {
videos: []
}
}
}
}
</script>