]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Set scroll position at top of the textarea when opening the subtitle editor.
[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 { VideoCaptionEditModalContentComponent } from './video-caption-edit-modal-content/video-caption-edit-modal-content.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 import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
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() waitTranscodingEnabled = true
70 @Input() type: VideoEditType
71 @Input() liveVideo: LiveVideo
72
73 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
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 private modalService: NgbModal
133 ) {
134 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
135 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
136 }
137
138 updateForm () {
139 const defaultValues: any = {
140 nsfw: 'false',
141 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
142 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
143 waitTranscoding: 'true',
144 licence: this.serverConfig.defaults.publish.licence,
145 tags: []
146 }
147 const obj: { [ id: string ]: BuildFormValidator } = {
148 name: VIDEO_NAME_VALIDATOR,
149 privacy: VIDEO_PRIVACY_VALIDATOR,
150 channelId: VIDEO_CHANNEL_VALIDATOR,
151 nsfw: null,
152 commentsEnabled: null,
153 downloadEnabled: null,
154 waitTranscoding: null,
155 category: VIDEO_CATEGORY_VALIDATOR,
156 licence: VIDEO_LICENCE_VALIDATOR,
157 language: VIDEO_LANGUAGE_VALIDATOR,
158 description: VIDEO_DESCRIPTION_VALIDATOR,
159 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
160 previewfile: null,
161 support: VIDEO_SUPPORT_VALIDATOR,
162 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
163 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
164 liveStreamKey: null,
165 permanentLive: null,
166 latencyMode: null,
167 saveReplay: null
168 }
169
170 this.formValidatorService.updateFormGroup(
171 this.form,
172 this.formErrors,
173 this.validationMessages,
174 obj,
175 defaultValues
176 )
177
178 this.form.addControl('captions', new FormArray([
179 new FormGroup({
180 language: new FormControl(),
181 captionfile: new FormControl()
182 })
183 ]))
184
185 this.trackChannelChange()
186 this.trackPrivacyChange()
187
188 this.formBuilt.emit()
189 }
190
191 ngOnInit () {
192 this.serverConfig = this.serverService.getHTMLConfig()
193
194 this.updateForm()
195
196 this.pluginService.ensurePluginsAreLoaded('video-edit')
197 .then(() => this.updatePluginFields())
198
199 this.serverService.getVideoCategories()
200 .subscribe(res => this.videoCategories = res)
201
202 this.serverService.getVideoLicences()
203 .subscribe(res => this.videoLicences = res)
204
205 forkJoin([
206 this.instanceService.getAbout(),
207 this.serverService.getVideoLanguages()
208 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
209 .subscribe(res => {
210 this.videoLanguages = res.languages
211 .map(l => {
212 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
213
214 return res.about.instance.languages.includes(l.id)
215 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
216 : { ...l, group: $localize`All languages`, groupOrder: 2 }
217 })
218 .sort((a, b) => a.groupOrder - b.groupOrder)
219 })
220
221 this.serverService.getVideoPrivacies()
222 .subscribe(privacies => {
223 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
224
225 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
226 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
227 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
228
229 this.videoPrivacies.push({
230 id: this.SPECIAL_SCHEDULED_PRIVACY,
231 label: $localize`Scheduled`,
232 description: $localize`Hide the video until a specific date`
233 })
234 })
235
236 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
237
238 this.ngZone.runOutsideAngular(() => {
239 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
240 })
241
242 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
243 }
244
245 ngOnDestroy () {
246 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
247 }
248
249 getExistingCaptions () {
250 return this.videoCaptions
251 .filter(c => c.action !== 'REMOVE')
252 .map(c => c.language.id)
253 }
254
255 onCaptionEdited (caption: VideoCaptionEdit) {
256 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
257
258 // Replace existing caption?
259 if (existingCaption) {
260 Object.assign(existingCaption, caption)
261 } else {
262 this.videoCaptions.push(
263 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
264 )
265 }
266
267 this.sortVideoCaptions()
268 }
269
270 deleteCaption (caption: VideoCaptionEdit) {
271 // Caption recovers his former state
272 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
273 caption.action = undefined
274 return
275 }
276
277 // This caption is not on the server, just remove it from our array
278 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
279 removeElementFromArray(this.videoCaptions, caption)
280 return
281 }
282
283 caption.action = 'REMOVE' as 'REMOVE'
284 }
285
286 openAddCaptionModal () {
287 this.videoCaptionAddModal.show()
288 }
289
290 openEditCaptionModal (videoCaption: VideoCaptionWithPathEdit) {
291 const modalRef = this.modalService.open(VideoCaptionEditModalContentComponent, { centered: true, keyboard: false })
292 modalRef.componentInstance.videoCaption = videoCaption
293 modalRef.componentInstance.serverConfig = this.serverConfig
294 modalRef.componentInstance.captionEdited.subscribe(this.onCaptionEdited.bind(this))
295 }
296
297 isSaveReplayEnabled () {
298 return this.serverConfig.live.allowReplay
299 }
300
301 isPermanentLiveEnabled () {
302 return this.form.value['permanentLive'] === true
303 }
304
305 isLatencyModeEnabled () {
306 return this.serverConfig.live.latencySetting.enabled
307 }
308
309 isPluginFieldHidden (pluginField: PluginField) {
310 if (typeof pluginField.commonOptions.hidden !== 'function') return false
311
312 return pluginField.commonOptions.hidden({
313 formValues: this.form.value,
314 videoToUpdate: this.videoToUpdate,
315 liveVideo: this.liveVideo
316 })
317 }
318
319 getPluginsFields (tab: 'main' | 'plugin-settings') {
320 return this.pluginFields.filter(p => {
321 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
322
323 return wanted === tab
324 })
325 }
326
327 private sortVideoCaptions () {
328 this.videoCaptions.sort((v1, v2) => {
329 if (v1.language.label < v2.language.label) return -1
330 if (v1.language.label === v2.language.label) return 0
331
332 return 1
333 })
334 }
335
336 private async updatePluginFields () {
337 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
338
339 if (this.pluginFields.length === 0) return
340
341 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
342 const pluginValidationMessages: FormReactiveValidationMessages = {}
343 const pluginFormErrors: any = {}
344 const pluginDefaults: any = {}
345
346 for (const setting of this.pluginFields) {
347 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
348
349 const validator = async (control: AbstractControl) => {
350 if (!setting.commonOptions.error) return null
351
352 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
353
354 return error?.error ? { [setting.commonOptions.name]: error.text } : null
355 }
356
357 const name = setting.commonOptions.name
358
359 pluginObj[name] = {
360 ASYNC_VALIDATORS: [ validator ],
361 VALIDATORS: [],
362 MESSAGES: {}
363 }
364
365 pluginDefaults[name] = setting.commonOptions.default
366 }
367
368 this.pluginDataFormGroup = new FormGroup({})
369 this.formValidatorService.updateFormGroup(
370 this.pluginDataFormGroup,
371 pluginFormErrors,
372 pluginValidationMessages,
373 pluginObj,
374 pluginDefaults
375 )
376
377 this.form.addControl('pluginData', this.pluginDataFormGroup)
378 this.formErrors['pluginData'] = pluginFormErrors
379 this.validationMessages['pluginData'] = pluginValidationMessages
380
381 this.cd.detectChanges()
382 this.pluginFieldsAdded.emit()
383
384 // Plugins may need other control values to calculate potential errors
385 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
386 }
387
388 private trackPrivacyChange () {
389 // We will update the schedule input and the wait transcoding checkbox validators
390 this.form.controls['privacy']
391 .valueChanges
392 .pipe(map(res => parseInt(res.toString(), 10)))
393 .subscribe(
394 newPrivacyId => {
395
396 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
397
398 // Value changed
399 const scheduleControl = this.form.get('schedulePublicationAt')
400 const waitTranscodingControl = this.form.get('waitTranscoding')
401
402 if (this.schedulePublicationEnabled) {
403 scheduleControl.setValidators([ Validators.required ])
404
405 waitTranscodingControl.disable()
406 waitTranscodingControl.setValue(false)
407 } else {
408 scheduleControl.clearValidators()
409
410 waitTranscodingControl.enable()
411
412 // Do not update the control value on first patch (values come from the server)
413 if (this.firstPatchDone === true) {
414 waitTranscodingControl.setValue(true)
415 }
416 }
417
418 scheduleControl.updateValueAndValidity()
419 waitTranscodingControl.updateValueAndValidity()
420
421 this.firstPatchDone = true
422
423 }
424 )
425 }
426
427 private trackChannelChange () {
428 // We will update the "support" field depending on the channel
429 this.form.controls['channelId']
430 .valueChanges
431 .pipe(map(res => parseInt(res.toString(), 10)))
432 .subscribe(
433 newChannelId => {
434 const oldChannelId = parseInt(this.form.value['channelId'], 10)
435
436 // Not initialized yet
437 if (isNaN(newChannelId)) return
438 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
439 if (!newChannel) return
440
441 // Wait support field update
442 setTimeout(() => {
443 const currentSupport = this.form.value['support']
444
445 // First time we set the channel?
446 if (isNaN(oldChannelId)) {
447 // Fill support if it's empty
448 if (!currentSupport) this.updateSupportField(newChannel.support)
449
450 return
451 }
452
453 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
454 if (!newChannel || !oldChannel) {
455 logger.error('Cannot find new or old channel.')
456 return
457 }
458
459 // If the current support text is not the same than the old channel, the user updated it.
460 // We don't want the user to lose his text, so stop here
461 if (currentSupport && currentSupport !== oldChannel.support) return
462
463 // Update the support text with our new channel
464 this.updateSupportField(newChannel.support)
465 })
466 }
467 )
468 }
469
470 private updateSupportField (support: string) {
471 return this.form.patchValue({ support: support || '' })
472 }
473 }