Commits

ronald martinez committed ff42714

okk

Comments (0)

Files changed (1)

 import simplejson
 import cPickle
 import datetime
+import time
 
 from models import User
 
-from tornado import gen
 from controllers import Session, BaseHandler
 from tornado.web import HTTPError, asynchronous
 from tornado.httpclient import AsyncHTTPClient
 
 
+from tornado.ioloop import IOLoop
+
+
 def get_age(date_of_birth):
 
     tmp = None
     def check_xsrf_cookie(self):
         pass
 
+    def _on_ok(self):
+        print "ok"
+        return
+
+    def _on_update_user(self):
+
+        cookie = self.get_secure_cookie('user')
+        user_data_facebook = cPickle.loads(cookie) if cookie else None
+
+        if not user_data_facebook:
+            raise HTTPError(500)
+
+        user = Session.query(User).filter_by(
+            fbid=user_data_facebook.get('user_id'))
+
+        if not user.first():
+
+            params = dict(
+                access_token=user_data_facebook.get('access_token'),
+                fields='email,birthday,gender,name'
+            )
+
+            url = '%s?%s' % (
+                '%s/%s' % (
+                    settings.FACEBOOK_GRAPH,
+                    user_data_facebook.get('user_id')
+                ),
+                 urllib.urlencode(params)
+            )
+
+            http_client = AsyncHTTPClient()
+            http_client.fetch(url, self.on_update_user)
+
+        else:
+
+            try:
+                user.update({'access_token': user_data_facebook.get(
+                    'access_token')})
+            except Exception as exc:
+                logging.error(exc)
+            else:
+                logging.info('update user token')
+
     @asynchronous
-    @gen.engine
     def post(self):
 
         signed_request = self.get_argument('signed_request', None)
 
             self.set_secure_cookie('user', data)
 
+            IOLoop.instance().add_timeout(
+                time.time() + 5,
+                self._on_update_user
+            )
+
+            """
             user = Session.query(User).filter_by(
                 fbid=user_data_facebook.get('user_id'))
 
                     logging.error(exc)
                 else:
                     logging.info('update user token')
+            """
 
             self.redirect(self.reverse_url('list_friends'))
 
         )
 
         self.render('index.html', data=data.get('data'))
-
-