
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/
    
// post操作
/*-------------------------------------------------------------------------------------------*/	
	class post
	{
		static async start(req,res,fi=$Config.upload)
		{
			var type=req.headers['content-type-binary']?req.headers['content-type-binary']:req.headers['content-type'];
			if(req.method.toLowerCase()=='post' && type)
			{
				if(req.headers['content-length']<$Config.postSize)
				{
					if(type.includes('x-www-form-urlencoded'))
					{
						return  await post.load(req,'form');
					}
					else if(type.includes('json'))
					{
						return await post.load(req,'json');
					}
					else if(fi && type.includes('multipart'))
					{
						return await post.multi(req,res,fi);
					}
					else if(fi && type.includes('binary'))
					{
						return await post.binary(req,res,fi);
					}
					else
					{
						return await post.text(req,res);
					}
				}
				else
				{
					return $Sys.model('/fun/filter','echo')(false,'文件超出大小限制');
				}
			}
			else
			{
				return;
			}
		}

		static text(req,res)
		{
			return (new Promise((reslove)=>
			{
				req.post="";
				var da='';
				req.setEncoding('utf8');
				var _mtag=false;
				req.on('data',(d)=>
				{
					if(da.length>$Config.postSize)
					{
						_mtag=true;
						console.info("超出数据大小限制");
						reslove($Sys.model('/fun/filter','echo')(false,'超出数据大小限制'));
						return;
					}
					else
					{
						da += d;
					}
				});
	
				req.on('end',()=>
				{
					if(_mtag)
					{
						return;
					}
					else
					{
						req.post=da
						reslove();
						return;
					}
				});
			}))
		}

		static load(req,ty1)
		{
			return (new Promise((reslove)=>
			{
				req.post={};
				var _post='';
				var da='';
				req.setEncoding('utf8');
				var _mtag=false;
				req.on('data',(d)=>
				{
					if(da.length>$Config.postSize)
					{
						_mtag=true;
						console.info("超出数据大小限制");
						reslove($Sys.model('/fun/filter','echo')(false,'文件超出大小限制'));
						return;
					}
					else
					{
						da += d;
					}
				});
	
				req.on('end',()=>
				{
					if(_mtag)
					{
						return;
					}
					else
					{
						try
						{
							if(ty1=='form')
							{
								var querystring=require('querystring');
								_post=querystring.parse(da);
							}
							else if(ty1=='json')
							{
								_post=JSON.parse(da);
							}
						}
						catch(e)
						{
							_post=da;
						}
						req.post=_post?_post:{};
						reslove();
						return;
					}
				});
			}))
		}

		static multi(req,res,private_path)
		{
			return (new Promise((reslove)=>
			{
				req.post={};
				req.file={};
				var _file={};
				var _post={};
				var filepost;
				filepost=req.headers['content-type'];
				req.setEncoding('binary');
				filepost=filepost.match(/multipart\/form-data;\sboundary=(\S+)/);
				var a='';
				var sta=filepost[1];
				var _mtag=false;
	
				req.on('data',(d)=>
				{
					if(a.length>$Config.postSize)
					{
						_mtag=true;
						console.warn("超出数据大小限制");
						reslove($Sys.model('/fun/filter','echo')(false,'超出数据大小限制'));
						return;
					}
					else
					{
						a+=d;
					}
				});


				req.on('end',()=>
				{
					if(_mtag)
					{
						return;
					}
					var fs=require('fs');
					var preg=new RegExp(sta,'g');
					var postsp=a.split(preg);

					var key;
					var postfilename;
					var postfieldname;
					var postfield;
					var unlinkfile=[];
					
					try 
					{
						for(key in postsp)
						{
							var postfile={};
							if(key==0 && key==postsp.length)
							{
								continue;
							}
							else if(postfilename=postsp[key].match(/filename="(.{0,50})"/))
							{
								var path = require('path');
								postfile['name']=postfilename[1];
								if(postfile['name'])
								{
									postfile['type']=path.extname(postfilename[1]);
									postfile['size']=req.headers['content-length'];
									let _dirfilename=private_path+$Sys.uid()+postfile['type'];
									let _res
									if(req.headers['length'])
									{
										_res=fs.writeFileSync($Config.root+_dirfilename,postsp[key].split(/Content-Length:\s\S+\r\n\r\n/i)[1].split(/\r\n--/)[0],{ encoding: 'binary'})
									}
									else
									{
										_res=fs.writeFileSync($Config.root+_dirfilename,postsp[key].split(/Content-Type:\s\S+\r\n\r\n/i)[1].split(/\r\n--/)[0],{ encoding: 'binary'})
									}
									
									if(_res)
									{
										postfile['file']=false;
									}
									else
									{
										unlinkfile.push(_dirfilename);
										postfile['file']=_dirfilename;
									}
									var filestatand=postsp[key].match(/name="(\S{1,50})".?;/)[1];
									if(_file[filestatand])
									{
										_file[filestatand].push(postfile);
									}
									else
									{
										_file[filestatand]=[];
										_file[filestatand].push(postfile);
									}
								}
							}
							else if(postfield=postsp[key].match(/; name="(\S{1,50})"/))
							{
								if(postfieldname=postsp[key].split(/; name=\S+\r\n\r\n/i))
								{	 
									var bdata=Buffer.from(postfieldname[1].split(/\r\n--/)[0],'binary');
									_post[postfield[1]]=bdata.toString('utf8');
								}
							}
						}					
					} 
					catch (error) 
					{
						console.error('[上传失败]',error);
					}
		
					req.post=_post?_post:{};
					req.file=_file;
					a=null;
					postsp=null;
					key=null;
					postfilename=null;
					postfieldname=null;
					postfield=null;

					res.on('finish',function()
					{
						if(!$Config.postTemp)return
						unlinkfile.forEach(val => 
						{
							try 
							{
								fs.unlink($Config.root+val,()=>{});	
							} 
							catch (error) 
							{
								console.warn("post上传文件删除失败或者已经移动");
							}
						});
					})
					reslove();
				});				
			}))
		}

		static binary(req,res,private_path)
		{
			return (new Promise((reslove)=>
			{
				req.file='';
				var a='';
				var _mtag=false
				req.on('data',(d)=>
				{
					if(a.length>$Config.postSize)
					{
						_mtag=true;
						console.warn("超出数据大小限制");
						reslove($Sys.model('/fun/filter','echo')(false,'超出数据大小限制'));
						return;
					}
					else
					{
						a+=d;
					}
				});


				req.on('end',()=>
				{
					if(_mtag)
					{
						return;
					}
					var fs=require('fs');
					
					try 
					{
						let _dirfilename=private_path+$Sys.uid();
						let ur=$Config.root+_dirfilename+req.headers['name'];
						fs.writeFileSync(ur,a,{ encoding: 'binary'});		
						req.file=_dirfilename+req.headers['name'];	
					} 
					catch (error) 
					{
						console.error('[上传失败]',error);
					}

					res.on('finish',function()
					{
						if(!$Config.postTemp)return
						try 
						{
							fs.unlink($Config.root+val,()=>{});	
						} 
						catch (error) 
						{
							$Sys.warn("post上传文件删除失败或者已经移动");
						}
					})
					reslove();
				});				
			}))
		}
  }
/*-------------------------------------------------------------------------------------------*/    
module.exports=post;