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