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 { NgbModal } from '@ng-bootstrap/ng-bootstrap'
26 import { logger } from '@root-helpers/logger'
27 import { PluginInfo } from '@root-helpers/plugins-manager'
32 RegisterClientFormFieldOptions,
33 RegisterClientVideoFieldOptions,
37 } from '@shared/models'
38 import { VideoSource } from '@shared/models/videos/video-source'
39 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
40 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
41 import { VideoCaptionEditModalContentComponent } from './video-caption-edit-modal-content/video-caption-edit-modal-content.component'
42 import { VideoEditType } from './video-edit.type'
44 type VideoLanguages = VideoConstant<string> & { group?: string }
46 pluginInfo: PluginInfo
47 commonOptions: RegisterClientFormFieldOptions
48 videoFormOptions: RegisterClientVideoFieldOptions
52 selector: 'my-video-edit',
53 styleUrls: [ './video-edit.component.scss' ],
54 templateUrl: './video-edit.component.html'
56 export class VideoEditComponent implements OnInit, OnDestroy {
57 @Input() form: FormGroup
58 @Input() formErrors: { [ id: string ]: string } = {}
59 @Input() validationMessages: FormReactiveValidationMessages = {}
61 @Input() videoToUpdate: VideoDetails
63 @Input() userVideoChannels: SelectChannelItem[] = []
64 @Input() forbidScheduledPublication = true
66 @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
67 @Input() videoSource: VideoSource
69 @Input() hideWaitTranscoding = false
71 @Input() type: VideoEditType
72 @Input() liveVideo: LiveVideo
74 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
76 @Output() formBuilt = new EventEmitter<void>()
77 @Output() pluginFieldsAdded = new EventEmitter<void>()
79 // So that it can be accessed in the template
80 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
82 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
83 videoCategories: VideoConstant<number>[] = []
84 videoLicences: VideoConstant<number>[] = []
85 videoLanguages: VideoLanguages[] = []
86 latencyModes: SelectOptionsItem[] = [
88 id: LiveVideoLatencyMode.SMALL_LATENCY,
89 label: $localize`Small latency`,
90 description: $localize`Reduce latency to ~15s disabling P2P`
93 id: LiveVideoLatencyMode.DEFAULT,
94 label: $localize`Default`,
95 description: $localize`Average latency of 30s`
98 id: LiveVideoLatencyMode.HIGH_LATENCY,
99 label: $localize`High latency`,
100 description: $localize`Average latency of 60s increasing P2P ratio`
104 pluginDataFormGroup: FormGroup
106 schedulePublicationEnabled = false
108 calendarLocale: any = {}
109 minScheduledDate = new Date()
110 myYearRange = '1880:' + (new Date()).getFullYear()
112 calendarTimezone: string
113 calendarDateFormat: string
115 serverConfig: HTMLServerConfig
117 pluginFields: PluginField[] = []
119 private schedulerInterval: any
120 private firstPatchDone = false
121 private initialVideoCaptions: string[] = []
124 private formValidatorService: FormValidatorService,
125 private videoService: VideoService,
126 private serverService: ServerService,
127 private pluginService: PluginService,
128 private instanceService: InstanceService,
129 private i18nPrimengCalendarService: I18nPrimengCalendarService,
130 private ngZone: NgZone,
131 private hooks: HooksService,
132 private cd: ChangeDetectorRef,
133 private modalService: NgbModal
135 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
136 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
140 const defaultValues: any = {
142 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
143 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
144 waitTranscoding: true,
145 licence: this.serverConfig.defaults.publish.licence,
148 const obj: { [ id: string ]: BuildFormValidator } = {
149 name: VIDEO_NAME_VALIDATOR,
150 privacy: VIDEO_PRIVACY_VALIDATOR,
151 channelId: VIDEO_CHANNEL_VALIDATOR,
153 commentsEnabled: null,
154 downloadEnabled: null,
155 waitTranscoding: null,
156 category: VIDEO_CATEGORY_VALIDATOR,
157 licence: VIDEO_LICENCE_VALIDATOR,
158 language: VIDEO_LANGUAGE_VALIDATOR,
159 description: VIDEO_DESCRIPTION_VALIDATOR,
160 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
162 support: VIDEO_SUPPORT_VALIDATOR,
163 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
164 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
171 this.formValidatorService.updateFormGroup(
174 this.validationMessages,
179 this.form.addControl('captions', new FormArray([
181 language: new FormControl(),
182 captionfile: new FormControl()
186 this.trackChannelChange()
187 this.trackPrivacyChange()
189 this.formBuilt.emit()
193 this.serverConfig = this.serverService.getHTMLConfig()
197 this.pluginService.ensurePluginsAreLoaded('video-edit')
198 .then(() => this.updatePluginFields())
200 this.serverService.getVideoCategories()
201 .subscribe(res => this.videoCategories = res)
203 this.serverService.getVideoLicences()
204 .subscribe(res => this.videoLicences = res)
207 this.instanceService.getAbout(),
208 this.serverService.getVideoLanguages()
209 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
211 this.videoLanguages = res.languages
213 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
215 return res.about.instance.languages.includes(l.id)
216 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
217 : { ...l, group: $localize`All languages`, groupOrder: 2 }
219 .sort((a, b) => a.groupOrder - b.groupOrder)
222 this.serverService.getVideoPrivacies()
223 .subscribe(privacies => {
224 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
226 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
227 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
228 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
230 this.videoPrivacies.push({
231 id: this.SPECIAL_SCHEDULED_PRIVACY,
232 label: $localize`Scheduled`,
233 description: $localize`Hide the video until a specific date`
237 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
239 this.ngZone.runOutsideAngular(() => {
240 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
243 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
247 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
250 getExistingCaptions () {
251 return this.videoCaptions
252 .filter(c => c.action !== 'REMOVE')
253 .map(c => c.language.id)
256 onCaptionEdited (caption: VideoCaptionEdit) {
257 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
259 // Replace existing caption?
260 if (existingCaption) {
261 Object.assign(existingCaption, caption)
263 this.videoCaptions.push(
264 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
268 this.sortVideoCaptions()
271 deleteCaption (caption: VideoCaptionEdit) {
272 // Caption recovers his former state
273 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
274 caption.action = undefined
278 // This caption is not on the server, just remove it from our array
279 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
280 removeElementFromArray(this.videoCaptions, caption)
284 caption.action = 'REMOVE' as 'REMOVE'
287 openAddCaptionModal () {
288 this.videoCaptionAddModal.show()
291 openEditCaptionModal (videoCaption: VideoCaptionWithPathEdit) {
292 const modalRef = this.modalService.open(VideoCaptionEditModalContentComponent, { centered: true, keyboard: false })
293 modalRef.componentInstance.videoCaption = videoCaption
294 modalRef.componentInstance.serverConfig = this.serverConfig
295 modalRef.componentInstance.captionEdited.subscribe(this.onCaptionEdited.bind(this))
298 isSaveReplayEnabled () {
299 return this.serverConfig.live.allowReplay
302 isPermanentLiveEnabled () {
303 return this.form.value['permanentLive'] === true
306 isLatencyModeEnabled () {
307 return this.serverConfig.live.latencySetting.enabled
310 isPluginFieldHidden (pluginField: PluginField) {
311 if (typeof pluginField.commonOptions.hidden !== 'function') return false
313 return pluginField.commonOptions.hidden({
314 formValues: this.form.value,
315 videoToUpdate: this.videoToUpdate,
316 liveVideo: this.liveVideo
320 getPluginsFields (tab: 'main' | 'plugin-settings') {
321 return this.pluginFields.filter(p => {
322 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
324 return wanted === tab
328 private sortVideoCaptions () {
329 this.videoCaptions.sort((v1, v2) => {
330 if (v1.language.label < v2.language.label) return -1
331 if (v1.language.label === v2.language.label) return 0
337 private async updatePluginFields () {
338 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
340 if (this.pluginFields.length === 0) return
342 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
343 const pluginValidationMessages: FormReactiveValidationMessages = {}
344 const pluginFormErrors: any = {}
345 const pluginDefaults: any = {}
347 for (const setting of this.pluginFields) {
348 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
350 const validator = async (control: AbstractControl) => {
351 if (!setting.commonOptions.error) return null
353 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
355 return error?.error ? { [setting.commonOptions.name]: error.text } : null
358 const name = setting.commonOptions.name
361 ASYNC_VALIDATORS: [ validator ],
366 pluginDefaults[name] = setting.commonOptions.default
369 this.pluginDataFormGroup = new FormGroup({})
370 this.formValidatorService.updateFormGroup(
371 this.pluginDataFormGroup,
373 pluginValidationMessages,
378 this.form.addControl('pluginData', this.pluginDataFormGroup)
379 this.formErrors['pluginData'] = pluginFormErrors
380 this.validationMessages['pluginData'] = pluginValidationMessages
382 this.cd.detectChanges()
383 this.pluginFieldsAdded.emit()
385 // Plugins may need other control values to calculate potential errors
386 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
389 private trackPrivacyChange () {
390 // We will update the schedule input and the wait transcoding checkbox validators
391 this.form.controls['privacy']
393 .pipe(map(res => parseInt(res.toString(), 10)))
397 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
400 const scheduleControl = this.form.get('schedulePublicationAt')
401 const waitTranscodingControl = this.form.get('waitTranscoding')
403 if (this.schedulePublicationEnabled) {
404 scheduleControl.setValidators([ Validators.required ])
406 waitTranscodingControl.disable()
407 waitTranscodingControl.setValue(false)
409 scheduleControl.clearValidators()
411 waitTranscodingControl.enable()
413 // Do not update the control value on first patch (values come from the server)
414 if (this.firstPatchDone === true) {
415 waitTranscodingControl.setValue(true)
419 scheduleControl.updateValueAndValidity()
420 waitTranscodingControl.updateValueAndValidity()
422 this.firstPatchDone = true
428 private trackChannelChange () {
429 // We will update the "support" field depending on the channel
430 this.form.controls['channelId']
432 .pipe(map(res => parseInt(res.toString(), 10)))
435 const oldChannelId = parseInt(this.form.value['channelId'], 10)
437 // Not initialized yet
438 if (isNaN(newChannelId)) return
439 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
440 if (!newChannel) return
442 // Wait support field update
444 const currentSupport = this.form.value['support']
446 // First time we set the channel?
447 if (isNaN(oldChannelId)) {
448 // Fill support if it's empty
449 if (!currentSupport) this.updateSupportField(newChannel.support)
454 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
455 if (!newChannel || !oldChannel) {
456 logger.error('Cannot find new or old channel.')
460 // If the current support text is not the same than the old channel, the user updated it.
461 // We don't want the user to lose his text, so stop here
462 if (currentSupport && currentSupport !== oldChannel.support) return
464 // Update the support text with our new channel
465 this.updateSupportField(newChannel.support)
471 private updateSupportField (support: string) {
472 return this.form.patchValue({ support: support || '' })