"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ImgController = void 0;

var _path = _interopRequireDefault(require("path"));

var _fsExtra = _interopRequireDefault(require("fs-extra"));

var _typescriptRoutesToOpenapiServer = require("typescript-routes-to-openapi-server");

var _utils = require("../utils");

var _mediaItem = require("../repository/mediaItem");

var _season = require("../repository/season");

var _image = require("../repository/image");

var _config = require("../config");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @openapi_tags Img
 */
class ImgController {
  /**
   * @openapi_operationId GetImage
   */
  image = (0, _typescriptRoutesToOpenapiServer.createExpressRoute)(async (req, res) => {
    const {
      size
    } = req.query;
    const {
      id
    } = req.params;

    const imagePath = _path.default.resolve(_config.Config.ASSETS_PATH, size || 'original', `${id}.webp`);

    if (!(await _fsExtra.default.pathExists(imagePath))) {
      const image = await _image.imageRepository.findOne({
        id: id
      });

      if (!image) {
        res.sendStatus(404);
        return;
      }

      if (image.seasonId) {
        const season = await _season.tvSeasonRepository.findOne({
          id: image.seasonId
        });

        if (!season.poster) {
          res.sendStatus(404);
          return;
        }

        await (0, _utils.downloadAsset)({
          imageId: image.id,
          url: season.poster
        });
      } else {
        const mediaItem = await _mediaItem.mediaItemRepository.findOne({
          id: image.mediaItemId
        });
        const url = image.type === 'poster' ? mediaItem.poster : mediaItem.backdrop;

        if (!url) {
          res.sendStatus(404);
          return;
        }

        await (0, _utils.downloadAsset)({
          imageId: image.id,
          url: url
        });
      }
    }

    if (!(await _fsExtra.default.pathExists(imagePath))) {
      res.sendStatus(404);
      return;
    }

    res.setHeader('Content-Type', 'image/webp');
    res.set('Cache-Control', 'max-age=31536000');
    res.sendFile(imagePath);
  });
}

exports.ImgController = ImgController;
//# sourceMappingURL=img.js.map