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'
14 async function installApplication () {
18 sequelizeTypescript.sync()
21 createApplicationIfNotExist(),
22 createOAuthClientIfNotExist(),
23 createOAuthAdminIfNotExist()
28 removeCacheAndTmpDirectories()
29 .then(() => createDirectoriesIfNotExist())
32 logger.error('Cannot install application.', { err })
37 // ---------------------------------------------------------------------------
43 // ---------------------------------------------------------------------------
45 function removeCacheAndTmpDirectories () {
46 const cacheDirectories = Object.keys(FILES_CACHE)
47 .map(k => FILES_CACHE[k].DIRECTORY)
49 const tasks: Promise<any>[] = []
52 for (const key of Object.keys(cacheDirectories)) {
53 const dir = cacheDirectories[key]
54 tasks.push(removeDirectoryOrContent(dir))
57 tasks.push(removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR))
59 return Promise.all(tasks)
62 async function removeDirectoryOrContent (dir: string) {
66 logger.debug('Cannot remove directory %s. Removing content instead.', dir, { err })
68 const files = await readdir(dir)
70 for (const file of files) {
71 await remove(join(dir, file))
76 function createDirectoriesIfNotExist () {
77 const storage = CONFIG.STORAGE
78 const cacheDirectories = Object.keys(FILES_CACHE)
79 .map(k => FILES_CACHE[k].DIRECTORY)
81 const tasks: Promise<void>[] = []
82 for (const key of Object.keys(storage)) {
83 const dir = storage[key]
84 tasks.push(ensureDir(dir))
88 for (const key of Object.keys(cacheDirectories)) {
89 const dir = cacheDirectories[key]
90 tasks.push(ensureDir(dir))
93 // Playlist directories
94 tasks.push(ensureDir(HLS_STREAMING_PLAYLIST_DIRECTORY))
96 // Resumable upload directory
97 tasks.push(ensureDir(RESUMABLE_UPLOAD_DIRECTORY))
99 return Promise.all(tasks)
102 async function createOAuthClientIfNotExist () {
103 const exist = await clientsExist()
104 // Nothing to do, clients already exist
105 if (exist === true) return undefined
107 logger.info('Creating a default OAuth Client.')
109 const id = passwordGenerator(32, false, /[a-z0-9]/)
110 const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/)
111 const client = new OAuthClientModel({
113 clientSecret: secret,
114 grants: [ 'password', 'refresh_token' ],
118 const createdClient = await client.save()
119 logger.info('Client id: ' + createdClient.clientId)
120 logger.info('Client secret: ' + createdClient.clientSecret)
125 async function createOAuthAdminIfNotExist () {
126 const exist = await usersExist()
127 // Nothing to do, users already exist
128 if (exist === true) return undefined
130 logger.info('Creating the administrator.')
132 const username = 'root'
133 const role = UserRole.ADMINISTRATOR
134 const email = CONFIG.ADMIN.EMAIL
135 let validatePassword = true
138 // Do not generate a random password for tests
139 if (process.env.NODE_ENV === 'test') {
142 if (process.env.NODE_APP_INSTANCE) {
143 password += process.env.NODE_APP_INSTANCE
146 // Our password is weak so do not validate it
147 validatePassword = false
148 } else if (process.env.PT_INITIAL_ROOT_PASSWORD) {
149 password = process.env.PT_INITIAL_ROOT_PASSWORD
151 password = passwordGenerator(16, true)
154 const user = buildUser({
164 await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword })
165 logger.info('Username: ' + username)
166 logger.info('User password: ' + password)
169 async function createApplicationIfNotExist () {
170 const exist = await applicationExist()
171 // Nothing to do, application already exist
172 if (exist === true) return undefined
174 logger.info('Creating application account.')
176 const application = await ApplicationModel.create({
177 migrationVersion: LAST_MIGRATION_VERSION
180 return createApplicationActor(application.id)