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 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 tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PRIVATE))
96 tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC))
97 tasks.push(ensureDir(DIRECTORIES.VIDEOS.PUBLIC))
98 tasks.push(ensureDir(DIRECTORIES.VIDEOS.PRIVATE))
100 // Resumable upload directory
101 tasks.push(ensureDir(DIRECTORIES.RESUMABLE_UPLOAD))
103 return Promise.all(tasks)
106 async function createOAuthClientIfNotExist () {
107 const exist = await clientsExist()
108 // Nothing to do, clients already exist
109 if (exist === true) return undefined
111 logger.info('Creating a default OAuth Client.')
113 const id = passwordGenerator(32, false, /[a-z0-9]/)
114 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
115 const client = new OAuthClientModel({
117 clientSecret: secret,
118 grants: [ 'password', 'refresh_token' ],
122 const createdClient = await client.save()
123 logger.info('Client id: ' + createdClient.clientId)
124 logger.info('Client secret: ' + createdClient.clientSecret)
129 async function createOAuthAdminIfNotExist () {
130 const exist = await usersExist()
131 // Nothing to do, users already exist
132 if (exist === true) return undefined
134 logger.info('Creating the administrator.')
136 const username = 'root'
137 const role = UserRole.ADMINISTRATOR
138 const email = CONFIG.ADMIN.EMAIL
139 let validatePassword = true
142 // Do not generate a random password for test and dev environments
143 if (isTestOrDevInstance()) {
146 if (process.env.NODE_APP_INSTANCE) {
147 password += process.env.NODE_APP_INSTANCE
150 // Our password is weak so do not validate it
151 validatePassword = false
152 } else if (process.env.PT_INITIAL_ROOT_PASSWORD) {
153 password = process.env.PT_INITIAL_ROOT_PASSWORD
155 password = passwordGenerator(16, true)
158 const user = buildUser({
168 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
169 logger.info('Username: ' + username)
170 logger.info('User password: ' + password)
173 async function createApplicationIfNotExist () {
174 const exist = await applicationExist()
175 // Nothing to do, application already exist
176 if (exist === true) return undefined
178 logger.info('Creating application account.')
180 const application = await ApplicationModel.create({
181 migrationVersion: LAST_MIGRATION_VERSION,
182 nodeVersion: process.version,
183 nodeABIVersion: getNodeABIVersion()
186 return createApplicationActor(application.id)