Esempio n. 1
0
    def get_timeline(self, format_="json", reqnum=200, type_=0, contenttype=0, pagetime=0, pageflag=0):
        qs = {}
        qs['format'] = format_
        qs['reqnum'] = reqnum
        qs['type'] = type_
        qs['contenttype'] = contenttype

        #pageflag: 分页标识(0:第一页,1:向下翻页,2:向上翻页)
        #lastid: 和pagetime配合使用(第一页:填0,向上翻页:填上一次请求返回的第一条记录id,向下翻页:填上一次请求返回的最后一条记录id)
        #pagetime 本页起始时间(第一页:填0,向上翻页:填上一次请求返回的第一条记录时间,向下翻页:填上一次请求返回的最后一条记录时间)
        qs['pageflag'] = pageflag
        qs['pagetime'] = pagetime if pagetime is not None else 0

        contents = self.auth.access_resource("GET", "/statuses/broadcast_timeline", qs)
        if not contents:
            return []

        try:
            contents_ = json_decode(contents)
        except:
            ##XXX:因为腾讯的json数据很2,导致有时候decode的时候会失败,一般都是因为双引号没有转义的问题
            import re
            r = re.sub('=\\"[^ >]*"( |>)', '', contents)
            contents_ = json_decode(r)
        contents = contents_

        if str(contents.get("ret")) != "0":
            return []
        
        data  = contents.get("data")
        info = data and data.get("info")
        print '---status from qqweibo, len is: %s' % len(info)

        return [QQWeiboStatusData(c) for c in info]
Esempio n. 2
0
 def __init__(self, id, user_id, origin_id, 
         create_time, site, category, title=""):
     self.id = str(id)
     self.user_id = str(user_id)
     self.origin_id = str(origin_id)
     self.create_time = create_time
     self.site = site
     self.category = category
     self.title = title
     self.text = json_decode(redis_conn.get(
             self.__class__.STATUS_REDIS_KEY % self.id))
     self.raw = json_decode(redis_conn.get(
             self.__class__.RAW_STATUS_REDIS_KEY % self.id))
     self.origin_user_id = UserAlias.get_by_user_and_type(self.user_id, self.site).alias
Esempio n. 3
0
 def access_resource2(self, method, api, params, file_params=None):
     r = self.access_resource(method, api, params, file_params)
     if not r:
         return None
     try:
         jdata = json_decode(r)
     except:
         ##XXX:因为腾讯的json数据很2,导致有时候decode的时候会失败,一般都是因为双引号没有转义的问题
         import re
         r_ = re.sub('=\\"[^ >]*"( |>)', '', r)
         try:
             jdata = json_decode(r_)
         except Exception, e:
             log.warning("json_decode qqweibo data fail, %s" % e)
             return None
Esempio n. 4
0
 def access_resource2(self, method, api, params, file_params=None):
     r = self.access_resource(method, api, params, file_params)
     if not r:
         return None
     try:
         jdata = json_decode(r)
     except:
         ##XXX:因为腾讯的json数据很2,导致有时候decode的时候会失败,一般都是因为双引号没有转义的问题
         import re
         r_ = re.sub('=\\"[^ >]*"( |>)', '', r)
         try:
             jdata = json_decode(r_)
         except Exception, e:
             log.warning("json_decode qqweibo data fail, %s" % e)
             return None
Esempio n. 5
0
 def get_thirdparty_profile(self, openid_type):
     p = self.get_profile_item(openid_type)
     if isinstance(p, dict):
         return p
     else:
         r = json_decode(p) if p else {}
         return r
Esempio n. 6
0
 def get_miniblogs(self, start, count):
     contents = self.get("/people/%s/miniblog" % self.alias,
             {"start-index": start, "max-results": count})
     contents = json_decode(contents).get("entry",[]) if contents else []
     if contents:
         print '------get douban miniblog,len is:', len(contents)
     return [DoubanMiniBlogData(c) for c in contents]
Esempio n. 7
0
    def check_result(self, uri, resp, content):
        user_id = self.user_alias and self.user_alias.user_id or None
        excp = OAuthTokenExpiredError(
            user_id, config.OPENID_TYPE_DICT[config.OPENID_DOUBAN], content)
        jdata = json_decode(content) if content else None
        if str(resp.status) == "200":
            excp.clear_the_profile()
            return jdata

        log.warning("get %s fail, status code=%s, msg=%s. go to refresh token" \
            % (uri, resp.status, content))
        if jdata and isinstance(jdata, dict):
            error_code = jdata.get("code")
            if str(error_code) == "103" or str(error_code) == "123":
                excp.set_the_profile()
                raise excp
            elif str(error_code) == "106" and self.user_alias:
                try:
                    new_tokens = super(Douban, self).refresh_tokens()
                    if new_tokens and isinstance(new_tokens, dict):
                        OAuth2Token.add(self.user_alias.id,
                                        new_tokens.get("access_token"),
                                        new_tokens.get("refresh_token"))
                        excp.clear_the_profile()
                except OAuthError, e:
                    log.warn("refresh token fail: %s" % e)
                    excp.set_the_profile()
                    raise e
Esempio n. 8
0
    def check_result(self, uri, resp, content):
        user_id = self.user_alias and self.user_alias.user_id or None
        excp = OAuthTokenExpiredError(user_id,
                config.OPENID_TYPE_DICT[config.OPENID_DOUBAN], content)
        jdata = json_decode(content) if content else None
        if str(resp.status) == "200":
            excp.clear_the_profile()
            return jdata

        log.warning("get %s fail, status code=%s, msg=%s. go to refresh token" \
            % (uri, resp.status, content))
        if jdata and isinstance(jdata, dict):
            error_code = jdata.get("code") 
            if str(error_code) == "103" or str(error_code) == "123":
                excp.set_the_profile()
                raise excp
            elif str(error_code) == "106" and self.user_alias:
                try:
                    new_tokens = super(Douban, self).refresh_tokens()
                    if new_tokens and isinstance(new_tokens, dict):
                        OAuth2Token.add(self.user_alias.id, 
                                new_tokens.get("access_token"), 
                                new_tokens.get("refresh_token"))
                        excp.clear_the_profile()
                except OAuthError, e:
                    log.warn("refresh token fail: %s" % e)
                    excp.set_the_profile()
                    raise e
Esempio n. 9
0
 def __init__(self, data):
     if data:
         self.data = data
     else:
         self.data = {}
     if isinstance(data, basestring):
         self.data = json_decode(data)
Esempio n. 10
0
    def get_timeline(self, format_="json", reqnum=200, type_=0, contenttype=0, pagetime=0, pageflag=0):
        qs = {}
        qs['format'] = format_
        qs['reqnum'] = reqnum
        qs['type'] = type_
        qs['contenttype'] = contenttype

        #pageflag: 分页标识(0:第一页,1:向下翻页,2:向上翻页)
        #lastid: 和pagetime配合使用(第一页:填0,向上翻页:填上一次请求返回的第一条记录id,向下翻页:填上一次请求返回的最后一条记录id)
        qs['pageflag'] = pageflag
        qs['pagetime'] = pagetime
        #qs['lastid'] = lastid

        contents = self.auth.access_resource("GET", "/statuses/broadcast_timeline", qs)
        if not contents:
            return []

        contents = json_decode(contents)
        print 'ret:', contents.get("ret")

        if str(contents.get("ret")) != "0":
            return []
        
        data  = contents.get("data")
        info = data and data.get("info")
        print '-----status from qqweibo, len is: %s' % len(info)

        return [QQWeiboStatusData(c) for c in info]
Esempio n. 11
0
 def __init__(self, data):
     if data:
         self.data = data
     else:
         self.data = {}
     if isinstance(data, basestring):
         self.data = json_decode(data)
Esempio n. 12
0
 def text(self):
     if self.category == config.CATE_THEPAST_NOTE:
         note = Note.get(self.origin_id)
         return note and note.content
     else:
         _text = mongo_conn.get(Status.STATUS_REDIS_KEY % self.id)
         return json_decode(_text) if _text else ""
Esempio n. 13
0
 def raw(self):
     if self.category == config.CATE_THEPAST_NOTE:
         note = Note.get(self.origin_id)
         return note
     else:
         _raw = mongo_conn.get(Status.RAW_STATUS_REDIS_KEY % self.id)
         return json_decode(_raw) if _raw else ""
Esempio n. 14
0
 def get_thirdparty_profile(self, openid_type):
     p = self.get_profile_item(openid_type)
     if isinstance(p, dict):
         return p
     else:
         r = json_decode(p) if p else {}
         return r
Esempio n. 15
0
 def text(self):
     if self.category == config.CATE_THEPAST_NOTE:
         note = Note.get(self.origin_id)
         return note and note.content
     else:
         r = RawStatus.get(self.id)
         _text = r.text if r else ""
         return json_decode(_text) if _text else ""
Esempio n. 16
0
 def get_profile(self):
     r = UserProfile.get(self.id)
     p = r.val if r else ""
     try:
         return json_decode(p) if p else {}
     except ValueError, e:
         print '------decode profile fail:', e
         return {}
Esempio n. 17
0
def _parse_qq_response(content):
    if not content:
        return {}
    if content.startswith('callback'):
        l = content.find('(')
        r = content.find(')')
        c = content[l+1:r]
        return json_decode(c) if c else {}
    elif content.startswith('{'):
        return json_decode(content)
    elif content.find('=')>0:
        qs = cgi.parse_qs(content)
        for x in qs:
            qs[x] = qs[x][0]
        return qs
    else:
        return {}
Esempio n. 18
0
 def raw(self):
     if self.category == config.CATE_THEPAST_NOTE:
         note = Note.get(self.origin_id)
         return note
     else:
         r = RawStatus.get(self.id)
         _raw = r.raw if r else ""
         return json_decode(_raw) if _raw else ""
Esempio n. 19
0
 def get_miniblogs(self, start, count):
     contents = self.get("/people/%s/miniblog" % self.alias, {
         "start-index": start,
         "max-results": count
     })
     contents = json_decode(contents).get("entry", []) if contents else []
     if contents:
         print '------get douban miniblog,len is:', len(contents)
     return [DoubanMiniBlogData(c) for c in contents]
Esempio n. 20
0
 def __init__(self, site, category, data):
     self.site = site
     self.category = category
     self.data = data or {}
     if isinstance(data, basestring):
         try:
             self.data = json_decode(data)
         except Exception, e:
             #import traceback; print traceback.format_exc()
             self.data = {}
Esempio n. 21
0
 def __init__(self, site, category, data):
     self.site = site
     self.category = category
     self.data = data or {}
     if isinstance(data, basestring):
         try:
             self.data = json_decode(data)
         except Exception, e:
             print e
             self.data = {}
Esempio n. 22
0
 def __init__(self, site, category, data):
     self.site = site
     self.category = category
     self.data = data or {}
     if isinstance(data, basestring):
         try:
             self.data = json_decode(data)
         except Exception, e:
             #import traceback; print traceback.format_exc()
             self.data = {}
Esempio n. 23
0
    def get_timeline(self,
                     format_="json",
                     reqnum=200,
                     type_=0,
                     contenttype=0,
                     pagetime=0,
                     pageflag=0):
        qs = {}
        qs['format'] = format_
        qs['reqnum'] = reqnum
        qs['type'] = type_
        qs['contenttype'] = contenttype

        #pageflag: 分页标识(0:第一页,1:向下翻页,2:向上翻页)
        #lastid: 和pagetime配合使用(第一页:填0,向上翻页:填上一次请求返回的第一条记录id,向下翻页:填上一次请求返回的最后一条记录id)
        #pagetime 本页起始时间(第一页:填0,向上翻页:填上一次请求返回的第一条记录时间,向下翻页:填上一次请求返回的最后一条记录时间)
        qs['pageflag'] = pageflag
        qs['pagetime'] = pagetime if pagetime is not None else 0

        contents = self.auth.access_resource("GET",
                                             "/statuses/broadcast_timeline",
                                             qs)
        if not contents:
            return []

        try:
            contents_ = json_decode(contents)
        except:
            ##XXX:因为腾讯的json数据很2,导致有时候decode的时候会失败,一般都是因为双引号没有转义的问题
            import re
            r = re.sub('=\\"[^ >]*"( |>)', '', contents)
            contents_ = json_decode(r)
        contents = contents_

        if str(contents.get("ret")) != "0":
            return []

        data = contents.get("data")
        info = data and data.get("info") or []
        print '---status from qqweibo, len is: %s' % len(info)

        return [QQWeiboStatusData(c) for c in info]
Esempio n. 24
0
    def get_timeline(self, since_id=None, until_id=None):
        d = {}
        if since_id is not None:
            d["since_id"] = since_id 
        if until_id is not None:
            d["until_id"] = until_id

        contents = self.get("/shuo/statuses/user_timeline/%s" \
                % self.alias, d)
        contents = json_decode(contents) if contents else []
        return [DoubanStatusData(c) for c in contents]
Esempio n. 25
0
    def get_home_timeline(self, since_id=None, until_id=None, count=200):
        qs = {}
        qs['count'] = count
        if since_id is not None:
            qs['since_id'] = since_id
        if until_id is not None:
            qs['until_id'] = until_id
        qs = urllib.urlencode(qs)
        contents = self.get("/shuo/v2/statuses/home_timeline?%s" % qs)
        contents = json_decode(contents) if contents else []

        return [DoubanStatusData(c) for c in contents]
Esempio n. 26
0
    def get_home_timeline(self, since_id=None, until_id=None, count=200):
        qs = {}
        qs['count'] = count
        if since_id is not None:
            qs['since_id'] = since_id
        if until_id is not None:
            qs['until_id'] = until_id
        qs = urllib.urlencode(qs)
        contents = self.get("/shuo/v2/statuses/home_timeline?%s" % qs)
        contents = json_decode(contents) if contents else []

        return [DoubanStatusData(c) for c in contents]
Esempio n. 27
0
    def get_timeline(self, since_id=None, until_id=None, count=200, user_id=None):
        user_id = user_id or self.alias
        qs = {}
        qs['count'] = count
        if since_id is not None:
            qs['since_id'] = since_id
        if until_id is not None:
            qs['until_id'] = until_id
        qs = urllib.urlencode(qs)
        contents = self.get("/shuo/v2/statuses/user_timeline/%s?%s" % (user_id, qs))
        contents = json_decode(contents) if contents else []

        return [DoubanStatusData(c) for c in contents]
Esempio n. 28
0
    def get_timeline_by_page(self, page=1, count=100):
        d = {}
        d["uid"] = self.alias
        d["trim_user"] = 0
        d["count"] = count
        d["page"] = page

        contents = self.get("/statuses/user_timeline.json", d)
        contents = json_decode(contents).get("statuses", []) if contents else []
        ##debug
        if contents:
            print '---get sinawebo page %s succ, result length is: %s' %(page, len(contents))
        return [SinaWeiboStatusData(c) for c in contents]
Esempio n. 29
0
    def get_user_info(self, access_token, uid=None):
        headers = {"Authorization": "Bearer %s" % access_token}
        qs = {
            "alt": "json",
        }
        uri = "%s?%s" % (self.user_info_uri, urllib.urlencode(qs))
        resp, content = httplib2_request(uri, "GET", headers=headers)
        if resp.status != 200:
            raise OAuthLoginError('get_access_token, status=%s:reason=%s:content=%s' \
                    %(resp.status, resp.reason, content))
        r = json_decode(content)
        user_info = DoubanUser(r)

        return user_info
Esempio n. 30
0
 def get_access_token(self, authorization_code):
     qs = {
         "client_id": self.apikey,
         "client_secret": self.apikey_secret,
         "redirect_uri": self.redirect_uri,
         "grant_type": "authorization_code",
         "code": authorization_code,
     }
     qs = urllib.urlencode(qs)
     resp, content = httplib2_request(self.access_token_uri, "POST", body=qs)
     if resp.status != 200:
         raise OAuthLoginError('get_access_token, status=%s:reason=%s:content=%s' \
                 %(resp.status, resp.reason, content))
     return json_decode(content)
Esempio n. 31
0
    def __init__(self, id, user_id, origin_id, create_time, site, category, title=""):
        self.id = str(id)
        self.user_id = str(user_id)
        self.origin_id = str(origin_id)
        self.create_time = create_time
        self.site = site
        self.category = category
        self.title = title
        self.text = mongo_conn.get(self.__class__.STATUS_REDIS_KEY % self.id)
        self.text = json_decode(self.text) if self.text else ""
        self.origin_user_id = UserAlias.get_by_user_and_type(self.user_id, self.site).alias
        if self.site == config.OPENID_TYPE_DICT[config.OPENID_TWITTER]:
            self.create_time += datetime.timedelta(seconds=8 * 3600)

        self.bare_text = self._generate_bare_text()
Esempio n. 32
0
    def get_timeline(self, since_id=None, until_id=None, count=200):
        d = {}
        d["uid"] = self.alias
        d["trim_user"] = 0
        if since_id is not None:
            d["since_id"] = since_id 
        if until_id is not None:
            d["max_id"] = until_id

        contents = self.get("/statuses/user_timeline.json", d)
        contents = json_decode(contents).get("statuses", []) if contents else []
        ##debug
        if contents:
            print '---get sinawebo succ, result length is:', len(contents)
        return [SinaWeiboStatusData(c) for c in contents]
Esempio n. 33
0
    def get_timeline_by_page(self, page=1, count=100):
        d = {}
        d["uid"] = self.alias
        d["trim_user"] = 0
        d["count"] = count
        d["page"] = page

        contents = self.get("/statuses/user_timeline.json", d)
        contents = json_decode(contents).get("statuses",
                                             []) if contents else []
        ##debug
        if contents:
            print '---get sinawebo page %s succ, result length is: %s' % (
                page, len(contents))
        return [SinaWeiboStatusData(c) for c in contents]
Esempio n. 34
0
    def get_user_info(self, access_token, uid=None):
        headers = {"Authorization": "Bearer %s" % access_token}     
        qs = {
            "alt":"json",
        }
        uri = "%s?%s" %(self.user_info_uri, urllib.urlencode(qs))
        resp, content = httplib2_request(uri, "GET", 
                headers = headers)
        if resp.status != 200:
            raise OAuthLoginError('get_access_token, status=%s:reason=%s:content=%s' \
                    %(resp.status, resp.reason, content))
        r = json_decode(content)
        user_info = DoubanUser(r)

        return user_info
Esempio n. 35
0
    def update_tokens(self, refresh_token):
        qs = {}
        qs["client_id"] = self.apikey
        qs["client_secret"] = self.apikey_secret
        qs["redirect_uri"] = self.redirect_uri
        qs["grant_type"] = "refresh_token"
        qs["refresh_token"] = refresh_token

        resp, content = httplib2_request(self.access_token_uri, "POST", 
            body=urllib.urlencode(qs))
        if resp.status != 200:
            raise OAuthLoginError('refres_tokens fail, status=%s:reason=%s:content=%s' \
                    %(resp.status, resp.reason, content))
        r = json_decode(content)
        
        return OAuth2Token.add(r.get("douban_user_id"), r.get("access_token"), r.get("refresh_token"))
Esempio n. 36
0
 def get_access_token(self, authorization_code):
     qs = {
         "client_id": self.apikey,
         "client_secret": self.apikey_secret,
         "redirect_uri": self.redirect_uri,
         "grant_type": "authorization_code",
         "code": authorization_code,
     }
     qs = urllib.urlencode(qs)
     resp, content = httplib2_request(self.access_token_uri,
                                      "POST",
                                      body=qs)
     if resp.status != 200:
         raise OAuthLoginError('get_access_token, status=%s:reason=%s:content=%s' \
                 %(resp.status, resp.reason, content))
     return json_decode(content)
Esempio n. 37
0
    def get_user_info(self, access_token, uid):
        qs = {
            "source": self.apikey,
            "access_token": access_token,
            "uid": uid,
        }
        qs = urllib.urlencode(qs)
        uri = "%s?%s" % (self.user_info_uri, qs)
        resp, content = httplib2_request(uri, "GET")
        if resp.status != 200:
            raise OAuthLoginError('get_access_token, status=%s:reason=%s:content=%s' \
                    %(resp.status, resp.reason, content))
        r = json_decode(content)
        user = SinaWeiboUser(r)

        return user
Esempio n. 38
0
    def get_user_info(self, access_token, uid):
        qs = {
            "source": self.apikey,
            "access_token": access_token,
            "uid": uid,
        }
        qs = urllib.urlencode(qs)
        uri = "%s?%s" % (self.user_info_uri, qs)
        resp, content = httplib2_request(uri, "GET")
        if resp.status != 200:
            raise OAuthLoginError('get_access_token, status=%s:reason=%s:content=%s' \
                    %(resp.status, resp.reason, content))
        r = json_decode(content)
        user = SinaWeiboUser(r)

        return user
Esempio n. 39
0
    def get_timeline(self, since_id=None, until_id=None, count=100):
        d = {}
        d["uid"] = self.alias
        d["trim_user"] = 0
        d["count"] = count
        if since_id is not None:
            d["since_id"] = since_id
        if until_id is not None:
            d["max_id"] = until_id

        contents = self.get("/statuses/user_timeline.json", d)
        contents = json_decode(contents).get("statuses",
                                             []) if contents else []
        ##debug
        if contents:
            print '---get sinawebo succ, result length is:', len(contents)
        return [SinaWeiboStatusData(c) for c in contents]
Esempio n. 40
0
    def _request(self, api, method="POST", extra_dict=None):
        if extra_dict is None:
            extra_dict = {}

        params = {
            "method": api,
            "v": "1.0",
            "access_token": self.access_token,
            "format": "json",
        }
        params.update(extra_dict)
        _, qs = Renren.sign(self.apikey_secret, **params)
        uri = "%s?%s" % (self.api_host, qs)

        log.info('getting %s...' % uri)
        resp, content = httplib2_request(uri, method)
        if resp.status == 200:
            user_id = self.user_alias and self.user_alias.user_id or None
            excp = OAuthTokenExpiredError(
                user_id=None,
                openid_type=config.OPENID_TYPE_DICT[config.OPENID_RENREN],
                msg=content)
            jdata = json_decode(content) if content else None
            if jdata and isinstance(jdata, dict):
                error_code = jdata.get("error_code")
                error_msg = jdata.get("error_msg")
                if error_code:
                    if str(error_code) == "105":
                        ## 无效的token
                        excp.set_the_profile()
                        raise excp
                    elif str(error_code) == "106" and self.user_alias:
                        ## FIXME: 过期的token, 是不是106?
                        try:
                            new_tokens = super(Renren, self).refresh_tokens()
                            if new_tokens and isinstance(new_tokens, dict):
                                OAuth2Token.add(
                                    self.user_alias.id,
                                    new_tokens.get("access_token"),
                                    new_tokens.get("refresh_token"))
                                excp.clear_the_profile()
                        except OAuthError, e:
                            log.warn("refresh token fail: %s" % e)
                            excp.set_the_profile()
                            raise e
            return jdata
Esempio n. 41
0
    def update_tokens(self, refresh_token):
        qs = {}
        qs["client_id"] = self.apikey
        qs["client_secret"] = self.apikey_secret
        qs["redirect_uri"] = self.redirect_uri
        qs["grant_type"] = "refresh_token"
        qs["refresh_token"] = refresh_token

        resp, content = httplib2_request(self.access_token_uri,
                                         "POST",
                                         body=urllib.urlencode(qs))
        if resp.status != 200:
            raise OAuthLoginError('refres_tokens fail, status=%s:reason=%s:content=%s' \
                    %(resp.status, resp.reason, content))
        r = json_decode(content)

        return OAuth2Token.add(r.get("douban_user_id"), r.get("access_token"),
                               r.get("refresh_token"))
Esempio n. 42
0
    def get_timeline(self,
                     since_id=None,
                     until_id=None,
                     count=200,
                     user_id=None):
        user_id = user_id or self.alias
        qs = {}
        qs['count'] = count
        if since_id is not None:
            qs['since_id'] = since_id
        if until_id is not None:
            qs['until_id'] = until_id
        qs = urllib.urlencode(qs)
        contents = self.get("/shuo/v2/statuses/user_timeline/%s?%s" %
                            (user_id, qs))
        contents = json_decode(contents) if contents else []

        return [DoubanStatusData(c) for c in contents]
Esempio n. 43
0
    def refresh_tokens(self):
        qs = {
            "grant_type": "refresh_token",
            "refresh_token": self.refresh_token,
            "client_id": self.apikey,
            "client_secret": self.apikey_secret,
            "redirect_uri": self.redirect_uri,
        }
        resp, content = httplib2_request(self.access_token_uri, "POST", 
            body=urllib.urlencode(qs))
        excp = OAuthLoginError(self.user_alias.user_id, self.provider, 
                'refresh_tokens, status=%s,reason=%s,content=%s' \
                %(resp.status, resp.reason, content))
        if resp.status != 200:
            raise excp

        jdata = json_decode(content) if content else None
        return jdata
Esempio n. 44
0
    def _request(self, api, method="POST", extra_dict=None):
        if extra_dict is None:
            extra_dict = {}

        params = {
            "method": api,
            "v": "1.0",
            "access_token": self.access_token,
            "format": "json",
        }
        params.update(extra_dict)
        _, qs = Renren.sign(self.apikey_secret, **params)
        uri = "%s?%s" % (self.api_host, qs)

        log.info('getting %s...' % uri)
        resp, content = httplib2_request(uri, method)
        if resp.status == 200:
            user_id = self.user_alias and self.user_alias.user_id or None
            excp = OAuthTokenExpiredError(user_id=None,
                    openid_type=config.OPENID_TYPE_DICT[config.OPENID_RENREN], 
                    msg=content)
            jdata = json_decode(content) if content else None
            if jdata and isinstance(jdata, dict):
                error_code = jdata.get("error_code")
                error_msg = jdata.get("error_msg")
                if error_code:
                    if str(error_code) == "105":
                        ## 无效的token
                        excp.set_the_profile()
                        raise excp
                    elif str(error_code) == "106" and self.user_alias:
                        ## FIXME: 过期的token, 是不是106?
                        try:
                            new_tokens = super(Renren, self).refresh_tokens()
                            if new_tokens and isinstance(new_tokens, dict):
                                OAuth2Token.add(self.user_alias.id, 
                                        new_tokens.get("access_token"), 
                                        new_tokens.get("refresh_token"))
                                excp.clear_the_profile()
                        except OAuthError, e:
                            log.warn("refresh token fail: %s" % e)
                            excp.set_the_profile()
                            raise e
            return jdata
Esempio n. 45
0
    def _request(self, api, method="GET", extra_dict=None):
        uri = urlparse.urljoin(self.api_host, api)
        if extra_dict is None:
            extra_dict = {}

        params = {
            "access_token": self.access_token,
        }
        params.update(extra_dict)
        qs = urllib.urlencode(params)
        uri = "%s?%s" % (uri, qs)

        log.info('getting %s...' % uri)
        resp, content = httplib2_request(uri, method)
        if resp.status == 200:
            return json_decode(content) if content else None
        else:
            log.warn("get %s fail, status code=%s, msg=%s" \
                    % (uri, resp.status, content))
Esempio n. 46
0
    def _request(self, api, method="GET", extra_dict=None):
        uri = urlparse.urljoin(self.api_host, api)
        if extra_dict is None:
            extra_dict = {}

        params = {
            "access_token": self.access_token,
        }
        params.update(extra_dict)
        qs = urllib.urlencode(params)
        uri = "%s?%s" % (uri, qs)

        log.info('getting %s...' % uri)
        resp, content = httplib2_request(uri, method)
        if resp.status == 200:
            return json_decode(content) if content else None
        else:
            log.warn("get %s fail, status code=%s, msg=%s" \
                    % (uri, resp.status, content))
Esempio n. 47
0
 def check_result(self, uri, resp, content):
     #{"error":"expired_token","error_code":21327,"request":"/2/statuses/update.json"}
     #log.debug("---sina check result, status: %s, resp: %s, content: %s" %(resp.status, resp, content))
     jdata = json_decode(content) if content else None
     if jdata and isinstance(jdata, dict):
         error_code = jdata.get("error_code")
         error = jdata.get("error")
         request_api = jdata.get("request")
         user_id = self.user_alias and self.user_alias.user_id or None
         excp = OAuthTokenExpiredError(
             user_id, config.OPENID_TYPE_DICT[config.OPENID_SINA],
             "%s:%s:%s" % (error_code, error, request_api))
         if error_code and isinstance(error_code, int):
             error_code = int(error_code)
             if error_code >= 21301 and error_code <= 21399:
                 excp.set_the_profile()
                 raise excp
             else:
                 log.warning("get %s fail, error_code=%s, error_msg=%s" \
                     % (uri, error_code, error))
         else:
             excp.clear_the_profile()
             return jdata
Esempio n. 48
0
 def check_result(self, uri, resp, content):
     #{"error":"expired_token","error_code":21327,"request":"/2/statuses/update.json"}
     #log.debug("---sina check result, status: %s, resp: %s, content: %s" %(resp.status, resp, content))
     jdata = json_decode(content) if content else None
     if jdata and isinstance(jdata, dict):
         error_code = jdata.get("error_code")
         error = jdata.get("error")
         request_api = jdata.get("request")
         user_id = self.user_alias and self.user_alias.user_id or None
         excp = OAuthTokenExpiredError(user_id,
                 config.OPENID_TYPE_DICT[config.OPENID_SINA], 
                 "%s:%s:%s" %(error_code, error, request_api))
         if error_code and isinstance(error_code, int):
             error_code = int(error_code)
             if error_code >= 21301 and error_code <= 21399:
                 excp.set_the_profile()
                 raise excp
             else:
                 log.warning("get %s fail, error_code=%s, error_msg=%s" \
                     % (uri, error_code, error))
         else:
             excp.clear_the_profile()
             return jdata
Esempio n. 49
0
 def check_result(self, uri, resp, content):
     if resp.status != 200:
         return None
     jdata = json_decode(content) if content else None
     if jdata and isinstance(jdata, dict):
         error_code = jdata.get("error_code")
         error = jdata.get("error")
         request_api = jdata.get("request")
         user_id = self.user_alias and self.user_alias.user_id or None
         excp = OAuthTokenExpiredError(user_id,
                 config.OPENID_TYPE_DICT[config.OPENID_SINA], 
                 "%s:%s:%s" %(error_code, error, request_api))
         if error_code and isinstance(error_code, int):
             error_code = int(error_code)
             if error_code >= 21301 and error_code <= 21399:
                 excp.set_the_profile()
                 raise excp
             else:
                 log.warning("get %s fail, error_code=%s, error_msg=%s" \
                     % (uri, error_code, error))
         else:
             excp.clear_the_profile()
             return jdata
Esempio n. 50
0
 def get_user_info(self):
     r = self.access_resource("GET", "/user/info", {"format": "json"})
     r = json_decode(r) if r else {}
     return QQWeiboUser(r.get('data'))
Esempio n. 51
0
sys.path.append('../')

import datetime
import past
from past.store import db_conn
from past.utils.escape import json_decode
from past.model.kv import RawStatus

cursor = db_conn.execute("select id from status where category=200")
rows = cursor.fetchall()
cursor and cursor.close()
ids = [x[0] for x in rows]

for x in ids:
    try:
        r = RawStatus.get(x)
        raw = r.raw if r else ""
        if raw:
            print x
            data = json_decode(raw)
            t = data.get("created_at")
            created_at = datetime.datetime.strptime(
                t, "%a %b %d %H:%M:%S +0800 %Y")
            db_conn.execute("update status set create_time = %s where id=%s",
                            (created_at, x))
            db_conn.commit()
    except:
        import traceback
        print traceback.format_exc()
        sys.stdout.flush()
Esempio n. 52
0
 def get_profile(self):
     r = UserProfile.get(self.id)
     p = r.val if r else ""
     return json_decode(p) if p else {}
Esempio n. 53
0
 def get_request_token_from_session(self, session_, delete=True):
     t = session_.get("request_token")
     token = json_decode(t) if t else {}
     if delete:
         self.delete_request_token_from_session(session_)
     return token