1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { SelectChannelItem, SelectOptionsItem } 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'
30 RegisterClientFormFieldOptions,
31 RegisterClientVideoFieldOptions,
35 } from '@shared/models'
36 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
37 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
38 import { VideoCaptionEditModalComponent } from './video-caption-edit-modal/video-caption-edit-modal.component'
39 import { VideoEditType } from './video-edit.type'
41 type VideoLanguages = VideoConstant<string> & { group?: string }
43 pluginInfo: PluginInfo
44 commonOptions: RegisterClientFormFieldOptions
45 videoFormOptions: RegisterClientVideoFieldOptions
49 selector: 'my-video-edit',
50 styleUrls: [ './video-edit.component.scss' ],
51 templateUrl: './video-edit.component.html'
53 export class VideoEditComponent implements OnInit, OnDestroy {
54 @Input() form: FormGroup
55 @Input() formErrors: { [ id: string ]: string } = {}
56 @Input() validationMessages: FormReactiveValidationMessages = {}
58 @Input() videoToUpdate: VideoDetails
60 @Input() userVideoChannels: SelectChannelItem[] = []
61 @Input() forbidScheduledPublication = true
63 @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
65 @Input() waitTranscodingEnabled = true
66 @Input() type: VideoEditType
67 @Input() liveVideo: LiveVideo
69 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
70 @ViewChild('videoCaptionEditModal', { static: true }) editCaptionModal: VideoCaptionEditModalComponent
72 @Output() formBuilt = new EventEmitter<void>()
73 @Output() pluginFieldsAdded = new EventEmitter<void>()
75 // So that it can be accessed in the template
76 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
78 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
79 videoCategories: VideoConstant<number>[] = []
80 videoLicences: VideoConstant<number>[] = []
81 videoLanguages: VideoLanguages[] = []
82 latencyModes: SelectOptionsItem[] = [
84 id: LiveVideoLatencyMode.SMALL_LATENCY,
85 label: $localize`Small latency`,
86 description: $localize`Reduce latency to ~15s disabling P2P`
89 id: LiveVideoLatencyMode.DEFAULT,
90 label: $localize`Default`,
91 description: $localize`Average latency of 30s`
94 id: LiveVideoLatencyMode.HIGH_LATENCY,
95 label: $localize`High latency`,
96 description: $localize`Average latency of 60s increasing P2P ratio`
100 pluginDataFormGroup: FormGroup
102 schedulePublicationEnabled = false
104 calendarLocale: any = {}
105 minScheduledDate = new Date()
106 myYearRange = '1880:' + (new Date()).getFullYear()
108 calendarTimezone: string
109 calendarDateFormat: string
111 serverConfig: HTMLServerConfig
113 pluginFields: PluginField[] = []
115 private schedulerInterval: any
116 private firstPatchDone = false
117 private initialVideoCaptions: string[] = []
120 private formValidatorService: FormValidatorService,
121 private videoService: VideoService,
122 private serverService: ServerService,
123 private pluginService: PluginService,
124 private instanceService: InstanceService,
125 private i18nPrimengCalendarService: I18nPrimengCalendarService,
126 private ngZone: NgZone,
127 private hooks: HooksService,
128 private cd: ChangeDetectorRef
130 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
131 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
135 const defaultValues: any = {
137 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
138 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
139 waitTranscoding: 'true',
140 licence: this.serverConfig.defaults.publish.licence,
143 const obj: { [ id: string ]: BuildFormValidator } = {
144 name: VIDEO_NAME_VALIDATOR,
145 privacy: VIDEO_PRIVACY_VALIDATOR,
146 channelId: VIDEO_CHANNEL_VALIDATOR,
148 commentsEnabled: null,
149 downloadEnabled: null,
150 waitTranscoding: null,
151 category: VIDEO_CATEGORY_VALIDATOR,
152 licence: VIDEO_LICENCE_VALIDATOR,
153 language: VIDEO_LANGUAGE_VALIDATOR,
154 description: VIDEO_DESCRIPTION_VALIDATOR,
155 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
157 support: VIDEO_SUPPORT_VALIDATOR,
158 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
159 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
166 this.formValidatorService.updateFormGroup(
169 this.validationMessages,
174 this.form.addControl('captions', new FormArray([
176 language: new FormControl(),
177 captionfile: new FormControl()
181 this.trackChannelChange()
182 this.trackPrivacyChange()
184 this.formBuilt.emit()
188 this.serverConfig = this.serverService.getHTMLConfig()
192 this.pluginService.ensurePluginsAreLoaded('video-edit')
193 .then(() => this.updatePluginFields())
195 this.serverService.getVideoCategories()
196 .subscribe(res => this.videoCategories = res)
198 this.serverService.getVideoLicences()
199 .subscribe(res => this.videoLicences = res)
202 this.instanceService.getAbout(),
203 this.serverService.getVideoLanguages()
204 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
206 this.videoLanguages = res.languages
208 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
210 return res.about.instance.languages.includes(l.id)
211 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
212 : { ...l, group: $localize`All languages`, groupOrder: 2 }
214 .sort((a, b) => a.groupOrder - b.groupOrder)
217 this.serverService.getVideoPrivacies()
218 .subscribe(privacies => {
219 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
221 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
222 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
223 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
225 this.videoPrivacies.push({
226 id: this.SPECIAL_SCHEDULED_PRIVACY,
227 label: $localize`Scheduled`,
228 description: $localize`Hide the video until a specific date`
232 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
234 this.ngZone.runOutsideAngular(() => {
235 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
238 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
242 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
245 getExistingCaptions () {
246 return this.videoCaptions
247 .filter(c => c.action !== 'REMOVE')
248 .map(c => c.language.id)
251 onCaptionEdited (caption: VideoCaptionEdit) {
252 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
254 // Replace existing caption?
255 if (existingCaption) {
256 Object.assign(existingCaption, caption)
258 this.videoCaptions.push(
259 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
263 this.sortVideoCaptions()
266 deleteCaption (caption: VideoCaptionEdit) {
267 // Caption recovers his former state
268 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
269 caption.action = undefined
273 // This caption is not on the server, just remove it from our array
274 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
275 removeElementFromArray(this.videoCaptions, caption)
279 caption.action = 'REMOVE' as 'REMOVE'
282 openAddCaptionModal () {
283 this.videoCaptionAddModal.show()
286 isSaveReplayEnabled () {
287 return this.serverConfig.live.allowReplay
290 isPermanentLiveEnabled () {
291 return this.form.value['permanentLive'] === true
294 isLatencyModeEnabled () {
295 return this.serverConfig.live.latencySetting.enabled
298 isPluginFieldHidden (pluginField: PluginField) {
299 if (typeof pluginField.commonOptions.hidden !== 'function') return false
301 return pluginField.commonOptions.hidden({
302 formValues: this.form.value,
303 videoToUpdate: this.videoToUpdate,
304 liveVideo: this.liveVideo
308 getPluginsFields (tab: 'main' | 'plugin-settings') {
309 return this.pluginFields.filter(p => {
310 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
312 return wanted === tab
316 private sortVideoCaptions () {
317 this.videoCaptions.sort((v1, v2) => {
318 if (v1.language.label < v2.language.label) return -1
319 if (v1.language.label === v2.language.label) return 0
325 private async updatePluginFields () {
326 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
328 if (this.pluginFields.length === 0) return
330 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
331 const pluginValidationMessages: FormReactiveValidationMessages = {}
332 const pluginFormErrors: any = {}
333 const pluginDefaults: any = {}
335 for (const setting of this.pluginFields) {
336 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
338 const validator = async (control: AbstractControl) => {
339 if (!setting.commonOptions.error) return null
341 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
343 return error?.error ? { [setting.commonOptions.name]: error.text } : null
346 const name = setting.commonOptions.name
349 ASYNC_VALIDATORS: [ validator ],
354 pluginDefaults[name] = setting.commonOptions.default
357 this.pluginDataFormGroup = new FormGroup({})
358 this.formValidatorService.updateFormGroup(
359 this.pluginDataFormGroup,
361 pluginValidationMessages,
366 this.form.addControl('pluginData', this.pluginDataFormGroup)
367 this.formErrors['pluginData'] = pluginFormErrors
368 this.validationMessages['pluginData'] = pluginValidationMessages
370 this.cd.detectChanges()
371 this.pluginFieldsAdded.emit()
373 // Plugins may need other control values to calculate potential errors
374 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
377 private trackPrivacyChange () {
378 // We will update the schedule input and the wait transcoding checkbox validators
379 this.form.controls['privacy']
381 .pipe(map(res => parseInt(res.toString(), 10)))
385 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
388 const scheduleControl = this.form.get('schedulePublicationAt')
389 const waitTranscodingControl = this.form.get('waitTranscoding')
391 if (this.schedulePublicationEnabled) {
392 scheduleControl.setValidators([ Validators.required ])
394 waitTranscodingControl.disable()
395 waitTranscodingControl.setValue(false)
397 scheduleControl.clearValidators()
399 waitTranscodingControl.enable()
401 // Do not update the control value on first patch (values come from the server)
402 if (this.firstPatchDone === true) {
403 waitTranscodingControl.setValue(true)
407 scheduleControl.updateValueAndValidity()
408 waitTranscodingControl.updateValueAndValidity()
410 this.firstPatchDone = true
416 private trackChannelChange () {
417 // We will update the "support" field depending on the channel
418 this.form.controls['channelId']
420 .pipe(map(res => parseInt(res.toString(), 10)))
423 const oldChannelId = parseInt(this.form.value['channelId'], 10)
425 // Not initialized yet
426 if (isNaN(newChannelId)) return
427 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
428 if (!newChannel) return
430 // Wait support field update
432 const currentSupport = this.form.value['support']
434 // First time we set the channel?
435 if (isNaN(oldChannelId)) {
436 // Fill support if it's empty
437 if (!currentSupport) this.updateSupportField(newChannel.support)
442 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
443 if (!newChannel || !oldChannel) {
444 console.error('Cannot find new or old channel.')
448 // If the current support text is not the same than the old channel, the user updated it.
449 // We don't want the user to lose his text, so stop here
450 if (currentSupport && currentSupport !== oldChannel.support) return
452 // Update the support text with our new channel
453 this.updateSupportField(newChannel.support)
459 private updateSupportField (support: string) {
460 return this.form.patchValue({ support: support || '' })