Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
serve-files.js 1.74 KiB
/*
 *
 * @copyright Copyright (c) Open-Xchange GmbH, Germany <info@open-xchange.com>
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OX App Suite. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
 *
 * Any use of the work other than as authorized under this license or copyright law is prohibited.
 *
 */

import { getFile } from '../files.js'
import { isNotAllowedOriginError, isNotFoundError, isVersionMismatchError } from '../errors.js'

export default async function serveFilePlugin (fastify, options) {
  fastify.get('*', async (req, reply) => {
    try {
      const version = reply.version
      const url = req.urlData('path').substr(process.env.APP_ROOT.length - 1)

      const path = url === '/' ? '/index.html' : url
      const { body, headers } = await getFile({ version, path })
      reply.headers(headers)
      reply.send(body)
    } catch (err) {
      if (isNotFoundError(err) || isVersionMismatchError(err)) throw fastify.httpErrors.createError(404, `File "${req.urlData('path')}" does not exist.`, err)
      if (isNotAllowedOriginError(err)) throw fastify.httpErrors.createError(400, err)
      throw fastify.httpErrors.createError(err.statusCode || 500, err)
    }
  })
}