1 import { ensureDir, readdir, remove } from 'fs-extra'
2 import passwordGenerator from 'password-generator'
3 import { join } from 'path'
4 import { isTestOrDevInstance } from '@server/helpers/core-utils'
5 import { getNodeABIVersion } from '@server/helpers/version'
6 import { UserRole } from '@shared/models'
7 import { logger } from '../helpers/logger'
8 import { buildUser, createApplicationActor, createUserAccountAndChannelAndPlaylist } from '../lib/user'
9 import { ApplicationModel } from '../models/application/application'
10 import { OAuthClientModel } from '../models/oauth/oauth-client'
11 import { applicationExist, clientsExist, usersExist } from './checker-after-init'
12 import { CONFIG } from './config'
13 import { FILES_CACHE, HLS_STREAMING_PLAYLIST_DIRECTORY, LAST_MIGRATION_VERSION, RESUMABLE_UPLOAD_DIRECTORY } from './constants'
14 import { sequelizeTypescript } from './database'
16 async function installApplication () {
20 sequelizeTypescript.sync()
23 createApplicationIfNotExist(),
24 createOAuthClientIfNotExist(),
25 createOAuthAdminIfNotExist()
30 removeCacheAndTmpDirectories()
31 .then(() => createDirectoriesIfNotExist())
34 logger.error('Cannot install application.', { err })
39 // ---------------------------------------------------------------------------
45 // ---------------------------------------------------------------------------
47 function removeCacheAndTmpDirectories () {
48 const cacheDirectories = Object.keys(FILES_CACHE)
49 .map(k => FILES_CACHE[k].DIRECTORY)
51 const tasks: Promise<any>[] = []
54 for (const key of Object.keys(cacheDirectories)) {
55 const dir = cacheDirectories[key]
56 tasks.push(removeDirectoryOrContent(dir))
59 tasks.push(removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR))
61 return Promise.all(tasks)
64 async function removeDirectoryOrContent (dir: string) {
68 logger.debug('Cannot remove directory %s. Removing content instead.', dir, { err })
70 const files = await readdir(dir)
72 for (const file of files) {
73 await remove(join(dir, file))
78 function createDirectoriesIfNotExist () {
79 const storage = CONFIG.STORAGE
80 const cacheDirectories = Object.keys(FILES_CACHE)
81 .map(k => FILES_CACHE[k].DIRECTORY)
83 const tasks: Promise<void>[] = []
84 for (const key of Object.keys(storage)) {
85 const dir = storage[key]
86 tasks.push(ensureDir(dir))
90 for (const key of Object.keys(cacheDirectories)) {
91 const dir = cacheDirectories[key]
92 tasks.push(ensureDir(dir))
95 // Playlist directories
96 tasks.push(ensureDir(HLS_STREAMING_PLAYLIST_DIRECTORY))
98 // Resumable upload directory
99 tasks.push(ensureDir(RESUMABLE_UPLOAD_DIRECTORY))
101 return Promise.all(tasks)
104 async function createOAuthClientIfNotExist () {
105 const exist = await clientsExist()
106 // Nothing to do, clients already exist
107 if (exist === true) return undefined
109 logger.info('Creating a default OAuth Client.')
111 const id = passwordGenerator(32, false, /[a-z0-9]/)
112 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
113 const client = new OAuthClientModel({
115 clientSecret: secret,
116 grants: [ 'password', 'refresh_token' ],
120 const createdClient = await client.save()
121 logger.info('Client id: ' + createdClient.clientId)
122 logger.info('Client secret: ' + createdClient.clientSecret)
127 async function createOAuthAdminIfNotExist () {
128 const exist = await usersExist()
129 // Nothing to do, users already exist
130 if (exist === true) return undefined
132 logger.info('Creating the administrator.')
134 const username = 'root'
135 const role = UserRole.ADMINISTRATOR
136 const email = CONFIG.ADMIN.EMAIL
137 let validatePassword = true
140 // Do not generate a random password for test and dev environments
141 if (isTestOrDevInstance()) {
144 if (process.env.NODE_APP_INSTANCE) {
145 password += process.env.NODE_APP_INSTANCE
148 // Our password is weak so do not validate it
149 validatePassword = false
150 } else if (process.env.PT_INITIAL_ROOT_PASSWORD) {
151 password = process.env.PT_INITIAL_ROOT_PASSWORD
153 password = passwordGenerator(16, true)
156 const user = buildUser({
166 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
167 logger.info('Username: ' + username)
168 logger.info('User password: ' + password)
171 async function createApplicationIfNotExist () {
172 const exist = await applicationExist()
173 // Nothing to do, application already exist
174 if (exist === true) return undefined
176 logger.info('Creating application account.')
178 const application = await ApplicationModel.create({
179 migrationVersion: LAST_MIGRATION_VERSION,
180 nodeVersion: process.version,
181 nodeABIVersion: getNodeABIVersion()
184 return createApplicationActor(application.id)