Example #1
0
def user_explore():
    g.count = 24
    user_ids = User.get_ids(start=g.start, limit=g.count)
    users = [User.get(x) for x in user_ids]
    users = [x for x in users if x.get_profile_item('user_privacy') != consts.USER_PRIVACY_PRIVATE]
    return render_template("user_explore.html",
            users=users, config=config)
Example #2
0
def user_explore():
    g.count = 24
    user_ids = User.get_ids(start=g.start, limit=g.count)
    users = [User.get(x) for x in user_ids]
    users = [x for x in users if x.get_profile_item('user_privacy') != consts.USER_PRIVACY_PRIVATE]
    return render_template("user_explore.html",
            users=users, config=config)
Example #3
0
def _save_user_and_token(token_dict, user_info, openid_type):
    ua = UserAlias.get(openid_type, user_info.get_user_id())
    if not ua:
        if not g.user:
            ua = UserAlias.create_new_user(openid_type,
                    user_info.get_user_id(), user_info.get_nickname())
        else:
            ua = UserAlias.bind_to_exists_user(g.user, 
                    openid_type, user_info.get_user_id())
    if not ua:
        return None

    ##设置个人资料(头像等等)
    u = User.get(ua.user_id)
    u.set_avatar_url(user_info.get_avatar())
    u.set_icon_url(user_info.get_icon())

    ##保存access token
    if openid_type == config.OPENID_TYPE_DICT[config.OPENID_TWITTER]:
        OAuth2Token.add(ua.id, token_dict.get("access_token"), 
                token_dict.get("access_token_secret", ""))
    else:
        OAuth2Token.add(ua.id, token_dict.get("access_token"), 
                token_dict.get("refresh_token", ""))
    ##set cookie,保持登录状态
    if not g.user:
        g.user = User.get(ua.user_id)
        set_user_cookie(g.user, session)
    
    return g.user
Example #4
0
def remove_user(uid):
    user = User.get(uid)
    if not user:
        print '---no user:%s' % uid

    print "---- delete from user, uid=", uid
    db_conn.execute("delete from user where id=%s", uid)
    db_conn.commit()
    User._clear_cache(uid)

    cursor = db_conn.execute("select id from status where user_id=%s", uid)
    if cursor:
        rows = cursor.fetchall()
        for row in rows:
            sid = row[0]
            print "---- delete mongo text, sid=", sid
            RawStatus.remove(sid)

    print "---- delete from status, uid=", uid
    db_conn.execute("delete from status where user_id=%s", uid)
    db_conn.commit()
    Status._clear_cache(uid, None)

    print "---- delete from passwd, uid=", uid
    db_conn.execute("delete from passwd where user_id=%s", uid)
    print "---- delete from sync_task, uid=", uid
    db_conn.execute("delete from sync_task where user_id=%s", uid)
    print "---- delete from user_alias, uid=", uid
    db_conn.execute("delete from user_alias where user_id=%s", uid)
    db_conn.commit()
Example #5
0
def remove_user(uid, clear_status=True):
    user = User.get(uid)
    if not user:
        print "---no user:%s" % uid

    suicide_log.info("---- delete from user, uid=%s" % uid)
    db_conn.execute("delete from user where id=%s", uid)
    db_conn.commit()
    User._clear_cache(uid)

    if clear_status:
        cursor = db_conn.execute("select id from status where user_id=%s", uid)
        if cursor:
            rows = cursor.fetchall()
            for row in rows:
                sid = row[0]
                suicide_log.info("---- delete status text, sid=%s" % sid)
                RawStatus.remove(sid)

        suicide_log.info("---- delete from status, uid=" % uid)
        db_conn.execute("delete from status where user_id=%s", uid)
        db_conn.commit()
        Status._clear_cache(uid, None)

    suicide_log.info("---- delete from passwd, uid=%s" % uid)
    db_conn.execute("delete from passwd where user_id=%s", uid)
    suicide_log.info("---- delete from sync_task, uid=%s" % uid)
    db_conn.execute("delete from sync_task where user_id=%s", uid)
    suicide_log.info("---- delete from user_alias, uid=%s" % uid)
    db_conn.execute("delete from user_alias where user_id=%s", uid)
    db_conn.commit()
Example #6
0
def remove_user(uid, clear_status=True):
    user = User.get(uid)
    if not user:
        print '---no user:%s' % uid

    suicide_log.info("---- delete from user, uid=%s" % uid)
    db_conn.execute("delete from user where id=%s", uid)
    db_conn.commit()
    User._clear_cache(uid)

    if clear_status:
        cursor = db_conn.execute("select id from status where user_id=%s", uid)
        if cursor:
            rows = cursor.fetchall()
            for row in rows:
                sid = row[0]
                suicide_log.info("---- delete status text, sid=%s" % sid)
                RawStatus.remove(sid)

        suicide_log.info("---- delete from status, uid=" % uid)
        db_conn.execute("delete from status where user_id=%s", uid)
        db_conn.commit()
        Status._clear_cache(uid, None)

    suicide_log.info("---- delete from passwd, uid=%s" % uid)
    db_conn.execute("delete from passwd where user_id=%s", uid)
    suicide_log.info("---- delete from sync_task, uid=%s" % uid)
    db_conn.execute("delete from sync_task where user_id=%s", uid)
    suicide_log.info("---- delete from user_alias, uid=%s" % uid)
    db_conn.execute("delete from user_alias where user_id=%s", uid)
    db_conn.commit()
Example #7
0
def home():
    user_ids = User.get_ids(limit=10000)

    user = None
    i = 0
    while i <= 3:
        random_uid = random.choice(user_ids)
        user = User.get(random_uid)
        r = check_access_user(user)
        if not r:
            break
        i+=1

    if user:
        history_ids = Status.get_ids(user.id, start=0, limit=20)
        status_list = Status.gets(history_ids)
        status_list  = statuses_timelize(status_list)
        intros = [user.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
        intros = filter(None, intros)
    else:
        status_list = []
        intros = []

    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

    d = defaultdict(list)
    for x in status_list:
        t = x.create_time.strftime("%Y年%m月%d日")
        d[t].append(x)
    history_status = d

    return render_template("v2/explore.html", **locals())
Example #8
0
def before_request():
    g.user = auth_user_from_session(session)
    g.user = User.get(8)
    if g.user:
        g.user_alias = UserAlias.gets_by_user_id(g.user.id)
    else:
        g.user_alias = None

    if g.user:
        unbinded = list(set(config.OPENID_TYPE_DICT.values()) - 
                set([ua.type for ua in g.user.get_alias()]) - set([config.OPENID_TYPE_DICT[config.OPENID_THEPAST]]))
        tmp = {}
        for k, v in config.OPENID_TYPE_DICT.items():
            tmp[v] = k
        g.unbinded = [[x, tmp[x], config.OPENID_TYPE_NAME_DICT[x]] for x in unbinded]

        expired_providers = []
        for t in [ua.type for ua in g.user.get_alias()]:
            p = g.user.get_thirdparty_profile(t)
            if p and p.get("expired"):
                _ = [t, config.OPENID_TYPE_DICT_REVERSE.get(t), config.OPENID_TYPE_NAME_DICT.get(t, "")]
                expired_providers.append(_)
        if expired_providers:
            msg = " ".join([x[-1] for x in expired_providers])
            flash(u"你的 %s 授权已经过期了,会影响数据同步,你可以重新授权 :)" % msg, "tip")
    else:
        g.unbinded = None

    g.start = int(request.args.get('start', 0))
    g.count = int(request.args.get('count', 30))
    g.cate = request.args.get("cate", "")
    if not g.cate.isdigit():
        g.cate = ""
Example #9
0
def send_today_in_history(user_id):
    u = User.get(user_id)
    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == 'N':
        print '---user %s does not like to receive remind mail' % u.id
        return

    email = u.get_email()
    if not email:
        print '---- user %s no email' % u.id
        return
    
    yesterday_ids = get_status_ids_yesterday(u.id, 
            day=(datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d"))
    status_of_yesterday = Status.gets(yesterday_ids)

    history_ids = get_status_ids_today_in_history(u.id, 
            day=datetime.datetime.now().strftime("%Y-%m-%d"))
    status_of_today_in_history = Status.gets(history_ids)

    intros = [u.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
    intros = filter(None, intros)
    
    history_ids = get_status_ids_today_in_history(u.id, 
            day=datetime.datetime.now().strftime("%Y-%m-%d"))
    d = {}
    for s in Status.gets(history_ids):
        t = s.create_time.strftime("%Y-%m-%d")
        if d.has_key(t):
            d[t].append(s)
        else:
            d[t] = [s]
    status_of_today_in_history = d
    from past.consts import YESTERDAY


    if not (status_of_yesterday or status_of_today_in_history):
        print '--- user %s has no status in history' % u.id
        return

    from jinja2 import Environment, PackageLoader
    env = Environment(loader=PackageLoader('past', 'templates'))
    env.filters['wrap_long_line'] = wrap_long_line
    env.filters['nl2br'] = filters.nl2br
    env.filters['clear_html_element'] = clear_html_element
    t = env.get_template('mail.html')
    m = t.module


    html = m.status_in_past(status_of_yesterday, status_of_today_in_history, YESTERDAY, config, intros)
    html = html.encode("utf8")

    subject = '''来自thepast.me的提醒 %s''' % datetime.datetime.now().strftime("%Y-%m-%d")
    text = ''
    
    print '--- send reminding to %s %s' %(user_id, email)
    send_mail(["%s" % email], "Today of The Past<*****@*****.**>", subject, text, html, files=[], server="localhost")
Example #10
0
def generate_pdf(filename, uid, start, count, cate=None, with_head=True, capacity=50*1024):

    #########Set FONT################
    from xhtml2pdf.default import DEFAULT_FONT
    from xhtml2pdf.document import pisaDocument
    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()
    full_file_name = get_pdf_full_filename(filename)
    if not full_file_name:
        return None
    result = open(full_file_name, 'wb', 1024*1000)

    user = User.get(uid)
    if not user:
        return None

    # get status
    ids = Status.get_ids(user_id=uid, start=start, limit=count, cate=cate)
    status_list = Status.gets(ids)
    _html = render(user, status_list, with_head)
    _pdf = pisaDocument(_html, result, default_css=css, link_callback=link_callback, capacity=capacity)
    result.close()

    if not _pdf.err:
        return full_file_name
    else:
        return None
Example #11
0
def send_pdf(user_id):
    u = User.get(user_id)

    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == 'N':
        print '---user %s does not like to receive remind mail' % u.id
        return

    email = u.get_email()
    if not email:
        print '---- user %s no email' % u.id
        return

    subject = '''你在thepast.me上的timeline PDF版本'''
    text = '''Hi,感谢你使用thepast.me来聚合、管理、备份自己的timeline.

离线PDF版本现在可以下载了,请猛击 http://thepast.me/%s/pdf

http://thepast.me | 个人杂志计划
thanks''' % user_id
    
    print '--- send pdf file to %s %s' %(user_id, email)
    send_mail(["%s" % email], "thepast<*****@*****.**>", subject, text, "")
Example #12
0
def tag(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")
    count = min(g.count, 50)
    kws = get_keywords(u.id, count)
    return ",".join([x[0] for x in kws])
Example #13
0
def cmd_bind(from_user, thepast_id):
    u = User.get(thepast_id)
    if not u:
        return "不存在这个id啊,是不是搞错了啊"

    UserWeixin.add(u.id, from_user)
    return "绑定成功了,输入「past 日期」查看过往的碎碎念"
Example #14
0
def send_reconnect(user_id):
    u = User.get(user_id)

    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == 'N':
        print '---user %s does not like to receive remind mail' % u.id
        return

    excps = [
        OAuthTokenExpiredError(user_id, x)
        for x in config.OPENID_TYPE_DICT.values()
    ]
    expires_site = {}
    for e in excps:
        t = e.is_exception_exists()
        if t:
            expires_site[e.openid_type] = t

    if not expires_site:
        print '--- user %s has no expired connection' % u.id
        return
    else:
        print '--- user %s expired connection: %s' % (u.id, expires_site)

    email = u.get_email()
    if not email:
        print '---- user %s no email' % u.id
        return

    names = []
    reconnect_urls = []
    for x in expires_site.keys():
        names.append(config.OPENID_TYPE_NAME_DICT.get(x, ""))
        reconnect_urls.append("http://thepast.me/connect/%s" %
                              config.OPENID_TYPE_DICT_REVERSE.get(x))

    subject = '''thepast.me授权过期提醒'''
    text = '''Hi,亲爱的%s,
    
感谢你使用thepast.me来整理自己的互联网印迹.
    
你在 %s 对thepast的授权过期了,影响到您的个人历史数据同步,

请依次访问下面的链接,重新授权:)

%s



如果你不愿意接收此类邮件,那么请到 http://thepast.me/settings 设置:)
---
http://thepast.me 
thanks''' % (u.name.encode("utf8"), ", ".join(names).encode("utf8"),
             "\n".join(reconnect_urls))

    print '--- send reconnections to %s %s' % (user_id, email)
    send_mail(["%s" % email], "thepast<*****@*****.**>", subject, text, "")
Example #15
0
def user_notes(uid):
    
    user = User.get(uid)
    if not user:
        abort(403, "no_such_user")

    return redirect("/user/%s?cate=%s" % (uid, config.CATE_THEPAST_NOTE))
Example #16
0
def visual(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    return render_template("visual_timeline.html", user=u, unbinded=[], 
            config=config)
Example #17
0
def tag(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")
    count = min(g.count, 50)
    kws = get_keywords(u.id, count)
    return ",".join([x[0] for x in kws])
Example #18
0
def pdf_down(filename):
    pdf_filename = filename
    if not is_pdf_file_exists(pdf_filename):
        abort(
            404,
            "Please wait one day to  download the PDF version, because the vps memory is limited"
        )

    user_id = pdf_filename.split('_')[1]
    u = User.get(user_id)
    if not u:
        abort(400, 'Bad request')

    if user_id != g.user.id and u.get_profile_item(
            'user_privacy') == consts.USER_PRIVACY_PRIVATE:
        abort(403, 'Not allowed')

    full_file_name = get_pdf_full_filename(pdf_filename)
    resp = make_response()
    resp.headers['Cache-Control'] = 'no-cache'
    resp.headers['Content-Type'] = 'application/pdf'
    resp.headers[
        'Content-Disposition'] = 'attachment; filename=%s' % pdf_filename
    resp.headers['Content-Length'] = os.path.getsize(full_file_name)
    redir = '/down/pdf/' + pdf_filename
    resp.headers['X-Accel-Redirect'] = redir
    return resp
Example #19
0
def generate_pdf(filename, uid, status_ids, with_head=True, capacity=50*1024):

    #########Set FONT################
    from xhtml2pdf.default import DEFAULT_FONT
    from xhtml2pdf.document import pisaDocument
    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()
    full_file_name = get_pdf_full_filename(filename)
    if not full_file_name:
        return None
    result = open(full_file_name, 'wb', 1024*1000)

    user = User.get(uid)
    if not user:
        return None

    # get status
    status_list = Status.gets(status_ids)
    _html = render(user, status_list, with_head)
    _pdf = pisaDocument(_html, result, default_css=css, link_callback=link_callback, capacity=capacity)
    result.close()

    if not _pdf.err:
        return full_file_name
    else:
        return None
Example #20
0
def pdf(uid):
    user = User.get(uid)
    if not user:
        abort(404, "No such user")

    if uid != g.user.id and user.get_profile_item('user_privacy') == consts.USER_PRIVACY_PRIVATE:
        flash(u"由于该用户设置了仅自己可见的权限,所以,我们就看不到了", "tip")
        return redirect(url_for("timeline"))

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

    pdf_files = []
    start_date = Status.get_oldest_create_time(None, user.id)
    now = datetime.now()
    d = start_date
    while d and d <= now:
        pdf_filename = get_pdf_filename(user.id, d.strftime("%Y%m"))
        if is_pdf_file_exists(pdf_filename):
            full_file_name = get_pdf_full_filename(pdf_filename)
            pdf_files.append([d, pdf_filename, sizeof_fmt(os.path.getsize(full_file_name))])

        days = calendar.monthrange(d.year, d.month)[1]
        d += timedelta(days=days)
        d = datetime(d.year, d.month, 1)
    files_dict = defaultdict(list)
    for date, filename, filesize in pdf_files:
        files_dict[date.year].append([date, filename, filesize])

    pdf_applyed = PdfSettings.is_user_id_exists(g.user.id)
    return render_template("pdf.html", **locals())
Example #21
0
def user_by_domain(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    r = check_access_user(u)
    if r:
        flash(r[1].decode("utf8"), "tip")
        return redirect(url_for("home"))

    ids = Status.get_ids(user_id=u.id, start=g.start, limit=g.count, cate=g.cate)
    status_list = Status.gets(ids)
    if g.user and g.user.id == uid:
        pass
    elif g.user and g.user.id != uid:
        status_list = [x for x in status_list if x.privacy() != consts.STATUS_PRIVACY_PRIVATE]
    elif not g.user:
        status_list = [x for x in status_list if x.privacy() == consts.STATUS_PRIVACY_PUBLIC]
        
    status_list  = statuses_timelize(status_list)
    tags_list = []
    intros = [u.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
    intros = filter(None, intros)

    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

    return render_template("timeline.html", user=u, unbinded=[], 
            tags_list=tags_list, intros=intros, 
            status_list=status_list, config=config, sync_list=sync_list)
Example #22
0
def user_notes(uid):

    user = User.get(uid)
    if not user:
        abort(403, "no_such_user")

    return redirect("/user/%s?cate=%s" % (uid, config.CATE_THEPAST_NOTE))
Example #23
0
def pdf(uid):
    user = User.get(uid)
    if not user:
        abort(404, "No such user")

    if uid != g.user.id and user.get_profile_item('user_privacy') == consts.USER_PRIVACY_PRIVATE:
        flash(u"由于该用户设置了仅自己可见的权限,所以,我们就看不到了", "tip")
        return redirect("/")

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

    pdf_files = []
    start_date = Status.get_oldest_create_time(None, user.id)
    now = datetime.now()
    d = start_date
    while d and d <= now:
        pdf_filename = get_pdf_filename(user.id, d.strftime("%Y%m"))
        if is_pdf_file_exists(pdf_filename):
            full_file_name = get_pdf_full_filename(pdf_filename)
            pdf_files.append([d, pdf_filename, sizeof_fmt(os.path.getsize(full_file_name))])

        days = calendar.monthrange(d.year, d.month)[1]
        d += timedelta(days=days)
        d = datetime(d.year, d.month, 1)
    files_dict = defaultdict(list)
    for date, filename, filesize in pdf_files:
        files_dict[date.year].append([date, filename, filesize])

    pdf_applyed = PdfSettings.is_user_id_exists(g.user.id)
    return render_template("v2/pdf.html", **locals())
Example #24
0
def user_more_by_domain(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    r = check_access_user(u)
    if r:
        abort(400, "no priv to access")

    ids = Status.get_ids(user_id=u.id, start=g.start, limit=g.count, cate=g.cate)
    status_list = Status.gets(ids)
    if g.user and g.user.id == uid:
        pass
    elif g.user and g.user.id != uid:
        status_list = [x for x in status_list if x.privacy() != consts.STATUS_PRIVACY_PRIVATE]
    elif not g.user:
        status_list = [x for x in status_list if x.privacy() == consts.STATUS_PRIVACY_PUBLIC]
        
    status_list  = statuses_timelize(status_list)
    intros = [u.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
    intros = filter(None, intros)

    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

    now = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
    return render_template("v2/user_more.html", user=u, intros=intros, 
            status_list=status_list, config=config, sync_list=sync_list, 
            now = now)
Example #25
0
def user(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    if g.user and g.user.id == u.id:
        return redirect(url_for("timeline"))
    
    if u.get_profile_item('user_privacy') == consts.USER_PRIVACY_PRIVATE:
        flash(u"由于该用户设置了仅自己可见的权限,所以,我们就看不到了", "tip")
        return redirect(url_for("timeline"))

    #TODO:增加可否查看其他用户的权限检查
    cate = request.args.get("cate", None)
    ids = Status.get_ids(user_id=u.id, start=g.start, limit=g.count, cate=g.cate)
    status_list = Status.gets(ids)
    status_list  = statuses_timelize(status_list)
    if status_list:
        ##XXX:暂时去除了个人关键字的功能
        #tags_list = [x[0] for x in get_keywords(u.id, 30)]
        tags_list = []
    else:
        tags_list = []
    intros = [u.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
    intros = filter(None, intros)
    return render_template("timeline.html", user=u, unbinded=[], 
            tags_list=tags_list, intros=intros, status_list=status_list, config=config)
Example #26
0
def cmd_bind(from_user, thepast_id):
    u = User.get(thepast_id)
    if not u:
        return "不存在这个id啊,是不是搞错了啊"

    UserWeixin.add(u.id, from_user)
    return "绑定成功了,输入「past 日期」查看过往的碎碎念"
Example #27
0
def send_pdf(user_id):
    u = User.get(user_id)

    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == 'N':
        print '---user %s does not like to receive remind mail' % u.id
        return

    email = u.get_email()
    if not email:
        print '---- user %s no email' % u.id
        return

    subject = '''你在thepast.me上的timeline PDF版本'''
    text = '''Hi,感谢你使用thepast.me来聚合、管理、备份自己的timeline.

离线PDF版本现在可以下载了,请猛击 http://thepast.me/%s/pdf

http://thepast.me | 个人杂志计划
thanks''' % user_id
    
    print '--- send pdf file to %s %s' %(user_id, email)
    send_mail(["%s" % email], "*****@*****.**", subject, text, '', files=[], server="localhost")
Example #28
0
def _save_user_and_token(token_dict, thirdparty_user, openid_type):
    first_connect = False
    ua = UserAlias.get(openid_type, thirdparty_user.get_user_id())
    if not ua:
        if not g.user:
            ua = UserAlias.create_new_user(openid_type,
                                           thirdparty_user.get_user_id(),
                                           thirdparty_user.get_nickname())
        else:
            ua = UserAlias.bind_to_exists_user(g.user, openid_type,
                                               thirdparty_user.get_user_id())
        first_connect = True
    if not ua:
        return None

    ##设置个人资料(头像等等)
    u = User.get(ua.user_id)
    u.set_avatar_url(thirdparty_user.get_avatar())
    u.set_icon_url(thirdparty_user.get_icon())

    ##把各个第三方的uid保存到profile里面
    k = openid_type
    v = {
        "uid": thirdparty_user.get_uid(),
        "name": thirdparty_user.get_nickname(),
        "intro": thirdparty_user.get_intro(),
        "signature": thirdparty_user.get_signature(),
        "avatar": thirdparty_user.get_avatar(),
        "icon": thirdparty_user.get_icon(),
        "email": thirdparty_user.get_email(),
        "first_connect": "Y" if first_connect else "N",
    }
    u.set_profile_item(k, json_encode(v))

    ##保存access token
    if openid_type == config.OPENID_TYPE_DICT[config.OPENID_TWITTER]:
        OAuth2Token.add(ua.id, token_dict.get("access_token"),
                        token_dict.get("access_token_secret", ""))
    else:
        OAuth2Token.add(ua.id, token_dict.get("access_token"),
                        token_dict.get("refresh_token", ""))
    ##set cookie,保持登录状态
    if not g.user:
        g.user = User.get(ua.user_id)
        set_user_cookie(g.user, session)

    return g.user
Example #29
0
def send_reconnect(user_id):
    u = User.get(user_id)

    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == "N":
        print "---user %s does not like to receive remind mail" % u.id
        return

    excps = [OAuthTokenExpiredError(user_id, x) for x in config.OPENID_TYPE_DICT.values()]
    expires_site = {}
    for e in excps:
        t = e.is_exception_exists()
        if t:
            expires_site[e.openid_type] = t

    if not expires_site:
        print "--- user %s has no expired connection" % u.id
        return
    else:
        print "--- user %s expired connection: %s" % (u.id, expires_site)

    email = u.get_email()
    if not email:
        print "---- user %s no email" % u.id
        return

    names = []
    reconnect_urls = []
    for x in expires_site.keys():
        names.append(config.OPENID_TYPE_NAME_DICT.get(x, ""))
        reconnect_urls.append("http://thepast.me/connect/%s" % config.OPENID_TYPE_DICT_REVERSE.get(x))

    subject = """thepast.me授权过期提醒"""
    text = """Hi,亲爱的%s,
    
感谢你使用thepast.me来整理自己的互联网印迹.
    
你在 %s 对thepast的授权过期了,影响到您的个人历史数据同步,

请依次访问下面的链接,重新授权:)

%s



如果你不愿意接收此类邮件,那么请到 http://thepast.me/settings 设置:)
---
http://thepast.me 
thanks""" % (
        u.name.encode("utf8"),
        ", ".join(names).encode("utf8"),
        "\n".join(reconnect_urls),
    )

    print "--- send reconnections to %s %s" % (user_id, email)
    send_mail(["%s" % email], "thepast<*****@*****.**>", subject, text, "")
Example #30
0
def generate_docs_file(file_):
    from past.model.user import User
    uids = User.get_ids(start=0, limit=400)
    with open(file_, "aw") as f:
        for x in uids:
            print 'get user %s text' % x
            text = get_all_text_by_user(x)
            f.write(text.encode("utf8"))
Example #31
0
def home():
    user_ids = Status.get_recent_updated_user_ids()
    users = filter(None, [User.get(x) for x in user_ids])
    users = [
        x for x in users
        if x.get_profile_item('user_privacy') != consts.USER_PRIVACY_PRIVATE
    ]
    return render_template("home.html", users=users, config=config)
Example #32
0
def _save_user_and_token(token_dict, thirdparty_user, openid_type):
    first_connect = False
    ua = UserAlias.get(openid_type, thirdparty_user.get_user_id())
    if not ua:
        if not g.user:
            ua = UserAlias.create_new_user(openid_type,
                    thirdparty_user.get_user_id(), thirdparty_user.get_nickname())
        else:
            ua = UserAlias.bind_to_exists_user(g.user, 
                    openid_type, thirdparty_user.get_user_id())
        first_connect = True
    if not ua:
        return None

    ##设置个人资料(头像等等)
    u = User.get(ua.user_id)
    u.set_avatar_url(thirdparty_user.get_avatar())
    u.set_icon_url(thirdparty_user.get_icon())

    ##把各个第三方的uid保存到profile里面
    k = openid_type
    v = {
        "uid": thirdparty_user.get_uid(), 
        "name": thirdparty_user.get_nickname(), 
        "intro": thirdparty_user.get_intro(),
        "signature": thirdparty_user.get_signature(),
        "avatar": thirdparty_user.get_avatar(),
        "icon": thirdparty_user.get_icon(),
        "email": thirdparty_user.get_email(),
        "first_connect": "Y" if first_connect else "N",
    }
    u.set_profile_item(k, json_encode(v))

    ##保存access token
    if openid_type == config.OPENID_TYPE_DICT[config.OPENID_TWITTER]:
        OAuth2Token.add(ua.id, token_dict.get("access_token"), 
                token_dict.get("access_token_secret", ""))
    else:
        OAuth2Token.add(ua.id, token_dict.get("access_token"), 
                token_dict.get("refresh_token", ""))
    ##set cookie,保持登录状态
    if not g.user:
        g.user = User.get(ua.user_id)
        set_user_cookie(g.user, session)
    
    return g.user
Example #33
0
 def set_the_profile(self, flush=False):
     if self.user_id:
         u = User.get(self.user_id)
         if u:
             if flush:
                 u.set_thirdparty_profile_item(self.openid_type, self.msg_type, datetime.datetime.now())
             else:
                 p = u.get_thirdparty_profile(self.openid_type)
                 t = p and p.get(self.msg_type)
                 u.set_thirdparty_profile_item(self.openid_type, self.msg_type, t or datetime.datetime.now())
Example #34
0
def auth_user_from_session(session_):
    user = None
    if config.SITE_COOKIE in session_:
        cookies = session_[config.SITE_COOKIE]
        user_id, session_id = cookies.split(":")
        _user = User.get(user_id)
        if _user and _user.session_id == session_id:
            user = _user

    return user 
Example #35
0
def visual(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    r = check_access_user(u)
    if r:
        flash(r[1].decode("utf8"), "tip")
        return redirect(url_for("timeline"))

    return render_template("visual_timeline.html", user=u, unbinded=[], config=config)
Example #36
0
def visual(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    if uid != g.user.id and u.get_profile_item('user_privacy') == consts.USER_PRIVACY_PRIVATE:
        flash(u"由于该用户设置了仅自己可见的权限,所以,我们就看不到了", "tip")
        return redirect(url_for("timeline"))

    return render_template("visual_timeline.html", user=u, unbinded=[], 
            config=config)
Example #37
0
def send_yesterday(user_id, now=None):
    if not now:
        now = datetime.datetime.now()

    u = User.get(user_id)
    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == 'N':
        print '---user %s does not like to receive remind mail' % u.id
        return

    email = u.get_email()
    if not email:
        print '---- user %s no email' % u.id
        return

    yesterday_ids = get_status_ids_yesterday(u.id, now)
    status_of_yesterday = Status.gets(yesterday_ids)

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

    from past.consts import YESTERDAY

    if not status_of_yesterday:
        print '--- user %s has no status in yesterday' % u.id
        return

    from jinja2 import Environment, PackageLoader
    env = Environment(loader=PackageLoader('past', 'templates'))
    env.filters['wrap_long_line'] = wrap_long_line
    env.filters['nl2br'] = filters.nl2br
    env.filters['stream_time'] = filters.stream_time
    env.filters['clear_html_element'] = clear_html_element
    t = env.get_template('mail.html')
    m = t.module

    if now:
        y = (now - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    else:
        y = YESTERDAY
    html = m.status_in_past(status_of_yesterday, None, y, config, intros)
    html = html.encode("utf8")

    subject = '''thepast.me|整理自己的故事 %s''' % now.strftime("%Y-%m-%d")
    text = ''

    print '--- send reminding to %s %s' % (user_id, email)
    send_mail(["%s" % email], "thepast<*****@*****.**>", subject, text, html)
Example #38
0
def auth_user_from_session(session_):
    user = None
    if config.SITE_COOKIE in session_:
        cookies = session_[config.SITE_COOKIE]
        user_id, session_id = cookies.split(":")
        ## 这里存在循环引用,所以放到函数内部,长远看这个函数不应该放在corelib中
        from past.model.user import User
        _user = User.get(user_id)
        if _user and _user.session_id == session_id:
            user = _user

    return user 
Example #39
0
def auth_user_from_session(session_):
    user = None
    if config.SITE_COOKIE in session_:
        cookies = session_[config.SITE_COOKIE]
        user_id, session_id = cookies.split(":")
        ## 这里存在循环引用,所以放到函数内部,长远看这个函数不应该放在corelib中
        from past.model.user import User
        _user = User.get(user_id)
        if _user and _user.session_id == session_id:
            user = _user

    return user
Example #40
0
def send_yesterday(user_id, now=None):
    if not now:
        now = datetime.datetime.now()

    u = User.get(user_id)
    if not u:
        return

    setting = u.get_profile_item("email_remind_today_in_history")
    if setting == "N":
        print "---user %s does not like to receive remind mail" % u.id
        return

    email = u.get_email()
    if not email:
        print "---- user %s no email" % u.id
        return

    yesterday_ids = get_status_ids_yesterday(u.id, now)
    status_of_yesterday = Status.gets(yesterday_ids)

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

    from past.consts import YESTERDAY

    if not status_of_yesterday:
        print "--- user %s has no status in yesterday" % u.id
        return

    from jinja2 import Environment, PackageLoader

    env = Environment(loader=PackageLoader("past", "templates"))
    env.filters["wrap_long_line"] = wrap_long_line
    env.filters["nl2br"] = filters.nl2br
    env.filters["stream_time"] = filters.stream_time
    env.filters["clear_html_element"] = clear_html_element
    t = env.get_template("mail.html")
    m = t.module

    if now:
        y = (now - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    else:
        y = YESTERDAY
    html = m.status_in_past(status_of_yesterday, None, y, config, intros)
    html = html.encode("utf8")

    subject = """thepast.me|整理自己的故事 %s""" % now.strftime("%Y-%m-%d")
    text = ""

    print "--- send reminding to %s %s" % (user_id, email)
    send_mail(["%s" % email], "thepast<*****@*****.**>", subject, text, html)
Example #41
0
def user(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    if g.user and g.user.id == u.id:
        return redirect(url_for("index"))
    
    #TODO:增加可否查看其他用户的权限检查
    cate = request.args.get("cate", None)
    ids = Status.get_ids(user_id=u.id, start=g.start, limit=g.count, cate=g.cate)
    status_list = Status.gets(ids)
    return render_template("timeline.html", user=u, status_list=status_list, config=config)
Example #42
0
def home():
    user_ids = User.get_ids(limit=10000)

    user = None
    i = 0
    while i <= 3:
        random_uid = random.choice(user_ids)
        user = User.get(random_uid)
        r = check_access_user(user)
        if not r:
            break
        i += 1

    if user:
        history_ids = Status.get_ids(user.id, start=0, limit=20)
        status_list = Status.gets(history_ids)
        status_list = statuses_timelize(status_list)
        intros = [
            user.get_thirdparty_profile(x).get("intro")
            for x in config.OPENID_TYPE_DICT.values()
        ]
        intros = filter(None, intros)
    else:
        status_list = []
        intros = []

    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

    d = defaultdict(list)
    for x in status_list:
        t = x.create_time.strftime("%Y年%m月%d日")
        d[t].append(x)
    history_status = d

    return render_template("v2/explore.html", **locals())
Example #43
0
def post(id):
    status = Status.get(id)
    if not status:
        abort(404, "访问的文章不存在^^")
    else:
        user = User.get(status.user_id)
        if user and not check_access_user(user):
            if status.category == config.CATE_THEPAST_NOTE:
                return redirect("/note/%s" % status.origin_id)
            intros = [user.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
            intros = filter(None, intros)
            return render_template("post.html", config=config, **locals())
        else:
            abort(403, "没有权限访问该文章")
Example #44
0
 def set_the_profile(self, flush=False):
     if self.user_id:
         u = User.get(self.user_id)
         if u:
             if flush:
                 u.set_thirdparty_profile_item(self.openid_type,
                                               self.msg_type,
                                               datetime.datetime.now())
             else:
                 p = u.get_thirdparty_profile(self.openid_type)
                 t = p and p.get(self.msg_type)
                 u.set_thirdparty_profile_item(self.openid_type,
                                               self.msg_type, t
                                               or datetime.datetime.now())
Example #45
0
def post(id):
    status = Status.get(id)
    if not status:
        abort(404, "访问的文章不存在^^")
    else:
        user = User.get(status.user_id)
        if user and not check_access_user(user):
            if status.category == config.CATE_THEPAST_NOTE:
                return redirect("/note/%s" % status.origin_id)
            intros = [user.get_thirdparty_profile(x).get("intro") for x in config.OPENID_TYPE_DICT.values()]
            intros = filter(None, intros)
            return render_template("post.html", config=config, **locals())
        else:
            abort(403, "没有权限访问该文章")
Example #46
0
def visual(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    r = check_access_user(u)
    if r:
        flash(r[1].decode("utf8"), "tip")
        return redirect(url_for("timeline"))

    return render_template("visual_timeline.html",
                           user=u,
                           unbinded=[],
                           config=config)
Example #47
0
def user_past(uid):
    user = User.get(uid)
    if not user:
        abort(404, "no such user")

    r = check_access_user(user)
    if r:
        flash(r[1].decode("utf8"), "tip")
        return redirect("/")

    try:
        now = datetime.datetime.strptime(request.args.get("now"), "%Y-%m-%d")
    except:
        now = datetime.datetime.now()

    history_ids = get_status_ids_today_in_history(user.id, now)
    status_list = Status.gets(history_ids)
    if g.user and g.user.id == uid:
        pass
    elif g.user and g.user.id != uid:
        status_list = [
            x for x in status_list
            if x.privacy() != consts.STATUS_PRIVACY_PRIVATE
        ]
    elif not g.user:
        status_list = [
            x for x in status_list
            if x.privacy() == consts.STATUS_PRIVACY_PUBLIC
        ]

    status_list = statuses_timelize(status_list)
    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

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

    d = defaultdict(list)
    for x in status_list:
        t = x.create_time.strftime("%Y年%m月%d日")
        d[t].append(x)
    history_status = d

    return render_template("v2/user_past.html", **locals())
Example #48
0
def user_by_domain(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    r = check_access_user(u)
    if r:
        flash(r[1].decode("utf8"), "tip")
        return redirect(url_for("home"))

    ids = Status.get_ids(user_id=u.id,
                         start=g.start,
                         limit=g.count,
                         cate=g.cate)
    status_list = Status.gets(ids)
    if g.user and g.user.id == uid:
        pass
    elif g.user and g.user.id != uid:
        status_list = [
            x for x in status_list
            if x.privacy() != consts.STATUS_PRIVACY_PRIVATE
        ]
    elif not g.user:
        status_list = [
            x for x in status_list
            if x.privacy() == consts.STATUS_PRIVACY_PUBLIC
        ]

    status_list = statuses_timelize(status_list)
    tags_list = []
    intros = [
        u.get_thirdparty_profile(x).get("intro")
        for x in config.OPENID_TYPE_DICT.values()
    ]
    intros = filter(None, intros)

    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

    return render_template("timeline.html",
                           user=u,
                           unbinded=[],
                           tags_list=tags_list,
                           intros=intros,
                           status_list=status_list,
                           config=config,
                           sync_list=sync_list)
Example #49
0
def bind(uid, feed_uri):
    user = User.get(uid)
    if not user:
        print 'no user'
        return
    ua = UserAlias.bind_to_exists_user(
        user, config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS], feed_uri)
    if not ua:
        print "no user alias"
    else:
        ##添加同步任务
        t = SyncTask.add(config.CATE_WORDPRESS_POST, user.id)
        t and TaskQueue.add(t.id, t.kind)
        ##删除confiration记录
        mc.delete("wordpress_bind:%s" % user.id)
Example #50
0
def update_p2t():
    cursor = db_conn.execute("select id from user")
    rows = cursor and cursor.fetchall()
    cursor and cursor.close()
    for row in rows:
        uid = row[0]
        user = User.get(uid)
        if not user:
            print '---no user %s' %uid
            return

        old_p = user.get_profile_item("user_privacy")
        if not old_p or old_p == consts.USER_PRIVACY_PUBLIC:
            user.set_profile_item("user_privacy", consts.USER_PRIVACY_THEPAST)
        print '---updated user %s' %uid
Example #51
0
def bind(uid, feed_uri):
    user = User.get(uid)
    if not user:
        print 'no user'
        return
    ua = UserAlias.bind_to_exists_user(user, 
            config.OPENID_TYPE_DICT[config.OPENID_WORDPRESS], feed_uri)
    if not ua:
        print "no user alias"
    else:
        ##添加同步任务
        t = SyncTask.add(config.CATE_WORDPRESS_POST, user.id)
        t and TaskQueue.add(t.id, t.kind)
        ##删除confiration记录
        mc.delete("wordpress_bind:%s" %user.id)
Example #52
0
def user_more_by_domain(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")

    r = check_access_user(u)
    if r:
        abort(400, "no priv to access")

    ids = Status.get_ids(user_id=u.id,
                         start=g.start,
                         limit=g.count,
                         cate=g.cate)
    status_list = Status.gets(ids)
    if g.user and g.user.id == uid:
        pass
    elif g.user and g.user.id != uid:
        status_list = [
            x for x in status_list
            if x.privacy() != consts.STATUS_PRIVACY_PRIVATE
        ]
    elif not g.user:
        status_list = [
            x for x in status_list
            if x.privacy() == consts.STATUS_PRIVACY_PUBLIC
        ]

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

    if g.user:
        sync_list = get_sync_list(g.user)
    else:
        sync_list = []

    now = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
    return render_template("v2/user_more.html",
                           user=u,
                           intros=intros,
                           status_list=status_list,
                           config=config,
                           sync_list=sync_list,
                           now=now)
Example #53
0
def note(nid):
    note = Note.get(nid)
    if not note:
        abort(404, "no such note")
    
    r = check_access_note(note)
    if r:
        flash(r[1].decode("utf8"), "tip")
        return redirect(url_for("home"))

    title = note.title
    content = note.content
    fmt = note.fmt
    if fmt == consts.NOTE_FMT_MARKDOWN:
        content = markdown2.markdown(note.content, extras=["wiki-tables", "code-friendly"])
    create_time = note.create_time
    user = User.get(note.user_id)
    return render_template("v2/note.html", consts=consts, **locals())
Example #54
0
def generate_pdf_by_user(user_id):
    user = User.get(user_id)
    if not user:
        return

    #XXX:暂时只生成2012年的(uid从98开始的用户)
    #XXX:暂时只生成2012年3月份的(uid从166开始的用户)
    start_date = Status.get_oldest_create_time(None, user_id)
    if not start_date:
        return
    now = datetime.datetime.now()
    now = datetime.datetime(now.year, now.month, now.day) - datetime.timedelta(
        days=calendar.monthrange(now.year, now.month)[1])

    d = start_date
    while d <= now:
        generate(user_id, d)

        days = calendar.monthrange(d.year, d.month)[1]
        d += datetime.timedelta(days=days)
        d = datetime.datetime(d.year, d.month, 1)
Example #55
0
 def clear_the_profile(self):
     if self.user_id:
         u = User.get(self.user_id)
         if u:
             u.set_thirdparty_profile_item(self.openid_type, self.msg_type,
                                           "")
Example #56
0
 def is_exception_exists(self):
     if self.user_id:
         u = User.get(self.user_id)
         p = u and u.get_thirdparty_profile(self.openid_type)
         return p and p.get(self.msg_type)
Example #57
0
def user(uid):
    u = User.get(uid)
    if not u:
        abort(404, "no such user")
    return redirect("/%s" % uid)