"use strict";
var UserModel_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserModel = void 0;
const tslib_1 = require("tslib");
const sequelize_1 = require("sequelize");
const sequelize_typescript_1 = require("sequelize-typescript");
const tokens_cache_1 = require("../../lib/auth/tokens-cache");
const live_1 = require("../../lib/live");
const users_1 = require("../../../shared/core-utils/users");
const plugins_1 = require("../../helpers/custom-validators/plugins");
const users_2 = require("../../helpers/custom-validators/users");
const peertube_crypto_1 = require("../../helpers/peertube-crypto");
const constants_1 = require("../../initializers/constants");
const theme_utils_1 = require("../../lib/plugins/theme-utils");
const account_1 = require("../account/account");
const actor_1 = require("../actor/actor");
const actor_follow_1 = require("../actor/actor-follow");
const actor_image_1 = require("../actor/actor-image");
const oauth_token_1 = require("../oauth/oauth-token");
const utils_1 = require("../utils");
const video_1 = require("../video/video");
const video_channel_1 = require("../video/video-channel");
const video_import_1 = require("../video/video-import");
const video_live_1 = require("../video/video-live");
const video_playlist_1 = require("../video/video-playlist");
const user_notification_setting_1 = require("./user-notification-setting");
const core_utils_1 = require("../../../shared/core-utils");
var ScopeNames;
(function (ScopeNames) {
    ScopeNames["FOR_ME_API"] = "FOR_ME_API";
    ScopeNames["WITH_VIDEOCHANNELS"] = "WITH_VIDEOCHANNELS";
    ScopeNames["WITH_QUOTA"] = "WITH_QUOTA";
    ScopeNames["WITH_STATS"] = "WITH_STATS";
})(ScopeNames || (ScopeNames = {}));
let UserModel = UserModel_1 = class UserModel extends sequelize_typescript_1.Model {
    static cryptPasswordIfNeeded(instance) {
        if (instance.changed('password') && instance.password) {
            return (0, peertube_crypto_1.cryptPassword)(instance.password)
                .then(hash => {
                instance.password = hash;
                return undefined;
            });
        }
    }
    static removeTokenCache(instance) {
        return tokens_cache_1.TokensCache.Instance.clearCacheByUserId(instance.id);
    }
    static countTotal() {
        return this.count();
    }
    static listForAdminApi(parameters) {
        const { start, count, sort, search, blocked } = parameters;
        const where = {};
        if (search) {
            Object.assign(where, {
                [sequelize_1.Op.or]: [
                    {
                        email: {
                            [sequelize_1.Op.iLike]: '%' + search + '%'
                        }
                    },
                    {
                        username: {
                            [sequelize_1.Op.iLike]: '%' + search + '%'
                        }
                    }
                ]
            });
        }
        if (blocked !== undefined) {
            Object.assign(where, { blocked });
        }
        const query = {
            offset: start,
            limit: count,
            order: (0, utils_1.getAdminUsersSort)(sort),
            where
        };
        return Promise.all([
            UserModel_1.unscoped().count(query),
            UserModel_1.scope(['defaultScope', ScopeNames.WITH_QUOTA]).findAll(query)
        ]).then(([total, data]) => ({ total, data }));
    }
    static listWithRight(right) {
        const roles = Object.keys(users_1.USER_ROLE_LABELS)
            .map(k => parseInt(k, 10))
            .filter(role => (0, users_1.hasUserRight)(role, right));
        const query = {
            where: {
                role: {
                    [sequelize_1.Op.in]: roles
                }
            }
        };
        return UserModel_1.findAll(query);
    }
    static listUserSubscribersOf(actorId) {
        const query = {
            include: [
                {
                    model: user_notification_setting_1.UserNotificationSettingModel.unscoped(),
                    required: true
                },
                {
                    attributes: ['userId'],
                    model: account_1.AccountModel.unscoped(),
                    required: true,
                    include: [
                        {
                            attributes: [],
                            model: actor_1.ActorModel.unscoped(),
                            required: true,
                            where: {
                                serverId: null
                            },
                            include: [
                                {
                                    attributes: [],
                                    as: 'ActorFollowings',
                                    model: actor_follow_1.ActorFollowModel.unscoped(),
                                    required: true,
                                    where: {
                                        targetActorId: actorId
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        };
        return UserModel_1.unscoped().findAll(query);
    }
    static listByUsernames(usernames) {
        const query = {
            where: {
                username: usernames
            }
        };
        return UserModel_1.findAll(query);
    }
    static loadById(id) {
        return UserModel_1.unscoped().findByPk(id);
    }
    static loadByIdFull(id) {
        return UserModel_1.findByPk(id);
    }
    static loadByIdWithChannels(id, withStats = false) {
        const scopes = [
            ScopeNames.WITH_VIDEOCHANNELS
        ];
        if (withStats) {
            scopes.push(ScopeNames.WITH_QUOTA);
            scopes.push(ScopeNames.WITH_STATS);
        }
        return UserModel_1.scope(scopes).findByPk(id);
    }
    static loadByUsername(username) {
        const query = {
            where: {
                username
            }
        };
        return UserModel_1.findOne(query);
    }
    static loadForMeAPI(id) {
        const query = {
            where: {
                id
            }
        };
        return UserModel_1.scope(ScopeNames.FOR_ME_API).findOne(query);
    }
    static loadByEmail(email) {
        const query = {
            where: {
                email
            }
        };
        return UserModel_1.findOne(query);
    }
    static loadByUsernameOrEmail(username, email) {
        if (!email)
            email = username;
        const query = {
            where: {
                [sequelize_1.Op.or]: [
                    (0, sequelize_1.where)((0, sequelize_1.fn)('lower', (0, sequelize_1.col)('username')), (0, sequelize_1.fn)('lower', username)),
                    { email }
                ]
            }
        };
        return UserModel_1.findOne(query);
    }
    static loadByVideoId(videoId) {
        const query = {
            include: [
                {
                    required: true,
                    attributes: ['id'],
                    model: account_1.AccountModel.unscoped(),
                    include: [
                        {
                            required: true,
                            attributes: ['id'],
                            model: video_channel_1.VideoChannelModel.unscoped(),
                            include: [
                                {
                                    required: true,
                                    attributes: ['id'],
                                    model: video_1.VideoModel.unscoped(),
                                    where: {
                                        id: videoId
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        };
        return UserModel_1.findOne(query);
    }
    static loadByVideoImportId(videoImportId) {
        const query = {
            include: [
                {
                    required: true,
                    attributes: ['id'],
                    model: video_import_1.VideoImportModel.unscoped(),
                    where: {
                        id: videoImportId
                    }
                }
            ]
        };
        return UserModel_1.findOne(query);
    }
    static loadByChannelActorId(videoChannelActorId) {
        const query = {
            include: [
                {
                    required: true,
                    attributes: ['id'],
                    model: account_1.AccountModel.unscoped(),
                    include: [
                        {
                            required: true,
                            attributes: ['id'],
                            model: video_channel_1.VideoChannelModel.unscoped(),
                            where: {
                                actorId: videoChannelActorId
                            }
                        }
                    ]
                }
            ]
        };
        return UserModel_1.findOne(query);
    }
    static loadByAccountActorId(accountActorId) {
        const query = {
            include: [
                {
                    required: true,
                    attributes: ['id'],
                    model: account_1.AccountModel.unscoped(),
                    where: {
                        actorId: accountActorId
                    }
                }
            ]
        };
        return UserModel_1.findOne(query);
    }
    static loadByLiveId(liveId) {
        const query = {
            include: [
                {
                    attributes: ['id'],
                    model: account_1.AccountModel.unscoped(),
                    required: true,
                    include: [
                        {
                            attributes: ['id'],
                            model: video_channel_1.VideoChannelModel.unscoped(),
                            required: true,
                            include: [
                                {
                                    attributes: ['id'],
                                    model: video_1.VideoModel.unscoped(),
                                    required: true,
                                    include: [
                                        {
                                            attributes: [],
                                            model: video_live_1.VideoLiveModel.unscoped(),
                                            required: true,
                                            where: {
                                                id: liveId
                                            }
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        };
        return UserModel_1.unscoped().findOne(query);
    }
    static generateUserQuotaBaseSQL(options) {
        const andWhere = options.daily === true
            ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
            : '';
        const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
            'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
            `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`;
        const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
            'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
            videoChannelJoin;
        const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
            'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
            'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
            videoChannelJoin;
        return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
            'FROM (' +
            `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
            'GROUP BY "t1"."videoId"' +
            ') t2';
    }
    static getTotalRawQuery(query, userId) {
        const options = {
            bind: { userId },
            type: sequelize_1.QueryTypes.SELECT
        };
        return UserModel_1.sequelize.query(query, options)
            .then(([{ total }]) => {
            if (total === null)
                return 0;
            return parseInt(total, 10);
        });
    }
    static getStats() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            function getActiveUsers(days) {
                const query = {
                    where: {
                        [sequelize_1.Op.and]: [
                            (0, sequelize_1.literal)(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
                        ]
                    }
                };
                return UserModel_1.unscoped().count(query);
            }
            const totalUsers = yield UserModel_1.unscoped().count();
            const totalDailyActiveUsers = yield getActiveUsers(1);
            const totalWeeklyActiveUsers = yield getActiveUsers(7);
            const totalMonthlyActiveUsers = yield getActiveUsers(30);
            const totalHalfYearActiveUsers = yield getActiveUsers(180);
            return {
                totalUsers,
                totalDailyActiveUsers,
                totalWeeklyActiveUsers,
                totalMonthlyActiveUsers,
                totalHalfYearActiveUsers
            };
        });
    }
    static autoComplete(search) {
        const query = {
            where: {
                username: {
                    [sequelize_1.Op.like]: `%${search}%`
                }
            },
            limit: 10
        };
        return UserModel_1.findAll(query)
            .then(u => u.map(u => u.username));
    }
    hasRight(right) {
        return (0, users_1.hasUserRight)(this.role, right);
    }
    hasAdminFlag(flag) {
        return this.adminFlags & flag;
    }
    isPasswordMatch(password) {
        return (0, peertube_crypto_1.comparePassword)(password, this.password);
    }
    toFormattedJSON(parameters = {}) {
        const videoQuotaUsed = this.get('videoQuotaUsed');
        const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily');
        const videosCount = this.get('videosCount');
        const [abusesCount, abusesAcceptedCount] = (this.get('abusesCount') || ':').split(':');
        const abusesCreatedCount = this.get('abusesCreatedCount');
        const videoCommentsCount = this.get('videoCommentsCount');
        const json = {
            id: this.id,
            username: this.username,
            email: this.email,
            theme: (0, theme_utils_1.getThemeOrDefault)(this.theme, constants_1.DEFAULT_USER_THEME_NAME),
            pendingEmail: this.pendingEmail,
            emailVerified: this.emailVerified,
            nsfwPolicy: this.nsfwPolicy,
            webTorrentEnabled: this.p2pEnabled,
            p2pEnabled: this.p2pEnabled,
            videosHistoryEnabled: this.videosHistoryEnabled,
            autoPlayVideo: this.autoPlayVideo,
            autoPlayNextVideo: this.autoPlayNextVideo,
            autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
            videoLanguages: this.videoLanguages,
            role: {
                id: this.role,
                label: users_1.USER_ROLE_LABELS[this.role]
            },
            videoQuota: this.videoQuota,
            videoQuotaDaily: this.videoQuotaDaily,
            videoQuotaUsed: videoQuotaUsed !== undefined
                ? (0, core_utils_1.forceNumber)(videoQuotaUsed) + live_1.LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
                : undefined,
            videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
                ? (0, core_utils_1.forceNumber)(videoQuotaUsedDaily) + live_1.LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
                : undefined,
            videosCount: videosCount !== undefined
                ? (0, core_utils_1.forceNumber)(videosCount)
                : undefined,
            abusesCount: abusesCount
                ? (0, core_utils_1.forceNumber)(abusesCount)
                : undefined,
            abusesAcceptedCount: abusesAcceptedCount
                ? (0, core_utils_1.forceNumber)(abusesAcceptedCount)
                : undefined,
            abusesCreatedCount: abusesCreatedCount !== undefined
                ? (0, core_utils_1.forceNumber)(abusesCreatedCount)
                : undefined,
            videoCommentsCount: videoCommentsCount !== undefined
                ? (0, core_utils_1.forceNumber)(videoCommentsCount)
                : undefined,
            noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
            noWelcomeModal: this.noWelcomeModal,
            noAccountSetupWarningModal: this.noAccountSetupWarningModal,
            blocked: this.blocked,
            blockedReason: this.blockedReason,
            account: this.Account.toFormattedJSON(),
            notificationSettings: this.NotificationSetting
                ? this.NotificationSetting.toFormattedJSON()
                : undefined,
            videoChannels: [],
            createdAt: this.createdAt,
            pluginAuth: this.pluginAuth,
            lastLoginDate: this.lastLoginDate,
            twoFactorEnabled: !!this.otpSecret
        };
        if (parameters.withAdminFlags) {
            Object.assign(json, { adminFlags: this.adminFlags });
        }
        if (Array.isArray(this.Account.VideoChannels) === true) {
            json.videoChannels = this.Account.VideoChannels
                .map(c => c.toFormattedJSON())
                .sort((v1, v2) => {
                if (v1.createdAt < v2.createdAt)
                    return -1;
                if (v1.createdAt === v2.createdAt)
                    return 0;
                return 1;
            });
        }
        return json;
    }
    toMeFormattedJSON() {
        const formatted = this.toFormattedJSON({ withAdminFlags: true });
        const specialPlaylists = this.Account.VideoPlaylists
            .map(p => ({ id: p.id, name: p.name, type: p.type }));
        return Object.assign(formatted, { specialPlaylists });
    }
};
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Is)('UserPassword', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserPasswordValid, 'user password', true)),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "password", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "username", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    sequelize_typescript_1.IsEmail,
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.STRING(400)),
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "email", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    sequelize_typescript_1.IsEmail,
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.STRING(400)),
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "pendingEmail", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Default)(null),
    (0, sequelize_typescript_1.Is)('UserEmailVerified', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserEmailVerifiedValid, 'email verified boolean', true)),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "emailVerified", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Is)('UserNSFWPolicy', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserNSFWPolicyValid, 'NSFW policy')),
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.ENUM(...Object.values(constants_1.NSFW_POLICY_TYPES))),
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "nsfwPolicy", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Is)('p2pEnabled', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserP2PEnabledValid, 'P2P enabled')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "p2pEnabled", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(true),
    (0, sequelize_typescript_1.Is)('UserVideosHistoryEnabled', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserVideosHistoryEnabledValid, 'Videos history enabled')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "videosHistoryEnabled", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(true),
    (0, sequelize_typescript_1.Is)('UserAutoPlayVideo', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserAutoPlayVideoValid, 'auto play video boolean')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "autoPlayVideo", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(false),
    (0, sequelize_typescript_1.Is)('UserAutoPlayNextVideo', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserAutoPlayNextVideoValid, 'auto play next video boolean')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "autoPlayNextVideo", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(true),
    (0, sequelize_typescript_1.Is)('UserAutoPlayNextVideoPlaylist', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "autoPlayNextVideoPlaylist", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Default)(null),
    (0, sequelize_typescript_1.Is)('UserVideoLanguages', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserVideoLanguages, 'video languages')),
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.ARRAY(sequelize_typescript_1.DataType.STRING)),
    tslib_1.__metadata("design:type", Array)
], UserModel.prototype, "videoLanguages", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(0),
    (0, sequelize_typescript_1.Is)('UserAdminFlags', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserAdminFlagsValid, 'user admin flags')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Number)
], UserModel.prototype, "adminFlags", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(false),
    (0, sequelize_typescript_1.Is)('UserBlocked', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserBlockedValid, 'blocked boolean')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "blocked", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Default)(null),
    (0, sequelize_typescript_1.Is)('UserBlockedReason', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserBlockedReasonValid, 'blocked reason', true)),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "blockedReason", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Is)('UserRole', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserRoleValid, 'role')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Number)
], UserModel.prototype, "role", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Is)('UserVideoQuota', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserVideoQuotaValid, 'video quota')),
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.BIGINT),
    tslib_1.__metadata("design:type", Number)
], UserModel.prototype, "videoQuota", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Is)('UserVideoQuotaDaily', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserVideoQuotaDailyValid, 'video quota daily')),
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.BIGINT),
    tslib_1.__metadata("design:type", Number)
], UserModel.prototype, "videoQuotaDaily", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(constants_1.DEFAULT_USER_THEME_NAME),
    (0, sequelize_typescript_1.Is)('UserTheme', value => (0, utils_1.throwIfNotValid)(value, plugins_1.isThemeNameValid, 'theme')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "theme", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(false),
    (0, sequelize_typescript_1.Is)('UserNoInstanceConfigWarningModal', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserNoModal, 'no instance config warning modal')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "noInstanceConfigWarningModal", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(false),
    (0, sequelize_typescript_1.Is)('UserNoWelcomeModal', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserNoModal, 'no welcome modal')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "noWelcomeModal", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(false),
    (0, sequelize_typescript_1.Is)('UserNoAccountSetupWarningModal', value => (0, utils_1.throwIfNotValid)(value, users_2.isUserNoModal, 'no account setup warning modal')),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Boolean)
], UserModel.prototype, "noAccountSetupWarningModal", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Default)(null),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "pluginAuth", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(false),
    (0, sequelize_typescript_1.Default)(sequelize_typescript_1.DataType.UUIDV4),
    (0, sequelize_typescript_1.IsUUID)(4),
    (0, sequelize_typescript_1.Column)(sequelize_typescript_1.DataType.UUID),
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "feedToken", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Default)(null),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", Date)
], UserModel.prototype, "lastLoginDate", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.AllowNull)(true),
    (0, sequelize_typescript_1.Default)(null),
    sequelize_typescript_1.Column,
    tslib_1.__metadata("design:type", String)
], UserModel.prototype, "otpSecret", void 0);
tslib_1.__decorate([
    sequelize_typescript_1.CreatedAt,
    tslib_1.__metadata("design:type", Date)
], UserModel.prototype, "createdAt", void 0);
tslib_1.__decorate([
    sequelize_typescript_1.UpdatedAt,
    tslib_1.__metadata("design:type", Date)
], UserModel.prototype, "updatedAt", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.HasOne)(() => account_1.AccountModel, {
        foreignKey: 'userId',
        onDelete: 'cascade',
        hooks: true
    }),
    tslib_1.__metadata("design:type", account_1.AccountModel)
], UserModel.prototype, "Account", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.HasOne)(() => user_notification_setting_1.UserNotificationSettingModel, {
        foreignKey: 'userId',
        onDelete: 'cascade',
        hooks: true
    }),
    tslib_1.__metadata("design:type", user_notification_setting_1.UserNotificationSettingModel)
], UserModel.prototype, "NotificationSetting", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.HasMany)(() => video_import_1.VideoImportModel, {
        foreignKey: 'userId',
        onDelete: 'cascade'
    }),
    tslib_1.__metadata("design:type", Array)
], UserModel.prototype, "VideoImports", void 0);
tslib_1.__decorate([
    (0, sequelize_typescript_1.HasMany)(() => oauth_token_1.OAuthTokenModel, {
        foreignKey: 'userId',
        onDelete: 'cascade'
    }),
    tslib_1.__metadata("design:type", Array)
], UserModel.prototype, "OAuthTokens", void 0);
tslib_1.__decorate([
    sequelize_typescript_1.BeforeCreate,
    sequelize_typescript_1.BeforeUpdate,
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [UserModel]),
    tslib_1.__metadata("design:returntype", void 0)
], UserModel, "cryptPasswordIfNeeded", null);
tslib_1.__decorate([
    sequelize_typescript_1.AfterUpdate,
    sequelize_typescript_1.AfterDestroy,
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [UserModel]),
    tslib_1.__metadata("design:returntype", void 0)
], UserModel, "removeTokenCache", null);
UserModel = UserModel_1 = tslib_1.__decorate([
    (0, sequelize_typescript_1.DefaultScope)(() => ({
        include: [
            {
                model: account_1.AccountModel,
                required: true
            },
            {
                model: user_notification_setting_1.UserNotificationSettingModel,
                required: true
            }
        ]
    })),
    (0, sequelize_typescript_1.Scopes)(() => ({
        [ScopeNames.FOR_ME_API]: {
            include: [
                {
                    model: account_1.AccountModel,
                    include: [
                        {
                            model: video_channel_1.VideoChannelModel.unscoped(),
                            include: [
                                {
                                    model: actor_1.ActorModel,
                                    required: true,
                                    include: [
                                        {
                                            model: actor_image_1.ActorImageModel,
                                            as: 'Banners',
                                            required: false
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            attributes: ['id', 'name', 'type'],
                            model: video_playlist_1.VideoPlaylistModel.unscoped(),
                            required: true,
                            where: {
                                type: {
                                    [sequelize_1.Op.ne]: 1
                                }
                            }
                        }
                    ]
                },
                {
                    model: user_notification_setting_1.UserNotificationSettingModel,
                    required: true
                }
            ]
        },
        [ScopeNames.WITH_VIDEOCHANNELS]: {
            include: [
                {
                    model: account_1.AccountModel,
                    include: [
                        {
                            model: video_channel_1.VideoChannelModel
                        },
                        {
                            attributes: ['id', 'name', 'type'],
                            model: video_playlist_1.VideoPlaylistModel.unscoped(),
                            required: true,
                            where: {
                                type: {
                                    [sequelize_1.Op.ne]: 1
                                }
                            }
                        }
                    ]
                }
            ]
        },
        [ScopeNames.WITH_QUOTA]: {
            attributes: {
                include: [
                    [
                        (0, sequelize_1.literal)('(' +
                            UserModel_1.generateUserQuotaBaseSQL({
                                withSelect: false,
                                whereUserId: '"UserModel"."id"',
                                daily: false
                            }) +
                            ')'),
                        'videoQuotaUsed'
                    ],
                    [
                        (0, sequelize_1.literal)('(' +
                            UserModel_1.generateUserQuotaBaseSQL({
                                withSelect: false,
                                whereUserId: '"UserModel"."id"',
                                daily: true
                            }) +
                            ')'),
                        'videoQuotaUsedDaily'
                    ]
                ]
            }
        },
        [ScopeNames.WITH_STATS]: {
            attributes: {
                include: [
                    [
                        (0, sequelize_1.literal)('(' +
                            'SELECT COUNT("video"."id") ' +
                            'FROM "video" ' +
                            'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
                            'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
                            'WHERE "account"."userId" = "UserModel"."id"' +
                            ')'),
                        'videosCount'
                    ],
                    [
                        (0, sequelize_1.literal)('(' +
                            `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
                            'FROM (' +
                            'SELECT COUNT("abuse"."id") AS "abuses", ' +
                            `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${3}) AS "acceptedAbuses" ` +
                            'FROM "abuse" ' +
                            'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
                            'WHERE "account"."userId" = "UserModel"."id"' +
                            ') t' +
                            ')'),
                        'abusesCount'
                    ],
                    [
                        (0, sequelize_1.literal)('(' +
                            'SELECT COUNT("abuse"."id") ' +
                            'FROM "abuse" ' +
                            'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
                            'WHERE "account"."userId" = "UserModel"."id"' +
                            ')'),
                        'abusesCreatedCount'
                    ],
                    [
                        (0, sequelize_1.literal)('(' +
                            'SELECT COUNT("videoComment"."id") ' +
                            'FROM "videoComment" ' +
                            'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
                            'WHERE "account"."userId" = "UserModel"."id"' +
                            ')'),
                        'videoCommentsCount'
                    ]
                ]
            }
        }
    })),
    (0, sequelize_typescript_1.Table)({
        tableName: 'user',
        indexes: [
            {
                fields: ['username'],
                unique: true
            },
            {
                fields: ['email'],
                unique: true
            }
        ]
    })
], UserModel);
exports.UserModel = UserModel;
//# sourceMappingURL=user.js.map