]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-edit/video-add.component.ts
Upgrade to rxjs 6
[github/Chocobozzz/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'
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 export class VideoAddComponent extends FormReactive implements OnInit, OnDestroy, CanComponentDeactivate {
28 @ViewChild('videofileInput') videofileInput
29
30 isUploadingVideo = false
31 isUpdatingVideo = false
32 videoUploaded = false
33 videoUploadObservable: Subscription = null
34 videoUploadPercents = 0
35 videoUploadedIds = {
36 id: 0,
37 uuid: ''
38 }
39 videoFileName: string
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] as File
136 if (!videofile) return
137
138 // Cannot upload videos > 4GB for now
139 if (videofile.size > 4 * 1024 * 1024 * 1024) {
140 this.notificationsService.error('Error', 'We are sorry but PeerTube cannot handle videos > 4GB')
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 = 'Your video quota is exceeded with this video ' +
149 `(video size: ${bytePipes.transform(videofile.size, 0)}, ` +
150 `used: ${bytePipes.transform(this.userVideoQuotaUsed, 0)}, ` +
151 `quota: ${bytePipes.transform(videoQuota, 0)})`
152 this.notificationsService.error('Error', msg)
153 return
154 }
155
156 this.videoFileName = videofile.name
157
158 const nameWithoutExtension = videofile.name.replace(/\.[^/.]+$/, '')
159 let name: string
160
161 // If the name of the file is very small, keep the extension
162 if (nameWithoutExtension.length < 3) {
163 name = videofile.name
164 } else {
165 name = nameWithoutExtension
166 }
167
168 const privacy = this.firstStepPrivacyId.toString()
169 const nsfw = false
170 const commentsEnabled = true
171 const channelId = this.firstStepChannelId.toString()
172
173 const formData = new FormData()
174 formData.append('name', name)
175 // Put the video "private" -> we are waiting the user validation of the second step
176 formData.append('privacy', VideoPrivacy.PRIVATE.toString())
177 formData.append('nsfw', '' + nsfw)
178 formData.append('commentsEnabled', '' + commentsEnabled)
179 formData.append('channelId', '' + channelId)
180 formData.append('videofile', videofile)
181
182 this.isUploadingVideo = true
183 this.form.patchValue({
184 name,
185 privacy,
186 nsfw,
187 channelId
188 })
189
190 this.videoUploadObservable = this.videoService.uploadVideo(formData).subscribe(
191 event => {
192 if (event.type === HttpEventType.UploadProgress) {
193 this.videoUploadPercents = Math.round(100 * event.loaded / event.total)
194 } else if (event instanceof HttpResponse) {
195 console.log('Video uploaded.')
196
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.notificationsService.error('Error', err.message)
211 }
212 )
213 }
214
215 updateSecondStep () {
216 if (this.checkForm() === false) {
217 return
218 }
219
220 const video = new VideoEdit()
221 video.patch(this.form.value)
222 video.channelId = this.firstStepChannelId
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 .subscribe(
230 () => {
231 this.isUpdatingVideo = false
232 this.isUploadingVideo = false
233 this.loadingBar.complete()
234
235 this.notificationsService.success('Success', 'Video published.')
236 this.router.navigate([ '/videos/watch', video.uuid ])
237 },
238
239 err => {
240 this.isUpdatingVideo = false
241 this.notificationsService.error('Error', err.message)
242 console.error(err)
243 }
244 )
245
246 }
247 }