]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/theme/theme.service.ts
Use random port for mock servers in tests
[github/Chocobozzz/PeerTube.git] / client / src / app / core / theme / theme.service.ts
1 import { first } from 'rxjs/operators'
2 import { Injectable } from '@angular/core'
3 import { UserLocalStorageKeys } from '@root-helpers/users'
4 import { ServerConfig, ServerConfigTheme } from '@shared/models'
5 import { environment } from '../../../environments/environment'
6 import { AuthService } from '../auth'
7 import { PluginService } from '../plugins/plugin.service'
8 import { ServerService } from '../server'
9 import { UserService } from '../users/user.service'
10 import { LocalStorageService } from '../wrappers/storage.service'
11
12 @Injectable()
13 export class ThemeService {
14
15 private oldThemeName: string
16 private themes: ServerConfigTheme[] = []
17
18 private themeFromLocalStorage: ServerConfigTheme
19 private themeDOMLinksFromLocalStorage: HTMLLinkElement[] = []
20
21 private serverConfig: ServerConfig
22
23 constructor (
24 private auth: AuthService,
25 private userService: UserService,
26 private pluginService: PluginService,
27 private server: ServerService,
28 private localStorageService: LocalStorageService
29 ) {}
30
31 initialize () {
32 // Try to load from local storage first, so we don't have to wait network requests
33 this.loadAndSetFromLocalStorage()
34
35 this.serverConfig = this.server.getTmpConfig()
36 this.server.getConfig()
37 .subscribe(config => {
38 this.serverConfig = config
39
40 const themes = this.serverConfig.theme.registered
41
42 this.removeThemeFromLocalStorageIfNeeded(themes)
43 this.injectThemes(themes)
44
45 this.listenUserTheme()
46 })
47 }
48
49 private injectThemes (themes: ServerConfigTheme[], fromLocalStorage = false) {
50 this.themes = themes
51
52 console.log('Injecting %d themes.', this.themes.length)
53
54 const head = this.getHeadElement()
55
56 for (const theme of this.themes) {
57 // Already added this theme?
58 if (fromLocalStorage === false && this.themeFromLocalStorage && this.themeFromLocalStorage.name === theme.name) continue
59
60 for (const css of theme.css) {
61 const link = document.createElement('link')
62
63 const href = environment.apiUrl + `/themes/${theme.name}/${theme.version}/css/${css}`
64 link.setAttribute('href', href)
65 link.setAttribute('rel', 'alternate stylesheet')
66 link.setAttribute('type', 'text/css')
67 link.setAttribute('title', theme.name)
68 link.setAttribute('disabled', '')
69
70 if (fromLocalStorage === true) this.themeDOMLinksFromLocalStorage.push(link)
71
72 head.appendChild(link)
73 }
74 }
75 }
76
77 private getCurrentTheme () {
78 if (this.themeFromLocalStorage) return this.themeFromLocalStorage.name
79
80 const theme = this.auth.isLoggedIn()
81 ? this.auth.getUser().theme
82 : this.userService.getAnonymousUser().theme
83
84 if (theme !== 'instance-default') return theme
85
86 const instanceTheme = this.serverConfig.theme.default
87 if (instanceTheme !== 'default') return instanceTheme
88
89 // Default to dark theme if available and wanted by the user
90 if (
91 this.themes.find(t => t.name === 'dark') &&
92 window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
93 ) {
94 return 'dark'
95 }
96
97 return instanceTheme
98 }
99
100 private loadTheme (name: string) {
101 const links = document.getElementsByTagName('link')
102 for (let i = 0; i < links.length; i++) {
103 const link = links[ i ]
104 if (link.getAttribute('rel').indexOf('style') !== -1 && link.getAttribute('title')) {
105 link.disabled = link.getAttribute('title') !== name
106 }
107 }
108 }
109
110 private updateCurrentTheme () {
111 if (this.oldThemeName) this.removeThemePlugins(this.oldThemeName)
112
113 const currentTheme = this.getCurrentTheme()
114
115 console.log('Enabling %s theme.', currentTheme)
116
117 this.loadTheme(currentTheme)
118
119 const theme = this.getTheme(currentTheme)
120 if (theme) {
121 console.log('Adding scripts of theme %s.', currentTheme)
122 this.pluginService.addPlugin(theme, true)
123
124 this.pluginService.reloadLoadedScopes()
125
126 this.localStorageService.setItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, JSON.stringify(theme), false)
127 } else {
128 this.localStorageService.removeItem(UserLocalStorageKeys.LAST_ACTIVE_THEME, false)
129 }
130
131 this.oldThemeName = currentTheme
132 }
133
134 private listenUserTheme () {
135 // We don't need them anymore
136 this.themeFromLocalStorage = undefined
137 this.themeDOMLinksFromLocalStorage = []
138
139 if (!this.auth.isLoggedIn()) {
140 this.updateCurrentTheme()
141
142 this.localStorageService.watch([ UserLocalStorageKeys.THEME ]).subscribe(
143 () => this.updateCurrentTheme()
144 )
145 }
146
147 this.auth.userInformationLoaded
148 .pipe(first())
149 .subscribe(() => this.updateCurrentTheme())
150 }
151
152 private loadAndSetFromLocalStorage () {
153 const lastActiveThemeString = this.localStorageService.getItem(UserLocalStorageKeys.LAST_ACTIVE_THEME)
154 if (!lastActiveThemeString) return
155
156 try {
157 const lastActiveTheme = JSON.parse(lastActiveThemeString)
158 this.themeFromLocalStorage = lastActiveTheme
159
160 this.injectThemes([ lastActiveTheme ], true)
161 this.updateCurrentTheme()
162 } catch (err) {
163 console.error('Cannot parse last active theme.', err)
164 return
165 }
166 }
167
168 private removeThemePlugins (themeName: string) {
169 const oldTheme = this.getTheme(themeName)
170 if (oldTheme) {
171 console.log('Removing scripts of old theme %s.', themeName)
172 this.pluginService.removePlugin(oldTheme)
173 }
174 }
175
176 private removeThemeFromLocalStorageIfNeeded (themes: ServerConfigTheme[]) {
177 if (!this.themeFromLocalStorage) return
178
179 const loadedTheme = themes.find(t => t.name === this.themeFromLocalStorage.name)
180 if (!loadedTheme || loadedTheme.version !== this.themeFromLocalStorage.version) {
181 // Need to remove this theme: we loaded an old version or a theme that does not exist anymore
182 this.removeThemePlugins(this.themeFromLocalStorage.name)
183 this.oldThemeName = undefined
184
185 const head = this.getHeadElement()
186 for (const htmlLinkElement of this.themeDOMLinksFromLocalStorage) {
187 head.removeChild(htmlLinkElement)
188 }
189
190 this.themeFromLocalStorage = undefined
191 this.themeDOMLinksFromLocalStorage = []
192 }
193 }
194
195 private getHeadElement () {
196 return document.getElementsByTagName('head')[0]
197 }
198
199 private getTheme (name: string) {
200 return this.themes.find(t => t.name === name)
201 }
202 }