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()
183 this.trackLivePermanentFieldChange()
185 this.formBuilt.emit()
189 this.serverConfig = this.serverService.getHTMLConfig()
193 this.pluginService.ensurePluginsAreLoaded('video-edit')
194 .then(() => this.updatePluginFields())
196 this.serverService.getVideoCategories()
197 .subscribe(res => this.videoCategories = res)
199 this.serverService.getVideoLicences()
200 .subscribe(res => this.videoLicences = res)
203 this.instanceService.getAbout(),
204 this.serverService.getVideoLanguages()
205 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
207 this.videoLanguages = res.languages
209 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
211 return res.about.instance.languages.includes(l.id)
212 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
213 : { ...l, group: $localize`All languages`, groupOrder: 2 }
215 .sort((a, b) => a.groupOrder - b.groupOrder)
218 this.serverService.getVideoPrivacies()
219 .subscribe(privacies => {
220 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
222 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
223 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
224 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
226 this.videoPrivacies.push({
227 id: this.SPECIAL_SCHEDULED_PRIVACY,
228 label: $localize`Scheduled`,
229 description: $localize`Hide the video until a specific date`
233 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
235 this.ngZone.runOutsideAngular(() => {
236 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
239 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
243 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
246 getExistingCaptions () {
247 return this.videoCaptions
248 .filter(c => c.action !== 'REMOVE')
249 .map(c => c.language.id)
252 onCaptionEdited (caption: VideoCaptionEdit) {
253 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
255 // Replace existing caption?
256 if (existingCaption) {
257 Object.assign(existingCaption, caption)
259 this.videoCaptions.push(
260 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
264 this.sortVideoCaptions()
267 deleteCaption (caption: VideoCaptionEdit) {
268 // Caption recovers his former state
269 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
270 caption.action = undefined
274 // This caption is not on the server, just remove it from our array
275 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
276 removeElementFromArray(this.videoCaptions, caption)
280 caption.action = 'REMOVE' as 'REMOVE'
283 openAddCaptionModal () {
284 this.videoCaptionAddModal.show()
287 isSaveReplayEnabled () {
288 return this.serverConfig.live.allowReplay
291 isPermanentLiveEnabled () {
292 return this.form.value['permanentLive'] === true
295 isLatencyModeEnabled () {
296 return this.serverConfig.live.latencySetting.enabled
299 isPluginFieldHidden (pluginField: PluginField) {
300 if (typeof pluginField.commonOptions.hidden !== 'function') return false
302 return pluginField.commonOptions.hidden({
303 formValues: this.form.value,
304 videoToUpdate: this.videoToUpdate,
305 liveVideo: this.liveVideo
309 getPluginsFields (tab: 'main' | 'plugin-settings') {
310 return this.pluginFields.filter(p => {
311 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
313 return wanted === tab
317 private sortVideoCaptions () {
318 this.videoCaptions.sort((v1, v2) => {
319 if (v1.language.label < v2.language.label) return -1
320 if (v1.language.label === v2.language.label) return 0
326 private async updatePluginFields () {
327 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
329 if (this.pluginFields.length === 0) return
331 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
332 const pluginValidationMessages: FormReactiveValidationMessages = {}
333 const pluginFormErrors: any = {}
334 const pluginDefaults: any = {}
336 for (const setting of this.pluginFields) {
337 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
339 const validator = async (control: AbstractControl) => {
340 if (!setting.commonOptions.error) return null
342 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
344 return error?.error ? { [setting.commonOptions.name]: error.text } : null
347 const name = setting.commonOptions.name
350 ASYNC_VALIDATORS: [ validator ],
355 pluginDefaults[name] = setting.commonOptions.default
358 this.pluginDataFormGroup = new FormGroup({})
359 this.formValidatorService.updateFormGroup(
360 this.pluginDataFormGroup,
362 pluginValidationMessages,
367 this.form.addControl('pluginData', this.pluginDataFormGroup)
368 this.formErrors['pluginData'] = pluginFormErrors
369 this.validationMessages['pluginData'] = pluginValidationMessages
371 this.cd.detectChanges()
372 this.pluginFieldsAdded.emit()
374 // Plugins may need other control values to calculate potential errors
375 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
378 private trackPrivacyChange () {
379 // We will update the schedule input and the wait transcoding checkbox validators
380 this.form.controls['privacy']
382 .pipe(map(res => parseInt(res.toString(), 10)))
386 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
389 const scheduleControl = this.form.get('schedulePublicationAt')
390 const waitTranscodingControl = this.form.get('waitTranscoding')
392 if (this.schedulePublicationEnabled) {
393 scheduleControl.setValidators([ Validators.required ])
395 waitTranscodingControl.disable()
396 waitTranscodingControl.setValue(false)
398 scheduleControl.clearValidators()
400 waitTranscodingControl.enable()
402 // Do not update the control value on first patch (values come from the server)
403 if (this.firstPatchDone === true) {
404 waitTranscodingControl.setValue(true)
408 scheduleControl.updateValueAndValidity()
409 waitTranscodingControl.updateValueAndValidity()
411 this.firstPatchDone = true
417 private trackChannelChange () {
418 // We will update the "support" field depending on the channel
419 this.form.controls['channelId']
421 .pipe(map(res => parseInt(res.toString(), 10)))
424 const oldChannelId = parseInt(this.form.value['channelId'], 10)
426 // Not initialized yet
427 if (isNaN(newChannelId)) return
428 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
429 if (!newChannel) return
431 // Wait support field update
433 const currentSupport = this.form.value['support']
435 // First time we set the channel?
436 if (isNaN(oldChannelId)) {
437 // Fill support if it's empty
438 if (!currentSupport) this.updateSupportField(newChannel.support)
443 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
444 if (!newChannel || !oldChannel) {
445 console.error('Cannot find new or old channel.')
449 // If the current support text is not the same than the old channel, the user updated it.
450 // We don't want the user to lose his text, so stop here
451 if (currentSupport && currentSupport !== oldChannel.support) return
453 // Update the support text with our new channel
454 this.updateSupportField(newChannel.support)
460 private trackLivePermanentFieldChange () {
461 // We will update the "support" field depending on the channel
462 this.form.controls['permanentLive']
466 const saveReplayControl = this.form.controls['saveReplay']
468 if (permanentLive === true) {
469 saveReplayControl.setValue(false)
470 saveReplayControl.disable()
472 saveReplayControl.enable()
478 private updateSupportField (support: string) {
479 return this.form.patchValue({ support: support || '' })