Example #1
0
    def add(cls, name=None, uid=None, session_id=None):
        cursor = None
        user = None

        name = "" if name is None else name
        uid = "" if uid is None else uid
        session_id = session_id if session_id else randbytes(8)

        try:
            cursor = db_conn.execute("""insert into user (uid, name, session_id) 
                values (%s, %s, %s)""", 
                (uid, name, session_id))
            user_id = cursor.lastrowid
            if uid == "":
                cursor = db_conn.execute("""update user set uid=%s where id=%s""", 
                    (user_id, user_id), cursor=cursor)
            db_conn.commit()
            cls._clear_cache(None)
            user = cls.get(user_id)
        except IntegrityError:
            db_conn.rollback()
        finally:
            cursor and cursor.close()

        return user
Example #2
0
    def add(cls, name=None, uid=None, session_id=None):
        cursor = None
        user = None

        name = "" if name is None else name
        uid = "" if uid is None else uid
        session_id = session_id if session_id else randbytes(8)

        try:
            cursor = db_conn.execute(
                """insert into user (uid, name, session_id) 
                values (%s, %s, %s)""", (uid, name, session_id))
            user_id = cursor.lastrowid
            if uid == "":
                cursor = db_conn.execute(
                    """update user set uid=%s where id=%s""",
                    (user_id, user_id),
                    cursor=cursor)
            db_conn.commit()
            cls._clear_cache(None)
            user = cls.get(user_id)
        except IntegrityError:
            db_conn.rollback()
        finally:
            cursor and cursor.close()

        return user
Example #3
0
def get_keywords(user_id=config.MY_USER_ID, count=30):
    text = get_all_text_by_user(user_id)
    file_ = "/tmp/tag_%s" % randbytes(8)
    with open(file_, 'w') as f:
        f.write(text.encode("utf8"))
    try:
        cmd = '%s -I -d %s -c utf8 -t500 -i "%s"|grep -E "^[0-9]+"' \
                % (config.SCWS, config.HOT_TERMS_DICT, file_)
        r = commands.getoutput(cmd)
    except Exception, e:
        print e
Example #4
0
def get_keywords(user_id=config.MY_USER_ID, count=30):
    text = get_all_text_by_user(user_id)
    file_ = "/tmp/tag_%s" % randbytes(8)
    with open(file_, 'w') as f:
        f.write(text.encode("utf8"))
    try:
        cmd = '%s -I -d %s -c utf8 -t200 -i "%s"|grep -E "^[0-9]+"' \
                % (config.SCWS, config.HOT_TERMS_DICT, file_)
        r = commands.getoutput(cmd)
    except Exception, e:
        import traceback
        print traceback.format_exc()
Example #5
0
    def sign(cls, method, uri, consumer_key, consumer_secret, token_secret,
             **kw):

        part1 = method.upper()
        part2 = urllib.quote(uri.lower(), safe="")
        part3 = ""

        d = {}
        for k, v in kw.items():
            d[k] = v

        d['oauth_consumer_key'] = consumer_key

        if 'oauth_timestamp' not in d or not d['oauth_timestamp']:
            d['oauth_timestamp'] = str(int(time.time()))

        if 'oauth_nonce' not in d or not d['oauth_nonce']:
            d['oauth_nonce'] = randbytes(32)

        if 'oauth_signature_method' not in d or not d['oauth_signature_method']:
            d['oauth_signature_method'] = 'HMAC-SHA1'

        if 'oauth_version' not in d or not d['oauth_version']:
            d['oauth_version'] = '1.0'

        d_ = sorted(d.items(), key=lambda x: x[0])

        dd_ = [urllib.urlencode([x]).replace("+", "%20") for x in d_]
        part3 = urllib.quote("&".join(dd_))

        key = consumer_secret + "&"
        if token_secret:
            key += token_secret

        raw = "%s&%s&%s" % (part1, part2, part3)

        if d['oauth_signature_method'] != "HMAC-SHA1":
            raise

        hashed = hmac.new(key, raw, hashlib.sha1)
        hashed = binascii.b2a_base64(hashed.digest())[:-1]
        d["oauth_signature"] = hashed

        qs = urllib.urlencode(d_).replace("+", "%20")
        qs += "&" + urllib.urlencode({"oauth_signature": hashed})

        return (d, qs)
Example #6
0
    def sign(cls, method, uri, consumer_key, consumer_secret, token_secret, **kw):
        
        part1 = method.upper()
        part2 = urllib.quote(uri.lower(), safe="")
        part3 = ""
        
        d = {}
        for k, v in kw.items():
            d[k] = v

        d['oauth_consumer_key'] = consumer_key

        if 'oauth_timestamp' not in d or not d['oauth_timestamp']:
            d['oauth_timestamp'] = str(int(time.time()))

        if 'oauth_nonce' not in d or not d['oauth_nonce']:
            d['oauth_nonce'] = randbytes(32)

        if 'oauth_signature_method' not in d or not d['oauth_signature_method']:
            d['oauth_signature_method'] = 'HMAC-SHA1'

        if 'oauth_version' not in d or not d['oauth_version']:
            d['oauth_version'] = '1.0'

        d_ = sorted(d.items(), key=lambda x:x[0])

        dd_ = [urllib.urlencode([x]).replace("+", "%20") for x in d_]
        part3 = urllib.quote("&".join(dd_))
        
        key = consumer_secret + "&"
        if token_secret:
            key += token_secret

        raw = "%s&%s&%s" % (part1, part2, part3)
        
        if d['oauth_signature_method'] != "HMAC-SHA1":
            raise

        hashed = hmac.new(key, raw, hashlib.sha1)
        hashed = binascii.b2a_base64(hashed.digest())[:-1]
        d["oauth_signature"] = hashed
        
        qs = urllib.urlencode(d_).replace("+", "%20")
        qs += "&" + urllib.urlencode({"oauth_signature":hashed})

        return (d, qs)
Example #7
0
def bind_wordpress():
    if not g.user:
        flash(u"请先使用豆瓣、微博、QQ、Twitter任意一个帐号登录后,再来做绑定blog的操作^^", "tip")
        return redirect("/home")
    user = g.user

    intros = [
        g.user.get_thirdparty_profile(x).get("intro")
        for x in config.OPENID_TYPE_DICT.values()
    ]
    intros = filter(None, intros)

    uas = g.user.get_alias()
    wordpress_alias_list = [
        x for x in uas
        if x.type == config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS]
    ]

    step = "1"
    random_id = mc.get("wordpress_bind:%s" % g.user.id)
    c = random_id and Confirmation.get_by_random_id(random_id)
    if c:
        _, feed_uri = c.text.split(":", 1)
        step = "2"
    else:
        feed_uri = ""

    if request.method == "GET":
        return render_template("v2/bind_wordpress.html",
                               consts=consts,
                               **locals())

    elif request.method == "POST":
        ret = {}
        ret['ok'] = False
        if step == '1':
            feed_uri = request.form.get("feed_uri")
            if not feed_uri:
                ret['msg'] = 'feed地址不能为空'
            elif not (feed_uri.startswith("http://")
                      or feed_uri.startswith("https://")):
                ret['msg'] = 'feed地址貌似不对'
            else:
                ua = UserAlias.get(
                    config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS], feed_uri)
                if ua:
                    ret['msg'] = '该feed地址已被绑定'
                else:
                    ##设置一个激活码
                    code = randbytes(16)
                    val = "%s:%s" % (g.user.id, feed_uri)
                    r = Confirmation.add(code, val)
                    if r:
                        ret['ok'] = True
                        ret['msg'] = '为了验证blog的主人^^,请发一篇blog,内容为 %s,完成该步骤后,请点下一步完成绑定' \
                                % code
                        mc.set("wordpress_bind:%s" % g.user.id, code)
                    else:
                        ret['msg'] = '抱歉,出错了,请重试, 或者给管理员捎个话:[email protected]'
            return json_encode(ret)
        elif step == '2':
            if not (random_id and c):
                ret['msg'] = '出错了,激活码不对^^'
            else:
                text = c.text
                user_id, feed_uri = text.split(":", 1)
                ## 同步一下,看看验证码的文章是否正确
                client = Wordpress(feed_uri)
                rs = client.get_feeds(refresh=True)
                if not rs:
                    ret['msg'] = '没有发现含有验证码的文章,请检查后再提交验证'
                else:
                    latest_post = rs[0]
                    if not latest_post:
                        ret['msg'] = "你的feed地址可能无法访问,请检查下"
                    else:
                        content = latest_post.get_content(
                        ) or latest_post.get_summary()
                        if content and content.encode("utf8")[:100].find(
                                str(random_id)) != -1:
                            ua = UserAlias.bind_to_exists_user(
                                g.user, config.OPENID_TYPE_DICT[
                                    config.OPENID_WORDPRESS], feed_uri)
                            if not ua:
                                ret['msg'] = '出错了,麻烦你重试一下吧^^'
                            else:
                                ##添加同步任务
                                t = SyncTask.add(config.CATE_WORDPRESS_POST,
                                                 g.user.id)
                                t and TaskQueue.add(t.id, t.kind)
                                ##删除confiration记录
                                c.delete()
                                mc.delete("wordpress_bind:%s" % g.user.id)

                                ret['ok'] = True
                                ret['msg'] = '恭喜,绑定成功啦'
                        else:
                            ret['msg'] = "没有发现含有验证码的文章,请检查后再提交验证"
            return json_encode(ret)
    else:
        return "method not allowed"
Example #8
0
def bind_wordpress():
    if not g.user:
        flash(u"请先使用豆瓣、微博、QQ、Twitter任意一个帐号登录后,再来做绑定blog的操作^^", "tip")
        return redirect("/home")

    intros = [g.user.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
    intros = filter(None, intros)

    uas = g.user.get_alias()
    wordpress_alias_list = [x for x in uas if x.type == config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS]]

    step = "1"
    random_id = mc.get("wordpress_bind:%s" % g.user.id)
    c = random_id and Confirmation.get_by_random_id(random_id)
    if c:
        _, feed_uri = c.text.split(":", 1)
        step = "2"
    else:
        feed_uri = ""
    

    if request.method == "GET":
        return render_template("bind_wordpress.html", consts=consts, **locals())
    
    elif request.method == "POST":
        ret = {}
        ret['ok'] = False
        if step == '1':
            feed_uri = request.form.get("feed_uri")
            if not feed_uri:
                ret['msg'] = 'feed地址不能为空'
            elif not (feed_uri.startswith("http://") or feed_uri.startswith("https://")):
                ret['msg'] = 'feed地址貌似不对'
            else:
                ua = UserAlias.get(config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS], feed_uri)
                if ua:
                    ret['msg'] = '该feed地址已被绑定'
                else:
                    ##设置一个激活码
                    code = randbytes(16)
                    val = "%s:%s" % (g.user.id, feed_uri)
                    r = Confirmation.add(code, val)
                    if r:
                        ret['ok'] = True
                        ret['msg'] = '为了验证blog的主人^^,请发一篇blog,内容为 %s,完成该步骤后,请点下一步完成绑定' \
                                % code
                        mc.set("wordpress_bind:%s" %g.user.id, code)
                    else:
                        ret['msg'] = '抱歉,出错了,请重试, 或者给管理员捎个话:[email protected]'
            return json_encode(ret)
        elif step == '2':
            if not (random_id and c):
                ret['msg'] = '出错了,激活码不对^^'
            else:
                text = c.text
                user_id, feed_uri = text.split(":", 1)
                ## 同步一下,看看验证码的文章是否正确
                client = Wordpress(feed_uri)
                rs = client.get_feeds(refresh=True)
                if not rs:
                    ret['msg'] = '没有发现含有验证码的文章,请检查后再提交验证'
                else:
                    latest_post = rs[0]
                    if not latest_post:
                        ret['msg'] = "你的feed地址可能无法访问,请检查下"
                    else:
                        content = latest_post.get_content() or latest_post.get_summary()
                        if content and content.encode("utf8")[:100].find(str(random_id)) != -1:
                            ua = UserAlias.bind_to_exists_user(g.user, 
                                    config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS], feed_uri)
                            if not ua:
                                ret['msg'] = '出错了,麻烦你重试一下吧^^'
                            else:
                                ##添加同步任务
                                t = SyncTask.add(config.CATE_WORDPRESS_POST, g.user.id)
                                t and TaskQueue.add(t.id, t.kind)
                                ##删除confiration记录
                                c.delete()
                                mc.delete("wordpress_bind:%s" %g.user.id)

                                ret['ok'] = True
                                ret['msg'] = '恭喜,绑定成功啦'
                        else:
                            ret['msg'] = "没有发现含有验证码的文章,请检查后再提交验证"
            return json_encode(ret)
    else:
        return "method not allowed"
Example #9
0
def set_user_cookie(user, session_):
    if not user:
        return None
    session_id = user.session_id if user.session_id else randbytes(8)
    user.update_session(session_id)
    session_[config.SITE_COOKIE] = "%s:%s" % (user.id, session_id)
Example #10
0
def set_user_cookie(user, session_):
    if not user:
        return None
    session_id = user.session_id if user.session_id else randbytes(8)
    user.update_session(session_id)
    session_[config.SITE_COOKIE] = "%s:%s" % (user.id, session_id)
Example #11
0
def pdf(uid):
    from xhtml2pdf.default import DEFAULT_FONT
    from xhtml2pdf.document import pisaDocument

    #########Set FONT################
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    pdfmetrics.registerFont(TTFont('zhfont', os.path.join(app.root_path, 'static/font/yahei-consolas.ttf')))
    DEFAULT_FONT["helvetica"]="zhfont"
    css = open(os.path.join(app.root_path, "static/css/pdf.css")).read()

    result = StringIO.StringIO()

    user = User.get(uid)
    if not g.user:
        ##匿名用户暂时只能看我的作为演示
        g.count = min(25, g.count)
        user = User.get(config.MY_USER_ID)
    else:
        if g.user.id == user.id:
            if g.count < 60:
                g.count = 60
            g.count = min(100, g.count)
        else:
            ##登录用户只能生成别人的25条
            g.count = min(25, g.count)

    # get status
    ids = Status.get_ids(user_id=uid, start=g.start, limit=g.count, cate=g.cate)
    status_list = Status.gets(ids)

    _html = u"""<html> <body>
        <div id="Top">
            <img src="%s"/> &nbsp; &nbsp;&nbsp; The Past of Me | 个人杂志计划&nbsp;&nbsp;&nbsp;%s&nbsp;&nbsp;&nbsp;CopyRight©%s
            <br/>
        </div>
        <br/> <br/>

        <div class="box">
    """ %(os.path.join(app.root_path, "static/img/logo.png"), 
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), user.name)

    for s in status_list:
        title = s.title
        create_time = s.create_time
        from_ = ''
        if s.category == config.CATE_DOUBAN_MINIBLOG:
            from_ = u'<a href="' + config.DOUBAN_MINIBLOG %(s.origin_user_id, s.origin_id) + u'class="node">From:豆瓣广播</a>'
        elif s.category == config.CATE_DOUBAN_NOTE:
            from_ = u'<a href="' + config.DOUBAN_NOTE %(s.origin_id,) + u'class="node">From:豆瓣日记</a>'
        elif s.category == config.CATE_SINA_STATUS:
            from_ = u'<a href="' + config.WEIBO_STATUS %(s.origin_id) + u'class="node">From:新浪微博</a>'
        elif s.category == config.CATE_TWITTER_STATUS:
            from_ = u'<a href="' + config.TWITTER_STATUS %(s.origin_id) + u'class="node">From:twitter</a>'
        text = s.text
        retweeted_text = ''
        img = ''
        if s.category == config.CATE_DOUBAN_MINIBLOG:
            ##miniblog不显示title
            title = ''
            links = s.get_data().get_links()
            if links and links.get("image"):
                img = links.get("image")
        elif s.category == config.CATE_SINA_STATUS:
            retweeted = s.get_data().get_retweeted_status()
            re_mid_pic = retweeted and retweeted.get_middle_pic() or ''
            middle_pic = s.get_data().get_middle_pic()

            if retweeted:
                retweeted_text = retweeted.get_user().get_nickname() + ": " + retweeted.get_content()
                    
            if re_mid_pic or middle_pic:
                img = re_mid_pic or middle_pic
        
        _html += """ <hr/> <div class="cell">"""
        if title:
            title = wrap_long_line(title)
            _html += """<div class="bigger">%s</div>""" %title
        if text:
            text = wrap_long_line(text)
            if s.category == config.CATE_DOUBAN_NOTE:
                text = filters.nl2br(text)
            _html += """<div class="content">%s</div>""" %text
        if retweeted_text:
            retweeted_text = wrap_long_line(retweeted_text)
            _html += """<div class='tip'><span class="fade">%s</span></div>""" %retweeted_text
        if img:
            _html += """<img src=%s></img>""" %img
        _html += """<div class="fade">%s &nbsp;&nbsp;&nbsp; %s</div>""" %(from_, create_time)
        _html += """ </div> <body> </html> """

    _pdf = pisaDocument(_html, result, default_css=css, link_callback=link_callback)

    if not _pdf.err:
        result.seek(0)
        pdf_filename = "thepast.me_pdf_%s%s.pdf" %(user.id, randbytes(6))
        save_pdf(result.getvalue(), pdf_filename)
        #resp = make_response(result.getvalue())
        #resp.headers["content-type"] = "application/pdf"
        resp = make_response()
        resp.headers['Cache-Control'] = 'no-cache'
        resp.headers['Content-Type'] = 'application/pdf'
        redir = '/down/pdf/' + pdf_filename
        resp.headers['X-Accel-Redirect'] = redir
        return resp
    else:
        return 'pdf error: %s' %_pdf.err