]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Implement avatar miniatures (#4639)
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / shared / video-edit.component.ts
... / ...
CommitLineData
1import { forkJoin } from 'rxjs'
2import { map } from 'rxjs/operators'
3import { SelectChannelItem } from 'src/types/select-options-item.model'
4import { ChangeDetectorRef, Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5import { AbstractControl, FormArray, FormControl, FormGroup, Validators } from '@angular/forms'
6import { HooksService, PluginService, ServerService } from '@app/core'
7import { removeElementFromArray } from '@app/helpers'
8import { BuildFormValidator } from '@app/shared/form-validators'
9import {
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'
22import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
23import { InstanceService } from '@app/shared/shared-instance'
24import { VideoCaptionEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
25import { PluginInfo } from '@root-helpers/plugins-manager'
26import {
27 HTMLServerConfig,
28 LiveVideo,
29 RegisterClientFormFieldOptions,
30 RegisterClientVideoFieldOptions,
31 VideoConstant,
32 VideoDetails,
33 VideoPrivacy
34} from '@shared/models'
35import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
36import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
37import { VideoEditType } from './video-edit.type'
38
39type VideoLanguages = VideoConstant<string> & { group?: string }
40type 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})
51export 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() forbidScheduledPublication = 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 // Can't schedule publication if private privacy is not available (could be deleted by a plugin)
202 const hasPrivatePrivacy = this.videoPrivacies.some(p => p.id === VideoPrivacy.PRIVATE)
203 if (this.forbidScheduledPublication || !hasPrivatePrivacy) return
204
205 this.videoPrivacies.push({
206 id: this.SPECIAL_SCHEDULED_PRIVACY,
207 label: $localize`Scheduled`,
208 description: $localize`Hide the video until a specific date`
209 })
210 })
211
212 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
213
214 this.ngZone.runOutsideAngular(() => {
215 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
216 })
217
218 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
219 }
220
221 ngOnDestroy () {
222 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
223 }
224
225 getExistingCaptions () {
226 return this.videoCaptions
227 .filter(c => c.action !== 'REMOVE')
228 .map(c => c.language.id)
229 }
230
231 onCaptionAdded (caption: VideoCaptionEdit) {
232 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
233
234 // Replace existing caption?
235 if (existingCaption) {
236 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
237 } else {
238 this.videoCaptions.push(
239 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
240 )
241 }
242
243 this.sortVideoCaptions()
244 }
245
246 deleteCaption (caption: VideoCaptionEdit) {
247 // Caption recovers his former state
248 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
249 caption.action = undefined
250 return
251 }
252
253 // This caption is not on the server, just remove it from our array
254 if (caption.action === 'CREATE') {
255 removeElementFromArray(this.videoCaptions, caption)
256 return
257 }
258
259 caption.action = 'REMOVE' as 'REMOVE'
260 }
261
262 openAddCaptionModal () {
263 this.videoCaptionAddModal.show()
264 }
265
266 isSaveReplayEnabled () {
267 return this.serverConfig.live.allowReplay
268 }
269
270 isPermanentLiveEnabled () {
271 return this.form.value['permanentLive'] === true
272 }
273
274 isPluginFieldHidden (pluginField: PluginField) {
275 if (typeof pluginField.commonOptions.hidden !== 'function') return false
276
277 return pluginField.commonOptions.hidden({
278 formValues: this.form.value,
279 videoToUpdate: this.videoToUpdate,
280 liveVideo: this.liveVideo
281 })
282 }
283
284 getPluginsFields (tab: 'main' | 'plugin-settings') {
285 return this.pluginFields.filter(p => {
286 const wanted = p.videoFormOptions.tab ?? 'plugin-settings'
287
288 return wanted === tab
289 })
290 }
291
292 private sortVideoCaptions () {
293 this.videoCaptions.sort((v1, v2) => {
294 if (v1.language.label < v2.language.label) return -1
295 if (v1.language.label === v2.language.label) return 0
296
297 return 1
298 })
299 }
300
301 private async updatePluginFields () {
302 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
303
304 if (this.pluginFields.length === 0) return
305
306 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
307 const pluginValidationMessages: FormReactiveValidationMessages = {}
308 const pluginFormErrors: any = {}
309 const pluginDefaults: any = {}
310
311 for (const setting of this.pluginFields) {
312 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
313
314 const validator = async (control: AbstractControl) => {
315 if (!setting.commonOptions.error) return null
316
317 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
318
319 return error?.error ? { [setting.commonOptions.name]: error.text } : null
320 }
321
322 const name = setting.commonOptions.name
323
324 pluginObj[name] = {
325 ASYNC_VALIDATORS: [ validator ],
326 VALIDATORS: [],
327 MESSAGES: {}
328 }
329
330 pluginDefaults[name] = setting.commonOptions.default
331 }
332
333 this.pluginDataFormGroup = new FormGroup({})
334 this.formValidatorService.updateFormGroup(
335 this.pluginDataFormGroup,
336 pluginFormErrors,
337 pluginValidationMessages,
338 pluginObj,
339 pluginDefaults
340 )
341
342 this.form.addControl('pluginData', this.pluginDataFormGroup)
343 this.formErrors['pluginData'] = pluginFormErrors
344 this.validationMessages['pluginData'] = pluginValidationMessages
345
346 this.cd.detectChanges()
347 this.pluginFieldsAdded.emit()
348
349 // Plugins may need other control values to calculate potential errors
350 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
351 }
352
353 private trackPrivacyChange () {
354 // We will update the schedule input and the wait transcoding checkbox validators
355 this.form.controls['privacy']
356 .valueChanges
357 .pipe(map(res => parseInt(res.toString(), 10)))
358 .subscribe(
359 newPrivacyId => {
360
361 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
362
363 // Value changed
364 const scheduleControl = this.form.get('schedulePublicationAt')
365 const waitTranscodingControl = this.form.get('waitTranscoding')
366
367 if (this.schedulePublicationEnabled) {
368 scheduleControl.setValidators([ Validators.required ])
369
370 waitTranscodingControl.disable()
371 waitTranscodingControl.setValue(false)
372 } else {
373 scheduleControl.clearValidators()
374
375 waitTranscodingControl.enable()
376
377 // Do not update the control value on first patch (values come from the server)
378 if (this.firstPatchDone === true) {
379 waitTranscodingControl.setValue(true)
380 }
381 }
382
383 scheduleControl.updateValueAndValidity()
384 waitTranscodingControl.updateValueAndValidity()
385
386 this.firstPatchDone = true
387
388 }
389 )
390 }
391
392 private trackChannelChange () {
393 // We will update the "support" field depending on the channel
394 this.form.controls['channelId']
395 .valueChanges
396 .pipe(map(res => parseInt(res.toString(), 10)))
397 .subscribe(
398 newChannelId => {
399 const oldChannelId = parseInt(this.form.value['channelId'], 10)
400
401 // Not initialized yet
402 if (isNaN(newChannelId)) return
403 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
404 if (!newChannel) return
405
406 // Wait support field update
407 setTimeout(() => {
408 const currentSupport = this.form.value['support']
409
410 // First time we set the channel?
411 if (isNaN(oldChannelId)) {
412 // Fill support if it's empty
413 if (!currentSupport) this.updateSupportField(newChannel.support)
414
415 return
416 }
417
418 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
419 if (!newChannel || !oldChannel) {
420 console.error('Cannot find new or old channel.')
421 return
422 }
423
424 // If the current support text is not the same than the old channel, the user updated it.
425 // We don't want the user to lose his text, so stop here
426 if (currentSupport && currentSupport !== oldChannel.support) return
427
428 // Update the support text with our new channel
429 this.updateSupportField(newChannel.support)
430 })
431 }
432 )
433 }
434
435 private trackLivePermanentFieldChange () {
436 // We will update the "support" field depending on the channel
437 this.form.controls['permanentLive']
438 .valueChanges
439 .subscribe(
440 permanentLive => {
441 const saveReplayControl = this.form.controls['saveReplay']
442
443 if (permanentLive === true) {
444 saveReplayControl.setValue(false)
445 saveReplayControl.disable()
446 } else {
447 saveReplayControl.enable()
448 }
449 }
450 )
451 }
452
453 private updateSupportField (support: string) {
454 return this.form.patchValue({ support: support || '' })
455 }
456}