dsh-plugin-zotero 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -276,7 +276,8 @@ async function handleFile(req, res, params) {
276
276
  return;
277
277
  }
278
278
  const file = await zotero.getAttachmentFile(key);
279
- const contentType = file.contentType.split(';')[0].trim().toLowerCase();
279
+ // `getAttachmentFile` 已经把 MIME 规范化过了(小写、无参数、缺失时按后缀兜底)。
280
+ const contentType = file.contentType;
280
281
  if (!SERVABLE_TYPES.has(contentType)) {
281
282
  fail(res, 415, 'bad_request', `暂不支持预览 ${file.contentType || '该附件类型'}`);
282
283
  return;
@@ -309,9 +310,37 @@ async function handleFile(req, res, params) {
309
310
  res.writeHead(206, headers);
310
311
  stream = createReadStream(file.path, { start: range.start, end: range.end });
311
312
  }
313
+ // 客户端中途关掉(关面板、pdf.js 放弃这次请求)就把文件句柄一起放掉,
314
+ // 否则大 PDF 的读流会一直挂到进程结束。
315
+ res.on('close', () => stream.destroy());
312
316
  stream.on('error', () => res.destroy());
313
317
  stream.pipe(res);
314
318
  }
319
+ /**
320
+ * 附件可读性探测:只回答「这个附件的文件在不在、是什么、能不能预览」。
321
+ *
322
+ * 存在的唯一理由是**把 `/api/file` 的失败原因说清楚**。那条路径的响应体是
323
+ * 二进制流,失败时 pdf.js 只能看到状态码,用户拿到的是
324
+ * 「Unexpected server response (404) while retrieving PDF "dsh-app://…"」;
325
+ * 前端在此之后调一次本端点,就能把「附件文件不存在:/path/xxx.pdf」
326
+ * 这种能自己动手修的信息显示出来。
327
+ */
328
+ async function handleAttachmentInfo(res, params) {
329
+ const key = params.get('key') ?? '';
330
+ if (!KEY_PATTERN.test(key)) {
331
+ fail(res, 400, 'bad_request', '附件 key 格式不合法');
332
+ return;
333
+ }
334
+ const file = await zotero.getAttachmentFile(key);
335
+ const data = {
336
+ key: file.key,
337
+ filename: file.filename,
338
+ contentType: file.contentType,
339
+ size: file.size,
340
+ servable: SERVABLE_TYPES.has(file.contentType),
341
+ };
342
+ ok(res, data);
343
+ }
315
344
  /** 用系统默认处理器打开 `zotero://` URL;参数数组传递,不经过 shell。 */
316
345
  function openExternal(url) {
317
346
  const command = process.platform === 'darwin'
@@ -530,6 +559,7 @@ const ROUTE_METHODS = new Map([
530
559
  ['item', 'GET'],
531
560
  ['collection-bib', 'GET'],
532
561
  ['file', 'GET'],
562
+ ['attachment-info', 'GET'],
533
563
  ['mcp-tools', 'GET'],
534
564
  ['auth-status', 'GET'],
535
565
  ['read-position', 'GET'],
@@ -597,6 +627,9 @@ export function createHandler(deps = {}) {
597
627
  case 'file':
598
628
  await handleFile(req, res, url.searchParams);
599
629
  return;
630
+ case 'attachment-info':
631
+ await handleAttachmentInfo(res, url.searchParams);
632
+ return;
600
633
  case 'open-in-zotero':
601
634
  await handleOpenInZotero(req, res);
602
635
  return;
@@ -210,11 +210,19 @@ export declare function getItemChildren(key: string): Promise<RawItem[]>;
210
210
  export declare function getItemAnnotations(key: string): Promise<RawAnnotation[]>;
211
211
  /** 附件全文;仅附件条目可用。 */
212
212
  export declare function getItemFulltext(attachmentKey: string): Promise<ZoteroFulltext | null>;
213
+ /**
214
+ * 附件内容类型的规范形态:小写、去掉 `;` 之后的参数,缺失时按后缀兜底。
215
+ *
216
+ * 不规范化的后果是同一份 PDF 在有的库里能预览、有的库里被 415 挡掉——判断
217
+ * 「能不能直接流出去」和「用哪个渲染器」都依赖这一个值。
218
+ */
219
+ export declare function normalizeContentType(contentType: string, filename: string): string;
213
220
  /**
214
221
  * 解析附件在磁盘上的真实路径。
215
222
  *
216
223
  * 路径只来自 Zotero 条目 JSON 的 `links.enclosure.href`(`file://` URL),
217
- * 客户端传来的任何路径都不接受。`lstat` 拒绝目录与非普通文件;
224
+ * 客户端传来的任何路径都不接受。用 `stat` 而不是 `lstat`:把大文件放外置盘、
225
+ * storage 里留软链是很常见的用法,`lstat` 会把这种附件当成「不是普通文件」拒掉。
218
226
  * 链接附件(`linkMode: linked_file`)同样走这里,不限制必须在 storage 下。
219
227
  */
220
228
  export declare function getAttachmentFile(key: string): Promise<ZoteroAttachmentFile>;
@@ -12,7 +12,7 @@
12
12
  * 要拿整目录引用必须走 `/items?itemKey=a,b&format=bib`(每批 ≤ 50)。
13
13
  * - `?include=bib` 会让响应**丢掉 `data`**,因此条目详情与 bib 必须分两次请求。
14
14
  */
15
- import { lstat } from 'node:fs/promises';
15
+ import { stat } from 'node:fs/promises';
16
16
  import { connect } from 'node:net';
17
17
  import { fileURLToPath } from 'node:url';
18
18
  import { anchorAnnotations } from './annotations.js';
@@ -829,11 +829,48 @@ export async function getItemFulltext(attachmentKey) {
829
829
  fallback: false,
830
830
  };
831
831
  }
832
+ /** 按后缀兜底的 MIME(Zotero 记录里 `contentType` 偶尔为空)。 */
833
+ const MIME_BY_EXT = {
834
+ pdf: 'application/pdf',
835
+ html: 'text/html',
836
+ htm: 'text/html',
837
+ xhtml: 'text/html',
838
+ epub: 'application/epub+zip',
839
+ txt: 'text/plain',
840
+ };
841
+ /**
842
+ * 附件内容类型的规范形态:小写、去掉 `;` 之后的参数,缺失时按后缀兜底。
843
+ *
844
+ * 不规范化的后果是同一份 PDF 在有的库里能预览、有的库里被 415 挡掉——判断
845
+ * 「能不能直接流出去」和「用哪个渲染器」都依赖这一个值。
846
+ */
847
+ export function normalizeContentType(contentType, filename) {
848
+ const base = contentType.split(';')[0].trim().toLowerCase();
849
+ if (base !== '')
850
+ return base;
851
+ const ext = /\.([a-z0-9]+)$/iu.exec(filename)?.[1]?.toLowerCase() ?? '';
852
+ return MIME_BY_EXT[ext] ?? '';
853
+ }
854
+ /** 读不到文件时的**人话**原因:用户据此能自己判断该去哪修。 */
855
+ function unreadableReason(error, path) {
856
+ const code = typeof error === 'object' && error !== null && 'code' in error
857
+ ? String(error.code ?? '')
858
+ : '';
859
+ if (code === 'ENOENT' || code === 'ENOTDIR')
860
+ return `附件文件不存在:${path}`;
861
+ if (code === 'EACCES' || code === 'EPERM')
862
+ return `没有权限读取附件文件:${path}`;
863
+ if (code === 'ELOOP')
864
+ return `附件文件是失效的符号链接:${path}`;
865
+ const detail = error instanceof Error ? error.message : String(error);
866
+ return `无法读取附件文件:${path}(${code === '' ? detail : code})`;
867
+ }
832
868
  /**
833
869
  * 解析附件在磁盘上的真实路径。
834
870
  *
835
871
  * 路径只来自 Zotero 条目 JSON 的 `links.enclosure.href`(`file://` URL),
836
- * 客户端传来的任何路径都不接受。`lstat` 拒绝目录与非普通文件;
872
+ * 客户端传来的任何路径都不接受。用 `stat` 而不是 `lstat`:把大文件放外置盘、
873
+ * storage 里留软链是很常见的用法,`lstat` 会把这种附件当成「不是普通文件」拒掉。
837
874
  * 链接附件(`linkMode: linked_file`)同样走这里,不限制必须在 storage 下。
838
875
  */
839
876
  export async function getAttachmentFile(key) {
@@ -844,31 +881,37 @@ export async function getAttachmentFile(key) {
844
881
  }
845
882
  const href = raw.links?.enclosure?.href ?? '';
846
883
  if (href === '') {
847
- throw new ZoteroError('zotero_not_found', `附件 ${key} 没有可读取的本地文件`);
884
+ // 没有 enclosure:附件记录在,但 Zotero 那边没有对应的本地文件(未下载、
885
+ // 只同步了元数据、或网页链接型附件)。这是「打不开 PDF」最常见的一种。
886
+ throw new ZoteroError('zotero_not_found', `附件 ${key} 没有本地文件(Zotero 里可能尚未下载)`);
848
887
  }
849
888
  let path;
850
889
  try {
851
890
  path = fileURLToPath(href);
852
891
  }
853
892
  catch {
854
- throw new ZoteroError('zotero_not_found', `附件 ${key} 的文件地址无法解析`);
893
+ const scheme = /^([a-z][a-z0-9+.-]*):/iu.exec(href)?.[1] ?? '';
894
+ throw new ZoteroError('zotero_not_found', scheme === '' || scheme === 'file'
895
+ ? `附件 ${key} 的文件地址无法解析:${href}`
896
+ : `附件 ${key} 不是本地文件(${scheme}:)`);
855
897
  }
856
898
  let stats;
857
899
  try {
858
- stats = await lstat(path);
900
+ stats = await stat(path);
859
901
  }
860
- catch {
861
- throw new ZoteroError('zotero_not_found', `附件文件不存在:${path}`);
902
+ catch (error) {
903
+ throw new ZoteroError('zotero_not_found', unreadableReason(error, path));
862
904
  }
863
905
  if (!stats.isFile()) {
864
- throw new ZoteroError('zotero_not_found', `附件路径不是普通文件:${path}`);
906
+ throw new ZoteroError('zotero_not_found', `附件路径不是文件:${path}`);
865
907
  }
908
+ const filename = data.filename ?? attachmentTitle(raw);
866
909
  return {
867
910
  key,
868
911
  path,
869
912
  size: stats.size,
870
- contentType: data.contentType ?? '',
871
- filename: data.filename ?? attachmentTitle(raw),
913
+ contentType: normalizeContentType(data.contentType ?? '', filename),
914
+ filename,
872
915
  };
873
916
  }
874
917
  /**
@@ -54,6 +54,22 @@ export interface ZoteroAttachmentFile {
54
54
  contentType: string;
55
55
  filename: string;
56
56
  }
57
+ /**
58
+ * 附件可读性探测(`/api/attachment-info`)。
59
+ *
60
+ * 存在的意义是**解释失败**:`/api/file` 的 4xx 只会被 pdf.js 回显成一句
61
+ * 「Unexpected server response (404)」,真正的原因(文件不存在 / 无权限 /
62
+ * 没有本地文件)在这个端点里以普通 JSON 给出,前端据此显示人话。
63
+ */
64
+ export interface ZoteroAttachmentInfo {
65
+ key: string;
66
+ filename: string;
67
+ /** 规范化后的 MIME:小写、不含参数;无法判断时为空串。 */
68
+ contentType: string;
69
+ size: number;
70
+ /** 该类型能否由插件直接流式预览。 */
71
+ servable: boolean;
72
+ }
57
73
  /** 条目上的一条标签(`data.tags` 的元素,标注与笔记同构)。 */
58
74
  export interface ZoteroTagRef {
59
75
  tag: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-zotero",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "Map your Zotero library into DSH: let AI operate Zotero for you and help you read papers. Browse collections and tags in the sidebar, read PDFs with highlights in place, and cite excerpts, annotations, notes or whole items into the chat. The model works from the source text for reviews, comparisons and data extraction, and can also search and organize the library, import papers and attach translations back to items; first use needs the Zotero MCP plugin and the local API enabled.",
5
5
  "keywords": [
6
6
  "dsh",