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