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