1 import { Transaction } from 'sequelize/types'
2 import { logger } from '@server/helpers/logger'
3 import { CONFIG } from '@server/initializers/config'
4 import { UserModel } from '@server/models/user/user'
5 import { MActorDefault } from '@server/types/models/actor'
6 import { ActivityPubActorType } from '../../shared/models/activitypub'
7 import { UserAdminFlag, UserNotificationSetting, UserNotificationSettingValue, UserRole } from '../../shared/models/users'
8 import { SERVER_ACTOR_NAME, WEBSERVER } from '../initializers/constants'
9 import { sequelizeTypescript } from '../initializers/database'
10 import { AccountModel } from '../models/account/account'
11 import { UserNotificationSettingModel } from '../models/user/user-notification-setting'
12 import { MAccountDefault, MChannelActor } from '../types/models'
13 import { MRegistration, MUser, MUserDefault, MUserId } from '../types/models/user'
14 import { generateAndSaveActorKeys } from './activitypub/actors'
15 import { getLocalAccountActivityPubUrl } from './activitypub/url'
16 import { Emailer } from './emailer'
17 import { LiveQuotaStore } from './live/live-quota-store'
18 import { buildActorInstance, findAvailableLocalActorName } from './local-actor'
19 import { Redis } from './redis'
20 import { createLocalVideoChannel } from './video-channel'
21 import { createWatchLaterPlaylist } from './video-playlist'
23 type ChannelNames = { name: string, displayName: string }
25 function buildUser (options: {
30 role?: UserRole // Default to UserRole.User
31 adminFlags?: UserAdminFlag // Default to UserAdminFlag.NONE
33 emailVerified: boolean | null
35 videoQuota?: number // Default to CONFIG.USER.VIDEO_QUOTA
36 videoQuotaDaily?: number // Default to CONFIG.USER.VIDEO_QUOTA_DAILY
46 videoQuota = CONFIG.USER.VIDEO_QUOTA,
47 videoQuotaDaily = CONFIG.USER.VIDEO_QUOTA_DAILY,
48 adminFlags = UserAdminFlag.NONE,
52 return new UserModel({
57 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
58 p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
59 videosHistoryEnabled: CONFIG.USER.HISTORY.VIDEOS.ENABLED,
74 // ---------------------------------------------------------------------------
76 async function createUserAccountAndChannelAndPlaylist (parameters: {
78 userDisplayName?: string
79 channelNames?: ChannelNames
80 validateUser?: boolean
81 }): Promise<{ user: MUserDefault, account: MAccountDefault, videoChannel: MChannelActor }> {
82 const { userToCreate, userDisplayName, channelNames, validateUser = true } = parameters
84 const { user, account, videoChannel } = await sequelizeTypescript.transaction(async t => {
87 validate: validateUser
90 const userCreated: MUserDefault = await userToCreate.save(userOptions)
91 userCreated.NotificationSetting = await createDefaultUserNotificationSettings(userCreated, t)
93 const accountCreated = await createLocalAccountWithoutKeys({
94 name: userCreated.username,
95 displayName: userDisplayName,
96 userId: userCreated.id,
100 userCreated.Account = accountCreated
102 const channelAttributes = await buildChannelAttributes({ user: userCreated, transaction: t, channelNames })
103 const videoChannel = await createLocalVideoChannel(channelAttributes, accountCreated, t)
105 const videoPlaylist = await createWatchLaterPlaylist(accountCreated, t)
107 return { user: userCreated, account: accountCreated, videoChannel, videoPlaylist }
110 const [ accountActorWithKeys, channelActorWithKeys ] = await Promise.all([
111 generateAndSaveActorKeys(account.Actor),
112 generateAndSaveActorKeys(videoChannel.Actor)
115 account.Actor = accountActorWithKeys
116 videoChannel.Actor = channelActorWithKeys
118 return { user, account, videoChannel }
121 async function createLocalAccountWithoutKeys (parameters: {
124 userId: number | null
125 applicationId: number | null
126 t: Transaction | undefined
127 type?: ActivityPubActorType
129 const { name, displayName, userId, applicationId, t, type = 'Person' } = parameters
130 const url = getLocalAccountActivityPubUrl(name)
132 const actorInstance = buildActorInstance(type, url, name)
133 const actorInstanceCreated: MActorDefault = await actorInstance.save({ transaction: t })
135 const accountInstance = new AccountModel({
136 name: displayName || name,
139 actorId: actorInstanceCreated.id
142 const accountInstanceCreated: MAccountDefault = await accountInstance.save({ transaction: t })
143 accountInstanceCreated.Actor = actorInstanceCreated
145 return accountInstanceCreated
148 async function createApplicationActor (applicationId: number) {
149 const accountCreated = await createLocalAccountWithoutKeys({
150 name: SERVER_ACTOR_NAME,
157 accountCreated.Actor = await generateAndSaveActorKeys(accountCreated.Actor)
159 return accountCreated
162 // ---------------------------------------------------------------------------
164 async function sendVerifyUserEmail (user: MUser, isPendingEmail = false) {
165 const verificationString = await Redis.Instance.setUserVerifyEmailVerificationString(user.id)
166 let verifyEmailUrl = `${WEBSERVER.URL}/verify-account/email?userId=${user.id}&verificationString=${verificationString}`
168 if (isPendingEmail) verifyEmailUrl += '&isPendingEmail=true'
170 const to = isPendingEmail
174 const username = user.username
176 Emailer.Instance.addVerifyEmailJob({ username, to, verifyEmailUrl, isRegistrationRequest: false })
179 async function sendVerifyRegistrationEmail (registration: MRegistration) {
180 const verificationString = await Redis.Instance.setRegistrationVerifyEmailVerificationString(registration.id)
181 const verifyEmailUrl = `${WEBSERVER.URL}/verify-account/email?registrationId=${registration.id}&verificationString=${verificationString}`
183 const to = registration.email
184 const username = registration.username
186 Emailer.Instance.addVerifyEmailJob({ username, to, verifyEmailUrl, isRegistrationRequest: true })
189 // ---------------------------------------------------------------------------
191 async function getOriginalVideoFileTotalFromUser (user: MUserId) {
192 // Don't use sequelize because we need to use a sub query
193 const query = UserModel.generateUserQuotaBaseSQL({
195 whereUserId: '$userId',
199 const base = await UserModel.getTotalRawQuery(query, user.id)
201 return base + LiveQuotaStore.Instance.getLiveQuotaOf(user.id)
204 // Returns cumulative size of all video files uploaded in the last 24 hours.
205 async function getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
206 // Don't use sequelize because we need to use a sub query
207 const query = UserModel.generateUserQuotaBaseSQL({
209 whereUserId: '$userId',
213 const base = await UserModel.getTotalRawQuery(query, user.id)
215 return base + LiveQuotaStore.Instance.getLiveQuotaOf(user.id)
218 async function isAbleToUploadVideo (userId: number, newVideoSize: number) {
219 const user = await UserModel.loadById(userId)
221 if (user.videoQuota === -1 && user.videoQuotaDaily === -1) return Promise.resolve(true)
223 const [ totalBytes, totalBytesDaily ] = await Promise.all([
224 getOriginalVideoFileTotalFromUser(user),
225 getOriginalVideoFileTotalDailyFromUser(user)
228 const uploadedTotal = newVideoSize + totalBytes
229 const uploadedDaily = newVideoSize + totalBytesDaily
232 'Check user %d quota to upload another video.', userId,
233 { totalBytes, totalBytesDaily, videoQuota: user.videoQuota, videoQuotaDaily: user.videoQuotaDaily, newVideoSize }
236 if (user.videoQuotaDaily === -1) return uploadedTotal < user.videoQuota
237 if (user.videoQuota === -1) return uploadedDaily < user.videoQuotaDaily
239 return uploadedTotal < user.videoQuota && uploadedDaily < user.videoQuotaDaily
242 // ---------------------------------------------------------------------------
245 getOriginalVideoFileTotalFromUser,
246 getOriginalVideoFileTotalDailyFromUser,
247 createApplicationActor,
248 createUserAccountAndChannelAndPlaylist,
249 createLocalAccountWithoutKeys,
252 sendVerifyRegistrationEmail,
258 // ---------------------------------------------------------------------------
260 function createDefaultUserNotificationSettings (user: MUserId, t: Transaction | undefined) {
261 const values: UserNotificationSetting & { userId: number } = {
263 newVideoFromSubscription: UserNotificationSettingValue.WEB,
264 newCommentOnMyVideo: UserNotificationSettingValue.WEB,
265 myVideoImportFinished: UserNotificationSettingValue.WEB,
266 myVideoPublished: UserNotificationSettingValue.WEB,
267 abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
268 videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
269 blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
270 newUserRegistration: UserNotificationSettingValue.WEB,
271 commentMention: UserNotificationSettingValue.WEB,
272 newFollow: UserNotificationSettingValue.WEB,
273 newInstanceFollower: UserNotificationSettingValue.WEB,
274 abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
275 abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
276 autoInstanceFollowing: UserNotificationSettingValue.WEB,
277 newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
278 newPluginVersion: UserNotificationSettingValue.WEB,
279 myVideoStudioEditionFinished: UserNotificationSettingValue.WEB
282 return UserNotificationSettingModel.create(values, { transaction: t })
285 async function buildChannelAttributes (options: {
287 transaction?: Transaction
288 channelNames?: ChannelNames
290 const { user, transaction, channelNames } = options
292 if (channelNames) return channelNames
294 const channelName = await findAvailableLocalActorName(user.username + '_channel', transaction)
295 const videoChannelDisplayName = `Main ${user.username} channel`
299 displayName: videoChannelDisplayName