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