]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-edit/shared/video-edit.component.ts
f04111e69488f7c7a18d8f3866eb4e80ebbc6ba8
[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, 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
28 type VideoLanguages = VideoConstant<string> & { group?: string }
29
30 @Component({
31 selector: 'my-video-edit',
32 styleUrls: [ './video-edit.component.scss' ],
33 templateUrl: './video-edit.component.html'
34 })
35 export class VideoEditComponent implements OnInit, OnDestroy {
36 @Input() form: FormGroup
37 @Input() formErrors: { [ id: string ]: string } = {}
38 @Input() validationMessages: FormReactiveValidationMessages = {}
39 @Input() userVideoChannels: SelectChannelItem[] = []
40 @Input() schedulePublicationPossible = true
41 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
42 @Input() waitTranscodingEnabled = true
43 @Input() type: 'import-url' | 'import-torrent' | 'upload' | 'update'
44
45 @ViewChild('videoCaptionAddModal', { static: true }) videoCaptionAddModal: VideoCaptionAddModalComponent
46
47 @Output() pluginFieldsAdded = new EventEmitter<void>()
48
49 // So that it can be accessed in the template
50 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
51
52 videoPrivacies: VideoConstant<VideoPrivacy>[] = []
53 videoCategories: VideoConstant<number>[] = []
54 videoLicences: VideoConstant<number>[] = []
55 videoLanguages: VideoLanguages[] = []
56
57 tagValidators: ValidatorFn[]
58 tagValidatorsMessages: { [ name: string ]: string }
59
60 pluginDataFormGroup: FormGroup
61
62 schedulePublicationEnabled = false
63
64 calendarLocale: any = {}
65 minScheduledDate = new Date()
66 myYearRange = '1880:' + (new Date()).getFullYear()
67
68 calendarTimezone: string
69 calendarDateFormat: string
70
71 serverConfig: ServerConfig
72
73 pluginFields: {
74 commonOptions: RegisterClientFormFieldOptions
75 videoFormOptions: RegisterClientVideoFieldOptions
76 }[] = []
77
78 private schedulerInterval: any
79 private firstPatchDone = false
80 private initialVideoCaptions: string[] = []
81
82 constructor (
83 private formValidatorService: FormValidatorService,
84 private videoService: VideoService,
85 private serverService: ServerService,
86 private pluginService: PluginService,
87 private instanceService: InstanceService,
88 private i18nPrimengCalendarService: I18nPrimengCalendarService,
89 private ngZone: NgZone,
90 private hooks: HooksService
91 ) {
92 this.calendarLocale = this.i18nPrimengCalendarService.getCalendarLocale()
93 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
94 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
95 }
96
97 get existingCaptions () {
98 return this.videoCaptions
99 .filter(c => c.action !== 'REMOVE')
100 .map(c => c.language.id)
101 }
102
103 updateForm () {
104 const defaultValues: any = {
105 nsfw: 'false',
106 commentsEnabled: 'true',
107 downloadEnabled: 'true',
108 waitTranscoding: 'true',
109 tags: []
110 }
111 const obj: any = {
112 name: VIDEO_NAME_VALIDATOR,
113 privacy: VIDEO_PRIVACY_VALIDATOR,
114 channelId: VIDEO_CHANNEL_VALIDATOR,
115 nsfw: null,
116 commentsEnabled: null,
117 downloadEnabled: null,
118 waitTranscoding: null,
119 category: VIDEO_CATEGORY_VALIDATOR,
120 licence: VIDEO_LICENCE_VALIDATOR,
121 language: VIDEO_LANGUAGE_VALIDATOR,
122 description: VIDEO_DESCRIPTION_VALIDATOR,
123 tags: VIDEO_TAGS_ARRAY_VALIDATOR,
124 previewfile: null,
125 support: VIDEO_SUPPORT_VALIDATOR,
126 schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR,
127 originallyPublishedAt: VIDEO_ORIGINALLY_PUBLISHED_AT_VALIDATOR
128 }
129
130 this.formValidatorService.updateForm(
131 this.form,
132 this.formErrors,
133 this.validationMessages,
134 obj,
135 defaultValues
136 )
137
138 this.form.addControl('captions', new FormArray([
139 new FormGroup({
140 language: new FormControl(),
141 captionfile: new FormControl()
142 })
143 ]))
144
145 this.trackChannelChange()
146 this.trackPrivacyChange()
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 onCaptionAdded (caption: VideoCaptionEdit) {
205 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
206
207 // Replace existing caption?
208 if (existingCaption) {
209 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
210 } else {
211 this.videoCaptions.push(
212 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
213 )
214 }
215
216 this.sortVideoCaptions()
217 }
218
219 async deleteCaption (caption: VideoCaptionEdit) {
220 // Caption recovers his former state
221 if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
222 caption.action = undefined
223 return
224 }
225
226 // This caption is not on the server, just remove it from our array
227 if (caption.action === 'CREATE') {
228 removeElementFromArray(this.videoCaptions, caption)
229 return
230 }
231
232 caption.action = 'REMOVE' as 'REMOVE'
233 }
234
235 openAddCaptionModal () {
236 this.videoCaptionAddModal.show()
237 }
238
239 private sortVideoCaptions () {
240 this.videoCaptions.sort((v1, v2) => {
241 if (v1.language.label < v2.language.label) return -1
242 if (v1.language.label === v2.language.label) return 0
243
244 return 1
245 })
246 }
247
248 private updatePluginFields () {
249 this.pluginFields = this.pluginService.getRegisteredVideoFormFields(this.type)
250
251 if (this.pluginFields.length === 0) return
252
253 const obj: any = {}
254
255 for (const setting of this.pluginFields) {
256 obj[setting.commonOptions.name] = new FormControl(setting.commonOptions.default)
257 }
258
259 this.pluginDataFormGroup = new FormGroup(obj)
260 this.form.addControl('pluginData', this.pluginDataFormGroup)
261
262 this.pluginFieldsAdded.emit()
263 }
264
265 private trackPrivacyChange () {
266 // We will update the schedule input and the wait transcoding checkbox validators
267 this.form.controls[ 'privacy' ]
268 .valueChanges
269 .pipe(map(res => parseInt(res.toString(), 10)))
270 .subscribe(
271 newPrivacyId => {
272
273 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
274
275 // Value changed
276 const scheduleControl = this.form.get('schedulePublicationAt')
277 const waitTranscodingControl = this.form.get('waitTranscoding')
278
279 if (this.schedulePublicationEnabled) {
280 scheduleControl.setValidators([ Validators.required ])
281
282 waitTranscodingControl.disable()
283 waitTranscodingControl.setValue(false)
284 } else {
285 scheduleControl.clearValidators()
286
287 waitTranscodingControl.enable()
288
289 // Do not update the control value on first patch (values come from the server)
290 if (this.firstPatchDone === true) {
291 waitTranscodingControl.setValue(true)
292 }
293 }
294
295 scheduleControl.updateValueAndValidity()
296 waitTranscodingControl.updateValueAndValidity()
297
298 this.firstPatchDone = true
299
300 }
301 )
302 }
303
304 private trackChannelChange () {
305 // We will update the "support" field depending on the channel
306 this.form.controls[ 'channelId' ]
307 .valueChanges
308 .pipe(map(res => parseInt(res.toString(), 10)))
309 .subscribe(
310 newChannelId => {
311 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
312
313 // Not initialized yet
314 if (isNaN(newChannelId)) return
315 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
316 if (!newChannel) return
317
318 // Wait support field update
319 setTimeout(() => {
320 const currentSupport = this.form.value[ 'support' ]
321
322 // First time we set the channel?
323 if (isNaN(oldChannelId) && !currentSupport) return this.updateSupportField(newChannel.support)
324
325 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
326 if (!newChannel || !oldChannel) {
327 console.error('Cannot find new or old channel.')
328 return
329 }
330
331 // If the current support text is not the same than the old channel, the user updated it.
332 // We don't want the user to lose his text, so stop here
333 if (currentSupport && currentSupport !== oldChannel.support) return
334
335 // Update the support text with our new channel
336 this.updateSupportField(newChannel.support)
337 })
338 }
339 )
340 }
341
342 private updateSupportField (support: string) {
343 return this.form.patchValue({ support: support || '' })
344 }
345 }