1 import * as Bluebird from 'bluebird'
2 import { values } from 'lodash'
3 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
23 } from 'sequelize-typescript'
30 MUserNotifSettingChannelDefault,
31 MUserWithNotificationSetting,
33 } from '@server/types/models'
34 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
35 import { AbuseState, MyUser, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared/models'
36 import { User, UserRole } from '../../../shared/models/users'
37 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
38 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
41 isNoInstanceConfigWarningModal,
43 isUserAdminFlagsValid,
44 isUserAutoPlayNextVideoPlaylistValid,
45 isUserAutoPlayNextVideoValid,
46 isUserAutoPlayVideoValid,
47 isUserBlockedReasonValid,
49 isUserEmailVerifiedValid,
50 isUserNSFWPolicyValid,
55 isUserVideoQuotaDailyValid,
56 isUserVideoQuotaValid,
57 isUserVideosHistoryEnabledValid,
58 isUserWebTorrentEnabledValid
59 } from '../../helpers/custom-validators/users'
60 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
61 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
62 import { clearCacheByUserId } from '../../lib/oauth-model'
63 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
64 import { ActorModel } from '../activitypub/actor'
65 import { ActorFollowModel } from '../activitypub/actor-follow'
66 import { OAuthTokenModel } from '../oauth/oauth-token'
67 import { getSort, throwIfNotValid } from '../utils'
68 import { VideoModel } from '../video/video'
69 import { VideoChannelModel } from '../video/video-channel'
70 import { VideoImportModel } from '../video/video-import'
71 import { VideoPlaylistModel } from '../video/video-playlist'
72 import { AccountModel } from './account'
73 import { UserNotificationSettingModel } from './user-notification-setting'
74 import { VideoLiveModel } from '../video/video-live'
77 FOR_ME_API = 'FOR_ME_API',
78 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
79 WITH_STATS = 'WITH_STATS'
82 @DefaultScope(() => ({
89 model: UserNotificationSettingModel,
95 [ScopeNames.FOR_ME_API]: {
101 model: VideoChannelModel
104 attributes: [ 'id', 'name', 'type' ],
105 model: VideoPlaylistModel.unscoped(),
109 [Op.ne]: VideoPlaylistType.REGULAR
116 model: UserNotificationSettingModel,
121 [ScopeNames.WITH_VIDEOCHANNELS]: {
127 model: VideoChannelModel
130 attributes: [ 'id', 'name', 'type' ],
131 model: VideoPlaylistModel.unscoped(),
135 [Op.ne]: VideoPlaylistType.REGULAR
143 [ScopeNames.WITH_STATS]: {
149 UserModel.generateUserQuotaBaseSQL({
151 whereUserId: '"UserModel"."id"'
160 'SELECT COUNT("video"."id") ' +
162 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
163 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
164 'WHERE "account"."userId" = "UserModel"."id"' +
172 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
174 'SELECT COUNT("abuse"."id") AS "abuses", ' +
175 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
177 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
178 'WHERE "account"."userId" = "UserModel"."id"' +
187 'SELECT COUNT("abuse"."id") ' +
189 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
190 'WHERE "account"."userId" = "UserModel"."id"' +
198 'SELECT COUNT("videoComment"."id") ' +
199 'FROM "videoComment" ' +
200 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
201 'WHERE "account"."userId" = "UserModel"."id"' +
214 fields: [ 'username' ],
223 export class UserModel extends Model<UserModel> {
226 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
231 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
237 @Column(DataType.STRING(400))
242 @Column(DataType.STRING(400))
247 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
249 emailVerified: boolean
252 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
253 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
254 nsfwPolicy: NSFWPolicyType
258 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
260 webTorrentEnabled: boolean
264 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
266 videosHistoryEnabled: boolean
270 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
272 autoPlayVideo: boolean
276 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
278 autoPlayNextVideo: boolean
283 'UserAutoPlayNextVideoPlaylist',
284 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
287 autoPlayNextVideoPlaylist: boolean
291 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
292 @Column(DataType.ARRAY(DataType.STRING))
293 videoLanguages: string[]
296 @Default(UserAdminFlag.NONE)
297 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
299 adminFlags?: UserAdminFlag
303 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
309 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
311 blockedReason: string
314 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
319 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
320 @Column(DataType.BIGINT)
324 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
325 @Column(DataType.BIGINT)
326 videoQuotaDaily: number
329 @Default(DEFAULT_USER_THEME_NAME)
330 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
337 'UserNoInstanceConfigWarningModal',
338 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
341 noInstanceConfigWarningModal: boolean
346 'UserNoInstanceConfigWarningModal',
347 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
350 noWelcomeModal: boolean
368 @HasOne(() => AccountModel, {
369 foreignKey: 'userId',
373 Account: AccountModel
375 @HasOne(() => UserNotificationSettingModel, {
376 foreignKey: 'userId',
380 NotificationSetting: UserNotificationSettingModel
382 @HasMany(() => VideoImportModel, {
383 foreignKey: 'userId',
386 VideoImports: VideoImportModel[]
388 @HasMany(() => OAuthTokenModel, {
389 foreignKey: 'userId',
392 OAuthTokens: OAuthTokenModel[]
396 static cryptPasswordIfNeeded (instance: UserModel) {
397 if (instance.changed('password') && instance.password) {
398 return cryptPassword(instance.password)
400 instance.password = hash
408 static removeTokenCache (instance: UserModel) {
409 return clearCacheByUserId(instance.id)
412 static countTotal () {
416 static listForApi (parameters: {
423 const { start, count, sort, search, blocked } = parameters
424 const where: WhereOptions = {}
427 Object.assign(where, {
431 [Op.iLike]: '%' + search + '%'
436 [Op.iLike]: '%' + search + '%'
443 if (blocked !== undefined) {
444 Object.assign(where, {
449 const query: FindOptions = {
455 UserModel.generateUserQuotaBaseSQL({
457 whereUserId: '"UserModel"."id"'
462 ] as any // FIXME: typings
467 order: getSort(sort),
471 return UserModel.findAndCountAll(query)
472 .then(({ rows, count }) => {
480 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
481 const roles = Object.keys(USER_ROLE_LABELS)
482 .map(k => parseInt(k, 10) as UserRole)
483 .filter(role => hasUserRight(role, right))
493 return UserModel.findAll(query)
496 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
500 model: UserNotificationSettingModel.unscoped(),
504 attributes: [ 'userId' ],
505 model: AccountModel.unscoped(),
510 model: ActorModel.unscoped(),
518 as: 'ActorFollowings',
519 model: ActorFollowModel.unscoped(),
522 targetActorId: actorId
532 return UserModel.unscoped().findAll(query)
535 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
542 return UserModel.findAll(query)
545 static loadById (id: number): Bluebird<MUser> {
546 return UserModel.unscoped().findByPk(id)
549 static loadByIdWithChannels (id: number, withStats = false): Bluebird<MUserDefault> {
551 ScopeNames.WITH_VIDEOCHANNELS
554 if (withStats) scopes.push(ScopeNames.WITH_STATS)
556 return UserModel.scope(scopes).findByPk(id)
559 static loadByUsername (username: string): Bluebird<MUserDefault> {
562 username: { [Op.iLike]: username }
566 return UserModel.findOne(query)
569 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
572 username: { [Op.iLike]: username }
576 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
579 static loadByEmail (email: string): Bluebird<MUserDefault> {
586 return UserModel.findOne(query)
589 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
590 if (!email) email = username
595 where(fn('lower', col('username')), fn('lower', username)),
602 return UserModel.findOne(query)
605 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
610 attributes: [ 'id' ],
611 model: AccountModel.unscoped(),
615 attributes: [ 'id' ],
616 model: VideoChannelModel.unscoped(),
620 attributes: [ 'id' ],
621 model: VideoModel.unscoped(),
633 return UserModel.findOne(query)
636 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
641 attributes: [ 'id' ],
642 model: VideoImportModel.unscoped(),
650 return UserModel.findOne(query)
653 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
658 attributes: [ 'id' ],
659 model: AccountModel.unscoped(),
663 attributes: [ 'id' ],
664 model: VideoChannelModel.unscoped(),
666 actorId: videoChannelActorId
674 return UserModel.findOne(query)
677 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
682 attributes: [ 'id' ],
683 model: AccountModel.unscoped(),
685 actorId: accountActorId
691 return UserModel.findOne(query)
694 static loadByLiveId (liveId: number): Bluebird<MUser> {
698 attributes: [ 'id' ],
699 model: AccountModel.unscoped(),
703 attributes: [ 'id' ],
704 model: VideoChannelModel.unscoped(),
708 attributes: [ 'id' ],
709 model: VideoModel.unscoped(),
713 attributes: [ 'id', 'videoId' ],
714 model: VideoLiveModel.unscoped(),
729 return UserModel.findOne(query)
732 static generateUserQuotaBaseSQL (options: {
733 whereUserId: '$userId' | '"UserModel"."id"'
737 const andWhere = options.where
738 ? 'AND ' + options.where
741 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
742 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
743 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
745 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
746 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
749 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
750 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
751 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
754 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
756 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
757 'GROUP BY "t1"."videoId"' +
761 static getTotalRawQuery (query: string, userId: number) {
764 type: QueryTypes.SELECT as QueryTypes.SELECT
767 return UserModel.sequelize.query<{ total: string }>(query, options)
768 .then(([ { total } ]) => {
769 if (total === null) return 0
771 return parseInt(total, 10)
775 static async getStats () {
776 function getActiveUsers (days: number) {
780 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
785 return UserModel.count(query)
788 const totalUsers = await UserModel.count()
789 const totalDailyActiveUsers = await getActiveUsers(1)
790 const totalWeeklyActiveUsers = await getActiveUsers(7)
791 const totalMonthlyActiveUsers = await getActiveUsers(30)
795 totalDailyActiveUsers,
796 totalWeeklyActiveUsers,
797 totalMonthlyActiveUsers
801 static autoComplete (search: string) {
805 [Op.like]: `%${search}%`
811 return UserModel.findAll(query)
812 .then(u => u.map(u => u.username))
815 canGetVideo (video: MVideoFullLight) {
816 const videoUserId = video.VideoChannel.Account.userId
818 if (video.isBlacklisted()) {
819 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
822 if (video.privacy === VideoPrivacy.PRIVATE) {
823 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
826 if (video.privacy === VideoPrivacy.INTERNAL) return true
831 hasRight (right: UserRight) {
832 return hasUserRight(this.role, right)
835 hasAdminFlag (flag: UserAdminFlag) {
836 return this.adminFlags & flag
839 isPasswordMatch (password: string) {
840 return comparePassword(password, this.password)
843 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
844 const videoQuotaUsed = this.get('videoQuotaUsed')
845 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
846 const videosCount = this.get('videosCount')
847 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
848 const abusesCreatedCount = this.get('abusesCreatedCount')
849 const videoCommentsCount = this.get('videoCommentsCount')
853 username: this.username,
855 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
857 pendingEmail: this.pendingEmail,
858 emailVerified: this.emailVerified,
860 nsfwPolicy: this.nsfwPolicy,
861 webTorrentEnabled: this.webTorrentEnabled,
862 videosHistoryEnabled: this.videosHistoryEnabled,
863 autoPlayVideo: this.autoPlayVideo,
864 autoPlayNextVideo: this.autoPlayNextVideo,
865 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
866 videoLanguages: this.videoLanguages,
869 roleLabel: USER_ROLE_LABELS[this.role],
871 videoQuota: this.videoQuota,
872 videoQuotaDaily: this.videoQuotaDaily,
873 videoQuotaUsed: videoQuotaUsed !== undefined
874 ? parseInt(videoQuotaUsed + '', 10)
876 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
877 ? parseInt(videoQuotaUsedDaily + '', 10)
879 videosCount: videosCount !== undefined
880 ? parseInt(videosCount + '', 10)
882 abusesCount: abusesCount
883 ? parseInt(abusesCount, 10)
885 abusesAcceptedCount: abusesAcceptedCount
886 ? parseInt(abusesAcceptedCount, 10)
888 abusesCreatedCount: abusesCreatedCount !== undefined
889 ? parseInt(abusesCreatedCount + '', 10)
891 videoCommentsCount: videoCommentsCount !== undefined
892 ? parseInt(videoCommentsCount + '', 10)
895 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
896 noWelcomeModal: this.noWelcomeModal,
898 blocked: this.blocked,
899 blockedReason: this.blockedReason,
901 account: this.Account.toFormattedJSON(),
903 notificationSettings: this.NotificationSetting
904 ? this.NotificationSetting.toFormattedJSON()
909 createdAt: this.createdAt,
911 pluginAuth: this.pluginAuth,
913 lastLoginDate: this.lastLoginDate
916 if (parameters.withAdminFlags) {
917 Object.assign(json, { adminFlags: this.adminFlags })
920 if (Array.isArray(this.Account.VideoChannels) === true) {
921 json.videoChannels = this.Account.VideoChannels
922 .map(c => c.toFormattedJSON())
924 if (v1.createdAt < v2.createdAt) return -1
925 if (v1.createdAt === v2.createdAt) return 0
934 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
935 const formatted = this.toFormattedJSON()
937 const specialPlaylists = this.Account.VideoPlaylists
938 .map(p => ({ id: p.id, name: p.name, type: p.type }))
940 return Object.assign(formatted, { specialPlaylists })