1 import { ensureDir, readdir, remove } from 'fs-extra'
2 import passwordGenerator from 'password-generator'
3 import { join } from 'path'
4 import { UserRole } from '@shared/models'
5 import { logger } from '../helpers/logger'
6 import { buildUser, createApplicationActor, createUserAccountAndChannelAndPlaylist } from '../lib/user'
7 import { ApplicationModel } from '../models/application/application'
8 import { OAuthClientModel } from '../models/oauth/oauth-client'
9 import { applicationExist, clientsExist, usersExist } from './checker-after-init'
10 import { CONFIG } from './config'
11 import { FILES_CACHE, HLS_STREAMING_PLAYLIST_DIRECTORY, LAST_MIGRATION_VERSION, RESUMABLE_UPLOAD_DIRECTORY } from './constants'
12 import { sequelizeTypescript } from './database'
13 import { isTestOrDevInstance } from '@server/helpers/core-utils'
15 async function installApplication () {
19 sequelizeTypescript.sync()
22 createApplicationIfNotExist(),
23 createOAuthClientIfNotExist(),
24 createOAuthAdminIfNotExist()
29 removeCacheAndTmpDirectories()
30 .then(() => createDirectoriesIfNotExist())
33 logger.error('Cannot install application.', { err })
38 // ---------------------------------------------------------------------------
44 // ---------------------------------------------------------------------------
46 function removeCacheAndTmpDirectories () {
47 const cacheDirectories = Object.keys(FILES_CACHE)
48 .map(k => FILES_CACHE[k].DIRECTORY)
50 const tasks: Promise<any>[] = []
53 for (const key of Object.keys(cacheDirectories)) {
54 const dir = cacheDirectories[key]
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 key of Object.keys(cacheDirectories)) {
90 const dir = cacheDirectories[key]
91 tasks.push(ensureDir(dir))
94 // Playlist directories
95 tasks.push(ensureDir(HLS_STREAMING_PLAYLIST_DIRECTORY))
97 // Resumable upload directory
98 tasks.push(ensureDir(RESUMABLE_UPLOAD_DIRECTORY))
100 return Promise.all(tasks)
103 async function createOAuthClientIfNotExist () {
104 const exist = await clientsExist()
105 // Nothing to do, clients already exist
106 if (exist === true) return undefined
108 logger.info('Creating a default OAuth Client.')
110 const id = passwordGenerator(32, false, /[a-z0-9]/)
111 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
112 const client = new OAuthClientModel({
114 clientSecret: secret,
115 grants: [ 'password', 'refresh_token' ],
119 const createdClient = await client.save()
120 logger.info('Client id: ' + createdClient.clientId)
121 logger.info('Client secret: ' + createdClient.clientSecret)
126 async function createOAuthAdminIfNotExist () {
127 const exist = await usersExist()
128 // Nothing to do, users already exist
129 if (exist === true) return undefined
131 logger.info('Creating the administrator.')
133 const username = 'root'
134 const role = UserRole.ADMINISTRATOR
135 const email = CONFIG.ADMIN.EMAIL
136 let validatePassword = true
139 // Do not generate a random password for test and dev environments
140 if (isTestOrDevInstance()) {
143 if (process.env.NODE_APP_INSTANCE) {
144 password += process.env.NODE_APP_INSTANCE
147 // Our password is weak so do not validate it
148 validatePassword = false
149 } else if (process.env.PT_INITIAL_ROOT_PASSWORD) {
150 password = process.env.PT_INITIAL_ROOT_PASSWORD
152 password = passwordGenerator(16, true)
155 const user = buildUser({
165 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
166 logger.info('Username: ' + username)
167 logger.info('User password: ' + password)
170 async function createApplicationIfNotExist () {
171 const exist = await applicationExist()
172 // Nothing to do, application already exist
173 if (exist === true) return undefined
175 logger.info('Creating application account.')
177 const application = await ApplicationModel.create({
178 migrationVersion: LAST_MIGRATION_VERSION
181 return createApplicationActor(application.id)