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