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