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'
40 import { VideoSource } from '@shared/models/videos/video-source'
42 type VideoLanguages = VideoConstant<string> & { group?: string }
44 pluginInfo: PluginInfo
45 commonOptions: RegisterClientFormFieldOptions
46 videoFormOptions: RegisterClientVideoFieldOptions
50 selector: 'my-video-edit',
51 styleUrls: [ './video-edit.component.scss' ],
52 templateUrl: './video-edit.component.html'
54 export class VideoEditComponent implements OnInit, OnDestroy {
55 @Input() form: FormGroup
56 @Input() formErrors: { [ id: string ]: string } = {}
57 @Input() validationMessages: FormReactiveValidationMessages = {}
59 @Input() videoToUpdate: VideoDetails
61 @Input() userVideoChannels: SelectChannelItem[] = []
62 @Input() forbidScheduledPublication = true
64 @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
65 @Input() videoSource: VideoSource
67 @Input() waitTranscodingEnabled = true
68 @Input() type: VideoEditType
69 @Input() liveVideo: LiveVideo
71 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
72 @ViewChild('videoCaptionEditModal', { static: true }) editCaptionModal: VideoCaptionEditModalComponent
74 @Output() formBuilt = new EventEmitter<void>()
75 @Output() pluginFieldsAdded = new EventEmitter<void>()
77 // So that it can be accessed in the template
78 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
80 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
81 videoCategories: VideoConstant<number>[] = []
82 videoLicences: VideoConstant<number>[] = []
83 videoLanguages: VideoLanguages[] = []
84 latencyModes: SelectOptionsItem[] = [
86 id: LiveVideoLatencyMode.SMALL_LATENCY,
87 label: $localize`Small latency`,
88 description: $localize`Reduce latency to ~15s disabling P2P`
91 id: LiveVideoLatencyMode.DEFAULT,
92 label: $localize`Default`,
93 description: $localize`Average latency of 30s`
96 id: LiveVideoLatencyMode.HIGH_LATENCY,
97 label: $localize`High latency`,
98 description: $localize`Average latency of 60s increasing P2P ratio`
102 pluginDataFormGroup: FormGroup
104 schedulePublicationEnabled = false
106 calendarLocale: any = {}
107 minScheduledDate = new Date()
108 myYearRange = '1880:' + (new Date()).getFullYear()
110 calendarTimezone: string
111 calendarDateFormat: string
113 serverConfig: HTMLServerConfig
115 pluginFields: PluginField[] = []
117 private schedulerInterval: any
118 private firstPatchDone = false
119 private initialVideoCaptions: string[] = []
122 private formValidatorService: FormValidatorService,
123 private videoService: VideoService,
124 private serverService: ServerService,
125 private pluginService: PluginService,
126 private instanceService: InstanceService,
127 private i18nPrimengCalendarService: I18nPrimengCalendarService,
128 private ngZone: NgZone,
129 private hooks: HooksService,
130 private cd: ChangeDetectorRef
132 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
133 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
137 const defaultValues: any = {
139 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
140 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
141 waitTranscoding: 'true',
142 licence: this.serverConfig.defaults.publish.licence,
145 const obj: { [ id: string ]: BuildFormValidator } = {
146 name: VIDEO_NAME_VALIDATOR,
147 privacy: VIDEO_PRIVACY_VALIDATOR,
148 channelId: VIDEO_CHANNEL_VALIDATOR,
150 commentsEnabled: null,
151 downloadEnabled: null,
152 waitTranscoding: null,
153 category: VIDEO_CATEGORY_VALIDATOR,
154 licence: VIDEO_LICENCE_VALIDATOR,
155 language: VIDEO_LANGUAGE_VALIDATOR,
156 description: VIDEO_DESCRIPTION_VALIDATOR,
157 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
159 support: VIDEO_SUPPORT_VALIDATOR,
160 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
161 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
168 this.formValidatorService.updateFormGroup(
171 this.validationMessages,
176 this.form.addControl('captions', new FormArray([
178 language: new FormControl(),
179 captionfile: new FormControl()
183 this.trackChannelChange()
184 this.trackPrivacyChange()
186 this.formBuilt.emit()
190 this.serverConfig = this.serverService.getHTMLConfig()
194 this.pluginService.ensurePluginsAreLoaded('video-edit')
195 .then(() => this.updatePluginFields())
197 this.serverService.getVideoCategories()
198 .subscribe(res => this.videoCategories = res)
200 this.serverService.getVideoLicences()
201 .subscribe(res => this.videoLicences = res)
204 this.instanceService.getAbout(),
205 this.serverService.getVideoLanguages()
206 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
208 this.videoLanguages = res.languages
210 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
212 return res.about.instance.languages.includes(l.id)
213 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
214 : { ...l, group: $localize`All languages`, groupOrder: 2 }
216 .sort((a, b) => a.groupOrder - b.groupOrder)
219 this.serverService.getVideoPrivacies()
220 .subscribe(privacies => {
221 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
223 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
224 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
225 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
227 this.videoPrivacies.push({
228 id: this.SPECIAL_SCHEDULED_PRIVACY,
229 label: $localize`Scheduled`,
230 description: $localize`Hide the video until a specific date`
234 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
236 this.ngZone.runOutsideAngular(() => {
237 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
240 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
244 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
247 getExistingCaptions () {
248 return this.videoCaptions
249 .filter(c => c.action !== 'REMOVE')
250 .map(c => c.language.id)
253 onCaptionEdited (caption: VideoCaptionEdit) {
254 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
256 // Replace existing caption?
257 if (existingCaption) {
258 Object.assign(existingCaption, caption)
260 this.videoCaptions.push(
261 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
265 this.sortVideoCaptions()
268 deleteCaption (caption: VideoCaptionEdit) {
269 // Caption recovers his former state
270 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
271 caption.action = undefined
275 // This caption is not on the server, just remove it from our array
276 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
277 removeElementFromArray(this.videoCaptions, caption)
281 caption.action = 'REMOVE' as 'REMOVE'
284 openAddCaptionModal () {
285 this.videoCaptionAddModal.show()
288 isSaveReplayEnabled () {
289 return this.serverConfig.live.allowReplay
292 isPermanentLiveEnabled () {
293 return this.form.value['permanentLive'] === true
296 isLatencyModeEnabled () {
297 return this.serverConfig.live.latencySetting.enabled
300 isPluginFieldHidden (pluginField: PluginField) {
301 if (typeof pluginField.commonOptions.hidden !== 'function') return false
303 return pluginField.commonOptions.hidden({
304 formValues: this.form.value,
305 videoToUpdate: this.videoToUpdate,
306 liveVideo: this.liveVideo
310 getPluginsFields (tab: 'main' | 'plugin-settings') {
311 return this.pluginFields.filter(p => {
312 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
314 return wanted === tab
318 private sortVideoCaptions () {
319 this.videoCaptions.sort((v1, v2) => {
320 if (v1.language.label < v2.language.label) return -1
321 if (v1.language.label === v2.language.label) return 0
327 private async updatePluginFields () {
328 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
330 if (this.pluginFields.length === 0) return
332 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
333 const pluginValidationMessages: FormReactiveValidationMessages = {}
334 const pluginFormErrors: any = {}
335 const pluginDefaults: any = {}
337 for (const setting of this.pluginFields) {
338 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
340 const validator = async (control: AbstractControl) => {
341 if (!setting.commonOptions.error) return null
343 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
345 return error?.error ? { [setting.commonOptions.name]: error.text } : null
348 const name = setting.commonOptions.name
351 ASYNC_VALIDATORS: [ validator ],
356 pluginDefaults[name] = setting.commonOptions.default
359 this.pluginDataFormGroup = new FormGroup({})
360 this.formValidatorService.updateFormGroup(
361 this.pluginDataFormGroup,
363 pluginValidationMessages,
368 this.form.addControl('pluginData', this.pluginDataFormGroup)
369 this.formErrors['pluginData'] = pluginFormErrors
370 this.validationMessages['pluginData'] = pluginValidationMessages
372 this.cd.detectChanges()
373 this.pluginFieldsAdded.emit()
375 // Plugins may need other control values to calculate potential errors
376 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
379 private trackPrivacyChange () {
380 // We will update the schedule input and the wait transcoding checkbox validators
381 this.form.controls['privacy']
383 .pipe(map(res => parseInt(res.toString(), 10)))
387 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
390 const scheduleControl = this.form.get('schedulePublicationAt')
391 const waitTranscodingControl = this.form.get('waitTranscoding')
393 if (this.schedulePublicationEnabled) {
394 scheduleControl.setValidators([ Validators.required ])
396 waitTranscodingControl.disable()
397 waitTranscodingControl.setValue(false)
399 scheduleControl.clearValidators()
401 waitTranscodingControl.enable()
403 // Do not update the control value on first patch (values come from the server)
404 if (this.firstPatchDone === true) {
405 waitTranscodingControl.setValue(true)
409 scheduleControl.updateValueAndValidity()
410 waitTranscodingControl.updateValueAndValidity()
412 this.firstPatchDone = true
418 private trackChannelChange () {
419 // We will update the "support" field depending on the channel
420 this.form.controls['channelId']
422 .pipe(map(res => parseInt(res.toString(), 10)))
425 const oldChannelId = parseInt(this.form.value['channelId'], 10)
427 // Not initialized yet
428 if (isNaN(newChannelId)) return
429 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
430 if (!newChannel) return
432 // Wait support field update
434 const currentSupport = this.form.value['support']
436 // First time we set the channel?
437 if (isNaN(oldChannelId)) {
438 // Fill support if it's empty
439 if (!currentSupport) this.updateSupportField(newChannel.support)
444 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
445 if (!newChannel || !oldChannel) {
446 console.error('Cannot find new or old channel.')
450 // If the current support text is not the same than the old channel, the user updated it.
451 // We don't want the user to lose his text, so stop here
452 if (currentSupport && currentSupport !== oldChannel.support) return
454 // Update the support text with our new channel
455 this.updateSupportField(newChannel.support)
461 private updateSupportField (support: string) {
462 return this.form.patchValue({ support: support || '' })