summaryrefslogtreecommitdiff
path: root/modules/pdfrotate/pdfrotate.js
blob: 92f8eb160cdb01278bc30364de2250e496e17282 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
var cmn=require("../$common.js"),
    fs=require("fs"),
    child_process=require("child_process"),
    multer=require("multer"),
    mkdirp=require("mkdirp");

var moddir;

var uniqid=(function(){
	var id=0;
	return function uniqid(){return id++;};
})();

function clearDirectory(path){
	var entries=fs.readdirSync(path);
	for(var i=0;i<entries.length;i++){
		fs.unlinkSync(path+"/"+entries[i]);
	}
}

function cleanUpDir(path){
	var nowtime=new Date().getTime();
	var entries=fs.readdirSync(path);
	for(var i=0;i<entries.length;i++){
		var stat=fs.statSync(path+"/"+entries[i]);
		if(stat.mtime-nowtime>30*60*1000){
			fs.unlink(path+"/"+entries[i],function(err){});
		}
	}
}

// Clear files older than 30 mins every 30 mins
setInterval(function(){
	process.nextTick(function(){cleanUpDir(moddir+"/uploads");});
	process.nextTick(function(){cleanUpDir(moddir+"/converted");});
},30*60*1000);

module.exports=function(app,io,_moddir){
	moddir=_moddir;

	mkdirp.sync(moddir+"/uploads");
	mkdirp.sync(moddir+"/converted");
	clearDirectory(moddir+"/uploads");

	var multerupload=multer({
		storage: multer.diskStorage({
			destination: function(req,file,cb){
				cb(null,moddir+"/uploads/");
			},
			filename: function(req,file,cb){
				cb(null,uniqid()+".pdf");
			}
		}),
		limits: {
			files: 1,
			fileSize: 100*1024*1024
		}
	});

	app.get("/pdfrotate",function(req,res){
		res.sendFile(moddir+"/index.html");
	});
	app.post("/pdfrotate/upload",multerupload.single("file"),function(req,res){
		if(!req.file){
			res.sendFile(moddir+"/index.html");
			return;
		}
		var origname=req.file.originalname;
		var path=req.file.path;
		var rot=req.body.rotgroup+"";
		if(rot=="rot0"){
			fs.unlink(path,function(err){});
			res.redirect("/pdfrotate?err=rot0");
			return;
		}

		var cmd;
		switch(rot){
			case "rot90": cmd="pdf90"; break;
			case "rot180": cmd="pdf180"; break;
			case "rot270": cmd="pdf270"; break;
			default:
				fs.unlink(path,function(err){});
				res.redirect("/pdfrotate?err=invrot");
				return;
		}

		var outfile=moddir+"/converted/"+uniqid()+".pdf";

		child_process.execFile(cmd,[path,"-o",outfile],function(err,stdout,stderr){
			if(err){
				console.log(err);
				res.redirect("/pdfrotate?err=pdfjamerr");
				return;
			}
			var newname=origname.replace(/\.pdf$/,"_rotated.pdf");
			res.download(outfile,newname,function(err){
				fs.unlink(path,function(err){});
				fs.unlink(outfile,function(err){});
			});
		});
	});
	app.get("/pdfrotate/upload",function(req,res){
		res.redirect("/pdfrotate");
	});
};