summaryrefslogtreecommitdiff
path: root/modules/proxy/proxy.js
blob: ccec53a313ea56b9d7870e1277a5ed55ff449a83 (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
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;
	try {
		iddict=objectFromList(
			fs.readFileSync(moddir+"/idfile.txt").toString()
				.split("\n").map(function(r){return r.split(" ");}));
	} catch (e) {
		console.error(e);
		return false;
	}

	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==null||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");
		}
	});
};