openmedialibrary/oml/item/handlers.py

97 lines
3.1 KiB
Python
Raw Normal View History

2014-05-19 22:50:41 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
from __future__ import division, with_statement
import os
import zipfile
import mimetypes
from datetime import datetime
import tornado.web
from models import Item
import settings
class OMLHandler(tornado.web.RequestHandler):
def initialize(self, app):
self._app = app
class EpubHandler(OMLHandler):
def get(self, id, filename):
with self._app.app_context():
item = Item.get(id)
path = item.get_path()
if not item or item.info['extension'] != 'epub' or not path:
self.set_status(404)
self.write('')
else:
z = zipfile.ZipFile(path)
if filename == '':
self.write('<br>\n'.join([f.filename for f in z.filelist]))
elif filename not in [f.filename for f in z.filelist]:
self.set_status(404)
self.write('')
else:
content_type = {
'xpgt': 'application/vnd.adobe-page-template+xml'
}.get(filename.split('.')[0], mimetypes.guess_type(filename)[0]) or 'text/plain'
self.set_header('Content-Type', content_type)
self.write(z.read(filename))
self.finish()
2014-05-25 20:32:00 +00:00
def serve_static(handler, path, mimetype, include_body=True):
2014-05-21 23:06:08 +00:00
#fixme use static file handler / serve ranges
2014-05-19 22:50:41 +00:00
handler.set_header('Content-Type', mimetype)
2014-05-21 23:06:08 +00:00
handler.set_header('Content-Length', str(os.stat(path).st_size))
2014-05-25 20:32:00 +00:00
if include_body:
with open(path) as fd:
handler.write(fd.read())
2014-05-19 22:50:41 +00:00
handler.finish()
return
class FileHandler(OMLHandler):
2014-05-25 20:32:00 +00:00
def head(self, id):
self.get(id, include_body=False)
def get(self, id, include_body=True):
2014-05-19 22:50:41 +00:00
with self._app.app_context():
item = Item.get(id)
2014-05-25 20:32:00 +00:00
path = item.get_path() if item else None
if not item or not path:
2014-05-19 22:50:41 +00:00
self.set_status(404)
self.finish()
return
mimetype={
'epub': 'application/epub+zip',
'pdf': 'application/pdf',
2014-05-21 23:06:08 +00:00
'txt': 'text/plain',
2014-05-19 22:50:41 +00:00
}.get(path.split('.')[-1], None)
2014-05-25 20:32:00 +00:00
return serve_static(self, path, mimetype, include_body)
2014-05-19 22:50:41 +00:00
class ReaderHandler(OMLHandler):
def get(self, id):
with self._app.app_context():
item = Item.get(id)
if not item:
self.set_status(404)
self.finish()
return
if item.info['extension'] == 'epub':
html = 'html/epub.html'
elif item.info['extension'] == 'pdf':
html = 'html/pdf.html'
elif item.info['extension'] == 'txt':
html = 'html/txt.html'
else:
self.set_status(404)
self.finish()
return
item.accessed = datetime.utcnow()
item.timesaccessed = (item.timesaccessed or 0) + 1
item.update_sort()
2014-05-19 22:50:41 +00:00
item.save()
return serve_static(self, os.path.join(settings.static_path, html), 'text/html')