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