-import * as uuidv4 from 'uuid/v4'
+import { Transaction } from 'sequelize/types'
+import { logger } from '@server/helpers/logger'
+import { CONFIG } from '@server/initializers/config'
+import { UserModel } from '@server/models/user/user'
+import { MActorDefault } from '@server/types/models/actor'
+import { buildUUID } from '@shared/extra-utils'
import { ActivityPubActorType } from '../../shared/models/activitypub'
+import { UserAdminFlag, UserNotificationSetting, UserNotificationSettingValue, UserRole } from '../../shared/models/users'
import { SERVER_ACTOR_NAME, WEBSERVER } from '../initializers/constants'
+import { sequelizeTypescript } from '../initializers/database'
import { AccountModel } from '../models/account/account'
-import { buildActorInstance, getAccountActivityPubUrl, setAsyncActorKeys } from './activitypub'
+import { ActorModel } from '../models/actor/actor'
+import { UserNotificationSettingModel } from '../models/user/user-notification-setting'
+import { MAccountDefault, MChannelActor } from '../types/models'
+import { MUser, MUserDefault, MUserId } from '../types/models/user'
+import { generateAndSaveActorKeys } from './activitypub/actors'
+import { getLocalAccountActivityPubUrl } from './activitypub/url'
+import { Emailer } from './emailer'
+import { LiveQuotaStore } from './live/live-quota-store'
+import { buildActorInstance } from './local-actor'
+import { Redis } from './redis'
import { createLocalVideoChannel } from './video-channel'
-import { ActorModel } from '../models/activitypub/actor'
-import { UserNotificationSettingModel } from '../models/account/user-notification-setting'
-import { UserNotificationSetting, UserNotificationSettingValue } from '../../shared/models/users'
import { createWatchLaterPlaylist } from './video-playlist'
-import { sequelizeTypescript } from '../initializers/database'
-import { Transaction } from 'sequelize/types'
-import { Redis } from './redis'
-import { Emailer } from './emailer'
-import { MAccountDefault, MActorDefault, MChannelActor } from '../typings/models'
-import { MUser, MUserDefault, MUserId } from '../typings/models/user'
type ChannelNames = { name: string, displayName: string }
+function buildUser (options: {
+ username: string
+ password: string
+ email: string
+
+ role?: UserRole // Default to UserRole.User
+ adminFlags?: UserAdminFlag // Default to UserAdminFlag.NONE
+
+ emailVerified: boolean | null
+
+ videoQuota?: number // Default to CONFIG.USER.VIDEO_QUOTA
+ videoQuotaDaily?: number // Default to CONFIG.USER.VIDEO_QUOTA_DAILY
+
+ pluginAuth?: string
+}): MUser {
+ const {
+ username,
+ password,
+ email,
+ role = UserRole.USER,
+ emailVerified,
+ videoQuota = CONFIG.USER.VIDEO_QUOTA,
+ videoQuotaDaily = CONFIG.USER.VIDEO_QUOTA_DAILY,
+ adminFlags = UserAdminFlag.NONE,
+ pluginAuth
+ } = options
+
+ return new UserModel({
+ username,
+ password,
+ email,
+
+ nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
+ p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
+ autoPlayVideo: true,
+
+ role,
+ emailVerified,
+ adminFlags,
+
+ videoQuota: videoQuota,
+ videoQuotaDaily: videoQuotaDaily,
+
+ pluginAuth
+ })
+}
+
async function createUserAccountAndChannelAndPlaylist (parameters: {
userToCreate: MUser
userDisplayName?: string
displayName: userDisplayName,
userId: userCreated.id,
applicationId: null,
- t: t
+ t
})
userCreated.Account = accountCreated
- const channelAttributes = await buildChannelAttributes(userCreated, channelNames)
+ const channelAttributes = await buildChannelAttributes(userCreated, t, channelNames)
const videoChannel = await createLocalVideoChannel(channelAttributes, accountCreated, t)
const videoPlaylist = await createWatchLaterPlaylist(accountCreated, t)
})
const [ accountActorWithKeys, channelActorWithKeys ] = await Promise.all([
- setAsyncActorKeys(account.Actor),
- setAsyncActorKeys(videoChannel.Actor)
+ generateAndSaveActorKeys(account.Actor),
+ generateAndSaveActorKeys(videoChannel.Actor)
])
account.Actor = accountActorWithKeys
type?: ActivityPubActorType
}) {
const { name, displayName, userId, applicationId, t, type = 'Person' } = parameters
- const url = getAccountActivityPubUrl(name)
+ const url = getLocalAccountActivityPubUrl(name)
const actorInstance = buildActorInstance(type, url, name)
const actorInstanceCreated: MActorDefault = await actorInstance.save({ transaction: t })
type: 'Application'
})
- accountCreated.Actor = await setAsyncActorKeys(accountCreated.Actor)
+ accountCreated.Actor = await generateAndSaveActorKeys(accountCreated.Actor)
return accountCreated
}
if (isPendingEmail) url += '&isPendingEmail=true'
const email = isPendingEmail ? user.pendingEmail : user.email
+ const username = user.username
+
+ Emailer.Instance.addVerifyEmailJob(username, email, url)
+}
+
+async function getOriginalVideoFileTotalFromUser (user: MUserId) {
+ // Don't use sequelize because we need to use a sub query
+ const query = UserModel.generateUserQuotaBaseSQL({
+ withSelect: true,
+ whereUserId: '$userId'
+ })
+
+ const base = await UserModel.getTotalRawQuery(query, user.id)
+
+ return base + LiveQuotaStore.Instance.getLiveQuotaOf(user.id)
+}
+
+// Returns cumulative size of all video files uploaded in the last 24 hours.
+async function getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
+ // Don't use sequelize because we need to use a sub query
+ const query = UserModel.generateUserQuotaBaseSQL({
+ withSelect: true,
+ whereUserId: '$userId',
+ where: '"video"."createdAt" > now() - interval \'24 hours\''
+ })
+
+ const base = await UserModel.getTotalRawQuery(query, user.id)
+
+ return base + LiveQuotaStore.Instance.getLiveQuotaOf(user.id)
+}
+
+async function isAbleToUploadVideo (userId: number, newVideoSize: number) {
+ const user = await UserModel.loadById(userId)
+
+ if (user.videoQuota === -1 && user.videoQuotaDaily === -1) return Promise.resolve(true)
+
+ const [ totalBytes, totalBytesDaily ] = await Promise.all([
+ getOriginalVideoFileTotalFromUser(user),
+ getOriginalVideoFileTotalDailyFromUser(user)
+ ])
+
+ const uploadedTotal = newVideoSize + totalBytes
+ const uploadedDaily = newVideoSize + totalBytesDaily
+
+ logger.debug(
+ 'Check user %d quota to upload another video.', userId,
+ { totalBytes, totalBytesDaily, videoQuota: user.videoQuota, videoQuotaDaily: user.videoQuotaDaily, newVideoSize }
+ )
+
+ if (user.videoQuotaDaily === -1) return uploadedTotal < user.videoQuota
+ if (user.videoQuota === -1) return uploadedDaily < user.videoQuotaDaily
- await Emailer.Instance.addVerifyEmailJob(email, url)
+ return uploadedTotal < user.videoQuota && uploadedDaily < user.videoQuotaDaily
}
// ---------------------------------------------------------------------------
export {
+ getOriginalVideoFileTotalFromUser,
+ getOriginalVideoFileTotalDailyFromUser,
createApplicationActor,
createUserAccountAndChannelAndPlaylist,
createLocalAccountWithoutKeys,
- sendVerifyUserEmail
+ sendVerifyUserEmail,
+ isAbleToUploadVideo,
+ buildUser
}
// ---------------------------------------------------------------------------
newCommentOnMyVideo: UserNotificationSettingValue.WEB,
myVideoImportFinished: UserNotificationSettingValue.WEB,
myVideoPublished: UserNotificationSettingValue.WEB,
- videoAbuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
+ abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newUserRegistration: UserNotificationSettingValue.WEB,
commentMention: UserNotificationSettingValue.WEB,
newFollow: UserNotificationSettingValue.WEB,
newInstanceFollower: UserNotificationSettingValue.WEB,
- autoInstanceFollowing: UserNotificationSettingValue.WEB
+ abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
+ abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
+ autoInstanceFollowing: UserNotificationSettingValue.WEB,
+ newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
+ newPluginVersion: UserNotificationSettingValue.WEB
}
return UserNotificationSettingModel.create(values, { transaction: t })
}
-async function buildChannelAttributes (user: MUser, channelNames?: ChannelNames) {
+async function buildChannelAttributes (user: MUser, transaction?: Transaction, channelNames?: ChannelNames) {
if (channelNames) return channelNames
let channelName = user.username + '_channel'
// Conflict, generate uuid instead
- const actor = await ActorModel.loadLocalByName(channelName)
- if (actor) channelName = uuidv4()
+ const actor = await ActorModel.loadLocalByName(channelName, transaction)
+ if (actor) channelName = buildUUID()
const videoChannelDisplayName = `Main ${user.username} channel`