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'
10 VIDEO_CATEGORY_VALIDATOR,
11 VIDEO_CHANNEL_VALIDATOR,
12 VIDEO_DESCRIPTION_VALIDATOR,
13 VIDEO_LANGUAGE_VALIDATOR,
14 VIDEO_LICENCE_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'
29 RegisterClientFormFieldOptions,
30 RegisterClientVideoFieldOptions,
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'
40 type VideoLanguages = VideoConstant<string> & { group?: string }
42 pluginInfo: PluginInfo
43 commonOptions: RegisterClientFormFieldOptions
44 videoFormOptions: RegisterClientVideoFieldOptions
48 selector: 'my-video-edit',
49 styleUrls: [ './video-edit.component.scss' ],
50 templateUrl: './video-edit.component.html'
52 export class VideoEditComponent implements OnInit, OnDestroy {
53 @Input() form: FormGroup
54 @Input() formErrors: { [ id: string ]: string } = {}
55 @Input() validationMessages: FormReactiveValidationMessages = {}
57 @Input() videoToUpdate: VideoDetails
59 @Input() userVideoChannels: SelectChannelItem[] = []
60 @Input() forbidScheduledPublication = true
62 @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
64 @Input() waitTranscodingEnabled = true
65 @Input() type: VideoEditType
66 @Input() liveVideo: LiveVideo
68 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
69 @ViewChild('videoCaptionEditModal', { static: true }) editCaptionModal: VideoCaptionEditModalComponent
71 @Output() formBuilt = new EventEmitter<void>()
72 @Output() pluginFieldsAdded = new EventEmitter<void>()
74 // So that it can be accessed in the template
75 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
77 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
78 videoCategories: VideoConstant<number>[] = []
79 videoLicences: VideoConstant<number>[] = []
80 videoLanguages: VideoLanguages[] = []
82 pluginDataFormGroup: FormGroup
84 schedulePublicationEnabled = false
86 calendarLocale: any = {}
87 minScheduledDate = new Date()
88 myYearRange = '1880:' + (new Date()).getFullYear()
90 calendarTimezone: string
91 calendarDateFormat: string
93 serverConfig: HTMLServerConfig
95 pluginFields: PluginField[] = []
97 private schedulerInterval: any
98 private firstPatchDone = false
99 private initialVideoCaptions: string[] = []
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
112 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
113 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
117 const defaultValues: any = {
119 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
120 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
121 waitTranscoding: 'true',
122 licence: this.serverConfig.defaults.publish.licence,
125 const obj: { [ id: string ]: BuildFormValidator } = {
126 name: VIDEO_NAME_VALIDATOR,
127 privacy: VIDEO_PRIVACY_VALIDATOR,
128 channelId: VIDEO_CHANNEL_VALIDATOR,
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,
139 support: VIDEO_SUPPORT_VALIDATOR,
140 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
141 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
147 this.formValidatorService.updateFormGroup(
150 this.validationMessages,
155 this.form.addControl('captions', new FormArray([
157 language: new FormControl(),
158 captionfile: new FormControl()
162 this.trackChannelChange()
163 this.trackPrivacyChange()
164 this.trackLivePermanentFieldChange()
166 this.formBuilt.emit()
170 this.serverConfig = this.serverService.getHTMLConfig()
174 this.pluginService.ensurePluginsAreLoaded('video-edit')
175 .then(() => this.updatePluginFields())
177 this.serverService.getVideoCategories()
178 .subscribe(res => this.videoCategories = res)
180 this.serverService.getVideoLicences()
181 .subscribe(res => this.videoLicences = res)
184 this.instanceService.getAbout(),
185 this.serverService.getVideoLanguages()
186 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
188 this.videoLanguages = res.languages
190 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
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 }
196 .sort((a, b) => a.groupOrder - b.groupOrder)
199 this.serverService.getVideoPrivacies()
200 .subscribe(privacies => {
201 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
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
207 this.videoPrivacies.push({
208 id: this.SPECIAL_SCHEDULED_PRIVACY,
209 label: $localize`Scheduled`,
210 description: $localize`Hide the video until a specific date`
214 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
216 this.ngZone.runOutsideAngular(() => {
217 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
220 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
224 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
227 getExistingCaptions () {
228 return this.videoCaptions
229 .filter(c => c.action !== 'REMOVE')
230 .map(c => c.language.id)
233 onCaptionEdited (caption: VideoCaptionEdit) {
234 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
236 // Replace existing caption?
237 if (existingCaption) {
238 Object.assign(existingCaption, caption)
240 this.videoCaptions.push(
241 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
245 this.sortVideoCaptions()
248 deleteCaption (caption: VideoCaptionEdit) {
249 // Caption recovers his former state
250 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
251 caption.action = undefined
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)
261 caption.action = 'REMOVE' as 'REMOVE'
264 openAddCaptionModal () {
265 this.videoCaptionAddModal.show()
268 isSaveReplayEnabled () {
269 return this.serverConfig.live.allowReplay
272 isPermanentLiveEnabled () {
273 return this.form.value['permanentLive'] === true
276 isPluginFieldHidden (pluginField: PluginField) {
277 if (typeof pluginField.commonOptions.hidden !== 'function') return false
279 return pluginField.commonOptions.hidden({
280 formValues: this.form.value,
281 videoToUpdate: this.videoToUpdate,
282 liveVideo: this.liveVideo
286 getPluginsFields (tab: 'main' | 'plugin-settings') {
287 return this.pluginFields.filter(p => {
288 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
290 return wanted === tab
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
303 private async updatePluginFields () {
304 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
306 if (this.pluginFields.length === 0) return
308 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
309 const pluginValidationMessages: FormReactiveValidationMessages = {}
310 const pluginFormErrors: any = {}
311 const pluginDefaults: any = {}
313 for (const setting of this.pluginFields) {
314 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
316 const validator = async (control: AbstractControl) => {
317 if (!setting.commonOptions.error) return null
319 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
321 return error?.error ? { [setting.commonOptions.name]: error.text } : null
324 const name = setting.commonOptions.name
327 ASYNC_VALIDATORS: [ validator ],
332 pluginDefaults[name] = setting.commonOptions.default
335 this.pluginDataFormGroup = new FormGroup({})
336 this.formValidatorService.updateFormGroup(
337 this.pluginDataFormGroup,
339 pluginValidationMessages,
344 this.form.addControl('pluginData', this.pluginDataFormGroup)
345 this.formErrors['pluginData'] = pluginFormErrors
346 this.validationMessages['pluginData'] = pluginValidationMessages
348 this.cd.detectChanges()
349 this.pluginFieldsAdded.emit()
351 // Plugins may need other control values to calculate potential errors
352 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
355 private trackPrivacyChange () {
356 // We will update the schedule input and the wait transcoding checkbox validators
357 this.form.controls['privacy']
359 .pipe(map(res => parseInt(res.toString(), 10)))
363 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
366 const scheduleControl = this.form.get('schedulePublicationAt')
367 const waitTranscodingControl = this.form.get('waitTranscoding')
369 if (this.schedulePublicationEnabled) {
370 scheduleControl.setValidators([ Validators.required ])
372 waitTranscodingControl.disable()
373 waitTranscodingControl.setValue(false)
375 scheduleControl.clearValidators()
377 waitTranscodingControl.enable()
379 // Do not update the control value on first patch (values come from the server)
380 if (this.firstPatchDone === true) {
381 waitTranscodingControl.setValue(true)
385 scheduleControl.updateValueAndValidity()
386 waitTranscodingControl.updateValueAndValidity()
388 this.firstPatchDone = true
394 private trackChannelChange () {
395 // We will update the "support" field depending on the channel
396 this.form.controls['channelId']
398 .pipe(map(res => parseInt(res.toString(), 10)))
401 const oldChannelId = parseInt(this.form.value['channelId'], 10)
403 // Not initialized yet
404 if (isNaN(newChannelId)) return
405 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
406 if (!newChannel) return
408 // Wait support field update
410 const currentSupport = this.form.value['support']
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)
420 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
421 if (!newChannel || !oldChannel) {
422 console.error('Cannot find new or old channel.')
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
430 // Update the support text with our new channel
431 this.updateSupportField(newChannel.support)
437 private trackLivePermanentFieldChange () {
438 // We will update the "support" field depending on the channel
439 this.form.controls['permanentLive']
443 const saveReplayControl = this.form.controls['saveReplay']
445 if (permanentLive === true) {
446 saveReplayControl.setValue(false)
447 saveReplayControl.disable()
449 saveReplayControl.enable()
455 private updateSupportField (support: string) {
456 return this.form.patchValue({ support: support || '' })