Commits

jayon ayon committed b5ddabc

first commit

Comments (0)

Files changed (4)

+from datetime import datetime
+import mongoengine as me
+
+
+class User(me.Document):
+
+    nick = me.StringField(
+        required=True,
+        unique=True,
+        min_length=5,
+        max_length=10
+    )
+
+    password = me.StringField(
+        required=True,
+        min_length=4,
+        max_length=4
+    )
+
+    access_token = me.DictField()
+    user_id = me.StringField()
+    created_at = me.DateTimeField(default=datetime.now)
+    updated_at = me.DateTimeField()
+
+    meta = {
+        'collection': 'users',
+        'indexes': [
+            'nick',
+            '-created_at'
+        ]
+    }
+mongoengine==0.6.10
+pymongo==2.2
+tornado==2.3
+wsgiref==0.1.2
+import logging
+import settings
+
+import cPickle
+
+
+import tornado.ioloop
+from tornado.httpserver import HTTPServer
+from tornado.options import define, options
+from tornado.web import RequestHandler, Application, asynchronous, url
+from tornado.auth import TwitterMixin
+
+from models import *
+from mongoengine import *
+
+
+class Favorite(RequestHandler, TwitterMixin):
+
+    @asynchronous
+    def get(self):
+        id = self.get_argument('id', None)
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+
+        if not nick or not password:
+            self.finish(dict(status_code=1))
+
+        user = User.objects(
+            nick=nick,
+            password=password
+        ).first()
+
+        if not user:
+            raise tornado.web.HTTPError(500, "Twitter App auth failed")
+        else:
+            self.twitter_request(
+                "/favorites/create/%s" % id,
+                post_args={'a': 'b'},
+                access_token=user.access_token,
+                callback=self.async_callback(self._on_post)
+            )
+
+    def _on_post(self, new_entry):
+
+        self.set_header("Access-Control-Allow-Origin", "*")
+        if not new_entry:
+            self.write(dict(status_code=1))
+            return
+        self.finish(dict(status_code=0))
+
+
+class DirectMesaage(RequestHandler, TwitterMixin):
+
+    @asynchronous
+    def get(self):
+        screen_name = self.get_argument('screen_name', None)
+        message = self.get_argument('message', None)
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+
+        user = User.objects(
+            nick=nick,
+            password=password
+        ).first()
+
+        if not user:
+            raise tornado.web.HTTPError(500, "Twitter App auth failed")
+        else:
+            self.twitter_request(
+                "/direct_messages/new",
+                post_args={'screen_name': screen_name, 'text': message},
+                access_token=user.access_token,
+                callback=self.async_callback(self._on_post)
+            )
+
+    def _on_post(self, new_entry):
+        if not new_entry:
+            self.write('not send message')
+            return
+        self.finish("send direct message!")
+
+
+class Timeline(RequestHandler, TwitterMixin):
+
+    @asynchronous
+    def get(self):
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+        since_id = self.get_argument('since_id', None)
+        count = self.get_argument('count', 5)
+
+        send_data = {}
+
+        get_args = {'count': count}
+
+        if since_id:
+            get_args.update({'since_id': since_id})
+
+        if not nick or not password:
+            send_data['status_code'] = 4
+            send_data['message'] = 'invalid parameters'
+            self.finish(send_data)
+
+        user = User.objects(nick=nick, password=password).first()
+
+        self.set_header("Access-Control-Allow-Origin", "*")
+
+        if not user:
+            send_data['status_code'] = 1
+            send_data['message'] = 'twitter auth failed'
+            self.finish(send_data)
+        else:
+            try:
+                self.twitter_request(
+                    "/statuses/home_timeline",
+                    access_token=user.access_token,
+                    callback=self.async_callback(self._on_post),
+                    **get_args
+                )
+            except Exception as exc:
+                send_data['status_code'] = 2
+                send_data['message'] = str(exc)
+                self.finish(send_data)
+
+    def _on_post(self, data):
+        send_data = {}
+
+        if not data:
+            send_data['status_code'] = 3
+            send_data['message'] = 'not timeline user'
+            self.finish(send_data)
+            return
+
+        data_json = []
+        for twitt in data:
+            data_json.append(dict(
+                id_str=twitt.get('id_str'),
+                id_int=twitt.get('id'),
+                profile_image_url_https=twitt
+                    .get('user').get('profile_image_url_https'),
+                from_user_id=twitt.get('user').get('id_str'),
+                from_user_name=twitt.get('user').get('name'),
+                from_user=twitt.get('user').get('screen_name'),
+                text=twitt.get('text'),
+                created_at=twitt.get('created_at')
+            ))
+
+        self.set_header("Content-Type", "text/json")
+
+        send_data['status_code'] = 0
+        send_data['data'] = data_json
+        self.finish(send_data)
+
+
+class Retwit(RequestHandler, TwitterMixin):
+
+    @asynchronous
+    def get(self):
+        twitter_id = self.get_argument('id', None)
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+
+        user = User.objects(
+            nick=nick,
+            password=password
+        ).first()
+
+        if not user:
+            raise tornado.web.HTTPError(500, "Twitter App auth failed")
+        else:
+            self.twitter_request(
+                "/statuses/retweet/" + twitter_id,
+                post_args={'a': 'b'},
+                access_token=user.access_token,
+                callback=self.async_callback(self._on_post)
+            )
+
+    def _on_post(self, new_entry):
+        self.set_header("Access-Control-Allow-Origin", "*")
+        if not new_entry:
+            self.write(dict(status_code=1))
+            return
+        self.finish(dict(status_code=0))
+
+
+class Twit(RequestHandler, TwitterMixin):
+
+    @asynchronous
+    def get(self):
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+        message = self.get_argument('message', None)
+        reply_id = self.get_argument('reply_id', None)
+
+        send_data = {}
+
+        if not nick or not password or not message:
+            send_data['status_code'] = 4
+            send_data['message'] = 'invalid parameters'
+            self.finish(send_data)
+
+        user = User.objects(nick=nick, password=password).first()
+
+        self.set_header("Access-Control-Allow-Origin", "*")
+
+        if not user:
+            send_data['status_code'] = 1
+            send_data['message'] = 'twitter auth failed'
+            self.finish(send_data)
+        else:
+            post_args = {}
+            post_args['status'] = message.encode('utf-8')
+
+            if reply_id:
+                post_args['in_reply_to_status_id'] = reply_id
+
+            try:
+                self.twitter_request(
+                    "/statuses/update",
+                    post_args=post_args,
+                    access_token=user.access_token,
+                    callback=self.async_callback(self._on_post)
+                )
+            except Exception as exc:
+                send_data['status_code'] = 2
+                send_data['message'] = str(exc)
+                self.finish(send_data)
+
+    def _on_post(self, new_entry):
+        send_data = {}
+
+        if not new_entry:
+            send_data['status_code'] = 3
+            send_data['message'] = 'cant not post'
+            self.finish(send_data)
+            return
+
+        send_data['status_code'] = 0
+        send_data['message'] = 'send post'
+        self.finish(send_data)
+
+
+class Auth(RequestHandler):
+
+    def get(self):
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+
+        send_data = {}
+
+        if not nick or not password:
+            send_data['status_code'] = 1
+            send_data['message'] = 'twitter auth failed'
+            send_data['token'] = ''
+            self.finish(send_data)
+
+        user = User.objects(
+            nick=nick,
+            password=password
+        ).first()
+
+        self.set_header("Access-Control-Allow-Origin", "*")
+
+        if not user:
+            send_data['status_code'] = 1
+            send_data['message'] = 'twitter auth failed'
+            send_data['token'] = ''
+            self.finish(send_data)
+        else:
+            send_data['status_code'] = 0
+            send_data['message'] = 'ok'
+            send_data['token'] = user.access_token
+            self.finish(send_data)
+
+
+class TwitterApp(RequestHandler):
+
+    def get(self):
+        nick = self.get_argument('nick', None)
+        password = self.get_argument('password', None)
+
+        send_data = {}
+
+        if not nick or not password:
+            send_data['status_code'] = 1
+            send_data['message'] = 'twitter auth failed'
+            self.finish(send_data)
+
+        user = User.objects(
+            nick=nick,
+            password=password
+        ).first()
+
+        if user:
+            access_token = user.access_token
+            self.write(
+                'usuario existe con token: %s' % access_token.get('key')
+            )
+        else:
+            data = cPickle.dumps({
+                'nick': nick,
+                'password': password
+            }, -1)
+
+            self.set_secure_cookie("twitter_user", str(data))
+            self.redirect(self.reverse_url('twitter_handler'))
+
+
+class TwitterHandler(RequestHandler, TwitterMixin):
+
+    @asynchronous
+    def get(self):
+        if self.get_argument("oauth_token", None):
+            self.get_authenticated_user(self.async_callback(self._on_auth))
+            return
+
+        self.authorize_redirect()
+
+    def _on_auth(self, data_user):
+        if not data_user:
+            raise tornado.web.HTTPError(500, "Twitter auth failed")
+
+        try:
+            data_user = data_user.get('access_token')
+            data_user_cookie = cPickle.loads(
+                self.get_secure_cookie('twitter_user')
+            )
+
+            self.clear_cookie("twitter_user")
+
+            check_account_twiiter_user = User.objects(
+                user_id=data_user.get('user_id')
+            ).first()
+
+            if check_account_twiiter_user:
+                self.write("""los datos ingresados ya estan
+                 asociados a una cuenta de twitter""")
+            else:
+                user = User()
+                user.access_token = data_user
+                user.user_id = data_user.get('user_id')
+                user.nick = data_user_cookie.get('nick')
+                user.password = data_user_cookie.get('password')
+                user.save()
+                self.write('El usuario se grabo!')
+        except Exception as exc:
+            #print "dsdsd"
+            self.write(str(exc))
+
+        self.finish()
+        return
+
+
+def main():
+    global_settings = dict((setting.lower(), getattr(settings, setting))
+        for setting in dir(settings) if setting.isupper())
+
+    define('port', type=int, default=8888)
+    define('host', type=str, default='127.0.0.1')
+
+    application = Application(
+        handlers=(
+            url('/twit', Twit),
+            url('/retwit', Retwit),
+            url('/direct_message', DirectMesaage),
+            url('/auth', Auth),
+            url('/twitter_app', TwitterApp),
+            url('/twitter_handler', TwitterHandler, name='twitter_handler'),
+            url('/timeline', Timeline),
+            url('/favorite', Favorite),
+        ), **global_settings
+    )
+
+    tornado.options.parse_command_line()
+    http_server = HTTPServer(application, xheaders=True)
+    http_server.listen(options.port, options.host)
+
+    try:
+        me.connect(**global_settings['mongo'])
+    except Exception, e:
+        import sys
+        logging.error(e)
+        sys.exit()
+
+    try:
+        tornado.ioloop.IOLoop.instance().start()
+    except KeyboardInterrupt:
+        tornado.ioloop.IOLoop.instance().stop()
+
+
+if __name__ == '__main__':
+    main()
+DEBUG = False
+XSRF_COOKIES = False
+
+VIDEOS_PER_PAGE = 8
+VIDEOS_TOTAL_PAGES = 5
+
+#MEMCACHED_SERVERS = ['127.0.0.1:11211']
+#MEMCACHED_DEBUG = True
+#MEMCACHED_TIMEOUTS_VIDEOS = 3600
+
+TWITTER_CONSUMER_KEY = 'UyBx5NVpGMiQJgh0jU1Kug'
+TWITTER_CONSUMER_SECRET = 'g32evW2ytcz70iUFoYQlqbMu93WabJCQvCMlFs3Pb9U'
+
+COOKIE_SECRET = 'msd44543444'
+
+MONGO = {
+    'db': 'smart_twit',
+    'username': None,
+    'password': None,
+    'host': '127.0.0.1',
+    'port': 27017
+}
+
+try:
+    from local_settings import *
+except ImportError:
+    pass
+