]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/initializers/installer.ts
Merge branch 'release/4.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / initializers / installer.ts
1 import { ensureDir, 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(remove(dir))
54 }
55
56 tasks.push(remove(CONFIG.STORAGE.TMP_DIR))
57
58 return Promise.all(tasks)
59 }
60
61 function createDirectoriesIfNotExist () {
62 const storage = CONFIG.STORAGE
63 const cacheDirectories = Object.keys(FILES_CACHE)
64 .map(k => FILES_CACHE[k].DIRECTORY)
65
66 const tasks: Promise<void>[] = []
67 for (const key of Object.keys(storage)) {
68 const dir = storage[key]
69 tasks.push(ensureDir(dir))
70 }
71
72 // Cache directories
73 for (const key of Object.keys(cacheDirectories)) {
74 const dir = cacheDirectories[key]
75 tasks.push(ensureDir(dir))
76 }
77
78 // Playlist directories
79 tasks.push(ensureDir(HLS_STREAMING_PLAYLIST_DIRECTORY))
80
81 // Resumable upload directory
82 tasks.push(ensureDir(RESUMABLE_UPLOAD_DIRECTORY))
83
84 return Promise.all(tasks)
85 }
86
87 async function createOAuthClientIfNotExist () {
88 const exist = await clientsExist()
89 // Nothing to do, clients already exist
90 if (exist === true) return undefined
91
92 logger.info('Creating a default OAuth Client.')
93
94 const id = passwordGenerator(32, false, /[a-z0-9]/)
95 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
96 const client = new OAuthClientModel({
97 clientId: id,
98 clientSecret: secret,
99 grants: [ 'password', 'refresh_token' ],
100 redirectUris: null
101 })
102
103 const createdClient = await client.save()
104 logger.info('Client id: ' + createdClient.clientId)
105 logger.info('Client secret: ' + createdClient.clientSecret)
106
107 return undefined
108 }
109
110 async function createOAuthAdminIfNotExist () {
111 const exist = await usersExist()
112 // Nothing to do, users already exist
113 if (exist === true) return undefined
114
115 logger.info('Creating the administrator.')
116
117 const username = 'root'
118 const role = UserRole.ADMINISTRATOR
119 const email = CONFIG.ADMIN.EMAIL
120 let validatePassword = true
121 let password = ''
122
123 // Do not generate a random password for tests
124 if (process.env.NODE_ENV === 'test') {
125 password = 'test'
126
127 if (process.env.NODE_APP_INSTANCE) {
128 password += process.env.NODE_APP_INSTANCE
129 }
130
131 // Our password is weak so do not validate it
132 validatePassword = false
133 } else if (process.env.PT_INITIAL_ROOT_PASSWORD) {
134 password = process.env.PT_INITIAL_ROOT_PASSWORD
135 } else {
136 password = passwordGenerator(16, true)
137 }
138
139 const user = buildUser({
140 username,
141 email,
142 password,
143 role,
144 emailVerified: true,
145 videoQuota: -1,
146 videoQuotaDaily: -1
147 })
148
149 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
150 logger.info('Username: ' + username)
151 logger.info('User password: ' + password)
152 }
153
154 async function createApplicationIfNotExist () {
155 const exist = await applicationExist()
156 // Nothing to do, application already exist
157 if (exist === true) return undefined
158
159 logger.info('Creating application account.')
160
161 const application = await ApplicationModel.create({
162 migrationVersion: LAST_MIGRATION_VERSION
163 })
164
165 return createApplicationActor(application.id)
166 }