forked from FreeTubeApp/FreeTube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWatch.js
1630 lines (1388 loc) · 57.3 KB
/
Watch.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
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
import { defineComponent } from 'vue'
import { mapActions } from 'vuex'
import shaka from 'shaka-player'
import FtLoader from '../../components/ft-loader/ft-loader.vue'
import FtShakaVideoPlayer from '../../components/ft-shaka-video-player/ft-shaka-video-player.vue'
import WatchVideoInfo from '../../components/watch-video-info/watch-video-info.vue'
import WatchVideoChapters from '../../components/WatchVideoChapters/WatchVideoChapters.vue'
import WatchVideoDescription from '../../components/WatchVideoDescription/WatchVideoDescription.vue'
import WatchVideoComments from '../../components/watch-video-comments/watch-video-comments.vue'
import WatchVideoLiveChat from '../../components/watch-video-live-chat/watch-video-live-chat.vue'
import WatchVideoPlaylist from '../../components/watch-video-playlist/watch-video-playlist.vue'
import WatchVideoRecommendations from '../../components/WatchVideoRecommendations/WatchVideoRecommendations.vue'
import FtAgeRestricted from '../../components/ft-age-restricted/ft-age-restricted.vue'
import packageDetails from '../../../../package.json'
import {
buildVTTFileLocally,
copyToClipboard,
formatDurationAsTimestamp,
formatNumber,
showToast
} from '../../helpers/utils'
import {
getLocalVideoInfo,
mapLocalLegacyFormat,
parseLocalSubscriberCount,
parseLocalTextRuns,
parseLocalWatchNextVideo
} from '../../helpers/api/local'
import {
convertInvidiousToLocalFormat,
filterInvidiousFormats,
generateInvidiousDashManifestLocally,
getProxyUrl,
invidiousFetch,
invidiousGetVideoInformation,
mapInvidiousLegacyFormat,
youtubeImageUrlToInvidious
} from '../../helpers/api/invidious'
const MANIFEST_TYPE_DASH = 'application/dash+xml'
const MANIFEST_TYPE_HLS = 'application/x-mpegurl'
export default defineComponent({
name: 'Watch',
components: {
'ft-loader': FtLoader,
'ft-shaka-video-player': FtShakaVideoPlayer,
'watch-video-info': WatchVideoInfo,
'watch-video-chapters': WatchVideoChapters,
'watch-video-description': WatchVideoDescription,
'watch-video-comments': WatchVideoComments,
'watch-video-live-chat': WatchVideoLiveChat,
'watch-video-playlist': WatchVideoPlaylist,
'watch-video-recommendations': WatchVideoRecommendations,
'ft-age-restricted': FtAgeRestricted
},
beforeRouteLeave: async function (to, from, next) {
this.handleRouteChange()
window.removeEventListener('beforeunload', this.handleWatchProgress)
if (this.$refs.player) {
await this.$refs.player.destroyPlayer()
}
next()
},
data: function () {
return {
isLoading: true,
firstLoad: true,
useTheatreMode: false,
videoPlayerLoaded: false,
isFamilyFriendly: false,
isLive: false,
liveChat: null,
isLiveContent: false,
isUpcoming: false,
isPostLiveDvr: false,
upcomingTimestamp: null,
upcomingTimeLeft: null,
/** @type {'dash' | 'audio' | 'legacy'} */
activeFormat: 'legacy',
thumbnail: '',
videoId: '',
videoTitle: '',
videoDescription: '',
videoDescriptionHtml: '',
videoViewCount: 0,
videoLikeCount: 0,
videoDislikeCount: 0,
videoLengthSeconds: 0,
videoChapters: [],
videoCurrentChapterIndex: 0,
channelName: '',
channelThumbnail: '',
channelId: '',
channelSubscriptionCountText: '',
videoPublished: 0,
videoStoryboardSrc: '',
/** @type {string|null} */
manifestSrc: null,
/** @type {(MANIFEST_TYPE_DASH|MANIFEST_TYPE_HLS)} */
manifestMimeType: MANIFEST_TYPE_DASH,
legacyFormats: [],
captions: [],
/** @type {'EQUIRECTANGULAR' | 'EQUIRECTANGULAR_THREED_TOP_BOTTOM' | 'MESH'| null} */
vrProjection: null,
recommendedVideos: [],
downloadLinks: [],
watchingPlaylist: false,
playlistId: '',
playlistType: '',
playlistItemId: null,
/** @type {number|null} */
timestamp: null,
playNextTimeout: null,
playNextCountDownIntervalId: null,
infoAreaSticky: true,
commentsEnabled: true,
onMountedRun: false,
// error handling/messages
/** @type {string|null} */
errorMessage: null,
/** @type {string[]|null} */
customErrorIcon: null,
videoGenreIsMusic: false,
/** @type {Date|null} */
streamingDataExpiryDate: null
}
},
computed: {
historyEntry: function () {
return this.$store.getters.getHistoryCacheById[this.videoId]
},
historyEntryExists: function () {
return typeof this.historyEntry !== 'undefined'
},
rememberHistory: function () {
return this.$store.getters.getRememberHistory
},
saveWatchedProgress: function () {
return this.$store.getters.getSaveWatchedProgress
},
saveVideoHistoryWithLastViewedPlaylist: function () {
return this.$store.getters.getSaveVideoHistoryWithLastViewedPlaylist
},
backendPreference: function () {
return this.$store.getters.getBackendPreference
},
backendFallback: function () {
return this.$store.getters.getBackendFallback
},
currentInvidiousInstanceUrl: function () {
return this.$store.getters.getCurrentInvidiousInstanceUrl
},
proxyVideos: function () {
return this.$store.getters.getProxyVideos
},
defaultInterval: function () {
return this.$store.getters.getDefaultInterval
},
defaultTheatreMode: function () {
return this.$store.getters.getDefaultTheatreMode
},
defaultVideoFormat: function () {
return this.$store.getters.getDefaultVideoFormat
},
thumbnailPreference: function () {
return this.$store.getters.getThumbnailPreference
},
playNextVideo: function () {
return this.$store.getters.getPlayNextVideo
},
autoplayPlaylists: function () {
return this.$store.getters.getAutoplayPlaylists
},
hideRecommendedVideos: function () {
return this.$store.getters.getHideRecommendedVideos
},
hideLiveChat: function () {
return this.$store.getters.getHideLiveChat
},
hideComments: function () {
return this.$store.getters.getHideComments
},
hideVideoDescription: function () {
return this.$store.getters.getHideVideoDescription
},
showFamilyFriendlyOnly: function () {
return this.$store.getters.getShowFamilyFriendlyOnly
},
hideChannelSubscriptions: function () {
return this.$store.getters.getHideChannelSubscriptions
},
hideVideoLikesAndDislikes: function () {
return this.$store.getters.getHideVideoLikesAndDislikes
},
theatrePossible: function () {
return !this.hideRecommendedVideos || (!this.hideLiveChat && this.isLive) || this.watchingPlaylist
},
currentLocale: function () {
return this.$i18n.locale
},
hideChapters: function () {
return this.$store.getters.getHideChapters
},
channelsHidden() {
return JSON.parse(this.$store.getters.getChannelsHidden).map((ch) => {
// Legacy support
if (typeof ch === 'string') {
return { name: ch, preferredName: '', icon: '' }
}
return ch
})
},
forbiddenTitles() {
return JSON.parse(this.$store.getters.getForbiddenTitles)
},
isUserPlaylistRequested: function () {
return this.$route.query.playlistType === 'user'
},
userPlaylistsReady: function () {
return this.$store.getters.getPlaylistsReady
},
selectedUserPlaylist: function () {
if (this.playlistId == null || this.playlistId === '') { return null }
if (!this.isUserPlaylistRequested) { return null }
return this.$store.getters.getPlaylist(this.playlistId)
},
startTimeSeconds: function () {
if (this.isLoading || this.isLive) {
return null
}
if (this.timestamp !== null && this.timestamp < this.videoLengthSeconds) {
return this.timestamp
} else if (this.saveWatchedProgress && this.historyEntryExists) {
// For UX consistency, no progress reading if writing disabled
/** @type {number} */
const watchProgress = this.historyEntry.watchProgress
if (watchProgress > 0 && watchProgress < this.videoLengthSeconds - 2) {
return watchProgress
}
}
return null
}
},
watch: {
async $route() {
this.handleRouteChange()
if (this.$refs.player) {
await this.$refs.player.destroyPlayer()
}
// react to route changes...
this.videoId = this.$route.params.id
this.firstLoad = true
this.videoPlayerLoaded = false
this.errorMessage = null
this.customErrorIcon = null
this.activeFormat = this.defaultVideoFormat
this.videoStoryboardSrc = ''
this.captions = []
this.vrProjection = null
this.downloadLinks = []
this.videoCurrentChapterIndex = 0
this.videoGenreIsMusic = false
this.checkIfTimestamp()
this.checkIfPlaylist()
switch (this.backendPreference) {
case 'local':
this.getVideoInformationLocal(this.videoId)
break
case 'invidious':
this.getVideoInformationInvidious(this.videoId)
break
}
},
userPlaylistsReady() {
this.onMountedDependOnLocalStateLoading()
},
},
created: function () {
this.videoId = this.$route.params.id
this.activeFormat = this.defaultVideoFormat
this.checkIfTimestamp()
},
mounted: function () {
this.onMountedDependOnLocalStateLoading()
},
methods: {
onMountedDependOnLocalStateLoading() {
// Prevent running twice
if (this.onMountedRun) { return }
// Stuff that require user playlists to be ready
if (this.isUserPlaylistRequested && !this.userPlaylistsReady) { return }
this.onMountedRun = true
this.checkIfPlaylist()
// this has to be below checkIfPlaylist() as theatrePossible needs to know if there is a playlist or not
this.useTheatreMode = this.defaultTheatreMode && this.theatrePossible
if (!process.env.SUPPORTS_LOCAL_API || this.backendPreference === 'invidious') {
this.getVideoInformationInvidious()
} else {
this.getVideoInformationLocal()
}
window.addEventListener('beforeunload', this.handleWatchProgress)
},
changeTimestamp: function (timestamp) {
const player = this.$refs.player
if (!this.isLoading && player?.hasLoaded) {
player.setCurrentTime(timestamp)
}
},
getVideoInformationLocal: async function () {
if (this.firstLoad) {
this.isLoading = true
}
try {
const result = await getLocalVideoInfo(this.videoId)
this.isFamilyFriendly = result.basic_info.is_family_safe
const recommendedVideos = result.watch_next_feed
?.filter((item) => item.type === 'CompactVideo' || item.type === 'CompactMovie')
.map(parseLocalWatchNextVideo) ?? []
// place watched recommended videos last
this.recommendedVideos = [
...recommendedVideos.filter((video) => !this.isRecommendedVideoWatched(video.videoId)),
...recommendedVideos.filter((video) => this.isRecommendedVideoWatched(video.videoId))
]
if (this.showFamilyFriendlyOnly && !this.isFamilyFriendly) {
this.isLoading = false
this.handleVideoEnded()
return
}
const playabilityStatus = result.playability_status
// The apostrophe is intentionally that one (char code 8217), because that is the one YouTube uses
const BOT_MESSAGE = 'Sign in to confirm you’re not a bot'
if (playabilityStatus.status === 'UNPLAYABLE' || (playabilityStatus.status === 'LOGIN_REQUIRED' && playabilityStatus.reason === BOT_MESSAGE)) {
if (playabilityStatus.reason === BOT_MESSAGE) {
throw new Error(this.$t('Video.IP block'))
}
let errorText = `[${playabilityStatus.status}] ${playabilityStatus.reason}`
if (playabilityStatus.error_screen) {
errorText += `: ${playabilityStatus.error_screen.subreason.text}`
}
throw new Error(errorText)
}
// extract localised title first and fall back to the not localised one
this.videoTitle = result.primary_info?.title.text ?? result.basic_info.title
this.videoViewCount = result.basic_info.view_count
this.channelId = result.basic_info.channel_id
this.channelName = result.basic_info.author
if (result.secondary_info.owner?.author) {
this.channelThumbnail = result.secondary_info.owner.author.best_thumbnail?.url ?? ''
} else {
this.channelThumbnail = ''
}
this.videoGenreIsMusic = result.basic_info.category === 'Music'
this.updateSubscriptionDetails({
channelThumbnailUrl: this.channelThumbnail.length === 0 ? null : this.channelThumbnail,
channelName: this.channelName,
channelId: this.channelId
})
// `result.page[0].microformat.publish_date` example value: `2023-08-12T08:59:59-07:00`
this.videoPublished = new Date(result.page[0].microformat.publish_date).getTime()
if (result.secondary_info?.description.runs) {
try {
this.videoDescription = parseLocalTextRuns(result.secondary_info.description.runs)
} catch (error) {
console.error('Failed to extract the localised description, falling back to the standard one.', error, JSON.stringify(result.secondary_info.description.runs))
this.videoDescription = result.basic_info.short_description
}
} else {
this.videoDescription = result.basic_info.short_description
}
switch (this.thumbnailPreference) {
case 'start':
this.thumbnail = `https://i.ytimg.com/vi/${this.videoId}/maxres1.jpg`
break
case 'middle':
this.thumbnail = `https://i.ytimg.com/vi/${this.videoId}/maxres2.jpg`
break
case 'end':
this.thumbnail = `https://i.ytimg.com/vi/${this.videoId}/maxres3.jpg`
break
default:
this.thumbnail = result.basic_info.thumbnail[0].url
break
}
if (this.hideVideoLikesAndDislikes) {
this.videoLikeCount = null
this.videoDislikeCount = null
} else {
this.videoLikeCount = isNaN(result.basic_info.like_count) ? 0 : result.basic_info.like_count
// YouTube doesn't return dislikes anymore
this.videoDislikeCount = 0
}
this.isLive = !!result.basic_info.is_live
this.isUpcoming = !!result.basic_info.is_upcoming
this.isLiveContent = !!result.basic_info.is_live_content
this.isPostLiveDvr = !!result.basic_info.is_post_live_dvr
const subCount = !result.secondary_info.owner.subscriber_count.isEmpty() ? parseLocalSubscriberCount(result.secondary_info.owner.subscriber_count.text) : NaN
if (!isNaN(subCount)) {
this.channelSubscriptionCountText = formatNumber(subCount, subCount >= 10000 ? { notation: 'compact' } : undefined)
} else {
this.channelSubscriptionCountText = ''
}
let chapters = []
if (!this.hideChapters) {
const rawChapters = result.player_overlays?.decorated_player_bar?.player_bar?.markers_map?.get({ marker_key: 'DESCRIPTION_CHAPTERS' })?.value.chapters
if (rawChapters) {
for (const chapter of rawChapters) {
const start = chapter.time_range_start_millis / 1000
chapters.push({
title: chapter.title.text,
timestamp: formatDurationAsTimestamp(start),
startSeconds: start,
endSeconds: 0,
thumbnail: chapter.thumbnail[0]
})
}
} else {
chapters = this.extractChaptersFromDescription(result.basic_info.short_description)
}
if (chapters.length > 0) {
this.addChaptersEndSeconds(chapters, result.basic_info.duration)
// prevent vue from adding reactivity which isn't needed
// as the chapter objects are read-only after this anyway
// the chapters are checked for every timeupdate event that the player emits
// this should lessen the performance and memory impact of the chapters
chapters.forEach(Object.freeze)
}
}
this.videoChapters = chapters
if (!this.hideLiveChat && this.isLive && result.livechat) {
this.liveChat = result.getLiveChat()
} else {
this.liveChat = null
}
// region No comment detection
// For videos without any comment (comment disabled?)
// e.g. https://youtu.be/8NBSwDEf8a8
//
// `comments_entry_point_header` is null probably when comment disabled
// e.g. https://youtu.be/8NBSwDEf8a8
// However videos with comments enabled but have no comment
// are different (which is not detected here)
this.commentsEnabled = result.comments_entry_point_header != null
// endregion No comment detection
if ((this.isLive || this.isPostLiveDvr) && !this.isUpcoming) {
let useRemoteManifest = true
if (this.isPostLiveDvr) {
try {
this.manifestSrc = await this.createLocalDashManifest(result, true)
this.manifestMimeType = MANIFEST_TYPE_DASH
useRemoteManifest = false
} catch (error) {
console.error(`Failed to generate DASH manifest for this Post Live DVR video ${this.videoId}, falling back to using YouTube's provided one...`, error)
}
}
if (useRemoteManifest) {
// The live DASH manifest is currently unusable it is not available on the iOS client
// but the web ones returns 403s after 1 minute of playback so we have to use the HLS one for now.
// Leaving the code here commented out in case we can use it again in the future
// if (result.streaming_data.dash_manifest_url) {
// let src = result.streaming_data.dash_manifest_url
// if (src.includes('?')) {
// src += '&mpd_version=7'
// } else {
// src += `${src.endsWith('/') ? '' : '/'}mpd_version/7`
// }
// this.manifestSrc = src
// this.manifestMimeType = MANIFEST_TYPE_DASH
// } else {
this.manifestSrc = result.streaming_data.hls_manifest_url
this.manifestMimeType = MANIFEST_TYPE_HLS
// }
}
this.streamingDataExpiryDate = result.streaming_data.expires
if (this.activeFormat === 'legacy') {
this.activeFormat = 'dash'
}
} else if (this.isUpcoming) {
const upcomingTimestamp = result.basic_info.start_timestamp
if (upcomingTimestamp) {
const timestampOptions = {
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
}
const now = new Date()
if (now.getFullYear() < upcomingTimestamp.getFullYear()) {
Object.defineProperty(timestampOptions, 'year', {
value: 'numeric'
})
}
this.upcomingTimestamp = Intl.DateTimeFormat(this.currentLocale, timestampOptions).format(upcomingTimestamp)
let upcomingTimeLeft = upcomingTimestamp - now
// Convert from ms to second to minute
upcomingTimeLeft = (upcomingTimeLeft / 1000) / 60
let timeUnit = 'minute'
// Youtube switches to showing time left in minutes at 120 minutes remaining
if (upcomingTimeLeft > 120) {
upcomingTimeLeft /= 60
timeUnit = 'hour'
}
if (timeUnit === 'hour' && upcomingTimeLeft > 24) {
upcomingTimeLeft /= 24
timeUnit = 'day'
}
// Value after decimal not to be displayed
// e.g. > 2 days = display as `2 days`
upcomingTimeLeft = Math.floor(upcomingTimeLeft)
// Displays when less than a minute remains
// Looks better than `Premieres in x seconds`
if (upcomingTimeLeft < 1) {
this.upcomingTimeLeft = this.$t('Video.Published.In less than a minute').toLowerCase()
} else {
// TODO a I18n entry for time format might be needed here
this.upcomingTimeLeft = new Intl.RelativeTimeFormat(this.currentLocale).format(upcomingTimeLeft, timeUnit)
}
} else {
this.upcomingTimestamp = null
this.upcomingTimeLeft = null
}
} else {
this.videoLengthSeconds = result.basic_info.duration
if (result.streaming_data) {
this.streamingDataExpiryDate = result.streaming_data.expires
if (result.streaming_data.formats.length > 0) {
this.legacyFormats = result.streaming_data.formats.map(mapLocalLegacyFormat)
}
/** @type {import('../../helpers/api/local').LocalFormat[]} */
const formats = [...result.streaming_data.formats, ...result.streaming_data.adaptive_formats]
const downloadLinks = formats.map((format) => {
const qualityLabel = format.quality_label ?? format.bitrate
const fps = format.fps ? `${format.fps}fps` : 'kbps'
const type = format.mime_type.split(';')[0]
let label = `${qualityLabel} ${fps} - ${type}`
if (format.has_audio !== format.has_video) {
if (format.has_video) {
label += ` ${this.$t('Video.video only')}`
} else {
label += ` ${this.$t('Video.audio only')}`
}
}
return {
url: format.freeTubeUrl,
label: label
}
})
if (result.captions) {
const captionTracks = result.captions?.caption_tracks?.map((caption) => {
const url = new URL(caption.base_url)
url.searchParams.set('fmt', 'vtt')
return {
url: url.toString(),
label: caption.name.text,
language: caption.language_code,
mimeType: 'text/vtt'
}
}) ?? []
if (captionTracks.length > 0) {
const languagesSet = new Set([this.currentLocale, this.currentLocale.split('-')[0]])
// special cases
switch (this.currentLocale) {
case 'nn':
case 'nb-NO':
// according to https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
// "no" is the macro language for "nb" and "nn"
languagesSet.add('no')
break
case 'he':
// according to https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
// "iw" is the old/original code for Hewbrew, these days it's "he"
languagesSet.add('iw')
break
}
if (!captionTracks.some(captionTrack => languagesSet.has(captionTrack.language))) {
const translatedCaptionTrack = this.getTranslatedLocaleCaption(result.captions, languagesSet)
if (translatedCaptionTrack) {
captionTracks.push(translatedCaptionTrack)
}
}
}
this.captions = captionTracks
const captionLinks = captionTracks.map((caption) => {
const label = `${caption.label} (${caption.language}) - text/vtt`
return {
url: caption.url,
label: label
}
})
downloadLinks.push(...captionLinks)
this.downloadLinks = downloadLinks
}
} else {
// video might be region locked or something else. This leads to no formats being available
showToast(
this.$t('This video is unavailable because of missing formats. This can happen due to country unavailability.'),
7000
)
this.handleVideoEnded()
return
}
if (result.streaming_data?.adaptive_formats.length > 0) {
this.vrProjection = result.streaming_data.adaptive_formats
.find(format => {
return format.has_video &&
typeof format.projection_type === 'string' &&
format.projection_type !== 'RECTANGULAR'
})
?.projection_type ?? null
this.manifestSrc = await this.createLocalDashManifest(result)
this.manifestMimeType = MANIFEST_TYPE_DASH
} else {
this.manifestSrc = null
this.enableLegacyFormat()
}
if (result.storyboards?.type === 'PlayerStoryboardSpec') {
let source = result.storyboards.boards
if (window.innerWidth < 500) {
source = source.filter((board) => board.thumbnail_height <= 90)
}
this.videoStoryboardSrc = this.createLocalStoryboardUrls(source.at(-1))
}
}
// this.errorMessage = 'Test error message'
this.isLoading = false
this.updateTitle()
} catch (err) {
const errorMessage = this.$t('Local API Error (Click to copy)')
showToast(`${errorMessage}: ${err}`, 10000, () => {
copyToClipboard(err)
})
console.error(err)
if (this.backendPreference === 'local' && this.backendFallback && !err.toString().includes('private')) {
showToast(this.$t('Falling back to Invidious API'))
this.getVideoInformationInvidious()
} else {
this.isLoading = false
}
}
},
getVideoInformationInvidious: function () {
if (this.firstLoad) {
this.isLoading = true
}
invidiousGetVideoInformation(this.videoId)
.then(async result => {
if (result.error) {
throw new Error(result.error)
}
this.videoTitle = result.title
this.videoViewCount = result.viewCount
this.channelSubscriptionCountText = isNaN(result.subCountText) ? '' : result.subCountText
if (this.hideVideoLikesAndDislikes) {
this.videoLikeCount = null
this.videoDislikeCount = null
} else {
this.videoLikeCount = result.likeCount
this.videoDislikeCount = result.dislikeCount
}
this.videoGenreIsMusic = result.genre === 'Music'
this.channelId = result.authorId
this.channelName = result.author
const channelThumb = result.authorThumbnails[1]
this.channelThumbnail = channelThumb ? youtubeImageUrlToInvidious(channelThumb.url, this.currentInvidiousInstanceUrl) : ''
this.updateSubscriptionDetails({
channelThumbnailUrl: channelThumb?.url,
channelName: result.author,
channelId: result.authorId
})
this.videoPublished = result.published * 1000
this.videoDescriptionHtml = result.descriptionHtml
const recommendedVideos = result.recommendedVideos
// place watched recommended videos last
this.recommendedVideos = [
...recommendedVideos.filter((video) => !this.isRecommendedVideoWatched(video.videoId)),
...recommendedVideos.filter((video) => this.isRecommendedVideoWatched(video.videoId))
]
this.isLive = result.liveNow
this.isFamilyFriendly = result.isFamilyFriendly
this.isPostLiveDvr = !!result.isPostLiveDvr
this.captions = result.captions.map(caption => {
return {
url: this.currentInvidiousInstanceUrl + caption.url,
label: caption.label,
language: caption.language_code,
mimeType: 'text/vtt'
}
})
if (!this.isLive && !this.isPostLiveDvr) {
this.videoStoryboardSrc = `${this.currentInvidiousInstanceUrl}/api/v1/storyboards/${this.videoId}?height=90`
}
switch (this.thumbnailPreference) {
case 'start':
this.thumbnail = `${this.currentInvidiousInstanceUrl}/vi/${this.videoId}/maxres1.jpg`
break
case 'middle':
this.thumbnail = `${this.currentInvidiousInstanceUrl}/vi/${this.videoId}/maxres2.jpg`
break
case 'end':
this.thumbnail = `${this.currentInvidiousInstanceUrl}/vi/${this.videoId}/maxres3.jpg`
break
default:
this.thumbnail = result.videoThumbnails[0].url
break
}
let chapters = []
if (!this.hideChapters) {
chapters = this.extractChaptersFromDescription(result.description)
if (chapters.length > 0) {
this.addChaptersEndSeconds(chapters, result.lengthSeconds)
// prevent vue from adding reactivity which isn't needed
// as the chapter objects are read-only after this anyway
// the chapters are checked for every timeupdate event that the player emits
// this should lessen the performance and memory impact of the chapters
chapters.forEach(Object.freeze)
}
}
this.videoChapters = chapters
if (this.isLive || this.isPostLiveDvr) {
// The live DASH manifest is currently unusable as it returns 403s after 1 minute of playback
// so we have to use the HLS one for now.
// Leaving the code here commented out in case we can use it again in the future
// const url = `${this.currentInvidiousInstanceUrl}/api/manifest/dash/id/${this.videoId}`
// // Proxying doesn't work for live or post live DVR DASH, so use HLS instead
// // https://github.com/iv-org/invidious/pull/4589
// if (this.proxyVideos) {
let hlsManifestUrl = result.hlsUrl
if (this.proxyVideos) {
const url = new URL(hlsManifestUrl)
url.searchParams.set('local', 'true')
hlsManifestUrl = url.toString()
}
this.manifestSrc = hlsManifestUrl
this.manifestMimeType = MANIFEST_TYPE_HLS
// The HLS manifests only contain combined audio+video streams, so we can't do audio only
if (this.activeFormat === 'audio') {
this.activeFormat = 'dash'
}
// } else {
// this.manifestSrc = url
// this.manifestMimeType = MANIFEST_TYPE_DASH
// }
this.legacyFormats = []
if (this.activeFormat === 'legacy') {
this.activeFormat = 'dash'
}
} else {
this.videoLengthSeconds = result.lengthSeconds
// Detect if the Invidious server is running a new enough version of Invidious
// to include this pull request: https://github.com/iv-org/invidious/pull/4586
// which fixed the API returning incorrect height, width and fps information
const trustApiResponse = result.adaptiveFormats.some(stream => typeof stream.size === 'string')
this.legacyFormats = result.formatStreams.map(format => mapInvidiousLegacyFormat(format, trustApiResponse))
if (!process.env.SUPPORTS_LOCAL_API || this.proxyVideos) {
this.legacyFormats.forEach(format => {
format.url = getProxyUrl(format.url)
})
}
this.vrProjection = result.adaptiveFormats
.find(stream => {
return typeof stream.projectionType === 'string' &&
stream.projectionType !== 'RECTANGULAR'
})
?.projectionType ?? null
this.downloadLinks = result.adaptiveFormats.concat(result.formatStreams).map((format) => {
const qualityLabel = format.qualityLabel || format.bitrate
const itag = parseInt(format.itag)
const fps = format.fps ? (format.fps + 'fps') : 'kbps'
const type = format.type.split(';')[0]
let label = `${qualityLabel} ${fps} - ${type}`
if (itag !== 18 && itag !== 22) {
if (type.includes('video')) {
label += ` ${this.$t('Video.video only')}`
} else {
label += ` ${this.$t('Video.audio only')}`
}
}
const object = {
url: format.url,
label: label
}
return object
}).reverse().concat(result.captions.map((caption) => {
const label = `${caption.label} (${caption.languageCode}) - text/vtt`
const object = {
url: caption.url,
label: label
}
return object
}))
this.manifestSrc = await this.createInvidiousDashManifest(result, trustApiResponse)
this.manifestMimeType = MANIFEST_TYPE_DASH
}
this.updateTitle()
this.isLoading = false
})
.catch(err => {
console.error(err)
const errorMessage = this.$t('Invidious API Error (Click to copy)')
showToast(`${errorMessage}: ${err}`, 10000, () => {
copyToClipboard(err)
})
console.error(err)
if (process.env.SUPPORTS_LOCAL_API && this.backendPreference === 'invidious' && this.backendFallback) {
showToast(this.$t('Falling back to Local API'))
this.getVideoInformationLocal()
} else {
this.isLoading = false
}
})
},
/**
* @param {string} description
*/
extractChaptersFromDescription: function (description) {
const chapters = []
// HH:MM:SS Text
// MM:SS Text
// HH:MM:SS - Text // separator is one of '-', '–', '•', '—'
// MM:SS - Text
// HH:MM:SS - HH:MM:SS - Text // end timestamp is ignored, separator is one of '-', '–', '—'
// HH:MM - HH:MM - Text // end timestamp is ignored
const chapterMatches = description.matchAll(/^(?<timestamp>((?<hours>\d+):)?(?<minutes>\d+):(?<seconds>\d+))(\s*[–—-]\s*(?:\d+:){1,2}\d+)?\s+([–—•-]\s*)?(?<title>.+)$/gm)
for (const { groups } of chapterMatches) {
let start = 60 * Number(groups.minutes) + Number(groups.seconds)
if (groups.hours) {
start += 3600 * Number(groups.hours)
}
// replace previous chapter with current one if they have an identical start time
if (chapters.length > 0 && chapters[chapters.length - 1].startSeconds === start) {
chapters.pop()
}
chapters.push({
title: groups.title.trim(),
timestamp: groups.timestamp,
startSeconds: start,
endSeconds: 0
})
}
return chapters
},
addChaptersEndSeconds: function (chapters, videoLengthSeconds) {
for (let i = 0; i < chapters.length - 1; i++) {
chapters[i].endSeconds = chapters[i + 1].startSeconds
}
chapters.at(-1).endSeconds = videoLengthSeconds
},
/**
* @param {number} currentSeconds
*/
updateCurrentChapter: function (currentSeconds) {
const chapters = this.videoChapters
if (this.hideChapters || chapters.length === 0) {
return
}
const currentChapterStart = chapters[this.videoCurrentChapterIndex].startSeconds
if (currentSeconds !== currentChapterStart) {
let i = currentSeconds < currentChapterStart ? 0 : this.videoCurrentChapterIndex
for (; i < chapters.length; i++) {
if (currentSeconds < chapters[i].endSeconds) {
this.videoCurrentChapterIndex = i
break
}
}
}
},