Skip to content

Commit

Permalink
feat: 变更png为压缩后的jpg
Browse files Browse the repository at this point in the history
  • Loading branch information
lisonge committed Oct 13, 2023
1 parent f23ac7b commit 52524aa
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 143 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@vueuse/components": "^10.3.0",
"@vueuse/core": "^10.3.0",
"browser-fs-access": "^0.34.1",
"compressorjs": "1.2.1",
"dayjs": "^1.11.9",
"file-saver": "^2.0.5",
"fs-extra": "^11.1.1",
Expand Down
19 changes: 19 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 42 additions & 7 deletions src/components/ActionCard.vue
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
<script setup lang="tsx">
import { showTextDLg } from '@/utils/dialog';
import { message } from '@/utils/discrete';
import {
exportSnapshotAsPng,
exportSnapshotAsPngUrl,
exportSnapshotAsZip,
exportSnapshotAsZipUrl,
} from '@/utils/export';
import { delay } from '@/utils/others';
import { snapshotStorage } from '@/utils/storage';
import {
githubPngStorage,
snapshotStorage,
githubZipStorage,
} from '@/utils/storage';
import { useTask } from '@/utils/task';
import { Snapshot } from '@/utils/types';
import { githubUrlToSelfUrl } from '@/utils/url';
import { githubUrlToSelfUrl, githubZipUrlReg } from '@/utils/url';
import { NButton, NPopover, NSpace, NIcon } from 'naive-ui';
import { computed } from 'vue';
import { useRouter } from 'vue-router';
Expand Down Expand Up @@ -74,7 +79,17 @@ const deleteSnapshot = async () => {
await delay(500);
props.onDelete();
};
HTMLAnchorElement;
const copy = async (content: string) => {
return navigator.clipboard
.writeText(content)
.then(() => {
message.success(`复制成功`);
})
.catch(() => {
message.success(`复制失败`);
});
};
</script>
<template>
<NSpace>
Expand Down Expand Up @@ -126,7 +141,7 @@ HTMLAnchorElement;
</template>
<NSpace vertical>
<NButton @click="exportPng.invoke" :loading="exportPng.loading">
下载-png
下载-jpg
</NButton>
<NButton @click="exportZip.invoke" :loading="exportZip.loading">
下载-zip
Expand Down Expand Up @@ -154,10 +169,30 @@ HTMLAnchorElement;
</NButton>
</template>
<NSpace vertical>
<NButton @click="exportPngUrl.invoke" :loading="exportPngUrl.loading">
生成链接-png
<NButton
v-if="githubPngStorage[snapshot.id]"
@click="copy(githubPngStorage[snapshot.id])"
>
复制链接-jpg
</NButton>
<NButton
v-else
@click="exportPngUrl.invoke"
:loading="exportPngUrl.loading"
>
生成链接-jpg
</NButton>
<NButton
v-if="githubZipStorage[snapshot.id]"
@click="copy(githubUrlToSelfUrl(githubZipStorage[snapshot.id]))"
>
复制链接-zip
</NButton>
<NButton @click="exportZipUrl.invoke" :loading="exportZipUrl.loading">
<NButton
v-else
@click="exportZipUrl.invoke"
:loading="exportZipUrl.loading"
>
生成链接-zip
</NButton>
</NSpace>
Expand Down
1 change: 1 addition & 0 deletions src/utils/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const showTextDLg = ({ title = `批量分享链接`, content = '' }) => {
}}
inputProps={{
style: `white-space: nowrap;`,
class:`gkd_code`
}}
value={content}
/>
Expand Down
32 changes: 28 additions & 4 deletions src/utils/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import {
screenshotStorage,
urlStorage,
} from './storage';
import Compressor from 'compressorjs';
import type { Snapshot } from './types';
import { message } from './discrete';

export const snapshotAsZip = async (snapshot: Snapshot) => {
const zip = new JSZip();
Expand All @@ -30,20 +32,38 @@ export const exportSnapshotAsZip = async (snapshot: Snapshot) => {

export const snapshotAsPng = async (snapshot: Snapshot) => {
const imgBf = (await screenshotStorage.getItem(snapshot.id))!;
const content = new Blob([imgBf, JSON.stringify(snapshot)]);
const jpgBlob = await new Promise<Blob>((res, rej) => {
new Compressor(new Blob([imgBf], { type: 'image/png' }), {
quality: 0.75,
convertSize: 200_000,
success(file) {
res(file);
},
error(error) {
rej(error);
},
});
});
// console.log([
// snapshot.id,
// (imgBf.byteLength / 1024).toFixed(3) + 'KB',
// (jpgBlob.size / 1024).toFixed(3) + 'KB',
// (1 - jpgBlob.size / imgBf.byteLength) * 100 + '%',
// ]);
const content = new Blob([jpgBlob]);
return content;
};

export const exportSnapshotAsPng = async (snapshot: Snapshot) => {
const fileName = `snapshot-${snapshot.id}.png`;
const fileName = `snapshot-${snapshot.id}.jpg`;
saveAs(await snapshotAsPng(snapshot), fileName);
};

export const batchPngDownloadZip = async (snapshots: Snapshot[]) => {
const zip = new JSZip();
for (const snapshot of snapshots) {
await delay();
zip.file(snapshot.id + `.png`, snapshotAsPng(snapshot));
zip.file(snapshot.id + `.jpg`, snapshotAsPng(snapshot));
}
const batchZipFile = await zip.generateAsync({
type: 'blob',
Expand All @@ -70,8 +90,10 @@ export const exportSnapshotAsPngUrl = async (snapshot: Snapshot) => {
githubPngStorage[snapshot.id] ??
uploadPoliciesAssets(
await snapshotAsPng(snapshot).then((r) => r.arrayBuffer()),
'file.jpg',
'image/jpeg',
).then((r) => {
urlStorage[r.href] = snapshot.id;
// urlStorage[r.href] = snapshot.id;
githubPngStorage[snapshot.id] = r.href;
return r.href;
})
Expand All @@ -83,6 +105,8 @@ export const exportSnapshotAsZipUrl = async (snapshot: Snapshot) => {
githubZipStorage[snapshot.id] ??
uploadPoliciesAssets(
await snapshotAsZip(snapshot).then((r) => r.arrayBuffer()),
'file.zip',
'application/x-zip-compressed',
).then((r) => {
githubZipStorage[snapshot.id] = r.href;
urlStorage[r.href] = snapshot.id;
Expand Down
39 changes: 8 additions & 31 deletions src/utils/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,40 +57,17 @@ type UploadPoliciesAssetsRsonpse = {

export const uploadPoliciesAssets = async (
bf: ArrayBuffer,
name: string,
content_type: string,
): Promise<GithubPoliciesAsset> => {
// const [name, content_type] = (() => {
// if (isPngBf(bf)) {
// return [`file.png`, `image/png`];
// } else if (isZipBf(bf)) {
// return [`file.zip`, `application/x-zip-compressed`];
// }
// throw new Error(`invalid buffer, it must be png or zip`);
// })();
// const file = new File([bf], name, { type: content_type });
// const resp = await fetch(
// 'https://github-upload-assets.lisonge.workers.dev/',
// {
// method: 'POST',
// body: obj2form({ file }),
// },
// );
// const xRpcOk = resp.headers.get('X_RPC_OK');
// if (xRpcOk === 'true') {
// return resp.json();
// }
return uploadPoliciesAssetsByExtension(bf);
return uploadPoliciesAssetsByExtension(bf, name, content_type);
};

export const uploadPoliciesAssetsByExtension = async (bf: ArrayBuffer) => {
const [name, content_type] = (() => {
if (isPngBf(bf)) {
return [`file.png`, `image/png`];
} else if (isZipBf(bf)) {
return [`file.zip`, `application/x-zip-compressed`];
}
throw new Error(`invalid buffer, it must be png or zip`);
})();

export const uploadPoliciesAssetsByExtension = async (
bf: ArrayBuffer,
name: string,
content_type: string,
) => {
const authenticity_token = await getCsrfToken();
if (!authenticity_token) {
store.githubErrorDlgVisible = true;
Expand Down
93 changes: 8 additions & 85 deletions src/utils/import.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,11 @@
import { fileOpen } from 'browser-fs-access';
import { message } from './discrete';
import JSZip, { loadAsync } from 'jszip';
import type { Snapshot } from './types';
import {
urlStorage,
snapshotStorage,
screenshotStorage,
setSnapshot,
} from './storage';
import { enhanceFetch } from './fetch';
import { isPngBf, isZipBf } from './file_type';
import pLimit from 'p-limit';

function splitArrayBuffer(
arrayBuffer: ArrayBuffer,
delimiter: ArrayBuffer,
limit?: number,
): ArrayBuffer[] {
const view = new Uint8Array(arrayBuffer);
const delimiterView = new Uint8Array(delimiter);
const delimiterLength = delimiterView.length;

const parts: ArrayBuffer[] = [];
let startIndex = 0;
let delimiterIndex = -1;
let count = 0;

for (let i = 0; i < view.length; i++) {
if (view[i] === delimiterView[0]) {
delimiterIndex = 0;
for (let j = 1; j < delimiterLength; j++) {
if (view[i + j] !== delimiterView[j]) {
delimiterIndex = -1;
break;
}
}
if (delimiterIndex === 0) {
const part = arrayBuffer.slice(startIndex, i);
parts.push(part);
startIndex = i + delimiterLength;
i += delimiterLength - 1;
count++;

if (limit && count === Math.abs(limit)) {
break;
}
}
}
}

if (startIndex < view.length) {
const part = arrayBuffer.slice(startIndex);
parts.push(part);
}

return parts;
}

const pngEndBf = new Uint8Array([
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]).buffer;
const decoder = new TextDecoder();
import { message } from './discrete';
import { enhanceFetch } from './fetch';
import { isZipBf } from './file_type';
import { setSnapshot, snapshotStorage, urlStorage } from './storage';
import type { Snapshot } from './types';

const parseZip = async (zip: JSZip) => {
const snapshotFile = zip.filter((s) => s.endsWith(`.json`))[0];
Expand All @@ -77,11 +22,10 @@ const parseZip = async (zip: JSZip) => {
export const importFromLocal = async () => {
const files = await fileOpen({
multiple: true,
mimeTypes: [`image/png`, `application/zip`],
mimeTypes: [`application/zip`],
});
const zipfiles = files.filter((f) => f.name.endsWith(`.zip`));
const pngfiles = files.filter((f) => f.name.endsWith(`.png`));
if (zipfiles.length == 0 && pngfiles.length == 0) {
if (zipfiles.length == 0) {
message.warning(`没有发现可导入文件`);
return;
}
Expand All @@ -107,22 +51,6 @@ export const importFromLocal = async () => {
}),
);
}
if (pngfiles.length > 0) {
await Promise.any(
pngfiles.map(async (file) => {
const bf = await file.arrayBuffer();
const [tempPngBf, jsonBf] = splitArrayBuffer(bf, pngEndBf, 2);
if (!jsonBf) return;
const screenshotBf = await new Blob([
tempPngBf,
pngEndBf,
]).arrayBuffer();
const snapshot = JSON.parse(decoder.decode(jsonBf)) as Snapshot;
await setSnapshot(snapshot, screenshotBf);
importNum++;
}),
);
}
if (importNum > 0) {
message.success(`导入${importNum}条记录`);
} else {
Expand Down Expand Up @@ -161,12 +89,7 @@ export const importFromNetwork = async (urls: string[] | string = []) => {
const bf = await resp.arrayBuffer();
let snapshot: Snapshot;
let screenshotBf: ArrayBuffer;
if (isPngBf(bf)) {
const [tempPngBf, jsonBf] = splitArrayBuffer(bf, pngEndBf, 2);
if (!jsonBf) return;
screenshotBf = await new Blob([tempPngBf, pngEndBf]).arrayBuffer();
snapshot = JSON.parse(decoder.decode(jsonBf)) as Snapshot;
} else if (isZipBf(bf)) {
if (isZipBf(bf)) {
const zip = await loadAsync(bf);
const [snapshotFile] = zip.filter((p) => p.endsWith(`.json`));
const [screenshotFile] = zip.filter((p) => p.endsWith(`.png`));
Expand Down
Loading

0 comments on commit 52524aa

Please sign in to comment.