1 import { Subscription } from 'rxjs'
2 import { HttpErrorResponse, HttpEventType, HttpResponse } from '@angular/common/http'
3 import { Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
4 import { Router } from '@angular/router'
5 import { AuthService, CanComponentDeactivate, Notifier, ServerService, UserService } from '@app/core'
6 import { scrollToTop, uploadErrorHandler } 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 { VideoPrivacy } from '@shared/models'
11 import { VideoSend } from './video-send'
12 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
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, CanComponentDeactivate {
24 @Output() firstStepDone = new EventEmitter<string>()
25 @Output() firstStepError = new EventEmitter<void>()
26 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
28 // So that it can be accessed in the template
29 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
31 userVideoQuotaUsed = 0
32 userVideoQuotaUsedDaily = 0
34 isUploadingAudioFile = false
35 isUploadingVideo = false
36 isUpdatingVideo = false
39 videoUploadObservable: Subscription = null
40 videoUploadPercents = 0
47 previewfileUpload: File
50 enableRetryAfterError: boolean
52 protected readonly DEFAULT_VIDEO_PRIVACY = VideoPrivacy.PUBLIC
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
68 get videoExtensions () {
69 return this.serverConfig.video.file.extensions.join(', ')
75 this.userService.getMyVideoQuotaUsed()
77 this.userVideoQuotaUsed = data.videoQuotaUsed
78 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
83 if (this.videoUploadObservable) this.videoUploadObservable.unsubscribe()
89 if (this.videoUploaded === true) {
90 // FIXME: cannot concatenate strings using $localize
91 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
92 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
94 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
98 canDeactivate: !this.isUploadingVideo,
104 return this.videofileInput.nativeElement.files[0]
107 setVideoFile (files: FileList) {
108 this.videofileInput.nativeElement.files = files
112 getAudioUploadLabel () {
113 const videofile = this.getVideoFile()
114 if (!videofile) return $localize`Upload`
116 return $localize`Upload ${videofile.name}`
120 this.uploadFirstStep()
124 this.enableRetryAfterError = false
130 if (this.videoUploadObservable !== null) {
131 this.videoUploadObservable.unsubscribe()
134 this.isUploadingVideo = false
135 this.videoUploadPercents = 0
136 this.videoUploadObservable = null
138 this.firstStepError.emit()
139 this.enableRetryAfterError = false
142 this.notifier.info($localize`Upload cancelled`)
145 uploadFirstStep (clickedOnButton = false) {
146 const videofile = this.getVideoFile()
147 if (!videofile) return
149 if (!this.checkGlobalUserQuota(videofile)) return
150 if (!this.checkDailyUserQuota(videofile)) return
152 if (clickedOnButton === false && this.isAudioFile(videofile.name)) {
153 this.isUploadingAudioFile = true
158 const nameWithoutExtension = videofile.name.replace(/\.[^/.]+$/, '')
161 // If the name of the file is very small, keep the extension
162 if (nameWithoutExtension.length < 3) name = videofile.name
163 else name = nameWithoutExtension
165 const nsfw = this.serverConfig.instance.isNSFW
166 const waitTranscoding = true
167 const commentsEnabled = true
168 const downloadEnabled = true
169 const channelId = this.firstStepChannelId.toString()
171 this.formData = new FormData()
172 this.formData.append('name', name)
173 // Put the video "private" -> we are waiting the user validation of the second step
174 this.formData.append('privacy', VideoPrivacy.PRIVATE.toString())
175 this.formData.append('nsfw', '' + nsfw)
176 this.formData.append('commentsEnabled', '' + commentsEnabled)
177 this.formData.append('downloadEnabled', '' + downloadEnabled)
178 this.formData.append('waitTranscoding', '' + waitTranscoding)
179 this.formData.append('channelId', '' + channelId)
180 this.formData.append('videofile', videofile)
182 if (this.previewfileUpload) {
183 this.formData.append('previewfile', this.previewfileUpload)
184 this.formData.append('thumbnailfile', this.previewfileUpload)
187 this.isUploadingVideo = true
188 this.firstStepDone.emit(name)
190 this.form.patchValue({
192 privacy: this.firstStepPrivacyId,
194 channelId: this.firstStepChannelId,
195 previewfile: this.previewfileUpload
202 this.videoUploadObservable = this.videoService.uploadVideo(this.formData).subscribe(
204 if (event.type === HttpEventType.UploadProgress) {
205 this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
206 } else if (event instanceof HttpResponse) {
207 this.videoUploaded = true
209 this.videoUploadedIds = event.body.video
211 this.videoUploadObservable = null
215 (err: HttpErrorResponse) => {
216 // Reset progress (but keep isUploadingVideo true)
217 this.videoUploadPercents = 0
218 this.videoUploadObservable = null
219 this.enableRetryAfterError = true
221 this.error = uploadErrorHandler({
223 name: $localize`video`,
224 notifier: this.notifier,
228 if (err.status === HttpStatusCode.PAYLOAD_TOO_LARGE_413 ||
229 err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
236 isPublishingButtonDisabled () {
237 return !this.form.valid ||
238 this.isUpdatingVideo === true ||
239 this.videoUploaded !== true ||
240 !this.videoUploadedIds.id
243 updateSecondStep () {
244 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
248 const video = new VideoEdit()
249 video.patch(this.form.value)
250 video.id = this.videoUploadedIds.id
251 video.uuid = this.videoUploadedIds.uuid
253 this.isUpdatingVideo = true
255 this.updateVideoAndCaptions(video)
258 this.isUpdatingVideo = false
259 this.isUploadingVideo = false
261 this.notifier.success($localize`Video published.`)
262 this.router.navigate([ '/videos/watch', video.uuid ])
266 this.error = err.message
273 private checkGlobalUserQuota (videofile: File) {
274 const bytePipes = new BytesPipe()
276 // Check global user quota
277 const videoQuota = this.authService.getUser().videoQuota
278 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
279 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
280 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
281 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
283 const msg = $localize`Your video quota is exceeded with this video (
284 video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
285 this.notifier.error(msg)
293 private checkDailyUserQuota (videofile: File) {
294 const bytePipes = new BytesPipe()
296 // Check daily user quota
297 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
298 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
299 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
300 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
301 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
303 const msg = $localize`Your daily video quota is exceeded with this video (
304 video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
305 this.notifier.error(msg)
313 private isAudioFile (filename: string) {
314 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
316 return extensions.some(e => filename.endsWith(e))