1 import { truncate } from 'lodash-es'
2 import { UploadState, UploadxOptions, UploadxService } from 'ngx-uploadx'
3 import { isIOS } from '@root-helpers/web-browser'
4 import { HttpErrorResponse, HttpEventType, HttpHeaders } from '@angular/common/http'
5 import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
6 import { ActivatedRoute, Router } from '@angular/router'
7 import { AuthService, CanComponentDeactivate, HooksService, MetaService, Notifier, ServerService, UserService } from '@app/core'
8 import { genericUploadErrorHandler, scrollToTop } from '@app/helpers'
9 import { FormValidatorService } from '@app/shared/shared-forms'
10 import { BytesPipe, Video, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main'
11 import { LoadingBarService } from '@ngx-loading-bar/core'
12 import { HttpStatusCode, VideoCreateResult } from '@shared/models'
13 import { UploaderXFormData } from './uploaderx-form-data'
14 import { VideoSend } from './video-send'
17 selector: 'my-video-upload',
18 templateUrl: './video-upload.component.html',
20 '../shared/video-edit.component.scss',
21 './video-upload.component.scss',
25 export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {
26 @Output() firstStepDone = new EventEmitter<string>()
27 @Output() firstStepError = new EventEmitter<void>()
28 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
30 userVideoQuotaUsed = 0
31 userVideoQuotaUsedDaily = 0
33 isUploadingAudioFile = false
34 isUploadingVideo = false
37 videoUploadPercents = 0
38 videoUploadedIds: VideoCreateResult = {
45 previewfileUpload: File
48 enableRetryAfterError: boolean
50 // So that it can be accessed in the template
51 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + '/upload-resumable'
53 private isUpdatingVideo = false
54 private fileToUpload: File
56 private alreadyRefreshedToken = false
59 protected formValidatorService: FormValidatorService,
60 protected loadingBar: LoadingBarService,
61 protected notifier: Notifier,
62 protected authService: AuthService,
63 protected serverService: ServerService,
64 protected videoService: VideoService,
65 protected videoCaptionService: VideoCaptionService,
66 private userService: UserService,
67 private router: Router,
68 private hooks: HooksService,
69 private resumableUploadService: UploadxService,
70 private metaService: MetaService,
71 private route: ActivatedRoute
76 get videoExtensions () {
77 return this.serverConfig.video.file.extensions.join(', ')
83 this.userService.getMyVideoQuotaUsed()
85 this.userVideoQuotaUsed = data.videoQuotaUsed
86 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
89 this.resumableUploadService.events
90 .subscribe(state => this.onUploadVideoOngoing(state))
94 this.hooks.runAction('action:video-upload.init', 'video-edit')
104 if (this.videoUploaded === true) {
105 // We can't concatenate strings using $localize
106 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
107 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
109 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
113 canDeactivate: !this.isUploadingVideo,
119 const videoName = this.form.get('name').value
121 if (this.videoUploaded) {
122 this.metaService.setTitle($localize`Publish ${videoName}`)
123 } else if (this.isUploadingAudioFile || this.isUploadingVideo) {
124 this.metaService.setTitle(`${this.videoUploadPercents}% - ${videoName}`)
126 this.metaService.update(this.route.snapshot.data['meta'])
130 onUploadVideoOngoing (state: UploadState) {
131 switch (state.status) {
133 if (!this.alreadyRefreshedToken && state.response.status === HttpStatusCode.UNAUTHORIZED_401) {
134 this.alreadyRefreshedToken = true
136 return this.refereshTokenAndRetryUpload()
139 const error = state.response?.error?.message || state.response?.error || 'Unknown error'
141 this.handleUploadError({
142 error: new Error(error),
143 name: 'HttpErrorResponse',
146 headers: new HttpHeaders(state.responseHeaders),
147 status: +state.responseStatus,
149 type: HttpEventType.Response,
156 this.isUploadingVideo = false
157 this.videoUploadPercents = 0
159 this.firstStepError.emit()
160 this.enableRetryAfterError = false
162 this.isUploadingAudioFile = false
166 this.closeFirstStep(state.name)
170 // TODO: remove || 0 when // https://github.com/kukhariev/ngx-uploadx/pull/368 is released
171 this.videoUploadPercents = state.progress || 0
175 this.notifier.info($localize`Upload on hold`)
179 this.videoUploaded = true
180 this.videoUploadPercents = 100
182 this.videoUploadedIds = state?.response.video
189 onFileDropped (files: FileList) {
190 this.videofileInput.nativeElement.files = files
192 this.onFileChange({ target: this.videofileInput.nativeElement })
195 onFileChange (event: Event | { target: HTMLInputElement }) {
196 const file = (event.target as HTMLInputElement).files[0]
200 if (!this.checkGlobalUserQuota(file)) return
201 if (!this.checkDailyUserQuota(file)) return
203 if (this.isAudioFile(file.name)) {
204 this.isUploadingAudioFile = true
208 this.isUploadingVideo = true
209 this.fileToUpload = file
211 this.uploadFile(file)
215 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
219 this.enableRetryAfterError = false
221 this.uploadFile(this.fileToUpload)
225 this.resumableUploadService.control({ action: 'cancel' })
228 isPublishingButtonDisabled () {
229 return !this.form.valid ||
230 this.isUpdatingVideo === true ||
231 this.videoUploaded !== true ||
232 !this.videoUploadedIds.id
235 getAudioUploadLabel () {
236 const videofile = this.getInputVideoFile()
237 if (!videofile) return $localize`Upload`
239 return $localize`Upload ${videofile.name}`
242 async updateSecondStep () {
243 if (!await this.isFormValid()) return
244 if (this.isPublishingButtonDisabled()) return
246 const video = new VideoEdit()
247 video.patch(this.form.value)
248 video.id = this.videoUploadedIds.id
249 video.uuid = this.videoUploadedIds.uuid
250 video.shortUUID = this.videoUploadedIds.shortUUID
252 this.isUpdatingVideo = true
254 this.updateVideoAndCaptions(video)
257 this.isUpdatingVideo = false
258 this.isUploadingVideo = false
260 this.notifier.success($localize`Video published.`)
261 this.router.navigateByUrl(Video.buildWatchUrl(video))
265 this.error = err.message
272 private getInputVideoFile () {
273 return this.videofileInput.nativeElement.files[0]
276 private uploadFile (file: File, previewfile?: File) {
278 waitTranscoding: true,
279 channelId: this.firstStepChannelId,
280 nsfw: this.serverConfig.instance.isNSFW,
281 privacy: this.highestPrivacy.toString(),
282 name: this.buildVideoFilename(file.name),
284 previewfile: previewfile as any
287 this.resumableUploadService.handleFiles(file, {
288 ...this.getUploadxOptions(),
293 this.isUploadingVideo = true
296 private handleUploadError (err: HttpErrorResponse) {
297 // Reset progress (but keep isUploadingVideo true)
298 this.videoUploadPercents = 0
299 this.enableRetryAfterError = true
301 this.error = genericUploadErrorHandler({
303 name: $localize`video`,
304 notifier: this.notifier,
308 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
313 private closeFirstStep (filename: string) {
314 const name = this.buildVideoFilename(filename)
316 this.form.patchValue({
318 privacy: this.firstStepPrivacyId,
319 nsfw: this.serverConfig.instance.isNSFW,
320 channelId: this.firstStepChannelId,
321 previewfile: this.previewfileUpload
324 this.firstStepDone.emit(name)
328 private checkGlobalUserQuota (videofile: File) {
329 const bytePipes = new BytesPipe()
331 // Check global user quota
332 const videoQuota = this.authService.getUser().videoQuota
333 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
334 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
335 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
336 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
338 // eslint-disable-next-line max-len
339 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
340 this.notifier.error(msg)
348 private checkDailyUserQuota (videofile: File) {
349 const bytePipes = new BytesPipe()
351 // Check daily user quota
352 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
353 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
354 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
355 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
356 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
357 // eslint-disable-next-line max-len
358 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
359 this.notifier.error(msg)
367 private isAudioFile (filename: string) {
368 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
370 return extensions.some(e => filename.endsWith(e))
373 private buildVideoFilename (filename: string) {
374 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
375 let name = nameWithoutExtension.length < 3
377 : nameWithoutExtension
379 const videoNameMaxSize = 110
380 if (name.length > videoNameMaxSize) {
381 name = truncate(name, { length: videoNameMaxSize, omission: '' })
387 private refereshTokenAndRetryUpload () {
388 this.authService.refreshAccessToken()
389 .subscribe(() => this.retryUpload())
392 private getUploadxOptions (): UploadxOptions {
393 // FIXME: https://github.com/Chocobozzz/PeerTube/issues/4382#issuecomment-915854167
394 const chunkSize = isIOS()
396 : undefined // Auto chunk size
399 endpoint: this.BASE_VIDEO_UPLOAD_URL,
402 maxChunkSize: this.serverConfig.client.videos.resumableUpload.maxChunkSize,
405 token: this.authService.getAccessToken(),
407 uploaderClass: UploaderXFormData,
410 maxAttempts: 30, // maximum attempts for 503 codes, otherwise set to 6, see below
411 maxDelay: 120_000, // 2 min
412 shouldRetry: (code: number, attempts: number) => {
413 return code === HttpStatusCode.SERVICE_UNAVAILABLE_503 || ((code < 400 || code > 500) && attempts < 6)