]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Translate plugin settings
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / shared / video-edit.component.ts
1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { SelectChannelItem } from 'src/types/select-options-item.model'
4 import { ChangeDetectorRef, Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { AbstractControl, FormArray, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms'
6 import { HooksService, PluginService, ServerService } from '@app/core'
7 import { removeElementFromArray } from '@app/helpers'
8 import { BuildFormValidator } from '@app/shared/form-validators'
9 import {
10 VIDEO_CATEGORY_VALIDATOR,
11 VIDEO_CHANNEL_VALIDATOR,
12 VIDEO_DESCRIPTION_VALIDATOR,
13 VIDEO_LANGUAGE_VALIDATOR,
14 VIDEO_LICENCE_VALIDATOR,
15 VIDEO_NAME_VALIDATOR,
16 VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
17 VIDEO_PRIVACY_VALIDATOR,
18 VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
19 VIDEO_SUPPORT_VALIDATOR,
20 VIDEO_TAGS_ARRAY_VALIDATOR
21 } from '@app/shared/form-validators/video-validators'
22 import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
23 import { InstanceService } from '@app/shared/shared-instance'
24 import { VideoCaptionEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
25 import { PluginInfo } from '@root-helpers/plugins-manager'
26 import {
27 HTMLServerConfig,
28 LiveVideo,
29 RegisterClientFormFieldOptions,
30 RegisterClientVideoFieldOptions,
31 VideoConstant,
32 VideoDetails,
33 VideoPrivacy
34 } from '@shared/models'
35 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
36 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
37 import { VideoEditType } from './video-edit.type'
38
39 type VideoLanguages = VideoConstant<string> & { group?: string }
40 type PluginField = {
41 pluginInfo: PluginInfo
42 commonOptions: RegisterClientFormFieldOptions
43 videoFormOptions: RegisterClientVideoFieldOptions
44 }
45
46 @Component({
47 selector: 'my-video-edit',
48 styleUrls: [ './video-edit.component.scss' ],
49 templateUrl: './video-edit.component.html'
50 })
51 export class VideoEditComponent implements OnInit, OnDestroy {
52 @Input() form: FormGroup
53 @Input() formErrors: { [ id: string ]: string } = {}
54 @Input() validationMessages: FormReactiveValidationMessages = {}
55
56 @Input() videoToUpdate: VideoDetails
57
58 @Input() userVideoChannels: SelectChannelItem[] = []
59 @Input() schedulePublicationPossible = true
60
61 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
62
63 @Input() waitTranscodingEnabled = true
64 @Input() type: VideoEditType
65 @Input() liveVideo: LiveVideo
66
67 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
68
69 @Output() formBuilt = new EventEmitter<void>()
70 @Output() pluginFieldsAdded = new EventEmitter<void>()
71
72 // So that it can be accessed in the template
73 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
74
75 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
76 videoCategories: VideoConstant<number>[] = []
77 videoLicences: VideoConstant<number>[] = []
78 videoLanguages: VideoLanguages[] = []
79
80 pluginDataFormGroup: FormGroup
81
82 schedulePublicationEnabled = false
83
84 calendarLocale: any = {}
85 minScheduledDate = new Date()
86 myYearRange = '1880:' + (new Date()).getFullYear()
87
88 calendarTimezone: string
89 calendarDateFormat: string
90
91 serverConfig: HTMLServerConfig
92
93 pluginFields: PluginField[] = []
94
95 private schedulerInterval: any
96 private firstPatchDone = false
97 private initialVideoCaptions: string[] = []
98
99 constructor (
100 private formValidatorService: FormValidatorService,
101 private videoService: VideoService,
102 private serverService: ServerService,
103 private pluginService: PluginService,
104 private instanceService: InstanceService,
105 private i18nPrimengCalendarService: I18nPrimengCalendarService,
106 private ngZone: NgZone,
107 private hooks: HooksService,
108 private cd: ChangeDetectorRef
109 ) {
110 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
111 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
112 }
113
114 updateForm () {
115 const defaultValues: any = {
116 nsfw: 'false',
117 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
118 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
119 waitTranscoding: 'true',
120 licence: this.serverConfig.defaults.publish.licence,
121 tags: []
122 }
123 const obj: { [ id: string ]: BuildFormValidator } = {
124 name: VIDEO_NAME_VALIDATOR,
125 privacy: VIDEO_PRIVACY_VALIDATOR,
126 channelId: VIDEO_CHANNEL_VALIDATOR,
127 nsfw: null,
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,
136 previewfile: null,
137 support: VIDEO_SUPPORT_VALIDATOR,
138 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
139 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
140 liveStreamKey: null,
141 permanentLive: null,
142 saveReplay: null
143 }
144
145 this.formValidatorService.updateFormGroup(
146 this.form,
147 this.formErrors,
148 this.validationMessages,
149 obj,
150 defaultValues
151 )
152
153 this.form.addControl('captions', new FormArray([
154 new FormGroup({
155 language: new FormControl(),
156 captionfile: new FormControl()
157 })
158 ]))
159
160 this.trackChannelChange()
161 this.trackPrivacyChange()
162 this.trackLivePermanentFieldChange()
163
164 this.formBuilt.emit()
165 }
166
167 ngOnInit () {
168 this.serverConfig = this.serverService.getHTMLConfig()
169
170 this.updateForm()
171
172 this.pluginService.ensurePluginsAreLoaded('video-edit')
173 .then(() => this.updatePluginFields())
174
175 this.serverService.getVideoCategories()
176 .subscribe(res => this.videoCategories = res)
177
178 this.serverService.getVideoLicences()
179 .subscribe(res => this.videoLicences = res)
180
181 forkJoin([
182 this.instanceService.getAbout(),
183 this.serverService.getVideoLanguages()
184 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
185 .subscribe(res => {
186 this.videoLanguages = res.languages
187 .map(l => {
188 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
189
190 return res.about.instance.languages.includes(l.id)
191 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
192 : { ...l, group: $localize`All languages`, groupOrder: 2 }
193 })
194 .sort((a, b) => a.groupOrder - b.groupOrder)
195 })
196
197 this.serverService.getVideoPrivacies()
198 .subscribe(privacies => {
199 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
200
201 if (this.schedulePublicationPossible) {
202 this.videoPrivacies.push({
203 id: this.SPECIAL_SCHEDULED_PRIVACY,
204 label: $localize`Scheduled`,
205 description: $localize`Hide the video until a specific date`
206 })
207 }
208 })
209
210 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
211
212 this.ngZone.runOutsideAngular(() => {
213 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
214 })
215
216 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
217 }
218
219 ngOnDestroy () {
220 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
221 }
222
223 getExistingCaptions () {
224 return this.videoCaptions
225 .filter(c => c.action !== 'REMOVE')
226 .map(c => c.language.id)
227 }
228
229 onCaptionAdded (caption: VideoCaptionEdit) {
230 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
231
232 // Replace existing caption?
233 if (existingCaption) {
234 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
235 } else {
236 this.videoCaptions.push(
237 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
238 )
239 }
240
241 this.sortVideoCaptions()
242 }
243
244 deleteCaption (caption: VideoCaptionEdit) {
245 // Caption recovers his former state
246 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
247 caption.action = undefined
248 return
249 }
250
251 // This caption is not on the server, just remove it from our array
252 if (caption.action === 'CREATE') {
253 removeElementFromArray(this.videoCaptions, caption)
254 return
255 }
256
257 caption.action = 'REMOVE' as 'REMOVE'
258 }
259
260 openAddCaptionModal () {
261 this.videoCaptionAddModal.show()
262 }
263
264 isSaveReplayEnabled () {
265 return this.serverConfig.live.allowReplay
266 }
267
268 isPermanentLiveEnabled () {
269 return this.form.value['permanentLive'] === true
270 }
271
272 isPluginFieldHidden (pluginField: PluginField) {
273 if (typeof pluginField.commonOptions.hidden !== 'function') return false
274
275 return pluginField.commonOptions.hidden({
276 formValues: this.form.value,
277 videoToUpdate: this.videoToUpdate,
278 liveVideo: this.liveVideo
279 })
280 }
281
282 getPluginsFields (tab: 'main' | 'plugin-settings') {
283 return this.pluginFields.filter(p => {
284 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
285
286 return wanted === tab
287 })
288 }
289
290 private sortVideoCaptions () {
291 this.videoCaptions.sort((v1, v2) => {
292 if (v1.language.label < v2.language.label) return -1
293 if (v1.language.label === v2.language.label) return 0
294
295 return 1
296 })
297 }
298
299 private async updatePluginFields () {
300 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
301
302 if (this.pluginFields.length === 0) return
303
304 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
305 const pluginValidationMessages: FormReactiveValidationMessages = {}
306 const pluginFormErrors: any = {}
307 const pluginDefaults: any = {}
308
309 for (const setting of this.pluginFields) {
310 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
311
312 const validator = (control: AbstractControl): ValidationErrors | null => {
313 if (!setting.commonOptions.error) return null
314
315 const error = setting.commonOptions.error({ formValues: this.form.value, value: control.value })
316
317 return error?.error ? { [setting.commonOptions.name]: error.text } : null
318 }
319
320 const name = setting.commonOptions.name
321
322 pluginObj[name] = {
323 VALIDATORS: [ validator ],
324 MESSAGES: {}
325 }
326
327 pluginDefaults[name] = setting.commonOptions.default
328 }
329
330 this.pluginDataFormGroup = new FormGroup({})
331 this.formValidatorService.updateFormGroup(
332 this.pluginDataFormGroup,
333 pluginFormErrors,
334 pluginValidationMessages,
335 pluginObj,
336 pluginDefaults
337 )
338
339 this.form.addControl('pluginData', this.pluginDataFormGroup)
340 this.formErrors['pluginData'] = pluginFormErrors
341 this.validationMessages['pluginData'] = pluginValidationMessages
342
343 this.cd.detectChanges()
344 this.pluginFieldsAdded.emit()
345 }
346
347 private trackPrivacyChange () {
348 // We will update the schedule input and the wait transcoding checkbox validators
349 this.form.controls['privacy']
350 .valueChanges
351 .pipe(map(res => parseInt(res.toString(), 10)))
352 .subscribe(
353 newPrivacyId => {
354
355 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
356
357 // Value changed
358 const scheduleControl = this.form.get('schedulePublicationAt')
359 const waitTranscodingControl = this.form.get('waitTranscoding')
360
361 if (this.schedulePublicationEnabled) {
362 scheduleControl.setValidators([ Validators.required ])
363
364 waitTranscodingControl.disable()
365 waitTranscodingControl.setValue(false)
366 } else {
367 scheduleControl.clearValidators()
368
369 waitTranscodingControl.enable()
370
371 // Do not update the control value on first patch (values come from the server)
372 if (this.firstPatchDone === true) {
373 waitTranscodingControl.setValue(true)
374 }
375 }
376
377 scheduleControl.updateValueAndValidity()
378 waitTranscodingControl.updateValueAndValidity()
379
380 this.firstPatchDone = true
381
382 }
383 )
384 }
385
386 private trackChannelChange () {
387 // We will update the "support" field depending on the channel
388 this.form.controls['channelId']
389 .valueChanges
390 .pipe(map(res => parseInt(res.toString(), 10)))
391 .subscribe(
392 newChannelId => {
393 const oldChannelId = parseInt(this.form.value['channelId'], 10)
394
395 // Not initialized yet
396 if (isNaN(newChannelId)) return
397 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
398 if (!newChannel) return
399
400 // Wait support field update
401 setTimeout(() => {
402 const currentSupport = this.form.value['support']
403
404 // First time we set the channel?
405 if (isNaN(oldChannelId)) {
406 // Fill support if it's empty
407 if (!currentSupport) this.updateSupportField(newChannel.support)
408
409 return
410 }
411
412 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
413 if (!newChannel || !oldChannel) {
414 console.error('Cannot find new or old channel.')
415 return
416 }
417
418 // If the current support text is not the same than the old channel, the user updated it.
419 // We don't want the user to lose his text, so stop here
420 if (currentSupport && currentSupport !== oldChannel.support) return
421
422 // Update the support text with our new channel
423 this.updateSupportField(newChannel.support)
424 })
425 }
426 )
427 }
428
429 private trackLivePermanentFieldChange () {
430 // We will update the "support" field depending on the channel
431 this.form.controls['permanentLive']
432 .valueChanges
433 .subscribe(
434 permanentLive => {
435 const saveReplayControl = this.form.controls['saveReplay']
436
437 if (permanentLive === true) {
438 saveReplayControl.setValue(false)
439 saveReplayControl.disable()
440 } else {
441 saveReplayControl.enable()
442 }
443 }
444 )
445 }
446
447 private updateSupportField (support: string) {
448 return this.form.patchValue({ support: support || '' })
449 }
450 }