vscode-zoterolens/src/commands.ts

60 lines
1.6 KiB
TypeScript

import { exec } from "child_process";
import { IncomingMessage, request } from "http";
import Reference from "./zoteroCodeLensProvider";
async function showInZotero(reference: Reference) {
openUrl("zotero://select/items/@" + reference.citekey);
}
async function openZoteroPDF(reference: Reference) {
const req = request("http://127.0.0.1:23119/better-bibtex/json-rpc", {
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
req.on("response", (res: IncomingMessage) => {
if (res.statusCode != 200) {
console.error('Error with request. Is Zotero running and Better-BibTex installed?')
} else {
// console.log('test2', res.statusCode, res);
res.on('readable', () => {
const buffer: Buffer = res.read();
const s = buffer.toString();
const data = JSON.parse(s);
console.log('received from Zotero', data);
for (const result of data['result']) {
if (result['path'].toLowerCase().endsWith('.pdf')) {
// TODO add ?page=nr to open given page
openUrl(result['open']);
break; // only open a single attachement
}
}
});
}
});
req.end('{"jsonrpc": "2.0", "method": "item.attachments", "params": ["' + reference.citekey + '"]}', 'binary');
}
function openUrl(url: string) {
switch (process.platform) {
case 'darwin':
exec('open "' + url + '"');
break;
case 'linux':
exec('xdg-open "' + url + '"');
break;
default:
exec('"' + url + '"');
}
}
export { openZoteroPDF, showInZotero };