Implement captions/subtitles
[oweals/peertube.git] / client / src / app / videos / +video-edit / video-add.component.ts
1 import { HttpEventType, HttpResponse } from '@angular/common/http'
2 import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { Router } from '@angular/router'
4 import { UserService } from '@app/shared'
5 import { CanComponentDeactivate } from '@app/shared/guards/can-deactivate-guard.service'
6 import { LoadingBarService } from '@ngx-loading-bar/core'
7 import { NotificationsService } from 'angular2-notifications'
8 import { BytesPipe } from 'ngx-pipes'
9 import { Subscription } from 'rxjs'
10 import { VideoPrivacy } from '../../../../../shared/models/videos'
11 import { AuthService, ServerService } from '../../core'
12 import { FormReactive } from '../../shared'
13 import { populateAsyncUserVideoChannels } from '../../shared/misc/utils'
14 import { VideoEdit } from '../../shared/video/video-edit.model'
15 import { VideoService } from '../../shared/video/video.service'
16 import { I18n } from '@ngx-translate/i18n-polyfill'
17 import { FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
18 import { switchMap } from 'rxjs/operators'
19 import { VideoCaptionService } from '@app/shared/video-caption'
20
21 @Component({
22   selector: 'my-videos-add',
23   templateUrl: './video-add.component.html',
24   styleUrls: [
25     './shared/video-edit.component.scss',
26     './video-add.component.scss'
27   ]
28 })
29 export class VideoAddComponent extends FormReactive implements OnInit, OnDestroy, CanComponentDeactivate {
30   @ViewChild('videofileInput') videofileInput
31
32   // So that it can be accessed in the template
33   readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
34
35   isUploadingVideo = false
36   isUpdatingVideo = false
37   videoUploaded = false
38   videoUploadObservable: Subscription = null
39   videoUploadPercents = 0
40   videoUploadedIds = {
41     id: 0,
42     uuid: ''
43   }
44   videoFileName: string
45
46   userVideoChannels: { id: number, label: string, support: string }[] = []
47   userVideoQuotaUsed = 0
48   videoPrivacies = []
49   firstStepPrivacyId = 0
50   firstStepChannelId = 0
51   videoCaptions = []
52
53   constructor (
54     protected formValidatorService: FormValidatorService,
55     private router: Router,
56     private notificationsService: NotificationsService,
57     private authService: AuthService,
58     private userService: UserService,
59     private serverService: ServerService,
60     private videoService: VideoService,
61     private loadingBar: LoadingBarService,
62     private i18n: I18n,
63     private videoCaptionService: VideoCaptionService
64   ) {
65     super()
66   }
67
68   get videoExtensions () {
69     return this.serverService.getConfig().video.file.extensions.join(',')
70   }
71
72   ngOnInit () {
73     this.buildForm({})
74
75     populateAsyncUserVideoChannels(this.authService, this.userVideoChannels)
76       .then(() => this.firstStepChannelId = this.userVideoChannels[0].id)
77
78     this.userService.getMyVideoQuotaUsed()
79       .subscribe(data => this.userVideoQuotaUsed = data.videoQuotaUsed)
80
81     this.serverService.videoPrivaciesLoaded
82       .subscribe(
83         () => {
84           this.videoPrivacies = this.serverService.getVideoPrivacies()
85
86           // Public by default
87           this.firstStepPrivacyId = VideoPrivacy.PUBLIC
88         })
89   }
90
91   ngOnDestroy () {
92     if (this.videoUploadObservable) {
93       this.videoUploadObservable.unsubscribe()
94     }
95   }
96
97   canDeactivate () {
98     let text = ''
99
100     if (this.videoUploaded === true) {
101       // FIXME: cannot concatenate strings inside i18n service :/
102       text = this.i18n('Your video was uploaded in your account and is private.') +
103         this.i18n('But associated data (tags, description...) will be lost, are you sure you want to leave this page?')
104     } else {
105       text = this.i18n('Your video is not uploaded yet, are you sure you want to leave this page?')
106     }
107
108     return {
109       canDeactivate: !this.isUploadingVideo,
110       text
111     }
112   }
113
114   fileChange () {
115     this.uploadFirstStep()
116   }
117
118   checkForm () {
119     this.forceCheck()
120
121     return this.form.valid
122   }
123
124   cancelUpload () {
125     if (this.videoUploadObservable !== null) {
126       this.videoUploadObservable.unsubscribe()
127       this.isUploadingVideo = false
128       this.videoUploadPercents = 0
129       this.videoUploadObservable = null
130       this.notificationsService.info(this.i18n('Info'), this.i18n('Upload cancelled'))
131     }
132   }
133
134   uploadFirstStep () {
135     const videofile = this.videofileInput.nativeElement.files[0] as File
136     if (!videofile) return
137
138     // Cannot upload videos > 8GB for now
139     if (videofile.size > 8 * 1024 * 1024 * 1024) {
140       this.notificationsService.error(this.i18n('Error'), this.i18n('We are sorry but PeerTube cannot handle videos > 8GB'))
141       return
142     }
143
144     const videoQuota = this.authService.getUser().videoQuota
145     if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
146       const bytePipes = new BytesPipe()
147
148       const msg = this.i18n(
149         'Your video quota is exceeded with this video (video size: {{ videoSize }}, used: {{ videoQuotaUsed }}, quota: {{ videoQuota }})',
150         {
151           videoSize: bytePipes.transform(videofile.size, 0),
152           videoQuotaUsed: bytePipes.transform(this.userVideoQuotaUsed, 0),
153           videoQuota: bytePipes.transform(videoQuota, 0)
154         }
155       )
156       this.notificationsService.error(this.i18n('Error'), msg)
157       return
158     }
159
160     this.videoFileName = videofile.name
161
162     const nameWithoutExtension = videofile.name.replace(/\.[^/.]+$/, '')
163     let name: string
164
165     // If the name of the file is very small, keep the extension
166     if (nameWithoutExtension.length < 3) name = videofile.name
167     else name = nameWithoutExtension
168
169     const privacy = this.firstStepPrivacyId.toString()
170     const nsfw = false
171     const waitTranscoding = true
172     const commentsEnabled = true
173     const channelId = this.firstStepChannelId.toString()
174
175     const formData = new FormData()
176     formData.append('name', name)
177     // Put the video "private" -> we are waiting the user validation of the second step
178     formData.append('privacy', VideoPrivacy.PRIVATE.toString())
179     formData.append('nsfw', '' + nsfw)
180     formData.append('commentsEnabled', '' + commentsEnabled)
181     formData.append('waitTranscoding', '' + waitTranscoding)
182     formData.append('channelId', '' + channelId)
183     formData.append('videofile', videofile)
184
185     this.isUploadingVideo = true
186     this.form.patchValue({
187       name,
188       privacy,
189       nsfw,
190       channelId
191     })
192
193     this.videoUploadObservable = this.videoService.uploadVideo(formData).subscribe(
194       event => {
195         if (event.type === HttpEventType.UploadProgress) {
196           this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
197         } else if (event instanceof HttpResponse) {
198           this.videoUploaded = true
199
200           this.videoUploadedIds = event.body.video
201
202           this.videoUploadObservable = null
203         }
204       },
205
206       err => {
207         // Reset progress
208         this.isUploadingVideo = false
209         this.videoUploadPercents = 0
210         this.videoUploadObservable = null
211         this.notificationsService.error(this.i18n('Error'), err.message)
212       }
213     )
214   }
215
216   updateSecondStep () {
217     if (this.checkForm() === false) {
218       return
219     }
220
221     const video = new VideoEdit()
222     video.patch(this.form.value)
223     video.id = this.videoUploadedIds.id
224     video.uuid = this.videoUploadedIds.uuid
225
226     this.isUpdatingVideo = true
227     this.loadingBar.start()
228     this.videoService.updateVideo(video)
229         .pipe(
230           // Then update captions
231           switchMap(() => this.videoCaptionService.updateCaptions(video.id, this.videoCaptions))
232         )
233         .subscribe(
234           () => {
235             this.isUpdatingVideo = false
236             this.isUploadingVideo = false
237             this.loadingBar.complete()
238
239             this.notificationsService.success(this.i18n('Success'), this.i18n('Video published.'))
240             this.router.navigate([ '/videos/watch', video.uuid ])
241           },
242
243           err => {
244             this.isUpdatingVideo = false
245             this.notificationsService.error(this.i18n('Error'), err.message)
246             console.error(err)
247           }
248         )
249   }
250 }