]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/user.ts
Merge remote-tracking branch 'weblate/develop' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / user.ts
1 import { Transaction } from 'sequelize/types'
2 import { v4 as uuidv4 } from 'uuid'
3 import { UserModel } from '@server/models/account/user'
4 import { ActivityPubActorType } from '../../shared/models/activitypub'
5 import { UserNotificationSetting, UserNotificationSettingValue } from '../../shared/models/users'
6 import { SERVER_ACTOR_NAME, WEBSERVER } from '../initializers/constants'
7 import { sequelizeTypescript } from '../initializers/database'
8 import { AccountModel } from '../models/account/account'
9 import { UserNotificationSettingModel } from '../models/account/user-notification-setting'
10 import { ActorModel } from '../models/activitypub/actor'
11 import { MAccountDefault, MActorDefault, MChannelActor } from '../types/models'
12 import { MUser, MUserDefault, MUserId } from '../types/models/user'
13 import { buildActorInstance, generateAndSaveActorKeys } from './activitypub/actor'
14 import { getLocalAccountActivityPubUrl } from './activitypub/url'
15 import { Emailer } from './emailer'
16 import { LiveManager } from './live-manager'
17 import { Redis } from './redis'
18 import { createLocalVideoChannel } from './video-channel'
19 import { createWatchLaterPlaylist } from './video-playlist'
20
21 type ChannelNames = { name: string, displayName: string }
22
23 async function createUserAccountAndChannelAndPlaylist (parameters: {
24 userToCreate: MUser
25 userDisplayName?: string
26 channelNames?: ChannelNames
27 validateUser?: boolean
28 }): Promise<{ user: MUserDefault, account: MAccountDefault, videoChannel: MChannelActor }> {
29 const { userToCreate, userDisplayName, channelNames, validateUser = true } = parameters
30
31 const { user, account, videoChannel } = await sequelizeTypescript.transaction(async t => {
32 const userOptions = {
33 transaction: t,
34 validate: validateUser
35 }
36
37 const userCreated: MUserDefault = await userToCreate.save(userOptions)
38 userCreated.NotificationSetting = await createDefaultUserNotificationSettings(userCreated, t)
39
40 const accountCreated = await createLocalAccountWithoutKeys({
41 name: userCreated.username,
42 displayName: userDisplayName,
43 userId: userCreated.id,
44 applicationId: null,
45 t: t
46 })
47 userCreated.Account = accountCreated
48
49 const channelAttributes = await buildChannelAttributes(userCreated, channelNames)
50 const videoChannel = await createLocalVideoChannel(channelAttributes, accountCreated, t)
51
52 const videoPlaylist = await createWatchLaterPlaylist(accountCreated, t)
53
54 return { user: userCreated, account: accountCreated, videoChannel, videoPlaylist }
55 })
56
57 const [ accountActorWithKeys, channelActorWithKeys ] = await Promise.all([
58 generateAndSaveActorKeys(account.Actor),
59 generateAndSaveActorKeys(videoChannel.Actor)
60 ])
61
62 account.Actor = accountActorWithKeys
63 videoChannel.Actor = channelActorWithKeys
64
65 return { user, account, videoChannel }
66 }
67
68 async function createLocalAccountWithoutKeys (parameters: {
69 name: string
70 displayName?: string
71 userId: number | null
72 applicationId: number | null
73 t: Transaction | undefined
74 type?: ActivityPubActorType
75 }) {
76 const { name, displayName, userId, applicationId, t, type = 'Person' } = parameters
77 const url = getLocalAccountActivityPubUrl(name)
78
79 const actorInstance = buildActorInstance(type, url, name)
80 const actorInstanceCreated: MActorDefault = await actorInstance.save({ transaction: t })
81
82 const accountInstance = new AccountModel({
83 name: displayName || name,
84 userId,
85 applicationId,
86 actorId: actorInstanceCreated.id
87 })
88
89 const accountInstanceCreated: MAccountDefault = await accountInstance.save({ transaction: t })
90 accountInstanceCreated.Actor = actorInstanceCreated
91
92 return accountInstanceCreated
93 }
94
95 async function createApplicationActor (applicationId: number) {
96 const accountCreated = await createLocalAccountWithoutKeys({
97 name: SERVER_ACTOR_NAME,
98 userId: null,
99 applicationId: applicationId,
100 t: undefined,
101 type: 'Application'
102 })
103
104 accountCreated.Actor = await generateAndSaveActorKeys(accountCreated.Actor)
105
106 return accountCreated
107 }
108
109 async function sendVerifyUserEmail (user: MUser, isPendingEmail = false) {
110 const verificationString = await Redis.Instance.setVerifyEmailVerificationString(user.id)
111 let url = WEBSERVER.URL + '/verify-account/email?userId=' + user.id + '&verificationString=' + verificationString
112
113 if (isPendingEmail) url += '&isPendingEmail=true'
114
115 const email = isPendingEmail ? user.pendingEmail : user.email
116 const username = user.username
117
118 await Emailer.Instance.addVerifyEmailJob(username, email, url)
119 }
120
121 async function getOriginalVideoFileTotalFromUser (user: MUserId) {
122 // Don't use sequelize because we need to use a sub query
123 const query = UserModel.generateUserQuotaBaseSQL({
124 withSelect: true,
125 whereUserId: '$userId'
126 })
127
128 const base = await UserModel.getTotalRawQuery(query, user.id)
129
130 return base + LiveManager.Instance.getLiveQuotaUsedByUser(user.id)
131 }
132
133 // Returns cumulative size of all video files uploaded in the last 24 hours.
134 async function getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
135 // Don't use sequelize because we need to use a sub query
136 const query = UserModel.generateUserQuotaBaseSQL({
137 withSelect: true,
138 whereUserId: '$userId',
139 where: '"video"."createdAt" > now() - interval \'24 hours\''
140 })
141
142 const base = await UserModel.getTotalRawQuery(query, user.id)
143
144 return base + LiveManager.Instance.getLiveQuotaUsedByUser(user.id)
145 }
146
147 async function isAbleToUploadVideo (userId: number, size: number) {
148 const user = await UserModel.loadById(userId)
149
150 if (user.videoQuota === -1 && user.videoQuotaDaily === -1) return Promise.resolve(true)
151
152 const [ totalBytes, totalBytesDaily ] = await Promise.all([
153 getOriginalVideoFileTotalFromUser(user),
154 getOriginalVideoFileTotalDailyFromUser(user)
155 ])
156
157 const uploadedTotal = size + totalBytes
158 const uploadedDaily = size + totalBytesDaily
159
160 if (user.videoQuotaDaily === -1) return uploadedTotal < user.videoQuota
161 if (user.videoQuota === -1) return uploadedDaily < user.videoQuotaDaily
162
163 return uploadedTotal < user.videoQuota && uploadedDaily < user.videoQuotaDaily
164 }
165
166 // ---------------------------------------------------------------------------
167
168 export {
169 getOriginalVideoFileTotalFromUser,
170 getOriginalVideoFileTotalDailyFromUser,
171 createApplicationActor,
172 createUserAccountAndChannelAndPlaylist,
173 createLocalAccountWithoutKeys,
174 sendVerifyUserEmail,
175 isAbleToUploadVideo
176 }
177
178 // ---------------------------------------------------------------------------
179
180 function createDefaultUserNotificationSettings (user: MUserId, t: Transaction | undefined) {
181 const values: UserNotificationSetting & { userId: number } = {
182 userId: user.id,
183 newVideoFromSubscription: UserNotificationSettingValue.WEB,
184 newCommentOnMyVideo: UserNotificationSettingValue.WEB,
185 myVideoImportFinished: UserNotificationSettingValue.WEB,
186 myVideoPublished: UserNotificationSettingValue.WEB,
187 abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
188 videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
189 blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
190 newUserRegistration: UserNotificationSettingValue.WEB,
191 commentMention: UserNotificationSettingValue.WEB,
192 newFollow: UserNotificationSettingValue.WEB,
193 newInstanceFollower: UserNotificationSettingValue.WEB,
194 abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
195 abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
196 autoInstanceFollowing: UserNotificationSettingValue.WEB,
197 newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
198 newPluginVersion: UserNotificationSettingValue.WEB
199 }
200
201 return UserNotificationSettingModel.create(values, { transaction: t })
202 }
203
204 async function buildChannelAttributes (user: MUser, channelNames?: ChannelNames) {
205 if (channelNames) return channelNames
206
207 let channelName = user.username + '_channel'
208
209 // Conflict, generate uuid instead
210 const actor = await ActorModel.loadLocalByName(channelName)
211 if (actor) channelName = uuidv4()
212
213 const videoChannelDisplayName = `Main ${user.username} channel`
214
215 return {
216 name: channelName,
217 displayName: videoChannelDisplayName
218 }
219 }