You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

247 lines
9.1 KiB

  1. 'use strict'
  2. // =====================================================
  3. // Wiki.js
  4. // Installation Script
  5. // =====================================================
  6. const Promise = require('bluebird')
  7. const _ = require('lodash')
  8. const colors = require('colors/safe')
  9. const exec = require('execa')
  10. const fs = Promise.promisifyAll(require('fs-extra'))
  11. const https = require('follow-redirects').https
  12. const inquirer = require('inquirer')
  13. const os = require('os')
  14. const path = require('path')
  15. const pm2 = Promise.promisifyAll(require('pm2'))
  16. const tar = require('tar')
  17. const zlib = require('zlib')
  18. const installDir = path.resolve(__dirname, '../..')
  19. // =====================================================
  20. // INSTALLATION TASKS
  21. // =====================================================
  22. const tasks = {
  23. /**
  24. * Stop and delete existing instances
  25. */
  26. stopAndDeleteInstances () {
  27. ora.text = 'Looking for running instances...'
  28. return pm2.connectAsync().then(() => {
  29. return pm2.describeAsync('wiki').then(() => {
  30. ora.text = 'Stopping and deleting process from pm2...'
  31. return pm2.deleteAsync('wiki')
  32. }).catch(err => { // eslint-disable-line handle-callback-err
  33. return true
  34. }).finally(() => {
  35. pm2.disconnect()
  36. })
  37. })
  38. },
  39. /**
  40. * Check for sufficient memory
  41. */
  42. checkRequirements () {
  43. ora.text = 'Checking system requirements...'
  44. if (os.totalmem() < 1024 * 1024 * 768) {
  45. return Promise.reject(new Error('Not enough memory to install dependencies. Minimum is 768 MB.'))
  46. } else {
  47. return Promise.resolve(true)
  48. }
  49. },
  50. /**
  51. * Install via local tarball if present
  52. */
  53. installFromLocal () {
  54. let hasTarball = true
  55. let tbPath = path.join(installDir, 'wiki-js.tar.gz')
  56. return fs.accessAsync(tbPath)
  57. .catch(err => { // eslint-disable-line handle-callback-err
  58. hasTarball = false
  59. }).then(() => {
  60. if (hasTarball) {
  61. ora.text = 'Local tarball found. Extracting...'
  62. return new Promise((resolve, reject) => {
  63. fs.createReadStream(tbPath).pipe(zlib.createGunzip())
  64. .pipe(tar.Extract({ path: installDir }))
  65. .on('error', err => reject(err))
  66. .on('end', () => {
  67. ora.text = 'Tarball extracted successfully.'
  68. resolve(true)
  69. })
  70. })
  71. } else {
  72. return false
  73. }
  74. })
  75. },
  76. /**
  77. * Install from GitHub release download
  78. */
  79. installFromRemote () {
  80. // Fetch version from npm package
  81. return fs.readJsonAsync('package.json').then((packageObj) => {
  82. let versionGet = _.chain(packageObj.version).split('.').take(4).join('.')
  83. let remoteURL = _.replace('https://github.com/Requarks/wiki/releases/download/v{0}/wiki-js.tar.gz', '{0}', versionGet)
  84. return new Promise((resolve, reject) => {
  85. // Fetch tarball
  86. ora.text = 'Looking for latest release...'
  87. https.get(remoteURL, resp => {
  88. if (resp.statusCode !== 200) {
  89. return reject(new Error('Remote file not found'))
  90. }
  91. ora.text = 'Remote wiki.js tarball found. Downloading...'
  92. // Extract tarball
  93. resp.pipe(zlib.createGunzip())
  94. .pipe(tar.Extract({ path: installDir }))
  95. .on('error', err => reject(err))
  96. .on('end', () => {
  97. ora.text = 'Tarball extracted successfully.'
  98. resolve(true)
  99. })
  100. })
  101. })
  102. })
  103. },
  104. /**
  105. * Install npm dependencies
  106. */
  107. installDependencies () {
  108. ora.text = 'Installing Wiki.js npm dependencies...'
  109. return exec.stdout('npm', ['install', '--only=production', '--no-optional'], {
  110. cwd: installDir
  111. }).then(results => {
  112. ora.text = 'Wiki.js npm dependencies installed successfully.'
  113. return true
  114. })
  115. },
  116. /**
  117. * Create default config.yml file if new installation
  118. */
  119. ensureConfigFile () {
  120. return fs.accessAsync(path.join(installDir, 'config.yml')).then(() => {
  121. // Is Upgrade
  122. ora.succeed('Upgrade completed.')
  123. console.info(colors.yellow('\n!!! IMPORTANT !!!'))
  124. console.info(colors.yellow('Running the configuration wizard is optional but recommended after an upgrade to ensure your config file is using the latest available settings.'))
  125. console.info(colors.yellow('Note that the contents of your config file will be displayed during the configuration wizard. It is therefor highly recommended to run the wizard on a non-publicly accessible port or skip this step completely.\n'))
  126. return true
  127. }).catch(err => {
  128. // Is New Install
  129. if (err.code === 'ENOENT') {
  130. ora.text = 'First-time install, creating a new config.yml...'
  131. let sourceConfigFile = path.join(installDir, 'config.sample.yml')
  132. if (process.env.WIKI_JS_HEROKU) {
  133. sourceConfigFile = path.join(__dirname, 'configs/config.heroku.yml')
  134. } else if (process.env.WIKI_JS_DOCKER) {
  135. sourceConfigFile = path.join(__dirname, 'configs/config.docker.yml')
  136. }
  137. return fs.copyAsync(sourceConfigFile, path.join(installDir, 'config.yml')).then(() => {
  138. ora.succeed('Installation succeeded.')
  139. return true
  140. })
  141. } else {
  142. return err
  143. }
  144. })
  145. },
  146. startConfigurationWizard () {
  147. if (process.env.WIKI_JS_HEROKU) {
  148. console.info('Wiki.js has been installed and is configured to use Heroku configuration.')
  149. } else if (process.env.WIKI_JS_DOCKER) {
  150. console.info('Docker environment detected. Skipping setup wizard auto-start.')
  151. } else if (process.stdout.isTTY) {
  152. inquirer.prompt([{
  153. type: 'list',
  154. name: 'action',
  155. message: 'Continue with configuration wizard?',
  156. default: 'default',
  157. choices: [
  158. { name: 'Yes, run configuration wizard on port 3000 (recommended)', value: 'default', short: 'Yes' },
  159. { name: 'Yes, run configuration wizard on a custom port...', value: 'custom', short: 'Yes' },
  160. { name: 'No, I\'ll configure the config file manually', value: 'exit', short: 'No' }
  161. ]
  162. }, {
  163. type: 'input',
  164. name: 'customport',
  165. message: 'Custom port to use:',
  166. default: 3000,
  167. validate: (val) => {
  168. val = _.toNumber(val)
  169. return (_.isNumber(val) && val > 0) ? true : 'Invalid Port!'
  170. },
  171. when: (ans) => {
  172. return ans.action === 'custom'
  173. }
  174. }]).then((ans) => {
  175. switch (ans.action) {
  176. case 'default':
  177. console.info(colors.bold.cyan('> Browse to http://your-server:3000/ to configure your wiki! (Replaced your-server with the hostname or IP of your server!)'))
  178. ora = require('ora')({ text: 'I\'ll wait until you\'re done ;)', color: 'yellow', spinner: 'pong' }).start()
  179. return exec.stdout('node', ['wiki', 'configure'], {
  180. cwd: installDir
  181. })
  182. case 'custom':
  183. console.info(colors.bold.cyan('> Browse to http://your-server:' + ans.customport + '/ to configure your wiki! (Replaced your-server with the hostname or IP of your server!)'))
  184. ora = require('ora')({ text: 'I\'ll wait until you\'re done ;)', color: 'yellow', spinner: 'pong' }).start()
  185. return exec.stdout('node', ['wiki', 'configure', ans.customport], {
  186. cwd: installDir
  187. })
  188. default:
  189. console.info(colors.bold.cyan('\n> You can run the configuration wizard using command:') + colors.bold.white(' node wiki configure') + colors.bold.cyan('.\n> Then start Wiki.js using command: ') + colors.bold.white('node wiki start'))
  190. return Promise.delay(7000).then(() => {
  191. process.exit(0)
  192. })
  193. }
  194. }).then(() => {
  195. ora.succeed(colors.bold.green('Wiki.js has been configured successfully. It is now starting up and should be accessible very soon!'))
  196. return Promise.delay(3000).then(() => {
  197. console.info('npm is finishing... please wait...')
  198. })
  199. })
  200. } else {
  201. console.info(colors.cyan('[WARNING] Non-interactive terminal detected. You must manually start the configuration wizard using the command: node wiki configure'))
  202. }
  203. }
  204. }
  205. // =====================================================
  206. // INSTALL SEQUENCE
  207. // =====================================================
  208. if (!process.env.WIKI_JS_HEROKU && !process.env.WIKI_JS_DOCKER) {
  209. console.info(colors.yellow(
  210. ' __ __ _ _ _ _ \n' +
  211. '/ / /\\ \\ (_) | _(_) (_)___ \n' +
  212. '\\ \\/ \\/ / | |/ / | | / __| \n' +
  213. ' \\ /\\ /| | <| |_ | \\__ \\ \n' +
  214. ' \\/ \\/ |_|_|\\_\\_(_)/ |___/ \n' +
  215. ' |__/\n'))
  216. } else {
  217. console.info('> WIKI.JS [Installing...]')
  218. }
  219. let ora = require('ora')({ text: 'Initializing...', spinner: 'dots12' }).start()
  220. Promise.join(
  221. tasks.stopAndDeleteInstances(),
  222. tasks.checkRequirements()
  223. ).then(() => {
  224. return tasks.installFromLocal().then(succeeded => {
  225. return (!succeeded) ? tasks.installFromRemote() : true
  226. })
  227. }).then(() => {
  228. return tasks.installDependencies()
  229. }).then(() => {
  230. return tasks.ensureConfigFile()
  231. }).then(() => {
  232. return tasks.startConfigurationWizard()
  233. }).catch(err => {
  234. ora.fail(err)
  235. })