3 Commits 26a8a9dc8b ... 7cec835d88

Author SHA1 Message Date
  Davide Alberani 7cec835d88 back-end error logging 5 years ago
  Davide Alberani 3f31fbe67d front-end error handling 5 years ago
  Davide Alberani d9740938b9 visible countdown 5 years ago
4 changed files with 46 additions and 14 deletions
  1. 4 0
      static/css/sb.css
  2. 1 1
      static/index.html
  3. 15 2
      static/js/sb.js
  4. 26 11
      toot-my-t-shirt

+ 4 - 0
static/css/sb.css

@@ -29,6 +29,10 @@
     z-index: 10000;
 }
 
+#sb-countdown {
+    min-width: 20px;
+}
+
 .btn {
     margin-right: 10px;
 }

+ 1 - 1
static/index.html

@@ -34,7 +34,7 @@
 
             <div class="row">
                 <div id="sb-message">
-                    <span id="sb-message-text">will be gone in few seconds!</span>
+                    <span id="sb-message-text">will be gone in few seconds! <span id="sb-countdown">&nbsp;</span></span>
                 </div>
                 <div id="canvas-container">
                     <video id="sb-video" autoplay="true" muted="muted"></video>

+ 15 - 2
static/js/sb.js

@@ -75,12 +75,24 @@ function sendData(data) {
             msg = "something went wrong sending the data: " + response.status;
             console.log(msg);
             M.toast({"html": msg});
+        }
+        cancelPhoto();
+        return response.json();
+    }).then(function(json) {
+        json = json || {};
+        console.log(json);
+        if (json && json.success) {
+            msg = "❤ ❤ ❤ photo sent successfully! ❤ ❤ ❤";
+            console.log(msg);
+            M.toast({"html": msg});
         } else {
-            msg = "photo was sent successfully!";
+            msg = "😭 😭 😭 something wrong on the backend 😭 😭 😭";
+            console.log(msg);
+            M.toast({"html": msg});
+            msg = "the server says: " + json.message;
             console.log(msg);
             M.toast({"html": msg});
         }
-        cancelPhoto();
     }).catch(function(err) {
         msg = "something went wrong connecting to server: " + err;
         console.log(msg);
@@ -103,6 +115,7 @@ function cancelPhoto() {
 
 
 function updateSendCountdown() {
+    document.querySelector("#sb-countdown").innerText = "" + countdown.seconds;
     console.log("deleting photo in " + countdown.seconds + " seconds");
 }
 

+ 26 - 11
toot-my-t-shirt

@@ -34,8 +34,9 @@ API_VERSION = '1.0'
 
 
 class Socialite:
-    def __init__(self, options):
+    def __init__(self, options, logger=None):
         self.options = options
+        self.logger = logger
         self.init()
 
     with_mastodon = property(lambda self: self.options.mastodon_token and
@@ -53,14 +54,25 @@ class Socialite:
                                      api_base_url=self.options.mastodon_api_url)
 
     def post_image(self, img, mime_type='image/jpeg', message=None, description=None):
+        errors = []
         if message is None:
             message = self.options.default_message
         if description is None:
             description = self.options.default_image_description
         if self.with_store:
-            self.store_image(img, mime_type, message, description)
+            try:
+                self.store_image(img, mime_type, message, description)
+            except Exception as e:
+                errors.append(str(e))
         if self.with_mastodon:
-            self.mastodon_post_image(img, mime_type, message, description)
+            try:
+                self.mastodon_post_image(img, mime_type, message, description)
+            except Exception as e:
+                errors.append(str(e))
+        if errors and self.logger:
+            for err in errors:
+                self.logger.error("ERROR: %s" % err)
+        return errors
 
     def mastodon_post_image(self, img, mime_type, message, description):
         mdict = self.mastodon.media_post(media_file=img, mime_type=mime_type, description=description)
@@ -75,7 +87,6 @@ class Socialite:
                 suffix = '.' + ms[1]
         prefix = str(datetime.datetime.now()).replace(' ', 'T') + '-'
         fd, fname = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=self.options.store_dir)
-        print(fd, fname)
         os.write(fd, img)
         os.close(fd)
         txt_fname = '%s.info' % fname
@@ -91,7 +102,7 @@ class BaseException(Exception):
     :type message: str
     :param status: numeric http status code
     :type status: int"""
-    def __init__(self, message, status=400):
+    def __init__(self, message, status=200):
         super(BaseException, self).__init__(message)
         self.message = message
         self.status = status
@@ -136,7 +147,7 @@ class BaseHandler(tornado.web.RequestHandler):
         for key, value in kwargs.items():
             setattr(self, key, value)
 
-    def build_error(self, message='', status=400):
+    def build_error(self, message='', status=200):
         """Build and write an error message.
 
         :param message: textual message
@@ -145,7 +156,7 @@ class BaseHandler(tornado.web.RequestHandler):
         :type status: int
         """
         self.set_status(status)
-        self.write({'error': True, 'message': message})
+        self.write({'success': False, 'message': message})
 
 
 class RootHandler(BaseHandler):
@@ -168,9 +179,13 @@ class PublishHandler(BaseHandler):
             body = info['body']
             b64_image = body.split(b',')[1]
             image = base64.decodestring(b64_image)
-            with open('/tmp/selfie.jpeg', 'wb') as fd:
-                fd.write(image)
-            self.socialite.post_image(image)
+            try:
+                errors = self.socialite.post_image(image)
+                if errors:
+                    reply['success'] = False
+                    reply['message'] = '<br>\n'.join(errors)
+            except Exception as e:
+                reply = {'success': False, 'message': 'something wrong sharing the image'}
         self.write(reply)
 
 
@@ -208,7 +223,7 @@ def run():
     if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
         ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
 
-    socialite = Socialite(options)
+    socialite = Socialite(options, logger=logger)
     init_params = dict(global_options=options, socialite=socialite)
 
     _publish_path = r"/publish/?"