]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts
emit more specific status codes on video upload (#3423)
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / video-add-components / video-upload.component.ts
CommitLineData
67ed6552 1import { Subscription } from 'rxjs'
d4132d3f 2import { HttpErrorResponse, HttpEventType, HttpResponse } from '@angular/common/http'
c199c427 3import { Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
fbad87b0 4import { Router } from '@angular/router'
67ed6552 5import { AuthService, CanComponentDeactivate, Notifier, ServerService, UserService } from '@app/core'
d4132d3f 6import { scrollToTop, uploadErrorHandler } from '@app/helpers'
67ed6552 7import { FormValidatorService } from '@app/shared/shared-forms'
94676e63 8import { BytesPipe, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main'
fbad87b0 9import { LoadingBarService } from '@ngx-loading-bar/core'
67ed6552 10import { VideoPrivacy } from '@shared/models'
1942f11d 11import { VideoSend } from './video-send'
f2eb23cd 12import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
fbad87b0
C
13
14@Component({
15 selector: 'my-video-upload',
16 templateUrl: './video-upload.component.html',
17 styleUrls: [
78848714 18 '../shared/video-edit.component.scss',
457bb213
C
19 './video-upload.component.scss',
20 './video-send.scss'
fbad87b0
C
21 ]
22})
43620009 23export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, CanComponentDeactivate {
fbad87b0 24 @Output() firstStepDone = new EventEmitter<string>()
7373507f 25 @Output() firstStepError = new EventEmitter<void>()
2f5d2ec5 26 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
fbad87b0
C
27
28 // So that it can be accessed in the template
29 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
30
43620009 31 userVideoQuotaUsed = 0
bee0abff 32 userVideoQuotaUsedDaily = 0
43620009 33
7b992a86 34 isUploadingAudioFile = false
fbad87b0
C
35 isUploadingVideo = false
36 isUpdatingVideo = false
7b992a86 37
fbad87b0
C
38 videoUploaded = false
39 videoUploadObservable: Subscription = null
40 videoUploadPercents = 0
41 videoUploadedIds = {
42 id: 0,
43 uuid: ''
44 }
d4132d3f 45 formData: FormData
7b992a86 46
14e2014a 47 waitTranscodingEnabled = true
7b992a86 48 previewfileUpload: File
fbad87b0 49
7373507f 50 error: string
d4132d3f 51 enableRetryAfterError: boolean
fbad87b0 52
43620009 53 protected readonly DEFAULT_VIDEO_PRIVACY = VideoPrivacy.PUBLIC
fbad87b0
C
54
55 constructor (
56 protected formValidatorService: FormValidatorService,
43620009 57 protected loadingBar: LoadingBarService,
f8b2c1b4 58 protected notifier: Notifier,
43620009
C
59 protected authService: AuthService,
60 protected serverService: ServerService,
61 protected videoService: VideoService,
62 protected videoCaptionService: VideoCaptionService,
fbad87b0 63 private userService: UserService,
66357162
C
64 private router: Router
65 ) {
fbad87b0
C
66 super()
67 }
68
69 get videoExtensions () {
758f0d19 70 return this.serverConfig.video.file.extensions.join(', ')
fbad87b0
C
71 }
72
73 ngOnInit () {
43620009 74 super.ngOnInit()
fbad87b0
C
75
76 this.userService.getMyVideoQuotaUsed()
348106f2
C
77 .subscribe(data => {
78 this.userVideoQuotaUsed = data.videoQuotaUsed
79 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
80 })
fbad87b0
C
81 }
82
83 ngOnDestroy () {
43620009 84 if (this.videoUploadObservable) this.videoUploadObservable.unsubscribe()
fbad87b0
C
85 }
86
87 canDeactivate () {
88 let text = ''
89
90 if (this.videoUploaded === true) {
5bfc33b6 91 // FIXME: cannot concatenate strings using $localize
66357162
C
92 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
93 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
fbad87b0 94 } else {
66357162 95 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
fbad87b0
C
96 }
97
98 return {
99 canDeactivate: !this.isUploadingVideo,
100 text
101 }
102 }
103
7b992a86
C
104 getVideoFile () {
105 return this.videofileInput.nativeElement.files[0]
106 }
107
c9ff8a08
RK
108 setVideoFile (files: FileList) {
109 this.videofileInput.nativeElement.files = files
110 this.fileChange()
111 }
112
7b992a86
C
113 getAudioUploadLabel () {
114 const videofile = this.getVideoFile()
66357162 115 if (!videofile) return $localize`Upload`
7b992a86 116
66357162 117 return $localize`Upload ${videofile.name}`
7b992a86
C
118 }
119
fbad87b0
C
120 fileChange () {
121 this.uploadFirstStep()
122 }
123
d4132d3f
RK
124 retryUpload () {
125 this.enableRetryAfterError = false
126 this.error = ''
127 this.uploadVideo()
128 }
129
fbad87b0
C
130 cancelUpload () {
131 if (this.videoUploadObservable !== null) {
132 this.videoUploadObservable.unsubscribe()
f2eb23cd 133 }
e713698f 134
f2eb23cd
RK
135 this.isUploadingVideo = false
136 this.videoUploadPercents = 0
137 this.videoUploadObservable = null
e713698f 138
f2eb23cd
RK
139 this.firstStepError.emit()
140 this.enableRetryAfterError = false
141 this.error = ''
e713698f 142
f2eb23cd 143 this.notifier.info($localize`Upload cancelled`)
fbad87b0
C
144 }
145
7b992a86
C
146 uploadFirstStep (clickedOnButton = false) {
147 const videofile = this.getVideoFile()
fbad87b0
C
148 if (!videofile) return
149
7b992a86
C
150 if (!this.checkGlobalUserQuota(videofile)) return
151 if (!this.checkDailyUserQuota(videofile)) return
fbad87b0 152
7b992a86
C
153 if (clickedOnButton === false && this.isAudioFile(videofile.name)) {
154 this.isUploadingAudioFile = true
bee0abff
FA
155 return
156 }
157
14e2014a 158 // Build name field
fbad87b0
C
159 const nameWithoutExtension = videofile.name.replace(/\.[^/.]+$/, '')
160 let name: string
161
162 // If the name of the file is very small, keep the extension
163 if (nameWithoutExtension.length < 3) name = videofile.name
164 else name = nameWithoutExtension
165
14e2014a
C
166 // Force user to wait transcoding for unsupported video types in web browsers
167 if (!videofile.name.endsWith('.mp4') && !videofile.name.endsWith('.webm') && !videofile.name.endsWith('.ogv')) {
168 this.waitTranscodingEnabled = false
169 }
170
ba430d75 171 const nsfw = this.serverConfig.instance.isNSFW
fbad87b0
C
172 const waitTranscoding = true
173 const commentsEnabled = true
7f2cfe3a 174 const downloadEnabled = true
fbad87b0
C
175 const channelId = this.firstStepChannelId.toString()
176
d4132d3f
RK
177 this.formData = new FormData()
178 this.formData.append('name', name)
fbad87b0 179 // Put the video "private" -> we are waiting the user validation of the second step
d4132d3f
RK
180 this.formData.append('privacy', VideoPrivacy.PRIVATE.toString())
181 this.formData.append('nsfw', '' + nsfw)
182 this.formData.append('commentsEnabled', '' + commentsEnabled)
183 this.formData.append('downloadEnabled', '' + downloadEnabled)
184 this.formData.append('waitTranscoding', '' + waitTranscoding)
185 this.formData.append('channelId', '' + channelId)
186 this.formData.append('videofile', videofile)
fbad87b0 187
7b992a86 188 if (this.previewfileUpload) {
d4132d3f
RK
189 this.formData.append('previewfile', this.previewfileUpload)
190 this.formData.append('thumbnailfile', this.previewfileUpload)
7b992a86
C
191 }
192
fbad87b0
C
193 this.isUploadingVideo = true
194 this.firstStepDone.emit(name)
195
196 this.form.patchValue({
197 name,
30b1e106 198 privacy: this.firstStepPrivacyId,
fbad87b0 199 nsfw,
30b1e106 200 channelId: this.firstStepChannelId,
7b992a86 201 previewfile: this.previewfileUpload
fbad87b0
C
202 })
203
d4132d3f
RK
204 this.uploadVideo()
205 }
206
207 uploadVideo () {
208 this.videoUploadObservable = this.videoService.uploadVideo(this.formData).subscribe(
fbad87b0
C
209 event => {
210 if (event.type === HttpEventType.UploadProgress) {
211 this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
212 } else if (event instanceof HttpResponse) {
213 this.videoUploaded = true
214
215 this.videoUploadedIds = event.body.video
216
217 this.videoUploadObservable = null
218 }
219 },
220
d4132d3f
RK
221 (err: HttpErrorResponse) => {
222 // Reset progress (but keep isUploadingVideo true)
fbad87b0
C
223 this.videoUploadPercents = 0
224 this.videoUploadObservable = null
d4132d3f
RK
225 this.enableRetryAfterError = true
226
227 this.error = uploadErrorHandler({
228 err,
229 name: $localize`video`,
230 notifier: this.notifier,
231 sticky: false
232 })
f2eb23cd
RK
233
234 if (err.status === HttpStatusCode.PAYLOAD_TOO_LARGE_413 ||
235 err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
236 this.cancelUpload()
237 }
fbad87b0
C
238 }
239 )
240 }
241
59c9c5d9
C
242 isPublishingButtonDisabled () {
243 return !this.form.valid ||
244 this.isUpdatingVideo === true ||
c7a53f61
C
245 this.videoUploaded !== true ||
246 !this.videoUploadedIds.id
59c9c5d9
C
247 }
248
fbad87b0 249 updateSecondStep () {
c7a53f61 250 if (this.isPublishingButtonDisabled() || !this.checkForm()) {
fbad87b0
C
251 return
252 }
253
254 const video = new VideoEdit()
255 video.patch(this.form.value)
256 video.id = this.videoUploadedIds.id
257 video.uuid = this.videoUploadedIds.uuid
258
259 this.isUpdatingVideo = true
43620009
C
260
261 this.updateVideoAndCaptions(video)
fbad87b0
C
262 .subscribe(
263 () => {
264 this.isUpdatingVideo = false
265 this.isUploadingVideo = false
fbad87b0 266
66357162 267 this.notifier.success($localize`Video published.`)
fbad87b0
C
268 this.router.navigate([ '/videos/watch', video.uuid ])
269 },
270
271 err => {
7373507f
C
272 this.error = err.message
273 scrollToTop()
fbad87b0
C
274 console.error(err)
275 }
276 )
277 }
7b992a86
C
278
279 private checkGlobalUserQuota (videofile: File) {
280 const bytePipes = new BytesPipe()
281
282 // Check global user quota
283 const videoQuota = this.authService.getUser().videoQuota
284 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
66357162
C
285 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
286 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
287 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
288
289 const msg = $localize`Your video quota is exceeded with this video (
290video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
7b992a86
C
291 this.notifier.error(msg)
292
293 return false
294 }
295
296 return true
297 }
298
299 private checkDailyUserQuota (videofile: File) {
300 const bytePipes = new BytesPipe()
301
302 // Check daily user quota
303 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
304 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
66357162
C
305 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
306 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
307 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
308
309 const msg = $localize`Your daily video quota is exceeded with this video (
310video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
7b992a86
C
311 this.notifier.error(msg)
312
313 return false
314 }
315
316 return true
317 }
318
319 private isAudioFile (filename: string) {
99d362de
C
320 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
321
322 return extensions.some(e => filename.endsWith(e))
7b992a86 323 }
fbad87b0 324}