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, VideoPrivacy } from '@shared/models'
11 import { UploaderXFormData } from './uploaderx-form-data'
12 import { VideoSend } from './video-send'
15 selector: 'my-video-upload',
16 templateUrl: './video-upload.component.html',
18 '../shared/video-edit.component.scss',
19 './video-upload.component.scss',
23 export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {
24 @Output() firstStepDone = new EventEmitter<string>()
25 @Output() firstStepError = new EventEmitter<void>()
26 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
28 userVideoQuotaUsed = 0
29 userVideoQuotaUsedDaily = 0
31 isUploadingAudioFile = false
32 isUploadingVideo = false
35 videoUploadPercents = 0
42 previewfileUpload: File
45 enableRetryAfterError: boolean
47 schedulePublicationPossible = false
49 // So that it can be accessed in the template
50 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + 'upload-resumable'
52 private uploadxOptions: UploadxOptions
53 private isUpdatingVideo = false
54 private fileToUpload: File
57 protected formValidatorService: FormValidatorService,
58 protected loadingBar: LoadingBarService,
59 protected notifier: Notifier,
60 protected authService: AuthService,
61 protected serverService: ServerService,
62 protected videoService: VideoService,
63 protected videoCaptionService: VideoCaptionService,
64 private userService: UserService,
65 private router: Router,
66 private hooks: HooksService,
67 private resumableUploadService: UploadxService
71 this.uploadxOptions = {
72 endpoint: this.BASE_VIDEO_UPLOAD_URL,
74 token: this.authService.getAccessToken(),
75 uploaderClass: UploaderXFormData,
78 shouldRetry: (code: number) => {
79 return code < 400 || code >= 501
85 get videoExtensions () {
86 return this.serverConfig.video.file.extensions.join(', ')
92 this.userService.getMyVideoQuotaUsed()
94 this.userVideoQuotaUsed = data.videoQuotaUsed
95 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
98 this.resumableUploadService.events
99 .subscribe(state => this.onUploadVideoOngoing(state))
101 this.schedulePublicationPossible = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
105 this.hooks.runAction('action:video-upload.init', 'video-edit')
115 if (this.videoUploaded === true) {
116 // FIXME: cannot concatenate strings using $localize
117 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
118 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
120 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
124 canDeactivate: !this.isUploadingVideo,
129 onUploadVideoOngoing (state: UploadState) {
130 switch (state.status) {
132 const error = state.response?.error || 'Unknow error'
134 this.handleUploadError({
135 error: new Error(error),
136 name: 'HttpErrorResponse',
139 headers: new HttpHeaders(state.responseHeaders),
140 status: +state.responseStatus,
142 type: HttpEventType.Response,
148 this.isUploadingVideo = false
149 this.videoUploadPercents = 0
151 this.firstStepError.emit()
152 this.enableRetryAfterError = false
157 this.closeFirstStep(state.name)
161 this.videoUploadPercents = state.progress
165 this.notifier.info($localize`Upload on hold`)
169 this.videoUploaded = true
170 this.videoUploadPercents = 100
172 this.videoUploadedIds = state?.response.video
177 onFileDropped (files: FileList) {
178 this.videofileInput.nativeElement.files = files
180 this.onFileChange({ target: this.videofileInput.nativeElement })
183 onFileChange (event: Event | { target: HTMLInputElement }) {
184 const file = (event.target as HTMLInputElement).files[0]
188 if (!this.checkGlobalUserQuota(file)) return
189 if (!this.checkDailyUserQuota(file)) return
191 if (this.isAudioFile(file.name)) {
192 this.isUploadingAudioFile = true
196 this.isUploadingVideo = true
197 this.fileToUpload = file
199 this.uploadFile(file)
203 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
207 this.enableRetryAfterError = false
209 this.uploadFile(this.fileToUpload)
213 this.resumableUploadService.control({ action: 'cancel' })
216 isPublishingButtonDisabled () {
217 return !this.form.valid ||
218 this.isUpdatingVideo === true ||
219 this.videoUploaded !== true ||
220 !this.videoUploadedIds.id
223 getAudioUploadLabel () {
224 const videofile = this.getInputVideoFile()
225 if (!videofile) return $localize`Upload`
227 return $localize`Upload ${videofile.name}`
230 updateSecondStep () {
231 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
235 const video = new VideoEdit()
236 video.patch(this.form.value)
237 video.id = this.videoUploadedIds.id
238 video.uuid = this.videoUploadedIds.uuid
240 this.isUpdatingVideo = true
242 this.updateVideoAndCaptions(video)
245 this.isUpdatingVideo = false
246 this.isUploadingVideo = false
248 this.notifier.success($localize`Video published.`)
249 this.router.navigateByUrl(Video.buildWatchUrl(video))
253 this.error = err.message
260 private getInputVideoFile () {
261 return this.videofileInput.nativeElement.files[0]
264 private uploadFile (file: File, previewfile?: File) {
266 waitTranscoding: true,
267 commentsEnabled: true,
268 downloadEnabled: true,
269 channelId: this.firstStepChannelId,
270 nsfw: this.serverConfig.instance.isNSFW,
271 privacy: this.highestPrivacy.toString(),
273 previewfile: previewfile as any
276 this.resumableUploadService.handleFiles(file, {
277 ...this.uploadxOptions,
281 this.isUploadingVideo = true
284 private handleUploadError (err: HttpErrorResponse) {
285 // Reset progress (but keep isUploadingVideo true)
286 this.videoUploadPercents = 0
287 this.enableRetryAfterError = true
289 this.error = genericUploadErrorHandler({
291 name: $localize`video`,
292 notifier: this.notifier,
296 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
301 private closeFirstStep (filename: string) {
302 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
303 const name = nameWithoutExtension.length < 3 ? filename : nameWithoutExtension
305 this.form.patchValue({
307 privacy: this.firstStepPrivacyId,
308 nsfw: this.serverConfig.instance.isNSFW,
309 channelId: this.firstStepChannelId,
310 previewfile: this.previewfileUpload
313 this.firstStepDone.emit(name)
316 private checkGlobalUserQuota (videofile: File) {
317 const bytePipes = new BytesPipe()
319 // Check global user quota
320 const videoQuota = this.authService.getUser().videoQuota
321 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
322 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
323 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
324 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
326 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
327 this.notifier.error(msg)
335 private checkDailyUserQuota (videofile: File) {
336 const bytePipes = new BytesPipe()
338 // Check daily user quota
339 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
340 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
341 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
342 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
343 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
344 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
345 this.notifier.error(msg)
353 private isAudioFile (filename: string) {
354 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
356 return extensions.some(e => filename.endsWith(e))