httprint.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """httprint - print files via web
  4. Copyright 2019 Davide Alberani <da@mimante.net>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import os
  15. import re
  16. import time
  17. import glob
  18. import random
  19. import shutil
  20. import logging
  21. import subprocess
  22. import multiprocessing as mp
  23. from tornado.ioloop import IOLoop
  24. import tornado.httpserver
  25. import tornado.options
  26. from tornado.options import define, options
  27. import tornado.web
  28. from tornado import gen, escape
  29. API_VERSION = '1.0'
  30. QUEUE_DIR = 'queue'
  31. ARCHIVE = True
  32. ARCHIVE_DIR = 'archive'
  33. PRINT_CMD = ['lp', '-n', '%(copies)s']
  34. CODE_DIGITS = 4
  35. MAX_PAGES = 10
  36. PRINT_WITH_CODE = True
  37. logger = logging.getLogger()
  38. logger.setLevel(logging.INFO)
  39. re_pages = re.compile('^Pages:\s+(\d+)$', re.M | re.I)
  40. class HTTPrintBaseException(Exception):
  41. """Base class for httprint custom exceptions.
  42. :param message: text message
  43. :type message: str
  44. :param status: numeric http status code
  45. :type status: int"""
  46. def __init__(self, message, status=400):
  47. super(HTTPrintBaseException, self).__init__(message)
  48. self.message = message
  49. self.status = status
  50. class BaseHandler(tornado.web.RequestHandler):
  51. """Base class for request handlers."""
  52. # A property to access the first value of each argument.
  53. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  54. for k, v in self.request.arguments.items()]))
  55. @property
  56. def clean_body(self):
  57. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  58. :returns: a clean copy of the body arguments
  59. :rtype: dict"""
  60. return escape.json_decode(self.request.body or '{}')
  61. def write_error(self, status_code, **kwargs):
  62. """Default error handler."""
  63. if isinstance(kwargs.get('exc_info', (None, None))[1], HTTPrintBaseException):
  64. exc = kwargs['exc_info'][1]
  65. status_code = exc.status
  66. message = exc.message
  67. else:
  68. message = 'internal error'
  69. self.build_error(message, status=status_code)
  70. def initialize(self, **kwargs):
  71. """Add every passed (key, value) as attributes of the instance."""
  72. for key, value in kwargs.items():
  73. setattr(self, key, value)
  74. def build_error(self, message='', status=400):
  75. """Build and write an error message.
  76. :param message: textual message
  77. :type message: str
  78. :param status: HTTP status code
  79. :type status: int
  80. """
  81. self.set_status(status)
  82. self.write({'error': True, 'message': message})
  83. def build_success(self, message='', status=200):
  84. """Build and write a success message.
  85. :param message: textual message
  86. :type message: str
  87. :param status: HTTP status code
  88. :type status: int
  89. """
  90. self.set_status(status)
  91. self.write({'error': False, 'message': message})
  92. def _run(self, cmd, fname):
  93. p = subprocess.Popen(cmd, close_fds=True)
  94. p.communicate()
  95. if self.cfg.archive:
  96. if not os.path.isdir(self.cfg.archive_dir):
  97. os.makedirs(self.cfg.archive_dir)
  98. for fn in glob.glob(fname + '*'):
  99. shutil.move(fn, self.cfg.archive_dir)
  100. for fn in glob.glob(fname + '*'):
  101. try:
  102. os.unlink(fn)
  103. except Exception:
  104. pass
  105. def run_subprocess(self, cmd, fname):
  106. """Execute the given action.
  107. :param cmd: the command to be run with its command line arguments
  108. :type cmd: list
  109. """
  110. p = mp.Process(target=self._run, args=(cmd, fname))
  111. p.start()
  112. def print_file(self, fname):
  113. copies = 1
  114. try:
  115. with open(fname + '.copies', 'r') as fd:
  116. copies = int(fd.read())
  117. if copies < 1:
  118. copies = 1
  119. except Exception:
  120. pass
  121. cmd = [x % {'copies': copies} for x in PRINT_CMD] + [fname]
  122. self.run_subprocess(cmd, fname)
  123. class PrintHandler(BaseHandler):
  124. """File print handler."""
  125. @gen.coroutine
  126. def post(self, code=None):
  127. if not code:
  128. self.build_error("empty code")
  129. return
  130. files = [x for x in sorted(glob.glob(self.cfg.queue_dir + '/%s-*' % code))
  131. if not x.endswith('.info') and not x.endswith('.pages')]
  132. if not files:
  133. self.build_error("no matching files")
  134. return
  135. self.print_file(files[0])
  136. self.build_success("file sent to printer")
  137. class UploadHandler(BaseHandler):
  138. """File upload handler."""
  139. def generateCode(self):
  140. filler = '%0' + str(self.cfg.code_digits) + 'd'
  141. existing = set()
  142. re_code = re.compile('(\d{' + str(self.cfg.code_digits) + '})-.*')
  143. for fname in glob.glob(self.cfg.queue_dir + '/*'):
  144. fname = os.path.basename(fname)
  145. match = re_code.match(fname)
  146. if not match:
  147. continue
  148. fcode = match.group(1)
  149. existing.add(fcode)
  150. code = None
  151. for i in range(10**self.cfg.code_digits):
  152. intCode = random.randint(0, (10**self.cfg.code_digits)-1)
  153. code = filler % intCode
  154. if code not in existing:
  155. break
  156. return code
  157. @gen.coroutine
  158. def post(self):
  159. if not self.request.files.get('file'):
  160. self.build_error("no file uploaded")
  161. return
  162. copies = 1
  163. try:
  164. copies = int(self.get_argument('copies'))
  165. if copies < 1:
  166. copies = 1
  167. except Exception:
  168. pass
  169. if copies > self.cfg.max_pages:
  170. self.build_error('you have asked too many copies')
  171. return
  172. fileinfo = self.request.files['file'][0]
  173. webFname = fileinfo['filename']
  174. extension = ''
  175. try:
  176. extension = os.path.splitext(webFname)[1]
  177. except Exception:
  178. pass
  179. if not os.path.isdir(self.cfg.queue_dir):
  180. os.makedirs(self.cfg.queue_dir)
  181. now = time.strftime('%Y%m%d%H%M%S')
  182. code = self.generateCode()
  183. fname = '%s-%s%s' % (code, now, extension)
  184. pname = os.path.join(self.cfg.queue_dir, fname)
  185. try:
  186. with open(pname, 'wb') as fd:
  187. fd.write(fileinfo['body'])
  188. except Exception as e:
  189. self.build_error("error writing file %s: %s" % (pname, e))
  190. return
  191. try:
  192. with open(pname + '.info', 'w') as fd:
  193. fd.write('original file name: %s\n' % webFname)
  194. fd.write('uploaded on: %s\n' % now)
  195. fd.write('copies: %d\n' % copies)
  196. except Exception:
  197. pass
  198. try:
  199. with open(pname + '.copies', 'w') as fd:
  200. fd.write('%d' % copies)
  201. except Exception:
  202. pass
  203. failure = False
  204. if self.cfg.check_pdf_pages or self.cfg.pdf_only:
  205. try:
  206. p = subprocess.Popen(['pdfinfo', pname], stdout=subprocess.PIPE)
  207. out, _ = p.communicate()
  208. if p.returncode != 0 and self.cfg.pdf_only:
  209. self.build_error('the uploaded file does not seem to be a PDF')
  210. failure = True
  211. out = out.decode('utf-8', errors='ignore')
  212. pages = int(re_pages.findall(out)[0])
  213. if pages * copies > self.cfg.max_pages and self.cfg.check_pdf_pages and not failure:
  214. self.build_error('too many pages to print (%d)' % (pages * copies))
  215. failure = True
  216. except Exception:
  217. if not failure:
  218. self.build_error('unable to get PDF information')
  219. failure = True
  220. pass
  221. if failure:
  222. for fn in glob.glob(pname + '*'):
  223. try:
  224. os.unlink(fn)
  225. except Exception:
  226. pass
  227. return
  228. if self.cfg.print_with_code:
  229. self.build_success("go to the printer and enter this code: %s" % code)
  230. else:
  231. self.print_file(pname)
  232. self.build_success("file sent to printer")
  233. class TemplateHandler(BaseHandler):
  234. """Handler for the template files in the / path."""
  235. @gen.coroutine
  236. def get(self, *args, **kwargs):
  237. """Get a template file."""
  238. page = 'index.html'
  239. if args and args[0]:
  240. page = args[0].strip('/')
  241. arguments = self.arguments
  242. self.render(page, **arguments)
  243. def serve():
  244. """Read configuration and start the server."""
  245. define('port', default=7777, help='run on the given port', type=int)
  246. define('address', default='', help='bind the server at the given address', type=str)
  247. define('ssl_cert', default=os.path.join(os.path.dirname(__file__), 'ssl', 'httprint_cert.pem'),
  248. help='specify the SSL certificate to use for secure connections')
  249. define('ssl_key', default=os.path.join(os.path.dirname(__file__), 'ssl', 'httprint_key.pem'),
  250. help='specify the SSL private key to use for secure connections')
  251. define('code-digits', default=CODE_DIGITS, help='number of digits of the code', type=int)
  252. define('max-pages', default=MAX_PAGES, help='maximum number of pages to print', type=int)
  253. define('queue-dir', default=QUEUE_DIR, help='directory to store files before they are printed', type=str)
  254. define('archive', default=True, help='archive printed files', type=bool)
  255. define('archive-dir', default=ARCHIVE_DIR, help='directory to archive printed files', type=str)
  256. define('print-with-code', default=True, help='a code must be entered for printing', type=bool)
  257. define('pdf-only', default=True, help='only print PDF files', type=bool)
  258. define('check-pdf-pages', default=True, help='check that the number of pages of PDF files do not exeed --max-pages', type=bool)
  259. define('debug', default=False, help='run in debug mode', type=bool)
  260. tornado.options.parse_command_line()
  261. if options.debug:
  262. logger.setLevel(logging.DEBUG)
  263. ssl_options = {}
  264. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  265. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  266. init_params = dict(listen_port=options.port, logger=logger, ssl_options=ssl_options, cfg=options)
  267. _upload_path = r'upload/?'
  268. _print_path = r'print/(?P<code>\d+)'
  269. application = tornado.web.Application([
  270. (r'/api/%s' % _upload_path, UploadHandler, init_params),
  271. (r'/api/v%s/%s' % (API_VERSION, _upload_path), UploadHandler, init_params),
  272. (r'/api/%s' % _print_path, PrintHandler, init_params),
  273. (r'/api/v%s/%s' % (API_VERSION, _print_path), PrintHandler, init_params),
  274. (r'/?(.*)', TemplateHandler, init_params),
  275. ],
  276. static_path=os.path.join(os.path.dirname(__file__), 'dist/static'),
  277. template_path=os.path.join(os.path.dirname(__file__), 'dist/'),
  278. debug=options.debug)
  279. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  280. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  281. options.address if options.address else '127.0.0.1',
  282. options.port)
  283. http_server.listen(options.port, options.address)
  284. try:
  285. IOLoop.instance().start()
  286. except (KeyboardInterrupt, SystemExit):
  287. pass
  288. if __name__ == '__main__':
  289. serve()