Reorganize client shared modules
[oweals/peertube.git] / client / src / app / shared / shared-main / account / actor.model.ts
1 import { Actor as ActorServer, Avatar } from '@shared/models'
2 import { getAbsoluteAPIUrl } from '@app/helpers'
3
4 export abstract class Actor implements ActorServer {
5   id: number
6   url: string
7   name: string
8   host: string
9   followingCount: number
10   followersCount: number
11   createdAt: Date | string
12   updatedAt: Date | string
13   avatar: Avatar
14
15   avatarUrl: string
16
17   static GET_ACTOR_AVATAR_URL (actor: { avatar?: Avatar }) {
18     if (actor?.avatar?.url) return actor.avatar.url
19
20     if (actor && actor.avatar) {
21       const absoluteAPIUrl = getAbsoluteAPIUrl()
22
23       return absoluteAPIUrl + actor.avatar.path
24     }
25
26     return this.GET_DEFAULT_AVATAR_URL()
27   }
28
29   static GET_DEFAULT_AVATAR_URL () {
30     return window.location.origin + '/client/assets/images/default-avatar.png'
31   }
32
33   static CREATE_BY_STRING (accountName: string, host: string, forceHostname = false) {
34     const absoluteAPIUrl = getAbsoluteAPIUrl()
35     const thisHost = new URL(absoluteAPIUrl).host
36
37     if (host.trim() === thisHost && !forceHostname) return accountName
38
39     return accountName + '@' + host
40   }
41
42   protected constructor (hash: ActorServer) {
43     this.id = hash.id
44     this.url = hash.url
45     this.name = hash.name
46     this.host = hash.host
47     this.followingCount = hash.followingCount
48     this.followersCount = hash.followersCount
49     this.createdAt = new Date(hash.createdAt.toString())
50     this.updatedAt = new Date(hash.updatedAt.toString())
51     this.avatar = hash.avatar
52
53     this.updateComputedAttributes()
54   }
55
56   updateAvatar (newAvatar: Avatar) {
57     this.avatar = newAvatar
58
59     this.updateComputedAttributes()
60   }
61
62   private updateComputedAttributes () {
63     this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this)
64   }
65 }