]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/initializers/installer.ts
Try to fix github api rate limit
[github/Chocobozzz/PeerTube.git] / server / initializers / installer.ts
CommitLineData
21d70a73 1import { ensureDir, readdir, remove } from 'fs-extra'
41fb13c3 2import passwordGenerator from 'password-generator'
c74cd9fe 3import { join } from 'path'
c795e196
C
4import { isTestOrDevInstance } from '@server/helpers/core-utils'
5import { getNodeABIVersion } from '@server/helpers/version'
d17c7b4e 6import { UserRole } from '@shared/models'
da854ddd 7import { logger } from '../helpers/logger'
d3d3deaa 8import { buildUser, createApplicationActor, createUserAccountAndChannelAndPlaylist } from '../lib/user'
3fd3ab2d
C
9import { ApplicationModel } from '../models/application/application'
10import { OAuthClientModel } from '../models/oauth/oauth-client'
e5565833 11import { applicationExist, clientsExist, usersExist } from './checker-after-init'
41fb13c3 12import { CONFIG } from './config'
3545e72c 13import { DIRECTORIES, FILES_CACHE, LAST_MIGRATION_VERSION } from './constants'
3fd3ab2d 14import { sequelizeTypescript } from './database'
6fcd19ba 15
f5028693 16async function installApplication () {
e34c85e5 17 try {
0b2f03d3
C
18 await Promise.all([
19 // Database related
20 sequelizeTypescript.sync()
21 .then(() => {
22 return Promise.all([
23 createApplicationIfNotExist(),
24 createOAuthClientIfNotExist(),
25 createOAuthAdminIfNotExist()
26 ])
27 }),
28
29 // Directories
f4800714 30 removeCacheAndTmpDirectories()
0b2f03d3
C
31 .then(() => createDirectoriesIfNotExist())
32 ])
e34c85e5 33 } catch (err) {
d5b7d911 34 logger.error('Cannot install application.', { err })
2ccaeeb3 35 process.exit(-1)
e34c85e5 36 }
37dc07b2
C
37}
38
39// ---------------------------------------------------------------------------
40
65fcc311
C
41export {
42 installApplication
43}
37dc07b2
C
44
45// ---------------------------------------------------------------------------
46
f4800714 47function removeCacheAndTmpDirectories () {
d74d29ad
C
48 const cacheDirectories = Object.keys(FILES_CACHE)
49 .map(k => FILES_CACHE[k].DIRECTORY)
f981dae8 50
571389d4 51 const tasks: Promise<any>[] = []
f981dae8
C
52
53 // Cache directories
f5028693 54 for (const key of Object.keys(cacheDirectories)) {
f981dae8 55 const dir = cacheDirectories[key]
21d70a73 56 tasks.push(removeDirectoryOrContent(dir))
f5028693 57 }
f981dae8 58
21d70a73 59 tasks.push(removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR))
f4800714 60
f981dae8
C
61 return Promise.all(tasks)
62}
63
21d70a73
C
64async function removeDirectoryOrContent (dir: string) {
65 try {
66 await remove(dir)
67 } catch (err) {
68 logger.debug('Cannot remove directory %s. Removing content instead.', dir, { err })
69
70 const files = await readdir(dir)
71
72 for (const file of files) {
c74cd9fe 73 await remove(join(dir, file))
21d70a73
C
74 }
75 }
76}
77
6fcd19ba 78function createDirectoriesIfNotExist () {
b0f9f39e 79 const storage = CONFIG.STORAGE
d74d29ad
C
80 const cacheDirectories = Object.keys(FILES_CACHE)
81 .map(k => FILES_CACHE[k].DIRECTORY)
37dc07b2 82
62689b94 83 const tasks: Promise<void>[] = []
f5028693 84 for (const key of Object.keys(storage)) {
b0f9f39e 85 const dir = storage[key]
62689b94 86 tasks.push(ensureDir(dir))
f5028693 87 }
f981dae8
C
88
89 // Cache directories
f5028693 90 for (const key of Object.keys(cacheDirectories)) {
f981dae8 91 const dir = cacheDirectories[key]
62689b94 92 tasks.push(ensureDir(dir))
f5028693 93 }
37dc07b2 94
3545e72c
C
95 tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE))
96 tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC))
97 tasks.push(ensureDir(DIRECTORIES.VIDEOS.PUBLIC))
98 tasks.push(ensureDir(DIRECTORIES.VIDEOS.PRIVATE))
09209296 99
f6d6e7f8 100 // Resumable upload directory
3545e72c 101 tasks.push(ensureDir(DIRECTORIES.RESUMABLE_UPLOAD))
f6d6e7f8 102
6fcd19ba
C
103 return Promise.all(tasks)
104}
37dc07b2 105
f5028693 106async function createOAuthClientIfNotExist () {
3fd3ab2d 107 const exist = await clientsExist()
f5028693
C
108 // Nothing to do, clients already exist
109 if (exist === true) return undefined
69b0a27c 110
f5028693 111 logger.info('Creating a default OAuth Client.')
37dc07b2 112
f5028693
C
113 const id = passwordGenerator(32, false, /[a-z0-9]/)
114 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
3fd3ab2d 115 const client = new OAuthClientModel({
f5028693
C
116 clientId: id,
117 clientSecret: secret,
118 grants: [ 'password', 'refresh_token' ],
119 redirectUris: null
37dc07b2 120 })
37dc07b2 121
f5028693
C
122 const createdClient = await client.save()
123 logger.info('Client id: ' + createdClient.clientId)
124 logger.info('Client secret: ' + createdClient.clientSecret)
37dc07b2 125
f5028693
C
126 return undefined
127}
37dc07b2 128
f5028693 129async function createOAuthAdminIfNotExist () {
3fd3ab2d 130 const exist = await usersExist()
f5028693
C
131 // Nothing to do, users already exist
132 if (exist === true) return undefined
d14b3e37 133
f5028693 134 logger.info('Creating the administrator.')
d14b3e37 135
f5028693 136 const username = 'root'
954605a8 137 const role = UserRole.ADMINISTRATOR
f5028693
C
138 const email = CONFIG.ADMIN.EMAIL
139 let validatePassword = true
140 let password = ''
67bf9b96 141
3efa4da1
F
142 // Do not generate a random password for test and dev environments
143 if (isTestOrDevInstance()) {
f5028693 144 password = 'test'
37dc07b2 145
f5028693
C
146 if (process.env.NODE_APP_INSTANCE) {
147 password += process.env.NODE_APP_INSTANCE
67bf9b96 148 }
69b0a27c 149
f5028693
C
150 // Our password is weak so do not validate it
151 validatePassword = false
3daaa192
AV
152 } else if (process.env.PT_INITIAL_ROOT_PASSWORD) {
153 password = process.env.PT_INITIAL_ROOT_PASSWORD
f5028693 154 } else {
490b595a 155 password = passwordGenerator(16, true)
f5028693
C
156 }
157
d3d3deaa 158 const user = buildUser({
f5028693
C
159 username,
160 email,
161 password,
162 role,
d3d3deaa 163 emailVerified: true,
bee0abff
FA
164 videoQuota: -1,
165 videoQuotaDaily: -1
d3d3deaa 166 })
f5028693 167
1f20622f 168 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
f5028693
C
169 logger.info('Username: ' + username)
170 logger.info('User password: ' + password)
571389d4 171}
f5028693 172
571389d4 173async function createApplicationIfNotExist () {
3fd3ab2d 174 const exist = await applicationExist()
350e31d6
C
175 // Nothing to do, application already exist
176 if (exist === true) return undefined
177
571389d4 178 logger.info('Creating application account.')
47e0652b 179
50d6de9c 180 const application = await ApplicationModel.create({
c795e196
C
181 migrationVersion: LAST_MIGRATION_VERSION,
182 nodeVersion: process.version,
183 nodeABIVersion: getNodeABIVersion()
50d6de9c 184 })
1b3989b0 185
50d6de9c 186 return createApplicationActor(application.id)
37dc07b2 187}