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: 'true',
114 downloadEnabled: 'true',
115 waitTranscoding: 'true',
119 name: VIDEO_NAME_VALIDATOR,
120 privacy: VIDEO_PRIVACY_VALIDATOR,
121 channelId: VIDEO_CHANNEL_VALIDATOR,
123 commentsEnabled: null,
124 downloadEnabled: null,
125 waitTranscoding: null,
126 category: VIDEO_CATEGORY_VALIDATOR,
127 licence: VIDEO_LICENCE_VALIDATOR,
128 language: VIDEO_LANGUAGE_VALIDATOR,
129 description: VIDEO_DESCRIPTION_VALIDATOR,
130 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
132 support: VIDEO_SUPPORT_VALIDATOR,
133 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
134 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
140 this.formValidatorService.updateForm(
143 this.validationMessages,
148 this.form.addControl('captions', new FormArray([
150 language: new FormControl(),
151 captionfile: new FormControl()
155 this.trackChannelChange()
156 this.trackPrivacyChange()
157 this.trackLivePermanentFieldChange()
159 this.formBuilt.emit()
165 this.pluginService.ensurePluginsAreLoaded('video-edit')
166 .then(() => this.updatePluginFields())
168 this.serverService.getVideoCategories()
169 .subscribe(res => this.videoCategories = res)
171 this.serverService.getVideoLicences()
172 .subscribe(res => this.videoLicences = res)
175 this.instanceService.getAbout(),
176 this.serverService.getVideoLanguages()
177 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
179 this.videoLanguages = res.languages
181 return res.about.instance.languages.includes(l.id)
182 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
183 : { ...l, group: $localize`All languages`, groupOrder: 1 }
185 .sort((a, b) => a.groupOrder - b.groupOrder)
188 this.serverService.getVideoPrivacies()
189 .subscribe(privacies => {
190 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
192 if (this.schedulePublicationPossible) {
193 this.videoPrivacies.push({
194 id: this.SPECIAL_SCHEDULED_PRIVACY,
195 label: $localize`Scheduled`,
196 description: $localize`Hide the video until a specific date`
201 this.serverConfig = this.serverService.getHTMLConfig()
203 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
205 this.ngZone.runOutsideAngular(() => {
206 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
209 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
213 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
216 getExistingCaptions () {
217 return this.videoCaptions
218 .filter(c => c.action !== 'REMOVE')
219 .map(c => c.language.id)
222 onCaptionAdded (caption: VideoCaptionEdit) {
223 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
225 // Replace existing caption?
226 if (existingCaption) {
227 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
229 this.videoCaptions.push(
230 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
234 this.sortVideoCaptions()
237 deleteCaption (caption: VideoCaptionEdit) {
238 // Caption recovers his former state
239 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
240 caption.action = undefined
244 // This caption is not on the server, just remove it from our array
245 if (caption.action === 'CREATE') {
246 removeElementFromArray(this.videoCaptions, caption)
250 caption.action = 'REMOVE' as 'REMOVE'
253 openAddCaptionModal () {
254 this.videoCaptionAddModal.show()
257 isSaveReplayEnabled () {
258 return this.serverConfig.live.allowReplay
261 isPermanentLiveEnabled () {
262 return this.form.value['permanentLive'] === true
265 isPluginFieldHidden (pluginField: PluginField) {
266 if (typeof pluginField.commonOptions.hidden !== 'function') return false
268 return pluginField.commonOptions.hidden({
269 formValues: this.form.value,
270 videoToUpdate: this.videoToUpdate,
271 liveVideo: this.liveVideo
275 private sortVideoCaptions () {
276 this.videoCaptions.sort((v1, v2) => {
277 if (v1.language.label < v2.language.label) return -1
278 if (v1.language.label === v2.language.label) return 0
284 private updatePluginFields () {
285 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
287 if (this.pluginFields.length === 0) return
291 for (const setting of this.pluginFields) {
292 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
295 this.pluginDataFormGroup = new FormGroup(obj)
296 this.form.addControl('pluginData', this.pluginDataFormGroup)
298 this.pluginFieldsAdded.emit()
301 private trackPrivacyChange () {
302 // We will update the schedule input and the wait transcoding checkbox validators
303 this.form.controls['privacy']
305 .pipe(map(res => parseInt(res.toString(), 10)))
309 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
312 const scheduleControl = this.form.get('schedulePublicationAt')
313 const waitTranscodingControl = this.form.get('waitTranscoding')
315 if (this.schedulePublicationEnabled) {
316 scheduleControl.setValidators([ Validators.required ])
318 waitTranscodingControl.disable()
319 waitTranscodingControl.setValue(false)
321 scheduleControl.clearValidators()
323 waitTranscodingControl.enable()
325 // Do not update the control value on first patch (values come from the server)
326 if (this.firstPatchDone === true) {
327 waitTranscodingControl.setValue(true)
331 scheduleControl.updateValueAndValidity()
332 waitTranscodingControl.updateValueAndValidity()
334 this.firstPatchDone = true
340 private trackChannelChange () {
341 // We will update the "support" field depending on the channel
342 this.form.controls['channelId']
344 .pipe(map(res => parseInt(res.toString(), 10)))
347 const oldChannelId = parseInt(this.form.value['channelId'], 10)
349 // Not initialized yet
350 if (isNaN(newChannelId)) return
351 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
352 if (!newChannel) return
354 // Wait support field update
356 const currentSupport = this.form.value['support']
358 // First time we set the channel?
359 if (isNaN(oldChannelId)) {
360 // Fill support if it's empty
361 if (!currentSupport) this.updateSupportField(newChannel.support)
366 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
367 if (!newChannel || !oldChannel) {
368 console.error('Cannot find new or old channel.')
372 // If the current support text is not the same than the old channel, the user updated it.
373 // We don't want the user to lose his text, so stop here
374 if (currentSupport && currentSupport !== oldChannel.support) return
376 // Update the support text with our new channel
377 this.updateSupportField(newChannel.support)
383 private trackLivePermanentFieldChange () {
384 // We will update the "support" field depending on the channel
385 this.form.controls['permanentLive']
389 const saveReplayControl = this.form.controls['saveReplay']
391 if (permanentLive === true) {
392 saveReplayControl.setValue(false)
393 saveReplayControl.disable()
395 saveReplayControl.enable()
401 private updateSupportField (support: string) {
402 return this.form.patchValue({ support: support || '' })