Merge branch 'develop' into pr/1285
[oweals/peertube.git] / client / src / app / videos / +video-edit / shared / video-edit.component.ts
1 import { Component, Input, 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[] = []
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   ) {
67     this.tagValidators = this.videoValidatorsService.VIDEO_TAGS.VALIDATORS
68     this.tagValidatorsMessages = this.videoValidatorsService.VIDEO_TAGS.MESSAGES
69
70     this.calendarLocale = this.i18nPrimengCalendarService.getCalendarLocale()
71     this.calendarTimezone = this.i18nPrimengCalendarService.getTimezone()
72     this.calendarDateFormat = this.i18nPrimengCalendarService.getDateFormat()
73   }
74
75   get existingCaptions () {
76     return this.videoCaptions
77                .filter(c => c.action !== 'REMOVE')
78                .map(c => c.language.id)
79   }
80
81   updateForm () {
82     const defaultValues: any = {
83       nsfw: 'false',
84       commentsEnabled: 'true',
85       downloadEnabled: 'true',
86       waitTranscoding: 'true',
87       tags: []
88     }
89     const obj: any = {
90       name: this.videoValidatorsService.VIDEO_NAME,
91       privacy: this.videoValidatorsService.VIDEO_PRIVACY,
92       channelId: this.videoValidatorsService.VIDEO_CHANNEL,
93       nsfw: null,
94       commentsEnabled: null,
95       downloadEnabled: null,
96       waitTranscoding: null,
97       category: this.videoValidatorsService.VIDEO_CATEGORY,
98       licence: this.videoValidatorsService.VIDEO_LICENCE,
99       language: this.videoValidatorsService.VIDEO_LANGUAGE,
100       description: this.videoValidatorsService.VIDEO_DESCRIPTION,
101       tags: null,
102       thumbnailfile: null,
103       previewfile: null,
104       support: this.videoValidatorsService.VIDEO_SUPPORT,
105       schedulePublicationAt: this.videoValidatorsService.VIDEO_SCHEDULE_PUBLICATION_AT,
106       originallyPublishedAt: this.videoValidatorsService.VIDEO_ORIGINALLY_PUBLISHED_AT
107     }
108
109     this.formValidatorService.updateForm(
110       this.form,
111       this.formErrors,
112       this.validationMessages,
113       obj,
114       defaultValues
115     )
116
117     this.form.addControl('captions', new FormArray([
118       new FormGroup({
119         language: new FormControl(),
120         captionfile: new FormControl()
121       })
122     ]))
123
124     this.trackChannelChange()
125     this.trackPrivacyChange()
126   }
127
128   ngOnInit () {
129     this.updateForm()
130
131     this.videoCategories = this.serverService.getVideoCategories()
132     this.videoLicences = this.serverService.getVideoLicences()
133     this.videoLanguages = this.serverService.getVideoLanguages()
134
135     this.schedulerInterval = setInterval(() => this.minScheduledDate = new Date(), 1000 * 60) // Update every minute
136
137     this.initialVideoCaptions = this.videoCaptions.map(c => c.language.id)
138   }
139
140   ngOnDestroy () {
141     if (this.schedulerInterval) clearInterval(this.schedulerInterval)
142   }
143
144   onCaptionAdded (caption: VideoCaptionEdit) {
145     const existingCaption = this.videoCaptions.find(c => c.language.id === caption.language.id)
146
147     // Replace existing caption?
148     if (existingCaption) {
149       Object.assign(existingCaption, caption, { action: 'CREATE' as 'CREATE' })
150     } else {
151       this.videoCaptions.push(
152         Object.assign(caption, { action: 'CREATE' as 'CREATE' })
153       )
154     }
155
156     this.sortVideoCaptions()
157   }
158
159   async deleteCaption (caption: VideoCaptionEdit) {
160     // Caption recovers his former state
161     if (caption.action && this.initialVideoCaptions.indexOf(caption.language.id) !== -1) {
162       caption.action = undefined
163       return
164     }
165
166     // This caption is not on the server, just remove it from our array
167     if (caption.action === 'CREATE') {
168       removeElementFromArray(this.videoCaptions, caption)
169       return
170     }
171
172     caption.action = 'REMOVE' as 'REMOVE'
173   }
174
175   openAddCaptionModal () {
176     this.videoCaptionAddModal.show()
177   }
178
179   private sortVideoCaptions () {
180     this.videoCaptions.sort((v1, v2) => {
181       if (v1.language.label < v2.language.label) return -1
182       if (v1.language.label === v2.language.label) return 0
183
184       return 1
185     })
186   }
187
188   private trackPrivacyChange () {
189     // We will update the "support" field depending on the channel
190     this.form.controls[ 'privacy' ]
191       .valueChanges
192       .pipe(map(res => parseInt(res.toString(), 10)))
193       .subscribe(
194         newPrivacyId => {
195
196           this.schedulePublicationEnabled = newPrivacyId === this.SPECIAL_SCHEDULED_PRIVACY
197
198           // Value changed
199           const scheduleControl = this.form.get('schedulePublicationAt')
200           const waitTranscodingControl = this.form.get('waitTranscoding')
201
202           if (this.schedulePublicationEnabled) {
203             scheduleControl.setValidators([ Validators.required ])
204
205             waitTranscodingControl.disable()
206             waitTranscodingControl.setValue(false)
207           } else {
208             scheduleControl.clearValidators()
209
210             waitTranscodingControl.enable()
211
212             // Do not update the control value on first patch (values come from the server)
213             if (this.firstPatchDone === true) {
214               waitTranscodingControl.setValue(true)
215             }
216           }
217
218           scheduleControl.updateValueAndValidity()
219           waitTranscodingControl.updateValueAndValidity()
220
221           this.firstPatchDone = true
222
223         }
224       )
225   }
226
227   private trackChannelChange () {
228     // We will update the "support" field depending on the channel
229     this.form.controls[ 'channelId' ]
230       .valueChanges
231       .pipe(map(res => parseInt(res.toString(), 10)))
232       .subscribe(
233         newChannelId => {
234           const oldChannelId = parseInt(this.form.value[ 'channelId' ], 10)
235           const currentSupport = this.form.value[ 'support' ]
236
237           // Not initialized yet
238           if (isNaN(newChannelId)) return
239           const newChannel = this.userVideoChannels.find(c => c.id === newChannelId)
240           if (!newChannel) return
241
242           // First time we set the channel?
243           if (isNaN(oldChannelId)) return this.updateSupportField(newChannel.support)
244           const oldChannel = this.userVideoChannels.find(c => c.id === oldChannelId)
245
246           if (!newChannel || !oldChannel) {
247             console.error('Cannot find new or old channel.')
248             return
249           }
250
251           // If the current support text is not the same than the old channel, the user updated it.
252           // We don't want the user to lose his text, so stop here
253           if (currentSupport && currentSupport !== oldChannel.support) return
254
255           // Update the support text with our new channel
256           this.updateSupportField(newChannel.support)
257         }
258       )
259   }
260
261   private updateSupportField (support: string) {
262     return this.form.patchValue({ support: support || '' })
263   }
264 }