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