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