Federated video streaming platform using ActivityPub and P2P in the web browser with Angular. https://joinpeertube.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

301 lines
9.1 KiB

  1. import { Subscription } from 'rxjs'
  2. import { HttpEventType, HttpResponse } from '@angular/common/http'
  3. import { Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
  4. import { Router } from '@angular/router'
  5. import { AuthService, CanComponentDeactivate, Notifier, ServerService, UserService } from '@app/core'
  6. import { scrollToTop } from '@app/helpers'
  7. import { FormValidatorService } from '@app/shared/shared-forms'
  8. import { BytesPipe, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main'
  9. import { LoadingBarService } from '@ngx-loading-bar/core'
  10. import { VideoPrivacy } from '@shared/models'
  11. import { VideoSend } from './video-send'
  12. @Component({
  13. selector: 'my-video-upload',
  14. templateUrl: './video-upload.component.html',
  15. styleUrls: [
  16. '../shared/video-edit.component.scss',
  17. './video-upload.component.scss',
  18. './video-send.scss'
  19. ]
  20. })
  21. export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, CanComponentDeactivate {
  22. @Output() firstStepDone = new EventEmitter<string>()
  23. @Output() firstStepError = new EventEmitter<void>()
  24. @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
  25. // So that it can be accessed in the template
  26. readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
  27. userVideoQuotaUsed = 0
  28. userVideoQuotaUsedDaily = 0
  29. isUploadingAudioFile = false
  30. isUploadingVideo = false
  31. isUpdatingVideo = false
  32. videoUploaded = false
  33. videoUploadObservable: Subscription = null
  34. videoUploadPercents = 0
  35. videoUploadedIds = {
  36. id: 0,
  37. uuid: ''
  38. }
  39. waitTranscodingEnabled = true
  40. previewfileUpload: File
  41. error: string
  42. protected readonly DEFAULT_VIDEO_PRIVACY = VideoPrivacy.PUBLIC
  43. constructor (
  44. protected formValidatorService: FormValidatorService,
  45. protected loadingBar: LoadingBarService,
  46. protected notifier: Notifier,
  47. protected authService: AuthService,
  48. protected serverService: ServerService,
  49. protected videoService: VideoService,
  50. protected videoCaptionService: VideoCaptionService,
  51. private userService: UserService,
  52. private router: Router
  53. ) {
  54. super()
  55. }
  56. get videoExtensions () {
  57. return this.serverConfig.video.file.extensions.join(', ')
  58. }
  59. ngOnInit () {
  60. super.ngOnInit()
  61. this.userService.getMyVideoQuotaUsed()
  62. .subscribe(data => {
  63. this.userVideoQuotaUsed = data.videoQuotaUsed
  64. this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
  65. })
  66. }
  67. ngOnDestroy () {
  68. if (this.videoUploadObservable) this.videoUploadObservable.unsubscribe()
  69. }
  70. canDeactivate () {
  71. let text = ''
  72. if (this.videoUploaded === true) {
  73. // FIXME: cannot concatenate strings inside i18n service :/
  74. text = $localize`Your video was uploaded to your account and is private.` + ' ' +
  75. $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
  76. } else {
  77. text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
  78. }
  79. return {
  80. canDeactivate: !this.isUploadingVideo,
  81. text
  82. }
  83. }
  84. getVideoFile () {
  85. return this.videofileInput.nativeElement.files[0]
  86. }
  87. setVideoFile (files: FileList) {
  88. this.videofileInput.nativeElement.files = files
  89. this.fileChange()
  90. }
  91. getAudioUploadLabel () {
  92. const videofile = this.getVideoFile()
  93. if (!videofile) return $localize`Upload`
  94. return $localize`Upload ${videofile.name}`
  95. }
  96. fileChange () {
  97. this.uploadFirstStep()
  98. }
  99. cancelUpload () {
  100. if (this.videoUploadObservable !== null) {
  101. this.videoUploadObservable.unsubscribe()
  102. this.isUploadingVideo = false
  103. this.videoUploadPercents = 0
  104. this.videoUploadObservable = null
  105. this.firstStepError.emit()
  106. this.notifier.info($localize`Upload cancelled`)
  107. }
  108. }
  109. uploadFirstStep (clickedOnButton = false) {
  110. const videofile = this.getVideoFile()
  111. if (!videofile) return
  112. if (!this.checkGlobalUserQuota(videofile)) return
  113. if (!this.checkDailyUserQuota(videofile)) return
  114. if (clickedOnButton === false && this.isAudioFile(videofile.name)) {
  115. this.isUploadingAudioFile = true
  116. return
  117. }
  118. // Build name field
  119. const nameWithoutExtension = videofile.name.replace(/\.[^/.]+$/, '')
  120. let name: string
  121. // If the name of the file is very small, keep the extension
  122. if (nameWithoutExtension.length < 3) name = videofile.name
  123. else name = nameWithoutExtension
  124. // Force user to wait transcoding for unsupported video types in web browsers
  125. if (!videofile.name.endsWith('.mp4') && !videofile.name.endsWith('.webm') && !videofile.name.endsWith('.ogv')) {
  126. this.waitTranscodingEnabled = false
  127. }
  128. const privacy = this.firstStepPrivacyId.toString()
  129. const nsfw = this.serverConfig.instance.isNSFW
  130. const waitTranscoding = true
  131. const commentsEnabled = true
  132. const downloadEnabled = true
  133. const channelId = this.firstStepChannelId.toString()
  134. const formData = new FormData()
  135. formData.append('name', name)
  136. // Put the video "private" -> we are waiting the user validation of the second step
  137. formData.append('privacy', VideoPrivacy.PRIVATE.toString())
  138. formData.append('nsfw', '' + nsfw)
  139. formData.append('commentsEnabled', '' + commentsEnabled)
  140. formData.append('downloadEnabled', '' + downloadEnabled)
  141. formData.append('waitTranscoding', '' + waitTranscoding)
  142. formData.append('channelId', '' + channelId)
  143. formData.append('videofile', videofile)
  144. if (this.previewfileUpload) {
  145. formData.append('previewfile', this.previewfileUpload)
  146. formData.append('thumbnailfile', this.previewfileUpload)
  147. }
  148. this.isUploadingVideo = true
  149. this.firstStepDone.emit(name)
  150. this.form.patchValue({
  151. name,
  152. privacy: this.firstStepPrivacyId,
  153. nsfw,
  154. channelId: this.firstStepChannelId,
  155. previewfile: this.previewfileUpload
  156. })
  157. this.videoUploadObservable = this.videoService.uploadVideo(formData).subscribe(
  158. event => {
  159. if (event.type === HttpEventType.UploadProgress) {
  160. this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
  161. } else if (event instanceof HttpResponse) {
  162. this.videoUploaded = true
  163. this.videoUploadedIds = event.body.video
  164. this.videoUploadObservable = null
  165. }
  166. },
  167. err => {
  168. // Reset progress
  169. this.isUploadingVideo = false
  170. this.videoUploadPercents = 0
  171. this.videoUploadObservable = null
  172. this.firstStepError.emit()
  173. this.notifier.error(err.message)
  174. }
  175. )
  176. }
  177. isPublishingButtonDisabled () {
  178. return !this.form.valid ||
  179. this.isUpdatingVideo === true ||
  180. this.videoUploaded !== true ||
  181. !this.videoUploadedIds.id
  182. }
  183. updateSecondStep () {
  184. if (this.isPublishingButtonDisabled() || !this.checkForm()) {
  185. return
  186. }
  187. const video = new VideoEdit()
  188. video.patch(this.form.value)
  189. video.id = this.videoUploadedIds.id
  190. video.uuid = this.videoUploadedIds.uuid
  191. this.isUpdatingVideo = true
  192. this.updateVideoAndCaptions(video)
  193. .subscribe(
  194. () => {
  195. this.isUpdatingVideo = false
  196. this.isUploadingVideo = false
  197. this.notifier.success($localize`Video published.`)
  198. this.router.navigate([ '/videos/watch', video.uuid ])
  199. },
  200. err => {
  201. this.error = err.message
  202. scrollToTop()
  203. console.error(err)
  204. }
  205. )
  206. }
  207. private checkGlobalUserQuota (videofile: File) {
  208. const bytePipes = new BytesPipe()
  209. // Check global user quota
  210. const videoQuota = this.authService.getUser().videoQuota
  211. if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
  212. const videoSizeBytes = bytePipes.transform(videofile.size, 0)
  213. const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
  214. const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
  215. const msg = $localize`Your video quota is exceeded with this video (
  216. video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
  217. this.notifier.error(msg)
  218. return false
  219. }
  220. return true
  221. }
  222. private checkDailyUserQuota (videofile: File) {
  223. const bytePipes = new BytesPipe()
  224. // Check daily user quota
  225. const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
  226. if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
  227. const videoSizeBytes = bytePipes.transform(videofile.size, 0)
  228. const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
  229. const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
  230. const msg = $localize`Your daily video quota is exceeded with this video (
  231. video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
  232. this.notifier.error(msg)
  233. return false
  234. }
  235. return true
  236. }
  237. private isAudioFile (filename: string) {
  238. const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
  239. return extensions.some(e => filename.endsWith(e))
  240. }
  241. }