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