]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / video-add-components / video-upload.component.ts
1 import { truncate } from 'lodash-es'
2 import { UploadState, UploadxOptions, UploadxService } from 'ngx-uploadx'
3 import { HttpErrorResponse, HttpEventType, HttpHeaders } from '@angular/common/http'
4 import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { ActivatedRoute, Router } from '@angular/router'
6 import { AuthService, CanComponentDeactivate, HooksService, MetaService, Notifier, ServerService, UserService } from '@app/core'
7 import { genericUploadErrorHandler, scrollToTop } from '@app/helpers'
8 import { FormReactiveService } from '@app/shared/shared-forms'
9 import { BytesPipe, Video, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main'
10 import { LoadingBarService } from '@ngx-loading-bar/core'
11 import { logger } from '@root-helpers/logger'
12 import { isIOS } from '@root-helpers/web-browser'
13 import { HttpStatusCode, VideoCreateResult } from '@shared/models'
14 import { UploaderXFormData } from './uploaderx-form-data'
15 import { VideoSend } from './video-send'
16 import { Subscription } from 'rxjs'
17
18 @Component({
19 selector: 'my-video-upload',
20 templateUrl: './video-upload.component.html',
21 styleUrls: [
22 '../shared/video-edit.component.scss',
23 './video-upload.component.scss',
24 './video-send.scss'
25 ]
26 })
27 export class VideoUploadComponent extends VideoSend implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {
28 @Output() firstStepDone = new EventEmitter<string>()
29 @Output() firstStepError = new EventEmitter<void>()
30 @ViewChild('videofileInput') videofileInput: ElementRef<HTMLInputElement>
31
32 userVideoQuotaUsed = 0
33 userVideoQuotaUsedDaily = 0
34
35 isUploadingAudioFile = false
36 isUploadingVideo = false
37
38 videoUploaded = false
39 videoUploadPercents = 0
40 videoUploadedIds: VideoCreateResult = {
41 id: 0,
42 uuid: '',
43 shortUUID: ''
44 }
45 formData: FormData
46
47 previewfileUpload: File
48
49 error: string
50 enableRetryAfterError: boolean
51
52 // So that it can be accessed in the template
53 protected readonly BASE_VIDEO_UPLOAD_URL = VideoService.BASE_VIDEO_URL + '/upload-resumable'
54
55 private isUpdatingVideo = false
56 private fileToUpload: File
57
58 private alreadyRefreshedToken = false
59
60 private uploadServiceSubscription: Subscription
61
62 constructor (
63 protected formReactiveService: FormReactiveService,
64 protected loadingBar: LoadingBarService,
65 protected notifier: Notifier,
66 protected authService: AuthService,
67 protected serverService: ServerService,
68 protected videoService: VideoService,
69 protected videoCaptionService: VideoCaptionService,
70 private userService: UserService,
71 private router: Router,
72 private hooks: HooksService,
73 private resumableUploadService: UploadxService,
74 private metaService: MetaService,
75 private route: ActivatedRoute
76 ) {
77 super()
78 }
79
80 get videoExtensions () {
81 return this.serverConfig.video.file.extensions.join(', ')
82 }
83
84 ngOnInit () {
85 super.ngOnInit()
86
87 this.userService.getMyVideoQuotaUsed()
88 .subscribe(data => {
89 this.userVideoQuotaUsed = data.videoQuotaUsed
90 this.userVideoQuotaUsedDaily = data.videoQuotaUsedDaily
91 })
92
93 this.uploadServiceSubscription = this.resumableUploadService.events
94 .subscribe(state => this.onUploadVideoOngoing(state))
95 }
96
97 ngAfterViewInit () {
98 this.hooks.runAction('action:video-upload.init', 'video-edit')
99 }
100
101 ngOnDestroy () {
102 this.resumableUploadService.disconnect()
103
104 if (this.uploadServiceSubscription) this.uploadServiceSubscription.unsubscribe()
105 }
106
107 canDeactivate () {
108 let text = ''
109
110 if (this.videoUploaded === true) {
111 // We can't concatenate strings using $localize
112 text = $localize`Your video was uploaded to your account and is private.` + ' ' +
113 $localize`But associated data (tags, description...) will be lost, are you sure you want to leave this page?`
114 } else {
115 text = $localize`Your video is not uploaded yet, are you sure you want to leave this page?`
116 }
117
118 return {
119 canDeactivate: !this.isUploadingVideo,
120 text
121 }
122 }
123
124 updateTitle () {
125 const videoName = this.form.get('name').value
126
127 if (this.videoUploaded) {
128 this.metaService.setTitle($localize`Publish ${videoName}`)
129 } else if (this.isUploadingAudioFile || this.isUploadingVideo) {
130 this.metaService.setTitle(`${this.videoUploadPercents}% - ${videoName}`)
131 } else {
132 this.metaService.update(this.route.snapshot.data['meta'])
133 }
134 }
135
136 onUploadVideoOngoing (state: UploadState) {
137 switch (state.status) {
138 case 'error': {
139 if (!this.alreadyRefreshedToken && state.responseStatus === HttpStatusCode.UNAUTHORIZED_401) {
140 this.alreadyRefreshedToken = true
141
142 return this.refereshTokenAndRetryUpload()
143 }
144
145 const error = state.response?.error?.message || state.response?.error || 'Unknown error'
146
147 this.handleUploadError({
148 error: new Error(error),
149 name: 'HttpErrorResponse',
150 message: error,
151 ok: false,
152 headers: new HttpHeaders(state.responseHeaders),
153 status: +state.responseStatus,
154 statusText: error,
155 type: HttpEventType.Response,
156 url: state.url
157 })
158 break
159 }
160
161 case 'cancelled':
162 this.isUploadingVideo = false
163 this.videoUploadPercents = 0
164
165 this.firstStepError.emit()
166 this.enableRetryAfterError = false
167 this.error = ''
168 this.isUploadingAudioFile = false
169 break
170
171 case 'queue':
172 this.closeFirstStep(state.name)
173 break
174
175 case 'uploading':
176 // TODO: remove || 0 when // https://github.com/kukhariev/ngx-uploadx/pull/368 is released
177 this.videoUploadPercents = state.progress || 0
178 break
179
180 case 'paused':
181 this.notifier.info($localize`Upload on hold`)
182 break
183
184 case 'complete':
185 this.videoUploaded = true
186 this.videoUploadPercents = 100
187
188 this.videoUploadedIds = state?.response.video
189 break
190 }
191
192 this.updateTitle()
193 }
194
195 onFileDropped (files: FileList) {
196 this.videofileInput.nativeElement.files = files
197
198 this.onFileChange({ target: this.videofileInput.nativeElement })
199 }
200
201 onFileChange (event: Event | { target: HTMLInputElement }) {
202 const file = (event.target as HTMLInputElement).files[0]
203
204 if (!file) return
205
206 if (!this.checkGlobalUserQuota(file)) return
207 if (!this.checkDailyUserQuota(file)) return
208
209 if (this.isAudioFile(file.name)) {
210 this.isUploadingAudioFile = true
211 return
212 }
213
214 this.isUploadingVideo = true
215 this.fileToUpload = file
216
217 this.uploadFile(file)
218 }
219
220 uploadAudio () {
221 this.uploadFile(this.getInputVideoFile(), this.previewfileUpload)
222 }
223
224 retryUpload () {
225 this.enableRetryAfterError = false
226 this.error = ''
227 this.uploadFile(this.fileToUpload)
228 }
229
230 cancelUpload () {
231 this.resumableUploadService.control({ action: 'cancel' })
232 }
233
234 isPublishingButtonDisabled () {
235 return !this.form.valid ||
236 this.isUpdatingVideo === true ||
237 this.videoUploaded !== true ||
238 !this.videoUploadedIds.id
239 }
240
241 getAudioUploadLabel () {
242 const videofile = this.getInputVideoFile()
243 if (!videofile) return $localize`Upload`
244
245 return $localize`Upload ${videofile.name}`
246 }
247
248 async updateSecondStep () {
249 if (!await this.isFormValid()) return
250 if (this.isPublishingButtonDisabled()) return
251
252 const video = new VideoEdit()
253 video.patch(this.form.value)
254 video.id = this.videoUploadedIds.id
255 video.uuid = this.videoUploadedIds.uuid
256 video.shortUUID = this.videoUploadedIds.shortUUID
257
258 this.isUpdatingVideo = true
259
260 this.updateVideoAndCaptions(video)
261 .subscribe({
262 next: () => {
263 this.isUpdatingVideo = false
264 this.isUploadingVideo = false
265
266 this.notifier.success($localize`Video published.`)
267 this.router.navigateByUrl(Video.buildWatchUrl(video))
268 },
269
270 error: err => {
271 this.error = err.message
272 scrollToTop()
273 logger.error(err)
274 }
275 })
276 }
277
278 private getInputVideoFile () {
279 return this.videofileInput.nativeElement.files[0]
280 }
281
282 private uploadFile (file: File, previewfile?: File) {
283 const metadata = {
284 waitTranscoding: true,
285 channelId: this.firstStepChannelId,
286 nsfw: this.serverConfig.instance.isNSFW,
287 privacy: this.highestPrivacy.toString(),
288 name: this.buildVideoFilename(file.name),
289 filename: file.name,
290 previewfile: previewfile as any
291 }
292
293 this.resumableUploadService.handleFiles(file, {
294 ...this.getUploadxOptions(),
295
296 metadata
297 })
298
299 this.isUploadingVideo = true
300 }
301
302 private handleUploadError (err: HttpErrorResponse) {
303 // Reset progress (but keep isUploadingVideo true)
304 this.videoUploadPercents = 0
305 this.enableRetryAfterError = true
306
307 this.error = genericUploadErrorHandler({
308 err,
309 name: $localize`video`,
310 notifier: this.notifier,
311 sticky: false
312 })
313
314 if (err.status === HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) {
315 this.cancelUpload()
316 }
317 }
318
319 private closeFirstStep (filename: string) {
320 const name = this.buildVideoFilename(filename)
321
322 this.form.patchValue({
323 name,
324 privacy: this.firstStepPrivacyId,
325 nsfw: this.serverConfig.instance.isNSFW,
326 channelId: this.firstStepChannelId,
327 previewfile: this.previewfileUpload
328 })
329
330 this.firstStepDone.emit(name)
331 this.updateTitle()
332 }
333
334 private checkGlobalUserQuota (videofile: File) {
335 const bytePipes = new BytesPipe()
336
337 // Check global user quota
338 const videoQuota = this.authService.getUser().videoQuota
339 if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
340 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
341 const videoQuotaUsedBytes = bytePipes.transform(this.userVideoQuotaUsed, 0)
342 const videoQuotaBytes = bytePipes.transform(videoQuota, 0)
343
344 // eslint-disable-next-line max-len
345 const msg = $localize`Your video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${videoQuotaUsedBytes}, quota: ${videoQuotaBytes})`
346 this.notifier.error(msg)
347
348 return false
349 }
350
351 return true
352 }
353
354 private checkDailyUserQuota (videofile: File) {
355 const bytePipes = new BytesPipe()
356
357 // Check daily user quota
358 const videoQuotaDaily = this.authService.getUser().videoQuotaDaily
359 if (videoQuotaDaily !== -1 && (this.userVideoQuotaUsedDaily + videofile.size) > videoQuotaDaily) {
360 const videoSizeBytes = bytePipes.transform(videofile.size, 0)
361 const quotaUsedDailyBytes = bytePipes.transform(this.userVideoQuotaUsedDaily, 0)
362 const quotaDailyBytes = bytePipes.transform(videoQuotaDaily, 0)
363 // eslint-disable-next-line max-len
364 const msg = $localize`Your daily video quota is exceeded with this video (video size: ${videoSizeBytes}, used: ${quotaUsedDailyBytes}, quota: ${quotaDailyBytes})`
365 this.notifier.error(msg)
366
367 return false
368 }
369
370 return true
371 }
372
373 private isAudioFile (filename: string) {
374 const extensions = [ '.mp3', '.flac', '.ogg', '.wma', '.wav' ]
375
376 return extensions.some(e => filename.endsWith(e))
377 }
378
379 private buildVideoFilename (filename: string) {
380 const nameWithoutExtension = filename.replace(/\.[^/.]+$/, '')
381 let name = nameWithoutExtension.length < 3
382 ? filename
383 : nameWithoutExtension
384
385 const videoNameMaxSize = 110
386 if (name.length > videoNameMaxSize) {
387 name = truncate(name, { length: videoNameMaxSize, omission: '' })
388 }
389
390 return name
391 }
392
393 private refereshTokenAndRetryUpload () {
394 this.authService.refreshAccessToken()
395 .subscribe(() => this.retryUpload())
396 }
397
398 private getUploadxOptions (): UploadxOptions {
399 // FIXME: https://github.com/Chocobozzz/PeerTube/issues/4382#issuecomment-915854167
400 const chunkSize = isIOS()
401 ? 0
402 : undefined // Auto chunk size
403
404 return {
405 endpoint: this.BASE_VIDEO_UPLOAD_URL,
406 multiple: false,
407
408 maxChunkSize: this.serverConfig.client.videos.resumableUpload.maxChunkSize,
409 chunkSize,
410
411 token: this.authService.getAccessToken(),
412
413 uploaderClass: UploaderXFormData,
414
415 retryConfig: {
416 maxAttempts: 30, // maximum attempts for 503 codes, otherwise set to 6, see below
417 maxDelay: 120_000, // 2 min
418 shouldRetry: (code: number, attempts: number) => {
419 return code === HttpStatusCode.SERVICE_UNAVAILABLE_503 || ((code < 400 || code > 500) && attempts < 6)
420 }
421 }
422 }
423 }
424 }