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