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