1 import { Subscription } from 'rxjs'
2 import { HttpErrorResponse, HttpEventType, HttpResponse } 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 { 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 { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
11 import { VideoPrivacy } from '@shared/models'
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, AfterViewInit, 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,
64 private hooks: HooksService
69 get videoExtensions () {
70 return this.serverConfig.video.file.extensions.join(', ')
76 this.userService.getMyVideoQuotaUsed()
78 this.userVideoQuotaUsed = data.videoQuotaUsed
79 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
84 this.hooks.runAction('action:video-upload.init', 'video-edit')
88 if (this.videoUploadObservable) this.videoUploadObservable.unsubscribe()
94 if (this.videoUploaded === true) {
95 // FIXME: cannot concatenate strings using $localize
96 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
97 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
99 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
103 canDeactivate: !this.isUploadingVideo,
109 return this.videofileInput.nativeElement.files[0]
112 setVideoFile (files: FileList) {
113 this.videofileInput.nativeElement.files = files
117 getAudioUploadLabel () {
118 const videofile = this.getVideoFile()
119 if (!videofile) return $localize`Upload`
121 return $localize`Upload ${videofile.name}`
125 this.uploadFirstStep()
129 this.enableRetryAfterError = false
135 if (this.videoUploadObservable !== null) {
136 this.videoUploadObservable.unsubscribe()
139 this.isUploadingVideo = false
140 this.videoUploadPercents = 0
141 this.videoUploadObservable = null
143 this.firstStepError.emit()
144 this.enableRetryAfterError = false
147 this.notifier.info($localize`Upload cancelled`)
150 uploadFirstStep (clickedOnButton = false) {
151 const videofile = this.getVideoFile()
152 if (!videofile) return
154 if (!this.checkGlobalUserQuota(videofile)) return
155 if (!this.checkDailyUserQuota(videofile)) return
157 if (clickedOnButton === false && this.isAudioFile(videofile.name)) {
158 this.isUploadingAudioFile = true
163 const nameWithoutExtension = videofile.name.replace(/\.[^/.]+$/, '')
166 // If the name of the file is very small, keep the extension
167 if (nameWithoutExtension.length < 3) name = videofile.name
168 else name = nameWithoutExtension
170 const nsfw = this.serverConfig.instance.isNSFW
171 const waitTranscoding = true
172 const commentsEnabled = true
173 const downloadEnabled = true
174 const channelId = this.firstStepChannelId.toString()
176 this.formData = new FormData()
177 this.formData.append('name', name)
178 // Put the video "private" -> we are waiting the user validation of the second step
179 this.formData.append('privacy', VideoPrivacy.PRIVATE.toString())
180 this.formData.append('nsfw', '' + nsfw)
181 this.formData.append('commentsEnabled', '' + commentsEnabled)
182 this.formData.append('downloadEnabled', '' + downloadEnabled)
183 this.formData.append('waitTranscoding', '' + waitTranscoding)
184 this.formData.append('channelId', '' + channelId)
185 this.formData.append('videofile', videofile)
187 if (this.previewfileUpload) {
188 this.formData.append('previewfile', this.previewfileUpload)
189 this.formData.append('thumbnailfile', this.previewfileUpload)
192 this.isUploadingVideo = true
193 this.firstStepDone.emit(name)
195 this.form.patchValue({
197 privacy: this.firstStepPrivacyId,
199 channelId: this.firstStepChannelId,
200 previewfile: this.previewfileUpload
207 this.videoUploadObservable = this.videoService.uploadVideo(this.formData).subscribe(
209 if (event.type === HttpEventType.UploadProgress) {
210 this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
211 } else if (event instanceof HttpResponse) {
212 this.videoUploaded = true
214 this.videoUploadedIds = event.body.video
216 this.videoUploadObservable = null
220 (err: HttpErrorResponse) => {
221 // Reset progress (but keep isUploadingVideo true)
222 this.videoUploadPercents = 0
223 this.videoUploadObservable = null
224 this.enableRetryAfterError = true
226 this.error = uploadErrorHandler({
228 name: $localize`video`,
229 notifier: this.notifier,
233 if (err.status === HttpStatusCode.PAYLOAD_TOO_LARGE_413 ||
234 err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
241 isPublishingButtonDisabled () {
242 return !this.form.valid ||
243 this.isUpdatingVideo === true ||
244 this.videoUploaded !== true ||
245 !this.videoUploadedIds.id
248 updateSecondStep () {
249 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
253 const video = new VideoEdit()
254 video.patch(this.form.value)
255 video.id = this.videoUploadedIds.id
256 video.uuid = this.videoUploadedIds.uuid
258 this.isUpdatingVideo = true
260 this.updateVideoAndCaptions(video)
263 this.isUpdatingVideo = false
264 this.isUploadingVideo = false
266 this.notifier.success($localize`Video published.`)
267 this.router.navigate([ '/videos/watch', video.uuid ])
271 this.error = err.message
278 private checkGlobalUserQuota (videofile: File) {
279 const bytePipes = new BytesPipe()
281 // Check global user quota
282 const videoQuota = this.authService.getUser().videoQuota
283 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
284 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
285 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
286 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
288 const msg = $localize`Your video quota is exceeded with this video (
289 video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
290 this.notifier.error(msg)
298 private checkDailyUserQuota (videofile: File) {
299 const bytePipes = new BytesPipe()
301 // Check daily user quota
302 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
303 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
304 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
305 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
306 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
308 const msg = $localize`Your daily video quota is exceeded with this video (
309 video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
310 this.notifier.error(msg)
318 private isAudioFile (filename: string) {
319 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
321 return extensions.some(e => filename.endsWith(e))