toot-my-t-shirt 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """toot-my-t-shirt
  4. Copyright 2018 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 base64
  16. import logging
  17. import tempfile
  18. import datetime
  19. import tornado.httpserver
  20. import tornado.ioloop
  21. from tornado.options import define, options
  22. import tornado.web
  23. from tornado import gen, escape
  24. from mastodon import Mastodon
  25. API_VERSION = '1.0'
  26. class Socialite:
  27. def __init__(self, options, logger=None):
  28. self.options = options
  29. self.logger = logger
  30. self.init()
  31. with_mastodon = property(lambda self: self.options.mastodon_token and
  32. self.options.mastodon_api_url)
  33. with_store = property(lambda self: bool(self.options.store_dir))
  34. def init(self):
  35. self.mastodon = None
  36. if self.with_store:
  37. if not os.path.isdir(self.options.store_dir):
  38. os.makedirs(self.options.store_dir)
  39. if self.with_mastodon:
  40. self.mastodon = Mastodon(access_token=self.options.mastodon_token,
  41. api_base_url=self.options.mastodon_api_url)
  42. def post_image(self, img, mime_type='image/jpeg', message=None, description=None):
  43. errors = []
  44. if message is None:
  45. message = self.options.default_message
  46. if description is None:
  47. description = self.options.default_image_description
  48. if self.with_store:
  49. try:
  50. self.store_image(img, mime_type, message, description)
  51. except Exception as e:
  52. errors.append(str(e))
  53. if self.with_mastodon:
  54. try:
  55. self.mastodon_post_image(img, mime_type, message, description)
  56. except Exception as e:
  57. errors.append(str(e))
  58. if errors and self.logger:
  59. for err in errors:
  60. self.logger.error("ERROR: %s" % err)
  61. return errors
  62. def mastodon_post_image(self, img, mime_type, message, description):
  63. mdict = self.mastodon.media_post(media_file=img, mime_type=mime_type, description=description)
  64. media_id = mdict['id']
  65. self.mastodon.status_post(status=message, media_ids=[media_id])
  66. def store_image(self, img, mime_type, message, description):
  67. suffix = '.jpg'
  68. if mime_type:
  69. ms = mime_type.split('/', 1)
  70. if len(ms) == 2 and ms[1]:
  71. suffix = '.' + ms[1]
  72. prefix = str(datetime.datetime.now()).replace(' ', 'T') + '-'
  73. fd, fname = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=self.options.store_dir)
  74. os.write(fd, img)
  75. os.close(fd)
  76. txt_fname = '%s.info' % fname
  77. with open(txt_fname, 'w') as tfd:
  78. tfd.write('message: %s\n' % message or '')
  79. tfd.write('description: %s\n' % description or '')
  80. class BaseException(Exception):
  81. """Base class for toot-my-t-shirt custom exceptions.
  82. :param message: text message
  83. :type message: str
  84. :param status: numeric http status code
  85. :type status: int"""
  86. def __init__(self, message, status=200):
  87. super(BaseException, self).__init__(message)
  88. self.message = message
  89. self.status = status
  90. class InputException(BaseException):
  91. """Exception raised by errors in input handling."""
  92. pass
  93. class BaseHandler(tornado.web.RequestHandler):
  94. """Base class for request handlers."""
  95. # A property to access the first value of each argument.
  96. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  97. for k, v in self.request.arguments.items()]))
  98. @property
  99. def json_body(self):
  100. """Return a dictionary from a JSON body.
  101. :returns: a copy of the body arguments
  102. :rtype: dict"""
  103. return escape.json_decode(self.request.body or '{}')
  104. def write_error(self, status_code, **kwargs):
  105. """Default error handler."""
  106. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  107. exc = kwargs['exc_info'][1]
  108. status_code = exc.status
  109. message = exc.message
  110. else:
  111. message = 'internal error'
  112. self.build_error(message, status=status_code)
  113. def is_api(self):
  114. """Return True if the path is from an API call."""
  115. return self.request.path.startswith('/v%s' % API_VERSION)
  116. def initialize(self, **kwargs):
  117. """Add every passed (key, value) as attributes of the instance."""
  118. for key, value in kwargs.items():
  119. setattr(self, key, value)
  120. def build_error(self, message='', status=200):
  121. """Build and write an error message.
  122. :param message: textual message
  123. :type message: str
  124. :param status: HTTP status code
  125. :type status: int
  126. """
  127. self.set_status(status)
  128. self.write({'success': False, 'message': message})
  129. class RootHandler(BaseHandler):
  130. """Handler for the / path."""
  131. app_path = os.path.join(os.path.dirname(__file__), "static")
  132. @gen.coroutine
  133. def get(self, *args, **kwargs):
  134. # serve the ./static/index.html file
  135. with open(self.app_path + "/index.html", 'r') as fd:
  136. self.write(fd.read())
  137. class PublishHandler(BaseHandler):
  138. @gen.coroutine
  139. def post(self, **kwargs):
  140. reply = {'success': True}
  141. for info in self.request.files['selfie']:
  142. _, content_type = info['filename'], info['content_type']
  143. body = info['body']
  144. b64_image = body.split(b',')[1]
  145. image = base64.decodestring(b64_image)
  146. try:
  147. errors = self.socialite.post_image(image)
  148. if errors:
  149. reply['success'] = False
  150. reply['message'] = '<br>\n'.join(errors)
  151. except Exception as e:
  152. reply = {'success': False, 'message': 'something wrong sharing the image'}
  153. self.write(reply)
  154. def run():
  155. """Run the Tornado web application."""
  156. # command line arguments; can also be written in a configuration file,
  157. # specified with the --config argument.
  158. define("port", default=9000, help="listen on the given port", type=int)
  159. define("address", default='', help="bind the server at the given address", type=str)
  160. define("default-message", help="Default message", type=str)
  161. define("default-image-description", help="Default image description", type=str)
  162. define("mastodon-token", help="Mastodon token", type=str)
  163. define("mastodon-api-url", help="Mastodon API URL", type=str)
  164. define("store-dir", help="store images in this directory", type=str)
  165. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'sb-cert.pem'),
  166. help="specify the SSL certificate to use for secure connections")
  167. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'sb-cert.key'),
  168. help="specify the SSL private key to use for secure connections")
  169. define("debug", default=False, help="run in debug mode")
  170. define("config", help="read configuration file",
  171. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  172. tornado.options.parse_command_line()
  173. logger = logging.getLogger()
  174. logger.setLevel(logging.INFO)
  175. if options.debug:
  176. logger.setLevel(logging.DEBUG)
  177. ssl_options = {}
  178. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  179. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  180. socialite = Socialite(options, logger=logger)
  181. init_params = dict(global_options=options, socialite=socialite)
  182. _publish_path = r"/publish/?"
  183. application = tornado.web.Application([
  184. (_publish_path, PublishHandler, init_params),
  185. (r'/v%s%s' % (API_VERSION, _publish_path), PublishHandler, init_params),
  186. (r"/(?:index.html)?", RootHandler, init_params),
  187. (r'/?(.*)', tornado.web.StaticFileHandler, {"path": "static"})
  188. ],
  189. static_path=os.path.join(os.path.dirname(__file__), "static"),
  190. debug=options.debug)
  191. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  192. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  193. options.address if options.address else '127.0.0.1',
  194. options.port)
  195. http_server.listen(options.port, options.address)
  196. tornado.ioloop.IOLoop.instance().start()
  197. if __name__ == '__main__':
  198. try:
  199. run()
  200. except KeyboardInterrupt:
  201. print('Server stopped')