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 { DIRECTORIES, FILES_CACHE, LAST_MIGRATION_VERSION } 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 dir of cacheDirectories) {
55 tasks.push(removeDirectoryOrContent(dir))
58 tasks.push(removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR))
60 return Promise.all(tasks)
63 async function removeDirectoryOrContent (dir: string) {
67 logger.debug('Cannot remove directory %s. Removing content instead.', dir, { err })
69 const files = await readdir(dir)
71 for (const file of files) {
72 await remove(join(dir, file))
77 function createDirectoriesIfNotExist () {
78 const storage = CONFIG.STORAGE
79 const cacheDirectories = Object.keys(FILES_CACHE)
80 .map(k => FILES_CACHE[k].DIRECTORY)
82 const tasks: Promise<void>[] = []
83 for (const key of Object.keys(storage)) {
84 const dir = storage[key]
85 tasks.push(ensureDir(dir))
89 for (const dir of cacheDirectories) {
90 tasks.push(ensureDir(dir))
93 tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE))
94 tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC))
95 tasks.push(ensureDir(DIRECTORIES.VIDEOS.PUBLIC))
96 tasks.push(ensureDir(DIRECTORIES.VIDEOS.PRIVATE))
98 // Resumable upload directory
99 tasks.push(ensureDir(DIRECTORIES.RESUMABLE_UPLOAD))
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)