///
///
///
import { pdfConverter } from "../scrapbox-pdftoimage/mod.ts";
import { upload } from "../deno-gyazo/mod.ts";
import { upload as uploadFile } from "../scrapbox-file-uploader/mod.ts";
import { pool, sort, Result } from "../async-lib/mod.ts";
import { getGyazoToken } from "../scrapbox-userscript-std/rest.ts";
export interface Props {
title?: string;
refererURL?: string;
printResolution?: number;
};
export async function* uploadPDF(props: Props): AsyncGenerator, void, unknown> {
// 読み込み
const file = await uploadFile({ accept: "application/pdf, *.pdf"});
if (!file) throw new Error("no file specified");
// access token取得
const result = await getGyazoToken();
if (!result.ok) throw new Error(JSON.stringify(result.value));
const accessToken = result.value;
if (!accessToken) throw new Error("Could not get the access token");
// 画像に変換する
const { convert, count } = await pdfConverter(new Uint8Array(await file.arrayBuffer()));
let counter = 0;
const reader = pool(
5,
Array(count).keys(),
async (index: number): Promise => {
const image = await convert(index + 1, {
mimeType: "image/jpeg",
printResolution: props?.printResolution ?? 300,
quality: 0.95,
});
// 順番を保証する
if (counter < index) {
await new Promise((resolve) => {
const timer = setInterval(
() => {
if (counter < index) return;
clearInterval(timer);
resolve();
},
1000,
);
});
}
const result = await upload(image, {
created: new Date(),
accessToken,
description: `${file.name} ${index + 1}`,
...props,
});
counter++;
if (!result.ok) throw new Error(JSON.stringify(result.value));
return { index, count, ...result.value};
},
);
yield* sort([...reader]);
};