video-watch.component.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. import { Hotkey, HotkeysService } from 'angular2-hotkeys'
  2. import { forkJoin, Observable, Subscription } from 'rxjs'
  3. import { catchError } from 'rxjs/operators'
  4. import { PlatformLocation } from '@angular/common'
  5. import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
  6. import { ActivatedRoute, Router } from '@angular/router'
  7. import {
  8. AuthService,
  9. AuthUser,
  10. ConfirmService,
  11. MarkdownService,
  12. Notifier,
  13. PeerTubeSocket,
  14. RestExtractor,
  15. ScreenService,
  16. ServerService,
  17. UserService
  18. } from '@app/core'
  19. import { HooksService } from '@app/core/plugins/hooks.service'
  20. import { RedirectService } from '@app/core/routing/redirect.service'
  21. import { isXPercentInViewport, scrollToTop } from '@app/helpers'
  22. import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
  23. import { VideoShareComponent } from '@app/shared/shared-share-modal'
  24. import { SupportModalComponent } from '@app/shared/shared-support-modal'
  25. import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
  26. import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature'
  27. import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
  28. import { MetaService } from '@ngx-meta/core'
  29. import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
  30. import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
  31. import { ServerConfig, ServerErrorCode, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
  32. import {
  33. cleanupVideoWatch,
  34. getStoredP2PEnabled,
  35. getStoredTheater,
  36. getStoredVideoWatchHistory
  37. } from '../../../assets/player/peertube-player-local-storage'
  38. import {
  39. CustomizationOptions,
  40. P2PMediaLoaderOptions,
  41. PeertubePlayerManager,
  42. PeertubePlayerManagerOptions,
  43. PlayerMode,
  44. videojs
  45. } from '../../../assets/player/peertube-player-manager'
  46. import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
  47. import { environment } from '../../../environments/environment'
  48. import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
  49. type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
  50. @Component({
  51. selector: 'my-video-watch',
  52. templateUrl: './video-watch.component.html',
  53. styleUrls: [ './video-watch.component.scss' ]
  54. })
  55. export class VideoWatchComponent implements OnInit, OnDestroy {
  56. private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
  57. @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
  58. @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
  59. @ViewChild('supportModal') supportModal: SupportModalComponent
  60. @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
  61. @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
  62. player: any
  63. playerElement: HTMLVideoElement
  64. theaterEnabled = false
  65. userRating: UserVideoRateType = null
  66. playerPlaceholderImgSrc: string
  67. video: VideoDetails = null
  68. videoCaptions: VideoCaption[] = []
  69. playlistPosition: number
  70. playlist: VideoPlaylist = null
  71. descriptionLoading = false
  72. completeDescriptionShown = false
  73. completeVideoDescription: string
  74. shortVideoDescription: string
  75. videoHTMLDescription = ''
  76. likesBarTooltipText = ''
  77. hasAlreadyAcceptedPrivacyConcern = false
  78. remoteServerDown = false
  79. hotkeys: Hotkey[] = []
  80. tooltipLike = ''
  81. tooltipDislike = ''
  82. tooltipSupport = ''
  83. tooltipSaveToPlaylist = ''
  84. videoActionsOptions: VideoActionsDisplayType = {
  85. playlist: false,
  86. download: true,
  87. update: true,
  88. blacklist: true,
  89. delete: true,
  90. report: true,
  91. duplicate: true,
  92. mute: true,
  93. liveInfo: true
  94. }
  95. private nextVideoUuid = ''
  96. private nextVideoTitle = ''
  97. private currentTime: number
  98. private paramsSub: Subscription
  99. private queryParamsSub: Subscription
  100. private configSub: Subscription
  101. private liveVideosSub: Subscription
  102. private serverConfig: ServerConfig
  103. constructor (
  104. private elementRef: ElementRef,
  105. private changeDetector: ChangeDetectorRef,
  106. private route: ActivatedRoute,
  107. private router: Router,
  108. private videoService: VideoService,
  109. private playlistService: VideoPlaylistService,
  110. private confirmService: ConfirmService,
  111. private metaService: MetaService,
  112. private authService: AuthService,
  113. private userService: UserService,
  114. private serverService: ServerService,
  115. private restExtractor: RestExtractor,
  116. private notifier: Notifier,
  117. private markdownService: MarkdownService,
  118. private zone: NgZone,
  119. private redirectService: RedirectService,
  120. private videoCaptionService: VideoCaptionService,
  121. private hotkeysService: HotkeysService,
  122. private hooks: HooksService,
  123. private peertubeSocket: PeerTubeSocket,
  124. private screenService: ScreenService,
  125. private location: PlatformLocation,
  126. @Inject(LOCALE_ID) private localeId: string
  127. ) { }
  128. get user () {
  129. return this.authService.getUser()
  130. }
  131. get anonymousUser () {
  132. return this.userService.getAnonymousUser()
  133. }
  134. async ngOnInit () {
  135. // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
  136. if (this.user || !this.screenService.isInMobileView()) {
  137. this.tooltipLike = $localize`Like this video`
  138. this.tooltipDislike = $localize`Dislike this video`
  139. this.tooltipSupport = $localize`Support options for this video`
  140. this.tooltipSaveToPlaylist = $localize`Save to playlist`
  141. }
  142. PeertubePlayerManager.initState()
  143. this.serverConfig = this.serverService.getTmpConfig()
  144. this.configSub = this.serverService.getConfig()
  145. .subscribe(config => {
  146. this.serverConfig = config
  147. if (
  148. isWebRTCDisabled() ||
  149. this.serverConfig.tracker.enabled === false ||
  150. getStoredP2PEnabled() === false ||
  151. peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
  152. ) {
  153. this.hasAlreadyAcceptedPrivacyConcern = true
  154. }
  155. })
  156. this.paramsSub = this.route.params.subscribe(routeParams => {
  157. const videoId = routeParams[ 'videoId' ]
  158. if (videoId) this.loadVideo(videoId)
  159. const playlistId = routeParams[ 'playlistId' ]
  160. if (playlistId) this.loadPlaylist(playlistId)
  161. })
  162. this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
  163. this.playlistPosition = queryParams[ 'playlistPosition' ]
  164. this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
  165. const start = queryParams[ 'start' ]
  166. if (this.player && start) this.player.currentTime(parseInt(start, 10))
  167. })
  168. this.initHotkeys()
  169. this.theaterEnabled = getStoredTheater()
  170. this.hooks.runAction('action:video-watch.init', 'video-watch')
  171. setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
  172. }
  173. ngOnDestroy () {
  174. this.flushPlayer()
  175. // Unsubscribe subscriptions
  176. if (this.paramsSub) this.paramsSub.unsubscribe()
  177. if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
  178. if (this.configSub) this.configSub.unsubscribe()
  179. if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
  180. // Unbind hotkeys
  181. this.hotkeysService.remove(this.hotkeys)
  182. }
  183. setLike () {
  184. if (this.isUserLoggedIn() === false) return
  185. // Already liked this video
  186. if (this.userRating === 'like') this.setRating('none')
  187. else this.setRating('like')
  188. }
  189. setDislike () {
  190. if (this.isUserLoggedIn() === false) return
  191. // Already disliked this video
  192. if (this.userRating === 'dislike') this.setRating('none')
  193. else this.setRating('dislike')
  194. }
  195. getRatePopoverText () {
  196. if (this.isUserLoggedIn()) return undefined
  197. return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
  198. }
  199. showMoreDescription () {
  200. if (this.completeVideoDescription === undefined) {
  201. return this.loadCompleteDescription()
  202. }
  203. this.updateVideoDescription(this.completeVideoDescription)
  204. this.completeDescriptionShown = true
  205. }
  206. showLessDescription () {
  207. this.updateVideoDescription(this.shortVideoDescription)
  208. this.completeDescriptionShown = false
  209. }
  210. showDownloadModal () {
  211. this.videoDownloadModal.show(this.video, this.videoCaptions)
  212. }
  213. isVideoDownloadable () {
  214. return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
  215. }
  216. loadCompleteDescription () {
  217. this.descriptionLoading = true
  218. this.videoService.loadCompleteDescription(this.video.descriptionPath)
  219. .subscribe(
  220. description => {
  221. this.completeDescriptionShown = true
  222. this.descriptionLoading = false
  223. this.shortVideoDescription = this.video.description
  224. this.completeVideoDescription = description
  225. this.updateVideoDescription(this.completeVideoDescription)
  226. },
  227. error => {
  228. this.descriptionLoading = false
  229. this.notifier.error(error.message)
  230. }
  231. )
  232. }
  233. showSupportModal () {
  234. this.supportModal.show()
  235. }
  236. showShareModal () {
  237. this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
  238. }
  239. isUserLoggedIn () {
  240. return this.authService.isLoggedIn()
  241. }
  242. getVideoTags () {
  243. if (!this.video || Array.isArray(this.video.tags) === false) return []
  244. return this.video.tags
  245. }
  246. onRecommendations (videos: Video[]) {
  247. if (videos.length > 0) {
  248. // The recommended videos's first element should be the next video
  249. const video = videos[0]
  250. this.nextVideoUuid = video.uuid
  251. this.nextVideoTitle = video.name
  252. }
  253. }
  254. onVideoRemoved () {
  255. this.redirectService.redirectToHomepage()
  256. }
  257. declinedPrivacyConcern () {
  258. peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
  259. this.hasAlreadyAcceptedPrivacyConcern = false
  260. }
  261. acceptedPrivacyConcern () {
  262. peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
  263. this.hasAlreadyAcceptedPrivacyConcern = true
  264. }
  265. isVideoToTranscode () {
  266. return this.video && this.video.state.id === VideoState.TO_TRANSCODE
  267. }
  268. isVideoToImport () {
  269. return this.video && this.video.state.id === VideoState.TO_IMPORT
  270. }
  271. hasVideoScheduledPublication () {
  272. return this.video && this.video.scheduledUpdate !== undefined
  273. }
  274. isLive () {
  275. return !!(this.video?.isLive)
  276. }
  277. isWaitingForLive () {
  278. return this.video?.state.id === VideoState.WAITING_FOR_LIVE
  279. }
  280. isLiveEnded () {
  281. return this.video?.state.id === VideoState.LIVE_ENDED
  282. }
  283. isVideoBlur (video: Video) {
  284. return video.isVideoNSFWForUser(this.user, this.serverConfig)
  285. }
  286. isAutoPlayEnabled () {
  287. return (
  288. (this.user && this.user.autoPlayNextVideo) ||
  289. this.anonymousUser.autoPlayNextVideo
  290. )
  291. }
  292. handleTimestampClicked (timestamp: number) {
  293. if (!this.player || this.video.isLive) return
  294. this.player.currentTime(timestamp)
  295. scrollToTop()
  296. }
  297. isPlaylistAutoPlayEnabled () {
  298. return (
  299. (this.user && this.user.autoPlayNextVideoPlaylist) ||
  300. this.anonymousUser.autoPlayNextVideoPlaylist
  301. )
  302. }
  303. isChannelDisplayNameGeneric () {
  304. const genericChannelDisplayName = [
  305. `Main ${this.video.channel.ownerAccount.name} channel`,
  306. `Default ${this.video.channel.ownerAccount.name} channel`
  307. ]
  308. return genericChannelDisplayName.includes(this.video.channel.displayName)
  309. }
  310. onPlaylistVideoFound (videoId: string) {
  311. this.loadVideo(videoId)
  312. }
  313. displayOtherVideosAsRow () {
  314. // Use the same value as in the SASS file
  315. return this.screenService.getWindowInnerWidth() <= 1100
  316. }
  317. private loadVideo (videoId: string) {
  318. // Video did not change
  319. if (this.video && this.video.uuid === videoId) return
  320. if (this.player) this.player.pause()
  321. const videoObs = this.hooks.wrapObsFun(
  322. this.videoService.getVideo.bind(this.videoService),
  323. { videoId },
  324. 'video-watch',
  325. 'filter:api.video-watch.video.get.params',
  326. 'filter:api.video-watch.video.get.result'
  327. )
  328. // Video did change
  329. forkJoin([
  330. videoObs,
  331. this.videoCaptionService.listCaptions(videoId)
  332. ])
  333. .pipe(
  334. // If 400, 403 or 404, the video is private or blocked so redirect to 404
  335. catchError(err => {
  336. if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
  337. const search = window.location.search
  338. let originUrl = err.body.originUrl
  339. if (search) originUrl += search
  340. this.confirmService.confirm(
  341. $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
  342. $localize`Redirection`
  343. ).then(res => {
  344. if (res === false) {
  345. return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
  346. HttpStatusCode.BAD_REQUEST_400,
  347. HttpStatusCode.FORBIDDEN_403,
  348. HttpStatusCode.NOT_FOUND_404
  349. ])
  350. }
  351. return window.location.href = originUrl
  352. })
  353. }
  354. return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
  355. HttpStatusCode.BAD_REQUEST_400,
  356. HttpStatusCode.FORBIDDEN_403,
  357. HttpStatusCode.NOT_FOUND_404
  358. ])
  359. })
  360. )
  361. .subscribe(([ video, captionsResult ]) => {
  362. const queryParams = this.route.snapshot.queryParams
  363. const urlOptions = {
  364. resume: queryParams.resume,
  365. startTime: queryParams.start,
  366. stopTime: queryParams.stop,
  367. muted: queryParams.muted,
  368. loop: queryParams.loop,
  369. subtitle: queryParams.subtitle,
  370. playerMode: queryParams.mode,
  371. peertubeLink: false
  372. }
  373. this.onVideoFetched(video, captionsResult.data, urlOptions)
  374. .catch(err => this.handleError(err))
  375. })
  376. }
  377. private loadPlaylist (playlistId: string) {
  378. // Playlist did not change
  379. if (this.playlist && this.playlist.uuid === playlistId) return
  380. this.playlistService.getVideoPlaylist(playlistId)
  381. .pipe(
  382. // If 400 or 403, the video is private or blocked so redirect to 404
  383. catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
  384. HttpStatusCode.BAD_REQUEST_400,
  385. HttpStatusCode.FORBIDDEN_403,
  386. HttpStatusCode.NOT_FOUND_404
  387. ]))
  388. )
  389. .subscribe(playlist => {
  390. this.playlist = playlist
  391. this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
  392. })
  393. }
  394. private updateVideoDescription (description: string) {
  395. this.video.description = description
  396. this.setVideoDescriptionHTML()
  397. .catch(err => console.error(err))
  398. }
  399. private async setVideoDescriptionHTML () {
  400. const html = await this.markdownService.textMarkdownToHTML(this.video.description)
  401. this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
  402. }
  403. private setVideoLikesBarTooltipText () {
  404. this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
  405. }
  406. private handleError (err: any) {
  407. const errorMessage: string = typeof err === 'string' ? err : err.message
  408. if (!errorMessage) return
  409. // Display a message in the video player instead of a notification
  410. if (errorMessage.indexOf('from xs param') !== -1) {
  411. this.flushPlayer()
  412. this.remoteServerDown = true
  413. this.changeDetector.detectChanges()
  414. return
  415. }
  416. this.notifier.error(errorMessage)
  417. }
  418. private checkUserRating () {
  419. // Unlogged users do not have ratings
  420. if (this.isUserLoggedIn() === false) return
  421. this.videoService.getUserVideoRating(this.video.id)
  422. .subscribe(
  423. ratingObject => {
  424. if (ratingObject) {
  425. this.userRating = ratingObject.rating
  426. }
  427. },
  428. err => this.notifier.error(err.message)
  429. )
  430. }
  431. private async onVideoFetched (
  432. video: VideoDetails,
  433. videoCaptions: VideoCaption[],
  434. urlOptions: URLOptions
  435. ) {
  436. this.subscribeToLiveEventsIfNeeded(this.video, video)
  437. this.video = video
  438. this.videoCaptions = videoCaptions
  439. // Re init attributes
  440. this.playerPlaceholderImgSrc = undefined
  441. this.descriptionLoading = false
  442. this.completeDescriptionShown = false
  443. this.completeVideoDescription = undefined
  444. this.remoteServerDown = false
  445. this.currentTime = undefined
  446. if (this.isVideoBlur(this.video)) {
  447. const res = await this.confirmService.confirm(
  448. $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
  449. $localize`Mature or explicit content`
  450. )
  451. if (res === false) return this.location.back()
  452. }
  453. this.buildPlayer(urlOptions)
  454. .catch(err => console.error('Cannot build the player', err))
  455. this.setVideoDescriptionHTML()
  456. this.setVideoLikesBarTooltipText()
  457. this.setOpenGraphTags()
  458. this.checkUserRating()
  459. this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
  460. }
  461. private async buildPlayer (urlOptions: URLOptions) {
  462. // Flush old player if needed
  463. this.flushPlayer()
  464. const videoState = this.video.state.id
  465. if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
  466. this.playerPlaceholderImgSrc = this.video.previewPath
  467. return
  468. }
  469. // Build video element, because videojs removes it on dispose
  470. const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
  471. this.playerElement = document.createElement('video')
  472. this.playerElement.className = 'video-js vjs-peertube-skin'
  473. this.playerElement.setAttribute('playsinline', 'true')
  474. playerElementWrapper.appendChild(this.playerElement)
  475. const params = {
  476. video: this.video,
  477. videoCaptions: this.videoCaptions,
  478. urlOptions,
  479. user: this.user
  480. }
  481. const { playerMode, playerOptions } = await this.hooks.wrapFun(
  482. this.buildPlayerManagerOptions.bind(this),
  483. params,
  484. 'video-watch',
  485. 'filter:internal.video-watch.player.build-options.params',
  486. 'filter:internal.video-watch.player.build-options.result'
  487. )
  488. this.zone.runOutsideAngular(async () => {
  489. this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
  490. this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
  491. this.player.on('timeupdate', () => {
  492. this.currentTime = Math.floor(this.player.currentTime())
  493. })
  494. /**
  495. * replaces this.player.one('ended')
  496. * 'condition()': true to make the upnext functionality trigger,
  497. * false to disable the upnext functionality
  498. * go to the next video in 'condition()' if you don't want of the timer.
  499. * 'next': function triggered at the end of the timer.
  500. * 'suspended': function used at each clic of the timer checking if we need
  501. * to reset progress and wait until 'suspended' becomes truthy again.
  502. */
  503. this.player.upnext({
  504. timeout: 10000, // 10s
  505. headText: $localize`Up Next`,
  506. cancelText: $localize`Cancel`,
  507. suspendedText: $localize`Autoplay is suspended`,
  508. getTitle: () => this.nextVideoTitle,
  509. next: () => this.zone.run(() => this.autoplayNext()),
  510. condition: () => {
  511. if (this.playlist) {
  512. if (this.isPlaylistAutoPlayEnabled()) {
  513. // upnext will not trigger, and instead the next video will play immediately
  514. this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
  515. }
  516. } else if (this.isAutoPlayEnabled()) {
  517. return true // upnext will trigger
  518. }
  519. return false // upnext will not trigger, and instead leave the video stopping
  520. },
  521. suspended: () => {
  522. return (
  523. !isXPercentInViewport(this.player.el(), 80) ||
  524. !document.getElementById('content').contains(document.activeElement)
  525. )
  526. }
  527. })
  528. this.player.one('stopped', () => {
  529. if (this.playlist) {
  530. if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
  531. }
  532. })
  533. this.player.one('ended', () => {
  534. if (this.video.isLive) {
  535. this.video.state.id = VideoState.LIVE_ENDED
  536. }
  537. })
  538. this.player.on('theaterChange', (_: any, enabled: boolean) => {
  539. this.zone.run(() => this.theaterEnabled = enabled)
  540. })
  541. this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
  542. })
  543. }
  544. private autoplayNext () {
  545. if (this.playlist) {
  546. this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
  547. } else if (this.nextVideoUuid) {
  548. this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
  549. }
  550. }
  551. private setRating (nextRating: UserVideoRateType) {
  552. const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
  553. like: this.videoService.setVideoLike,
  554. dislike: this.videoService.setVideoDislike,
  555. none: this.videoService.unsetVideoLike
  556. }
  557. ratingMethods[nextRating].call(this.videoService, this.video.id)
  558. .subscribe(
  559. () => {
  560. // Update the video like attribute
  561. this.updateVideoRating(this.userRating, nextRating)
  562. this.userRating = nextRating
  563. },
  564. (err: { message: string }) => this.notifier.error(err.message)
  565. )
  566. }
  567. private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
  568. let likesToIncrement = 0
  569. let dislikesToIncrement = 0
  570. if (oldRating) {
  571. if (oldRating === 'like') likesToIncrement--
  572. if (oldRating === 'dislike') dislikesToIncrement--
  573. }
  574. if (newRating === 'like') likesToIncrement++
  575. if (newRating === 'dislike') dislikesToIncrement++
  576. this.video.likes += likesToIncrement
  577. this.video.dislikes += dislikesToIncrement
  578. this.video.buildLikeAndDislikePercents()
  579. this.setVideoLikesBarTooltipText()
  580. }
  581. private setOpenGraphTags () {
  582. this.metaService.setTitle(this.video.name)
  583. this.metaService.setTag('og:type', 'video')
  584. this.metaService.setTag('og:title', this.video.name)
  585. this.metaService.setTag('name', this.video.name)
  586. this.metaService.setTag('og:description', this.video.description)
  587. this.metaService.setTag('description', this.video.description)
  588. this.metaService.setTag('og:image', this.video.previewPath)
  589. this.metaService.setTag('og:duration', this.video.duration.toString())
  590. this.metaService.setTag('og:site_name', 'PeerTube')
  591. this.metaService.setTag('og:url', window.location.href)
  592. this.metaService.setTag('url', window.location.href)
  593. }
  594. private isAutoplay () {
  595. // We'll jump to the thread id, so do not play the video
  596. if (this.route.snapshot.params['threadId']) return false
  597. // Otherwise true by default
  598. if (!this.user) return true
  599. // Be sure the autoPlay is set to false
  600. return this.user.autoPlayVideo !== false
  601. }
  602. private flushPlayer () {
  603. // Remove player if it exists
  604. if (this.player) {
  605. try {
  606. this.player.dispose()
  607. this.player = undefined
  608. } catch (err) {
  609. console.error('Cannot dispose player.', err)
  610. }
  611. }
  612. }
  613. private buildPlayerManagerOptions (params: {
  614. video: VideoDetails,
  615. videoCaptions: VideoCaption[],
  616. urlOptions: CustomizationOptions & { playerMode: PlayerMode },
  617. user?: AuthUser
  618. }) {
  619. const { video, videoCaptions, urlOptions, user } = params
  620. const getStartTime = () => {
  621. const byUrl = urlOptions.startTime !== undefined
  622. const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
  623. const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
  624. if (byUrl) return timeToInt(urlOptions.startTime)
  625. if (byHistory) return video.userHistory.currentTime
  626. if (byLocalStorage) return byLocalStorage.duration
  627. return 0
  628. }
  629. let startTime = getStartTime()
  630. // If we are at the end of the video, reset the timer
  631. if (video.duration - startTime <= 1) startTime = 0
  632. const playerCaptions = videoCaptions.map(c => ({
  633. label: c.language.label,
  634. language: c.language.id,
  635. src: environment.apiUrl + c.captionPath
  636. }))
  637. const options: PeertubePlayerManagerOptions = {
  638. common: {
  639. autoplay: this.isAutoplay(),
  640. nextVideo: () => this.zone.run(() => this.autoplayNext()),
  641. playerElement: this.playerElement,
  642. onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
  643. videoDuration: video.duration,
  644. enableHotkeys: true,
  645. inactivityTimeout: 2500,
  646. poster: video.previewUrl,
  647. startTime,
  648. stopTime: urlOptions.stopTime,
  649. controls: urlOptions.controls,
  650. muted: urlOptions.muted,
  651. loop: urlOptions.loop,
  652. subtitle: urlOptions.subtitle,
  653. peertubeLink: urlOptions.peertubeLink,
  654. theaterButton: true,
  655. captions: videoCaptions.length !== 0,
  656. videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
  657. ? this.videoService.getVideoViewUrl(video.uuid)
  658. : null,
  659. embedUrl: video.embedUrl,
  660. embedTitle: video.name,
  661. isLive: video.isLive,
  662. language: this.localeId,
  663. userWatching: user && user.videosHistoryEnabled === true ? {
  664. url: this.videoService.getUserWatchingVideoUrl(video.uuid),
  665. authorizationHeader: this.authService.getRequestHeaderValue()
  666. } : undefined,
  667. serverUrl: environment.apiUrl,
  668. videoCaptions: playerCaptions,
  669. videoUUID: video.uuid
  670. },
  671. webtorrent: {
  672. videoFiles: video.files
  673. }
  674. }
  675. let mode: PlayerMode
  676. if (urlOptions.playerMode) {
  677. if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
  678. else mode = 'webtorrent'
  679. } else {
  680. if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
  681. else mode = 'webtorrent'
  682. }
  683. // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
  684. if (typeof TextEncoder === 'undefined') {
  685. mode = 'webtorrent'
  686. }
  687. if (mode === 'p2p-media-loader') {
  688. const hlsPlaylist = video.getHlsPlaylist()
  689. const p2pMediaLoader = {
  690. playlistUrl: hlsPlaylist.playlistUrl,
  691. segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
  692. redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
  693. trackerAnnounce: video.trackerUrls,
  694. videoFiles: hlsPlaylist.files
  695. } as P2PMediaLoaderOptions
  696. Object.assign(options, { p2pMediaLoader })
  697. }
  698. return { playerMode: mode, playerOptions: options }
  699. }
  700. private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
  701. if (!this.liveVideosSub) {
  702. this.liveVideosSub = this.buildLiveEventsSubscription()
  703. }
  704. if (oldVideo && oldVideo.id !== newVideo.id) {
  705. await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
  706. }
  707. if (!newVideo.isLive) return
  708. await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
  709. }
  710. private buildLiveEventsSubscription () {
  711. return this.peertubeSocket.getLiveVideosObservable()
  712. .subscribe(({ type, payload }) => {
  713. if (type === 'state-change') return this.handleLiveStateChange(payload.state)
  714. if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
  715. })
  716. }
  717. private handleLiveStateChange (newState: VideoState) {
  718. if (newState !== VideoState.PUBLISHED) return
  719. const videoState = this.video.state.id
  720. if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
  721. console.log('Loading video after live update.')
  722. const videoUUID = this.video.uuid
  723. // Reset to refetch the video
  724. this.video = undefined
  725. this.loadVideo(videoUUID)
  726. }
  727. private handleLiveViewsChange (newViews: number) {
  728. if (!this.video) {
  729. console.error('Cannot update video live views because video is no defined.')
  730. return
  731. }
  732. console.log('Updating live views.')
  733. this.video.views = newViews
  734. }
  735. private initHotkeys () {
  736. this.hotkeys = [
  737. // These hotkeys are managed by the player
  738. new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
  739. new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
  740. new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
  741. new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)`),
  742. new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
  743. new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
  744. new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
  745. new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
  746. new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
  747. new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
  748. new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
  749. ]
  750. if (this.isUserLoggedIn()) {
  751. this.hotkeys = this.hotkeys.concat([
  752. new Hotkey('shift+l', () => {
  753. this.setLike()
  754. return false
  755. }, undefined, $localize`Like the video`),
  756. new Hotkey('shift+d', () => {
  757. this.setDislike()
  758. return false
  759. }, undefined, $localize`Dislike the video`),
  760. new Hotkey('shift+s', () => {
  761. this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
  762. return false
  763. }, undefined, $localize`Subscribe to the account`)
  764. ])
  765. }
  766. this.hotkeysService.add(this.hotkeys)
  767. }
  768. }