kisstkondoros / gutter-preview

Other
158 stars 37 forks source link

Supports detection of some image URLs without extension name #162

Closed toFrankie closed 5 months ago

toFrankie commented 5 months ago

This PR originated from #155.

During use, I found that some pictures could not be preview (such as https://mmbiz.qpic.cn/mmbiz_jpg/Tf57CQjDpibn2Qx0soyYTPRCGMWSJ2AHYasuUpLf5o7TvibD9HTxOjibT0Y0LbiaCO6mIsrAibEXZiacBBDnfzZB8OLw/640?wx_fmt=jpeg). Since it is a link with Referer anti-hotlink protection, it cannot be displayed on third-party websites. Therefore, it is mistakenly believed that the request contains HTTP Referer, resulting in the inability to access the image.

However, after verification, it was found that after a series of parsed links, the extension name could not be obtained. It is ignored because it is not within the scope of acceptedExtensions.

// server.ts
async function convertToLocalImagePath(absoluteImagePath: string, urlMatch: UrlMatch): Promise<ImageInfo> {
    if (absoluteImagePath) {
        let isDataUri = absoluteImagePath.indexOf('data:image') == 0;
        let isExtensionSupported: boolean;

        if (!isDataUri) {
            const absoluteImageUrl = URI.parse(absoluteImagePath);
            if (absoluteImageUrl && absoluteImageUrl.path) {
                let absolutePath = path.parse(absoluteImageUrl.path);
                isExtensionSupported = acceptedExtensions.some(
                    (ext) => absolutePath && absolutePath.ext && absolutePath.ext.toLowerCase().startsWith(ext)
                );
            }
        }

        const start = Position.create(urlMatch.lineIndex, urlMatch.start);
        const end = Position.create(urlMatch.lineIndex, urlMatch.end);
        const range = { start, end };

        absoluteImagePath = absoluteImagePath.replace(/\|(width=\d*)?(height=\d*)?/gm, '');

        if (isDataUri || isExtensionSupported) {
            // ...
        }
    }
}

url parse demo

I think detecting URL extensions is a reasonable and correct approach since there are a lot of non-image URLs in many projects and it can reduce a lot of unnecessary requests.

However, some OSS services do provide image links that do not end with a common extension name, so we hope to add a configuration item gutterpreview.urlDetectionPatterns, which allows you to set some regular expressions. When the extension does not meet the requirements, a specific regular expression can be matched so that the image can be obtained normally.

The configuration example is as follows:

{
  "gutterpreview.urlDetectionPatterns": ["/^http(s)*://mmbiz.qpic.cn/i"]
}
kisstkondoros commented 5 months ago

Thank you for the contribution! Published with vscode-gutter-preview@0.31.0.