1 import { HttpClient } from '@angular/common/http'
2 import { Injectable } from '@angular/core'
3 import 'rxjs/add/operator/do'
4 import { ReplaySubject } from 'rxjs/ReplaySubject'
5 import { ServerConfig } from '../../../../../shared'
6 import { About } from '../../../../../shared/models/config/about.model'
7 import { environment } from '../../../environments/environment'
10 export class ServerService {
11 private static BASE_CONFIG_URL = environment.apiUrl + '/api/v1/config/'
12 private static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
13 private static CONFIG_LOCAL_STORAGE_KEY = 'server-config'
15 videoPrivaciesLoaded = new ReplaySubject<boolean>(1)
16 videoCategoriesLoaded = new ReplaySubject<boolean>(1)
17 videoLicencesLoaded = new ReplaySubject<boolean>(1)
18 videoLanguagesLoaded = new ReplaySubject<boolean>(1)
20 private config: ServerConfig = {
24 serverVersion: 'Unknown',
29 enabledResolutions: []
43 private videoCategories: Array<{ id: number, label: string }> = []
44 private videoLicences: Array<{ id: number, label: string }> = []
45 private videoLanguages: Array<{ id: number, label: string }> = []
46 private videoPrivacies: Array<{ id: number, label: string }> = []
48 constructor (private http: HttpClient) {
49 this.loadConfigLocally()
53 this.http.get<ServerConfig>(ServerService.BASE_CONFIG_URL)
54 .do(this.saveConfigLocally)
55 .subscribe(data => this.config = data)
58 loadVideoCategories () {
59 return this.loadVideoAttributeEnum('categories', this.videoCategories, this.videoCategoriesLoaded)
62 loadVideoLicences () {
63 return this.loadVideoAttributeEnum('licences', this.videoLicences, this.videoLicencesLoaded)
66 loadVideoLanguages () {
67 return this.loadVideoAttributeEnum('languages', this.videoLanguages, this.videoLanguagesLoaded)
70 loadVideoPrivacies () {
71 return this.loadVideoAttributeEnum('privacies', this.videoPrivacies, this.videoPrivaciesLoaded)
78 getVideoCategories () {
79 return this.videoCategories
83 return this.videoLicences
86 getVideoLanguages () {
87 return this.videoLanguages
90 getVideoPrivacies () {
91 return this.videoPrivacies
95 return this.http.get<About>(ServerService.BASE_CONFIG_URL + '/about')
98 private loadVideoAttributeEnum (
99 attributeName: 'categories' | 'licences' | 'languages' | 'privacies',
100 hashToPopulate: { id: number, label: string }[],
101 notifier: ReplaySubject<boolean>
103 return this.http.get(ServerService.BASE_VIDEO_URL + attributeName)
106 .forEach(dataKey => {
107 hashToPopulate.push({
108 id: parseInt(dataKey, 10),
117 private saveConfigLocally (config: ServerConfig) {
118 localStorage.setItem(ServerService.CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config))
121 private loadConfigLocally () {
122 const configString = localStorage.getItem(ServerService.CONFIG_LOCAL_STORAGE_KEY)
126 const parsed = JSON.parse(configString)
127 Object.assign(this.config, parsed)
129 console.error('Cannot parse config saved in local storage.', err)