summaryrefslogtreecommitdiff
path: root/modules/proxy/proxy.js
blob: e18ab6aa8373ec3106d159493dc7254dd85bf851 (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
var cmn=require("../$common.js"),
    fs=require("fs"),
    http=require("http"),
    https=require("https"),
    URL=require("url");


function fetch(method,url,cb){
	var module;
	if(url.slice(0,7)=="http://")module=http;
	else if(url.slice(0,8)=="https://")module=https;
	var obj=URL.parse(url);
	obj.method=method;
	module.request(obj,function(res){
		var body="";
		res.on("data",function(data){body+=data;});
		res.on("end",function(){
			cb({status: res.statusCode, headers: res.headers},body);
		});
	}).on("error",function(){
		cb(null,null);
	}).end();
}

function objectFromList(l){
	var obj={};
	for(var i=0;i<l.length;i++)obj[l[i][0]]=l[i][1];
	return obj;
}

module.exports=function(app,io,moddir){
	var iddict=objectFromList(
			fs.readFileSync(moddir+"/idfile.txt").toString()
				.split("\n").map(function(r){return r.split(" ");}));

	app.all("/proxy/:id/*",function(req,res){
		var id=req.params.id;
		var path="/"+req.path.split("/").slice(3).join("/");
		if(iddict[id]){
			fetch(req.method,iddict[id]+path,function(obj,body){
				if(obj.status==null){
					res.status(500).send("An error occurred...\n");
					return;
				}
				res.status(obj.status);
				if(obj.headers["content-type"]){
					res.set("Content-Type",obj.headers["content-type"]);
				}
				res.send(body);
			});
		} else {
			res.status(404).send(
				"That ID is incorrect.\n"+
				"Please contact the person you got this link from.\n");
		}
	});
};