const{stanz:stanz}=require("stanz"),WebSocket=require("faye-websocket"),http=require("http"),jiami=require("./jiami"),NodeRSA=require("node-rsa"),jsonToStr=(e,t,s)=>{return jiami.aesEncrypt(JSON.stringify(e),t,s)},strToJson=(e,t,s)=>{return JSON.parse(jiami.aesDecrypt(e),t,s)};function StanzServer(e){let t,s=this.server=http.createServer(),n=this.pageWSMap=new Set,r=e=>{let{trend:t}=e;n.forEach(e=>{e.send({type:"update",trend:t})})};Object.defineProperties(this,{commonData:{set:e=>(t&&t.off("update",r),(t=stanz(e)).on("update",r),t),get:()=>t}}),s.on("upgrade",(e,s,r)=>{let o=this.canAccess(e),a=o instanceof Object;if(WebSocket.isWebSocket(e)&&o){let d=new WebSocket(e,s,r),l={key:"gt916wxhyfvc8f93",iv:"262te1454r9qyaac",ws:d,send(e){this.ws.send(jsonToStr(e),this.key,this.iv)}};var i=new NodeRSA({b:1024});i.setOptions({encryptionScheme:"pkcs1"});var c=i.exportKey("private"),p=i.exportKey("public");n.add(l),this.onmsg("startInit",{request:e,tarObj:l}),d.on("open",e=>{this.onmsg("open",{event:e,tarObj:l}),l.send({type:"beforeInit",p:p})}),d.on("message",e=>{let s=strToJson(e.data);switch(this.onmsg("message",{event:e,data:s,tarObj:l}),s.type){case"init":let n=new NodeRSA(c);n.setOptions({encryptionScheme:"pkcs1"});let r=n.decrypt(s.c,"utf8"),i=r.slice(0,16),p=r.slice(16);l.key=i,l.iv=p;let d=t.object;a&&o.filter&&o.filter.forEach(e=>{delete d[e]}),l.send({type:"start",data:d}),console.log(s,r);break;case"update":a&&"onlypull"===o.type?o.allow&&o.allow.includes(s.trend.fromKey)&&t.entrend(s.trend):t.entrend(s.trend);break;case"ping":l.send({type:"pong"})}}),d.on("close",e=>{this.onmsg("close",{event:e,tarObj:l}),console.log("close",e.code,e.reason),n.delete(l),d=l=l.ws=null})}else s.end()})}Object.assign(StanzServer.prototype,{send(e){e&&this.pageWSMap.forEach(t=>{t.send(e)})},onmsg(e,t){},canAccess:e=>!0,listen(e=8005){this.server.listen(e)}}),module.exports=StanzServer;