server.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import base64
  2. import datetime
  3. import hashlib
  4. import os
  5. from subprocess import Popen, PIPE
  6. import tornado.ioloop
  7. import tornado.web
  8. from tornado.options import define, options
  9. import xattr
  10. class MainHandler(tornado.web.RequestHandler):
  11. def get(self, arg, head=False):
  12. if not arg:
  13. self.redirect("/post.html")
  14. path = os.path.join('files',arg)
  15. try:
  16. with open(path,"rb") as f:
  17. attrs = xattr.xattr(f)
  18. self.set_header("Expires", datetime.datetime.utcnow() + datetime.timedelta(1000000))
  19. if 'user.Content-Type' in attrs:
  20. self.set_header("Content-Type", attrs['user.Content-Type'].decode('utf-8'))
  21. try:
  22. orig_filename = attrs.get('user.filename').decode('utf-8')
  23. self.set_header('Content-Disposition',' inline; filename="{}"'.format(orig_filename))
  24. except IOError:
  25. pass
  26. self.set_header('content-length',os.stat(f.fileno()).st_size)
  27. if head:
  28. self.finish()
  29. return
  30. self.write(f.read())
  31. self.finish()
  32. except IOError:
  33. raise tornado.web.HTTPError(404)
  34. def head(self, arg):
  35. self.get(arg, head=True)
  36. def post(self, arg):
  37. file_body = self.request.arguments.get('data')[0]
  38. if not file_body:
  39. self.finish()
  40. return
  41. filename = base64.urlsafe_b64encode(hashlib.sha256(file_body).digest()).decode('utf-8')
  42. with open(os.path.join('files', filename), "wb") as f:
  43. f.write(file_body)
  44. attrs = xattr.xattr(f)
  45. mimetype = Popen(["file", "-b","--mime-type", f.name], stdout=PIPE).communicate()[0].decode('utf8').strip()
  46. attrs['user.Content-Type'] = mimetype.encode('utf-8')
  47. self.write('<html><body><a href="http://h45h.com/{}"></body></html>{}'.format(filename,filename))
  48. def put(self, arg):
  49. filename = base64.urlsafe_b64encode(hashlib.sha256(self.request.body).digest()).decode('utf-8')
  50. with open(os.path.join('files',filename),"wb") as f:
  51. f.write(self.request.body)
  52. attrs = xattr.xattr(f)
  53. mimetype = Popen(["file", "-b","--mime-type", f.name], stdout=PIPE).communicate()[0].decode('utf8').strip()
  54. attrs['user.Content-Type'] = mimetype.encode('utf-8')
  55. attrs['user.filename'] = arg.encode('utf-8')
  56. self.write('http://h45h.com/{}\n'.format(filename))
  57. application = tornado.web.Application([
  58. (r"/(.*\.html)", tornado.web.StaticFileHandler, dict(path=os.path.join(os.path.dirname(__file__)))),
  59. (r"/(.*)", MainHandler),
  60. ], debug=True)
  61. if __name__ == "__main__":
  62. tornado.options.parse_command_line()
  63. path = os.path.join(os.path.join(os.path.dirname(__file__)), 'files')
  64. if not os.path.exists(path):
  65. os.makedirs(path)
  66. application.listen(8888)
  67. tornado.ioloop.IOLoop.instance().start()