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