1. ronald martinez
  2. find-gift

Source

find-gift / controllers / __init__.py

import cPickle
import settings
import memcache
import logging
import urllib
import simplejson

from models import User
from tornado.web import RequestHandler
from sqlalchemy import orm, create_engine

engine = create_engine(settings.DATABASE_DSN)
Session = orm.sessionmaker(bind=engine)()

Memcached = memcache.Client(
    settings.MEMCACHED_SERVERS,
    debug=settings.MEMCACHED_DEBUG
)


class BaseHandler(RequestHandler):

    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)

    @property
    def user_data_facebook(self):

        cookie = self.get_secure_cookie('user')

        if not cookie:
            return None
        else:
            return cPickle.loads(cookie)

    def get_current_user(self):

        cookie = self.get_secure_cookie('user')

        if not cookie:
            return None
        else:

            try:
                cookie_user = cPickle.loads(cookie)
            except Exception as exc:
                logging.error(exc)
                return None
            else:

                return Session.query(User).filter_by(
                    fbid=cookie_user.get('user_id')).first()

    def render_string(self, template, **kwargs):

        kwargs.update({'handler': self})

        return self.settings.get('template_env')\
            .get_template(template).render(**kwargs)

    def render(self, template, **kwargs):

        self.finish(self.render_string(template, **kwargs))


class Facebook(object):

    def get_info(self, access_token, user_id):

        params = dict(
            access_token=access_token,
            fields='email,birthday,gender,name'
        )

        url = '%s/%s' % (settings.FACEBOOK_GRAPH, user_id)

        try:
            data = urllib.urlopen('%s?%s' % (
                url, urllib.urlencode(params))).read()
            return simplejson.loads(data)

        except Exception as exc:
            logging.error(exc)
            return None

    def get_friends(self, access_token, user_id, limit, page):

        def pagination(limit, page):

            if page.isdigit():
                page = int(page)
            else:
                page = 1

            offset = ((page - 1) * limit)

            return (limit, offset)

        limit, offset = pagination(limit, page)

        print offset

        params = dict(
            access_token=access_token,
            fields='name',
            limit=limit,
            offset=offset
        )

        url = '%s/%s/friends' % (settings.FACEBOOK_GRAPH, user_id)

        try:
            data = urllib.urlopen('%s?%s' % (
                url, urllib.urlencode(params))).read()
            return simplejson.loads(data)

        except Exception as exc:
            logging.error(exc)
            return None

    def search_in_wall_keys(self, access_token, friend_id, search_items):

        def sql_multiquery_kwords(friend_id, search_items):

            q = None
            tmp_queries = []

            for x in search_items:

                sku = x.sku
                keywords = x.keywords.split(',')

                kwors = ''
                tmp_keywords_sql = []

                for k in keywords:

                    tmp_keywords_sql.append(
                        "strpos(lower(message), '%s') >= 0" % k.lower())

                if tmp_keywords_sql:
                    kwors = ' or '.join(tmp_keywords_sql)
                    kwors = ' and (%s)' % kwors

                tmp_queries.append(
                    '"%s": "select uid from status where uid=%s %s"' % (
                        sku, friend_id, kwors))

            if tmp_queries:
                url = ','.join(tmp_queries)
                q = '{%s}' % url

                #logging.info('q: %s' % q)

            return {'q': q, 'tmp_queries': tmp_queries}

        q = sql_multiquery_kwords(friend_id, search_items)

        if not q.get('tmp_queries'):
            return None
        else:
            params = dict(
                q=q.get('q'),
                access_token=access_token
            )

            url = '%s/fql' % settings.FACEBOOK_GRAPH

            logging.info('%s?%s' % (
                    url, urllib.urlencode(params)))

            try:
                data = urllib.urlopen('%s?%s' % (
                    url, urllib.urlencode(params))).read()
                return simplejson.loads(data)

            except Exception as exc:
                logging.error(exc)
                return None