]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-edit/shared/video-edit.component.ts
Fix error in form when scheduling video publication
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-edit / shared / video-edit.component.ts
1 import { Component, Input, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
2 import { FormArray, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { FormReactiveValidationMessages, VideoValidatorsService } from '@app/shared'
5 import { Notifier } from '@app/core'
6 import { ServerService } from '../../../core/server'
7 import { VideoEdit } from '../../../shared/video/video-edit.model'
8 import { map } from 'rxjs/operators'
9 import { FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
10 import { I18nPrimengCalendarService } from '@app/shared/i18n/i18n-primeng-calendar'
11 import { VideoCaptionService } from '@app/shared/video-caption'
12 import { VideoCaptionAddModalComponent } from '@app/videos/+video-edit/shared/video-caption-add-modal.component'
13 import { VideoCaptionEdit } from '@app/shared/video-caption/video-caption-edit.model'
14 import { removeElementFromArray } from '@app/shared/misc/utils'
15 import { VideoConstant, VideoPrivacy } from '../../../../../../shared'
16
17 @Component({
18 selector: 'my-video-edit',
19 styleUrls: [ './video-edit.component.scss' ],
20 templateUrl: './video-edit.component.html'
21 })
22 export class VideoEditComponent implements OnInit, OnDestroy {
23 @Input() form: FormGroup
24 @Input() formErrors: { [ id: string ]: string } = {}
25 @Input() validationMessages: FormReactiveValidationMessages = {}
26 @Input() videoPrivacies: VideoConstant<VideoPrivacy>[] = []
27 @Input() userVideoChannels: { id: number, label: string, support: string }[] = []
28 @Input() schedulePublicationPossible = true
29 @Input() videoCaptions: (VideoCaptionEdit & { captionPath?: string })[] = []
30 @Input() waitTranscodingEnabled = true
31
32 @ViewChild('videoCaptionAddModal') videoCaptionAddModal: VideoCaptionAddModalComponent
33
34 // So that it can be accessed in the template
35 readonly SPECIAL_SCHEDULED_PRIVACY = VideoEdit.SPECIAL_SCHEDULED_PRIVACY
36
37 videoCategories: VideoConstant<number>[] = []
38 videoLicences: VideoConstant<number>[] = []
39 videoLanguages: VideoConstant<string>[] = []
40
41 tagValidators: ValidatorFn[]
42 tagValidatorsMessages: { [ name: string ]: string }
43
44 schedulePublicationEnabled = false
45
46 calendarLocale: any = {}
47 minScheduledDate = new Date()
48 myYearRange = '1880:' + (new Date()).getFullYear()
49
50 calendarTimezone: string
51 calendarDateFormat: string
52
53 private schedulerInterval: any
54 private firstPatchDone = false
55 private initialVideoCaptions: string[] = []
56
57 constructor (
58 private formValidatorService: FormValidatorService,
59 private videoValidatorsService: VideoValidatorsService,
60 private videoCaptionService: VideoCaptionService,
61 private route: ActivatedRoute,
62 private router: Router,
63 private notifier: Notifier,
64 private serverService: ServerService,
65 private i18nPrimengCalendarService: I18nPrimengCalendarService,
66 private ngZone: NgZone
67 ) {
68 this.tagValidators = this.videoValidatorsService.VIDEO_TAGS.VALIDATORS
69 this.tagValidatorsMessages = this.videoValidatorsService.VIDEO_TAGS.MESSAGES
70
71 this.calendarLocale = this.i18nPrimengCalendarService.getCalendarLocale()
72 this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
73 this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
74 }
75
76 get existingCaptions () {
77 return this.videoCaptions
78 .filter(c => c.action !== 'REMOVE')
79 .map(c => c.language.id)
80 }
81
82 updateForm () {
83 const defaultValues: any = {
84 nsfw: 'false',
85 commentsEnabled: 'true',
86 downloadEnabled: 'true',
87 waitTranscoding: 'true',
88 tags: []
89 }
90 const obj: any = {
91 name: this.videoValidatorsService.VIDEO_NAME,
92 privacy: this.videoValidatorsService.VIDEO_PRIVACY,
93 channelId: this.videoValidatorsService.VIDEO_CHANNEL,
94 nsfw: null,
95 commentsEnabled: null,
96 downloadEnabled: null,
97 waitTranscoding: null,
98 category: this.videoValidatorsService.VIDEO_CATEGORY,
99 licence: this.videoValidatorsService.VIDEO_LICENCE,
100 language: this.videoValidatorsService.VIDEO_LANGUAGE,
101 description: this.videoValidatorsService.VIDEO_DESCRIPTION,
102 tags: null,
103 thumbnailfile: null,
104 previewfile: null,
105 support: this.videoValidatorsService.VIDEO_SUPPORT,
106 schedulePublicationAt: this.videoValidatorsService.VIDEO_SCHEDULE_PUBLICATION_AT,
107 originallyPublishedAt: this.videoValidatorsService.VIDEO_ORIGINALLY_PUBLISHED_AT
108 }
109
110 this.formValidatorService.updateForm(
111 this.form,
112 this.formErrors,
113 this.validationMessages,
114 obj,
115 defaultValues
116 )
117
118 this.form.addControl('captions', new FormArray([
119 new FormGroup({
120 language: new FormControl(),
121 captionfile: new FormControl()
122 })
123 ]))
124
125 this.trackChannelChange()
126 this.trackPrivacyChange()
127 }
128
129 ngOnInit () {
130 this.updateForm()
131
132 this.videoCategories = this.serverService.getVideoCategories()
133 this.videoLicences = this.serverService.getVideoLicences()
134 this.videoLanguages = this.serverService.getVideoLanguages()
135
136 this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
137
138 this.ngZone.runOutsideAngular(() => {
139 this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
140 })
141 }
142
143 ngOnDestroy () {
144 if (this.schedulerInterval) clearInterval(this.schedulerInterval)
145 }
146
147 onCaptionAdded (caption: VideoCaptionEdit) {
148 const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
149
150 // Replace existing caption?
151 if (existingCaption) {
152 Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
153 } else {
154 this.videoCaptions.push(
155 Object.assign(caption, { action: 'CREATE' as 'CREATE' })
156 )
157 }
158
159 this.sortVideoCaptions()
160 }
161
162 async deleteCaption (caption: VideoCaptionEdit) {
163 // Caption recovers his former state
164 if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
165 caption.action = undefined
166 return
167 }
168
169 // This caption is not on the server, just remove it from our array
170 if (caption.action === 'CREATE') {
171 removeElementFromArray(this.videoCaptions, caption)
172 return
173 }
174
175 caption.action = 'REMOVE' as 'REMOVE'
176 }
177
178 openAddCaptionModal () {
179 this.videoCaptionAddModal.show()
180 }
181
182 private sortVideoCaptions () {
183 this.videoCaptions.sort((v1, v2) => {
184 if (v1.language.label < v2.language.label) return -1
185 if (v1.language.label === v2.language.label) return 0
186
187 return 1
188 })
189 }
190
191 private trackPrivacyChange () {
192 // We will update the schedule input and the wait transcoding checkbox validators
193 this.form.controls[ 'privacy' ]
194 .valueChanges
195 .pipe(map(res => parseInt(res.toString(), 10)))
196 .subscribe(
197 newPrivacyId => {
198
199 this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
200
201 // Value changed
202 const scheduleControl = this.form.get('schedulePublicationAt')
203 const waitTranscodingControl = this.form.get('waitTranscoding')
204
205 if (this.schedulePublicationEnabled) {
206 scheduleControl.setValidators([ Validators.required ])
207
208 waitTranscodingControl.disable()
209 waitTranscodingControl.setValue(false)
210 } else {
211 scheduleControl.clearValidators()
212
213 waitTranscodingControl.enable()
214
215 // Do not update the control value on first patch (values come from the server)
216 if (this.firstPatchDone === true) {
217 waitTranscodingControl.setValue(true)
218 }
219 }
220
221 scheduleControl.updateValueAndValidity()
222 waitTranscodingControl.updateValueAndValidity()
223
224 this.firstPatchDone = true
225
226 }
227 )
228 }
229
230 private trackChannelChange () {
231 // We will update the "support" field depending on the channel
232 this.form.controls[ 'channelId' ]
233 .valueChanges
234 .pipe(map(res => parseInt(res.toString(), 10)))
235 .subscribe(
236 newChannelId => {
237 const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
238 const currentSupport = this.form.value[ 'support' ]
239
240 // Not initialized yet
241 if (isNaN(newChannelId)) return
242 const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
243 if (!newChannel) return
244
245 // First time we set the channel?
246 if (isNaN(oldChannelId)) return this.updateSupportField(newChannel.support)
247 const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
248
249 if (!newChannel || !oldChannel) {
250 console.error('Cannot find new or old channel.')
251 return
252 }
253
254 // If the current support text is not the same than the old channel, the user updated it.
255 // We don't want the user to lose his text, so stop here
256 if (currentSupport && currentSupport !== oldChannel.support) return
257
258 // Update the support text with our new channel
259 this.updateSupportField(newChannel.support)
260 }
261 )
262 }
263
264 private updateSupportField (support: string) {
265 return this.form.patchValue({ support: support || '' })
266 }
267 }