]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
Merge branch 'release/4.2.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / shared / video-edit.component.ts
CommitLineData
9abd170d 1import { forkJoin } from 'rxjs'
67ed6552 2import { map } from 'rxjs/operators'
f443a746 3import { SelectChannelItem, SelectOptionsItem } from 'src/types/select-options-item.model'
3c065fe3 4import { ChangeDetectorRef, Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
cc4bf76c 5import { AbstractControl, FormArray, FormControl, FormGroup, Validators } from '@angular/forms'
7294aab0 6import { HooksService, PluginService, ServerService } from '@app/core'
67ed6552 7import { removeElementFromArray } from '@app/helpers'
3c065fe3 8import { BuildFormValidator } from '@app/shared/form-validators'
7ed1edbb
C
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'
21e493d4 22import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
9abd170d 23import { InstanceService } from '@app/shared/shared-instance'
57d74ec8 24import { VideoCaptionEdit, VideoCaptionWithPathEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
fb3c9e2b 25import { PluginInfo } from '@root-helpers/plugins-manager'
428ccb8b 26import {
2989628b 27 HTMLServerConfig,
428ccb8b 28 LiveVideo,
f443a746 29 LiveVideoLatencyMode,
428ccb8b
C
30 RegisterClientFormFieldOptions,
31 RegisterClientVideoFieldOptions,
428ccb8b
C
32 VideoConstant,
33 VideoDetails,
34 VideoPrivacy
35} from '@shared/models'
67ed6552
C
36import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
37import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
57d74ec8 38import { VideoCaptionEditModalComponent } from './video-caption-edit-modal/video-caption-edit-modal.component'
c6c0fa6c 39import { VideoEditType } from './video-edit.type'
2e401e85 40import { VideoSource } from '@shared/models/videos/video-source'
02c01341
RK
41
42type VideoLanguages = VideoConstant<string> & { group?: string }
0f319334 43type PluginField = {
fb3c9e2b 44 pluginInfo: PluginInfo
0f319334
C
45 commonOptions: RegisterClientFormFieldOptions
46 videoFormOptions: RegisterClientVideoFieldOptions
47}
ff249f49
C
48
49@Component({
50 selector: 'my-video-edit',
51 styleUrls: [ './video-edit.component.scss' ],
52 templateUrl: './video-edit.component.html'
53})
40e87e9e 54export class VideoEditComponent implements OnInit, OnDestroy {
ff249f49
C
55 @Input() form: FormGroup
56 @Input() formErrors: { [ id: string ]: string } = {}
e309822b 57 @Input() validationMessages: FormReactiveValidationMessages = {}
0f319334
C
58
59 @Input() videoToUpdate: VideoDetails
60
9abd170d 61 @Input() userVideoChannels: SelectChannelItem[] = []
4afec735 62 @Input() forbidScheduledPublication = true
0f319334 63
70a8e50a 64 @Input() videoCaptions: VideoCaptionWithPathEdit[] = []
2e401e85 65 @Input() videoSource: VideoSource
0f319334 66
14e2014a 67 @Input() waitTranscodingEnabled = true
c6c0fa6c 68 @Input() type: VideoEditType
a5cf76af 69 @Input() liveVideo: LiveVideo
40e87e9e 70
f36da21e 71 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
57d74ec8 72 @ViewChild('videoCaptionEditModal', { static: true }) editCaptionModal: VideoCaptionEditModalComponent
bbe0f064 73
0ba9696c 74 @Output() formBuilt = new EventEmitter<void>()
7294aab0
C
75 @Output() pluginFieldsAdded = new EventEmitter<void>()
76
bbe0f064
C
77 // So that it can be accessed in the template
78 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
ff249f49 79
851f5daa 80 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
8cd7faaa
C
81 videoCategories: VideoConstant<number>[] = []
82 videoLicences: VideoConstant<number>[] = []
02c01341 83 videoLanguages: VideoLanguages[] = []
f443a746
C
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 ]
ff249f49 101
7294aab0
C
102 pluginDataFormGroup: FormGroup
103
bbe0f064
C
104 schedulePublicationEnabled = false
105
bbe0f064
C
106 calendarLocale: any = {}
107 minScheduledDate = new Date()
1e74f19a 108 myYearRange = '1880:' + (new Date()).getFullYear()
bbe0f064
C
109
110 calendarTimezone: string
111 calendarDateFormat: string
ff249f49 112
2989628b 113 serverConfig: HTMLServerConfig
ba430d75 114
0f319334 115 pluginFields: PluginField[] = []
7294aab0 116
244b4ae3 117 private schedulerInterval: any
0f7fedc3 118 private firstPatchDone = false
772d5642 119 private initialVideoCaptions: string[] = []
40e87e9e 120
ff249f49 121 constructor (
d18d6478 122 private formValidatorService: FormValidatorService,
851f5daa 123 private videoService: VideoService,
bbe0f064 124 private serverService: ServerService,
7294aab0 125 private pluginService: PluginService,
02c01341 126 private instanceService: InstanceService,
84c7cde6 127 private i18nPrimengCalendarService: I18nPrimengCalendarService,
7294aab0 128 private ngZone: NgZone,
3c065fe3
C
129 private hooks: HooksService,
130 private cd: ChangeDetectorRef
e309822b 131 ) {
bbe0f064
C
132 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
133 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
e309822b 134 }
ff249f49
C
135
136 updateForm () {
244b4ae3 137 const defaultValues: any = {
d18d6478 138 nsfw: 'false',
3cf68b86
C
139 commentsEnabled: this.serverConfig.defaults.publish.commentsEnabled,
140 downloadEnabled: this.serverConfig.defaults.publish.downloadEnabled,
2186386c 141 waitTranscoding: 'true',
3cf68b86 142 licence: this.serverConfig.defaults.publish.licence,
d18d6478
C
143 tags: []
144 }
3c065fe3 145 const obj: { [ id: string ]: BuildFormValidator } = {
7ed1edbb
C
146 name: VIDEO_NAME_VALIDATOR,
147 privacy: VIDEO_PRIVACY_VALIDATOR,
148 channelId: VIDEO_CHANNEL_VALIDATOR,
d18d6478
C
149 nsfw: null,
150 commentsEnabled: null,
7f2cfe3a 151 downloadEnabled: null,
2186386c 152 waitTranscoding: null,
7ed1edbb
C
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,
d18d6478 158 previewfile: null,
7ed1edbb
C
159 support: VIDEO_SUPPORT_VALIDATOR,
160 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
c6c0fa6c 161 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
b5b68755 162 liveStreamKey: null,
bb4ba6d9 163 permanentLive: null,
f443a746 164 latencyMode: null,
b5b68755 165 saveReplay: null
d18d6478 166 }
ff249f49 167
3c065fe3 168 this.formValidatorService.updateFormGroup(
d18d6478
C
169 this.form,
170 this.formErrors,
171 this.validationMessages,
172 obj,
173 defaultValues
174 )
74af5145 175
40e87e9e
C
176 this.form.addControl('captions', new FormArray([
177 new FormGroup({
178 language: new FormControl(),
179 captionfile: new FormControl()
180 })
181 ]))
182
bbe0f064
C
183 this.trackChannelChange()
184 this.trackPrivacyChange()
0ba9696c
C
185
186 this.formBuilt.emit()
bbe0f064
C
187 }
188
189 ngOnInit () {
3cf68b86
C
190 this.serverConfig = this.serverService.getHTMLConfig()
191
bbe0f064
C
192 this.updateForm()
193
7294aab0
C
194 this.pluginService.ensurePluginsAreLoaded('video-edit')
195 .then(() => this.updatePluginFields())
196
ba430d75
C
197 this.serverService.getVideoCategories()
198 .subscribe(res => this.videoCategories = res)
7294aab0 199
ba430d75
C
200 this.serverService.getVideoLicences()
201 .subscribe(res => this.videoLicences = res)
7294aab0 202
02c01341
RK
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
7294aab0 209 .map(l => {
81547acb
FC
210 if (l.id === 'zxx') return { ...l, group: $localize`Other`, groupOrder: 1 }
211
7294aab0
C
212 return res.about.instance.languages.includes(l.id)
213 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
81547acb 214 : { ...l, group: $localize`All languages`, groupOrder: 2 }
7294aab0 215 })
02c01341
RK
216 .sort((a, b) => a.groupOrder - b.groupOrder)
217 })
ba430d75
C
218
219 this.serverService.getVideoPrivacies()
02c01341 220 .subscribe(privacies => {
29510651 221 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies).videoPrivacies
a3f45a2a 222
4afec735
C
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 })
02c01341 232 })
bbe0f064 233
772d5642 234 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
84c7cde6
C
235
236 this.ngZone.runOutsideAngular(() => {
237 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
238 })
7294aab0
C
239
240 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
40e87e9e
C
241 }
242
243 ngOnDestroy () {
244 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
245 }
246
ddb62a85
C
247 getExistingCaptions () {
248 return this.videoCaptions
249 .filter(c => c.action !== 'REMOVE')
250 .map(c => c.language.id)
251 }
252
57d74ec8 253 onCaptionEdited (caption: VideoCaptionEdit) {
f4001cf4
C
254 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
255
256 // Replace existing caption?
257 if (existingCaption) {
57d74ec8 258 Object.assign(existingCaption, caption)
ad774752
C
259 } else {
260 this.videoCaptions.push(
261 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
262 )
f4001cf4
C
263 }
264
ad774752 265 this.sortVideoCaptions()
40e87e9e
C
266 }
267
98ab5dc8 268 deleteCaption (caption: VideoCaptionEdit) {
772d5642 269 // Caption recovers his former state
9df52d66 270 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
772d5642
C
271 caption.action = undefined
272 return
273 }
274
40e87e9e 275 // This caption is not on the server, just remove it from our array
57d74ec8 276 if (caption.action === 'CREATE' || caption.action === 'UPDATE') {
40e87e9e
C
277 removeElementFromArray(this.videoCaptions, caption)
278 return
279 }
280
281 caption.action = 'REMOVE' as 'REMOVE'
282 }
283
284 openAddCaptionModal () {
285 this.videoCaptionAddModal.show()
bbe0f064
C
286 }
287
b5b68755
C
288 isSaveReplayEnabled () {
289 return this.serverConfig.live.allowReplay
290 }
291
bb4ba6d9
C
292 isPermanentLiveEnabled () {
293 return this.form.value['permanentLive'] === true
294 }
295
f443a746
C
296 isLatencyModeEnabled () {
297 return this.serverConfig.live.latencySetting.enabled
298 }
299
0f319334
C
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
3c065fe3
C
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
ad774752
C
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
fb3c9e2b 327 private async updatePluginFields () {
7294aab0
C
328 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
329
330 if (this.pluginFields.length === 0) return
331
3c065fe3
C
332 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
333 const pluginValidationMessages: FormReactiveValidationMessages = {}
334 const pluginFormErrors: any = {}
335 const pluginDefaults: any = {}
7294aab0
C
336
337 for (const setting of this.pluginFields) {
fb3c9e2b
C
338 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
339
cc4bf76c 340 const validator = async (control: AbstractControl) => {
3c065fe3
C
341 if (!setting.commonOptions.error) return null
342
cc4bf76c 343 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
3c065fe3
C
344
345 return error?.error ? { [setting.commonOptions.name]: error.text } : null
346 }
347
348 const name = setting.commonOptions.name
349
350 pluginObj[name] = {
cc4bf76c
C
351 ASYNC_VALIDATORS: [ validator ],
352 VALIDATORS: [],
3c065fe3
C
353 MESSAGES: {}
354 }
355
356 pluginDefaults[name] = setting.commonOptions.default
7294aab0
C
357 }
358
3c065fe3
C
359 this.pluginDataFormGroup = new FormGroup({})
360 this.formValidatorService.updateFormGroup(
361 this.pluginDataFormGroup,
362 pluginFormErrors,
363 pluginValidationMessages,
364 pluginObj,
365 pluginDefaults
366 )
367
7294aab0 368 this.form.addControl('pluginData', this.pluginDataFormGroup)
3c065fe3
C
369 this.formErrors['pluginData'] = pluginFormErrors
370 this.validationMessages['pluginData'] = pluginValidationMessages
7294aab0 371
3c065fe3 372 this.cd.detectChanges()
7294aab0 373 this.pluginFieldsAdded.emit()
cc4bf76c
C
374
375 // Plugins may need other control values to calculate potential errors
376 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
7294aab0
C
377 }
378
bbe0f064 379 private trackPrivacyChange () {
4adf2673 380 // We will update the schedule input and the wait transcoding checkbox validators
9df52d66 381 this.form.controls['privacy']
bbe0f064
C
382 .valueChanges
383 .pipe(map(res => parseInt(res.toString(), 10)))
384 .subscribe(
385 newPrivacyId => {
0f7fedc3 386
bbe0f064
C
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()
0f7fedc3
C
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 }
bbe0f064
C
407 }
408
409 scheduleControl.updateValueAndValidity()
410 waitTranscodingControl.updateValueAndValidity()
0f7fedc3
C
411
412 this.firstPatchDone = true
413
bbe0f064
C
414 }
415 )
416 }
417
418 private trackChannelChange () {
74af5145 419 // We will update the "support" field depending on the channel
9df52d66 420 this.form.controls['channelId']
74af5145
C
421 .valueChanges
422 .pipe(map(res => parseInt(res.toString(), 10)))
423 .subscribe(
424 newChannelId => {
9df52d66 425 const oldChannelId = parseInt(this.form.value['channelId'], 10)
74af5145
C
426
427 // Not initialized yet
428 if (isNaN(newChannelId)) return
429 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
d18d6478 430 if (!newChannel) return
74af5145 431
6f79be11
C
432 // Wait support field update
433 setTimeout(() => {
9df52d66 434 const currentSupport = this.form.value['support']
74af5145 435
6f79be11 436 // First time we set the channel?
c6c0fa6c
C
437 if (isNaN(oldChannelId)) {
438 // Fill support if it's empty
439 if (!currentSupport) this.updateSupportField(newChannel.support)
440
441 return
442 }
6f79be11
C
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 }
74af5145 449
6f79be11
C
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
74af5145 453
6f79be11
C
454 // Update the support text with our new channel
455 this.updateSupportField(newChannel.support)
456 })
74af5145
C
457 }
458 )
ff249f49
C
459 }
460
74af5145
C
461 private updateSupportField (support: string) {
462 return this.form.patchValue({ support: support || '' })
463 }
ff249f49 464}