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 { VideoCaptionEditModalContentComponent } from './video-caption-edit-modal-content/video-caption-edit-modal-content.component'
39 import { VideoEditType } from './video-edit.type'
40 import { VideoSource } from '@shared/models/videos/video-source'
41 import { logger } from '@root-helpers/logger'
42 import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
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() waitTranscodingEnabled = true
70 @Input() type: VideoEditType
71 @Input() liveVideo: LiveVideo
73 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
75 @Output() formBuilt = new EventEmitter<void>()
76 @Output() pluginFieldsAdded = new EventEmitter<void>()
78 // So that it can be accessed in the template
79 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
81 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
82 videoCategories: VideoConstant<number>[] = []
83 videoLicences: VideoConstant<number>[] = []
84 videoLanguages: VideoLanguages[] = []
85 latencyModes: SelectOptionsItem[] = [
87 id: LiveVideoLatencyMode.SMALL_LATENCY,
88 label: $localize`Small latency`,
89 description: $localize`Reduce latency to ~15s disabling P2P`
92 id: LiveVideoLatencyMode.DEFAULT,
93 label: $localize`Default`,
94 description: $localize`Average latency of 30s`
97 id: LiveVideoLatencyMode.HIGH_LATENCY,
98 label: $localize`High latency`,
99 description: $localize`Average latency of 60s increasing P2P ratio`
103 pluginDataFormGroup: FormGroup
105 schedulePublicationEnabled = false
107 calendarLocale: any = {}
108 minScheduledDate = new Date()
109 myYearRange = '1880:' + (new Date()).getFullYear()
111 calendarTimezone: string
112 calendarDateFormat: string
114 serverConfig: HTMLServerConfig
116 pluginFields: PluginField[] = []
118 private schedulerInterval: any
119 private firstPatchDone = false
120 private initialVideoCaptions: string[] = []
123 private formValidatorService: FormValidatorService,
124 private videoService: VideoService,
125 private serverService: ServerService,
126 private pluginService: PluginService,
127 private instanceService: InstanceService,
128 private i18nPrimengCalendarService: I18nPrimengCalendarService,
129 private ngZone: NgZone,
130 private hooks: HooksService,
131 private cd: ChangeDetectorRef,
132 private modalService: NgbModal
134 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
135 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
139 const defaultValues: any = {
141 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
142 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
143 waitTranscoding: 'true',
144 licence: this.serverConfig.defaults.publish.licence,
147 const obj: { [ id: string ]: BuildFormValidator } = {
148 name: VIDEO_NAME_VALIDATOR,
149 privacy: VIDEO_PRIVACY_VALIDATOR,
150 channelId: VIDEO_CHANNEL_VALIDATOR,
152 commentsEnabled: null,
153 downloadEnabled: null,
154 waitTranscoding: null,
155 category: VIDEO_CATEGORY_VALIDATOR,
156 licence: VIDEO_LICENCE_VALIDATOR,
157 language: VIDEO_LANGUAGE_VALIDATOR,
158 description: VIDEO_DESCRIPTION_VALIDATOR,
159 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
161 support: VIDEO_SUPPORT_VALIDATOR,
162 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
163 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
170 this.formValidatorService.updateFormGroup(
173 this.validationMessages,
178 this.form.addControl('captions', new FormArray([
180 language: new FormControl(),
181 captionfile: new FormControl()
185 this.trackChannelChange()
186 this.trackPrivacyChange()
188 this.formBuilt.emit()
192 this.serverConfig = this.serverService.getHTMLConfig()
196 this.pluginService.ensurePluginsAreLoaded('video-edit')
197 .then(() => this.updatePluginFields())
199 this.serverService.getVideoCategories()
200 .subscribe(res => this.videoCategories = res)
202 this.serverService.getVideoLicences()
203 .subscribe(res => this.videoLicences = res)
206 this.instanceService.getAbout(),
207 this.serverService.getVideoLanguages()
208 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
210 this.videoLanguages = res.languages
212 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
214 return res.about.instance.languages.includes(l.id)
215 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
216 : { ...l, group: $localize`All languages`, groupOrder: 2 }
218 .sort((a, b) => a.groupOrder - b.groupOrder)
221 this.serverService.getVideoPrivacies()
222 .subscribe(privacies => {
223 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
225 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
226 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
227 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
229 this.videoPrivacies.push({
230 id: this.SPECIAL_SCHEDULED_PRIVACY,
231 label: $localize`Scheduled`,
232 description: $localize`Hide the video until a specific date`
236 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
238 this.ngZone.runOutsideAngular(() => {
239 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
242 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
246 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
249 getExistingCaptions () {
250 return this.videoCaptions
251 .filter(c => c.action !== 'REMOVE')
252 .map(c => c.language.id)
255 onCaptionEdited (caption: VideoCaptionEdit) {
256 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
258 // Replace existing caption?
259 if (existingCaption) {
260 Object.assign(existingCaption, caption)
262 this.videoCaptions.push(
263 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
267 this.sortVideoCaptions()
270 deleteCaption (caption: VideoCaptionEdit) {
271 // Caption recovers his former state
272 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
273 caption.action = undefined
277 // This caption is not on the server, just remove it from our array
278 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
279 removeElementFromArray(this.videoCaptions, caption)
283 caption.action = 'REMOVE' as 'REMOVE'
286 openAddCaptionModal () {
287 this.videoCaptionAddModal.show()
290 openEditCaptionModal (videoCaption: VideoCaptionWithPathEdit) {
291 const modalRef = this.modalService.open(VideoCaptionEditModalContentComponent, { centered: true, keyboard: false })
292 modalRef.componentInstance.videoCaption = videoCaption
293 modalRef.componentInstance.serverConfig = this.serverConfig
294 modalRef.componentInstance.captionEdited.subscribe(this.onCaptionEdited.bind(this))
297 isSaveReplayEnabled () {
298 return this.serverConfig.live.allowReplay
301 isPermanentLiveEnabled () {
302 return this.form.value['permanentLive'] === true
305 isLatencyModeEnabled () {
306 return this.serverConfig.live.latencySetting.enabled
309 isPluginFieldHidden (pluginField: PluginField) {
310 if (typeof pluginField.commonOptions.hidden !== 'function') return false
312 return pluginField.commonOptions.hidden({
313 formValues: this.form.value,
314 videoToUpdate: this.videoToUpdate,
315 liveVideo: this.liveVideo
319 getPluginsFields (tab: 'main' | 'plugin-settings') {
320 return this.pluginFields.filter(p => {
321 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
323 return wanted === tab
327 private sortVideoCaptions () {
328 this.videoCaptions.sort((v1, v2) => {
329 if (v1.language.label < v2.language.label) return -1
330 if (v1.language.label === v2.language.label) return 0
336 private async updatePluginFields () {
337 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
339 if (this.pluginFields.length === 0) return
341 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
342 const pluginValidationMessages: FormReactiveValidationMessages = {}
343 const pluginFormErrors: any = {}
344 const pluginDefaults: any = {}
346 for (const setting of this.pluginFields) {
347 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
349 const validator = async (control: AbstractControl) => {
350 if (!setting.commonOptions.error) return null
352 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
354 return error?.error ? { [setting.commonOptions.name]: error.text } : null
357 const name = setting.commonOptions.name
360 ASYNC_VALIDATORS: [ validator ],
365 pluginDefaults[name] = setting.commonOptions.default
368 this.pluginDataFormGroup = new FormGroup({})
369 this.formValidatorService.updateFormGroup(
370 this.pluginDataFormGroup,
372 pluginValidationMessages,
377 this.form.addControl('pluginData', this.pluginDataFormGroup)
378 this.formErrors['pluginData'] = pluginFormErrors
379 this.validationMessages['pluginData'] = pluginValidationMessages
381 this.cd.detectChanges()
382 this.pluginFieldsAdded.emit()
384 // Plugins may need other control values to calculate potential errors
385 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
388 private trackPrivacyChange () {
389 // We will update the schedule input and the wait transcoding checkbox validators
390 this.form.controls['privacy']
392 .pipe(map(res => parseInt(res.toString(), 10)))
396 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
399 const scheduleControl = this.form.get('schedulePublicationAt')
400 const waitTranscodingControl = this.form.get('waitTranscoding')
402 if (this.schedulePublicationEnabled) {
403 scheduleControl.setValidators([ Validators.required ])
405 waitTranscodingControl.disable()
406 waitTranscodingControl.setValue(false)
408 scheduleControl.clearValidators()
410 waitTranscodingControl.enable()
412 // Do not update the control value on first patch (values come from the server)
413 if (this.firstPatchDone === true) {
414 waitTranscodingControl.setValue(true)
418 scheduleControl.updateValueAndValidity()
419 waitTranscodingControl.updateValueAndValidity()
421 this.firstPatchDone = true
427 private trackChannelChange () {
428 // We will update the "support" field depending on the channel
429 this.form.controls['channelId']
431 .pipe(map(res => parseInt(res.toString(), 10)))
434 const oldChannelId = parseInt(this.form.value['channelId'], 10)
436 // Not initialized yet
437 if (isNaN(newChannelId)) return
438 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
439 if (!newChannel) return
441 // Wait support field update
443 const currentSupport = this.form.value['support']
445 // First time we set the channel?
446 if (isNaN(oldChannelId)) {
447 // Fill support if it's empty
448 if (!currentSupport) this.updateSupportField(newChannel.support)
453 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
454 if (!newChannel || !oldChannel) {
455 logger.error('Cannot find new or old channel.')
459 // If the current support text is not the same than the old channel, the user updated it.
460 // We don't want the user to lose his text, so stop here
461 if (currentSupport && currentSupport !== oldChannel.support) return
463 // Update the support text with our new channel
464 this.updateSupportField(newChannel.support)
470 private updateSupportField (support: string) {
471 return this.form.patchValue({ support: support || '' })