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