1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
4 import { FormArray, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'
5 import { HooksService, PluginService, ServerService } from '@app/core'
6 import { removeElementFromArray } from '@app/helpers'
8 VIDEO_CATEGORY_VALIDATOR,
9 VIDEO_CHANNEL_VALIDATOR,
10 VIDEO_DESCRIPTION_VALIDATOR,
11 VIDEO_LANGUAGE_VALIDATOR,
12 VIDEO_LICENCE_VALIDATOR,
14 VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
15 VIDEO_PRIVACY_VALIDATOR,
16 VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
17 VIDEO_SUPPORT_VALIDATOR,
18 VIDEO_TAGS_ARRAY_VALIDATOR
19 } from '@app/shared/form-validators/video-validators'
20 import { FormReactiveValidationMessages, FormValidatorService, SelectChannelItem } from '@app/shared/shared-forms'
21 import { InstanceService } from '@app/shared/shared-instance'
22 import { VideoCaptionEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
23 import { ServerConfig, VideoConstant, LiveVideo, VideoPrivacy } from '@shared/models'
24 import { RegisterClientFormFieldOptions, RegisterClientVideoFieldOptions } from '@shared/models/plugins/register-client-form-field.model'
25 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
26 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
27 import { VideoEditType } from './video-edit.type'
29 type VideoLanguages = VideoConstant<string> & { group?: string }
32 selector: 'my-video-edit',
33 styleUrls: [ './video-edit.component.scss' ],
34 templateUrl: './video-edit.component.html'
36 export class VideoEditComponent implements OnInit, OnDestroy {
37 @Input() form: FormGroup
38 @Input() formErrors: { [ id: string ]: string } = {}
39 @Input() validationMessages: FormReactiveValidationMessages = {}
40 @Input() userVideoChannels: SelectChannelItem[] = []
41 @Input() schedulePublicationPossible = true
42 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
43 @Input() waitTranscodingEnabled = true
44 @Input() type: VideoEditType
45 @Input() liveVideo: LiveVideo
47 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
49 @Output() pluginFieldsAdded = new EventEmitter<void>()
51 // So that it can be accessed in the template
52 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
54 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
55 videoCategories: VideoConstant<number>[] = []
56 videoLicences: VideoConstant<number>[] = []
57 videoLanguages: VideoLanguages[] = []
59 tagValidators: ValidatorFn[]
60 tagValidatorsMessages: { [ name: string ]: string }
62 pluginDataFormGroup: FormGroup
64 schedulePublicationEnabled = false
66 calendarLocale: any = {}
67 minScheduledDate = new Date()
68 myYearRange = '1880:' + (new Date()).getFullYear()
70 calendarTimezone: string
71 calendarDateFormat: string
73 serverConfig: ServerConfig
76 commonOptions: RegisterClientFormFieldOptions
77 videoFormOptions: RegisterClientVideoFieldOptions
80 private schedulerInterval: any
81 private firstPatchDone = false
82 private initialVideoCaptions: string[] = []
85 private formValidatorService: FormValidatorService,
86 private videoService: VideoService,
87 private serverService: ServerService,
88 private pluginService: PluginService,
89 private instanceService: InstanceService,
90 private i18nPrimengCalendarService: I18nPrimengCalendarService,
91 private ngZone: NgZone,
92 private hooks: HooksService
94 this.calendarLocale = this.i18nPrimengCalendarService.getCalendarLocale()
95 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
96 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
99 get existingCaptions () {
100 return this.videoCaptions
101 .filter(c => c.action !== 'REMOVE')
102 .map(c => c.language.id)
105 isWaitTranscodingDisplayed () {
106 if (!this.waitTranscodingEnabled) return false
108 if (this.liveVideo) {
109 return this.form.value['saveReplay'] === true
116 const defaultValues: any = {
118 commentsEnabled: 'true',
119 downloadEnabled: 'true',
120 waitTranscoding: 'true',
124 name: VIDEO_NAME_VALIDATOR,
125 privacy: VIDEO_PRIVACY_VALIDATOR,
126 channelId: VIDEO_CHANNEL_VALIDATOR,
128 commentsEnabled: null,
129 downloadEnabled: null,
130 waitTranscoding: null,
131 category: VIDEO_CATEGORY_VALIDATOR,
132 licence: VIDEO_LICENCE_VALIDATOR,
133 language: VIDEO_LANGUAGE_VALIDATOR,
134 description: VIDEO_DESCRIPTION_VALIDATOR,
135 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
137 support: VIDEO_SUPPORT_VALIDATOR,
138 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
139 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
145 this.formValidatorService.updateForm(
148 this.validationMessages,
153 this.form.addControl('captions', new FormArray([
155 language: new FormControl(),
156 captionfile: new FormControl()
160 this.trackChannelChange()
161 this.trackPrivacyChange()
162 this.trackLivePermanentFieldChange()
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 return res.about.instance.languages.includes(l.id)
185 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
186 : { ...l, group: $localize`All languages`, groupOrder: 1 }
188 .sort((a, b) => a.groupOrder - b.groupOrder)
191 this.serverService.getVideoPrivacies()
192 .subscribe(privacies => {
193 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies)
194 if (this.schedulePublicationPossible) {
195 this.videoPrivacies.push({
196 id: this.SPECIAL_SCHEDULED_PRIVACY,
197 label: $localize`Scheduled`,
198 description: $localize`Hide the video until a specific date`
203 this.serverConfig = this.serverService.getTmpConfig()
204 this.serverService.getConfig()
205 .subscribe(config => this.serverConfig = config)
207 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
209 this.ngZone.runOutsideAngular(() => {
210 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
213 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
217 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
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 private sortVideoCaptions () {
264 this.videoCaptions.sort((v1, v2) => {
265 if (v1.language.label < v2.language.label) return -1
266 if (v1.language.label === v2.language.label) return 0
272 private updatePluginFields () {
273 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
275 if (this.pluginFields.length === 0) return
279 for (const setting of this.pluginFields) {
280 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
283 this.pluginDataFormGroup = new FormGroup(obj)
284 this.form.addControl('pluginData', this.pluginDataFormGroup)
286 this.pluginFieldsAdded.emit()
289 private trackPrivacyChange () {
290 // We will update the schedule input and the wait transcoding checkbox validators
291 this.form.controls[ 'privacy' ]
293 .pipe(map(res => parseInt(res.toString(), 10)))
297 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
300 const scheduleControl = this.form.get('schedulePublicationAt')
301 const waitTranscodingControl = this.form.get('waitTranscoding')
303 if (this.schedulePublicationEnabled) {
304 scheduleControl.setValidators([ Validators.required ])
306 waitTranscodingControl.disable()
307 waitTranscodingControl.setValue(false)
309 scheduleControl.clearValidators()
311 waitTranscodingControl.enable()
313 // Do not update the control value on first patch (values come from the server)
314 if (this.firstPatchDone === true) {
315 waitTranscodingControl.setValue(true)
319 scheduleControl.updateValueAndValidity()
320 waitTranscodingControl.updateValueAndValidity()
322 this.firstPatchDone = true
328 private trackChannelChange () {
329 // We will update the "support" field depending on the channel
330 this.form.controls[ 'channelId' ]
332 .pipe(map(res => parseInt(res.toString(), 10)))
335 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
337 // Not initialized yet
338 if (isNaN(newChannelId)) return
339 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
340 if (!newChannel) return
342 // Wait support field update
344 const currentSupport = this.form.value[ 'support' ]
346 // First time we set the channel?
347 if (isNaN(oldChannelId)) {
348 // Fill support if it's empty
349 if (!currentSupport) this.updateSupportField(newChannel.support)
354 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
355 if (!newChannel || !oldChannel) {
356 console.error('Cannot find new or old channel.')
360 // If the current support text is not the same than the old channel, the user updated it.
361 // We don't want the user to lose his text, so stop here
362 if (currentSupport && currentSupport !== oldChannel.support) return
364 // Update the support text with our new channel
365 this.updateSupportField(newChannel.support)
371 private trackLivePermanentFieldChange () {
372 // We will update the "support" field depending on the channel
373 this.form.controls['permanentLive']
377 const saveReplayControl = this.form.controls['saveReplay']
379 if (permanentLive === true) {
380 saveReplayControl.setValue(false)
381 saveReplayControl.disable()
383 saveReplayControl.enable()
389 private updateSupportField (support: string) {
390 return this.form.patchValue({ support: support || '' })