Better typings
[oweals/peertube.git] / client / src / app / shared / users / user.model.ts
1 import {
2   Account as AccountServerModel,
3   hasUserRight,
4   User as UserServerModel,
5   UserRight,
6   UserRole,
7   VideoChannel
8 } from '../../../../../shared'
9 import { NSFWPolicyType } from '../../../../../shared/models/videos/nsfw-policy.type'
10 import { Account } from '@app/shared/account/account.model'
11 import { Avatar } from '../../../../../shared/models/avatars/avatar.model'
12
13 export type UserConstructorHash = {
14   id: number,
15   username: string,
16   email: string,
17   role: UserRole,
18   videoQuota?: number,
19   videoQuotaDaily?: number,
20   nsfwPolicy?: NSFWPolicyType,
21   webTorrentEnabled?: boolean,
22   autoPlayVideo?: boolean,
23   createdAt?: Date,
24   account?: AccountServerModel,
25   videoChannels?: VideoChannel[]
26
27   blocked?: boolean
28   blockedReason?: string
29 }
30 export class User implements UserServerModel {
31   id: number
32   username: string
33   email: string
34   role: UserRole
35   nsfwPolicy: NSFWPolicyType
36   webTorrentEnabled: boolean
37   autoPlayVideo: boolean
38   videoQuota: number
39   videoQuotaDaily: number
40   account: Account
41   videoChannels: VideoChannel[]
42   createdAt: Date
43
44   blocked: boolean
45   blockedReason?: string
46
47   constructor (hash: UserConstructorHash) {
48     this.id = hash.id
49     this.username = hash.username
50     this.email = hash.email
51     this.role = hash.role
52
53     this.videoChannels = hash.videoChannels
54     this.videoQuota = hash.videoQuota
55     this.videoQuotaDaily = hash.videoQuotaDaily
56     this.nsfwPolicy = hash.nsfwPolicy
57     this.webTorrentEnabled = hash.webTorrentEnabled
58     this.autoPlayVideo = hash.autoPlayVideo
59     this.createdAt = hash.createdAt
60     this.blocked = hash.blocked
61     this.blockedReason = hash.blockedReason
62
63     if (hash.account !== undefined) {
64       this.account = new Account(hash.account)
65     }
66   }
67
68   get accountAvatarUrl () {
69     if (!this.account) return ''
70
71     return this.account.avatarUrl
72   }
73
74   hasRight (right: UserRight) {
75     return hasUserRight(this.role, right)
76   }
77
78   patch (obj: UserServerModel) {
79     for (const key of Object.keys(obj)) {
80       this[key] = obj[key]
81     }
82
83     if (obj.account !== undefined) {
84       this.account = new Account(obj.account)
85     }
86   }
87
88   updateAccountAvatar (newAccountAvatar: Avatar) {
89     this.account.updateAvatar(newAccountAvatar)
90   }
91 }