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,
86 shouldRetry: (code: number) => {
87 return code < 400 || code >= 501
93 get videoExtensions () {
94 return this.serverConfig.video.file.extensions.join(', ')
100 this.userService.getMyVideoQuotaUsed()
102 this.userVideoQuotaUsed = data.videoQuotaUsed
103 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
106 this.resumableUploadService.events
107 .subscribe(state => this.onUploadVideoOngoing(state))
109 this.schedulePublicationPossible = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
113 this.hooks.runAction('action:video-upload.init', 'video-edit')
123 if (this.videoUploaded === true) {
124 // FIXME: cannot concatenate strings using $localize
125 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
126 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
128 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
132 canDeactivate: !this.isUploadingVideo,
137 onUploadVideoOngoing (state: UploadState) {
138 switch (state.status) {
140 const error = state.response?.error || 'Unknow error'
142 this.handleUploadError({
143 error: new Error(error),
144 name: 'HttpErrorResponse',
147 headers: new HttpHeaders(state.responseHeaders),
148 status: +state.responseStatus,
150 type: HttpEventType.Response,
157 this.isUploadingVideo = false
158 this.videoUploadPercents = 0
160 this.firstStepError.emit()
161 this.enableRetryAfterError = false
166 this.closeFirstStep(state.name)
170 this.videoUploadPercents = state.progress
174 this.notifier.info($localize`Upload on hold`)
178 this.videoUploaded = true
179 this.videoUploadPercents = 100
181 this.videoUploadedIds = state?.response.video
186 onFileDropped (files: FileList) {
187 this.videofileInput.nativeElement.files = files
189 this.onFileChange({ target: this.videofileInput.nativeElement })
192 onFileChange (event: Event | { target: HTMLInputElement }) {
193 const file = (event.target as HTMLInputElement).files[0]
197 if (!this.checkGlobalUserQuota(file)) return
198 if (!this.checkDailyUserQuota(file)) return
200 if (this.isAudioFile(file.name)) {
201 this.isUploadingAudioFile = true
205 this.isUploadingVideo = true
206 this.fileToUpload = file
208 this.uploadFile(file)
212 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
216 this.enableRetryAfterError = false
218 this.uploadFile(this.fileToUpload)
222 this.resumableUploadService.control({ action: 'cancel' })
225 isPublishingButtonDisabled () {
226 return !this.form.valid ||
227 this.isUpdatingVideo === true ||
228 this.videoUploaded !== true ||
229 !this.videoUploadedIds.id
232 getAudioUploadLabel () {
233 const videofile = this.getInputVideoFile()
234 if (!videofile) return $localize`Upload`
236 return $localize`Upload ${videofile.name}`
239 updateSecondStep () {
240 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
244 const video = new VideoEdit()
245 video.patch(this.form.value)
246 video.id = this.videoUploadedIds.id
247 video.uuid = this.videoUploadedIds.uuid
248 video.shortUUID = this.videoUploadedIds.shortUUID
250 this.isUpdatingVideo = true
252 this.updateVideoAndCaptions(video)
255 this.isUpdatingVideo = false
256 this.isUploadingVideo = false
258 this.notifier.success($localize`Video published.`)
259 this.router.navigateByUrl(Video.buildWatchUrl(video))
263 this.error = err.message
270 private getInputVideoFile () {
271 return this.videofileInput.nativeElement.files[0]
274 private uploadFile (file: File, previewfile?: File) {
276 waitTranscoding: true,
277 commentsEnabled: true,
278 downloadEnabled: true,
279 channelId: this.firstStepChannelId,
280 nsfw: this.serverConfig.instance.isNSFW,
281 privacy: this.highestPrivacy.toString(),
283 previewfile: previewfile as any
286 this.resumableUploadService.handleFiles(file, {
287 ...this.uploadxOptions,
291 this.isUploadingVideo = true
294 private handleUploadError (err: HttpErrorResponse) {
295 // Reset progress (but keep isUploadingVideo true)
296 this.videoUploadPercents = 0
297 this.enableRetryAfterError = true
299 this.error = genericUploadErrorHandler({
301 name: $localize`video`,
302 notifier: this.notifier,
306 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
311 private closeFirstStep (filename: string) {
312 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
313 const name = nameWithoutExtension.length < 3 ? filename : nameWithoutExtension
315 this.form.patchValue({
317 privacy: this.firstStepPrivacyId,
318 nsfw: this.serverConfig.instance.isNSFW,
319 channelId: this.firstStepChannelId,
320 previewfile: this.previewfileUpload
323 this.firstStepDone.emit(name)
326 private checkGlobalUserQuota (videofile: File) {
327 const bytePipes = new BytesPipe()
329 // Check global user quota
330 const videoQuota = this.authService.getUser().videoQuota
331 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
332 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
333 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
334 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
336 // eslint-disable-next-line max-len
337 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
338 this.notifier.error(msg)
346 private checkDailyUserQuota (videofile: File) {
347 const bytePipes = new BytesPipe()
349 // Check daily user quota
350 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
351 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
352 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
353 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
354 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
355 // eslint-disable-next-line max-len
356 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
357 this.notifier.error(msg)
365 private isAudioFile (filename: string) {
366 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
368 return extensions.some(e => filename.endsWith(e))