92 lines
2.8 KiB
Python
Executable File
92 lines
2.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from flask import Flask, jsonify, request, send_from_directory
|
|
import tempfile
|
|
import subprocess
|
|
import os
|
|
import sys
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route('/')
|
|
def helloWorld():
|
|
return "Hi! Please check usage docs.\n"
|
|
|
|
|
|
@app.route('/status')
|
|
def getStatus():
|
|
PRINTER_HOST = os.environ.get("PRINTER_HOST")
|
|
return jsonify({"status": "OK", "printer_host": PRINTER_HOST})
|
|
|
|
|
|
def getFile(tmpDir):
|
|
if request.files.get('file', None):
|
|
f = request.files['file']
|
|
infile = tmpDir.name + '/' + f.name
|
|
f.save(infile)
|
|
elif request.form.get('smbfile'):
|
|
smbhost = request.form.get('smbhost', None)
|
|
smbuser = request.form.get('smbuser', None)
|
|
smbpass = request.form.get('smbpass', None)
|
|
smbworkgroup = request.form.get('smbworkgroup', None)
|
|
smbshare = request.form.get('smbshare', None)
|
|
smbdir = request.form.get('smbdir', None)
|
|
smbfile = request.form.get('smbfile', None)
|
|
v = [ smbhost, smbuser, smbpass, smbworkgroup, smbshare, smbdir, smbfile ]
|
|
if (all(v)):
|
|
os.chdir(tmpDir.name)
|
|
r = subprocess.run(['smbclient',
|
|
'--user', smbuser,
|
|
'--workgroup', smbworkgroup,
|
|
'--directory', smbdir,
|
|
'--command', 'get "%s"' % (smbfile),
|
|
'//%s/%s' % (smbhost, smbshare),
|
|
smbpass ] )
|
|
if r.returncode != 0:
|
|
return None
|
|
infile = tmpDir.name + '/' + smbfile
|
|
else:
|
|
return None
|
|
return infile
|
|
|
|
|
|
@app.route('/convert/pdf', methods=["POST"])
|
|
def toPDF():
|
|
tmpDir = tempfile.TemporaryDirectory()
|
|
infile = getFile(tmpDir)
|
|
pdffile = infile + '.pdf'
|
|
|
|
r = subprocess.run(['/usr/bin/unoconv', '--output', pdffile, infile])
|
|
if r.returncode != 0:
|
|
return jsonify({"status": "conversion error"})
|
|
|
|
return send_from_directory(directory=tmpDir.name,
|
|
filename=os.path.basename(pdffile),
|
|
mimetype='application/pdf',
|
|
as_attachment=True)
|
|
|
|
|
|
@app.route('/print', methods=["POST"])
|
|
def print():
|
|
PRINTER_HOST = os.environ.get("PRINTER_HOST")
|
|
if not PRINTER_HOST:
|
|
raise ValueError("You have to set the PRINTER_HOST environment variable")
|
|
|
|
tmpDir = tempfile.TemporaryDirectory()
|
|
infile = getFile(tmpDir)
|
|
|
|
unoconv = subprocess.Popen(['/usr/bin/unoconv','--stdout',infile], stdout=subprocess.PIPE)
|
|
pdf2ps = subprocess.Popen(['/usr/bin/pdf2ps','-','-'], stdin=unoconv.stdout, stdout=subprocess.PIPE)
|
|
unoconv.wait()
|
|
unoconv.stdout.close()
|
|
printer = subprocess.Popen(['/usr/bin/nc','-w','1', PRINTER_HOST,'9100'], stdin=pdf2ps.stdout)
|
|
pdf2ps.wait()
|
|
pdf2ps.stdout.close()
|
|
printer.wait()
|
|
|
|
return jsonify({"status": "ok"})
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(port=6000)
|