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