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