Example #1
0
def weiboLogin(request):
    # TODO: bug 目前还有错,不知道是哪儿的原因:
    # 用WeBless和新闻追踪007可以正常登录,但是用zzy和幸运女神的帐号登录就没有user_id!!!
    signed_request = request.POST.get('signed_request')
    # signed_request传到python这边, 数据结构是一个字符串型的list
    if isinstance(signed_request, list):
        signed_request = signed_request[0]
    encoded_sig, payload = signed_request.split(".", 2)

    # 余数2, 那么需要补一个=
    payload = str(payload)
    if len(payload) % 3 == 2:
        payload += '='
    # 余数1, 那么需要补两个=
    if len(payload) % 3 == 1:
        payload += '=='
    # urlsafe_b64decode() Decode string s using a URL-safe alphabet,
    # which substitutes - instead of + and _ instead of / in the standard Base64 alphabet.
    # 得到data
    data = simplejson.loads(base64.urlsafe_b64decode(payload))

    # 得到sig
    encoded_sig = str(encoded_sig)
    if len(encoded_sig) % 3 == 2:
        encoded_sig += '='
    if len(encoded_sig) % 3 == 1:
        encoded_sig += '=='
    sig = base64.urlsafe_b64decode(encoded_sig)

    try:
        user_id = data['user_id']
        oauth_token = data['oauth_token']
        expires = data['expires']
    except:
        print '认证错误,这个错误还未解决!!!'

    if _DEBUG:
        print 'signed_request: ', signed_request
        print 'data: ', data
        print user_id

    # #判断用户是否已经登录过(第一次登录会自动帮用户注册)
    try:
        _account = Account.objects.get(weiboId=user_id)
    except:
        print 'create new Account for:' + str(user_id)
        _weibo = weiboAPI(oauth_token, expires, user_id)
        _account = dbop.get_or_create_account_from_weibo(_weibo.getUserInfo())
    # # TODO: 如何实现用户自动登录??
    request.session['user'] = _account.user
    return HttpResponseRedirect('/home/')
Example #2
0
def login(request):
    template_var = {}
    # # 用户weibo登录的认证链接
    authorize_url = weiboAPI().getAuthorizeUrl()
    template_var['authorize_url'] = authorize_url

    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(request.POST.copy())
        if form.is_valid():
            if _login(request,
                   form.cleaned_data["username"],
                   form.cleaned_data["password"]):
                return HttpResponseRedirect("/")
    template_var["form"] = form
    return render_to_response("login.html",
                              template_var,
                              context_instance=RequestContext(request))
Example #3
0
def weibo_callback(request):
    # 获取code
    code = request.GET.get('code')
    # 构建微博对象
    _wb = weiboAPI()
    _r = _wb.client.request_access_token(code)
    access_token = _r.access_token
    expires_in = _r.expires_in
    u_id = _r.uid
    _wb.client.set_access_token(access_token, expires_in)
    uinfo = _wb.getUserInfo(uid=u_id)
    # 保存授权信息
    _oauth = dbop.create_or_update_weibo_auth(u_id=u_id, access_token=access_token, expires_in=expires_in)
    _account = dbop.get_or_create_account_from_weibo(uinfo)
    _account.oauth = _oauth
    _account.save()
    _account.user.backend = 'django.contrib.auth.backends.ModelBackend'
    auth_login(request, _account.user)
    return HttpResponseRedirect('/home/')
Example #4
0
def remindUserTopicUpdates(topicTitle):
    try:
        logger.debug(u'Start remind user for topic:%s' % topicTitle)
        topic = djangodb.Topic.objects.get(title=topicTitle)
        if topic.alive():
            topic_news = topic.news_set.all()[0]
        else:
            logger.warn(u'topic:%s is already dead, add unsubscribe task!' % topicTitle)
            djangodb.add_task(topic=topic, type=u'unsubscribe')
            return False
    except:
        logger.exception(u'topic or news may not exist in database')
        return False

    topicWatchers = topic.watcher.all()
    topicWatcherWeibo = topic.watcher_weibo.all()


    '''
    得到订阅该话题的所有用户,分两类,已经授权的和没有授权的
    '''
    watcherWithAuth = set()
    watcherWithoutAuth = set()
    for watcher in topicWatchers:
        if watcher.has_oauth():
            watcherWithAuth.add(watcher)
        else:
            watcherWithoutAuth.add(watcher)

    '''
    筛选出其中需要提醒的用户,分为四类:
    
    watcherWithoutStatusAndAuth
    watcherWithStatusAndAuth
    watcherWithStatusWithoutAuth
    watcherWithoutStatusWithAuth
    '''
    watcherWithStatusAndAuth = set()
    watcherWithStatusWithoutAuth = set()
    for watcherWeibo in topicWatcherWeibo:
        watcher = watcherWeibo.user
        if not watcher.to_remind():
            # 去掉不需要提醒的用户
            continue
        watcher.original_weibo = watcherWeibo  # 人工添加的字段
        if watcher in watcherWithAuth:
            watcherWithStatusAndAuth.add(watcher)
        elif watcher in watcherWithoutAuth:
            watcherWithStatusWithoutAuth.add(watcher)

    # 去掉不需要提醒的用户
    watcherWithoutStatusAndAuth = set([watcher for watcher in (watcherWithoutAuth - watcherWithStatusWithoutAuth) if watcher.to_remind()])
    watcherWithoutStatusWithAuth = set([watcher for watcher in (watcherWithAuth - watcherWithStatusAndAuth) if watcher.to_remind()])

    _shorturl = weibo.getShortUrl(Conf.get_timeline_url(topic.id))
    _msg = u'#%s#有新进展:%s 『%s』' % (topicTitle, topic_news.title, _shorturl)
    reqInterval(61)

    logger.debug(u'topicWatcherWeibo:%s' % topicWatcherWeibo)
    logger.debug(u'topicWatchers:%s' % topicWatchers)
    logger.debug(u'watcherWithAuth:%s' % watcherWithAuth)
    logger.debug(u'watcherWithoutAuth:%s' % watcherWithoutAuth)
    logger.debug(u'posgMsg:%s' % _msg)

    _user_reminded = []

    '''
    先更新有授权同时也发过微博的用户的状态
    '''
    for watcher in watcherWithStatusAndAuth:
        '''
        自己转发或评论自己的原始微博提醒自己,如果允许提醒他人的话,顺带提醒~
        '''
        [access_token, expires_in] = djangodb.get_weibo_auth_info(watcher.weiboId)
        _weibo = weiboAPI.weiboAPI(access_token=access_token, \
                                   expires_in=expires_in, \
                                   u_id=watcher.weiboId)
        watcher_btw = None
        if watcher.allow_remind_others and watcherWithStatusWithoutAuth:
            watcher_btw = watcherWithStatusWithoutAuth.pop()
            postMsg = _msg + u' @' + watcher_btw.weiboName + u' 顺便提醒你一下~'
        else:
            postMsg = _msg + u' @' + watcher.weiboName

        logger.info(u'remind user:%s \ntopic:%s \nupdate with msg:%s\noriginalWeibo:%s' % \
                     (watcher.weiboName, topicTitle, postMsg, watcher.original_weibo))
        res = {}
        try:
            if watcher.repost_remind:
                res[u'type'] = u'repost status'
                res[u'status'] = _weibo.repostStatus(weibo_id=watcher.original_weibo.weibo_id, content=postMsg)
            else:
                res[u'type'] = u'comment status'
                res[u'status'] = _weibo.postComment(weibo_id=watcher.original_weibo.weibo_id, content=postMsg)
        except APIError, err:
            logger.warn(u'%s failed:\t%s' % (res[u'type'], err.error))
            if err.error == u'target weibo does not exist!':
                topic.watcher_weibo.remove(watcher.original_weibo)
                topic.watcher.remove(watcher)
                logger.info(u'remove watcher:%s and delete watcherWeibo:%s' % (watcher, watcher.original_weibo))
                watcher.original_weibo.delete()
            else:
                logger.exception(u'')
        else:
            logger.info(u'%s Succeed!' % res[u'type'])
            if watcher_btw:
                watcher_btw.add_remind()
            watcher.add_remind()
            logger.info(u'added remind history for user: [%s, %s]' % (watcher.weiboName, watcher_btw))
        finally:
Example #5
0
fh.setLevel(logging.DEBUG)
# create console handler with warn log level
ch = logging.StreamHandler()
ch.setLevel(logging.WARN)
# create logger output formater
formatter = logging.Formatter(u'%(asctime)s %(name)s %(levelname)s %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

# setup weibo
[access_token, expires_in] = djangodb.get_weibo_auth_info(3041970403)
if time.time() > float(expires_in):
    raise Exception(u'授权过期了,with expires_in:%s' % expires_in)
weibo = weiboAPI.weiboAPI(access_token=access_token, expires_in=expires_in, u_id=3041970403)
reqInterval(31)
logger.info(u'Sina Weibo 登录信息:\t' + weibo.getUserInfo()[u'name'])

# setup google reader
from libgreader import readerAPI
[access_token, refresh_token, access_expires] = djangodb.get_google_auth_info(u_id=1)
reader = readerAPI.readerAPI(u_id=1, access_token=access_token, \
                  refresh_token=refresh_token, expires_access=access_expires)
reqInterval(31)
logger.info(u'Google Reader 登录信息:\t' + reader.getUserInfo()[u'userName'])


def remindUserTopicUpdates(topicTitle):
    try:
        logger.debug(u'Start remind user for topic:%s' % topicTitle)
Example #6
0
fh.setLevel(logging.DEBUG)
# create console handler with warn log level
ch = logging.StreamHandler()
ch.setLevel(logging.WARN)
# create logger output formater
formatter = logging.Formatter(u"%(asctime)s %(name)s %(levelname)s %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

# setup weibo
[access_token, expires_in] = djangodb.get_weibo_auth_info(3041970403)
if time.time() > float(expires_in):
    raise Exception(u"授权过期了,with expires_in:%s" % str(expires_in))
weibo = weiboAPI.weiboAPI(access_token=access_token, expires_in=expires_in, u_id=3041970403)
reqInterval(31)
logger.info(u"Sina Weibo 登录信息:%s" % weibo.getUserInfo()[u"name"])


def fetchUserMention():
    """
    获取微博上用户的订阅话题,之后更新订阅
    用户订阅话题的方式可以发布包含:@狗狗追踪 *订阅或取消订阅* #话题内容#的微博;或者转发上述微博

    TODO:
    1. mentions只获取了前50条
    """
    # 得到用户mentions
    lastMentionId = djangodb.get_last_mention_id()
    logger.info(u"Get lastMentionId:%s" % str(lastMentionId))
Example #7
0
def home(request):
    template_var = {}
    my_topics = []
    exclude_set = []
    if request.user.is_authenticated():
        current_account = _get_account_from_req(request)
        if not current_account:
            return HttpResponse('''当前用户没有Account帐号''')
        my_topics = current_account.topic_set.all()
        template_var['current_account'] = current_account
        template_var['my_topics'] = my_topics
        exclude_set.append(current_account)
    else:
        current_account = None
        # 用户weibo登录的认证链接
        template_var['authorize_url'] = weiboAPI().getAuthorizeUrl()

    # 得到数据库其他的比较热门的5个话题
    other_topics = Topic.alive_objects.exclude(watcher__in=exclude_set).\
    annotate(watcher_count=Count('watcher')).order_by('-watcher_count')[:5]
    template_var['other_topics'] = other_topics

    # 得到数据库中最新的5个话题(原本就是按照时间排列的)
    new_topics = Topic.alive_objects.exclude(watcher__in=exclude_set)[:5]
    template_var['new_topics'] = new_topics

    for topic in itertools.chain(my_topics, other_topics, new_topics):
        _news_count = topic.news_set.count()
        if _news_count > 0:

            if _news_count > 6:
                _lmt = 6
            else:
                _lmt = _news_count
            _news_list = topic.news_set.all()[:_lmt]
            topic.recent_news[topic.title] = []
            topic.recent_news[topic.title].append({'title':_news_list[0].title, \
                                                   'link':_news_list[0].link, \
                                                   'time_passed':_get_time_passed(_news_list[0].pubDate)})
            topic.recent_news[topic.title].append({'title':_news_list[_lmt / 2].title, \
                                                   'link':_news_list[_lmt / 2].link, \
                                                   'time_passed':_get_time_passed(_news_list[_lmt / 2].pubDate)})
            topic.recent_news[topic.title].append({'title':_news_list[_lmt - 1].title, \
                                                   'link':_news_list[_lmt - 1].link, \
                                                   'time_passed':_get_time_passed(_news_list[_lmt - 1].pubDate)})
            topic.timeline_ready = True
        else:
            topic.recent_news[topic.title] = []
            topic.recent_news[topic.title].append({'title':'还木有更新呢==!', \
                                                   'link':'javascript:void(0)', \
                                                   'time_passed':_get_time_passed(datetime.datetime.now())})
            topic.timeline_ready = False

    if _DEBUG:
        for key in template_var:
            print key, template_var[key]

    template_var["setting_form"] = _get_setting_form(current_account)

    return render_to_response("home.html",
                              template_var,
                              context_instance=RequestContext(request))