summaryrefslogtreecommitdiff
path: root/modules/quotesgrab/quotesgrab.js
blob: c540d3a848ee87b3a17161876f3476cf8c9294cc (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
72
73
74
75
var cmn=require("../$common.js"),
    https=require("https");

function parsequoteshtml(html){
	var idx=html.indexOf("row-header-wrapper"); if(idx==-1)return []; idx+=18;
	var endidx=html.indexOf("<tbody>",idx);
	var idx2;
	var list=[],obj;
	var keylist=["timestamp","name","quote"],i;
	while(true){
		idx=html.indexOf("row-header-wrapper",idx); if(idx==-1)break; idx+=18;
		if(idx>endidx)break;
		obj={};
		for(i=0;i<keylist.length;i++){
			idx=html.indexOf("<td",idx); if(idx==-1)break; idx+=3;
			idx=html.indexOf(">",idx); if(idx==-1)break; idx+=1;
			idx2=html.indexOf("</td>",idx); if(idx2==-1)break;
			obj[keylist[i]]=
				html.slice(idx,idx2)
				    .replace(/<\/?div[^>]*>/g,"")
				    .replace(/<br>/g,"\n")
				    .replace(/&gt;/g,">")
				    .replace(/&lt;/g,"<")
				    .replace(/&quot;/g,'"')
				    .replace(/&amp;/g,"&")
				    .replace(/&#x([0-9a-f][0-9a-f]);/gi,function(match,p1){
				    	return String.fromCharCode(parseInt(p1,16));
				    })
				    .replace(/&#([0-9]{1,3});/g,function(match,p1){
				    	return String.fromCharCode(parseInt(p1,10));
				    });
			idx=idx2+5;
		}
		if(obj.name=="x"||obj.name=="X")continue;
		obj.timestamp=new Date(obj.timestamp);
		list.push(obj);
	}
	return list;
}

function getquoteslist(cb){
	https.get("https://docs.google.com/spreadsheets/d/1ywrThdscubPOC-gHh_qnFGfuPrtYxTap6UsJBDnt88c/htmlview",function(res){
		var body="";
		res.on("data",function(data){
			body+=data.toString();
		});
		res.on("end",function(){
			cb(parsequoteshtml(body));
		});
		res.on("error",function(err){
			console.log("Error in quotes res:",err);
			cb("");
		});
	}).on("error",function(err){
		console.log("Error in quotes https:",err);
		cb("");
	});
}

var cache=null,cachedate=null;

module.exports=function(app,io,moddir){
	app.get("/quotes",function(req,res){
		res.set("Content-Type", "text/json");
		if(cache!=null&&new Date()-cachedate<60*1000){
			res.end(cache);
		} else {
			getquoteslist(function(obj){
				cache=JSON.stringify(obj);
				cachedate=new Date();
				res.end(cache);
			});
		}
	});
};