Add loading bar when updating a video
[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 { FormBuilder, FormGroup } from '@angular/forms'
4 import { Router } from '@angular/router'
5 import { UserService } from '@app/shared'
6 import { CanComponentDeactivate } from '@app/shared/guards/can-deactivate-guard.service'
7 import { LoadingBarService } from '@ngx-loading-bar/core'
8 import { NotificationsService } from 'angular2-notifications'
9 import { BytesPipe } from 'ngx-pipes'
10 import { Subscription } from 'rxjs/Subscription'
11 import { VideoPrivacy } from '../../../../../shared/models/videos'
12 import { AuthService, ServerService } from '../../core'
13 import { FormReactive } from '../../shared'
14 import { ValidatorMessage } from '../../shared/forms/form-validators/validator-message'
15 import { populateAsyncUserVideoChannels } from '../../shared/misc/utils'
16 import { VideoEdit } from '../../shared/video/video-edit.model'
17 import { VideoService } from '../../shared/video/video.service'
18
19 @Component({
20   selector: 'my-videos-add',
21   templateUrl: './video-add.component.html',
22   styleUrls: [
23     './shared/video-edit.component.scss',
24     './video-add.component.scss'
25   ]
26 })
27
28 export class VideoAddComponent extends FormReactive implements OnInit, OnDestroy, CanComponentDeactivate {
29   @ViewChild('videofileInput') videofileInput
30
31   isUploadingVideo = false
32   isUpdatingVideo = false
33   videoUploaded = false
34   videoUploadObservable: Subscription = null
35   videoUploadPercents = 0
36   videoUploadedIds = {
37     id: 0,
38     uuid: ''
39   }
40
41   form: FormGroup
42   formErrors: { [ id: string ]: string } = {}
43   validationMessages: ValidatorMessage = {}
44
45   userVideoChannels = []
46   userVideoQuotaUsed = 0
47   videoPrivacies = []
48   firstStepPrivacyId = 0
49   firstStepChannelId = 0
50
51   constructor (
52     private formBuilder: FormBuilder,
53     private router: Router,
54     private notificationsService: NotificationsService,
55     private authService: AuthService,
56     private userService: UserService,
57     private serverService: ServerService,
58     private videoService: VideoService,
59     private loadingBar: LoadingBarService
60   ) {
61     super()
62   }
63
64   get videoExtensions () {
65     return this.serverService.getConfig().video.file.extensions.join(',')
66   }
67
68   buildForm () {
69     this.form = this.formBuilder.group({})
70     this.form.valueChanges.subscribe(data => this.onValueChanged(data))
71   }
72
73   ngOnInit () {
74     this.buildForm()
75
76     populateAsyncUserVideoChannels(this.authService, this.userVideoChannels)
77       .then(() => this.firstStepChannelId = this.userVideoChannels[0].id)
78
79     this.userService.getMyVideoQuotaUsed()
80       .subscribe(data => this.userVideoQuotaUsed = data.videoQuotaUsed)
81
82     this.serverService.videoPrivaciesLoaded
83       .subscribe(
84         () => {
85           this.videoPrivacies = this.serverService.getVideoPrivacies()
86
87           // Public by default
88           this.firstStepPrivacyId = VideoPrivacy.PUBLIC
89         })
90   }
91
92   ngOnDestroy () {
93     if (this.videoUploadObservable) {
94       this.videoUploadObservable.unsubscribe()
95     }
96   }
97
98   canDeactivate () {
99     let text = ''
100
101     if (this.videoUploaded === true) {
102       text = 'Your video was uploaded in your account and is private.' +
103         ' But associated data (tags, description...) will be lost, are you sure you want to leave this page?'
104     } else {
105       text = '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('Info', 'Upload cancelled')
131     }
132   }
133
134   uploadFirstStep () {
135     const videofile = this.videofileInput.nativeElement.files[0]
136     if (!videofile) return
137
138     const videoQuota = this.authService.getUser().videoQuota
139     if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
140       const bytePipes = new BytesPipe()
141
142       const msg = 'Your video quota is exceeded with this video ' +
143         `(video size: ${bytePipes.transform(videofile.size, 0)}, ` +
144         `used: ${bytePipes.transform(this.userVideoQuotaUsed, 0)}, ` +
145         `quota: ${bytePipes.transform(videoQuota, 0)})`
146       this.notificationsService.error('Error', msg)
147       return
148     }
149
150     const name = videofile.name.replace(/\.[^/.]+$/, '')
151     const privacy = this.firstStepPrivacyId.toString()
152     const nsfw = false
153     const commentsEnabled = true
154     const channelId = this.firstStepChannelId.toString()
155
156     const formData = new FormData()
157     formData.append('name', name)
158     // Put the video "private" -> we wait he validates the second step
159     formData.append('privacy', VideoPrivacy.PRIVATE.toString())
160     formData.append('nsfw', '' + nsfw)
161     formData.append('commentsEnabled', '' + commentsEnabled)
162     formData.append('channelId', '' + channelId)
163     formData.append('videofile', videofile)
164
165     this.isUploadingVideo = true
166     this.form.patchValue({
167       name,
168       privacy,
169       nsfw,
170       channelId
171     })
172
173     this.videoUploadObservable = this.videoService.uploadVideo(formData).subscribe(
174       event => {
175         if (event.type === HttpEventType.UploadProgress) {
176           this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
177         } else if (event instanceof HttpResponse) {
178           console.log('Video uploaded.')
179
180           this.videoUploaded = true
181
182           this.videoUploadedIds = event.body.video
183
184           this.videoUploadObservable = null
185         }
186       },
187
188       err => {
189         // Reset progress
190         this.isUploadingVideo = false
191         this.videoUploadPercents = 0
192         this.videoUploadObservable = null
193         this.notificationsService.error('Error', err.message)
194       }
195     )
196   }
197
198   updateSecondStep () {
199     if (this.checkForm() === false) {
200       return
201     }
202
203     const video = new VideoEdit()
204     video.patch(this.form.value)
205     video.channel = this.firstStepChannelId
206     video.id = this.videoUploadedIds.id
207     video.uuid = this.videoUploadedIds.uuid
208
209     this.isUpdatingVideo = true
210     this.loadingBar.start()
211     this.videoService.updateVideo(video)
212       .subscribe(
213         () => {
214           this.isUpdatingVideo = false
215           this.isUploadingVideo = false
216           this.loadingBar.complete()
217
218           this.notificationsService.success('Success', 'Video published.')
219           this.router.navigate([ '/videos/watch', video.uuid ])
220         },
221
222         err => {
223           this.isUpdatingVideo = false
224           this.notificationsService.error('Error', err.message)
225           console.error(err)
226         }
227       )
228
229   }
230 }