"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetMediaController = void 0;
const openapi = require("@nestjs/swagger");
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const decorators_1 = require("../decorators");
const asset_media_response_dto_1 = require("../dtos/asset-media-response.dto");
const asset_media_dto_1 = require("../dtos/asset-media.dto");
const asset_dto_1 = require("../dtos/asset.dto");
const enum_1 = require("../enum");
const asset_upload_interceptor_1 = require("../middleware/asset-upload.interceptor");
const auth_guard_1 = require("../middleware/auth.guard");
const file_upload_interceptor_1 = require("../middleware/file-upload.interceptor");
const logging_repository_1 = require("../repositories/logging.repository");
const asset_media_service_1 = require("../services/asset-media.service");
const file_1 = require("../utils/file");
const validation_1 = require("../validation");
let AssetMediaController = class AssetMediaController {
    logger;
    service;
    constructor(logger, service) {
        this.logger = logger;
        this.service = service;
    }
    async uploadAsset(auth, files, dto, res) {
        const { file, sidecarFile } = (0, file_upload_interceptor_1.getFiles)(files);
        const responseDto = await this.service.uploadAsset(auth, dto, file, sidecarFile);
        if (responseDto.status === asset_media_response_dto_1.AssetMediaStatus.DUPLICATE) {
            res.status(common_1.HttpStatus.OK);
        }
        return responseDto;
    }
    async downloadAsset(auth, { id }, dto, res, next) {
        await (0, file_1.sendFile)(res, next, () => this.service.downloadOriginal(auth, id, dto), this.logger);
    }
    async viewAsset(auth, { id }, dto, req, res, next) {
        if (dto.size === asset_media_dto_1.AssetMediaSize.Original) {
            this.logger.deprecate('Calling the thumbnail endpoint with size=original is deprecated. Use the :id/original endpoint instead');
            const [_, reqSearch] = req.url.split('?', 2);
            const redirSearchParams = new URLSearchParams(reqSearch);
            redirSearchParams.delete('size');
            return res.redirect('original?' + redirSearchParams.toString());
        }
        const viewThumbnailRes = await this.service.viewThumbnail(auth, id, dto);
        if (viewThumbnailRes instanceof file_1.ImmichFileResponse) {
            await (0, file_1.sendFile)(res, next, () => Promise.resolve(viewThumbnailRes), this.logger);
        }
        else {
            const { targetSize } = viewThumbnailRes;
            const [reqPath, reqSearch] = req.url.split('?', 2);
            let redirPath;
            const redirSearchParams = new URLSearchParams(reqSearch);
            if (targetSize === 'original') {
                redirPath = 'original';
                redirSearchParams.delete('size');
            }
            else if (Object.values(asset_media_dto_1.AssetMediaSize).includes(targetSize)) {
                redirPath = reqPath;
                redirSearchParams.set('size', targetSize);
            }
            else {
                throw new Error('Invalid targetSize: ' + targetSize);
            }
            const finalRedirPath = redirPath + '?' + redirSearchParams.toString();
            return res.redirect(finalRedirPath);
        }
    }
    async playAssetVideo(auth, { id }, res, next) {
        await (0, file_1.sendFile)(res, next, () => this.service.playbackVideo(auth, id), this.logger);
    }
    checkBulkUpload(auth, dto) {
        return this.service.bulkUploadCheck(auth, dto);
    }
};
exports.AssetMediaController = AssetMediaController;
__decorate([
    (0, common_1.Post)(),
    (0, auth_guard_1.Authenticated)({ permission: enum_1.Permission.AssetUpload, sharedLink: true }),
    (0, common_1.UseInterceptors)(asset_upload_interceptor_1.AssetUploadInterceptor, file_upload_interceptor_1.FileUploadInterceptor),
    (0, swagger_1.ApiConsumes)('multipart/form-data'),
    (0, swagger_1.ApiHeader)({
        name: enum_1.ImmichHeader.Checksum,
        description: 'sha1 checksum that can be used for duplicate detection before the file is uploaded',
        required: false,
    }),
    (0, swagger_1.ApiBody)({ description: 'Asset Upload Information', type: asset_media_dto_1.AssetMediaCreateDto }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'Asset is a duplicate',
        type: asset_media_response_dto_1.AssetMediaResponseDto,
    }),
    (0, swagger_1.ApiResponse)({
        status: 201,
        description: 'Asset uploaded successfully',
        type: asset_media_response_dto_1.AssetMediaResponseDto,
    }),
    (0, decorators_1.Endpoint)({
        summary: 'Upload asset',
        description: 'Uploads a new asset to the server.',
        history: new decorators_1.HistoryBuilder().added('v1').beta('v1').stable('v2'),
    }),
    __param(0, (0, auth_guard_1.Auth)()),
    __param(1, (0, common_1.UploadedFiles)(new common_1.ParseFilePipe({ validators: [new validation_1.FileNotEmptyValidator(['assetData'])] }))),
    __param(2, (0, common_1.Body)()),
    __param(3, (0, common_1.Res)({ passthrough: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, asset_media_dto_1.AssetMediaCreateDto, Object]),
    __metadata("design:returntype", Promise)
], AssetMediaController.prototype, "uploadAsset", null);
__decorate([
    (0, common_1.Get)(':id/original'),
    (0, auth_guard_1.FileResponse)(),
    (0, auth_guard_1.Authenticated)({ permission: enum_1.Permission.AssetDownload, sharedLink: true }),
    (0, decorators_1.Endpoint)({
        summary: 'Download original asset',
        description: 'Downloads the original file of the specified asset.',
        history: new decorators_1.HistoryBuilder().added('v1').beta('v1').stable('v2'),
    }),
    openapi.ApiResponse({ status: 200 }),
    __param(0, (0, auth_guard_1.Auth)()),
    __param(1, (0, common_1.Param)()),
    __param(2, (0, common_1.Query)()),
    __param(3, (0, common_1.Res)()),
    __param(4, (0, common_1.Next)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, validation_1.UUIDParamDto,
        asset_dto_1.AssetDownloadOriginalDto, Object, Function]),
    __metadata("design:returntype", Promise)
], AssetMediaController.prototype, "downloadAsset", null);
__decorate([
    (0, common_1.Get)(':id/thumbnail'),
    (0, auth_guard_1.FileResponse)(),
    (0, auth_guard_1.Authenticated)({ permission: enum_1.Permission.AssetView, sharedLink: true }),
    (0, decorators_1.Endpoint)({
        summary: 'View asset thumbnail',
        description: 'Retrieve the thumbnail image for the specified asset. Viewing the fullsize thumbnail might redirect to downloadAsset, which requires a different permission.',
        history: new decorators_1.HistoryBuilder().added('v1').beta('v1').stable('v2'),
    }),
    openapi.ApiResponse({ status: 200 }),
    __param(0, (0, auth_guard_1.Auth)()),
    __param(1, (0, common_1.Param)()),
    __param(2, (0, common_1.Query)()),
    __param(3, (0, common_1.Req)()),
    __param(4, (0, common_1.Res)()),
    __param(5, (0, common_1.Next)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, validation_1.UUIDParamDto,
        asset_media_dto_1.AssetMediaOptionsDto, Object, Object, Function]),
    __metadata("design:returntype", Promise)
], AssetMediaController.prototype, "viewAsset", null);
__decorate([
    (0, common_1.Get)(':id/video/playback'),
    (0, auth_guard_1.FileResponse)(),
    (0, auth_guard_1.Authenticated)({ permission: enum_1.Permission.AssetView, sharedLink: true }),
    (0, decorators_1.Endpoint)({
        summary: 'Play asset video',
        description: 'Streams the video file for the specified asset. This endpoint also supports byte range requests.',
        history: new decorators_1.HistoryBuilder().added('v1').beta('v1').stable('v2'),
    }),
    openapi.ApiResponse({ status: 200 }),
    __param(0, (0, auth_guard_1.Auth)()),
    __param(1, (0, common_1.Param)()),
    __param(2, (0, common_1.Res)()),
    __param(3, (0, common_1.Next)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, validation_1.UUIDParamDto, Object, Function]),
    __metadata("design:returntype", Promise)
], AssetMediaController.prototype, "playAssetVideo", null);
__decorate([
    (0, common_1.Post)('bulk-upload-check'),
    (0, auth_guard_1.Authenticated)({ permission: enum_1.Permission.AssetUpload }),
    (0, decorators_1.Endpoint)({
        summary: 'Check bulk upload',
        description: 'Determine which assets have already been uploaded to the server based on their SHA1 checksums.',
        history: new decorators_1.HistoryBuilder().added('v1').beta('v1').stable('v2'),
    }),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    openapi.ApiResponse({ status: common_1.HttpStatus.OK, type: require("../dtos/asset-media-response.dto").AssetBulkUploadCheckResponseDto }),
    __param(0, (0, auth_guard_1.Auth)()),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, asset_media_dto_1.AssetBulkUploadCheckDto]),
    __metadata("design:returntype", Promise)
], AssetMediaController.prototype, "checkBulkUpload", null);
exports.AssetMediaController = AssetMediaController = __decorate([
    (0, swagger_1.ApiTags)(enum_1.ApiTag.Assets),
    (0, common_1.Controller)(enum_1.RouteKey.Asset),
    __metadata("design:paramtypes", [logging_repository_1.LoggingRepository,
        asset_media_service_1.AssetMediaService])
], AssetMediaController);
//# sourceMappingURL=asset-media.controller.js.map