summaryrefslogtreecommitdiff
path: root/misc/userscripts/readability-js
blob: efd086ce0b9cafc0b26a3fea1240270062e4ef1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env node
// 
// # Description
// 
// Summarize the current page in a new tab, by processing it with the standalone readability
// library used for Firefox Reader View.
// 
// # Prerequisites
// 
//   - NODE_PATH might be required to point to your global node libraries:
//     export NODE_PATH=$NODE_PATH:$(npm root -g)
//   - Mozilla's readability library (npm install -g https://github.com/mozilla/readability.git)
//     NOTE: You might have to *login* as root for a system-wide installation to work (e.g. sudo -s)
//   - jsdom (npm install -g jsdom)
//   - qutejs (npm install -g qutejs)
// 
// # Usage
// 
// :spawn --userscript readability-js
// 
// One may wish to define an easy to type command alias in Qutebrowser's configuration file:
// c.aliases = {"readability" : "spawn --userscript readability-js", ...}

const Readability = require('readability');
const qute = require('qutejs');
const JSDOM = require('jsdom').JSDOM;
const fs = require('fs');
const path = require('path');
const util = require('util');

const HEADER = `
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, text/html, charset=UTF-8" http-equiv="Content-Type">
    </meta>
    <title>%s</title>
    <style type="text/css">
        body {
            margin: 30px auto;
            max-width: 650px;
            line-height: 1.4;
            padding: 0 10px;
        }
        h1, h2, h3 {
            line-height: 1.2;
        }
    </style>
</head>`;
const scriptsDir = path.join(process.env.QUTE_DATA_DIR, 'userscripts');
const tmpFile = path.join(scriptsDir, '/readability.html');
const domOpts = {url: process.env.QUTE_URL, contentType: "text/html; charset=utf-8"}

if (!fs.existsSync(scriptsDir)){
    fs.mkdirSync(scriptsDir);
}

JSDOM.fromFile(process.env.QUTE_HTML, domOpts).then(dom => {
    let reader = new Readability(dom.window.document);
    let article = reader.parse();
    let content = util.format(HEADER, article.title) + article.content;

    fs.writeFile(tmpFile, content, (err) => {
        if (err) {
            qute.messageError([`"${err}"`])
            return 1;
        }
        // Success
        qute.open(['-t', tmpFile]);
    })
});