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