1 import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { UploadxOptions, UploadState, UploadxService } from 'ngx-uploadx'
4 import { UploaderXFormData } from './uploaderx-form-data'
5 import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService, UserService } from '@app/core'
6 import { scrollToTop, genericUploadErrorHandler } 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 { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
11 import { VideoPrivacy } from '@shared/models'
12 import { VideoSend } from './video-send'
13 import { HttpErrorResponse, HttpEventType, HttpHeaders } from '@angular/common/http'
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
43 previewfileUpload: File
46 enableRetryAfterError: boolean
48 // So that it can be accessed in the template
49 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + 'upload-resumable'
51 private uploadxOptions: UploadxOptions
52 private isUpdatingVideo = false
53 private fileToUpload: File
56 protected formValidatorService: FormValidatorService,
57 protected loadingBar: LoadingBarService,
58 protected notifier: Notifier,
59 protected authService: AuthService,
60 protected serverService: ServerService,
61 protected videoService: VideoService,
62 protected videoCaptionService: VideoCaptionService,
63 private userService: UserService,
64 private router: Router,
65 private hooks: HooksService,
66 private resumableUploadService: UploadxService
70 this.uploadxOptions = {
71 endpoint: this.BASE_VIDEO_UPLOAD_URL,
73 token: this.authService.getAccessToken(),
74 uploaderClass: UploaderXFormData,
77 shouldRetry: (code: number) => {
78 return code < 400 || code >= 501
84 get videoExtensions () {
85 return this.serverConfig.video.file.extensions.join(', ')
88 onUploadVideoOngoing (state: UploadState) {
89 switch (state.status) {
91 const error = state.response?.error || 'Unknow error'
93 this.handleUploadError({
94 error: new Error(error),
95 name: 'HttpErrorResponse',
98 headers: new HttpHeaders(state.responseHeaders),
99 status: +state.responseStatus,
101 type: HttpEventType.Response,
107 this.isUploadingVideo = false
108 this.videoUploadPercents = 0
110 this.firstStepError.emit()
111 this.enableRetryAfterError = false
116 this.closeFirstStep(state.name)
120 this.videoUploadPercents = state.progress
124 this.notifier.info($localize`Upload on hold`)
128 this.videoUploaded = true
129 this.videoUploadPercents = 100
131 this.videoUploadedIds = state?.response.video
139 this.userService.getMyVideoQuotaUsed()
141 this.userVideoQuotaUsed = data.videoQuotaUsed
142 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
145 this.resumableUploadService.events
146 .subscribe(state => this.onUploadVideoOngoing(state))
150 this.hooks.runAction('action:video-upload.init', 'video-edit')
160 if (this.videoUploaded === true) {
161 // FIXME: cannot concatenate strings using $localize
162 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
163 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
165 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
169 canDeactivate: !this.isUploadingVideo,
174 onFileDropped (files: FileList) {
175 this.videofileInput.nativeElement.files = files
177 this.onFileChange({ target: this.videofileInput.nativeElement })
180 onFileChange (event: Event | { target: HTMLInputElement }) {
181 const file = (event.target as HTMLInputElement).files[0]
185 if (!this.checkGlobalUserQuota(file)) return
186 if (!this.checkDailyUserQuota(file)) return
188 if (this.isAudioFile(file.name)) {
189 this.isUploadingAudioFile = true
193 this.isUploadingVideo = true
194 this.fileToUpload = file
196 this.uploadFile(file)
200 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
204 this.enableRetryAfterError = false
206 this.uploadFile(this.fileToUpload)
210 this.resumableUploadService.control({ action: 'cancel' })
213 isPublishingButtonDisabled () {
214 return !this.form.valid ||
215 this.isUpdatingVideo === true ||
216 this.videoUploaded !== true ||
217 !this.videoUploadedIds.id
220 getAudioUploadLabel () {
221 const videofile = this.getInputVideoFile()
222 if (!videofile) return $localize`Upload`
224 return $localize`Upload ${videofile.name}`
227 updateSecondStep () {
228 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
232 const video = new VideoEdit()
233 video.patch(this.form.value)
234 video.id = this.videoUploadedIds.id
235 video.uuid = this.videoUploadedIds.uuid
237 this.isUpdatingVideo = true
239 this.updateVideoAndCaptions(video)
242 this.isUpdatingVideo = false
243 this.isUploadingVideo = false
245 this.notifier.success($localize`Video published.`)
246 this.router.navigate([ '/w', video.uuid ])
250 this.error = err.message
257 private getInputVideoFile () {
258 return this.videofileInput.nativeElement.files[0]
261 private uploadFile (file: File, previewfile?: File) {
263 waitTranscoding: true,
264 commentsEnabled: true,
265 downloadEnabled: true,
266 channelId: this.firstStepChannelId,
267 nsfw: this.serverConfig.instance.isNSFW,
268 privacy: VideoPrivacy.PRIVATE.toString(),
270 previewfile: previewfile as any
273 this.resumableUploadService.handleFiles(file, {
274 ...this.uploadxOptions,
278 this.isUploadingVideo = true
281 private handleUploadError (err: HttpErrorResponse) {
282 // Reset progress (but keep isUploadingVideo true)
283 this.videoUploadPercents = 0
284 this.enableRetryAfterError = true
286 this.error = genericUploadErrorHandler({
288 name: $localize`video`,
289 notifier: this.notifier,
293 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
298 private closeFirstStep (filename: string) {
299 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
300 const name = nameWithoutExtension.length < 3 ? filename : nameWithoutExtension
302 this.form.patchValue({
304 privacy: this.firstStepPrivacyId,
305 nsfw: this.serverConfig.instance.isNSFW,
306 channelId: this.firstStepChannelId,
307 previewfile: this.previewfileUpload
310 this.firstStepDone.emit(name)
313 private checkGlobalUserQuota (videofile: File) {
314 const bytePipes = new BytesPipe()
316 // Check global user quota
317 const videoQuota = this.authService.getUser().videoQuota
318 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
319 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
320 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
321 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
323 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
324 this.notifier.error(msg)
332 private checkDailyUserQuota (videofile: File) {
333 const bytePipes = new BytesPipe()
335 // Check daily user quota
336 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
337 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
338 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
339 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
340 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
341 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
342 this.notifier.error(msg)
350 private isAudioFile (filename: string) {
351 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
353 return extensions.some(e => filename.endsWith(e))