X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Finitializers%2Finstaller.ts;h=7e321fb76e8c9f30c3e34eed1db3ab10b5ba3009;hb=c3edc5b074aa4bb1861ed0a94d3713808e87170f;hp=f105c82924d52e248c514802285034597cc18ded;hpb=69818c9394366b954b6ba3bd697bd9d2b09f2a16;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/initializers/installer.ts b/server/initializers/installer.ts index f105c8292..7e321fb76 100644 --- a/server/initializers/installer.ts +++ b/server/initializers/installer.ts @@ -1,37 +1,37 @@ -import { join } from 'path' -import * as config from 'config' -import { each, series } from 'async' -import * as mkdirp from 'mkdirp' -import * as passwordGenerator from 'password-generator' - -import { database as db } from './database' -import { USER_ROLES, CONFIG, LAST_MIGRATION_VERSION } from './constants' -import { clientsExist, usersExist } from './checker' -import { logger, createCertsIfNotExist, root } from '../helpers' - -function installApplication (callback: (err: Error) => void) { - series([ - function createDatabase (callbackAsync) { - db.sequelize.sync().asCallback(callbackAsync) - // db.sequelize.sync({ force: true }).asCallback(callbackAsync) - }, - - function createDirectories (callbackAsync) { - createDirectoriesIfNotExist(callbackAsync) - }, - - function createCertificates (callbackAsync) { - createCertsIfNotExist(callbackAsync) - }, - - function createOAuthClient (callbackAsync) { - createOAuthClientIfNotExist(callbackAsync) - }, - - function createOAuthUser (callbackAsync) { - createOAuthAdminIfNotExist(callbackAsync) - } - ], callback) +import { ensureDir, remove } from 'fs-extra' +import passwordGenerator from 'password-generator' +import { UserRole } from '@shared/models' +import { logger } from '../helpers/logger' +import { createApplicationActor, createUserAccountAndChannelAndPlaylist } from '../lib/user' +import { ApplicationModel } from '../models/application/application' +import { OAuthClientModel } from '../models/oauth/oauth-client' +import { UserModel } from '../models/user/user' +import { applicationExist, clientsExist, usersExist } from './checker-after-init' +import { CONFIG } from './config' +import { FILES_CACHE, HLS_STREAMING_PLAYLIST_DIRECTORY, LAST_MIGRATION_VERSION, RESUMABLE_UPLOAD_DIRECTORY } from './constants' +import { sequelizeTypescript } from './database' + +async function installApplication () { + try { + await Promise.all([ + // Database related + sequelizeTypescript.sync() + .then(() => { + return Promise.all([ + createApplicationIfNotExist(), + createOAuthClientIfNotExist(), + createOAuthAdminIfNotExist() + ]) + }), + + // Directories + removeCacheAndTmpDirectories() + .then(() => createDirectoriesIfNotExist()) + ]) + } catch (err) { + logger.error('Cannot install application.', { err }) + process.exit(-1) + } } // --------------------------------------------------------------------------- @@ -42,88 +42,129 @@ export { // --------------------------------------------------------------------------- -function createDirectoriesIfNotExist (callback: (err: Error) => void) { - const storages = config.get('storage') +function removeCacheAndTmpDirectories () { + const cacheDirectories = Object.keys(FILES_CACHE) + .map(k => FILES_CACHE[k].DIRECTORY) + + const tasks: Promise[] = [] + + // Cache directories + for (const key of Object.keys(cacheDirectories)) { + const dir = cacheDirectories[key] + tasks.push(remove(dir)) + } - each(Object.keys(storages), function (key, callbackEach) { - const dir = storages[key] - mkdirp(join(root(), dir), callbackEach) - }, callback) + tasks.push(remove(CONFIG.STORAGE.TMP_DIR)) + + return Promise.all(tasks) } -function createOAuthClientIfNotExist (callback: (err: Error) => void) { - clientsExist(function (err, exist) { - if (err) return callback(err) +function createDirectoriesIfNotExist () { + const storage = CONFIG.STORAGE + const cacheDirectories = Object.keys(FILES_CACHE) + .map(k => FILES_CACHE[k].DIRECTORY) + + const tasks: Promise[] = [] + for (const key of Object.keys(storage)) { + const dir = storage[key] + tasks.push(ensureDir(dir)) + } + + // Cache directories + for (const key of Object.keys(cacheDirectories)) { + const dir = cacheDirectories[key] + tasks.push(ensureDir(dir)) + } - // Nothing to do, clients already exist - if (exist === true) return callback(null) + // Playlist directories + tasks.push(ensureDir(HLS_STREAMING_PLAYLIST_DIRECTORY)) - logger.info('Creating a default OAuth Client.') + // Resumable upload directory + tasks.push(ensureDir(RESUMABLE_UPLOAD_DIRECTORY)) - const id = passwordGenerator(32, false, /[a-z0-9]/) - const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/) - const client = db.OAuthClient.build({ - clientId: id, - clientSecret: secret, - grants: [ 'password', 'refresh_token' ], - redirectUris: null - }) + return Promise.all(tasks) +} - client.save().asCallback(function (err, createdClient) { - if (err) return callback(err) +async function createOAuthClientIfNotExist () { + const exist = await clientsExist() + // Nothing to do, clients already exist + if (exist === true) return undefined - logger.info('Client id: ' + createdClient.clientId) - logger.info('Client secret: ' + createdClient.clientSecret) + logger.info('Creating a default OAuth Client.') - return callback(null) - }) + const id = passwordGenerator(32, false, /[a-z0-9]/) + const secret = passwordGenerator(32, false, /[a-zA-Z0-9]/) + const client = new OAuthClientModel({ + clientId: id, + clientSecret: secret, + grants: [ 'password', 'refresh_token' ], + redirectUris: null }) -} -function createOAuthAdminIfNotExist (callback: (err: Error) => void) { - usersExist(function (err, exist) { - if (err) return callback(err) + const createdClient = await client.save() + logger.info('Client id: ' + createdClient.clientId) + logger.info('Client secret: ' + createdClient.clientSecret) - // Nothing to do, users already exist - if (exist === true) return callback(null) + return undefined +} - logger.info('Creating the administrator.') +async function createOAuthAdminIfNotExist () { + const exist = await usersExist() + // Nothing to do, users already exist + if (exist === true) return undefined - const username = 'root' - const role = USER_ROLES.ADMIN - const email = CONFIG.ADMIN.EMAIL - const createOptions: { validate?: boolean } = {} - let password = '' + logger.info('Creating the administrator.') - // Do not generate a random password for tests - if (process.env.NODE_ENV === 'test') { - password = 'test' + const username = 'root' + const role = UserRole.ADMINISTRATOR + const email = CONFIG.ADMIN.EMAIL + let validatePassword = true + let password = '' - if (process.env.NODE_APP_INSTANCE) { - password += process.env.NODE_APP_INSTANCE - } + // Do not generate a random password for tests + if (process.env.NODE_ENV === 'test') { + password = 'test' - // Our password is weak so do not validate it - createOptions.validate = false - } else { - password = passwordGenerator(8, true) + if (process.env.NODE_APP_INSTANCE) { + password += process.env.NODE_APP_INSTANCE } - const userData = { - username, - email, - password, - role - } + // Our password is weak so do not validate it + validatePassword = false + } else if (process.env.PT_INITIAL_ROOT_PASSWORD) { + password = process.env.PT_INITIAL_ROOT_PASSWORD + } else { + password = passwordGenerator(16, true) + } + + const userData = { + username, + email, + password, + role, + verified: true, + nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, + p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED, + videoQuota: -1, + videoQuotaDaily: -1 + } + const user = new UserModel(userData) + + await createUserAccountAndChannelAndPlaylist({ userToCreate: user, channelNames: undefined, validateUser: validatePassword }) + logger.info('Username: ' + username) + logger.info('User password: ' + password) +} - db.User.create(userData, createOptions).asCallback(function (err, createdUser) { - if (err) return callback(err) +async function createApplicationIfNotExist () { + const exist = await applicationExist() + // Nothing to do, application already exist + if (exist === true) return undefined - logger.info('Username: ' + username) - logger.info('User password: ' + password) + logger.info('Creating application account.') - logger.info('Creating Application table.') - db.Application.create({ migrationVersion: LAST_MIGRATION_VERSION }).asCallback(callback) - }) + const application = await ApplicationModel.create({ + migrationVersion: LAST_MIGRATION_VERSION }) + + return createApplicationActor(application.id) }