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'
13 async function installApplication () {
17 sequelizeTypescript.sync()
20 createApplicationIfNotExist(),
21 createOAuthClientIfNotExist(),
22 createOAuthAdminIfNotExist()
27 removeCacheAndTmpDirectories()
28 .then(() => createDirectoriesIfNotExist())
31 logger.error('Cannot install application.', { err })
36 // ---------------------------------------------------------------------------
42 // ---------------------------------------------------------------------------
44 function removeCacheAndTmpDirectories () {
45 const cacheDirectories = Object.keys(FILES_CACHE)
46 .map(k => FILES_CACHE[k].DIRECTORY)
48 const tasks: Promise<any>[] = []
51 for (const key of Object.keys(cacheDirectories)) {
52 const dir = cacheDirectories[key]
53 tasks.push(removeDirectoryOrContent(dir))
56 tasks.push(removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR))
58 return Promise.all(tasks)
61 async function removeDirectoryOrContent (dir: string) {
65 logger.debug('Cannot remove directory %s. Removing content instead.', dir, { err })
67 const files = await readdir(dir)
69 for (const file of files) {
75 function createDirectoriesIfNotExist () {
76 const storage = CONFIG.STORAGE
77 const cacheDirectories = Object.keys(FILES_CACHE)
78 .map(k => FILES_CACHE[k].DIRECTORY)
80 const tasks: Promise<void>[] = []
81 for (const key of Object.keys(storage)) {
82 const dir = storage[key]
83 tasks.push(ensureDir(dir))
87 for (const key of Object.keys(cacheDirectories)) {
88 const dir = cacheDirectories[key]
89 tasks.push(ensureDir(dir))
92 // Playlist directories
93 tasks.push(ensureDir(HLS_STREAMING_PLAYLIST_DIRECTORY))
95 // Resumable upload directory
96 tasks.push(ensureDir(RESUMABLE_UPLOAD_DIRECTORY))
98 return Promise.all(tasks)
101 async function createOAuthClientIfNotExist () {
102 const exist = await clientsExist()
103 // Nothing to do, clients already exist
104 if (exist === true) return undefined
106 logger.info('Creating a default OAuth Client.')
108 const id = passwordGenerator(32, false, /[a-z0-9]/)
109 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
110 const client = new OAuthClientModel({
112 clientSecret: secret,
113 grants: [ 'password', 'refresh_token' ],
117 const createdClient = await client.save()
118 logger.info('Client id: ' + createdClient.clientId)
119 logger.info('Client secret: ' + createdClient.clientSecret)
124 async function createOAuthAdminIfNotExist () {
125 const exist = await usersExist()
126 // Nothing to do, users already exist
127 if (exist === true) return undefined
129 logger.info('Creating the administrator.')
131 const username = 'root'
132 const role = UserRole.ADMINISTRATOR
133 const email = CONFIG.ADMIN.EMAIL
134 let validatePassword = true
137 // Do not generate a random password for tests
138 if (process.env.NODE_ENV === 'test') {
141 if (process.env.NODE_APP_INSTANCE) {
142 password += process.env.NODE_APP_INSTANCE
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
150 password = passwordGenerator(16, true)
153 const user = buildUser({
163 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
164 logger.info('Username: ' + username)
165 logger.info('User password: ' + password)
168 async function createApplicationIfNotExist () {
169 const exist = await applicationExist()
170 // Nothing to do, application already exist
171 if (exist === true) return undefined
173 logger.info('Creating application account.')
175 const application = await ApplicationModel.create({
176 migrationVersion: LAST_MIGRATION_VERSION
179 return createApplicationActor(application.id)