69 lines
2.3 KiB
JavaScript
69 lines
2.3 KiB
JavaScript
/*
|
|
Copyright (C) 2025 QuantumNous
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Affero General Public License as
|
|
published by the Free Software Foundation, either version 3 of the
|
|
License, or (at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Affero General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Affero General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
For commercial licensing, please contact support@quantumnous.com
|
|
*/
|
|
export const ARTICLE_IMAGE_LIMIT = 2 * 1024 * 1024;
|
|
export const ARTICLE_IMAGE_TYPES = [
|
|
'image/jpeg',
|
|
'image/png',
|
|
'image/webp',
|
|
'image/gif',
|
|
];
|
|
|
|
export function articleImageSource(value) {
|
|
const source = String(value || '').trim();
|
|
if (source.startsWith('data:')) {
|
|
const match =
|
|
/^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]+={0,2})$/i.exec(
|
|
source,
|
|
);
|
|
if (!match || match[2].length % 4) return '';
|
|
const bytes =
|
|
(match[2].length * 3) / 4 - (match[2].match(/=+$/)?.[0].length || 0);
|
|
return bytes > 0 && bytes <= ARTICLE_IMAGE_LIMIT ? source : '';
|
|
}
|
|
try {
|
|
const url = new URL(source);
|
|
return ['http:', 'https:'].includes(url.protocol) &&
|
|
!url.username &&
|
|
!url.password
|
|
? url.href
|
|
: '';
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
export async function readArticleImage(file) {
|
|
if (!ARTICLE_IMAGE_TYPES.includes(file.type))
|
|
throw new Error('正文图片仅支持 JPG、PNG、WebP、GIF 格式');
|
|
if (!file.size || file.size > ARTICLE_IMAGE_LIMIT)
|
|
throw new Error('单张正文图片大小不能超过 2 MB,且不能为空');
|
|
try {
|
|
const bitmap = await createImageBitmap(file);
|
|
bitmap.close();
|
|
} catch {
|
|
throw new Error('无法读取图片,请选择有效的图片文件');
|
|
}
|
|
return new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => resolve(String(reader.result));
|
|
reader.onerror = () => reject(new Error('图片读取失败,请重新选择或粘贴'));
|
|
reader.readAsDataURL(file);
|
|
});
|
|
}
|