]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
f51f521606ef3c1a8b33d88df98b648ebcbcb118
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-edit / shared / video-edit.component.ts
1 import { forkJoin } from 'rxjs'
2 import { map } from 'rxjs/operators'
3 import { SelectChannelItem } from 'src/types/select-options-item.model'
4 import { Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
5 import { FormArray, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'
6 import { HooksService, PluginService, ServerService } from '@app/core'
7 import { removeElementFromArray } from '@app/helpers'
8 import {
9 VIDEO_CATEGORY_VALIDATOR,
10 VIDEO_CHANNEL_VALIDATOR,
11 VIDEO_DESCRIPTION_VALIDATOR,
12 VIDEO_LANGUAGE_VALIDATOR,
13 VIDEO_LICENCE_VALIDATOR,
14 VIDEO_NAME_VALIDATOR,
15 VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
16 VIDEO_PRIVACY_VALIDATOR,
17 VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
18 VIDEO_SUPPORT_VALIDATOR,
19 VIDEO_TAGS_ARRAY_VALIDATOR
20 } from '@app/shared/form-validators/video-validators'
21 import { FormReactiveValidationMessages, FormValidatorService } from '@app/shared/shared-forms'
22 import { InstanceService } from '@app/shared/shared-instance'
23 import { VideoCaptionEdit, VideoEdit, VideoService } from '@app/shared/shared-main'
24 import { LiveVideo, ServerConfig, VideoConstant, VideoPrivacy } from '@shared/models'
25 import { RegisterClientFormFieldOptions, RegisterClientVideoFieldOptions } from '@shared/models/plugins/register-client-form-field.model'
26 import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
27 import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
28 import { VideoEditType } from './video-edit.type'
29
30 type VideoLanguages = VideoConstant<string> & { group?: string }
31
32 @Component({
33 selector: 'my-video-edit',
34 styleUrls: [ './video-edit.component.scss' ],
35 templateUrl: './video-edit.component.html'
36 })
37 export class VideoEditComponent implements OnInit, OnDestroy {
38 @Input() form: FormGroup
39 @Input() formErrors: { [ id: string ]: string } = {}
40 @Input() validationMessages: FormReactiveValidationMessages = {}
41 @Input() userVideoChannels: SelectChannelItem[] = []
42 @Input() schedulePublicationPossible = true
43 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
44 @Input() waitTranscodingEnabled = true
45 @Input() type: VideoEditType
46 @Input() liveVideo: LiveVideo
47
48 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
49
50 @Output() pluginFieldsAdded = new EventEmitter<void>()
51
52 // So that it can be accessed in the template
53 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
54
55 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
56 videoCategories: VideoConstant<number>[] = []
57 videoLicences: VideoConstant<number>[] = []
58 videoLanguages: VideoLanguages[] = []
59
60 tagValidators: ValidatorFn[]
61 tagValidatorsMessages: { [ name: string ]: string }
62
63 pluginDataFormGroup: FormGroup
64
65 schedulePublicationEnabled = false
66
67 calendarLocale: any = {}
68 minScheduledDate = new Date()
69 myYearRange = '1880:' + (new Date()).getFullYear()
70
71 calendarTimezone: string
72 calendarDateFormat: string
73
74 serverConfig: ServerConfig
75
76 pluginFields: {
77 commonOptions: RegisterClientFormFieldOptions
78 videoFormOptions: RegisterClientVideoFieldOptions
79 }[] = []
80
81 private schedulerInterval: any
82 private firstPatchDone = false
83 private initialVideoCaptions: string[] = []
84
85 constructor (
86 private formValidatorService: FormValidatorService,
87 private videoService: VideoService,
88 private serverService: ServerService,
89 private pluginService: PluginService,
90 private instanceService: InstanceService,
91 private i18nPrimengCalendarService: I18nPrimengCalendarService,
92 private ngZone: NgZone,
93 private hooks: HooksService
94 ) {
95 this.calendarLocale = this.i18nPrimengCalendarService.getCalendarLocale()
96 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
97 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
98 }
99
100 updateForm () {
101 const defaultValues: any = {
102 nsfw: 'false',
103 commentsEnabled: 'true',
104 downloadEnabled: 'true',
105 waitTranscoding: 'true',
106 tags: []
107 }
108 const obj: any = {
109 name: VIDEO_NAME_VALIDATOR,
110 privacy: VIDEO_PRIVACY_VALIDATOR,
111 channelId: VIDEO_CHANNEL_VALIDATOR,
112 nsfw: null,
113 commentsEnabled: null,
114 downloadEnabled: null,
115 waitTranscoding: null,
116 category: VIDEO_CATEGORY_VALIDATOR,
117 licence: VIDEO_LICENCE_VALIDATOR,
118 language: VIDEO_LANGUAGE_VALIDATOR,
119 description: VIDEO_DESCRIPTION_VALIDATOR,
120 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
121 previewfile: null,
122 support: VIDEO_SUPPORT_VALIDATOR,
123 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
124 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR,
125 liveStreamKey: null,
126 permanentLive: null,
127 saveReplay: null
128 }
129
130 this.formValidatorService.updateForm(
131 this.form,
132 this.formErrors,
133 this.validationMessages,
134 obj,
135 defaultValues
136 )
137
138 this.form.addControl('captions', new FormArray([
139 new FormGroup({
140 language: new FormControl(),
141 captionfile: new FormControl()
142 })
143 ]))
144
145 this.trackChannelChange()
146 this.trackPrivacyChange()
147 this.trackLivePermanentFieldChange()
148 }
149
150 ngOnInit () {
151 this.updateForm()
152
153 this.pluginService.ensurePluginsAreLoaded('video-edit')
154 .then(() => this.updatePluginFields())
155
156 this.serverService.getVideoCategories()
157 .subscribe(res => this.videoCategories = res)
158
159 this.serverService.getVideoLicences()
160 .subscribe(res => this.videoLicences = res)
161
162 forkJoin([
163 this.instanceService.getAbout(),
164 this.serverService.getVideoLanguages()
165 ]).pipe(map(([ about, languages ]) => ({ about, languages })))
166 .subscribe(res => {
167 this.videoLanguages = res.languages
168 .map(l => {
169 return res.about.instance.languages.includes(l.id)
170 ? { ...l, group: $localize`Instance languages`, groupOrder: 0 }
171 : { ...l, group: $localize`All languages`, groupOrder: 1 }
172 })
173 .sort((a, b) => a.groupOrder - b.groupOrder)
174 })
175
176 this.serverService.getVideoPrivacies()
177 .subscribe(privacies => {
178 this.videoPrivacies = this.videoService.explainedPrivacyLabels(privacies)
179 if (this.schedulePublicationPossible) {
180 this.videoPrivacies.push({
181 id: this.SPECIAL_SCHEDULED_PRIVACY,
182 label: $localize`Scheduled`,
183 description: $localize`Hide the video until a specific date`
184 })
185 }
186 })
187
188 this.serverConfig = this.serverService.getTmpConfig()
189 this.serverService.getConfig()
190 .subscribe(config => this.serverConfig = config)
191
192 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
193
194 this.ngZone.runOutsideAngular(() => {
195 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
196 })
197
198 this.hooks.runAction('action:video-edit.init', 'video-edit', { type: this.type })
199 }
200
201 ngOnDestroy () {
202 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
203 }
204
205 getExistingCaptions () {
206 return this.videoCaptions
207 .filter(c => c.action !== 'REMOVE')
208 .map(c => c.language.id)
209 }
210
211 onCaptionAdded (caption: VideoCaptionEdit) {
212 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
213
214 // Replace existing caption?
215 if (existingCaption) {
216 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
217 } else {
218 this.videoCaptions.push(
219 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
220 )
221 }
222
223 this.sortVideoCaptions()
224 }
225
226 async deleteCaption (caption: VideoCaptionEdit) {
227 // Caption recovers his former state
228 if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
229 caption.action = undefined
230 return
231 }
232
233 // This caption is not on the server, just remove it from our array
234 if (caption.action === 'CREATE') {
235 removeElementFromArray(this.videoCaptions, caption)
236 return
237 }
238
239 caption.action = 'REMOVE' as 'REMOVE'
240 }
241
242 openAddCaptionModal () {
243 this.videoCaptionAddModal.show()
244 }
245
246 isSaveReplayEnabled () {
247 return this.serverConfig.live.allowReplay
248 }
249
250 isPermanentLiveEnabled () {
251 return this.form.value['permanentLive'] === true
252 }
253
254 private sortVideoCaptions () {
255 this.videoCaptions.sort((v1, v2) => {
256 if (v1.language.label < v2.language.label) return -1
257 if (v1.language.label === v2.language.label) return 0
258
259 return 1
260 })
261 }
262
263 private updatePluginFields () {
264 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
265
266 if (this.pluginFields.length === 0) return
267
268 const obj: any = {}
269
270 for (const setting of this.pluginFields) {
271 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
272 }
273
274 this.pluginDataFormGroup = new FormGroup(obj)
275 this.form.addControl('pluginData', this.pluginDataFormGroup)
276
277 this.pluginFieldsAdded.emit()
278 }
279
280 private trackPrivacyChange () {
281 // We will update the schedule input and the wait transcoding checkbox validators
282 this.form.controls[ 'privacy' ]
283 .valueChanges
284 .pipe(map(res => parseInt(res.toString(), 10)))
285 .subscribe(
286 newPrivacyId => {
287
288 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
289
290 // Value changed
291 const scheduleControl = this.form.get('schedulePublicationAt')
292 const waitTranscodingControl = this.form.get('waitTranscoding')
293
294 if (this.schedulePublicationEnabled) {
295 scheduleControl.setValidators([ Validators.required ])
296
297 waitTranscodingControl.disable()
298 waitTranscodingControl.setValue(false)
299 } else {
300 scheduleControl.clearValidators()
301
302 waitTranscodingControl.enable()
303
304 // Do not update the control value on first patch (values come from the server)
305 if (this.firstPatchDone === true) {
306 waitTranscodingControl.setValue(true)
307 }
308 }
309
310 scheduleControl.updateValueAndValidity()
311 waitTranscodingControl.updateValueAndValidity()
312
313 this.firstPatchDone = true
314
315 }
316 )
317 }
318
319 private trackChannelChange () {
320 // We will update the "support" field depending on the channel
321 this.form.controls[ 'channelId' ]
322 .valueChanges
323 .pipe(map(res => parseInt(res.toString(), 10)))
324 .subscribe(
325 newChannelId => {
326 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
327
328 // Not initialized yet
329 if (isNaN(newChannelId)) return
330 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
331 if (!newChannel) return
332
333 // Wait support field update
334 setTimeout(() => {
335 const currentSupport = this.form.value[ 'support' ]
336
337 // First time we set the channel?
338 if (isNaN(oldChannelId)) {
339 // Fill support if it's empty
340 if (!currentSupport) this.updateSupportField(newChannel.support)
341
342 return
343 }
344
345 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
346 if (!newChannel || !oldChannel) {
347 console.error('Cannot find new or old channel.')
348 return
349 }
350
351 // If the current support text is not the same than the old channel, the user updated it.
352 // We don't want the user to lose his text, so stop here
353 if (currentSupport && currentSupport !== oldChannel.support) return
354
355 // Update the support text with our new channel
356 this.updateSupportField(newChannel.support)
357 })
358 }
359 )
360 }
361
362 private trackLivePermanentFieldChange () {
363 // We will update the "support" field depending on the channel
364 this.form.controls['permanentLive']
365 .valueChanges
366 .subscribe(
367 permanentLive => {
368 const saveReplayControl = this.form.controls['saveReplay']
369
370 if (permanentLive === true) {
371 saveReplayControl.setValue(false)
372 saveReplayControl.disable()
373 } else {
374 saveReplayControl.enable()
375 }
376 }
377 )
378 }
379
380 private updateSupportField (support: string) {
381 return this.form.patchValue({ support: support || '' })
382 }
383 }