]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.service.ts
32a13520366eb200edba3342e7557faabff64aa4
[github/Chocobozzz/PeerTube.git] / server.service.ts
1 import { Observable, of, Subject } from 'rxjs'
2 import { first, map, share, shareReplay, switchMap, tap } from 'rxjs/operators'
3 import { HttpClient } from '@angular/common/http'
4 import { Inject, Injectable, LOCALE_ID } from '@angular/core'
5 import { getDevLocale, isOnDevLocale, peertubeLocalStorage, sortBy } from '@app/helpers'
6 import {
7 getCompleteLocale,
8 isDefaultLocale,
9 peertubeTranslate,
10 SearchTargetType,
11 ServerConfig,
12 ServerStats,
13 VideoConstant
14 } from '@shared/models'
15 import { environment } from '../../../environments/environment'
16
17 @Injectable()
18 export class ServerService {
19 private static BASE_CONFIG_URL = environment.apiUrl + '/api/v1/config/'
20 private static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
21 private static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
22 private static BASE_LOCALE_URL = environment.apiUrl + '/client/locales/'
23 private static BASE_STATS_URL = environment.apiUrl + '/api/v1/server/stats'
24
25 private static CONFIG_LOCAL_STORAGE_KEY = 'server-config'
26
27 configReloaded = new Subject<ServerConfig>()
28
29 private localeObservable: Observable<any>
30 private videoLicensesObservable: Observable<VideoConstant<number>[]>
31 private videoCategoriesObservable: Observable<VideoConstant<number>[]>
32 private videoPrivaciesObservable: Observable<VideoConstant<number>[]>
33 private videoPlaylistPrivaciesObservable: Observable<VideoConstant<number>[]>
34 private videoLanguagesObservable: Observable<VideoConstant<string>[]>
35 private configObservable: Observable<ServerConfig>
36
37 private configReset = false
38
39 private configLoaded = false
40 private config: ServerConfig = {
41 instance: {
42 name: 'PeerTube',
43 shortDescription: 'PeerTube, a federated (ActivityPub) video streaming platform ' +
44 'using P2P (BitTorrent) directly in the web browser with WebTorrent and Angular.',
45 defaultClientRoute: '',
46 isNSFW: false,
47 defaultNSFWPolicy: 'do_not_list' as 'do_not_list',
48 customizations: {
49 javascript: '',
50 css: ''
51 }
52 },
53 plugin: {
54 registered: [],
55 registeredExternalAuths: [],
56 registeredIdAndPassAuths: []
57 },
58 theme: {
59 registered: [],
60 default: 'default'
61 },
62 email: {
63 enabled: false
64 },
65 contactForm: {
66 enabled: false
67 },
68 serverVersion: 'Unknown',
69 signup: {
70 allowed: false,
71 allowedForCurrentIP: false,
72 requiresEmailVerification: false
73 },
74 transcoding: {
75 enabledResolutions: [],
76 hls: {
77 enabled: false
78 },
79 webtorrent: {
80 enabled: true
81 }
82 },
83 avatar: {
84 file: {
85 size: { max: 0 },
86 extensions: []
87 }
88 },
89 video: {
90 image: {
91 size: { max: 0 },
92 extensions: []
93 },
94 file: {
95 extensions: []
96 }
97 },
98 videoCaption: {
99 file: {
100 size: { max: 0 },
101 extensions: []
102 }
103 },
104 user: {
105 videoQuota: -1,
106 videoQuotaDaily: -1
107 },
108 import: {
109 videos: {
110 http: {
111 enabled: false
112 },
113 torrent: {
114 enabled: false
115 }
116 }
117 },
118 trending: {
119 videos: {
120 intervalDays: 0
121 }
122 },
123 autoBlacklist: {
124 videos: {
125 ofUsers: {
126 enabled: false
127 }
128 }
129 },
130 tracker: {
131 enabled: true
132 },
133 followings: {
134 instance: {
135 autoFollowIndex: {
136 indexUrl: 'https://instances.joinpeertube.org'
137 }
138 }
139 },
140 broadcastMessage: {
141 enabled: false,
142 message: '',
143 level: 'info',
144 dismissable: false
145 },
146 search: {
147 remoteUri: {
148 users: true,
149 anonymous: false
150 },
151 searchIndex: {
152 enabled: false,
153 url: '',
154 disableLocalSearch: false,
155 isDefaultSearch: false
156 }
157 }
158 }
159
160 constructor (
161 private http: HttpClient,
162 @Inject(LOCALE_ID) private localeId: string
163 ) {
164 this.loadConfigLocally()
165 }
166
167 getServerVersionAndCommit () {
168 const serverVersion = this.config.serverVersion
169 const commit = this.config.serverCommit || ''
170
171 let result = serverVersion
172 if (commit) result += '...' + commit
173
174 return result
175 }
176
177 resetConfig () {
178 this.configLoaded = false
179 this.configReset = true
180
181 // Notify config update
182 this.getConfig().subscribe(() => {
183 // empty, to fire a reset config event
184 })
185 }
186
187 getConfig () {
188 if (this.configLoaded) return of(this.config)
189
190 if (!this.configObservable) {
191 this.configObservable = this.http.get<ServerConfig>(ServerService.BASE_CONFIG_URL)
192 .pipe(
193 tap(config => this.saveConfigLocally(config)),
194 tap(config => {
195 this.config = config
196 this.configLoaded = true
197 }),
198 tap(config => {
199 if (this.configReset) {
200 this.configReloaded.next(config)
201 this.configReset = false
202 }
203 }),
204 share()
205 )
206 }
207
208 return this.configObservable
209 }
210
211 getTmpConfig () {
212 return this.config
213 }
214
215 getVideoCategories () {
216 if (!this.videoCategoriesObservable) {
217 this.videoCategoriesObservable = this.loadAttributeEnum<number>(ServerService.BASE_VIDEO_URL, 'categories', true)
218 }
219
220 return this.videoCategoriesObservable.pipe(first())
221 }
222
223 getVideoLicences () {
224 if (!this.videoLicensesObservable) {
225 this.videoLicensesObservable = this.loadAttributeEnum<number>(ServerService.BASE_VIDEO_URL, 'licences')
226 }
227
228 return this.videoLicensesObservable.pipe(first())
229 }
230
231 getVideoLanguages () {
232 if (!this.videoLanguagesObservable) {
233 this.videoLanguagesObservable = this.loadAttributeEnum<string>(ServerService.BASE_VIDEO_URL, 'languages', true)
234 }
235
236 return this.videoLanguagesObservable.pipe(first())
237 }
238
239 getVideoPrivacies () {
240 if (!this.videoPrivaciesObservable) {
241 this.videoPrivaciesObservable = this.loadAttributeEnum<number>(ServerService.BASE_VIDEO_URL, 'privacies')
242 }
243
244 return this.videoPrivaciesObservable.pipe(first())
245 }
246
247 getVideoPlaylistPrivacies () {
248 if (!this.videoPlaylistPrivaciesObservable) {
249 this.videoPlaylistPrivaciesObservable = this.loadAttributeEnum<number>(ServerService.BASE_VIDEO_PLAYLIST_URL, 'privacies')
250 }
251
252 return this.videoPlaylistPrivaciesObservable.pipe(first())
253 }
254
255 getServerLocale () {
256 if (!this.localeObservable) {
257 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
258
259 // Default locale, nothing to translate
260 if (isDefaultLocale(completeLocale)) {
261 this.localeObservable = of({}).pipe(shareReplay())
262 } else {
263 this.localeObservable = this.http
264 .get(ServerService.BASE_LOCALE_URL + completeLocale + '/server.json')
265 .pipe(shareReplay())
266 }
267 }
268
269 return this.localeObservable.pipe(first())
270 }
271
272 getServerStats () {
273 return this.http.get<ServerStats>(ServerService.BASE_STATS_URL)
274 }
275
276 getDefaultSearchTarget (): Promise<SearchTargetType> {
277 return this.getConfig().pipe(
278 map(config => {
279 const searchIndexConfig = config.search.searchIndex
280
281 if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
282 return 'search-index'
283 }
284
285 return 'local'
286 })
287 ).toPromise()
288 }
289
290 private loadAttributeEnum <T extends string | number> (
291 baseUrl: string,
292 attributeName: 'categories' | 'licences' | 'languages' | 'privacies',
293 sort = false
294 ) {
295 return this.getServerLocale()
296 .pipe(
297 switchMap(translations => {
298 return this.http.get<{ [ id: string ]: string }>(baseUrl + attributeName)
299 .pipe(map(data => ({ data, translations })))
300 }),
301 map(({ data, translations }) => {
302 const hashToPopulate: VideoConstant<T>[] = Object.keys(data)
303 .map(dataKey => {
304 const label = data[ dataKey ]
305
306 const id = attributeName === 'languages'
307 ? dataKey as T
308 : parseInt(dataKey, 10) as T
309
310 return {
311 id,
312 label: peertubeTranslate(label, translations)
313 }
314 })
315
316 if (sort === true) sortBy(hashToPopulate, 'label')
317
318 return hashToPopulate
319 }),
320 shareReplay()
321 )
322 }
323
324 private saveConfigLocally (config: ServerConfig) {
325 peertubeLocalStorage.setItem(ServerService.CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config))
326 }
327
328 private loadConfigLocally () {
329 const configString = peertubeLocalStorage.getItem(ServerService.CONFIG_LOCAL_STORAGE_KEY)
330
331 if (configString) {
332 try {
333 const parsed = JSON.parse(configString)
334 Object.assign(this.config, parsed)
335 } catch (err) {
336 console.error('Cannot parse config saved in local storage.', err)
337 }
338 }
339 }
340 }