storage.js 6.36 KB
Newer Older
1 2
const fs = require('fs-extra')
const path = require('path')
3 4 5
const tar = require('tar-fs')
const zlib = require('zlib')
const stream = require('stream')
6
const _ = require('lodash')
7 8 9
const Promise = require('bluebird')
const pipeline = Promise.promisify(stream.pipeline)
const moment = require('moment')
10 11 12

const pageHelper = require('../../../helpers/page')
const commonDisk = require('./common')
13 14

/* global WIKI */
15

16
module.exports = {
17
  async activated() {
18
    // not used
19
  },
20
  async deactivated() {
21
    // not used
22
  },
23
  async init() {
24
    WIKI.logger.info('(STORAGE/DISK) Initializing...')
25
    await fs.ensureDir(this.config.path)
26
    WIKI.logger.info('(STORAGE/DISK) Initialization completed.')
27
  },
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  async sync({ manual } = { manual: false }) {
    if (this.config.createDailyBackups || manual) {
      const dirPath = path.join(this.config.path, manual ? '_manual' : '_daily')
      await fs.ensureDir(dirPath)

      const dateFilename = moment().format(manual ? 'YYYYMMDD-HHmmss' : 'DD')

      WIKI.logger.info(`(STORAGE/DISK) Creating backup archive...`)
      await pipeline(
        tar.pack(this.config.path, {
          ignore: (filePath) => {
            return filePath.indexOf('_daily') >= 0 || filePath.indexOf('_manual') >= 0
          }
        }),
        zlib.createGzip(),
        fs.createWriteStream(path.join(dirPath, `wiki-${dateFilename}.tar.gz`))
      )
      WIKI.logger.info('(STORAGE/DISK) Backup archive created successfully.')
    }
47 48
  },
  async created(page) {
49
    WIKI.logger.info(`(STORAGE/DISK) Creating file [${page.localeCode}] ${page.path}...`)
NGPixel's avatar
NGPixel committed
50
    let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
51
    if (WIKI.config.lang.code !== page.localeCode) {
52 53 54
      fileName = `${page.localeCode}/${fileName}`
    }
    const filePath = path.join(this.config.path, fileName)
55
    await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
56
  },
57
  async updated(page) {
58
    WIKI.logger.info(`(STORAGE/DISK) Updating file [${page.localeCode}] ${page.path}...`)
NGPixel's avatar
NGPixel committed
59
    let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
60
    if (WIKI.config.lang.code !== page.localeCode) {
61 62 63
      fileName = `${page.localeCode}/${fileName}`
    }
    const filePath = path.join(this.config.path, fileName)
64
    await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
65
  },
66
  async deleted(page) {
67
    WIKI.logger.info(`(STORAGE/DISK) Deleting file [${page.localeCode}] ${page.path}...`)
NGPixel's avatar
NGPixel committed
68
    let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
69
    if (WIKI.config.lang.code !== page.localeCode) {
70 71 72
      fileName = `${page.localeCode}/${fileName}`
    }
    const filePath = path.join(this.config.path, fileName)
73
    await fs.unlink(filePath)
74
  },
75
  async renamed(page) {
76 77
    WIKI.logger.info(`(STORAGE/DISK) Renaming file [${page.localeCode}] ${page.path} to [${page.destinationLocaleCode}] ${page.destinationPath}...`)

NGPixel's avatar
NGPixel committed
78 79
    let sourceFilePath = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
    let destinationFilePath = `${page.destinationPath}.${pageHelper.getFileExtension(page.contentType)}`
80

NGPixel's avatar
NGPixel committed
81 82 83 84 85 86 87
    if (WIKI.config.lang.namespacing) {
      if (WIKI.config.lang.code !== page.localeCode) {
        sourceFilePath = `${page.localeCode}/${sourceFilePath}`
      }
      if (WIKI.config.lang.code !== page.destinationLocaleCode) {
        destinationFilePath = `${page.destinationLocaleCode}/${destinationFilePath}`
      }
88
    }
NGPixel's avatar
NGPixel committed
89

90
    await fs.move(path.join(this.config.path, sourceFilePath), path.join(this.config.path, destinationFilePath), { overwrite: true })
91
  },
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  /**
   * ASSET UPLOAD
   *
   * @param {Object} asset Asset to upload
   */
  async assetUploaded (asset) {
    WIKI.logger.info(`(STORAGE/DISK) Creating new file ${asset.path}...`)
    await fs.outputFile(path.join(this.config.path, asset.path), asset.data)
  },
  /**
   * ASSET DELETE
   *
   * @param {Object} asset Asset to delete
   */
  async assetDeleted (asset) {
    WIKI.logger.info(`(STORAGE/DISK) Deleting file ${asset.path}...`)
    await fs.remove(path.join(this.config.path, asset.path))
  },
  /**
   * ASSET RENAME
   *
   * @param {Object} asset Asset to rename
   */
  async assetRenamed (asset) {
    WIKI.logger.info(`(STORAGE/DISK) Renaming file from ${asset.path} to ${asset.destinationPath}...`)
    await fs.move(path.join(this.config.path, asset.path), path.join(this.config.path, asset.destinationPath), { overwrite: true })
  },
119 120 121 122 123 124

  /**
   * HANDLERS
   */
  async dump() {
    WIKI.logger.info(`(STORAGE/DISK) Dumping all content to disk...`)
125 126

    // -> Pages
127 128 129 130 131 132 133
    await pipeline(
      WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt').select().from('pages').where({
        isPrivate: false
      }).stream(),
      new stream.Transform({
        objectMode: true,
        transform: async (page, enc, cb) => {
NGPixel's avatar
NGPixel committed
134
          let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
135
          if (WIKI.config.lang.code !== page.localeCode) {
136 137
            fileName = `${page.localeCode}/${fileName}`
          }
138
          WIKI.logger.info(`(STORAGE/DISK) Dumping page ${fileName}...`)
139 140 141 142 143 144
          const filePath = path.join(this.config.path, fileName)
          await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
          cb()
        }
      })
    )
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    // -> Assets
    const assetFolders = await WIKI.models.assetFolders.getAllPaths()

    await pipeline(
      WIKI.models.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
      new stream.Transform({
        objectMode: true,
        transform: async (asset, enc, cb) => {
          const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
          WIKI.logger.info(`(STORAGE/DISK) Dumping asset ${filename}...`)
          await fs.outputFile(path.join(this.config.path, filename), asset.data)
          cb()
        }
      })
    )

162 163 164 165
    WIKI.logger.info('(STORAGE/DISK) All content was dumped to disk successfully.')
  },
  async backup() {
    return this.sync({ manual: true })
166 167 168
  },
  async importAll() {
    WIKI.logger.info(`(STORAGE/DISK) Importing all content from local disk folder to the DB...`)
169 170 171 172
    await commonDisk.importFromDisk({
      fullPath: this.config.path,
      moduleName: 'DISK'
    })
173
    WIKI.logger.info('(STORAGE/DISK) Import completed.')
174 175
  }
}