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