]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/user.ts
Move uuid stuff in extra utils
[github/Chocobozzz/PeerTube.git] / server / lib / user.ts
CommitLineData
fb719404 1import { Transaction } from 'sequelize/types'
7d9ba5c0
C
2import { UserModel } from '@server/models/user/user'
3import { MActorDefault } from '@server/types/models/actor'
0628157f 4import { buildUUID } from '@shared/extra-utils'
50d6de9c 5import { ActivityPubActorType } from '../../shared/models/activitypub'
fb719404 6import { UserNotificationSetting, UserNotificationSettingValue } from '../../shared/models/users'
d1ab89de 7import { SERVER_ACTOR_NAME, WEBSERVER } from '../initializers/constants'
fb719404 8import { sequelizeTypescript } from '../initializers/database'
3fd3ab2d 9import { AccountModel } from '../models/account/account'
7d9ba5c0
C
10import { ActorModel } from '../models/actor/actor'
11import { UserNotificationSettingModel } from '../models/user/user-notification-setting'
12import { MAccountDefault, MChannelActor } from '../types/models'
26d6bf65 13import { MUser, MUserDefault, MUserId } from '../types/models/user'
136d7efd 14import { generateAndSaveActorKeys } from './activitypub/actors'
de94ac86 15import { getLocalAccountActivityPubUrl } from './activitypub/url'
fb719404 16import { Emailer } from './emailer'
8ebf2a5d 17import { LiveQuotaStore } from './live/live-quota-store'
136d7efd 18import { buildActorInstance } from './local-actor'
fb719404
C
19import { Redis } from './redis'
20import { createLocalVideoChannel } from './video-channel'
21import { createWatchLaterPlaylist } from './video-playlist'
22
e590b4a5 23type ChannelNames = { name: string, displayName: string }
453e83ea 24
1f20622f 25async function createUserAccountAndChannelAndPlaylist (parameters: {
a1587156
C
26 userToCreate: MUser
27 userDisplayName?: string
28 channelNames?: ChannelNames
1f20622f 29 validateUser?: boolean
1ca9f7c3 30}): Promise<{ user: MUserDefault, account: MAccountDefault, videoChannel: MChannelActor }> {
1f20622f
C
31 const { userToCreate, userDisplayName, channelNames, validateUser = true } = parameters
32
f05a1c30 33 const { user, account, videoChannel } = await sequelizeTypescript.transaction(async t => {
72c7248b
C
34 const userOptions = {
35 transaction: t,
36 validate: validateUser
37 }
38
1ca9f7c3 39 const userCreated: MUserDefault = await userToCreate.save(userOptions)
cef534ed
C
40 userCreated.NotificationSetting = await createDefaultUserNotificationSettings(userCreated, t)
41
1f20622f
C
42 const accountCreated = await createLocalAccountWithoutKeys({
43 name: userCreated.username,
44 displayName: userDisplayName,
45 userId: userCreated.id,
46 applicationId: null,
eae0365b 47 t
1f20622f 48 })
80e36cd9 49 userCreated.Account = accountCreated
f5028693 50
eae0365b 51 const channelAttributes = await buildChannelAttributes(userCreated, t, channelNames)
1ca9f7c3 52 const videoChannel = await createLocalVideoChannel(channelAttributes, accountCreated, t)
f5028693 53
df0b219d
C
54 const videoPlaylist = await createWatchLaterPlaylist(accountCreated, t)
55
56 return { user: userCreated, account: accountCreated, videoChannel, videoPlaylist }
72c7248b 57 })
f5028693 58
453e83ea 59 const [ accountActorWithKeys, channelActorWithKeys ] = await Promise.all([
8795d6f2
C
60 generateAndSaveActorKeys(account.Actor),
61 generateAndSaveActorKeys(videoChannel.Actor)
0b2f03d3
C
62 ])
63
453e83ea
C
64 account.Actor = accountActorWithKeys
65 videoChannel.Actor = channelActorWithKeys
47e0652b 66
453e83ea 67 return { user, account, videoChannel }
72c7248b
C
68}
69
1f20622f 70async function createLocalAccountWithoutKeys (parameters: {
a1587156
C
71 name: string
72 displayName?: string
73 userId: number | null
74 applicationId: number | null
75 t: Transaction | undefined
1f20622f
C
76 type?: ActivityPubActorType
77}) {
78 const { name, displayName, userId, applicationId, t, type = 'Person' } = parameters
de94ac86 79 const url = getLocalAccountActivityPubUrl(name)
571389d4 80
50d6de9c 81 const actorInstance = buildActorInstance(type, url, name)
1ca9f7c3 82 const actorInstanceCreated: MActorDefault = await actorInstance.save({ transaction: t })
fadf619a
C
83
84 const accountInstance = new AccountModel({
1f20622f 85 name: displayName || name,
571389d4
C
86 userId,
87 applicationId,
c39ea24b 88 actorId: actorInstanceCreated.id
1735c825 89 })
571389d4 90
1ca9f7c3 91 const accountInstanceCreated: MAccountDefault = await accountInstance.save({ transaction: t })
fadf619a
C
92 accountInstanceCreated.Actor = actorInstanceCreated
93
94 return accountInstanceCreated
571389d4
C
95}
96
50d6de9c 97async function createApplicationActor (applicationId: number) {
1f20622f
C
98 const accountCreated = await createLocalAccountWithoutKeys({
99 name: SERVER_ACTOR_NAME,
100 userId: null,
101 applicationId: applicationId,
102 t: undefined,
103 type: 'Application'
104 })
50d6de9c 105
8795d6f2 106 accountCreated.Actor = await generateAndSaveActorKeys(accountCreated.Actor)
50d6de9c
C
107
108 return accountCreated
109}
110
453e83ea 111async function sendVerifyUserEmail (user: MUser, isPendingEmail = false) {
d1ab89de
C
112 const verificationString = await Redis.Instance.setVerifyEmailVerificationString(user.id)
113 let url = WEBSERVER.URL + '/verify-account/email?userId=' + user.id + '&verificationString=' + verificationString
114
115 if (isPendingEmail) url += '&isPendingEmail=true'
116
117 const email = isPendingEmail ? user.pendingEmail : user.email
963023ab 118 const username = user.username
d1ab89de 119
963023ab 120 await Emailer.Instance.addVerifyEmailJob(username, email, url)
d1ab89de
C
121}
122
fb719404
C
123async function getOriginalVideoFileTotalFromUser (user: MUserId) {
124 // Don't use sequelize because we need to use a sub query
125 const query = UserModel.generateUserQuotaBaseSQL({
126 withSelect: true,
127 whereUserId: '$userId'
128 })
129
130 const base = await UserModel.getTotalRawQuery(query, user.id)
131
8ebf2a5d 132 return base + LiveQuotaStore.Instance.getLiveQuotaOf(user.id)
fb719404
C
133}
134
135// Returns cumulative size of all video files uploaded in the last 24 hours.
136async function getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
137 // Don't use sequelize because we need to use a sub query
138 const query = UserModel.generateUserQuotaBaseSQL({
139 withSelect: true,
140 whereUserId: '$userId',
141 where: '"video"."createdAt" > now() - interval \'24 hours\''
142 })
143
144 const base = await UserModel.getTotalRawQuery(query, user.id)
145
8ebf2a5d 146 return base + LiveQuotaStore.Instance.getLiveQuotaOf(user.id)
fb719404
C
147}
148
8ebf2a5d 149async function isAbleToUploadVideo (userId: number, newVideoSize: number) {
fb719404
C
150 const user = await UserModel.loadById(userId)
151
152 if (user.videoQuota === -1 && user.videoQuotaDaily === -1) return Promise.resolve(true)
153
154 const [ totalBytes, totalBytesDaily ] = await Promise.all([
97969c4e
C
155 getOriginalVideoFileTotalFromUser(user),
156 getOriginalVideoFileTotalDailyFromUser(user)
fb719404
C
157 ])
158
8ebf2a5d
C
159 const uploadedTotal = newVideoSize + totalBytes
160 const uploadedDaily = newVideoSize + totalBytesDaily
fb719404
C
161
162 if (user.videoQuotaDaily === -1) return uploadedTotal < user.videoQuota
163 if (user.videoQuota === -1) return uploadedDaily < user.videoQuotaDaily
164
165 return uploadedTotal < user.videoQuota && uploadedDaily < user.videoQuotaDaily
166}
167
72c7248b
C
168// ---------------------------------------------------------------------------
169
170export {
fb719404
C
171 getOriginalVideoFileTotalFromUser,
172 getOriginalVideoFileTotalDailyFromUser,
50d6de9c 173 createApplicationActor,
df0b219d 174 createUserAccountAndChannelAndPlaylist,
d1ab89de 175 createLocalAccountWithoutKeys,
fb719404
C
176 sendVerifyUserEmail,
177 isAbleToUploadVideo
72c7248b 178}
cef534ed
C
179
180// ---------------------------------------------------------------------------
181
453e83ea 182function createDefaultUserNotificationSettings (user: MUserId, t: Transaction | undefined) {
f7cc67b4 183 const values: UserNotificationSetting & { userId: number } = {
cef534ed 184 userId: user.id,
2f1548fd
C
185 newVideoFromSubscription: UserNotificationSettingValue.WEB,
186 newCommentOnMyVideo: UserNotificationSettingValue.WEB,
187 myVideoImportFinished: UserNotificationSettingValue.WEB,
188 myVideoPublished: UserNotificationSettingValue.WEB,
4f32032f 189 abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
7ccddd7b 190 videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
2f1548fd
C
191 blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
192 newUserRegistration: UserNotificationSettingValue.WEB,
193 commentMention: UserNotificationSettingValue.WEB,
883993c8 194 newFollow: UserNotificationSettingValue.WEB,
8424c402 195 newInstanceFollower: UserNotificationSettingValue.WEB,
594d3e48
C
196 abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
197 abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
32a18cbf
C
198 autoInstanceFollowing: UserNotificationSettingValue.WEB,
199 newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
200 newPluginVersion: UserNotificationSettingValue.WEB
f7cc67b4
C
201 }
202
203 return UserNotificationSettingModel.create(values, { transaction: t })
cef534ed 204}
e590b4a5 205
eae0365b 206async function buildChannelAttributes (user: MUser, transaction?: Transaction, channelNames?: ChannelNames) {
e590b4a5
C
207 if (channelNames) return channelNames
208
209 let channelName = user.username + '_channel'
210
211 // Conflict, generate uuid instead
eae0365b 212 const actor = await ActorModel.loadLocalByName(channelName, transaction)
d4a8e7a6 213 if (actor) channelName = buildUUID()
e590b4a5
C
214
215 const videoChannelDisplayName = `Main ${user.username} channel`
216
217 return {
218 name: channelName,
219 displayName: videoChannelDisplayName
220 }
221}