Issue #195 : When uploading, warn when the user quits the page (#222)
[oweals/peertube.git] / client / src / app / videos / +video-edit / video-add.component.ts
1 import { HttpEventType, HttpResponse } from '@angular/common/http'
2 import { Component, 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 { NotificationsService } from 'angular2-notifications'
7 import { BytesPipe } from 'ngx-pipes'
8 import { VideoPrivacy } from '../../../../../shared/models/videos'
9 import { AuthService, ServerService } from '../../core'
10 import { FormReactive } from '../../shared'
11 import { ValidatorMessage } from '../../shared/forms/form-validators/validator-message'
12 import { populateAsyncUserVideoChannels } from '../../shared/misc/utils'
13 import { VideoEdit } from '../../shared/video/video-edit.model'
14 import { VideoService } from '../../shared/video/video.service'
15 import { CanComponentDeactivate } from '@app/shared/can-deactivate-guard.service'
16
17 @Component({
18   selector: 'my-videos-add',
19   templateUrl: './video-add.component.html',
20   styleUrls: [
21     './shared/video-edit.component.scss',
22     './video-add.component.scss'
23   ]
24 })
25
26 export class VideoAddComponent extends FormReactive implements OnInit, CanComponentDeactivate {
27   @ViewChild('videofileInput') videofileInput
28
29   isUploadingVideo = false
30   videoUploaded = false
31   videoUploadObservable = null
32   videoUploadPercents = 0
33   videoUploadedIds = {
34     id: 0,
35     uuid: ''
36   }
37
38   form: FormGroup
39   formErrors: { [ id: string ]: string } = {}
40   validationMessages: ValidatorMessage = {}
41
42   userVideoChannels = []
43   userVideoQuotaUsed = 0
44   videoPrivacies = []
45   firstStepPrivacyId = 0
46   firstStepChannelId = 0
47
48   constructor (
49     private formBuilder: FormBuilder,
50     private router: Router,
51     private notificationsService: NotificationsService,
52     private authService: AuthService,
53     private userService: UserService,
54     private serverService: ServerService,
55     private videoService: VideoService
56   ) {
57     super()
58   }
59
60   get videoExtensions () {
61     return this.serverService.getConfig().video.file.extensions.join(',')
62   }
63
64   buildForm () {
65     this.form = this.formBuilder.group({})
66     this.form.valueChanges.subscribe(data => this.onValueChanged(data))
67   }
68
69   ngOnInit () {
70     this.buildForm()
71
72     populateAsyncUserVideoChannels(this.authService, this.userVideoChannels)
73       .then(() => this.firstStepChannelId = this.userVideoChannels[0].id)
74
75     this.userService.getMyVideoQuotaUsed()
76       .subscribe(data => this.userVideoQuotaUsed = data.videoQuotaUsed)
77
78     this.serverService.videoPrivaciesLoaded
79       .subscribe(
80         () => {
81           this.videoPrivacies = this.serverService.getVideoPrivacies()
82
83           // Public by default
84           this.firstStepPrivacyId = VideoPrivacy.PUBLIC
85         })
86   }
87
88   canDeactivate () {
89     return !this.isUploadingVideo
90   }
91
92   fileChange () {
93     this.uploadFirstStep()
94   }
95
96   checkForm () {
97     this.forceCheck()
98
99     return this.form.valid
100   }
101
102   cancelUpload () {
103     if (this.videoUploadObservable !== null) {
104       this.videoUploadObservable.unsubscribe()
105       this.isUploadingVideo = false
106       this.videoUploadPercents = 0
107       this.videoUploadObservable = null
108       this.notificationsService.info('Info', 'Upload cancelled')
109     }
110   }
111
112   uploadFirstStep () {
113     const videofile = this.videofileInput.nativeElement.files[0]
114     if (!videofile) return
115
116     const videoQuota = this.authService.getUser().videoQuota
117     if (videoQuota !== -1 && (this.userVideoQuotaUsed + videofile.size) > videoQuota) {
118       const bytePipes = new BytesPipe()
119
120       const msg = 'Your video quota is exceeded with this video ' +
121         `(video size: ${bytePipes.transform(videofile.size, 0)}, ` +
122         `used: ${bytePipes.transform(this.userVideoQuotaUsed, 0)}, ` +
123         `quota: ${bytePipes.transform(videoQuota, 0)})`
124       this.notificationsService.error('Error', msg)
125       return
126     }
127
128     const name = videofile.name.replace(/\.[^/.]+$/, '')
129     const privacy = this.firstStepPrivacyId.toString()
130     const nsfw = false
131     const commentsEnabled = true
132     const channelId = this.firstStepChannelId.toString()
133
134     const formData = new FormData()
135     formData.append('name', name)
136     // Put the video "private" -> we wait he validates the second step
137     formData.append('privacy', VideoPrivacy.PRIVATE.toString())
138     formData.append('nsfw', '' + nsfw)
139     formData.append('commentsEnabled', '' + commentsEnabled)
140     formData.append('channelId', '' + channelId)
141     formData.append('videofile', videofile)
142
143     this.isUploadingVideo = true
144     this.form.patchValue({
145       name,
146       privacy,
147       nsfw,
148       channelId
149     })
150
151     this.videoUploadObservable = this.videoService.uploadVideo(formData).subscribe(
152       event => {
153         if (event.type === HttpEventType.UploadProgress) {
154           this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
155         } else if (event instanceof HttpResponse) {
156           console.log('Video uploaded.')
157
158           this.videoUploaded = true
159
160           this.videoUploadedIds = event.body.video
161
162           this.videoUploadObservable = null
163         }
164       },
165
166       err => {
167         // Reset progress
168         this.isUploadingVideo = false
169         this.videoUploadPercents = 0
170         this.videoUploadObservable = null
171         this.notificationsService.error('Error', err.message)
172       }
173     )
174   }
175
176   updateSecondStep () {
177     if (this.checkForm() === false) {
178       return
179     }
180
181     const video = new VideoEdit()
182     video.patch(this.form.value)
183     video.channel = this.firstStepChannelId
184     video.id = this.videoUploadedIds.id
185     video.uuid = this.videoUploadedIds.uuid
186
187     this.videoService.updateVideo(video)
188       .subscribe(
189         () => {
190           this.notificationsService.success('Success', 'Video published.')
191           this.router.navigate([ '/videos/watch', video.uuid ])
192         },
193
194         err => {
195           this.notificationsService.error('Error', err.message)
196           console.error(err)
197         }
198       )
199
200   }
201 }