Commit ef24ffa1 authored by jan.koester's avatar jan.koester
Browse files

test

parent 74ce194e
Loading
Loading
Loading
Loading
+28 −0
Original line number Diff line number Diff line
@@ -5118,6 +5118,32 @@ struct UploadedExternalImage {
    std::string mediaExt;
};

// Sniffs the actual image format from its bytes for URLs whose path has no
// extension at all (common on CDNs that serve images off an opaque id, e.g.
// "/cdn/img/a1b2c3") -- fetchExternalResource already verified the response's
// Content-Type starts with "image/" but doesn't hand that header back to the
// caller, so this reads the format straight from the (already-fetched, so
// free) body instead of plumbing the header through. Falls back to "webp",
// matching the same default used for mediaExt elsewhere in this file.
static std::string guessImageExtFromBytes(const std::vector<std::uint8_t> &bytes) {
    auto startsWith = [&](std::initializer_list<unsigned char> sig, size_t off = 0) {
        if (bytes.size() < off + sig.size()) return false;
        return std::equal(sig.begin(), sig.end(), bytes.begin() + off);
    };
    if (startsWith({0xFF, 0xD8, 0xFF})) return "jpg";
    if (startsWith({0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A})) return "png";
    if (startsWith({0x47, 0x49, 0x46, 0x38})) return "gif";
    if (startsWith({0x52, 0x49, 0x46, 0x46}) && startsWith({0x57, 0x45, 0x42, 0x50}, 8)) return "webp";
    if (startsWith({0x42, 0x4D})) return "bmp";
    if (!bytes.empty() && bytes[0] == '<') {
        std::string head(bytes.begin(), bytes.begin() + std::min<size_t>(bytes.size(), 256));
        std::transform(head.begin(), head.end(), head.begin(),
                        [](unsigned char c) { return std::tolower(c); });
        if (head.find("<svg") != std::string::npos) return "svg";
    }
    return "webp";
}

static bool isExternalImageUrl(const std::string &s) {
    return s.compare(0, 7, "http://") == 0 || s.compare(0, 8, "https://") == 0;
}
@@ -5567,6 +5593,8 @@ void webedit::Api::handleImportHtml(libhttppp::HttpRequest &curreq,

                std::string filename = std::filesystem::path(url).filename().string();
                if (filename.empty()) filename = "image";
                if (std::filesystem::path(filename).extension().empty())
                    filename += "." + guessImageExtFromBytes(bytes);
                int seen = filenameCounts[filename]++;
                if (seen > 0) {
                    std::filesystem::path p(filename);