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