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'
24 import { LiveVideo, ServerConfig, VideoConstant, VideoDetails, VideoPrivacy } from '@shared/models'
25 import { RegisterClientFormFieldOptions, RegisterClientVideoFieldOptions } from '@shared/models/plugins/register-client-form-field.model'
26 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
27 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
28 import { VideoEditType } from './video-edit.type'
30 type VideoLanguages = VideoConstant<string> & { group?: string }
32 commonOptions: RegisterClientFormFieldOptions
33 videoFormOptions: RegisterClientVideoFieldOptions
37 selector: 'my-video-edit',
38 styleUrls: [ './video-edit.component.scss' ],
39 templateUrl: './video-edit.component.html'
41 export class VideoEditComponent implements OnInit, OnDestroy {
42 @Input() form: FormGroup
43 @Input() formErrors: { [ id: string ]: string } = {}
44 @Input() validationMessages: FormReactiveValidationMessages = {}
46 @Input() videoToUpdate: VideoDetails
48 @Input() userVideoChannels: SelectChannelItem[] = []
49 @Input() schedulePublicationPossible = true
51 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
53 @Input() waitTranscodingEnabled = true
54 @Input() type: VideoEditType
55 @Input() liveVideo: LiveVideo
57 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
59 @Output() pluginFieldsAdded = new EventEmitter<void>()
61 // So that it can be accessed in the template
62 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
64 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
65 videoCategories: VideoConstant<number>[] = []
66 videoLicences: VideoConstant<number>[] = []
67 videoLanguages: VideoLanguages[] = []
69 pluginDataFormGroup: FormGroup
71 schedulePublicationEnabled = false
73 calendarLocale: any = {}
74 minScheduledDate = new Date()
75 myYearRange = '1880:' + (new Date()).getFullYear()
77 calendarTimezone: string
78 calendarDateFormat: string
80 serverConfig: ServerConfig
82 pluginFields: PluginField[] = []
84 private schedulerInterval: any
85 private firstPatchDone = false
86 private initialVideoCaptions: string[] = []
89 private formValidatorService: FormValidatorService,
90 private videoService: VideoService,
91 private serverService: ServerService,
92 private pluginService: PluginService,
93 private instanceService: InstanceService,
94 private i18nPrimengCalendarService: I18nPrimengCalendarService,
95 private ngZone: NgZone,
96 private hooks: HooksService
98 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
99 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
103 const defaultValues: any = {
105 commentsEnabled: 'true',
106 downloadEnabled: 'true',
107 waitTranscoding: 'true',
111 name: VIDEO_NAME_VALIDATOR,
112 privacy: VIDEO_PRIVACY_VALIDATOR,
113 channelId: VIDEO_CHANNEL_VALIDATOR,
115 commentsEnabled: null,
116 downloadEnabled: null,
117 waitTranscoding: null,
118 category: VIDEO_CATEGORY_VALIDATOR,
119 licence: VIDEO_LICENCE_VALIDATOR,
120 language: VIDEO_LANGUAGE_VALIDATOR,
121 description: VIDEO_DESCRIPTION_VALIDATOR,
122 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
124 support: VIDEO_SUPPORT_VALIDATOR,
125 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
126 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
132 this.formValidatorService.updateForm(
135 this.validationMessages,
140 this.form.addControl('captions', new FormArray([
142 language: new FormControl(),
143 captionfile: new FormControl()
147 this.trackChannelChange()
148 this.trackPrivacyChange()
149 this.trackLivePermanentFieldChange()
155 this.pluginService.ensurePluginsAreLoaded('video-edit')
156 .then(() => this.updatePluginFields())
158 this.serverService.getVideoCategories()
159 .subscribe(res => this.videoCategories = res)
161 this.serverService.getVideoLicences()
162 .subscribe(res => this.videoLicences = res)
165 this.instanceService.getAbout(),
166 this.serverService.getVideoLanguages()
167 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
169 this.videoLanguages = res.languages
171 return res.about.instance.languages.includes(l.id)
172 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
173 : { ...l, group: $localize`All languages`, groupOrder: 1 }
175 .sort((a, b) => a.groupOrder - b.groupOrder)
178 this.serverService.getVideoPrivacies()
179 .subscribe(privacies => {
180 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies)
181 if (this.schedulePublicationPossible) {
182 this.videoPrivacies.push({
183 id: this.SPECIAL_SCHEDULED_PRIVACY,
184 label: $localize`Scheduled`,
185 description: $localize`Hide the video until a specific date`
190 this.serverConfig = this.serverService.getTmpConfig()
191 this.serverService.getConfig()
192 .subscribe(config => this.serverConfig = config)
194 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
196 this.ngZone.runOutsideAngular(() => {
197 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
200 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
204 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
207 getExistingCaptions () {
208 return this.videoCaptions
209 .filter(c => c.action !== 'REMOVE')
210 .map(c => c.language.id)
213 onCaptionAdded (caption: VideoCaptionEdit) {
214 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
216 // Replace existing caption?
217 if (existingCaption) {
218 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
220 this.videoCaptions.push(
221 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
225 this.sortVideoCaptions()
228 async deleteCaption (caption: VideoCaptionEdit) {
229 // Caption recovers his former state
230 if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
231 caption.action = undefined
235 // This caption is not on the server, just remove it from our array
236 if (caption.action === 'CREATE') {
237 removeElementFromArray(this.videoCaptions, caption)
241 caption.action = 'REMOVE' as 'REMOVE'
244 openAddCaptionModal () {
245 this.videoCaptionAddModal.show()
248 isSaveReplayEnabled () {
249 return this.serverConfig.live.allowReplay
252 isPermanentLiveEnabled () {
253 return this.form.value['permanentLive'] === true
256 isPluginFieldHidden (pluginField: PluginField) {
257 if (typeof pluginField.commonOptions.hidden !== 'function') return false
259 return pluginField.commonOptions.hidden({
260 formValues: this.form.value,
261 videoToUpdate: this.videoToUpdate,
262 liveVideo: this.liveVideo
266 private sortVideoCaptions () {
267 this.videoCaptions.sort((v1, v2) => {
268 if (v1.language.label < v2.language.label) return -1
269 if (v1.language.label === v2.language.label) return 0
275 private updatePluginFields () {
276 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
278 if (this.pluginFields.length === 0) return
282 for (const setting of this.pluginFields) {
283 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
286 this.pluginDataFormGroup = new FormGroup(obj)
287 this.form.addControl('pluginData', this.pluginDataFormGroup)
289 this.pluginFieldsAdded.emit()
292 private trackPrivacyChange () {
293 // We will update the schedule input and the wait transcoding checkbox validators
294 this.form.controls[ 'privacy' ]
296 .pipe(map(res => parseInt(res.toString(), 10)))
300 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
303 const scheduleControl = this.form.get('schedulePublicationAt')
304 const waitTranscodingControl = this.form.get('waitTranscoding')
306 if (this.schedulePublicationEnabled) {
307 scheduleControl.setValidators([ Validators.required ])
309 waitTranscodingControl.disable()
310 waitTranscodingControl.setValue(false)
312 scheduleControl.clearValidators()
314 waitTranscodingControl.enable()
316 // Do not update the control value on first patch (values come from the server)
317 if (this.firstPatchDone === true) {
318 waitTranscodingControl.setValue(true)
322 scheduleControl.updateValueAndValidity()
323 waitTranscodingControl.updateValueAndValidity()
325 this.firstPatchDone = true
331 private trackChannelChange () {
332 // We will update the "support" field depending on the channel
333 this.form.controls[ 'channelId' ]
335 .pipe(map(res => parseInt(res.toString(), 10)))
338 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
340 // Not initialized yet
341 if (isNaN(newChannelId)) return
342 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
343 if (!newChannel) return
345 // Wait support field update
347 const currentSupport = this.form.value[ 'support' ]
349 // First time we set the channel?
350 if (isNaN(oldChannelId)) {
351 // Fill support if it's empty
352 if (!currentSupport) this.updateSupportField(newChannel.support)
357 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
358 if (!newChannel || !oldChannel) {
359 console.error('Cannot find new or old channel.')
363 // If the current support text is not the same than the old channel, the user updated it.
364 // We don't want the user to lose his text, so stop here
365 if (currentSupport && currentSupport !== oldChannel.support) return
367 // Update the support text with our new channel
368 this.updateSupportField(newChannel.support)
374 private trackLivePermanentFieldChange () {
375 // We will update the "support" field depending on the channel
376 this.form.controls['permanentLive']
380 const saveReplayControl = this.form.controls['saveReplay']
382 if (permanentLive === true) {
383 saveReplayControl.setValue(false)
384 saveReplayControl.disable()
386 saveReplayControl.enable()
392 private updateSupportField (support: string) {
393 return this.form.patchValue({ support: support || '' })