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