Skip to content

Commit

Permalink
🐞: { Fixed configuration issues, TinyPngWeb is disabled and an except…
Browse files Browse the repository at this point in the history
…ion is thrown}

📝 :
1. Change compress-webp-lossless to compress-next

fix :
🐞 About config
2.. Fixed an unreadable configuration problem
3. Change the configuration to use compress-next
🐞 About TinyPngWeb
4. TinyPngWeb cannot used and return 404(not found) or 413(too large if > 1MB or maybe less). So I break by throwing an exception
  • Loading branch information
supine0703 committed Aug 2, 2024
1 parent 662bc52 commit 0d7c562
Show file tree
Hide file tree
Showing 9 changed files with 57 additions and 44 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@ jobs:
node-version: 'latest'

- name: Compile and Package
run: npm install && npm run build && zip -q -r picgo-plugin-compress-webp-lossless.zip dist
run: npm install && npm run build && zip -q -r picgo-plugin-compress-next.zip dist

- name: Get Latest Release Version
id: get_latest_release
run: echo "VERSION=$(curl -s https://api.github.com/repos/mrgeneralgoo/picgo-plugin-compress-webp-lossless/releases/latest | jq -r .tag_name)" >> $GITHUB_OUTPUT
run: echo "VERSION=$(curl -s https://api.github.com/repos/mrgeneralgoo/picgo-plugin-compress-next/releases/latest | jq -r .tag_name)" >> $GITHUB_OUTPUT

- name: Create Release
uses: ncipollo/release-action@v1
with:
token: ${{ secrets.AUTO_RELEASE_TOKEN }}
tag: ${{github.ref_name}}
artifacts: "picgo-plugin-compress-webp-lossless.zip"
artifacts: "picgo-plugin-compress-next.zip"
body: |
**Full Changelog**: https://github.com/mrgeneralgoo/picgo-plugin-compress-webp-lossless/compare/${{ steps.get_latest_release.outputs.VERSION }}...${{github.ref_name}})
**Full Changelog**: https://github.com/mrgeneralgoo/picgo-plugin-compress-next/compare/${{ steps.get_latest_release.outputs.VERSION }}...${{github.ref_name}})
- name: Publishing to NPM
uses: JS-DevTools/npm-publish@v3
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ Feel free to contribute to this project or report any issues you encounter. Your

# Reporting Issues

[You can click here directly to create an issue](https://github.com/mrgeneralgoo/picgo-plugin-compress-webp-lossless/issues/new)
[You can click here directly to create an issue](https://github.com/supine0703/picgo-plugin-compress-next/issues/new)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "picgo-plugin-compress-next",
"version": "1.0.1",
"version": "1.0.2",
"description": "Image compression plugin for PicGo(>=^2.3.0). Update, adapt and optimize. Better support and richer features",
"main": "dist/index.js",
"type": "commonjs",
Expand Down
16 changes: 8 additions & 8 deletions src/compress/tinypng/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import { IPicGo } from 'picgo';
import { getImageInfo } from '../../utils';
import { CommonParams, ImageInfo } from '../../interface';
import Tinypng from './tinypng';
import TinyPng from './tinypng';

// Interface for Tinypng options
export interface ITinypngOptions {
// Interface for TinyPng options
export interface ITinyPngOptions {
key: string;
}

/**
* Function to compress image using Tinypng API key
* Function to compress image using TinyPng API key
* @param ctx The PicGo instance.
* @param imageUrl The URL of the image to be compressed.
* @returns A Promise that resolves to an ImageInfo object containing information about the compressed image.
*/
export function TinypngKeyCompress(ctx: IPicGo, { imageUrl, key }: CommonParams & ITinypngOptions): Promise<ImageInfo> {
return Tinypng.init({ ctx, keys: key!.split(',') })
export function TinyPngKeyCompress(ctx: IPicGo, { imageUrl, key }: CommonParams & ITinyPngOptions): Promise<ImageInfo> {
return TinyPng.init({ ctx, keys: key!.split(',') })
.then(() => {
return Tinypng.upload(imageUrl);
return TinyPng.upload(imageUrl);
})
.then((buffer) => {
ctx.log.info('Tinypng upload successful');
ctx.log.info('TinyPng upload successful');
return getImageInfo(imageUrl, buffer);
});
}
2 changes: 1 addition & 1 deletion src/compress/tinypng/tinypng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class TinyPng {

// Upload image with specified options
private uploadImage(options: { key: string; originalUrl: string; url?: string; buffer?: Buffer }): Promise<Buffer> {
this.IPicGo.log.info('Using Tinypng key: ' + options.key);
this.IPicGo.log.info('Using TinyPng key:', options.key);
const bearer = Base64.stringify(Utf8.parse(`api:${options.key}`));
const headersObj = {
Host: 'api.tinify.com',
Expand Down
18 changes: 12 additions & 6 deletions src/compress/tinypngweb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@ import { TINYPNG_WEBUPLOAD_URL } from '../config';
import { getImageBuffer, getImageInfo } from '../utils';

/**
* Compress image using TinypngWeb service
* Compress image using TinyPngWeb service
* @param ctx The PicGo instance.
* @param imageUrl The URL of the image to be compressed.
* @returns A Promise that resolves to an ImageInfo object containing information about the compressed image.
*/
export function TinypngCompress(ctx: IPicGo, { imageUrl }: CommonParams): Promise<ImageInfo> {
export function TinyPngCompress(ctx: IPicGo, { imageUrl }: CommonParams): Promise<ImageInfo> {
/**
* This cannot use and return 404(not found) or 413(too large) error, so I break the code here.
* @author: 李宗霖 <email: [email protected]> or <github: https://github.com/supine0703>
*/
throw new Error('Please set the TinyPNG API Key. TinyPngWeb is cannot use, maybe you can try?');

return getImageBuffer(ctx, imageUrl).then((buffer) => {
ctx.log.info('TinypngWeb compression started');
ctx.log.info('TinyPngWeb compression started');
return ctx
.request({
url: TINYPNG_WEBUPLOAD_URL,
Expand All @@ -22,12 +28,12 @@ export function TinypngCompress(ctx: IPicGo, { imageUrl }: CommonParams): Promis
})
.then((resp) => {
if (resp.headers.location) {
ctx.log.info('TinypngWeb compression successful: ' + resp.headers.location);
ctx.log.info('Downloading Tinypng image');
ctx.log.info('TinyPngWeb compression successful:', resp.headers.location);
ctx.log.info('Downloading TinyPng image');
return getImageBuffer(ctx, resp.headers.location);
}
// If compression failed, throw an error
throw new Error('TinypngWeb upload failed');
throw new Error('TinyPngWeb upload failed');
})
.then((buffer) => {
return getImageInfo(imageUrl, buffer);
Expand Down
2 changes: 2 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ export enum CompressType {
imagemin = 'imagemin',
image2webp = 'image2webp',
}

export const PROJ_CONF = 'compress-next';
47 changes: 26 additions & 21 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,48 @@
import { IPicGo, IPlugin, IPluginConfig, IPicGoPlugin } from 'picgo';
import { TinypngCompress } from './compress/tinypngweb';
import { TinypngKeyCompress } from './compress/tinypng/index';
import { TinyPngCompress } from './compress/tinypngweb';
import { TinyPngKeyCompress } from './compress/tinypng/index';
import { ImageminCompress } from './compress/imagemin';
import { Image2WebPCompress } from './compress/image2webp';
import { CompressType } from './config';
import { getUrlInfo } from './utils';
import { IConfig } from './interface';
import { SkipCompress } from './compress/skip';
import { PROJ_CONF } from './config';

// Allowed image file extensions
const ALLOW_EXTNAME = ['.png', '.jpg', '.webp', '.jpeg'];

// Get configuration from ctx
const getConfig = (ctx: IPicGo): IConfig => {
return ctx.getConfig(PROJ_CONF) || ctx.getConfig(`picgo-plugin-${PROJ_CONF}`);
};

// Compression handler function
const handle = async (ctx: IPicGo): Promise<IPicGo> => {
// Get compression configuration
const config: IConfig = ctx.getConfig('compress-webp-lossless');
const config: IConfig = getConfig(ctx);
const compress = config?.compress;
const key = config?.key || config?.tinypngKey;

// Log compression setting
ctx.log.info('Compression type: ' + compress);
ctx.log.info('Compression type:', compress);

// Process images
const tasks = ctx.input.map((imageUrl) => {
// Log image URL
ctx.log.info('Image URL: ' + imageUrl);
ctx.log.info('Image URL:', imageUrl);
const info = getUrlInfo(imageUrl);
// Log image information
ctx.log.info('Image info: ' + JSON.stringify(info));
ctx.log.info('Image info:', JSON.stringify(info));
if (ALLOW_EXTNAME.includes(info.extname.toLowerCase())) {
switch (compress) {
case CompressType.tinypng:
return key ? TinypngKeyCompress(ctx, { imageUrl, key }) : TinypngCompress(ctx, { imageUrl });
case CompressType.imagemin:
return ImageminCompress(ctx, { imageUrl });
case CompressType.image2webp:
return Image2WebPCompress(ctx, { imageUrl });
case CompressType.tinypng:
default:
return key ? TinypngKeyCompress(ctx, { imageUrl, key }) : TinypngCompress(ctx, { imageUrl });
return key ? TinyPngKeyCompress(ctx, { imageUrl, key }) : TinyPngCompress(ctx, { imageUrl });
}
}
// Log unsupported format warning
Expand All @@ -48,15 +53,15 @@ const handle = async (ctx: IPicGo): Promise<IPicGo> => {
return Promise.all(tasks).then((output) => {
// Log compressed image information
ctx.log.info(
'Compressed image info: ' +
JSON.stringify(
output.map((item) => ({
fileName: item.fileName,
extname: item.extname,
height: item.height,
width: item.width,
})),
),
'Compressed image info:',
JSON.stringify(
output.map((item) => ({
fileName: item.fileName,
extname: item.extname,
height: item.height,
width: item.width,
})),
),
);

// Set output images
Expand All @@ -68,13 +73,13 @@ const handle = async (ctx: IPicGo): Promise<IPicGo> => {
// Export plugin function
const CompressTransformers: IPicGoPlugin = (ctx: IPicGo) => {
return {
transformer: 'compress-webp-lossless',
transformer: 'compress-next',
register(ctx: IPicGo) {
// Register compression transformer
ctx.helper.transformer.register('compress-webp-lossless', { handle });
ctx.helper.transformer.register('compress-next', { handle });
},
config(ctx: IPicGo): IPluginConfig[] {
let config: IConfig = ctx.getConfig('compress-webp-lossless');
let config: IConfig = getConfig(ctx);

return [
{
Expand Down
4 changes: 2 additions & 2 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { CompressType } from '../src/config';
import CompressTransformers from '../src/index';

jest.mock('../src/compress/tinypngweb', () => ({
TinypngCompress: jest.fn().mockReturnValue({
TinyPngCompress: jest.fn().mockReturnValue({
fileName: 'compressed.png',
extname: '.png',
height: 100,
Expand All @@ -12,7 +12,7 @@ jest.mock('../src/compress/tinypngweb', () => ({
}));

jest.mock('../src/compress/tinypng/index', () => ({
TinypngKeyCompress: jest.fn().mockReturnValue({
TinyPngKeyCompress: jest.fn().mockReturnValue({
fileName: 'compressed.jpg',
extname: '.jpg',
height: 150,
Expand Down

0 comments on commit 0d7c562

Please sign in to comment.