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