1 import { truncate } from 'lodash-es'
2 import { UploadState, UploadxOptions, UploadxService } from 'ngx-uploadx'
3 import { HttpErrorResponse, HttpEventType, HttpHeaders } from '@angular/common/http'
4 import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { ActivatedRoute, Router } from '@angular/router'
6 import { AuthService, CanComponentDeactivate, HooksService, MetaService, Notifier, ServerService, UserService } from '@app/core'
7 import { genericUploadErrorHandler, scrollToTop } from '@app/helpers'
8 import { FormReactiveService } from '@app/shared/shared-forms'
9 import { BytesPipe, Video, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main'
10 import { LoadingBarService } from '@ngx-loading-bar/core'
11 import { logger } from '@root-helpers/logger'
12 import { isIOS } from '@root-helpers/web-browser'
13 import { HttpStatusCode, VideoCreateResult } from '@shared/models'
14 import { UploaderXFormData } from './uploaderx-form-data'
15 import { VideoSend } from './video-send'
16 import { Subscription } from 'rxjs'
19 selector: 'my-video-upload',
20 templateUrl: './video-upload.component.html',
22 '../shared/video-edit.component.scss',
23 './video-upload.component.scss',
27 export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {
28 @Output() firstStepDone = new EventEmitter<string>()
29 @Output() firstStepError = new EventEmitter<void>()
30 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
32 userVideoQuotaUsed = 0
33 userVideoQuotaUsedDaily = 0
35 isUploadingAudioFile = false
36 isUploadingVideo = false
39 videoUploadPercents = 0
40 videoUploadedIds: VideoCreateResult = {
47 previewfileUpload: File
50 enableRetryAfterError: boolean
52 // So that it can be accessed in the template
53 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + '/upload-resumable'
55 private isUpdatingVideo = false
56 private fileToUpload: File
58 private alreadyRefreshedToken = false
60 private uploadServiceSubscription: Subscription
63 protected formReactiveService: FormReactiveService,
64 protected loadingBar: LoadingBarService,
65 protected notifier: Notifier,
66 protected authService: AuthService,
67 protected serverService: ServerService,
68 protected videoService: VideoService,
69 protected videoCaptionService: VideoCaptionService,
70 private userService: UserService,
71 private router: Router,
72 private hooks: HooksService,
73 private resumableUploadService: UploadxService,
74 private metaService: MetaService,
75 private route: ActivatedRoute
80 get videoExtensions () {
81 return this.serverConfig.video.file.extensions.join(', ')
87 this.userService.getMyVideoQuotaUsed()
89 this.userVideoQuotaUsed = data.videoQuotaUsed
90 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
93 this.uploadServiceSubscription = this.resumableUploadService.events
94 .subscribe(state => this.onUploadVideoOngoing(state))
98 this.hooks.runAction('action:video-upload.init', 'video-edit')
102 this.resumableUploadService.disconnect()
104 if (this.uploadServiceSubscription) this.uploadServiceSubscription.unsubscribe()
110 if (this.videoUploaded === true) {
111 // We can't concatenate strings using $localize
112 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
113 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
115 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
119 canDeactivate: !this.isUploadingVideo,
125 const videoName = this.form.get('name').value
127 if (this.videoUploaded) {
128 this.metaService.setTitle($localize`Publish ${videoName}`)
129 } else if (this.isUploadingAudioFile || this.isUploadingVideo) {
130 this.metaService.setTitle(`${this.videoUploadPercents}% - ${videoName}`)
132 this.metaService.update(this.route.snapshot.data['meta'])
136 onUploadVideoOngoing (state: UploadState) {
137 switch (state.status) {
139 if (!this.alreadyRefreshedToken && state.responseStatus === HttpStatusCode.UNAUTHORIZED_401) {
140 this.alreadyRefreshedToken = true
142 return this.refereshTokenAndRetryUpload()
145 const error = state.response?.error?.message || state.response?.error || 'Unknown error'
147 this.handleUploadError({
148 error: new Error(error),
149 name: 'HttpErrorResponse',
152 headers: new HttpHeaders(state.responseHeaders),
153 status: +state.responseStatus,
155 type: HttpEventType.Response,
162 this.isUploadingVideo = false
163 this.videoUploadPercents = 0
165 this.firstStepError.emit()
166 this.enableRetryAfterError = false
168 this.isUploadingAudioFile = false
172 this.closeFirstStep(state.name)
176 // TODO: remove || 0 when // https://github.com/kukhariev/ngx-uploadx/pull/368 is released
177 this.videoUploadPercents = state.progress || 0
181 this.notifier.info($localize`Upload on hold`)
185 this.videoUploaded = true
186 this.videoUploadPercents = 100
188 this.videoUploadedIds = state?.response.video
195 onFileDropped (files: FileList) {
196 this.videofileInput.nativeElement.files = files
198 this.onFileChange({ target: this.videofileInput.nativeElement })
201 onFileChange (event: Event | { target: HTMLInputElement }) {
202 const file = (event.target as HTMLInputElement).files[0]
206 if (!this.checkGlobalUserQuota(file)) return
207 if (!this.checkDailyUserQuota(file)) return
209 if (this.isAudioFile(file.name)) {
210 this.isUploadingAudioFile = true
214 this.isUploadingVideo = true
215 this.fileToUpload = file
217 this.uploadFile(file)
221 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
225 this.enableRetryAfterError = false
227 this.uploadFile(this.fileToUpload)
231 this.resumableUploadService.control({ action: 'cancel' })
234 isPublishingButtonDisabled () {
235 return !this.form.valid ||
236 this.isUpdatingVideo === true ||
237 this.videoUploaded !== true ||
238 !this.videoUploadedIds.id
241 getAudioUploadLabel () {
242 const videofile = this.getInputVideoFile()
243 if (!videofile) return $localize`Upload`
245 return $localize`Upload ${videofile.name}`
248 async updateSecondStep () {
249 if (!await this.isFormValid()) return
250 if (this.isPublishingButtonDisabled()) return
252 const video = new VideoEdit()
253 video.patch(this.form.value)
254 video.id = this.videoUploadedIds.id
255 video.uuid = this.videoUploadedIds.uuid
256 video.shortUUID = this.videoUploadedIds.shortUUID
258 this.isUpdatingVideo = true
260 this.updateVideoAndCaptions(video)
263 this.isUpdatingVideo = false
264 this.isUploadingVideo = false
266 this.notifier.success($localize`Video published.`)
267 this.router.navigateByUrl(Video.buildWatchUrl(video))
271 this.error = err.message
278 private getInputVideoFile () {
279 return this.videofileInput.nativeElement.files[0]
282 private uploadFile (file: File, previewfile?: File) {
284 waitTranscoding: true,
285 channelId: this.firstStepChannelId,
286 nsfw: this.serverConfig.instance.isNSFW,
287 privacy: this.highestPrivacy.toString(),
288 name: this.buildVideoFilename(file.name),
290 previewfile: previewfile as any
293 this.resumableUploadService.handleFiles(file, {
294 ...this.getUploadxOptions(),
299 this.isUploadingVideo = true
302 private handleUploadError (err: HttpErrorResponse) {
303 // Reset progress (but keep isUploadingVideo true)
304 this.videoUploadPercents = 0
305 this.enableRetryAfterError = true
307 this.error = genericUploadErrorHandler({
309 name: $localize`video`,
310 notifier: this.notifier,
314 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
319 private closeFirstStep (filename: string) {
320 const name = this.buildVideoFilename(filename)
322 this.form.patchValue({
324 privacy: this.firstStepPrivacyId,
325 nsfw: this.serverConfig.instance.isNSFW,
326 channelId: this.firstStepChannelId,
327 previewfile: this.previewfileUpload
330 this.firstStepDone.emit(name)
334 private checkGlobalUserQuota (videofile: File) {
335 const bytePipes = new BytesPipe()
337 // Check global user quota
338 const videoQuota = this.authService.getUser().videoQuota
339 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
340 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
341 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
342 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
344 // eslint-disable-next-line max-len
345 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
346 this.notifier.error(msg)
354 private checkDailyUserQuota (videofile: File) {
355 const bytePipes = new BytesPipe()
357 // Check daily user quota
358 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
359 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
360 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
361 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
362 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
363 // eslint-disable-next-line max-len
364 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
365 this.notifier.error(msg)
373 private isAudioFile (filename: string) {
374 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
376 return extensions.some(e => filename.endsWith(e))
379 private buildVideoFilename (filename: string) {
380 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
381 let name = nameWithoutExtension.length < 3
383 : nameWithoutExtension
385 const videoNameMaxSize = 110
386 if (name.length > videoNameMaxSize) {
387 name = truncate(name, { length: videoNameMaxSize, omission: '' })
393 private refereshTokenAndRetryUpload () {
394 this.authService.refreshAccessToken()
395 .subscribe(() => this.retryUpload())
398 private getUploadxOptions (): UploadxOptions {
399 // FIXME: https://github.com/Chocobozzz/PeerTube/issues/4382#issuecomment-915854167
400 const chunkSize = isIOS()
402 : undefined // Auto chunk size
405 endpoint: this.BASE_VIDEO_UPLOAD_URL,
408 maxChunkSize: this.serverConfig.client.videos.resumableUpload.maxChunkSize,
411 token: this.authService.getAccessToken(),
413 uploaderClass: UploaderXFormData,
416 maxAttempts: 30, // maximum attempts for 503 codes, otherwise set to 6, see below
417 maxDelay: 120_000, // 2 min
418 shouldRetry: (code: number, attempts: number) => {
419 return code === HttpStatusCode.SERVICE_UNAVAILABLE_503 || ((code < 400 || code > 500) && attempts < 6)