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 // So that it can be accessed in the template
48 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + 'upload-resumable'
50 private uploadxOptions: UploadxOptions
51 private isUpdatingVideo = false
52 private fileToUpload: File
55 protected formValidatorService: FormValidatorService,
56 protected loadingBar: LoadingBarService,
57 protected notifier: Notifier,
58 protected authService: AuthService,
59 protected serverService: ServerService,
60 protected videoService: VideoService,
61 protected videoCaptionService: VideoCaptionService,
62 private userService: UserService,
63 private router: Router,
64 private hooks: HooksService,
65 private resumableUploadService: UploadxService
69 this.uploadxOptions = {
70 endpoint: this.BASE_VIDEO_UPLOAD_URL,
72 token: this.authService.getAccessToken(),
73 uploaderClass: UploaderXFormData,
76 shouldRetry: (code: number) => {
77 return code < 400 || code >= 501
83 get videoExtensions () {
84 return this.serverConfig.video.file.extensions.join(', ')
87 onUploadVideoOngoing (state: UploadState) {
88 switch (state.status) {
90 const error = state.response?.error || 'Unknow error'
92 this.handleUploadError({
93 error: new Error(error),
94 name: 'HttpErrorResponse',
97 headers: new HttpHeaders(state.responseHeaders),
98 status: +state.responseStatus,
100 type: HttpEventType.Response,
106 this.isUploadingVideo = false
107 this.videoUploadPercents = 0
109 this.firstStepError.emit()
110 this.enableRetryAfterError = false
115 this.closeFirstStep(state.name)
119 this.videoUploadPercents = state.progress
123 this.notifier.info($localize`Upload on hold`)
127 this.videoUploaded = true
128 this.videoUploadPercents = 100
130 this.videoUploadedIds = state?.response.video
138 this.userService.getMyVideoQuotaUsed()
140 this.userVideoQuotaUsed = data.videoQuotaUsed
141 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
144 this.resumableUploadService.events
145 .subscribe(state => this.onUploadVideoOngoing(state))
149 this.hooks.runAction('action:video-upload.init', 'video-edit')
159 if (this.videoUploaded === true) {
160 // FIXME: cannot concatenate strings using $localize
161 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
162 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
164 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
168 canDeactivate: !this.isUploadingVideo,
173 onFileDropped (files: FileList) {
174 this.videofileInput.nativeElement.files = files
176 this.onFileChange({ target: this.videofileInput.nativeElement })
179 onFileChange (event: Event | { target: HTMLInputElement }) {
180 const file = (event.target as HTMLInputElement).files[0]
184 if (!this.checkGlobalUserQuota(file)) return
185 if (!this.checkDailyUserQuota(file)) return
187 if (this.isAudioFile(file.name)) {
188 this.isUploadingAudioFile = true
192 this.isUploadingVideo = true
193 this.fileToUpload = file
195 this.uploadFile(file)
199 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
203 this.enableRetryAfterError = false
205 this.uploadFile(this.fileToUpload)
209 this.resumableUploadService.control({ action: 'cancel' })
212 isPublishingButtonDisabled () {
213 return !this.form.valid ||
214 this.isUpdatingVideo === true ||
215 this.videoUploaded !== true ||
216 !this.videoUploadedIds.id
219 getAudioUploadLabel () {
220 const videofile = this.getInputVideoFile()
221 if (!videofile) return $localize`Upload`
223 return $localize`Upload ${videofile.name}`
226 updateSecondStep () {
227 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
231 const video = new VideoEdit()
232 video.patch(this.form.value)
233 video.id = this.videoUploadedIds.id
234 video.uuid = this.videoUploadedIds.uuid
236 this.isUpdatingVideo = true
238 this.updateVideoAndCaptions(video)
241 this.isUpdatingVideo = false
242 this.isUploadingVideo = false
244 this.notifier.success($localize`Video published.`)
245 this.router.navigateByUrl(Video.buildWatchUrl(video))
249 this.error = err.message
256 private getInputVideoFile () {
257 return this.videofileInput.nativeElement.files[0]
260 private uploadFile (file: File, previewfile?: File) {
262 waitTranscoding: true,
263 commentsEnabled: true,
264 downloadEnabled: true,
265 channelId: this.firstStepChannelId,
266 nsfw: this.serverConfig.instance.isNSFW,
267 privacy: this.highestPrivacy.toString(),
269 previewfile: previewfile as any
272 this.resumableUploadService.handleFiles(file, {
273 ...this.uploadxOptions,
277 this.isUploadingVideo = true
280 private handleUploadError (err: HttpErrorResponse) {
281 // Reset progress (but keep isUploadingVideo true)
282 this.videoUploadPercents = 0
283 this.enableRetryAfterError = true
285 this.error = genericUploadErrorHandler({
287 name: $localize`video`,
288 notifier: this.notifier,
292 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
297 private closeFirstStep (filename: string) {
298 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
299 const name = nameWithoutExtension.length < 3 ? filename : nameWithoutExtension
301 this.form.patchValue({
303 privacy: this.firstStepPrivacyId,
304 nsfw: this.serverConfig.instance.isNSFW,
305 channelId: this.firstStepChannelId,
306 previewfile: this.previewfileUpload
309 this.firstStepDone.emit(name)
312 private checkGlobalUserQuota (videofile: File) {
313 const bytePipes = new BytesPipe()
315 // Check global user quota
316 const videoQuota = this.authService.getUser().videoQuota
317 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
318 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
319 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
320 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
322 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
323 this.notifier.error(msg)
331 private checkDailyUserQuota (videofile: File) {
332 const bytePipes = new BytesPipe()
334 // Check daily user quota
335 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
336 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
337 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
338 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
339 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
340 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
341 this.notifier.error(msg)
349 private isAudioFile (filename: string) {
350 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
352 return extensions.some(e => filename.endsWith(e))