<commit_before>/*
	Berechnet aus JPEG, GIF, PNG Bilden gcode zum Laser-gravieren
	Auflösung: 75 dpi -> Zeilen sind erkennbar

	optimal Speed F1000 und 8% Laserstärke

	Testen ob weniger Speed und Laserstärke geht (F500 & 4% ?)
	150dpi testen
*/

var akPicToLaser=function(zielID){
	var ziel;

	//http://www.shapeoko.com/wiki/index.php/Previewing_G-Code
	//reprap.org/wiki/G-code

	//helper
	var cE=function(z,e,id){
			var l=document.createElement(e);
			if(id!="" && id!=undefined)l.id=id;
			if(z)z.appendChild(l);
				else console.log("cE Ziel:" ,z);
			return l;
		}
	var gE=function(id){
		var re=undefined;
		if(id=="")return re;

		re=document.getElementById(id);
		if(re==null)re=undefined;
		return re;
	}
	var addClass=function(o,s){
		var s2;
		if(o!=undefined){
			s2=o.className;
			if(s2==undefined)s2="";
			if(s2.indexOf(s)<0)o.className=s2+' '+s;
		}
	}
	var subClass=function(o,s){
		var s2;
		if(o!=undefined){
			s2=o.className;
			s2=s2.split('  ').join(' ');
			if(s2.indexOf(s)>-1)o.className=s2.split(' '+s).join('');
			if(s2.indexOf(s)>-1)o.className=s2.split(s).join('');
		}
	}
	var delClass=function(o){
		if(o!=undefined) o.className="";
	}
	var getClass=function(o){return o.className;}
	var istClass=function(o,s){
		if(o.className)
			return (o.className.indexOf(s)>-1);
		else
			return false;
	}
	var maF=function(r){return Math.floor(r*1000)/1000;}
	var maR=function(r){return Math.round(r);}

	//--var--
	var inputFile;
	var outPutDoc;
	var inputimage;
	var outputcanvas;
	var makeButt;
	var pauseButt;

	var input_Width=undefined;
	var input_Height;

	var objektdata={
		width:1,	//mm
		height:1,
		unit:"mm",
		Dlaser:0.125,//Laserdurchmesser in mm  --> minimaler Zeilenabstand --> 203,2dpi
		dpi:75		 //Punkte pro Zoll = Punkte pro 2,54cm
	}

	var pause=false;
	//

	var ini=function(){
		var html,p;
		p=cE(ziel,"p");
		p.innerHTML="Bitte Datei wählen: ";
		inputFile=cE(p,"input","inputFile");
		inputFile.type="file";
		inputFile.accept="image/*;capture=camera";
		inputFile.size="50";//MB
		inputFile.onchange=handleFile;

		inputimage=cE(ziel,"img","inputimage");
		inputimage.onload=prework;
		addClass(inputimage,"unsichtbar");

		p=cE(ziel,"p","setdaten");
		addClass(p,"unsichtbar");
		p.innerHTML="Lasern in einer Größe von ";

		input_Width=cE(p,"input","input_Width");
		input_Width.name="input_Width";
		input_Width.type="number";
		input_Width.step="any";
		input_Width.min=1;
		input_Width.max=500;
		input_Width.placeholder ="in mm";
		input_Width.setAttribute("value",objektdata.width);

		p.innerHTML+=" * ";

		input_Height=cE(p,"input","input_Height");
		input_Height.name="input_Height";
		input_Height.step="any";
		input_Height.type="number";
		input_Height.placeholder ="in "+objektdata.unit;
		input_Height.min=1;
		input_Height.max=500;
		input_Height.setAttribute("value",objektdata.height);

		p.innerHTML+=" (Breite * Höhe in "+objektdata.unit+") ";

		html=cE(p,"a");
		html.href="#";
		html.onclick=setNewSize;
		html.innerHTML="set new size";
		html.className="Button";

		p=cE(ziel,"p");
		outputcanvas=cE(p,"canvas","outputcanvas");

		p=cE(ziel,"p");
		makeButt=cE(p,"a","makeButt");
		makeButt.className="Button";
		makeButt.href="#";
		makeButt.onclick=function(){ konvertiere(); return false;}
		makeButt.innerHTML="konvertiere";
		addClass(makeButt,"unsichtbar");

		p=cE(ziel,"p");
		pauseButt=cE(p,"a","pauseButt");
		pauseButt.href="#";
		pauseButt.className="Button";
		pauseButt.onclick=function(){ pause=true; return false;}
		pauseButt.innerHTML="stopp";
		addClass(pauseButt,"unsichtbar");

		outPutDoc=cE(ziel,"textarea","outPutDoc");
 		addClass(outPutDoc,"unsichtbar");
	}

	var loadImage=function(ifile){
		inputimage.src = URL.createObjectURL(ifile);
	}

	var prework=function(){
		var c;
		var dpi=objektdata.dpi;//Punkte pro Zoll = 2,54cm

 		objektdata.width	=this.width /dpi*2.54*10;
		objektdata.height	=this.height/dpi*2.54*10;

		e=gE("input_Width");
		e.value=maF(objektdata.width);

		e=gE("input_Height");
		e.value=maF(objektdata.height);

		c=gE("setdaten");
		subClass(c,"unsichtbar");

		preWorkPicture();
	}

 	var setNewSize=function(e){
		var e;
		e=gE("input_Width");
 		objektdata.width	=e.value;
		e=gE("input_Height");
		objektdata.height	=e.value;

		preWorkPicture();

		subClass(makeButt,"unsichtbar");
		addClass(pauseButt,"unsichtbar");

	}

	var preWorkPicture=function(){
		var c,cc,bb,hh,imgd,pix,v,r,g,b,d,x,y,e;
		var dpi=objektdata.dpi;//Punkte pro Zoll = 2,54cm

		var inputimage=gE("inputimage");

		c=outputcanvas;
		c.width =maR(objektdata.width*dpi/2.54/10);
		c.height=maR(objektdata.height*dpi/2.54/10);
		cc=c.getContext("2d");

		bb=inputimage.width;
		hh=inputimage.height;

		cc.drawImage(inputimage,0,0,bb,hh, 0,0,c.width,c.height);
		imgd=cc.getImageData(0,0,c.width,c.height);
		pix=imgd.data;

		//in graustufen
		for(y=0;y<c.height;y++)
			for(x=0;x<c.width;x++){
				d=(x*4)+(y)*c.width*4;
				r=Math.round(16/255*pix[d+0])*16;
				g=Math.round(16/255*pix[d+1])*16;
				b=Math.round(16/255*pix[d+2])*16;

				v=Math.round(r*0.299+g*0.587+b*0.114);	// nach helligkeit
				v=Math.floor((r+g+b)/3);				// (r+g+b)/2
				pix[d+0]=v;
				pix[d+1]=v;
				pix[d+2]=v;

			}
		 cc.putImageData(imgd, 0, 0);

	}

	var setPixel=function(canv,x,y,r,g,b,a){
		var cc,id,d;
		cc=canv.getContext("2d");
		id = cc.createImageData(1,1);
		d  = id.data;
		d[0]   = r;
		d[1]   = g;
		d[2]   = b;
		d[3]   = a;
		cc.putImageData( id, x, y );
	}
	var getPixel=function(canv,x,y){
		var cc,id,d;
		cc=canv.getContext("2d");
		id=cc.getImageData(x,y,1,1);
		pix=id.data;
		return pix;//[r,g,b,a]
	}

	var zeile=0;
	var konvertiere=function(){
		zeile=0;

		addClass(makeButt,"unsichtbar");
		subClass(pauseButt,"unsichtbar");
		outPutDoc.innerHTML=";start\n";
		outPutDoc.innerHTML+=";"+maF(objektdata.width)+" x "+maF(objektdata.height)+"mm² \n";

		outPutDoc.innerHTML+="G90 ;absolute Positioning\n";
		outPutDoc.innerHTML+="M08 ;Flood Coolant On\n";// opt.
		outPutDoc.innerHTML+="G21 ;Set Units to Millimeters\n";//
		outPutDoc.innerHTML+="F1000 ;speed\n";
		outPutDoc.style.display="none"
		window.setTimeout(konvertiereF,10);//Zeilen per Timer durchgehen um Script-Blockierung zu verhindern
	}

	var konvertiereF=function(){
		var c,cc,imgd,pix,x,y,d,r,g,b;
		c=outputcanvas;
		cc=c.getContext("2d");
		imgd=cc.getImageData(0,0,c.width,c.height);
		pix=imgd.data;

		//mm pro Pixel
		var stepX=objektdata.width/c.width ;	//mm pro Pixel
		var stepY=objektdata.height/c.height ;
		if(zeile==0){
			outPutDoc.innerHTML+="; mm/Pixel "+maF(stepX)+" "+maF(stepY)+"\n";
			outPutDoc.innerHTML+="; "+objektdata.dpi+" dpi \n";
		}

		var lposX=stepX;
		var lposY=-zeile*stepY;
		var s="";
		y=zeile;//Y per Timer sonst Script zu sehr ausgelastet
		s+="G01 X"+maF(lposX)+" Y"+maF(lposY)+"\n";//or G00 Linear Move
		s+="M03\n";

		x=0;
		d=(x*4)+(y)*c.width*4;
		var lastpixel=pix[d+1];
		for(x=1;x<c.width;x++){
			d=(x*4)+(y)*c.width*4;
			r=pix[d+1];//nur Rotkanal auswerten (=graustufen)

			//lauflängen...
			if(r!=lastpixel || x==(c.width-1)){
				//if(x==(c.width-1) && lastpixel!=255)
				//TODO: leerfahrten am Ende evtl. entfernen
				//burnIN am Anfang/Ende verhindern, wie? -> wenigerPower + langsammer?
				s+="S"+Math.round(1000-(1000/255*lastpixel))+"\n";//Intensität
				s+="G01 X"+maF(lposX)+"\n";//fahre bis

				//G1 Xnnn Ynnn Znnn Ennn Fnnn Snnn

				lastpixel=r;
			}

			//if(r>128)s+="0";else s+="1"
			lposX+=stepX;
		}
		//s+="\n";
		s+="M05\n";

		outPutDoc.innerHTML+=s;

		setPixel(c,0,zeile, 255,0,0,255);
		setPixel(c,1,zeile, 255,0,0,255);
		setPixel(c,(c.width-1),zeile, 255,0,0,255);
		setPixel(c,(c.width-2),zeile, 255,0,0,255);

		zeile++;
		if(zeile<c.height){
				if(pause){//Stopp
					//window.setTimeout(konvertiereF,1000);//1sec
					outPutDoc.style.display="inline-block";
				}
				else
					window.setTimeout(konvertiereF,10);
			}
			else{
				//ende
				outPutDoc.innerHTML+="S0\n ";//
				outPutDoc.innerHTML+="G01 X0 Y0\n";//back to start
				outPutDoc.innerHTML+="M09 ;Coolant Off\n";//
				outPutDoc.innerHTML+=";end \n";//
				outPutDoc.style.display="inline-block";
				addClass(pauseButt,"unsichtbar");
			}
	}

	var handleFile=function(){
		addClass(pauseButt,"unsichtbar");
		pause=false;

		var reader = new FileReader();
		reader.onload = function(theFile) {
				var data=this.result;
				var ifile=inputFile.files[0];
				var filename=ifile.name.toLowerCase();

				if(filename.indexOf(".jpg")>-1
					|| filename.indexOf(".jpeg")>-1
					|| filename.indexOf(".png")>-1
					|| filename.indexOf(".bmp")>-1
					|| filename.indexOf(".gif")>-1
					){

					loadImage(ifile);
					subClass(makeButt,"unsichtbar");
				}

				outPutDoc.innerHTML="";

			};
		reader.readAsBinaryString(inputFile.files[0]);
	}

	ziel=gE(zielID);
	ini();

}

window.onload=function(){
	var ptl=new akPicToLaser("PicToLaser");

};
<commit_msg>update CSS functionen<commit_after>/*
	Berechnet aus JPEG, GIF, PNG Bilden gcode zum Laser-gravieren
	Auflösung: 75 dpi -> Zeilen sind erkennbar

	optimal Speed F1000 und 8% Laserstärke

	Testen ob weniger Speed und Laserstärke geht (F500 & 4% ?)
	150dpi testen
*/

var akPicToLaser=function(zielID){
	var ziel;

	//http://www.shapeoko.com/wiki/index.php/Previewing_G-Code
	//reprap.org/wiki/G-code

	//helper
	var cE=function(z,e,id){
			var l=document.createElement(e);
			if(id!="" && id!=undefined)l.id=id;
			if(z)z.appendChild(l);
				else console.log("cE Ziel:" ,z);
			return l;
		}
	var gE=function(id){
		var re=undefined;
		if(id=="")return re;

		re=document.getElementById(id);
		if(re==null)re=undefined;
		return re;
	}
	var addClass=function(htmlNode,Classe){
		var newClass;
		if(htmlNode!=undefined){
			newClass=htmlNode.className;
			if(newClass==undefined || newClass=="")newClass=Classe;
			else
			if(!istClass(htmlNode,Classe))newClass+=' '+Classe;
			htmlNode.className=newClass;
		}
	}
	var subClass=function(htmlNode,Classe){
		var aClass,i;
		if(htmlNode!=undefined && htmlNode.className!=undefined){
			aClass=htmlNode.className.split(" ");
			var newClass="";
			for(i=0;i<aClass.length;i++){
				if(aClass[i]!=Classe){
					if(newClass!="")newClass+=" ";
					newClass+=aClass[i];
					}
			}
			htmlNode.className=newClass;
		}
	}
	var delClass=function(o){
		if(o!=undefined) o.className="";
	}
	var getClass=function(o){return o.className;}
	var istClass=function(htmlNode,Classe){
		if(htmlNode.className){
			var i,aClass=htmlNode.className.split(' ');
			for(i=0;i<aClass.length;i++){
				if(aClass[i]==Classe)return true;
			}
		}
		return false;
	}
	var maF=function(r){return Math.floor(r*1000)/1000;}
	var maR=function(r){return Math.round(r);}

	//--var--
	var inputFile;
	var outPutDoc;
	var inputimage;
	var outputcanvas;
	var makeButt;
	var pauseButt;

	var input_Width=undefined;
	var input_Height;

	var objektdata={
		width:1,	//mm
		height:1,
		unit:"mm",
		Dlaser:0.125,//Laserdurchmesser in mm  --> minimaler Zeilenabstand --> 203,2dpi
		dpi:75		 //Punkte pro Zoll = Punkte pro 2,54cm
	}

	var pause=false;
	//

	var ini=function(){
		var html,p;
		p=cE(ziel,"p");
		p.innerHTML="Bitte Datei wählen: ";
		inputFile=cE(p,"input","inputFile");
		inputFile.type="file";
		inputFile.accept="image/*;capture=camera";
		inputFile.size="50";//MB
		inputFile.onchange=handleFile;

		inputimage=cE(ziel,"img","inputimage");
		inputimage.onload=prework;
		addClass(inputimage,"unsichtbar");

		p=cE(ziel,"p","setdaten");
		addClass(p,"unsichtbar");
		p.innerHTML="Lasern in einer Größe von ";

		input_Width=cE(p,"input","input_Width");
		input_Width.name="input_Width";
		input_Width.type="number";
		input_Width.step="any";
		input_Width.min=1;
		input_Width.max=500;
		input_Width.placeholder ="in mm";
		input_Width.setAttribute("value",objektdata.width);

		p.innerHTML+=" * ";

		input_Height=cE(p,"input","input_Height");
		input_Height.name="input_Height";
		input_Height.step="any";
		input_Height.type="number";
		input_Height.placeholder ="in "+objektdata.unit;
		input_Height.min=1;
		input_Height.max=500;
		input_Height.setAttribute("value",objektdata.height);

		p.innerHTML+=" (Breite * Höhe in "+objektdata.unit+") ";

		html=cE(p,"a");
		html.href="#";
		html.onclick=setNewSize;
		html.innerHTML="set new size";
		html.className="Button";

		p=cE(ziel,"p");
		outputcanvas=cE(p,"canvas","outputcanvas");

		p=cE(ziel,"p");
		makeButt=cE(p,"a","makeButt");
		makeButt.className="Button";
		makeButt.href="#";
		makeButt.onclick=function(){ konvertiere(); return false;}
		makeButt.innerHTML="konvertiere";
		addClass(makeButt,"unsichtbar");

		p=cE(ziel,"p");
		pauseButt=cE(p,"a","pauseButt");
		pauseButt.href="#";
		pauseButt.className="Button";
		pauseButt.onclick=function(){ pause=true; return false;}
		pauseButt.innerHTML="stopp";
		addClass(pauseButt,"unsichtbar");

		outPutDoc=cE(ziel,"textarea","outPutDoc");
 		addClass(outPutDoc,"unsichtbar");
	}

	var loadImage=function(ifile){
		inputimage.src = URL.createObjectURL(ifile);
	}

	var prework=function(){
		var c;
		var dpi=objektdata.dpi;//Punkte pro Zoll = 2,54cm

 		objektdata.width	=this.width /dpi*2.54*10;
		objektdata.height	=this.height/dpi*2.54*10;

		e=gE("input_Width");
		e.value=maF(objektdata.width);

		e=gE("input_Height");
		e.value=maF(objektdata.height);

		c=gE("setdaten");
		subClass(c,"unsichtbar");

		preWorkPicture();
	}

 	var setNewSize=function(e){
		var e;
		e=gE("input_Width");
 		objektdata.width	=e.value;
		e=gE("input_Height");
		objektdata.height	=e.value;

		preWorkPicture();

		subClass(makeButt,"unsichtbar");
		addClass(pauseButt,"unsichtbar");

	}

	var preWorkPicture=function(){
		var c,cc,bb,hh,imgd,pix,v,r,g,b,d,x,y,e;
		var dpi=objektdata.dpi;//Punkte pro Zoll = 2,54cm

		var inputimage=gE("inputimage");

		c=outputcanvas;
		c.width =maR(objektdata.width*dpi/2.54/10);
		c.height=maR(objektdata.height*dpi/2.54/10);
		cc=c.getContext("2d");

		bb=inputimage.width;
		hh=inputimage.height;

		cc.drawImage(inputimage,0,0,bb,hh, 0,0,c.width,c.height);
		imgd=cc.getImageData(0,0,c.width,c.height);
		pix=imgd.data;

		//in graustufen
		for(y=0;y<c.height;y++)
			for(x=0;x<c.width;x++){
				d=(x*4)+(y)*c.width*4;
				r=Math.round(16/255*pix[d+0])*16;
				g=Math.round(16/255*pix[d+1])*16;
				b=Math.round(16/255*pix[d+2])*16;

				v=Math.round(r*0.299+g*0.587+b*0.114);	// nach helligkeit
				v=Math.floor((r+g+b)/3);				// (r+g+b)/2
				pix[d+0]=v;
				pix[d+1]=v;
				pix[d+2]=v;

			}
		 cc.putImageData(imgd, 0, 0);

	}

	var setPixel=function(canv,x,y,r,g,b,a){
		var cc,id,d;
		cc=canv.getContext("2d");
		id = cc.createImageData(1,1);
		d  = id.data;
		d[0]   = r;
		d[1]   = g;
		d[2]   = b;
		d[3]   = a;
		cc.putImageData( id, x, y );
	}
	var getPixel=function(canv,x,y){
		var cc,id,d;
		cc=canv.getContext("2d");
		id=cc.getImageData(x,y,1,1);
		pix=id.data;
		return pix;//[r,g,b,a]
	}

	var zeile=0;
	var konvertiere=function(){
		zeile=0;

		addClass(makeButt,"unsichtbar");
		subClass(pauseButt,"unsichtbar");
		outPutDoc.innerHTML=";start\n";
		outPutDoc.innerHTML+=";"+maF(objektdata.width)+" x "+maF(objektdata.height)+"mm² \n";

		outPutDoc.innerHTML+="G90 ;absolute Positioning\n";
		outPutDoc.innerHTML+="M08 ;Flood Coolant On\n";// opt.
		outPutDoc.innerHTML+="G21 ;Set Units to Millimeters\n";//
		outPutDoc.innerHTML+="F1000 ;speed\n";
		outPutDoc.style.display="none"
		window.setTimeout(konvertiereF,10);//Zeilen per Timer durchgehen um Script-Blockierung zu verhindern
	}

	var konvertiereF=function(){
		var c,cc,imgd,pix,x,y,d,r,g,b;
		c=outputcanvas;
		cc=c.getContext("2d");
		imgd=cc.getImageData(0,0,c.width,c.height);
		pix=imgd.data;

		//mm pro Pixel
		var stepX=objektdata.width/c.width ;	//mm pro Pixel
		var stepY=objektdata.height/c.height ;
		if(zeile==0){
			outPutDoc.innerHTML+="; mm/Pixel "+maF(stepX)+" "+maF(stepY)+"\n";
			outPutDoc.innerHTML+="; "+objektdata.dpi+" dpi \n";
		}

		var lposX=stepX;
		var lposY=-zeile*stepY;
		var s="";
		y=zeile;//Y per Timer sonst Script zu sehr ausgelastet
		s+="G01 X"+maF(lposX)+" Y"+maF(lposY)+"\n";//or G00 Linear Move
		s+="M03\n";

		x=0;
		d=(x*4)+(y)*c.width*4;
		var lastpixel=pix[d+1];
		for(x=1;x<c.width;x++){
			d=(x*4)+(y)*c.width*4;
			r=pix[d+1];//nur Rotkanal auswerten (=graustufen)

			//lauflängen...
			if(r!=lastpixel || x==(c.width-1)){
				//if(x==(c.width-1) && lastpixel!=255)
				//TODO: leerfahrten am Ende evtl. entfernen
				//burnIN am Anfang/Ende verhindern, wie? -> wenigerPower + langsammer?
				s+="S"+Math.round(1000-(1000/255*lastpixel))+"\n";//Intensität
				s+="G01 X"+maF(lposX)+"\n";//fahre bis

				//G1 Xnnn Ynnn Znnn Ennn Fnnn Snnn

				lastpixel=r;
			}

			//if(r>128)s+="0";else s+="1"
			lposX+=stepX;
		}
		//s+="\n";
		s+="M05\n";

		outPutDoc.innerHTML+=s;

		setPixel(c,0,zeile, 255,0,0,255);
		setPixel(c,1,zeile, 255,0,0,255);
		setPixel(c,(c.width-1),zeile, 255,0,0,255);
		setPixel(c,(c.width-2),zeile, 255,0,0,255);

		zeile++;
		if(zeile<c.height){
				if(pause){//Stopp
					//window.setTimeout(konvertiereF,1000);//1sec
					outPutDoc.style.display="inline-block";
				}
				else
					window.setTimeout(konvertiereF,10);
			}
			else{
				//ende
				outPutDoc.innerHTML+="S0\n ";//
				outPutDoc.innerHTML+="G01 X0 Y0\n";//back to start
				outPutDoc.innerHTML+="M09 ;Coolant Off\n";//
				outPutDoc.innerHTML+=";end \n";//
				outPutDoc.style.display="inline-block";
				addClass(pauseButt,"unsichtbar");
			}
	}

	var handleFile=function(){
		addClass(pauseButt,"unsichtbar");
		pause=false;

		var reader = new FileReader();
		reader.onload = function(theFile) {
				var data=this.result;
				var ifile=inputFile.files[0];
				var filename=ifile.name.toLowerCase();

				if(filename.indexOf(".jpg")>-1
					|| filename.indexOf(".jpeg")>-1
					|| filename.indexOf(".png")>-1
					|| filename.indexOf(".bmp")>-1
					|| filename.indexOf(".gif")>-1
					){

					loadImage(ifile);
					subClass(makeButt,"unsichtbar");
				}

				outPutDoc.innerHTML="";

			};
		reader.readAsBinaryString(inputFile.files[0]);
	}

	ziel=gE(zielID);
	ini();

}

window.onload=function(){
	var ptl=new akPicToLaser("PicToLaser");

};
<|endoftext|>


<commit_before>var cronJob = require('cron').CronJob,
    hipqus = require('./hipqus.js'),
    D  = require('./disqus-config.js');

var lastTimestamp = null;
hipqus.sendMessage('Test without room token');
// new cronJob('*/10 * * * * *', function (){

//     D.disqus.request('posts/list', D.disqus_options, function(data) {

//         if(data.error){
//             console.log('Something went wrong...');
//             console.log(data);
//         }else{
//             var response = JSON.parse(data).response;

//             if(!lastTimestamp){
//                 // initializing lastTimestamp with most recent comment date
//                 lastTimestamp = new Date(response[0].createdAt);
//             }else{
//                 var mostRecentTimestamp = null;
//                 for(var i=0; i < response.length; i++){
//                     var postDate = new Date(response[i].createdAt);
//                     if(postDate > lastTimestamp){
//                         hipqus.buildMessage(response[i]);
//                         if(!mostRecentTimestamp){
//                             mostRecentTimestamp = postDate;
//                         }
//                     }else{
//                         console.log('Nothing new to send. Last comment timestamp: ' + lastTimestamp.toISOString());
//                         break;
//                     }
//                 }
//                 if(mostRecentTimestamp){
//                     lastTimestamp = mostRecentTimestamp;
//                 }
//             }
//         }
//     });

// }, null, true, null);

<commit_msg>removing dumb test<commit_after>var cronJob = require('cron').CronJob,
    hipqus = require('./hipqus.js'),
    D  = require('./disqus-config.js');

var lastTimestamp = null;

new cronJob('*/10 * * * * *', function (){

    D.disqus.request('posts/list', D.disqus_options, function(data) {

        if(data.error){
            console.log('Something went wrong...');
            console.log(data);
        }else{
            var response = JSON.parse(data).response;

            if(!lastTimestamp){
                // initializing lastTimestamp with most recent comment date
                lastTimestamp = new Date(response[0].createdAt);
            }else{
                var mostRecentTimestamp = null;
                for(var i=0; i < response.length; i++){
                    var postDate = new Date(response[i].createdAt);
                    if(postDate > lastTimestamp){
                        hipqus.buildMessage(response[i]);
                        if(!mostRecentTimestamp){
                            mostRecentTimestamp = postDate;
                        }
                    }else{
                        console.log('Nothing new to send. Last comment timestamp: ' + lastTimestamp.toISOString());
                        break;
                    }
                }
                if(mostRecentTimestamp){
                    lastTimestamp = mostRecentTimestamp;
                }
            }
        }
    });

}, null, true, null);

<|endoftext|>


<commit_before>/**
 * Dependencies
 */
var express   = require('express')
  , passport  = require('passport')
  , http      = require('http')
  , path      = require('path')
  , flash     = require('connect-flash')
  , mongoose  = require('mongoose')
  , stylus    = require('stylus')
  , nib       = require('nib')
  , GitHubStrategy = require('passport-github').Strategy;

/**
 * Routes
 */
var routes    = require('./routes/routes')
  , pages     = require('./routes/pages');

/**
 * Config
 */
var settings  = require('./config/application')
  , secrets   = require('./config/secrets')
  , db        = require('./config/database');

/**
 * Helpers
 */
var mh        = require('./lib/menu_helper')
  , ah        = require('./lib/auth_helper');

/**
 * Models
 */
var User      = require('./models/user');

var app = express();

/**
 * Establish database connection
 */
mongoose.connect(db[app.settings.env]);

/**
 * Local variables
 */
app.set('about', settings.about);
app.set('domain', settings.domain);
app.set('name', settings.name);
app.set('networks', settings.networks);
app.set('organizers', settings.organizers);
app.set('description', settings.description);
app.set('keywords', settings.keywords);
app.set('menu', mh.generate('./views/pages'));
app.set('getTitle', function(title) {
  if (title) return title + ' | ' + app.settings.name;
  return app.settings.name;
});

/**
 * Authentication helper functions
 */
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new GitHubStrategy({
  clientID: secrets['providers']['github']['id'],
  clientSecret: secrets['providers']['github']['secret'],
  callbackURL: app.settings.env === 'production' ? 'http://' + settings.domain + '/auth/github/callback' : 'http://127.0.0.1:3000/auth/github/callback'
}, function(accessToken, refreshToken, profile, done) {
  User.find({uid: profile.id, network: 'github'}, function(err, users) {
    if (err) throw err;

    if (users.length > 0) {
      return done(err, users[0]);
    } else {
      var user = new User();
      user.network = 'github';
      user.uid = profile.id;
      user.name = profile.first_name || profile.name;
      user.profile = profile;
      user.save(function(err) {
        if (err) throw err;
        return done(err, user);
      });
    }
  });
}));

/**
 * Stylus Middleware
 */
function stylusCompiler(str, path) {
  return stylus(str).set('filename', path).set('compress', true).use(nib()).import('nib');
}

/**
 * Error Middleware
 */

function errorHandler(err, req, res, next) {
  res.status(500);

  if (req.accepts('html')) {
    res.render('500', {title: '500 Application Error', error: err, user: req.user});
    return;
  }

  if (req.accepts('json')) {
    res.send({error: 'Application error'});
  }

  res.type('txt').send('Application error');
}

function notFoundHandler(req, res, next) {
  res.status(400);

  if (req.accepts('html')) {
    res.render('404', {title: '404 Not Found', error: req.uri + ' was not found on the server.', user: req.user});
    return;
  }

  if (req.accepts('json')) {
    res.send({error: 'Not found'});
  }

  res.type('txt').send('Not found');
}

/**
 * Authentication Middleware
 */
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated() && ah.authorize(req)) { return next(); }
  req.flash('error', 'Access denied. You are not authorized to access that resource.');
  res.redirect('/')
}

/**
 * Middleware
 */
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser(secrets['cookies']['key']));
  app.use(express.session());
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(stylus.middleware({
    src: __dirname + '/public',
    compile: stylusCompiler
  }));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(notFoundHandler);
  app.use(errorHandler);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

/**
 * Routes
 */
require('./routes/auth')(app, passport);
app.post('/contact', routes.contact);
app.get('/', pages.page);
app.get('/:page', pages.page);

/*
app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});
*/

/**
 * Server
 */
var port = process.env.PORT || 5000;
http.createServer(app).listen(port, function(){
  console.log("Express server listening on port " + port);
});<commit_msg>Load events in local variable.<commit_after>/**
 * Dependencies
 */
var express   = require('express')
  , passport  = require('passport')
  , http      = require('http')
  , path      = require('path')
  , flash     = require('connect-flash')
  , mongoose  = require('mongoose')
  , stylus    = require('stylus')
  , nib       = require('nib')
  , GitHubStrategy = require('passport-github').Strategy;

/**
 * Routes
 */
var routes    = require('./routes/routes')
  , pages     = require('./routes/pages');

/**
 * Config
 */
var settings  = require('./config/application')
  , secrets   = require('./config/secrets')
  , db        = require('./config/database');

/**
 * Helpers
 */
var mh        = require('./lib/menu_helper')
  , ah        = require('./lib/auth_helper');

/**
 * Models
 */
var User      = require('./models/user');

var app = express();

/**
 * Establish database connection
 */
mongoose.connect(db[app.settings.env]);

/**
 * Local variables
 */
app.set('about', settings.about);
app.set('domain', settings.domain);
app.set('name', settings.name);
app.set('networks', settings.networks);
app.set('organizers', settings.organizers);
app.set('events', settings.events);
app.set('description', settings.description);
app.set('keywords', settings.keywords);
app.set('menu', mh.generate('./views/pages'));
app.set('getTitle', function(title) {
  if (title) return title + ' | ' + app.settings.name;
  return app.settings.name;
});

/**
 * Authentication helper functions
 */
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new GitHubStrategy({
  clientID: secrets['providers']['github']['id'],
  clientSecret: secrets['providers']['github']['secret'],
  callbackURL: app.settings.env === 'production' ? 'http://' + settings.domain + '/auth/github/callback' : 'http://127.0.0.1:3000/auth/github/callback'
}, function(accessToken, refreshToken, profile, done) {
  User.find({uid: profile.id, network: 'github'}, function(err, users) {
    if (err) throw err;

    if (users.length > 0) {
      return done(err, users[0]);
    } else {
      var user = new User();
      user.network = 'github';
      user.uid = profile.id;
      user.name = profile.first_name || profile.name;
      user.profile = profile;
      user.save(function(err) {
        if (err) throw err;
        return done(err, user);
      });
    }
  });
}));

/**
 * Stylus Middleware
 */
function stylusCompiler(str, path) {
  return stylus(str).set('filename', path).set('compress', true).use(nib()).import('nib');
}

/**
 * Error Middleware
 */

function errorHandler(err, req, res, next) {
  res.status(500);

  if (req.accepts('html')) {
    res.render('500', {title: '500 Application Error', error: err, user: req.user});
    return;
  }

  if (req.accepts('json')) {
    res.send({error: 'Application error'});
  }

  res.type('txt').send('Application error');
}

function notFoundHandler(req, res, next) {
  res.status(400);

  if (req.accepts('html')) {
    res.render('404', {title: '404 Not Found', error: req.uri + ' was not found on the server.', user: req.user});
    return;
  }

  if (req.accepts('json')) {
    res.send({error: 'Not found'});
  }

  res.type('txt').send('Not found');
}

/**
 * Authentication Middleware
 */
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated() && ah.authorize(req)) { return next(); }
  req.flash('error', 'Access denied. You are not authorized to access that resource.');
  res.redirect('/')
}

/**
 * Middleware
 */
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser(secrets['cookies']['key']));
  app.use(express.session());
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(stylus.middleware({
    src: __dirname + '/public',
    compile: stylusCompiler
  }));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(notFoundHandler);
  app.use(errorHandler);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

/**
 * Routes
 */
require('./routes/auth')(app, passport);
app.post('/contact', routes.contact);
app.get('/', pages.page);
app.get('/:page', pages.page);

/*
app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});
*/

/**
 * Server
 */
var port = process.env.PORT || 5000;
http.createServer(app).listen(port, function(){
  console.log("Express server listening on port " + port);
});<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');
var express = require('express');
var expressValidator = require('express-validator');
var path = require('path');
var assert = require('assert');

var app = express();
var appValidator = expressValidator();

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(appValidator);
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res) {
  res.status(404).render('404', {title: 'Not found, 404'});
});

if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

var routesDir = './routes';
fs.readdir(routesDir, function (err, files) {
  assert.ifError(err);
  files.forEach(function (file) {
    require(path.join(__dirname, routesDir, file)).init(app);
  });
});

var server = http.createServer(app).listen(app.get('port'), function() {
  var address = server.address();
  console.log("opened server on %j %s", address.address, address.port);
});
<commit_msg>Add mongoose configuration<commit_after>var http = require('http');
var fs = require('fs');
var express = require('express');
var expressValidator = require('express-validator');
var path = require('path');
var assert = require('assert');
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/jsconfuy');

var app = express();
var appValidator = expressValidator();

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(appValidator);
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res) {
  res.status(404).render('404', {title: 'Not found, 404'});
});

if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

var routesDir = './routes';
fs.readdir(routesDir, function (err, files) {
  assert.ifError(err);
  files.forEach(function (file) {
    require(path.join(__dirname, routesDir, file)).init(app);
  });
});

var server = http.createServer(app).listen(app.get('port'), function() {
  var address = server.address();
  console.log("opened server on %j %s", address.address, address.port);
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var favicon = require('serve-favicon');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var lusca = require('lusca');
var methodOverride = require('method-override');

var _ = require('lodash');
var MongoStore = require('connect-mongo')(session);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');

/**
 * Controllers (route handlers).
 */
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');

/**
 * API keys and Passport configuration.
 */
var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */
var app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(connectAssets({
  paths: [path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js')]
}));
app.use(logger('dev'));
app.use(favicon(path.join(__dirname, 'public/favicon.png')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: new MongoStore({ url: secrets.db, autoReconnect: true })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(lusca({
  csrf: true,
  xframe: 'SAMEORIGIN',
  xssProtection: true
}));
app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  if (/api/i.test(req.path)) req.session.returnTo = req.path;
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/steam', apiController.getSteam);
app.get('/api/stripe', apiController.getStripe);
app.post('/api/stripe', apiController.postStripe);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);
app.get('/api/instagram', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getInstagram);
app.get('/api/yahoo', apiController.getYahoo);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/lob', apiController.getLob);
app.get('/api/bitgo', apiController.getBitGo);
app.post('/api/bitgo', apiController.postBitGo);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/instagram', passport.authenticate('instagram'));
app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * OAuth authorization routes. (API examples)
 */
app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});

/**
 * Error Handler.
 */
app.use(errorHandler());

/**
 * Start Express server.
 */
app.listen(app.get('port'), function() {
  console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});

module.exports = app;
<commit_msg>fixed a bug with connect-assets where assets were served twice<commit_after>/**
 * Module dependencies.
 */
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var favicon = require('serve-favicon');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var lusca = require('lusca');
var methodOverride = require('method-override');

var _ = require('lodash');
var MongoStore = require('connect-mongo')(session);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var assets = require('connect-assets');

/**
 * Controllers (route handlers).
 */
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');

/**
 * API keys and Passport configuration.
 */
var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */
var app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(assets({
  paths: ['public/css', 'public/js']
}));
app.use(logger('dev'));
app.use(favicon(path.join(__dirname, 'public/favicon.png')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: new MongoStore({ url: secrets.db, autoReconnect: true })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(lusca({
  csrf: true,
  xframe: 'SAMEORIGIN',
  xssProtection: true
}));
app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  if (/api/i.test(req.path)) req.session.returnTo = req.path;
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/steam', apiController.getSteam);
app.get('/api/stripe', apiController.getStripe);
app.post('/api/stripe', apiController.postStripe);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);
app.get('/api/instagram', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getInstagram);
app.get('/api/yahoo', apiController.getYahoo);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/lob', apiController.getLob);
app.get('/api/bitgo', apiController.getBitGo);
app.post('/api/bitgo', apiController.postBitGo);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/instagram', passport.authenticate('instagram'));
app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * OAuth authorization routes. (API examples)
 */
app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});

/**
 * Error Handler.
 */
app.use(errorHandler());

/**
 * Start Express server.
 */
app.listen(app.get('port'), function() {
  console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});

module.exports = app;
<|endoftext|>


<commit_before>const breakpoints = ['48em', '64em']

const colors = {
  black: '#2a2722',
  nearBlack: '#39342d',
  darkGrey: '#443e35',
  grey: '#efedea',
  nearWhite: '#f9f9f8',
  white: '#fff',
  transparent: 'transparent',
  orange: '#f2930d',
}

// Box-sizing & borders
const space = [0, '0.25rem', '0.5rem', '1rem', '2rem', '4rem', '8rem', '16rem']
const borders = [
  0,
  '0.125rem solid',
  '0.25rem solid',
  '0.5rem solid',
  '1rem solid',
  '2rem solid',
]
const radii = [0, '0.125rem', '0.25rem', '0.5rem', '1rem', '100%']

// Typography
const fontSizes = [
  '0.875rem',
  '1rem',
  '1.25rem',
  '1.5rem',
  '2.25rem',
  '3rem',
  '5rem',
  '6rem',
]
const lineHeights = {
  title: 1.25,
  copy: 1.5,
}
const fontWeights = {
  1: '100',
  2: '200',
  3: '300',
  4: '400',
  5: '500',
  6: '600',
  7: '700',
  normal: '400',
  bold: '700',
}
const fonts = {
  'sans-serif':
    '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',
  monospace:
    '"SF Mono", SFMono-Regular, "Roboto Mono", consolas, monaco, courier, "Courier New", monospace',
}

const theme = {
  breakpoints,
  space,
  fontSizes,
  borders,
  radii,
  fonts,
  lineHeights,
  fontWeights,
  colors,
}

export default theme
<commit_msg>:lipstick: update font stacks<commit_after>const breakpoints = ['48em', '64em']

const colors = {
  black: '#2a2722',
  nearBlack: '#39342d',
  darkGrey: '#443e35',
  grey: '#efedea',
  nearWhite: '#f9f9f8',
  white: '#fff',
  transparent: 'transparent',
  orange: '#f2930d',
}

// Box-sizing & borders
const space = [0, '0.25rem', '0.5rem', '1rem', '2rem', '4rem', '8rem', '16rem']
const borders = [
  0,
  '0.125rem solid',
  '0.25rem solid',
  '0.5rem solid',
  '1rem solid',
  '2rem solid',
]
const radii = [0, '0.125rem', '0.25rem', '0.5rem', '1rem', '100%']

// Typography
const fontSizes = [
  '0.875rem',
  '1rem',
  '1.25rem',
  '1.5rem',
  '2.25rem',
  '3rem',
  '5rem',
  '6rem',
]
const lineHeights = {
  title: 1.25,
  copy: 1.5,
}
const fontWeights = {
  1: '100',
  2: '200',
  3: '300',
  4: '400',
  5: '500',
  6: '600',
  7: '700',
  normal: '400',
  bold: '700',
}
const fonts = {
  'sans-serif':
    'system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Oxygen, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
  monospace:
    'Menlo, Consolas, Roboto Mono, Ubuntu Monospace, Oxygen Mono, Liberation Mono, monospace',
}

const theme = {
  breakpoints,
  space,
  fontSizes,
  borders,
  radii,
  fonts,
  lineHeights,
  fontWeights,
  colors,
}

export default theme
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , util = require('util')
  , fs = require('fs')
  , url = require('url')
  , http = require('http')
  , io = require('socket.io')
  , yaml = require('js-yaml')
  , glob = require('glob')
  , httpdigest = require('http-digest')
  , Mustache = require('mustache')
  , child = require('child_process');

var app = module.exports = express.createServer();

var parseConfig = function(filename) {
  return yaml.load(fs.readFileSync(filename, 'utf8'));
};

var config = parseConfig('./config/config.yml');

var logs = [];

for (var i=0; i < config.logs.length; i++) {
  files = glob.sync(config.logs[i]);

  for (var j=0; j < files.length; j++) {
    if (-1 == logs.indexOf(files[j])) {
      logs.push(files[j]);
    }
  };
};

var log_opts = [];

for (var i=0; i < logs.length; i++) {
  log_opts.push({idx: i, name: logs[i]});
};

// Configuration

app.helpers({
  log_opts: log_opts,
  config: config
});

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.basicAuth(config.user, config.pass));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

app.listen(config.port);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

var io = io.listen(app);
var processes = {};

io.sockets.on('connection', function(client) {

  var sessionId = client.sessionId;
  var stringdata = '';
  var restdata = '';

  processes[sessionId] = {
    active_log: null,
    tail: null
  }

  var emit_data = function(data, search) {
    stringdata = restdata + data;
    linedata = stringdata.substr(0, stringdata.lastIndexOf('\n')).split('\n');
    restdata = stringdata.substr(stringdata.lastIndexOf('\n') + 1);

    buffer = []
    for (var i=0; i < linedata.length; i++) {
      if (search && !linedata[i].match(search)) {
        continue;
      }
      buffer.push({ message: linedata[i] });
    };
    client.emit('buffer', { buffer: buffer });
    buffer = []
  };

  var tail_start = function(active, search) {
    var tail_opts = ["-f", "-n", 250, logs[active]];

    processes[sessionId].active_log = active;
    processes[sessionId].active_search = search;
    processes[sessionId].tail = child.spawn("tail", tail_opts);
    processes[sessionId].tail.stdout.on("data", function(data) {
        emit_data(data, search);
    });
  }

  var tail_stop = function() {
    if (processes[sessionId].tail !== null) processes[sessionId].tail.kill();
  }

  client.on('log_request', function(message) {
    var active = parseInt(message.log_file);
    var search = message.search;
    if (active !== processes[sessionId].active_log || search !== processes[sessionId].active_search) {
      tail_stop();
      client.emit('flush');
      tail_start(active, search);
    }
  });

  client.on('disconnect', function(){
    tail_stop();
  });
});
<commit_msg>Remove deprecated requires<commit_after>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , util = require('util')
  , fs = require('fs')
  , url = require('url')
  , io = require('socket.io')
  , yaml = require('js-yaml')
  , glob = require('glob')
  , child = require('child_process');

var app = module.exports = express.createServer();

var parseConfig = function(filename) {
  return yaml.load(fs.readFileSync(filename, 'utf8'));
};

var config = parseConfig('./config/config.yml');

var logs = [];

for (var i=0; i < config.logs.length; i++) {
  files = glob.sync(config.logs[i]);

  for (var j=0; j < files.length; j++) {
    if (-1 == logs.indexOf(files[j])) {
      logs.push(files[j]);
    }
  };
};

var log_opts = [];

for (var i=0; i < logs.length; i++) {
  log_opts.push({idx: i, name: logs[i]});
};

// Configuration

app.helpers({
  log_opts: log_opts,
  config: config
});

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.basicAuth(config.user, config.pass));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

app.listen(config.port);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

var io = io.listen(app);
var processes = {};

io.sockets.on('connection', function(client) {

  var sessionId = client.sessionId;
  var stringdata = '';
  var restdata = '';

  processes[sessionId] = {
    active_log: null,
    tail: null
  }

  var emit_data = function(data, search) {
    stringdata = restdata + data;
    linedata = stringdata.substr(0, stringdata.lastIndexOf('\n')).split('\n');
    restdata = stringdata.substr(stringdata.lastIndexOf('\n') + 1);

    buffer = []
    for (var i=0; i < linedata.length; i++) {
      if (search && !linedata[i].match(search)) {
        continue;
      }
      buffer.push({ message: linedata[i] });
    };
    client.emit('buffer', { buffer: buffer });
    buffer = []
  };

  var tail_start = function(active, search) {
    var tail_opts = ["-f", "-n", 250, logs[active]];

    processes[sessionId].active_log = active;
    processes[sessionId].active_search = search;
    processes[sessionId].tail = child.spawn("tail", tail_opts);
    processes[sessionId].tail.stdout.on("data", function(data) {
        emit_data(data, search);
    });
  }

  var tail_stop = function() {
    if (processes[sessionId].tail !== null) processes[sessionId].tail.kill();
  }

  client.on('log_request', function(message) {
    var active = parseInt(message.log_file);
    var search = message.search;
    if (active !== processes[sessionId].active_log || search !== processes[sessionId].active_search) {
      tail_stop();
      client.emit('flush');
      tail_start(active, search);
    }
  });

  client.on('disconnect', function(){
    tail_stop();
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var pushitio = io.of('/push-it');
var github = require('./github');

app.use(express.static('public'));

app.get('/', function (req, res) {
    res.sendFile('index.html', { 'root': __dirname + '/public/' });
});

// Match: /[word]/[word] or /[word]/[word]/
app.get(/^\/\w+\/\w+\/?$/, function (req, res) {
    res.sendFile('push-it.html', { 'root': __dirname + '/public/' });
});

app.use(function(req, res, next) {
    res.status(404).sendFile('404.html', { 'root': __dirname + '/public/' });
});
var clients = {};

function clientsInRoom(nsp, room) {
    var clients = io.of(nsp).adapter.rooms[room];
    if (clients) {
        return Object.keys(clients).length;
    } else {
        return 0;
    }
}

pushitio.on('connection', function(socket){
    github.setActive(true);
    github.getCommits(function annoyEveryone() {
        pushitio.emit('push it', 'test');
    });

    socket.on('client connected', function (data) {
        console.log('Joining: %s', data.room);
        socket.join(data.room);
        console.log('%s clients in room %s', clientsInRoom('/push-it', data.room), data.room);
        console.log('%s roster:', data.room);
        for (var id in io.of('/push-it').adapter.rooms[data.room]) {
            console.log("    Client:" + io.of('/push-it').adapter.nsp.connected[id]);
        };
    });

    socket.on('disconnect', function (data) {
        github.setActive(false);
    });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

<commit_msg>Add server side validation for valid URI<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var pushitio = io.of('/push-it');
var github = require('./github');

app.use(express.static('public'));

app.get('/', function (req, res) {
    res.sendFile('index.html', { 'root': __dirname + '/public/' });
});

// Match: /[word]/[word] or /[word]/[word]/
app.get(/^\/\w+\/\w+\/?$/, function (req, res) {
    res.sendFile('push-it.html', { 'root': __dirname + '/public/' });
});

app.use(function(req, res, next) {
    res.status(404).sendFile('404.html', { 'root': __dirname + '/public/' });
});
var clients = {};

function clientsInRoom(nsp, room) {
    var clients = io.of(nsp).adapter.rooms[room];
    if (clients) {
        return Object.keys(clients).length;
    } else {
        return 0;
    }
}

pushitio.on('connection', function(socket){
    github.setActive(true);
    github.getCommits(function annoyEveryone() {
        pushitio.emit('push it', 'test');
    });

    socket.on('client connected', function (data) {
        if (data.room.match(/^\/\w+\/\w+\/?/)) {
            console.log('Someone probably tinkered with the client side code');
            return;
        }

        console.log('Joining: %s', data.room);
        socket.join(data.room);
        console.log('%s clients in room %s', clientsInRoom('/push-it', data.room), data.room);
        console.log('%s roster:', data.room);
        for (var id in io.of('/push-it').adapter.rooms[data.room]) {
            console.log("    Client:" + io.of('/push-it').adapter.nsp.connected[id]);
        };
    });

    socket.on('disconnect', function (data) {
        github.setActive(false);
    });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import { Platform } from 'react-native'

export const availableApplePayNetworks = [
  'american_express',
  'cartes_bancaires',
  'china_union_pay',
  'discover',
  'eftpos',
  'electron',
  'elo',
  'id_credit',
  'interac',
  'jcb',
  'mada',
  'maestro',
  'master_card',
  'private_label',
  'quic_pay',
  'suica',
  'visa',
  'vpay',
]
export const availableApplePayAddressFields = ['all', 'name', 'email', 'phone', 'postal_address']
export const availableApplePayShippingTypes = [
  'shipping',
  'delivery',
  'store_pickup',
  'service_pickup',
]
export const availableSourceTypes = [
  'bancontact',
  'giropay',
  'ideal',
  'sepaDebit',
  'sofort',
  'threeDSecure',
  'alipay',
  'card',
]

/** Keys are lower-cased slug|string */
export const brandToBrandSlugMapping = {
  unknown: 'unknown',
  amex: 'amex',
  diners: 'diners',
  discover: 'discover',
  jcb: 'jcb',
  mastercard: 'mastercard',
  unionpay: 'unionpay',
  visa: 'visa',

  'american express': 'amex',
  'diners club': 'diners',
}
export const exactBrandSlugs = new Set(Object.values(brandToBrandSlugMapping))
/** Keys are lower-cased slug|string */
export const brandToPresentableBrandStringMapping = {
  unknown: 'Unknown',
  amex: 'American Express',
  diners: 'Diners Club',
  discover: 'Discover',
  jcb: 'JCB',
  mastercard: 'MasterCard',
  unionpay: 'UnionPay',
  visa: 'Visa',

  'american express': 'American Express',
  'diners club': 'Diners Club',
}
export const exactPresentableBrandStrings = new Set(
  Object.values(brandToPresentableBrandStringMapping)
)

export const setOptionsOptionsPropTypes = {
  publishableKey: PropTypes.string,
  merchantId: PropTypes.string,
  androidPayMode: PropTypes.string,
}

export const availableApplePayNetworkPropTypes = PropTypes.oneOf(availableApplePayNetworks)

export const canMakeApplePayPaymentsOptionsPropTypes = {
  networks: PropTypes.arrayOf(availableApplePayNetworkPropTypes),
}
export const potentiallyAvailableNativePayPaymentsOptionsPropTypes = Platform.select({
  ios: {
    networks: PropTypes.arrayOf(availableApplePayNetworkPropTypes),
  },
  android: {},
})

export const paymentRequestWithApplePayItemPropTypes = {
  label: PropTypes.string.isRequired,
  amount: PropTypes.string.isRequired,
  type: PropTypes.oneOf(['final', 'pending']),
}

export const paymentRequestWithApplePayItemsPropTypes = {
  items: PropTypes.arrayOf(PropTypes.shape(paymentRequestWithApplePayItemPropTypes)).isRequired,
}

export const applePayAddressFieldsPropTypes = PropTypes.oneOf(availableApplePayAddressFields)

export const applePayOptionShippingMethodPropTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  detail: PropTypes.string.isRequired,
  amount: PropTypes.string.isRequired,
}

export const paymentRequestWithApplePayOptionsPropTypes = {
  currencyCode: PropTypes.string,
  countryCode: PropTypes.string,
  requiredBillingAddressFields: PropTypes.arrayOf(applePayAddressFieldsPropTypes),
  requiredShippingAddressFields: PropTypes.arrayOf(applePayAddressFieldsPropTypes),
  shippingMethods: PropTypes.arrayOf(PropTypes.shape(applePayOptionShippingMethodPropTypes)),
  shippingType: PropTypes.oneOf(availableApplePayShippingTypes),
}

export const paymentRequestWithCardFormOptionsPropTypes = {
  requiredBillingAddressFields: PropTypes.oneOf(['full', 'name', 'zip']),
  smsAutofillDisabled: PropTypes.bool,
  prefilledInformation: PropTypes.shape({
    email: PropTypes.string,
    phone: PropTypes.string,
    billingAddress: PropTypes.shape({
      name: PropTypes.string,
      line1: PropTypes.string,
      line2: PropTypes.string,
      city: PropTypes.string,
      state: PropTypes.string,
      postalCode: PropTypes.string,
      country: PropTypes.string,
      phone: PropTypes.string,
      email: PropTypes.string,
    }),
  }),
  theme: PropTypes.shape({
    primaryBackgroundColor: PropTypes.string,
    secondaryBackgroundColor: PropTypes.string,
    primaryForegroundColor: PropTypes.string,
    secondaryForegroundColor: PropTypes.string,
    accentColor: PropTypes.string,
    errorColor: PropTypes.string,
  }),
}

export const createTokenWithCardParamsPropTypes = {
  number: PropTypes.string.isRequired,
  expMonth: PropTypes.number.isRequired,
  expYear: PropTypes.number.isRequired,
  cvc: PropTypes.string,
  name: PropTypes.string,
  addressLine1: PropTypes.string,
  addressLine2: PropTypes.string,
  addressCity: PropTypes.string,
  addressState: PropTypes.string,
  addressZip: PropTypes.string,
  addressCountry: PropTypes.string,
  country: PropTypes.string,
  currency: PropTypes.string,

  // Android Only
  brand: PropTypes.string,
  last4: PropTypes.string,
  fingerprint: PropTypes.string,
  funding: PropTypes.string,
}

export const createTokenWithBankAccountParamsPropTypes = {
  accountNumber: PropTypes.string.isRequired,
  countryCode: PropTypes.string.isRequired,
  currency: PropTypes.string.isRequired,
  routingNumber: PropTypes.string,
  accountHolderName: PropTypes.string,
  accountHolderType: PropTypes.oneOf(['company', 'individual']),
}

export const androidPayLineItemPropTypes = {
  currency_code: PropTypes.string.isRequired,
  total_price: PropTypes.string.isRequired,
  unit_price: PropTypes.string.isRequired,
  quantity: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
}

export const paymentRequestWithAndroidPayOptionsPropTypes = {
  total_price: PropTypes.string.isRequired,
  currency_code: PropTypes.string.isRequired,
  line_items: PropTypes.arrayOf(PropTypes.shape(androidPayLineItemPropTypes)).isRequired,
  shipping_address_required: PropTypes.bool,
  billing_address_required: PropTypes.bool,
  email_address_required: PropTypes.bool,
}

export const createSourceWithParamsPropType = {
  type: PropTypes.oneOf(availableSourceTypes).isRequired,
  amount: PropTypes.number,
  name: PropTypes.string,
  returnURL: PropTypes.string,
  statementDescriptor: PropTypes.string,
  currency: PropTypes.string,
  email: PropTypes.string,
  bank: PropTypes.string,
  iban: PropTypes.string,
  addressLine1: PropTypes.string,
  city: PropTypes.string,
  postalCode: PropTypes.string,
  country: PropTypes.string,
  card: PropTypes.string,
  number: PropTypes.string,
  expMonth: PropTypes.number,
  expYear: PropTypes.number,
  cvc: PropTypes.string,
  addressCity: PropTypes.string,
  addressCountry: PropTypes.string,
  addressLine2: PropTypes.string,
  addressState: PropTypes.string,
  addressZip: PropTypes.string,
  brand: PropTypes.string,
  fingerprint: PropTypes.string,
  funding: PropTypes.string,
  id: PropTypes.string,
  last4: PropTypes.string,
}

// Corresponds to https://stripe.com/docs/api/payment_methods/create
export const createPaymentMethodPropType = {
  // BillingDetails properties:
  billingDetails: PropTypes.shape({
    address: PropTypes.shape({
      city: PropTypes.string,
      country: PropTypes.string,
      line1: PropTypes.string,
      line2: PropTypes.string,
      postalCode: PropTypes.string,
      state: PropTypes.string,
    }),
    email: PropTypes.string,
    name: PropTypes.string,
    phone: PropTypes.string,
  }),

  // Card properties:
  // - As an alternative to providing card PAN info, you can also provide a Stripe token:
  //   https://stripe.com/docs/api/payment_methods/create#create_payment_method-card
  card: PropTypes.oneOfType([
    PropTypes.shape({
      cvc: PropTypes.string,
      expMonth: PropTypes.number,
      expYear: PropTypes.number,
      number: PropTypes.string,
    }),
    PropTypes.shape({ token: PropTypes.string }),
  ]),

  // TODO: Add documentation for metadata (supported on iOS and Android)
  metadata: PropTypes.object,
  // TODO: customerId support
}

const confirmPaymentIntentPropTypeBase = {
  clientSecret: PropTypes.string.isRequired,
  savePaymentMethod: PropTypes.bool,
  returnURL: PropTypes.string,
}
/**
 * One of the following must be provided:
 * - paymentMethod
 * - paymentMethodId (any supported ID, including IDs for saved card sources)
 */
export const confirmPaymentIntentPropType = PropTypes.oneOfType([
  PropTypes.shape({
    ...confirmPaymentIntentPropTypeBase,
    paymentMethod: PropTypes.shape(createPaymentMethodPropType).isRequired,
  }),
  PropTypes.shape({
    ...confirmPaymentIntentPropTypeBase,
    paymentMethodId: PropTypes.string.isRequired,
  }),
]).isRequired

export const authenticatePaymentIntentPropType = {
  clientSecret: PropTypes.string.isRequired,
  returnURL: PropTypes.string,
}

const confirmSetupIntentPropTypeBase = {
  clientSecret: PropTypes.string.isRequired,
  returnURL: PropTypes.string,
}
/**
 * One of the following must be provided:
 * - paymentMethod
 * - paymentMethodId (any supported ID, including IDs for saved card sources)
 */
export const confirmSetupIntentPropType = PropTypes.oneOfType([
  PropTypes.shape({
    ...confirmSetupIntentPropTypeBase,
    paymentMethod: PropTypes.shape(createPaymentMethodPropType),
  }),
  PropTypes.shape({ ...confirmSetupIntentPropTypeBase, paymentMethodId: PropTypes.string }),
]).isRequired

export const authenticateSetupIntentPropType = {
  clientSecret: PropTypes.string.isRequired,
  returnURL: PropTypes.string,
}
<commit_msg>PropTypes: Allow omitting paymentMethod/paymentMethodId on confirmPaymentIntent<commit_after>import PropTypes from 'prop-types'
import { Platform } from 'react-native'

export const availableApplePayNetworks = [
  'american_express',
  'cartes_bancaires',
  'china_union_pay',
  'discover',
  'eftpos',
  'electron',
  'elo',
  'id_credit',
  'interac',
  'jcb',
  'mada',
  'maestro',
  'master_card',
  'private_label',
  'quic_pay',
  'suica',
  'visa',
  'vpay',
]
export const availableApplePayAddressFields = ['all', 'name', 'email', 'phone', 'postal_address']
export const availableApplePayShippingTypes = [
  'shipping',
  'delivery',
  'store_pickup',
  'service_pickup',
]
export const availableSourceTypes = [
  'bancontact',
  'giropay',
  'ideal',
  'sepaDebit',
  'sofort',
  'threeDSecure',
  'alipay',
  'card',
]

/** Keys are lower-cased slug|string */
export const brandToBrandSlugMapping = {
  unknown: 'unknown',
  amex: 'amex',
  diners: 'diners',
  discover: 'discover',
  jcb: 'jcb',
  mastercard: 'mastercard',
  unionpay: 'unionpay',
  visa: 'visa',

  'american express': 'amex',
  'diners club': 'diners',
}
export const exactBrandSlugs = new Set(Object.values(brandToBrandSlugMapping))
/** Keys are lower-cased slug|string */
export const brandToPresentableBrandStringMapping = {
  unknown: 'Unknown',
  amex: 'American Express',
  diners: 'Diners Club',
  discover: 'Discover',
  jcb: 'JCB',
  mastercard: 'MasterCard',
  unionpay: 'UnionPay',
  visa: 'Visa',

  'american express': 'American Express',
  'diners club': 'Diners Club',
}
export const exactPresentableBrandStrings = new Set(
  Object.values(brandToPresentableBrandStringMapping)
)

export const setOptionsOptionsPropTypes = {
  publishableKey: PropTypes.string,
  merchantId: PropTypes.string,
  androidPayMode: PropTypes.string,
}

export const availableApplePayNetworkPropTypes = PropTypes.oneOf(availableApplePayNetworks)

export const canMakeApplePayPaymentsOptionsPropTypes = {
  networks: PropTypes.arrayOf(availableApplePayNetworkPropTypes),
}
export const potentiallyAvailableNativePayPaymentsOptionsPropTypes = Platform.select({
  ios: {
    networks: PropTypes.arrayOf(availableApplePayNetworkPropTypes),
  },
  android: {},
})

export const paymentRequestWithApplePayItemPropTypes = {
  label: PropTypes.string.isRequired,
  amount: PropTypes.string.isRequired,
  type: PropTypes.oneOf(['final', 'pending']),
}

export const paymentRequestWithApplePayItemsPropTypes = {
  items: PropTypes.arrayOf(PropTypes.shape(paymentRequestWithApplePayItemPropTypes)).isRequired,
}

export const applePayAddressFieldsPropTypes = PropTypes.oneOf(availableApplePayAddressFields)

export const applePayOptionShippingMethodPropTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  detail: PropTypes.string.isRequired,
  amount: PropTypes.string.isRequired,
}

export const paymentRequestWithApplePayOptionsPropTypes = {
  currencyCode: PropTypes.string,
  countryCode: PropTypes.string,
  requiredBillingAddressFields: PropTypes.arrayOf(applePayAddressFieldsPropTypes),
  requiredShippingAddressFields: PropTypes.arrayOf(applePayAddressFieldsPropTypes),
  shippingMethods: PropTypes.arrayOf(PropTypes.shape(applePayOptionShippingMethodPropTypes)),
  shippingType: PropTypes.oneOf(availableApplePayShippingTypes),
}

export const paymentRequestWithCardFormOptionsPropTypes = {
  requiredBillingAddressFields: PropTypes.oneOf(['full', 'name', 'zip']),
  smsAutofillDisabled: PropTypes.bool,
  prefilledInformation: PropTypes.shape({
    email: PropTypes.string,
    phone: PropTypes.string,
    billingAddress: PropTypes.shape({
      name: PropTypes.string,
      line1: PropTypes.string,
      line2: PropTypes.string,
      city: PropTypes.string,
      state: PropTypes.string,
      postalCode: PropTypes.string,
      country: PropTypes.string,
      phone: PropTypes.string,
      email: PropTypes.string,
    }),
  }),
  theme: PropTypes.shape({
    primaryBackgroundColor: PropTypes.string,
    secondaryBackgroundColor: PropTypes.string,
    primaryForegroundColor: PropTypes.string,
    secondaryForegroundColor: PropTypes.string,
    accentColor: PropTypes.string,
    errorColor: PropTypes.string,
  }),
}

export const createTokenWithCardParamsPropTypes = {
  number: PropTypes.string.isRequired,
  expMonth: PropTypes.number.isRequired,
  expYear: PropTypes.number.isRequired,
  cvc: PropTypes.string,
  name: PropTypes.string,
  addressLine1: PropTypes.string,
  addressLine2: PropTypes.string,
  addressCity: PropTypes.string,
  addressState: PropTypes.string,
  addressZip: PropTypes.string,
  addressCountry: PropTypes.string,
  country: PropTypes.string,
  currency: PropTypes.string,

  // Android Only
  brand: PropTypes.string,
  last4: PropTypes.string,
  fingerprint: PropTypes.string,
  funding: PropTypes.string,
}

export const createTokenWithBankAccountParamsPropTypes = {
  accountNumber: PropTypes.string.isRequired,
  countryCode: PropTypes.string.isRequired,
  currency: PropTypes.string.isRequired,
  routingNumber: PropTypes.string,
  accountHolderName: PropTypes.string,
  accountHolderType: PropTypes.oneOf(['company', 'individual']),
}

export const androidPayLineItemPropTypes = {
  currency_code: PropTypes.string.isRequired,
  total_price: PropTypes.string.isRequired,
  unit_price: PropTypes.string.isRequired,
  quantity: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
}

export const paymentRequestWithAndroidPayOptionsPropTypes = {
  total_price: PropTypes.string.isRequired,
  currency_code: PropTypes.string.isRequired,
  line_items: PropTypes.arrayOf(PropTypes.shape(androidPayLineItemPropTypes)).isRequired,
  shipping_address_required: PropTypes.bool,
  billing_address_required: PropTypes.bool,
  email_address_required: PropTypes.bool,
}

export const createSourceWithParamsPropType = {
  type: PropTypes.oneOf(availableSourceTypes).isRequired,
  amount: PropTypes.number,
  name: PropTypes.string,
  returnURL: PropTypes.string,
  statementDescriptor: PropTypes.string,
  currency: PropTypes.string,
  email: PropTypes.string,
  bank: PropTypes.string,
  iban: PropTypes.string,
  addressLine1: PropTypes.string,
  city: PropTypes.string,
  postalCode: PropTypes.string,
  country: PropTypes.string,
  card: PropTypes.string,
  number: PropTypes.string,
  expMonth: PropTypes.number,
  expYear: PropTypes.number,
  cvc: PropTypes.string,
  addressCity: PropTypes.string,
  addressCountry: PropTypes.string,
  addressLine2: PropTypes.string,
  addressState: PropTypes.string,
  addressZip: PropTypes.string,
  brand: PropTypes.string,
  fingerprint: PropTypes.string,
  funding: PropTypes.string,
  id: PropTypes.string,
  last4: PropTypes.string,
}

// Corresponds to https://stripe.com/docs/api/payment_methods/create
export const createPaymentMethodPropType = {
  // BillingDetails properties:
  billingDetails: PropTypes.shape({
    address: PropTypes.shape({
      city: PropTypes.string,
      country: PropTypes.string,
      line1: PropTypes.string,
      line2: PropTypes.string,
      postalCode: PropTypes.string,
      state: PropTypes.string,
    }),
    email: PropTypes.string,
    name: PropTypes.string,
    phone: PropTypes.string,
  }),

  // Card properties:
  // - As an alternative to providing card PAN info, you can also provide a Stripe token:
  //   https://stripe.com/docs/api/payment_methods/create#create_payment_method-card
  card: PropTypes.oneOfType([
    PropTypes.shape({
      cvc: PropTypes.string,
      expMonth: PropTypes.number,
      expYear: PropTypes.number,
      number: PropTypes.string,
    }),
    PropTypes.shape({ token: PropTypes.string }),
  ]),

  // TODO: Add documentation for metadata (supported on iOS and Android)
  metadata: PropTypes.object,
  // TODO: customerId support
}

const confirmPaymentIntentPropTypeBase = {
  clientSecret: PropTypes.string.isRequired,
  savePaymentMethod: PropTypes.bool,
  returnURL: PropTypes.string,
}
/**
 * One of the following may be provided
 * - paymentMethod
 * - paymentMethodId (any supported ID, including IDs for saved card sources)
 *
 * If you don't provide these, then you're required to attach the paymentMethod
 *  on your backend before you call this API.
 */
export const confirmPaymentIntentPropType = PropTypes.oneOfType([
  PropTypes.shape({
    ...confirmPaymentIntentPropTypeBase,
    paymentMethod: PropTypes.shape(createPaymentMethodPropType),
  }),
  PropTypes.shape({
    ...confirmPaymentIntentPropTypeBase,
    paymentMethodId: PropTypes.string,
  }),
]).isRequired

export const authenticatePaymentIntentPropType = {
  clientSecret: PropTypes.string.isRequired,
  returnURL: PropTypes.string,
}

const confirmSetupIntentPropTypeBase = {
  clientSecret: PropTypes.string.isRequired,
  returnURL: PropTypes.string,
}
/**
 * One of the following must be provided:
 * - paymentMethod
 * - paymentMethodId (any supported ID, including IDs for saved card sources)
 */
export const confirmSetupIntentPropType = PropTypes.oneOfType([
  PropTypes.shape({
    ...confirmSetupIntentPropTypeBase,
    paymentMethod: PropTypes.shape(createPaymentMethodPropType).isRequired,
  }),
  PropTypes.shape({
    ...confirmSetupIntentPropTypeBase,
    paymentMethodId: PropTypes.string.isRequired,
  }),
]).isRequired

export const authenticateSetupIntentPropType = {
  clientSecret: PropTypes.string.isRequired,
  returnURL: PropTypes.string,
}
<|endoftext|>


<commit_before>const express = require('express');
const app = express();

const fs = require('fs');
const path = require('path');

const Compile = require('udmdcompiler');
const comp = new Compile();

// Run the markdown compiler
comp.process('./md', './public');

// App routing set here

/**
 * Class for setup of the routing for the application
 * @type {Handlers}
 * @example
 * const Handler = new Handlers();
 * Handler.generateYaml('./public', './md');
 */
class Handlers {

  /**
   * Gets the recursive folder/file structure of the filedest to pass to writeYaml
   * @param  {string} filedest location of the files to generate the app.yaml
   * @param  {string} src      source files built from e.g. md files
   * @example
   *  generateYaml(filedest, src){
   *   var yamlfiles = comp.getrecursivestructure(filedest);
   *   var destfiles = [];
   *   for (var i = 0; i < yamlfiles.length; i++) {
   *     if (yamlfiles[i].endsWith('.html')) {
   *       destfiles.push(yamlfiles[i]);
   *     }
   *   }
   *   this.writeYaml( destfiles );
   *  }
   */
  generateYaml(filedest, src){

    var yamlfiles = comp.getrecursivestructure(filedest);
    var destfiles = [];
    for (var i = 0; i < yamlfiles.length; i++) {
      if (yamlfiles[i].endsWith('.html')) {
        destfiles.push(yamlfiles[i]);
      }
    }

    this.writeYaml( destfiles );

  }

  /**
   * Writes the app.yaml file, using an array of line items and the appyamlcontents array
   * @param  {array} appyamlcontents array of valid files for adding to the routing app.yaml file
   * @return {file} app.yaml in the root directory
   * @example
   * writeYaml(appyamlcontents){
   *
   *  var handlerstructure = [];
   *
   *  handlerstructure.push('runtime: nodejs');
   *  handlerstructure.push('env: flex');
   *  handlerstructure.push('\nhandlers:');
   *  handlerstructure.push( appyamlcontents.join('\n') );
   *
   *  fs.writeFile('app.yaml', handlerstructure.join('\n'), (err) => {
   *    if (err) throw err;
   *    console.log('The file has been saved!');
   *   });
   *
   * }
   */
  writeYaml(appyamlcontents){

    var handlerstructure = [];
    handlerstructure.push('runtime: nodejs');
    handlerstructure.push('env: flex');
    handlerstructure.push('\nhandlers:');
    handlerstructure.push('- url:', appyamlcontents.join('\n') );

    fs.writeFile('app.yaml', handlerstructure.join('\n'), (err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });
  }

}

const Handler = new Handlers();
Handler.generateYaml('./public', './md');

// Internal handling is not required, this is running on google app engine, handling via app.yaml
// app.get('/', function (req, res) {
//   res.send('Hello World!')
// });
//
// app.get('/another.html', function (req, res) {
//   res.sendFile(path.join(__dirname, 'public', 'another.html'));
// });

/**
 * app listener on port 3000
 * @example
 *  app.listen(3000, function () {
 *    console.log('udhost app listening on port 3000!');
 *  });
 */
app.listen(3000, function () {
  console.log('udhost app listening on port 3000!');
});
<commit_msg>fixed app.yaml routing<commit_after>const express = require('express');
const app = express();

const fs = require('fs');
const path = require('path');

const Compile = require('udmdcompiler');
const comp = new Compile();

// Run the markdown compiler
comp.process('./md', './public');

// App routing set here

/**
 * Class for setup of the routing for the application
 * @type {Handlers}
 * @example
 * const Handler = new Handlers();
 * Handler.generateYaml('./public', './md');
 */
class Handlers {

  /**
   * Gets the recursive folder/file structure of the filedest to pass to writeYaml
   * @param  {string} filedest location of the files to generate the app.yaml
   * @param  {string} src      source files built from e.g. md files
   * @example
   *  generateYaml(filedest, src){
   *   var yamlfiles = comp.getrecursivestructure(filedest);
   *   var destfiles = [];
   *   for (var i = 0; i < yamlfiles.length; i++) {
   *     if (yamlfiles[i].endsWith('.html')) {
   *       destfiles.push(yamlfiles[i]);
   *     }
   *   }
   *   this.writeYaml( destfiles );
   *  }
   */
  generateYaml(filedest, src){

    var yamlfiles = comp.getrecursivestructure(filedest);
    var destfiles = [];
    for (var i = 0; i < yamlfiles.length; i++) {
      if (yamlfiles[i].endsWith('.html')) {
        destfiles.push('- url: ' + yamlfiles[i] + '\n');
      }
    }

    this.writeYaml( destfiles );

  }

  /**
   * Writes the app.yaml file, using an array of line items and the appyamlcontents array
   * @param  {array} appyamlcontents array of valid files for adding to the routing app.yaml file
   * @return {file} app.yaml in the root directory
   * @example
   * writeYaml(appyamlcontents){
   *
   *  var handlerstructure = [];
   *
   *  handlerstructure.push('runtime: nodejs');
   *  handlerstructure.push('env: flex');
   *  handlerstructure.push('\nhandlers:');
   *  handlerstructure.push( appyamlcontents.join('\n') );
   *
   *  fs.writeFile('app.yaml', handlerstructure.join('\n'), (err) => {
   *    if (err) throw err;
   *    console.log('The file has been saved!');
   *   });
   *
   * }
   */
  writeYaml(appyamlcontents){

    var handlerstructure = [];
    handlerstructure.push('runtime: nodejs');
    handlerstructure.push('env: flex');
    handlerstructure.push('\nhandlers:\n');
    handlerstructure.push(appyamlcontents.join('\n') );

    fs.writeFile('app.yaml', handlerstructure.join('\n'), (err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });
  }

}

const Handler = new Handlers();
Handler.generateYaml('./public', './md');

// Internal handling is not required, this is running on google app engine, handling via app.yaml
// app.get('/', function (req, res) {
//   res.send('Hello World!')
// });
//
// app.get('/another.html', function (req, res) {
//   res.sendFile(path.join(__dirname, 'public', 'another.html'));
// });

/**
 * app listener on port 3000
 * @example
 *  app.listen(3000, function () {
 *    console.log('udhost app listening on port 3000!');
 *  });
 */
app.listen(3000, function () {
  console.log('udhost app listening on port 3000!');
});
<|endoftext|>