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