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, ValidatorFn, 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, 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 }
33 selector: 'my-video-edit',
34 styleUrls: [ './video-edit.component.scss' ],
35 templateUrl: './video-edit.component.html'
37 export class VideoEditComponent implements OnInit, OnDestroy {
38 @Input() form: FormGroup
39 @Input() formErrors: { [ id: string ]: string } = {}
40 @Input() validationMessages: FormReactiveValidationMessages = {}
41 @Input() userVideoChannels: SelectChannelItem[] = []
42 @Input() schedulePublicationPossible = true
43 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
44 @Input() waitTranscodingEnabled = true
45 @Input() type: VideoEditType
46 @Input() liveVideo: LiveVideo
48 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
50 @Output() pluginFieldsAdded = new EventEmitter<void>()
52 // So that it can be accessed in the template
53 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
55 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
56 videoCategories: VideoConstant<number>[] = []
57 videoLicences: VideoConstant<number>[] = []
58 videoLanguages: VideoLanguages[] = []
60 tagValidators: ValidatorFn[]
61 tagValidatorsMessages: { [ name: string ]: string }
63 pluginDataFormGroup: FormGroup
65 schedulePublicationEnabled = false
67 calendarLocale: any = {}
68 minScheduledDate = new Date()
69 myYearRange = '1880:' + (new Date()).getFullYear()
71 calendarTimezone: string
72 calendarDateFormat: string
74 serverConfig: ServerConfig
77 commonOptions: RegisterClientFormFieldOptions
78 videoFormOptions: RegisterClientVideoFieldOptions
81 private schedulerInterval: any
82 private firstPatchDone = false
83 private initialVideoCaptions: string[] = []
86 private formValidatorService: FormValidatorService,
87 private videoService: VideoService,
88 private serverService: ServerService,
89 private pluginService: PluginService,
90 private instanceService: InstanceService,
91 private i18nPrimengCalendarService: I18nPrimengCalendarService,
92 private ngZone: NgZone,
93 private hooks: HooksService
95 this.calendarLocale = this.i18nPrimengCalendarService.getCalendarLocale()
96 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
97 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
101 const defaultValues: any = {
103 commentsEnabled: 'true',
104 downloadEnabled: 'true',
105 waitTranscoding: 'true',
109 name: VIDEO_NAME_VALIDATOR,
110 privacy: VIDEO_PRIVACY_VALIDATOR,
111 channelId: VIDEO_CHANNEL_VALIDATOR,
113 commentsEnabled: null,
114 downloadEnabled: null,
115 waitTranscoding: null,
116 category: VIDEO_CATEGORY_VALIDATOR,
117 licence: VIDEO_LICENCE_VALIDATOR,
118 language: VIDEO_LANGUAGE_VALIDATOR,
119 description: VIDEO_DESCRIPTION_VALIDATOR,
120 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
122 support: VIDEO_SUPPORT_VALIDATOR,
123 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
124 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
130 this.formValidatorService.updateForm(
133 this.validationMessages,
138 this.form.addControl('captions', new FormArray([
140 language: new FormControl(),
141 captionfile: new FormControl()
145 this.trackChannelChange()
146 this.trackPrivacyChange()
147 this.trackLivePermanentFieldChange()
153 this.pluginService.ensurePluginsAreLoaded('video-edit')
154 .then(() => this.updatePluginFields())
156 this.serverService.getVideoCategories()
157 .subscribe(res => this.videoCategories = res)
159 this.serverService.getVideoLicences()
160 .subscribe(res => this.videoLicences = res)
163 this.instanceService.getAbout(),
164 this.serverService.getVideoLanguages()
165 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
167 this.videoLanguages = res.languages
169 return res.about.instance.languages.includes(l.id)
170 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
171 : { ...l, group: $localize`All languages`, groupOrder: 1 }
173 .sort((a, b) => a.groupOrder - b.groupOrder)
176 this.serverService.getVideoPrivacies()
177 .subscribe(privacies => {
178 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies)
179 if (this.schedulePublicationPossible) {
180 this.videoPrivacies.push({
181 id: this.SPECIAL_SCHEDULED_PRIVACY,
182 label: $localize`Scheduled`,
183 description: $localize`Hide the video until a specific date`
188 this.serverConfig = this.serverService.getTmpConfig()
189 this.serverService.getConfig()
190 .subscribe(config => this.serverConfig = config)
192 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
194 this.ngZone.runOutsideAngular(() => {
195 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
198 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
202 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
205 getExistingCaptions () {
206 return this.videoCaptions
207 .filter(c => c.action !== 'REMOVE')
208 .map(c => c.language.id)
211 onCaptionAdded (caption: VideoCaptionEdit) {
212 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
214 // Replace existing caption?
215 if (existingCaption) {
216 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
218 this.videoCaptions.push(
219 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
223 this.sortVideoCaptions()
226 async deleteCaption (caption: VideoCaptionEdit) {
227 // Caption recovers his former state
228 if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
229 caption.action = undefined
233 // This caption is not on the server, just remove it from our array
234 if (caption.action === 'CREATE') {
235 removeElementFromArray(this.videoCaptions, caption)
239 caption.action = 'REMOVE' as 'REMOVE'
242 openAddCaptionModal () {
243 this.videoCaptionAddModal.show()
246 isSaveReplayEnabled () {
247 return this.serverConfig.live.allowReplay
250 isPermanentLiveEnabled () {
251 return this.form.value['permanentLive'] === true
254 private sortVideoCaptions () {
255 this.videoCaptions.sort((v1, v2) => {
256 if (v1.language.label < v2.language.label) return -1
257 if (v1.language.label === v2.language.label) return 0
263 private updatePluginFields () {
264 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
266 if (this.pluginFields.length === 0) return
270 for (const setting of this.pluginFields) {
271 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
274 this.pluginDataFormGroup = new FormGroup(obj)
275 this.form.addControl('pluginData', this.pluginDataFormGroup)
277 this.pluginFieldsAdded.emit()
280 private trackPrivacyChange () {
281 // We will update the schedule input and the wait transcoding checkbox validators
282 this.form.controls[ 'privacy' ]
284 .pipe(map(res => parseInt(res.toString(), 10)))
288 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
291 const scheduleControl = this.form.get('schedulePublicationAt')
292 const waitTranscodingControl = this.form.get('waitTranscoding')
294 if (this.schedulePublicationEnabled) {
295 scheduleControl.setValidators([ Validators.required ])
297 waitTranscodingControl.disable()
298 waitTranscodingControl.setValue(false)
300 scheduleControl.clearValidators()
302 waitTranscodingControl.enable()
304 // Do not update the control value on first patch (values come from the server)
305 if (this.firstPatchDone === true) {
306 waitTranscodingControl.setValue(true)
310 scheduleControl.updateValueAndValidity()
311 waitTranscodingControl.updateValueAndValidity()
313 this.firstPatchDone = true
319 private trackChannelChange () {
320 // We will update the "support" field depending on the channel
321 this.form.controls[ 'channelId' ]
323 .pipe(map(res => parseInt(res.toString(), 10)))
326 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
328 // Not initialized yet
329 if (isNaN(newChannelId)) return
330 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
331 if (!newChannel) return
333 // Wait support field update
335 const currentSupport = this.form.value[ 'support' ]
337 // First time we set the channel?
338 if (isNaN(oldChannelId)) {
339 // Fill support if it's empty
340 if (!currentSupport) this.updateSupportField(newChannel.support)
345 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
346 if (!newChannel || !oldChannel) {
347 console.error('Cannot find new or old channel.')
351 // If the current support text is not the same than the old channel, the user updated it.
352 // We don't want the user to lose his text, so stop here
353 if (currentSupport && currentSupport !== oldChannel.support) return
355 // Update the support text with our new channel
356 this.updateSupportField(newChannel.support)
362 private trackLivePermanentFieldChange () {
363 // We will update the "support" field depending on the channel
364 this.form.controls['permanentLive']
368 const saveReplayControl = this.form.controls['saveReplay']
370 if (permanentLive === true) {
371 saveReplayControl.setValue(false)
372 saveReplayControl.disable()
374 saveReplayControl.enable()
380 private updateSupportField (support: string) {
381 return this.form.patchValue({ support: support || '' })