]> git.lizzy.rs Git - google_images.git/blob - init.js
Style fixes
[google_images.git] / init.js
1 const fetch = require("node-fetch")
2 const cheerio = require("cheerio")
3 const jsonic = require("jsonic")
4
5 const makeImage = elem => {
6         return {
7                 url: elem[0],
8                 size: {
9                         width: elem[2],
10                         height: elem[1],
11                 }
12         }
13 }
14
15 module.exports.search = (query, userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0") => {
16         return fetch("https://www.google.com/search?tbm=isch&q=" + encodeURIComponent(query), {headers: {"User-Agent": userAgent}})
17                 .then(res => res.text())
18                 .then(data => cheerio.load(data, null, false))
19                 .then(content => content("script"))
20                 .then(scripts => scripts.toArray())
21                 .then(scripts => scripts.map(script => script.children[0]?.data))
22                 .then(scripts => scripts.filter(script => script?.search("http") >= 0))
23                 .then(scripts => scripts[4])
24                 .then(script => script.slice("AF_ini2tDataCallback(".length, script.length - ");".length))
25                 .then(jsonic)
26                 .then(data => data.data[31][0][12][2])
27                 .then(data => data.map(elem => elem[1]))
28                 .then(data => data.map(elem => new Object({
29                         preview: makeImage(elem[2]),
30                         image: makeImage(elem[3]),
31                         color: elem[6],
32                         link: elem[9][2003][2],
33                         title: elem[9][2003][3],
34                 })))
35 }
36
37 /*
38 In case google makes minor changes, here are some snippets used to reverse engineer the format:
39
40
41 Find which script to use (use the query astolfo+images for this)
42 ----------------------------------------------------------------
43
44         .then(scripts => scripts.filter(script => script.children[0]?.data?.search("http") >= 0))
45         .then(scripts => scripts.reduce((a, b, i) => b.children[0]?.data?.search("https://steamcdn-a.akamaihd.net/steamcommunity/public/images/items/622220/f4d2d4074167411a7e15b9a845cf18b434c02af3.jpg") >= 0 ? i : a), -1)
46
47 Reverse engineer data passed to AF_initDataCallback
48 ---------------------------------------------------
49
50 const findStrings = (obj, path = "") => {
51         let found = [];
52
53         for (k in obj) {
54                 let v = obj[k];
55                 let t = typeof v;
56                 let p = path + "." + k
57
58                 if (t == "object")
59                         found = found.concat(findStrings(v, p));
60                 else if (t == "string")
61                         found.push([v, p]);
62         }
63
64         return found;
65 };
66
67         .then(findStrings)
68 */