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'
26 RegisterClientFormFieldOptions,
27 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() pluginFieldsAdded = new EventEmitter<void>()
68 // So that it can be accessed in the template
69 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
71 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
72 videoCategories: VideoConstant<number>[] = []
73 videoLicences: VideoConstant<number>[] = []
74 videoLanguages: VideoLanguages[] = []
76 pluginDataFormGroup: FormGroup
78 schedulePublicationEnabled = false
80 calendarLocale: any = {}
81 minScheduledDate = new Date()
82 myYearRange = '1880:' + (new Date()).getFullYear()
84 calendarTimezone: string
85 calendarDateFormat: string
87 serverConfig: ServerConfig
89 pluginFields: PluginField[] = []
91 private schedulerInterval: any
92 private firstPatchDone = false
93 private initialVideoCaptions: string[] = []
96 private formValidatorService: FormValidatorService,
97 private videoService: VideoService,
98 private serverService: ServerService,
99 private pluginService: PluginService,
100 private instanceService: InstanceService,
101 private i18nPrimengCalendarService: I18nPrimengCalendarService,
102 private ngZone: NgZone,
103 private hooks: HooksService
105 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
106 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
110 const defaultValues: any = {
112 commentsEnabled: 'true',
113 downloadEnabled: 'true',
114 waitTranscoding: 'true',
118 name: VIDEO_NAME_VALIDATOR,
119 privacy: VIDEO_PRIVACY_VALIDATOR,
120 channelId: VIDEO_CHANNEL_VALIDATOR,
122 commentsEnabled: null,
123 downloadEnabled: null,
124 waitTranscoding: null,
125 category: VIDEO_CATEGORY_VALIDATOR,
126 licence: VIDEO_LICENCE_VALIDATOR,
127 language: VIDEO_LANGUAGE_VALIDATOR,
128 description: VIDEO_DESCRIPTION_VALIDATOR,
129 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
131 support: VIDEO_SUPPORT_VALIDATOR,
132 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
133 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
139 this.formValidatorService.updateForm(
142 this.validationMessages,
147 this.form.addControl('captions', new FormArray([
149 language: new FormControl(),
150 captionfile: new FormControl()
154 this.trackChannelChange()
155 this.trackPrivacyChange()
156 this.trackLivePermanentFieldChange()
162 this.pluginService.ensurePluginsAreLoaded('video-edit')
163 .then(() => this.updatePluginFields())
165 this.serverService.getVideoCategories()
166 .subscribe(res => this.videoCategories = res)
168 this.serverService.getVideoLicences()
169 .subscribe(res => this.videoLicences = res)
172 this.instanceService.getAbout(),
173 this.serverService.getVideoLanguages()
174 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
176 this.videoLanguages = res.languages
178 return res.about.instance.languages.includes(l.id)
179 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
180 : { ...l, group: $localize`All languages`, groupOrder: 1 }
182 .sort((a, b) => a.groupOrder - b.groupOrder)
185 this.serverService.getVideoPrivacies()
186 .subscribe(privacies => {
187 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies)
188 if (this.schedulePublicationPossible) {
189 this.videoPrivacies.push({
190 id: this.SPECIAL_SCHEDULED_PRIVACY,
191 label: $localize`Scheduled`,
192 description: $localize`Hide the video until a specific date`
197 this.serverConfig = this.serverService.getTmpConfig()
198 this.serverService.getConfig()
199 .subscribe(config => this.serverConfig = config)
201 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
203 this.ngZone.runOutsideAngular(() => {
204 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
207 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
211 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
214 getExistingCaptions () {
215 return this.videoCaptions
216 .filter(c => c.action !== 'REMOVE')
217 .map(c => c.language.id)
220 onCaptionAdded (caption: VideoCaptionEdit) {
221 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
223 // Replace existing caption?
224 if (existingCaption) {
225 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
227 this.videoCaptions.push(
228 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
232 this.sortVideoCaptions()
235 async deleteCaption (caption: VideoCaptionEdit) {
236 // Caption recovers his former state
237 if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
238 caption.action = undefined
242 // This caption is not on the server, just remove it from our array
243 if (caption.action === 'CREATE') {
244 removeElementFromArray(this.videoCaptions, caption)
248 caption.action = 'REMOVE' as 'REMOVE'
251 openAddCaptionModal () {
252 this.videoCaptionAddModal.show()
255 isSaveReplayEnabled () {
256 return this.serverConfig.live.allowReplay
259 isPermanentLiveEnabled () {
260 return this.form.value['permanentLive'] === true
263 isPluginFieldHidden (pluginField: PluginField) {
264 if (typeof pluginField.commonOptions.hidden !== 'function') return false
266 return pluginField.commonOptions.hidden({
267 formValues: this.form.value,
268 videoToUpdate: this.videoToUpdate,
269 liveVideo: this.liveVideo
273 private sortVideoCaptions () {
274 this.videoCaptions.sort((v1, v2) => {
275 if (v1.language.label < v2.language.label) return -1
276 if (v1.language.label === v2.language.label) return 0
282 private updatePluginFields () {
283 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
285 if (this.pluginFields.length === 0) return
289 for (const setting of this.pluginFields) {
290 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
293 this.pluginDataFormGroup = new FormGroup(obj)
294 this.form.addControl('pluginData', this.pluginDataFormGroup)
296 this.pluginFieldsAdded.emit()
299 private trackPrivacyChange () {
300 // We will update the schedule input and the wait transcoding checkbox validators
301 this.form.controls[ 'privacy' ]
303 .pipe(map(res => parseInt(res.toString(), 10)))
307 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
310 const scheduleControl = this.form.get('schedulePublicationAt')
311 const waitTranscodingControl = this.form.get('waitTranscoding')
313 if (this.schedulePublicationEnabled) {
314 scheduleControl.setValidators([ Validators.required ])
316 waitTranscodingControl.disable()
317 waitTranscodingControl.setValue(false)
319 scheduleControl.clearValidators()
321 waitTranscodingControl.enable()
323 // Do not update the control value on first patch (values come from the server)
324 if (this.firstPatchDone === true) {
325 waitTranscodingControl.setValue(true)
329 scheduleControl.updateValueAndValidity()
330 waitTranscodingControl.updateValueAndValidity()
332 this.firstPatchDone = true
338 private trackChannelChange () {
339 // We will update the "support" field depending on the channel
340 this.form.controls[ 'channelId' ]
342 .pipe(map(res => parseInt(res.toString(), 10)))
345 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
347 // Not initialized yet
348 if (isNaN(newChannelId)) return
349 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
350 if (!newChannel) return
352 // Wait support field update
354 const currentSupport = this.form.value[ 'support' ]
356 // First time we set the channel?
357 if (isNaN(oldChannelId)) {
358 // Fill support if it's empty
359 if (!currentSupport) this.updateSupportField(newChannel.support)
364 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
365 if (!newChannel || !oldChannel) {
366 console.error('Cannot find new or old channel.')
370 // If the current support text is not the same than the old channel, the user updated it.
371 // We don't want the user to lose his text, so stop here
372 if (currentSupport && currentSupport !== oldChannel.support) return
374 // Update the support text with our new channel
375 this.updateSupportField(newChannel.support)
381 private trackLivePermanentFieldChange () {
382 // We will update the "support" field depending on the channel
383 this.form.controls['permanentLive']
387 const saveReplayControl = this.form.controls['saveReplay']
389 if (permanentLive === true) {
390 saveReplayControl.setValue(false)
391 saveReplayControl.disable()
393 saveReplayControl.enable()
399 private updateSupportField (support: string) {
400 return this.form.patchValue({ support: support || '' })