Merge branch 'release/v1.2.0'
[oweals/peertube.git] / client / src / app / core / server / server.service.ts
1 import { map, shareReplay, switchMap, tap } from 'rxjs/operators'
2 import { HttpClient } from '@angular/common/http'
3 import { Inject, Injectable, LOCALE_ID } from '@angular/core'
4 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
5 import { Observable, of, ReplaySubject } from 'rxjs'
6 import { getCompleteLocale, ServerConfig } from '../../../../../shared'
7 import { About } from '../../../../../shared/models/server/about.model'
8 import { environment } from '../../../environments/environment'
9 import { VideoConstant, VideoPrivacy } from '../../../../../shared/models/videos'
10 import { isDefaultLocale, peertubeTranslate } from '../../../../../shared/models/i18n'
11 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
12 import { sortBy } from '@app/shared/misc/utils'
13
14 @Injectable()
15 export class ServerService {
16   private static BASE_SERVER_URL = environment.apiUrl + '/api/v1/server/'
17   private static BASE_CONFIG_URL = environment.apiUrl + '/api/v1/config/'
18   private static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
19   private static BASE_LOCALE_URL = environment.apiUrl + '/client/locales/'
20   private static CONFIG_LOCAL_STORAGE_KEY = 'server-config'
21
22   configLoaded = new ReplaySubject<boolean>(1)
23   videoPrivaciesLoaded = new ReplaySubject<boolean>(1)
24   videoCategoriesLoaded = new ReplaySubject<boolean>(1)
25   videoLicencesLoaded = new ReplaySubject<boolean>(1)
26   videoLanguagesLoaded = new ReplaySubject<boolean>(1)
27   localeObservable: Observable<any>
28
29   private config: ServerConfig = {
30     instance: {
31       name: 'PeerTube',
32       shortDescription: 'PeerTube, a federated (ActivityPub) video streaming platform  ' +
33                         'using P2P (BitTorrent) directly in the web browser with WebTorrent and Angular.',
34       defaultClientRoute: '',
35       defaultNSFWPolicy: 'do_not_list' as 'do_not_list',
36       customizations: {
37         javascript: '',
38         css: ''
39       }
40     },
41     email: {
42       enabled: false
43     },
44     contactForm: {
45       enabled: false
46     },
47     serverVersion: 'Unknown',
48     signup: {
49       allowed: false,
50       allowedForCurrentIP: false,
51       requiresEmailVerification: false
52     },
53     transcoding: {
54       enabledResolutions: []
55     },
56     avatar: {
57       file: {
58         size: { max: 0 },
59         extensions: []
60       }
61     },
62     video: {
63       image: {
64         size: { max: 0 },
65         extensions: []
66       },
67       file: {
68         extensions: []
69       }
70     },
71     videoCaption: {
72       file: {
73         size: { max: 0 },
74         extensions: []
75       }
76     },
77     user: {
78       videoQuota: -1,
79       videoQuotaDaily: -1
80     },
81     import: {
82       videos: {
83         http: {
84           enabled: false
85         },
86         torrent: {
87           enabled: false
88         }
89       }
90     },
91     trending: {
92       videos: {
93         intervalDays: 0
94       }
95     }
96   }
97   private videoCategories: Array<VideoConstant<number>> = []
98   private videoLicences: Array<VideoConstant<number>> = []
99   private videoLanguages: Array<VideoConstant<string>> = []
100   private videoPrivacies: Array<VideoConstant<VideoPrivacy>> = []
101
102   constructor (
103     private http: HttpClient,
104     @Inject(LOCALE_ID) private localeId: string
105   ) {
106     this.loadServerLocale()
107     this.loadConfigLocally()
108   }
109
110   loadConfig () {
111     this.http.get<ServerConfig>(ServerService.BASE_CONFIG_URL)
112         .pipe(tap(this.saveConfigLocally))
113         .subscribe(data => {
114           this.config = data
115
116           this.configLoaded.next(true)
117         })
118   }
119
120   loadVideoCategories () {
121     return this.loadVideoAttributeEnum('categories', this.videoCategories, this.videoCategoriesLoaded, true)
122   }
123
124   loadVideoLicences () {
125     return this.loadVideoAttributeEnum('licences', this.videoLicences, this.videoLicencesLoaded)
126   }
127
128   loadVideoLanguages () {
129     return this.loadVideoAttributeEnum('languages', this.videoLanguages, this.videoLanguagesLoaded, true)
130   }
131
132   loadVideoPrivacies () {
133     return this.loadVideoAttributeEnum('privacies', this.videoPrivacies, this.videoPrivaciesLoaded)
134   }
135
136   getConfig () {
137     return this.config
138   }
139
140   getVideoCategories () {
141     return this.videoCategories
142   }
143
144   getVideoLicences () {
145     return this.videoLicences
146   }
147
148   getVideoLanguages () {
149     return this.videoLanguages
150   }
151
152   getVideoPrivacies () {
153     return this.videoPrivacies
154   }
155
156   private loadVideoAttributeEnum (
157     attributeName: 'categories' | 'licences' | 'languages' | 'privacies',
158     hashToPopulate: VideoConstant<string | number>[],
159     notifier: ReplaySubject<boolean>,
160     sort = false
161   ) {
162     this.localeObservable
163         .pipe(
164           switchMap(translations => {
165             return this.http.get<{ [id: string]: string }>(ServerService.BASE_VIDEO_URL + attributeName)
166                        .pipe(map(data => ({ data, translations })))
167           })
168         )
169         .subscribe(({ data, translations }) => {
170           Object.keys(data)
171                 .forEach(dataKey => {
172                   const label = data[ dataKey ]
173
174                   hashToPopulate.push({
175                     id: attributeName === 'languages' ? dataKey : parseInt(dataKey, 10),
176                     label: peertubeTranslate(label, translations)
177                   })
178                 })
179
180           if (sort === true) sortBy(hashToPopulate, 'label')
181
182           notifier.next(true)
183         })
184   }
185
186   private loadServerLocale () {
187     const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
188
189     // Default locale, nothing to translate
190     if (isDefaultLocale(completeLocale)) {
191       this.localeObservable = of({}).pipe(shareReplay())
192       return
193     }
194
195     this.localeObservable = this.http
196                                   .get(ServerService.BASE_LOCALE_URL + completeLocale + '/server.json')
197                                   .pipe(shareReplay())
198   }
199
200   private saveConfigLocally (config: ServerConfig) {
201     peertubeLocalStorage.setItem(ServerService.CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config))
202   }
203
204   private loadConfigLocally () {
205     const configString = peertubeLocalStorage.getItem(ServerService.CONFIG_LOCAL_STORAGE_KEY)
206
207     if (configString) {
208       try {
209         const parsed = JSON.parse(configString)
210         Object.assign(this.config, parsed)
211       } catch (err) {
212         console.error('Cannot parse config saved in local storage.', err)
213       }
214     }
215   }
216 }