Add channel avatar to overviews
[oweals/peertube.git] / server / initializers / installer.ts
1 import * as passwordGenerator from 'password-generator'
2 import { UserRole } from '../../shared'
3 import { logger } from '../helpers/logger'
4 import { createApplicationActor, createUserAccountAndChannel } from '../lib/user'
5 import { UserModel } from '../models/account/user'
6 import { ApplicationModel } from '../models/application/application'
7 import { OAuthClientModel } from '../models/oauth/oauth-client'
8 import { applicationExist, clientsExist, usersExist } from './checker'
9 import { CACHE, CONFIG, LAST_MIGRATION_VERSION } from './constants'
10 import { sequelizeTypescript } from './database'
11 import { remove, ensureDir } from 'fs-extra'
12
13 async function installApplication () {
14   try {
15     await sequelizeTypescript.sync()
16     await removeCacheDirectories()
17     await createDirectoriesIfNotExist()
18     await createApplicationIfNotExist()
19     await createOAuthClientIfNotExist()
20     await createOAuthAdminIfNotExist()
21   } catch (err) {
22     logger.error('Cannot install application.', { err })
23     process.exit(-1)
24   }
25 }
26
27 // ---------------------------------------------------------------------------
28
29 export {
30   installApplication
31 }
32
33 // ---------------------------------------------------------------------------
34
35 function removeCacheDirectories () {
36   const cacheDirectories = Object.keys(CACHE)
37     .map(k => CACHE[k].DIRECTORY)
38
39   const tasks: Promise<any>[] = []
40
41   // Cache directories
42   for (const key of Object.keys(cacheDirectories)) {
43     const dir = cacheDirectories[key]
44     tasks.push(remove(dir))
45   }
46
47   return Promise.all(tasks)
48 }
49
50 function createDirectoriesIfNotExist () {
51   const storage = CONFIG.STORAGE
52   const cacheDirectories = Object.keys(CACHE)
53                                  .map(k => CACHE[k].DIRECTORY)
54
55   const tasks: Promise<void>[] = []
56   for (const key of Object.keys(storage)) {
57     const dir = storage[key]
58     tasks.push(ensureDir(dir))
59   }
60
61   // Cache directories
62   for (const key of Object.keys(cacheDirectories)) {
63     const dir = cacheDirectories[key]
64     tasks.push(ensureDir(dir))
65   }
66
67   return Promise.all(tasks)
68 }
69
70 async function createOAuthClientIfNotExist () {
71   const exist = await clientsExist()
72   // Nothing to do, clients already exist
73   if (exist === true) return undefined
74
75   logger.info('Creating a default OAuth Client.')
76
77   const id = passwordGenerator(32, false, /[a-z0-9]/)
78   const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
79   const client = new OAuthClientModel({
80     clientId: id,
81     clientSecret: secret,
82     grants: [ 'password', 'refresh_token' ],
83     redirectUris: null
84   })
85
86   const createdClient = await client.save()
87   logger.info('Client id: ' + createdClient.clientId)
88   logger.info('Client secret: ' + createdClient.clientSecret)
89
90   return undefined
91 }
92
93 async function createOAuthAdminIfNotExist () {
94   const exist = await usersExist()
95   // Nothing to do, users already exist
96   if (exist === true) return undefined
97
98   logger.info('Creating the administrator.')
99
100   const username = 'root'
101   const role = UserRole.ADMINISTRATOR
102   const email = CONFIG.ADMIN.EMAIL
103   let validatePassword = true
104   let password = ''
105
106   // Do not generate a random password for tests
107   if (process.env.NODE_ENV === 'test') {
108     password = 'test'
109
110     if (process.env.NODE_APP_INSTANCE) {
111       password += process.env.NODE_APP_INSTANCE
112     }
113
114     // Our password is weak so do not validate it
115     validatePassword = false
116   } else {
117     password = passwordGenerator(16, true)
118   }
119
120   const userData = {
121     username,
122     email,
123     password,
124     role,
125     verified: true,
126     nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
127     videoQuota: -1,
128     videoQuotaDaily: -1
129   }
130   const user = new UserModel(userData)
131
132   await createUserAccountAndChannel(user, validatePassword)
133   logger.info('Username: ' + username)
134   logger.info('User password: ' + password)
135 }
136
137 async function createApplicationIfNotExist () {
138   const exist = await applicationExist()
139   // Nothing to do, application already exist
140   if (exist === true) return undefined
141
142   logger.info('Creating application account.')
143
144   const application = await ApplicationModel.create({
145     migrationVersion: LAST_MIGRATION_VERSION
146   })
147
148   return createApplicationActor(application.id)
149 }