6aeb198b9e75de7d6517d86ca4a1700f4336d9b2
[oweals/peertube.git] / server / lib / user.ts
1 import * as Sequelize from 'sequelize'
2 import { createPrivateAndPublicKeys, logger } from '../helpers'
3 import { CONFIG, sequelizeTypescript } from '../initializers'
4 import { AccountModel } from '../models/account/account'
5 import { UserModel } from '../models/account/user'
6 import { ActorModel } from '../models/activitypub/actor'
7 import { getAccountActivityPubUrl } from './activitypub'
8 import { createVideoChannel } from './video-channel'
9
10 async function createUserAccountAndChannel (user: UserModel, validateUser = true) {
11   const { account, videoChannel } = await sequelizeTypescript.transaction(async t => {
12     const userOptions = {
13       transaction: t,
14       validate: validateUser
15     }
16
17     const userCreated = await user.save(userOptions)
18     const accountCreated = await createLocalAccountWithoutKeys(user.username, user.id, null, t)
19
20     const videoChannelName = `Default ${userCreated.username} channel`
21     const videoChannelInfo = {
22       name: videoChannelName
23     }
24     const videoChannel = await createVideoChannel(videoChannelInfo, accountCreated, t)
25
26     return { account: accountCreated, videoChannel }
27   })
28
29   // Set account keys, this could be long so process after the account creation and do not block the client
30   const { publicKey, privateKey } = await createPrivateAndPublicKeys()
31   const actor = account.Actor
32   actor.set('publicKey', publicKey)
33   actor.set('privateKey', privateKey)
34   actor.save().catch(err => logger.error('Cannot set public/private keys of actor %d.', actor.uuid, err))
35
36   return { account, videoChannel }
37 }
38
39 async function createLocalAccountWithoutKeys (name: string, userId: number, applicationId: number, t: Sequelize.Transaction) {
40   const url = getAccountActivityPubUrl(name)
41
42   const actorInstance = new ActorModel({
43     url,
44     publicKey: null,
45     privateKey: null,
46     followersCount: 0,
47     followingCount: 0,
48     inboxUrl: url + '/inbox',
49     outboxUrl: url + '/outbox',
50     sharedInboxUrl: CONFIG.WEBSERVER.URL + '/inbox',
51     followersUrl: url + '/followers',
52     followingUrl: url + '/following'
53   })
54   const actorInstanceCreated = await actorInstance.save({ transaction: t })
55
56   const accountInstance = new AccountModel({
57     name,
58     userId,
59     applicationId,
60     actorId: actorInstanceCreated.id,
61     serverId: null // It is our server
62   })
63
64   const accountInstanceCreated = await accountInstance.save({ transaction: t })
65   accountInstanceCreated.Actor = actorInstanceCreated
66
67   return accountInstanceCreated
68 }
69
70 // ---------------------------------------------------------------------------
71
72 export {
73   createUserAccountAndChannel,
74   createLocalAccountWithoutKeys
75 }