UNPKG

easy-yopmail

Version:

Easy-YOPMail (get mail address, inbox and read mail from YOPMail with nodeJS)

1 lines 7.75 kB
"use strict";const fs=require("fs"),zlib=require("zlib"),https=require("https"),cheerio=require("cheerio"),constants=require("./constants");class Core{constructor(){this.constants=constants,this.cwd=process.cwd()}getSettings(a,b,c){const d=new URL(a);return{hostname:d.hostname,port:443,path:`${d.pathname}${d.search}`,method:b.toUpperCase(),...c}}async requestAttachment(a,b){let c=2<arguments.length&&arguments[2]!==void 0?arguments[2]:{};return new Promise(((d,e)=>{const f=this.getSettings(b,a,c),g=https.request(f,(a=>{let b=a;const c=a.headers["content-encoding"];"gzip"===c?b=a.pipe(zlib.createGunzip()):"deflate"===c&&(b=a.pipe(zlib.createInflate()));const f=[];b.on("data",(a=>{f.push(a)})),b.on("end",(()=>{const b=Buffer.concat(f),c={statusCode:a.statusCode,headers:a.headers,body:b};d(c)})),b.on("error",(a=>{e(a)}))}));g.on("error",(a=>{e(a)})),g.end()}))}async request(a,b){let c=2<arguments.length&&arguments[2]!==void 0?arguments[2]:{},d=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;b||this.handleError({customMessage:this.constants.ERROR_URL_NOT_FOUND});const e=(a,b)=>{const c=Buffer.concat(b).toString();return{statusCode:a.statusCode,headers:a.headers,body:c}},f=(a,b,c)=>{const d=a.headers["content-encoding"];let f=a;"gzip"===d?f=a.pipe(zlib.createGunzip()):"deflate"===d&&(f=a.pipe(zlib.createInflate()));const g=[];f.on("data",(a=>g.push(a))),f.on("end",(()=>b(e(a,g)))),f.on("error",(a=>c(a)))},g=this.getSettings(b,a,c),h=(a,b)=>new Promise(((c,d)=>{const e=https.request(a,(a=>{f(a,c,d)}));e.on("error",(a=>d(a))),a.body&&e.write(a.body),"POST"===a.method&&b&&e.write(b),e.end()}));try{return await h(g,d)}catch(a){this.handleError({customMessage:"Request Error",error:a})}}async getHttpSettings(){try{const a=await this.request("GET",this.constants.URL_BASE);200!==a.statusCode&&this.handleError({customMessage:this.constants.ERROR_GET_COOKIES});const b=this.loadHTMl(a.body),c=b(this.constants.S_INPUT_YP).val(),d=a.headers["set-cookie"].map((a=>a.split(";")[0])).join("; "),e=a.body.match(this.constants.REGEX_LOCATION)[1],f=a.body.match(this.constants.REGEX_VER)[1],g=await this.request("GET",this.constants.URL_WEBMAIL_JS(f),{headers:{Cookie:d}});200!==g.statusCode&&this.handleError({customMessage:this.constants.ERROR_GET_YJ});const h=g.body.match(this.constants.REGEX_YJ),i=h?h[1]:null,j=this.timeStampInSeconds(),k=this.timeStampInSeconds(),l=this.obtenerYTime(j);return{location:e,version:f,cookie:d,yp:c,yj:i,T:j,RT:k,ytime:l}}catch(a){return this.handleError({customMessage:this.constants.ERROR_GET_COOKIES,error:a}),null}}async detailInbox(a,b,c,d){const{location:e,version:f,cookie:g,yp:h,yj:i,T:j,RT:k,ytime:l}=d,m=15;let n=1,o=!0,p={},q=0,r=[],s={};const t=async(a,b,c,d,e,f,g)=>{let h=constants.URL_INBOX(a,b,c,d,f,g),i=constants.HEADERS_INBOX(e,a,g,j,k,l);const m=await this.request("GET",h,i);return 200!==m.statusCode&&this.handleError({customMessage:constants.ERROR_LOAD_PAGE}),m};b&&0<Object.keys(b).length&&(s=this.validateSearch(b));const u=await t(a,h,i,f,g,1,e),v=u.body,w=this.getTotalMails(v);for(;o;){const b=1===n?v:(await t(a,h,i,f,g,n,e)).body,d=this.getDetailInboxFromPage(b,s,n);p[`page_${n}`]=d.length,q=n,r.push(...d),n*m>=w||n>=c.LIMIT?o=!1:n+=1}return{mail:`${a}@yopmail.com`,settings:c,filteredSearch:s,pageCount:Math.ceil(w/m),totalEmails:w,emailsPerPageCount:p,exploredPageCount:q,fetchedEmailCount:r.length,inbox:r}}getDetailInboxFromPage(a,b,c){const d=this.loadHTMl(a),e=d(".m");return e.map(((a,b)=>this.parseEmail(b,c))).toArray().filter((a=>this.shouldIncludeEmail(a,b)))}validateSelectAttrEQ=(a,b,c,d,e)=>(b&&0===a(b).length?e.push(`Warning - The selector <${b}> is not found in the html.`):d>a(b).length&&e.push(`Warning - The eq(${d}) is greater than the number of elements found in the selector ${b}.`),e);getContentBySelectorForTxt=(a,b,c,d,e)=>{let f=[];return e=this.validateSelectAttrEQ(a,b,c,d,e),b||(f+=a(this.constants.S_MAIL).text().replace(/\s+|\n/gm," ").trim()),b&&!d&&a(b).each(((b,c)=>{f.push(a(c).text().trim())})),b&&d&&(f+=a(b).eq(parseInt(d,10)).text().replace(/\s+|\n/gm," ").trim(),!f&&e.push(`Warning - No text found with selector <${b}> and .eq(${d})`)),{info:e,content:f}};getContentBySelectorForHTML=(a,b,c,d,e)=>{let f;if(e=this.validateSelectAttrEQ(a,b,c,d,e),!b)return f=a.html(this.constants.S_MAIL),{info:e,content:f};if(f=(()=>c?void 0!==d&&null!==d?a(b).eq(parseInt(d,10)).attr(c):a(b).map(((b,d)=>a(d).attr(c))).toArray():void 0!==d&&null!==d?a(b).eq(parseInt(d,10)).html():a(b).map(((b,c)=>a.html(c))).toArray())(),!f||Array.isArray(f)&&!f.length){let a=`Element not found`;a+=` with selector ${b}`,a+=c?` and attribute ${c}`:"",a+=void 0===d?"":` and eq ${d}`,e.push(a)}return{info:e,content:f}};loadHTMl(a){return cheerio.load(a)}getTotalMails(a){const b=a.match(constants.REGEX_TOTAL_MAILS);let c=0;return b&&(c=b[1].split(",")[0]),+c}saveEmailHTML(a,b,c){let d=`${this.cwd}/${a}`;fs.existsSync(d)||fs.mkdirSync(d,{recursive:!0}),fs.writeFileSync(`${d}/emailPage_${c}.html`,b,(function(a){if(a)return new Error(a)}))}validateSearch(a){const b=["id","from","subject","timestamp"],c=b.some((b=>Object.keys(a).includes(b)||null));return c||this.handleError({customMessage:this.constants.ERROR_PARAMETERS_INVALID,error:new Error}),Object.keys(a).reduce(((c,d)=>(b.includes(d)&&(c[d]=a[d]),c)),{})}parseEmail(a,b){const c=cheerio.load(a),d=c(a).attr("id"),e=c(a).find(".lmh").text(),f=c(a).find(".lmf").text(),g=c(a).find(".lms").text();return{id:d,from:f,subject:g,timestamp:e,page:b}}shouldIncludeEmail(a,b){return Object.entries(b).every((b=>{let[c,d]=b;return"id"===c?a.id===d:"from"===c?a.from===d:"subject"===c?a.subject===d:!("timestamp"!==c)&&a.timestamp===d}))}obtenerYTime(a){const b=new Date(1e3*a),c=b.getHours(),d=b.getMinutes();return`${c}:${d}`}timeStampInSeconds(){return Math.floor(Date.now()/1e3)}simplifyEmail(a){return-1<a.indexOf("@")?(a.split("@")[0]||"").toLowerCase():a.toLowerCase()}validateReadMessageOpt(a){const{format:e="txt",selector:b,attribute:c,pathToSave:d,saveAttachment:f=!1}={...{format:"txt",selector:null,attribute:null,pathToSave:null},...a};a={format:e.toLowerCase(),selector:b,attribute:c,pathToSave:d,eq:null,saveAttachment:f};let g=[];const h=(a,b,c)=>{["html","txt"].includes(b.toLowerCase())||(c.push(`Warning - the format ${b} is incorrect, the default format is TXT`),a.format="txt")},i=(a,b,c)=>{const d=b?.match(/^(.+)\.eq\((\d+)\)$/);if(d){const[,b,c]=d;a.eq=c,a.selector=b}else if(b?.includes(".eq(")){const[d]=b.split(".eq(");a.selector=d,a.eq=null,c.push(`Warning - the ".eq()" value is invalid, the default eq is null`)}},j=(a,b,c,d)=>{c&&!b?(d.push(`Warning - the attribute requires a selector, the default attribute is null`),a.attribute=null):c&&"string"!=typeof c&&(d.push(`Warning - the attribute ${c} is incorrect, the default attribute is empty`),a.attribute=null)},k=(a,b,c)=>{b&&"string"!=typeof b&&(c.push(`Warning - the pathToSave ${b} is incorrect, the default pathToSave is empty`),a.pathToSave=null)},l=(a,b,c)=>{"boolean"!=typeof b&&(c.push(`Warning - the saveAttachment ${b} is incorrect, the default saveAttachment is false`),a.saveAttachment=!1)};return h(a,e,g),((a,b,c)=>{b&&"string"!=typeof b?(c.push(`Warning - the selector ${b} is incorrect, the default selector is null`),a.selector=null):i(a,b,c)})(a,b,g),j(a,b,c,g),k(a,d,g),l(a,f,g),{opt:a,info:g}}handleError(){let{customMessage:b=this.constants.ERROR_LOAD_PAGE,error:a}=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};throw a?.message&&(b+=`\n - ${a.message}`),new Error(b)}downloadAttachments(a,b,c){let d=`${this.cwd}/attachments`;fs.existsSync(d)||fs.mkdirSync(d,{recursive:!0}),this.requestAttachment("GET",a,c).then((a=>{fs.writeFileSync(`${d}/${b}`,a.body)}))}}module.exports=Core;