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