1 import { UploadState, UploadxOptions, UploadxService } from 'ngx-uploadx'
2 import { HttpErrorResponse, HttpEventType, HttpHeaders } from '@angular/common/http'
3 import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
4 import { Router } from '@angular/router'
5 import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService, UserService } from '@app/core'
6 import { genericUploadErrorHandler, scrollToTop } from '@app/helpers'
7 import { FormValidatorService } from '@app/shared/shared-forms'
8 import { BytesPipe, Video, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main'
9 import { LoadingBarService } from '@ngx-loading-bar/core'
10 import { HttpStatusCode, VideoCreateResult, VideoPrivacy } from '@shared/models'
11 import { UploaderXFormData } from './uploaderx-form-data'
12 import { VideoSend } from './video-send'
13 import { isIOS } from 'src/assets/player/utils'
16 selector: 'my-video-upload',
17 templateUrl: './video-upload.component.html',
19 '../shared/video-edit.component.scss',
20 './video-upload.component.scss',
24 export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {
25 @Output() firstStepDone = new EventEmitter<string>()
26 @Output() firstStepError = new EventEmitter<void>()
27 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
29 userVideoQuotaUsed = 0
30 userVideoQuotaUsedDaily = 0
32 isUploadingAudioFile = false
33 isUploadingVideo = false
36 videoUploadPercents = 0
37 videoUploadedIds: VideoCreateResult = {
44 previewfileUpload: File
47 enableRetryAfterError: boolean
49 schedulePublicationPossible = false
51 // So that it can be accessed in the template
52 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + 'upload-resumable'
54 private uploadxOptions: UploadxOptions
55 private isUpdatingVideo = false
56 private fileToUpload: File
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
73 // FIXME: https://github.com/Chocobozzz/PeerTube/issues/4382#issuecomment-915854167
74 const chunkSize = isIOS()
76 : undefined // Auto chunk size
78 this.uploadxOptions = {
79 endpoint: this.BASE_VIDEO_UPLOAD_URL,
81 token: this.authService.getAccessToken(),
82 uploaderClass: UploaderXFormData,
85 maxAttempts: 30, // maximum attempts for 503 codes, otherwise set to 6, see below
86 maxDelay: 120_000, // 2 min
87 shouldRetry: (code: number, attempts: number) => {
88 return code === HttpStatusCode.SERVICE_UNAVAILABLE_503 || ((code < 400 || code > 500) && attempts < 6)
94 get videoExtensions () {
95 return this.serverConfig.video.file.extensions.join(', ')
101 this.userService.getMyVideoQuotaUsed()
103 this.userVideoQuotaUsed = data.videoQuotaUsed
104 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
107 this.resumableUploadService.events
108 .subscribe(state => this.onUploadVideoOngoing(state))
110 this.schedulePublicationPossible = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
114 this.hooks.runAction('action:video-upload.init', 'video-edit')
124 if (this.videoUploaded === true) {
125 // We can't concatenate strings using $localize
126 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
127 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
129 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
133 canDeactivate: !this.isUploadingVideo,
138 onUploadVideoOngoing (state: UploadState) {
139 switch (state.status) {
141 const error = state.response?.error || 'Unknow error'
143 this.handleUploadError({
144 error: new Error(error),
145 name: 'HttpErrorResponse',
148 headers: new HttpHeaders(state.responseHeaders),
149 status: +state.responseStatus,
151 type: HttpEventType.Response,
158 this.isUploadingVideo = false
159 this.videoUploadPercents = 0
161 this.firstStepError.emit()
162 this.enableRetryAfterError = false
167 this.closeFirstStep(state.name)
171 this.videoUploadPercents = state.progress
175 this.notifier.info($localize`Upload on hold`)
179 this.videoUploaded = true
180 this.videoUploadPercents = 100
182 this.videoUploadedIds = state?.response.video
187 onFileDropped (files: FileList) {
188 this.videofileInput.nativeElement.files = files
190 this.onFileChange({ target: this.videofileInput.nativeElement })
193 onFileChange (event: Event | { target: HTMLInputElement }) {
194 const file = (event.target as HTMLInputElement).files[0]
198 if (!this.checkGlobalUserQuota(file)) return
199 if (!this.checkDailyUserQuota(file)) return
201 if (this.isAudioFile(file.name)) {
202 this.isUploadingAudioFile = true
206 this.isUploadingVideo = true
207 this.fileToUpload = file
209 this.uploadFile(file)
213 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
217 this.enableRetryAfterError = false
219 this.uploadFile(this.fileToUpload)
223 this.resumableUploadService.control({ action: 'cancel' })
226 isPublishingButtonDisabled () {
227 return !this.form.valid ||
228 this.isUpdatingVideo === true ||
229 this.videoUploaded !== true ||
230 !this.videoUploadedIds.id
233 getAudioUploadLabel () {
234 const videofile = this.getInputVideoFile()
235 if (!videofile) return $localize`Upload`
237 return $localize`Upload ${videofile.name}`
240 updateSecondStep () {
241 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
245 const video = new VideoEdit()
246 video.patch(this.form.value)
247 video.id = this.videoUploadedIds.id
248 video.uuid = this.videoUploadedIds.uuid
249 video.shortUUID = this.videoUploadedIds.shortUUID
251 this.isUpdatingVideo = true
253 this.updateVideoAndCaptions(video)
256 this.isUpdatingVideo = false
257 this.isUploadingVideo = false
259 this.notifier.success($localize`Video published.`)
260 this.router.navigateByUrl(Video.buildWatchUrl(video))
264 this.error = err.message
271 private getInputVideoFile () {
272 return this.videofileInput.nativeElement.files[0]
275 private uploadFile (file: File, previewfile?: File) {
277 waitTranscoding: true,
278 commentsEnabled: true,
279 downloadEnabled: true,
280 channelId: this.firstStepChannelId,
281 nsfw: this.serverConfig.instance.isNSFW,
282 privacy: this.highestPrivacy.toString(),
284 previewfile: previewfile as any
287 this.resumableUploadService.handleFiles(file, {
288 ...this.uploadxOptions,
292 this.isUploadingVideo = true
295 private handleUploadError (err: HttpErrorResponse) {
296 // Reset progress (but keep isUploadingVideo true)
297 this.videoUploadPercents = 0
298 this.enableRetryAfterError = true
300 this.error = genericUploadErrorHandler({
302 name: $localize`video`,
303 notifier: this.notifier,
307 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
312 private closeFirstStep (filename: string) {
313 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
314 const name = nameWithoutExtension.length < 3 ? filename : nameWithoutExtension
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)
327 private checkGlobalUserQuota (videofile: File) {
328 const bytePipes = new BytesPipe()
330 // Check global user quota
331 const videoQuota = this.authService.getUser().videoQuota
332 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
333 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
334 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
335 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
337 // eslint-disable-next-line max-len
338 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
339 this.notifier.error(msg)
347 private checkDailyUserQuota (videofile: File) {
348 const bytePipes = new BytesPipe()
350 // Check daily user quota
351 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
352 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
353 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
354 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
355 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
356 // eslint-disable-next-line max-len
357 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
358 this.notifier.error(msg)
366 private isAudioFile (filename: string) {
367 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
369 return extensions.some(e => filename.endsWith(e))