aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/core/users/user-local-storage.service.ts
blob: a87f3b98a426f8d618a8868bb8187c0f3e638ee9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { filter, throttleTime } from 'rxjs'
import { Injectable } from '@angular/core'
import { AuthService, AuthStatus } from '@app/core/auth'
import { getBoolOrDefault } from '@root-helpers/local-storage-utils'
import { logger } from '@root-helpers/logger'
import { OAuthUserTokens, UserLocalStorageKeys } from '@root-helpers/users'
import { objectKeysTyped } from '@shared/core-utils'
import { UserRole, UserUpdateMe } from '@shared/models'
import { NSFWPolicyType } from '@shared/models/videos'
import { ServerService } from '../server'
import { LocalStorageService } from '../wrappers/storage.service'

@Injectable()
export class UserLocalStorageService {

  constructor (
    private authService: AuthService,
    private server: ServerService,
    private localStorageService: LocalStorageService
  ) {
    this.authService.userInformationLoaded.subscribe({
      next: () => {
        const user = this.authService.getUser()

        this.setLoggedInUser(user)
        this.setUserInfo(user)
        this.setTokens(user.oauthTokens)
      }
    })

    this.authService.loginChangedSource
      .pipe(filter(status => status === AuthStatus.LoggedOut))
      .subscribe({
        next: () => {
          this.flushLoggedInUser()
          this.flushUserInfo()
          this.flushTokens()
        }
      })

    this.authService.tokensRefreshed
      .subscribe({
        next: () => {
          const user = this.authService.getUser()

          this.setTokens(user.oauthTokens)
        }
      })
  }

  // ---------------------------------------------------------------------------

  getLoggedInUser () {
    const usernameLocalStorage = this.localStorageService.getItem(UserLocalStorageKeys.USERNAME)

    if (!usernameLocalStorage) return undefined

    return {
      id: parseInt(this.localStorageService.getItem(UserLocalStorageKeys.ID), 10),
      username: this.localStorageService.getItem(UserLocalStorageKeys.USERNAME),
      email: this.localStorageService.getItem(UserLocalStorageKeys.EMAIL),
      role: {
        id: parseInt(this.localStorageService.getItem(UserLocalStorageKeys.ROLE), 10) as UserRole,
        label: ''
      },

      ...this.getUserInfo()
    }
  }

  setLoggedInUser (user: {
    id: number
    username: string
    email: string
    role: {
      id: UserRole
    }
  }) {
    this.localStorageService.setItem(UserLocalStorageKeys.ID, user.id.toString())
    this.localStorageService.setItem(UserLocalStorageKeys.USERNAME, user.username)
    this.localStorageService.setItem(UserLocalStorageKeys.EMAIL, user.email)
    this.localStorageService.setItem(UserLocalStorageKeys.ROLE, user.role.id.toString())
  }

  flushLoggedInUser () {
    this.localStorageService.removeItem(UserLocalStorageKeys.ID)
    this.localStorageService.removeItem(UserLocalStorageKeys.USERNAME)
    this.localStorageService.removeItem(UserLocalStorageKeys.EMAIL)
    this.localStorageService.removeItem(UserLocalStorageKeys.ROLE)
  }

  // ---------------------------------------------------------------------------

  getUserInfo () {
    let videoLanguages: string[]

    try {
      const languagesString = this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES)
      videoLanguages = languagesString && languagesString !== 'undefined'
        ? JSON.parse(languagesString)
        : null
    } catch (err) {
      videoLanguages = null
      logger.error('Cannot parse desired video languages from localStorage.', err)
    }

    const htmlConfig = this.server.getHTMLConfig()

    const defaultNSFWPolicy = htmlConfig.instance.defaultNSFWPolicy
    const defaultP2PEnabled = htmlConfig.defaults.p2p.webapp.enabled

    return {
      nsfwPolicy: this.localStorageService.getItem<NSFWPolicyType>(UserLocalStorageKeys.NSFW_POLICY) || defaultNSFWPolicy,
      p2pEnabled: getBoolOrDefault(this.localStorageService.getItem(UserLocalStorageKeys.P2P_ENABLED), defaultP2PEnabled),
      theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default',
      videoLanguages,

      autoPlayVideo: getBoolOrDefault(this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO), true),
      autoPlayNextVideo: getBoolOrDefault(this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_NEXT_VIDEO), false),
      autoPlayNextVideoPlaylist: getBoolOrDefault(this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST), true)
    }
  }

  setUserInfo (profile: UserUpdateMe) {
    const localStorageKeys = {
      nsfwPolicy: UserLocalStorageKeys.NSFW_POLICY,
      p2pEnabled: UserLocalStorageKeys.P2P_ENABLED,
      autoPlayVideo: UserLocalStorageKeys.AUTO_PLAY_VIDEO,
      autoPlayNextVideo: UserLocalStorageKeys.AUTO_PLAY_NEXT_VIDEO,
      autoPlayNextVideoPlaylist: UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
      theme: UserLocalStorageKeys.THEME,
      videoLanguages: UserLocalStorageKeys.VIDEO_LANGUAGES
    }

    const obj: [ string, string | boolean | string[] ][] = objectKeysTyped(localStorageKeys)
      .filter(key => key in profile)
      .map(key => ([ localStorageKeys[key], profile[key] ]))

    for (const [ key, value ] of obj) {
      try {
        if (value === undefined) {
          this.localStorageService.removeItem(key)
          continue
        }

        const localStorageValue = typeof value === 'string'
          ? value
          : JSON.stringify(value)

        this.localStorageService.setItem(key, localStorageValue)
      } catch (err) {
        logger.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err)
      }
    }
  }

  flushUserInfo () {
    this.localStorageService.removeItem(UserLocalStorageKeys.NSFW_POLICY)
    this.localStorageService.removeItem(UserLocalStorageKeys.P2P_ENABLED)
    this.localStorageService.removeItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO)
    this.localStorageService.removeItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST)
    this.localStorageService.removeItem(UserLocalStorageKeys.THEME)
    this.localStorageService.removeItem(UserLocalStorageKeys.VIDEO_LANGUAGES)
  }

  listenUserInfoChange () {
    return this.localStorageService.watch([
      UserLocalStorageKeys.NSFW_POLICY,
      UserLocalStorageKeys.P2P_ENABLED,
      UserLocalStorageKeys.AUTO_PLAY_VIDEO,
      UserLocalStorageKeys.AUTO_PLAY_NEXT_VIDEO,
      UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
      UserLocalStorageKeys.THEME,
      UserLocalStorageKeys.VIDEO_LANGUAGES
    ]).pipe(
      throttleTime(200),
      filter(() => this.authService.isLoggedIn() !== true)
    )
  }

  // ---------------------------------------------------------------------------

  getTokens () {
    return OAuthUserTokens.getUserTokens(this.localStorageService)
  }

  setTokens (tokens: OAuthUserTokens) {
    OAuthUserTokens.saveToLocalStorage(this.localStorageService, tokens)
  }

  flushTokens () {
    OAuthUserTokens.flushLocalStorage(this.localStorageService)
  }
}