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