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