]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
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[] = []
4afec735 59 @Input() forbidScheduledPublication = 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
4afec735
C
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 })
02c01341 210 })
bbe0f064 211
772d5642 212 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
84c7cde6
C
213
214 this.ngZone.runOutsideAngular(() => {
215 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
216 })
7294aab0
C
217
218 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
40e87e9e
C
219 }
220
221 ngOnDestroy () {
222 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
223 }
224
ddb62a85
C
225 getExistingCaptions () {
226 return this.videoCaptions
227 .filter(c => c.action !== 'REMOVE')
228 .map(c => c.language.id)
229 }
230
40e87e9e 231 onCaptionAdded (caption: VideoCaptionEdit) {
f4001cf4
C
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' })
ad774752
C
237 } else {
238 this.videoCaptions.push(
239 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
240 )
f4001cf4
C
241 }
242
ad774752 243 this.sortVideoCaptions()
40e87e9e
C
244 }
245
98ab5dc8 246 deleteCaption (caption: VideoCaptionEdit) {
772d5642 247 // Caption recovers his former state
9df52d66 248 if (caption.action && this.initialVideoCaptions.includes(caption.language.id)) {
772d5642
C
249 caption.action = undefined
250 return
251 }
252
40e87e9e
C
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()
bbe0f064
C
264 }
265
b5b68755
C
266 isSaveReplayEnabled () {
267 return this.serverConfig.live.allowReplay
268 }
269
bb4ba6d9
C
270 isPermanentLiveEnabled () {
271 return this.form.value['permanentLive'] === true
272 }
273
0f319334
C
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
3c065fe3
C
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
ad774752
C
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
fb3c9e2b 301 private async updatePluginFields () {
7294aab0
C
302 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
303
304 if (this.pluginFields.length === 0) return
305
3c065fe3
C
306 const pluginObj: { [ id: string ]: BuildFormValidator } = {}
307 const pluginValidationMessages: FormReactiveValidationMessages = {}
308 const pluginFormErrors: any = {}
309 const pluginDefaults: any = {}
7294aab0
C
310
311 for (const setting of this.pluginFields) {
fb3c9e2b
C
312 await this.pluginService.translateSetting(setting.pluginInfo.plugin.npmName, setting.commonOptions)
313
cc4bf76c 314 const validator = async (control: AbstractControl) => {
3c065fe3
C
315 if (!setting.commonOptions.error) return null
316
cc4bf76c 317 const error = await setting.commonOptions.error({ formValues: this.form.value, value: control.value })
3c065fe3
C
318
319 return error?.error ? { [setting.commonOptions.name]: error.text } : null
320 }
321
322 const name = setting.commonOptions.name
323
324 pluginObj[name] = {
cc4bf76c
C
325 ASYNC_VALIDATORS: [ validator ],
326 VALIDATORS: [],
3c065fe3
C
327 MESSAGES: {}
328 }
329
330 pluginDefaults[name] = setting.commonOptions.default
7294aab0
C
331 }
332
3c065fe3
C
333 this.pluginDataFormGroup = new FormGroup({})
334 this.formValidatorService.updateFormGroup(
335 this.pluginDataFormGroup,
336 pluginFormErrors,
337 pluginValidationMessages,
338 pluginObj,
339 pluginDefaults
340 )
341
7294aab0 342 this.form.addControl('pluginData', this.pluginDataFormGroup)
3c065fe3
C
343 this.formErrors['pluginData'] = pluginFormErrors
344 this.validationMessages['pluginData'] = pluginValidationMessages
7294aab0 345
3c065fe3 346 this.cd.detectChanges()
7294aab0 347 this.pluginFieldsAdded.emit()
cc4bf76c
C
348
349 // Plugins may need other control values to calculate potential errors
350 this.form.valueChanges.subscribe(() => this.formValidatorService.updateTreeValidity(this.pluginDataFormGroup))
7294aab0
C
351 }
352
bbe0f064 353 private trackPrivacyChange () {
4adf2673 354 // We will update the schedule input and the wait transcoding checkbox validators
9df52d66 355 this.form.controls['privacy']
bbe0f064
C
356 .valueChanges
357 .pipe(map(res => parseInt(res.toString(), 10)))
358 .subscribe(
359 newPrivacyId => {
0f7fedc3 360
bbe0f064
C
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()
0f7fedc3
C
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 }
bbe0f064
C
381 }
382
383 scheduleControl.updateValueAndValidity()
384 waitTranscodingControl.updateValueAndValidity()
0f7fedc3
C
385
386 this.firstPatchDone = true
387
bbe0f064
C
388 }
389 )
390 }
391
392 private trackChannelChange () {
74af5145 393 // We will update the "support" field depending on the channel
9df52d66 394 this.form.controls['channelId']
74af5145
C
395 .valueChanges
396 .pipe(map(res => parseInt(res.toString(), 10)))
397 .subscribe(
398 newChannelId => {
9df52d66 399 const oldChannelId = parseInt(this.form.value['channelId'], 10)
74af5145
C
400
401 // Not initialized yet
402 if (isNaN(newChannelId)) return
403 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
d18d6478 404 if (!newChannel) return
74af5145 405
6f79be11
C
406 // Wait support field update
407 setTimeout(() => {
9df52d66 408 const currentSupport = this.form.value['support']
74af5145 409
6f79be11 410 // First time we set the channel?
c6c0fa6c
C
411 if (isNaN(oldChannelId)) {
412 // Fill support if it's empty
413 if (!currentSupport) this.updateSupportField(newChannel.support)
414
415 return
416 }
6f79be11
C
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 }
74af5145 423
6f79be11
C
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
74af5145 427
6f79be11
C
428 // Update the support text with our new channel
429 this.updateSupportField(newChannel.support)
430 })
74af5145
C
431 }
432 )
ff249f49
C
433 }
434
bb4ba6d9
C
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
74af5145
C
453 private updateSupportField (support: string) {
454 return this.form.patchValue({ support: support || '' })
455 }
ff249f49 456}