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