1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { SelectChannelItem } from 'src/types/select-options-item.model'
4 import { Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms'
6 import { HooksService, PluginService, ServerService } from '@app/core'
7 import { removeElementFromArray } from '@app/helpers'
9 VIDEO_CATEGORY_VALIDATOR,
10 VIDEO_CHANNEL_VALIDATOR,
11 VIDEO_DESCRIPTION_VALIDATOR,
12 VIDEO_LANGUAGE_VALIDATOR,
13 VIDEO_LICENCE_VALIDATOR,
15 VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
16 VIDEO_PRIVACY_VALIDATOR,
17 VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
18 VIDEO_SUPPORT_VALIDATOR,
19 VIDEO_TAGS_ARRAY_VALIDATOR
20 } from '@app/shared/form-validators/video-validators'
21 import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
22 import { InstanceService } from '@app/shared/shared-instance'
23 import { VideoCaptionEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
27 RegisterClientFormFieldOptions,
28 RegisterClientVideoFieldOptions,
32 } from '@shared/models'
33 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
34 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
35 import { VideoEditType } from './video-edit.type'
37 type VideoLanguages = VideoConstant<string> & { group?: string }
39 commonOptions: RegisterClientFormFieldOptions
40 videoFormOptions: RegisterClientVideoFieldOptions
44 selector: 'my-video-edit',
45 styleUrls: [ './video-edit.component.scss' ],
46 templateUrl: './video-edit.component.html'
48 export class VideoEditComponent implements OnInit, OnDestroy {
49 @Input() form: FormGroup
50 @Input() formErrors: { [ id: string ]: string } = {}
51 @Input() validationMessages: FormReactiveValidationMessages = {}
53 @Input() videoToUpdate: VideoDetails
55 @Input() userVideoChannels: SelectChannelItem[] = []
56 @Input() schedulePublicationPossible = true
58 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
60 @Input() waitTranscodingEnabled = true
61 @Input() type: VideoEditType
62 @Input() liveVideo: LiveVideo
64 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
66 @Output() formBuilt = new EventEmitter<void>()
67 @Output() pluginFieldsAdded = new EventEmitter<void>()
69 // So that it can be accessed in the template
70 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
72 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
73 videoCategories: VideoConstant<number>[] = []
74 videoLicences: VideoConstant<number>[] = []
75 videoLanguages: VideoLanguages[] = []
77 pluginDataFormGroup: FormGroup
79 schedulePublicationEnabled = false
81 calendarLocale: any = {}
82 minScheduledDate = new Date()
83 myYearRange = '1880:' + (new Date()).getFullYear()
85 calendarTimezone: string
86 calendarDateFormat: string
88 serverConfig: HTMLServerConfig
90 pluginFields: PluginField[] = []
92 private schedulerInterval: any
93 private firstPatchDone = false
94 private initialVideoCaptions: string[] = []
97 private formValidatorService: FormValidatorService,
98 private videoService: VideoService,
99 private serverService: ServerService,
100 private pluginService: PluginService,
101 private instanceService: InstanceService,
102 private i18nPrimengCalendarService: I18nPrimengCalendarService,
103 private ngZone: NgZone,
104 private hooks: HooksService
106 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
107 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
111 const defaultValues: any = {
113 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
114 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
115 waitTranscoding: 'true',
116 licence: this.serverConfig.defaults.publish.licence,
120 name: VIDEO_NAME_VALIDATOR,
121 privacy: VIDEO_PRIVACY_VALIDATOR,
122 channelId: VIDEO_CHANNEL_VALIDATOR,
124 commentsEnabled: null,
125 downloadEnabled: null,
126 waitTranscoding: null,
127 category: VIDEO_CATEGORY_VALIDATOR,
128 licence: VIDEO_LICENCE_VALIDATOR,
129 language: VIDEO_LANGUAGE_VALIDATOR,
130 description: VIDEO_DESCRIPTION_VALIDATOR,
131 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
133 support: VIDEO_SUPPORT_VALIDATOR,
134 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
135 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
141 this.formValidatorService.updateForm(
144 this.validationMessages,
149 this.form.addControl('captions', new FormArray([
151 language: new FormControl(),
152 captionfile: new FormControl()
156 this.trackChannelChange()
157 this.trackPrivacyChange()
158 this.trackLivePermanentFieldChange()
160 this.formBuilt.emit()
164 this.serverConfig = this.serverService.getHTMLConfig()
168 this.pluginService.ensurePluginsAreLoaded('video-edit')
169 .then(() => this.updatePluginFields())
171 this.serverService.getVideoCategories()
172 .subscribe(res => this.videoCategories = res)
174 this.serverService.getVideoLicences()
175 .subscribe(res => this.videoLicences = res)
178 this.instanceService.getAbout(),
179 this.serverService.getVideoLanguages()
180 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
182 this.videoLanguages = res.languages
184 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
186 return res.about.instance.languages.includes(l.id)
187 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
188 : { ...l, group: $localize`All languages`, groupOrder: 2 }
190 .sort((a, b) => a.groupOrder - b.groupOrder)
193 this.serverService.getVideoPrivacies()
194 .subscribe(privacies => {
195 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
197 if (this.schedulePublicationPossible) {
198 this.videoPrivacies.push({
199 id: this.SPECIAL_SCHEDULED_PRIVACY,
200 label: $localize`Scheduled`,
201 description: $localize`Hide the video until a specific date`
206 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
208 this.ngZone.runOutsideAngular(() => {
209 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
212 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
216 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
219 getExistingCaptions () {
220 return this.videoCaptions
221 .filter(c => c.action !== 'REMOVE')
222 .map(c => c.language.id)
225 onCaptionAdded (caption: VideoCaptionEdit) {
226 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
228 // Replace existing caption?
229 if (existingCaption) {
230 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
232 this.videoCaptions.push(
233 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
237 this.sortVideoCaptions()
240 deleteCaption (caption: VideoCaptionEdit) {
241 // Caption recovers his former state
242 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
243 caption.action = undefined
247 // This caption is not on the server, just remove it from our array
248 if (caption.action === 'CREATE') {
249 removeElementFromArray(this.videoCaptions, caption)
253 caption.action = 'REMOVE' as 'REMOVE'
256 openAddCaptionModal () {
257 this.videoCaptionAddModal.show()
260 isSaveReplayEnabled () {
261 return this.serverConfig.live.allowReplay
264 isPermanentLiveEnabled () {
265 return this.form.value['permanentLive'] === true
268 isPluginFieldHidden (pluginField: PluginField) {
269 if (typeof pluginField.commonOptions.hidden !== 'function') return false
271 return pluginField.commonOptions.hidden({
272 formValues: this.form.value,
273 videoToUpdate: this.videoToUpdate,
274 liveVideo: this.liveVideo
278 private sortVideoCaptions () {
279 this.videoCaptions.sort((v1, v2) => {
280 if (v1.language.label < v2.language.label) return -1
281 if (v1.language.label === v2.language.label) return 0
287 private updatePluginFields () {
288 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
290 if (this.pluginFields.length === 0) return
294 for (const setting of this.pluginFields) {
295 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
298 this.pluginDataFormGroup = new FormGroup(obj)
299 this.form.addControl('pluginData', this.pluginDataFormGroup)
301 this.pluginFieldsAdded.emit()
304 private trackPrivacyChange () {
305 // We will update the schedule input and the wait transcoding checkbox validators
306 this.form.controls['privacy']
308 .pipe(map(res => parseInt(res.toString(), 10)))
312 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
315 const scheduleControl = this.form.get('schedulePublicationAt')
316 const waitTranscodingControl = this.form.get('waitTranscoding')
318 if (this.schedulePublicationEnabled) {
319 scheduleControl.setValidators([ Validators.required ])
321 waitTranscodingControl.disable()
322 waitTranscodingControl.setValue(false)
324 scheduleControl.clearValidators()
326 waitTranscodingControl.enable()
328 // Do not update the control value on first patch (values come from the server)
329 if (this.firstPatchDone === true) {
330 waitTranscodingControl.setValue(true)
334 scheduleControl.updateValueAndValidity()
335 waitTranscodingControl.updateValueAndValidity()
337 this.firstPatchDone = true
343 private trackChannelChange () {
344 // We will update the "support" field depending on the channel
345 this.form.controls['channelId']
347 .pipe(map(res => parseInt(res.toString(), 10)))
350 const oldChannelId = parseInt(this.form.value['channelId'], 10)
352 // Not initialized yet
353 if (isNaN(newChannelId)) return
354 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
355 if (!newChannel) return
357 // Wait support field update
359 const currentSupport = this.form.value['support']
361 // First time we set the channel?
362 if (isNaN(oldChannelId)) {
363 // Fill support if it's empty
364 if (!currentSupport) this.updateSupportField(newChannel.support)
369 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
370 if (!newChannel || !oldChannel) {
371 console.error('Cannot find new or old channel.')
375 // If the current support text is not the same than the old channel, the user updated it.
376 // We don't want the user to lose his text, so stop here
377 if (currentSupport && currentSupport !== oldChannel.support) return
379 // Update the support text with our new channel
380 this.updateSupportField(newChannel.support)
386 private trackLivePermanentFieldChange () {
387 // We will update the "support" field depending on the channel
388 this.form.controls['permanentLive']
392 const saveReplayControl = this.form.controls['saveReplay']
394 if (permanentLive === true) {
395 saveReplayControl.setValue(false)
396 saveReplayControl.disable()
398 saveReplayControl.enable()
404 private updateSupportField (support: string) {
405 return this.form.patchValue({ support: support || '' })