1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | import https from "https";
|
12 |
|
13 | import debugFactory from "debug";
|
14 | const log = debugFactory("tgwf:hosting-node");
|
15 |
|
16 | import hostingJSON from "./hosting-json.node.js";
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | async function getBody(url) {
|
26 | return new Promise(function (resolve, reject) {
|
27 |
|
28 | const req = https.get(url, function (res) {
|
29 | if (res.statusCode < 200 || res.statusCode >= 300) {
|
30 | log(
|
31 | "Could not get info from the Green Web Foundation API, %s for %s",
|
32 | res.statusCode,
|
33 | url
|
34 | );
|
35 | return reject(new Error(`Status Code: ${res.statusCode}`));
|
36 | }
|
37 | const data = [];
|
38 |
|
39 | res.on("data", (chunk) => {
|
40 | data.push(chunk);
|
41 | });
|
42 |
|
43 | res.on("end", () => resolve(Buffer.concat(data).toString()));
|
44 | });
|
45 | req.end();
|
46 | });
|
47 | }
|
48 |
|
49 | function check(domain, db) {
|
50 | if (db) {
|
51 | return hostingJSON.check(domain, db);
|
52 | }
|
53 |
|
54 |
|
55 | if (typeof domain === "string") {
|
56 | return checkAgainstAPI(domain);
|
57 | } else {
|
58 | return checkDomainsAgainstAPI(domain);
|
59 | }
|
60 | }
|
61 |
|
62 | async function checkAgainstAPI(domain) {
|
63 | const res = JSON.parse(
|
64 | await getBody(`https://api.thegreenwebfoundation.org/greencheck/${domain}`)
|
65 | );
|
66 | return res.green;
|
67 | }
|
68 |
|
69 | async function checkDomainsAgainstAPI(domains) {
|
70 | try {
|
71 | const allGreenCheckResults = JSON.parse(
|
72 | await getBody(
|
73 | `https://api.thegreenwebfoundation.org/v2/greencheckmulti/${JSON.stringify(
|
74 | domains
|
75 | )}`
|
76 | )
|
77 | );
|
78 | return hostingJSON.greenDomainsFromResults(allGreenCheckResults);
|
79 | } catch (e) {
|
80 | return [];
|
81 | }
|
82 | }
|
83 |
|
84 | async function checkPage(pageXray, db) {
|
85 | const domains = Object.keys(pageXray.domains);
|
86 | return check(domains, db);
|
87 | }
|
88 |
|
89 | export default {
|
90 | check,
|
91 | checkPage,
|
92 | greendomains: hostingJSON.greenDomainsFromResults,
|
93 | loadJSON: hostingJSON.loadJSON,
|
94 | };
|