]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Cleanup video update component
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / shared / video-edit.component.ts
1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { SelectChannelItem } from 'src/types/select-options-item.model'
4 import { Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms'
6 import { HooksService, PluginService, ServerService } from '@app/core'
7 import { removeElementFromArray } from '@app/helpers'
8 import {
9 VIDEO_CATEGORY_VALIDATOR,
10 VIDEO_CHANNEL_VALIDATOR,
11 VIDEO_DESCRIPTION_VALIDATOR,
12 VIDEO_LANGUAGE_VALIDATOR,
13 VIDEO_LICENCE_VALIDATOR,
14 VIDEO_NAME_VALIDATOR,
15 VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
16 VIDEO_PRIVACY_VALIDATOR,
17 VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
18 VIDEO_SUPPORT_VALIDATOR,
19 VIDEO_TAGS_ARRAY_VALIDATOR
20 } from '@app/shared/form-validators/video-validators'
21 import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
22 import { InstanceService } from '@app/shared/shared-instance'
23 import { VideoCaptionEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
24 import {
25 HTMLServerConfig,
26 LiveVideo,
27 RegisterClientFormFieldOptions,
28 RegisterClientVideoFieldOptions,
29 VideoConstant,
30 VideoDetails,
31 VideoPrivacy
32 } from '@shared/models'
33 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
34 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
35 import { VideoEditType } from './video-edit.type'
36
37 type VideoLanguages = VideoConstant<string> & { group?: string }
38 type PluginField = {
39 commonOptions: RegisterClientFormFieldOptions
40 videoFormOptions: RegisterClientVideoFieldOptions
41 }
42
43 @Component({
44 selector: 'my-video-edit',
45 styleUrls: [ './video-edit.component.scss' ],
46 templateUrl: './video-edit.component.html'
47 })
48 export class VideoEditComponent implements OnInit, OnDestroy {
49 @Input() form: FormGroup
50 @Input() formErrors: { [ id: string ]: string } = {}
51 @Input() validationMessages: FormReactiveValidationMessages = {}
52
53 @Input() videoToUpdate: VideoDetails
54
55 @Input() userVideoChannels: SelectChannelItem[] = []
56 @Input() schedulePublicationPossible = true
57
58 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
59
60 @Input() waitTranscodingEnabled = true
61 @Input() type: VideoEditType
62 @Input() liveVideo: LiveVideo
63
64 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
65
66 @Output() formBuilt = new EventEmitter<void>()
67 @Output() pluginFieldsAdded = new EventEmitter<void>()
68
69 // So that it can be accessed in the template
70 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
71
72 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
73 videoCategories: VideoConstant<number>[] = []
74 videoLicences: VideoConstant<number>[] = []
75 videoLanguages: VideoLanguages[] = []
76
77 pluginDataFormGroup: FormGroup
78
79 schedulePublicationEnabled = false
80
81 calendarLocale: any = {}
82 minScheduledDate = new Date()
83 myYearRange = '1880:' + (new Date()).getFullYear()
84
85 calendarTimezone: string
86 calendarDateFormat: string
87
88 serverConfig: HTMLServerConfig
89
90 pluginFields: PluginField[] = []
91
92 private schedulerInterval: any
93 private firstPatchDone = false
94 private initialVideoCaptions: string[] = []
95
96 constructor (
97 private formValidatorService: FormValidatorService,
98 private videoService: VideoService,
99 private serverService: ServerService,
100 private pluginService: PluginService,
101 private instanceService: InstanceService,
102 private i18nPrimengCalendarService: I18nPrimengCalendarService,
103 private ngZone: NgZone,
104 private hooks: HooksService
105 ) {
106 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
107 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
108 }
109
110 updateForm () {
111 const defaultValues: any = {
112 nsfw: 'false',
113 commentsEnabled: 'true',
114 downloadEnabled: 'true',
115 waitTranscoding: 'true',
116 tags: []
117 }
118 const obj: any = {
119 name: VIDEO_NAME_VALIDATOR,
120 privacy: VIDEO_PRIVACY_VALIDATOR,
121 channelId: VIDEO_CHANNEL_VALIDATOR,
122 nsfw: null,
123 commentsEnabled: null,
124 downloadEnabled: null,
125 waitTranscoding: null,
126 category: VIDEO_CATEGORY_VALIDATOR,
127 licence: VIDEO_LICENCE_VALIDATOR,
128 language: VIDEO_LANGUAGE_VALIDATOR,
129 description: VIDEO_DESCRIPTION_VALIDATOR,
130 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
131 previewfile: null,
132 support: VIDEO_SUPPORT_VALIDATOR,
133 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
134 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
135 liveStreamKey: null,
136 permanentLive: null,
137 saveReplay: null
138 }
139
140 this.formValidatorService.updateForm(
141 this.form,
142 this.formErrors,
143 this.validationMessages,
144 obj,
145 defaultValues
146 )
147
148 this.form.addControl('captions', new FormArray([
149 new FormGroup({
150 language: new FormControl(),
151 captionfile: new FormControl()
152 })
153 ]))
154
155 this.trackChannelChange()
156 this.trackPrivacyChange()
157 this.trackLivePermanentFieldChange()
158
159 this.formBuilt.emit()
160 }
161
162 ngOnInit () {
163 this.updateForm()
164
165 this.pluginService.ensurePluginsAreLoaded('video-edit')
166 .then(() => this.updatePluginFields())
167
168 this.serverService.getVideoCategories()
169 .subscribe(res => this.videoCategories = res)
170
171 this.serverService.getVideoLicences()
172 .subscribe(res => this.videoLicences = res)
173
174 forkJoin([
175 this.instanceService.getAbout(),
176 this.serverService.getVideoLanguages()
177 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
178 .subscribe(res => {
179 this.videoLanguages = res.languages
180 .map(l => {
181 return res.about.instance.languages.includes(l.id)
182 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
183 : { ...l, group: $localize`All languages`, groupOrder: 1 }
184 })
185 .sort((a, b) => a.groupOrder - b.groupOrder)
186 })
187
188 this.serverService.getVideoPrivacies()
189 .subscribe(privacies => {
190 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
191
192 if (this.schedulePublicationPossible) {
193 this.videoPrivacies.push({
194 id: this.SPECIAL_SCHEDULED_PRIVACY,
195 label: $localize`Scheduled`,
196 description: $localize`Hide the video until a specific date`
197 })
198 }
199 })
200
201 this.serverConfig = this.serverService.getHTMLConfig()
202
203 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
204
205 this.ngZone.runOutsideAngular(() => {
206 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
207 })
208
209 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
210 }
211
212 ngOnDestroy () {
213 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
214 }
215
216 getExistingCaptions () {
217 return this.videoCaptions
218 .filter(c => c.action !== 'REMOVE')
219 .map(c => c.language.id)
220 }
221
222 onCaptionAdded (caption: VideoCaptionEdit) {
223 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
224
225 // Replace existing caption?
226 if (existingCaption) {
227 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
228 } else {
229 this.videoCaptions.push(
230 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
231 )
232 }
233
234 this.sortVideoCaptions()
235 }
236
237 deleteCaption (caption: VideoCaptionEdit) {
238 // Caption recovers his former state
239 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
240 caption.action = undefined
241 return
242 }
243
244 // This caption is not on the server, just remove it from our array
245 if (caption.action === 'CREATE') {
246 removeElementFromArray(this.videoCaptions, caption)
247 return
248 }
249
250 caption.action = 'REMOVE' as 'REMOVE'
251 }
252
253 openAddCaptionModal () {
254 this.videoCaptionAddModal.show()
255 }
256
257 isSaveReplayEnabled () {
258 return this.serverConfig.live.allowReplay
259 }
260
261 isPermanentLiveEnabled () {
262 return this.form.value['permanentLive'] === true
263 }
264
265 isPluginFieldHidden (pluginField: PluginField) {
266 if (typeof pluginField.commonOptions.hidden !== 'function') return false
267
268 return pluginField.commonOptions.hidden({
269 formValues: this.form.value,
270 videoToUpdate: this.videoToUpdate,
271 liveVideo: this.liveVideo
272 })
273 }
274
275 private sortVideoCaptions () {
276 this.videoCaptions.sort((v1, v2) => {
277 if (v1.language.label < v2.language.label) return -1
278 if (v1.language.label === v2.language.label) return 0
279
280 return 1
281 })
282 }
283
284 private updatePluginFields () {
285 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
286
287 if (this.pluginFields.length === 0) return
288
289 const obj: any = {}
290
291 for (const setting of this.pluginFields) {
292 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
293 }
294
295 this.pluginDataFormGroup = new FormGroup(obj)
296 this.form.addControl('pluginData', this.pluginDataFormGroup)
297
298 this.pluginFieldsAdded.emit()
299 }
300
301 private trackPrivacyChange () {
302 // We will update the schedule input and the wait transcoding checkbox validators
303 this.form.controls['privacy']
304 .valueChanges
305 .pipe(map(res => parseInt(res.toString(), 10)))
306 .subscribe(
307 newPrivacyId => {
308
309 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
310
311 // Value changed
312 const scheduleControl = this.form.get('schedulePublicationAt')
313 const waitTranscodingControl = this.form.get('waitTranscoding')
314
315 if (this.schedulePublicationEnabled) {
316 scheduleControl.setValidators([ Validators.required ])
317
318 waitTranscodingControl.disable()
319 waitTranscodingControl.setValue(false)
320 } else {
321 scheduleControl.clearValidators()
322
323 waitTranscodingControl.enable()
324
325 // Do not update the control value on first patch (values come from the server)
326 if (this.firstPatchDone === true) {
327 waitTranscodingControl.setValue(true)
328 }
329 }
330
331 scheduleControl.updateValueAndValidity()
332 waitTranscodingControl.updateValueAndValidity()
333
334 this.firstPatchDone = true
335
336 }
337 )
338 }
339
340 private trackChannelChange () {
341 // We will update the "support" field depending on the channel
342 this.form.controls['channelId']
343 .valueChanges
344 .pipe(map(res => parseInt(res.toString(), 10)))
345 .subscribe(
346 newChannelId => {
347 const oldChannelId = parseInt(this.form.value['channelId'], 10)
348
349 // Not initialized yet
350 if (isNaN(newChannelId)) return
351 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
352 if (!newChannel) return
353
354 // Wait support field update
355 setTimeout(() => {
356 const currentSupport = this.form.value['support']
357
358 // First time we set the channel?
359 if (isNaN(oldChannelId)) {
360 // Fill support if it's empty
361 if (!currentSupport) this.updateSupportField(newChannel.support)
362
363 return
364 }
365
366 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
367 if (!newChannel || !oldChannel) {
368 console.error('Cannot find new or old channel.')
369 return
370 }
371
372 // If the current support text is not the same than the old channel, the user updated it.
373 // We don't want the user to lose his text, so stop here
374 if (currentSupport && currentSupport !== oldChannel.support) return
375
376 // Update the support text with our new channel
377 this.updateSupportField(newChannel.support)
378 })
379 }
380 )
381 }
382
383 private trackLivePermanentFieldChange () {
384 // We will update the "support" field depending on the channel
385 this.form.controls['permanentLive']
386 .valueChanges
387 .subscribe(
388 permanentLive => {
389 const saveReplayControl = this.form.controls['saveReplay']
390
391 if (permanentLive === true) {
392 saveReplayControl.setValue(false)
393 saveReplayControl.disable()
394 } else {
395 saveReplayControl.enable()
396 }
397 }
398 )
399 }
400
401 private updateSupportField (support: string) {
402 return this.form.patchValue({ support: support || '' })
403 }
404 }