Exemplo n.º 1
0
def chatDelete(request):
    '''在 inbox 界面删除某条消息'''
    user = util.user.getCurrentUser(request)
    if not user:
        return util.user.loginToContinue(request)
    # get history.back
    if 'HTTP_REFERER' in request.META:
        href_back = request.META.get('HTTP_REFERER')
        response = redirect(href_back)
    else:
        response = redirect('/chat/inbox')
    # get inputs
    chat_id = request.GET.get('id')
    if not chat_id:
        return util.ctrl.infoMsg("您输入的网址不完整,缺少参数 id")
    # get chat
    try:
        chat = Chat.objects.get(id=chat_id)
    except Chat.DoesNotExist:
        return util.ctrl.infoMsg("您查找的消息 id:{id} 并不存在".format(id=str(chat_id)))
    if user.id != chat.receiverid and (not user.getUserpermission('superuser')):
        return util.ctrl.infoMsg("只有消息的接收者可以删除消息")
    chat.delete()
    # add exps
    userexp, created = UserExp.objects.get_or_create(userid=user.id, category='chat')
    userexp.addExp(1, '删除了一条来自 @{sender.nickname} 的消息'.format(sender=chat.sender))
    # render
    return response
Exemplo n.º 2
0
def userCheckLogin(request):  # POST
    '''用户点击登入后:判断用户是否可以登入'''
    # get posts
    username = request.POST.get('username')
    answer = request.POST.get('answer')
    rememberme = request.POST.get('rememberme') or 'off'
    from_ = request.POST.get('from') or ''
    _failto = request.META.get('HTTP_REFERER', "/user/signin")
    if not username:
        messages.error(request, "登入失败:用户名不能为空")
        return redirect(_failto)
    if not answer:
        messages.error(request, "登入失败:答案不能为空")
        return redirect(_failto)
    # check username vs. answer
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        messages.error(request, "登入失败:找不到用户名为 {} 的用户".format(username))
        return redirect(_failto)
    if user.getUserpermission('signin') is False:  # None is OK, True is OK, False is not OK
        messages.error(request, '登入失败:您已被禁止登入,请联系管理员')
        return redirect(_failto)
    if checkAnswer(user, answer):
        util.user.rememberLogin(request, user)
    else:
        messages.error(request, "登入失败:用户名与答案不匹配")
        return redirect(_failto)
    # redirections
    to_ = from_ or '/'
    response = redirect(to_)
    # add exp
    userexp, created = UserExp.objects.get_or_create(userid=user.id, category='user')
    userexp.addExp(1, '登入成功')
    # remove old msgs
    msg_title = 'Hi, @{user.nickname}'.format(user=user)
    sysuser = Chat.objects.getSyschatUser()
    old_msg = user.getChats('received').filter(senderid=sysuser.id, title=msg_title)
    has_old_msg = old_msg.exists()
    old_msg.delete()
    # send chat
    chat_content = '''
        欢迎您归来,开始您的网站之旅吧!<br/>
        <li>访问 <a href="/progress/list">我的进度</a> 查看进度列表</li>
        <li>访问 <a href="/user/profile">我的账号信息</a> 查看您的活跃度、进度统计</li>
        <li>访问 <a href="/chat/conversation?mode=quicknote">临时笔记</a> 随手记录您的想法</li>
        <li>遇到问题或想 #提建议 ,请发消息给 @系统消息 !</li>
    '''
    new_msg = Chat.objects.sendBySys(user, title=msg_title, content=chat_content)
    if has_old_msg:
        new_msg.isread = True
        new_msg.save()
    # set cookie
    if rememberme == 'on':
        oneweek = 60 * 60 * 24 * 7
        response.set_cookie('user_id', user.id, max_age=oneweek)
        response.set_cookie('user_answer', user.answer1, max_age=oneweek)
    return response
Exemplo n.º 3
0
def userSetting(request):
    '''修改用户设置'''
    user = util.user.getCurrentUser(request)
    if not user:
        return util.user.loginToContinue(request)
    icalon = user.getUserpermission('progressical')
    context = {
        'icalon': icalon,
        'privatekey': user.privatekey,
    }
    return render(request, 'user/setting.html', context)
Exemplo n.º 4
0
def markread(request):  # AJAX
    """用户标记自己的 chat 消息为已读"""
    # get chat
    chatid = request.GET.get('chatid')
    user = util.user.getCurrentUser(request)
    chat = Chat.objects.get_or_none(id=chatid)
    if not chat:
        return util.ctrl.returnJsonError(_("您查找的消息 id: {} 并不存在").format(chatid))
    if chat.receiverid != user.id and (not user.getUserpermission('superuser')):
        return util.ctrl.returnJsonError(_("只有消息的接收者可以{}消息").format(_("更新")))
    # add exp
    util.userexp.addExp(user, 'chat', 2, _("阅读来自 @{} 的消息").format(chat.sender.nickname))
    # markread
    isSuccessed = chat.markRead()
    return util.ctrl.returnJsonResult(isSuccessed)
Exemplo n.º 5
0
def chatMarkread(request):  # AJAX
    '''用户标记自己的 chat 消息为已读'''
    user = util.user.getCurrentUser(request)
    if not user:
        return util.ctrl.returnJsonError("您还没有登入,请先登入")
    # get chat
    chatid = request.GET.get('chatid')
    try:
        chat = Chat.objects.get(id=chatid)
    except Chat.DoesNotExist:
        return util.ctrl.returnJsonError("您查找的消息 id: {id} 并不存在".format(id=str(chatid)))
    if chat.receiverid != user.id and (not user.getUserpermission('superuser')):
        return util.ctrl.returnJsonError('你没有权限修改 id: {chat.id} 的消息'.format(chat=chat))
    # add exps
    userexp, created = UserExp.objects.get_or_create(userid=user.id, category='chat')
    userexp.addExp(2, '阅读来自 @{sender.nickname} 的消息'.format(sender=chat.sender))
    # markread
    isSuccessed = chat.markRead()
    return util.ctrl.returnJsonResult(isSuccessed)
Exemplo n.º 6
0
def delete(request):
    """在 inbox 界面删除某条消息"""
    # get history.back
    if 'HTTP_REFERER' in request.META:
        href_back = request.META.get('HTTP_REFERER')
        response = redirect(href_back)
    else:
        response = redirect('/chat/inbox')
    # get inputs
    chat_id = request.GET.get('id')
    if not chat_id:
        raise Http404(_("{} 参数不能为空").format("Chat ID"))
    # get chat
    user = util.user.getCurrentUser(request)
    chat = Chat.objects.get_or_404(id=chat_id)
    if user.id != chat.receiverid and (not user.getUserpermission('superuser')):
        return util.ctrl.infoMsg(_("只有消息的接收者可以{}消息").format(_("删除")), title=_("删除失败"))
    chat.delete()
    # add exp
    util.userexp.addExp(user, 'chat', 1, _('删除了一条来自 @{} 的消息').format(chat.sender.nickname))
    # render
    return response
Exemplo n.º 7
0
def ical(request):  # GET
    """生成 ical 字符串加入 google calendar"""
    def generate_summery(status, name):
        if status == 'done':
            pattern = "{act} {nm}"
            params = {
                "act": _("完成了"),
            }
        elif status == 'deactivated':
            pattern = "{act} {nm}"
            params = {
                "act": _("冻结了"),
            }
        elif status == 'inprogress':
            pattern = "{nm} {act} {crrt}/{ttl}"
            params = {
                "act": _("进行至"),
                "crrt": prg.current,
                "ttl": prg.total,
            }
        elif status == 'follow':
            pattern = "{nm} {act} {di} {num} {ji}"
            params = {
                "act": _("追剧至"),
                "di": _("第"),
                "num": prg.current,
                "ji": _("集"),
            }
        elif status == 'todo':
            pattern = "{nm} {act} {todo}"
            params = {
                "act": _("加入至"),
                "todo": _("待阅读"),
            }
        else:
            pattern = "{nm} {act}"
            params = {
                "act": _("出错"),
            }
        return pattern.format(nm=name, **params)

    userid = request.GET.get("userid")
    privatekey = request.GET.get("private") or None
    user = User.objects.get_or_404(id=userid)
    if privatekey:  # private mode
        if privatekey != user.privatekey:
            raise Http404(_("获取日历失败") + _(":") + _("用户的私钥不合法"))
    else:  # public mode
        if not user.getUserpermission("progress.public_ical"):
            raise Http404(_("获取日历失败") + _(":") + _("此用户尚未公开其进度日历"))
    # get user's progresses
    progresses = Progress.objects.filter(userid=user.id).order_by('-modified')
    # construct iCalendar
    cal = icalendar.Calendar()
    cal.update({
        "PRODID":
        "-//kyan001.com//Progress Calendar//{}".format(
            translation.get_language().upper()),
        "VERSION":
        "2.0",
        "METHOD":
        "PUBLISH",
        "CALSACLE":
        "GREGORIAN",
        "X-WR-CALNAME":
        "「{t}」@{u}".format(t=_("进度日历"), u=user.nickname),
        "X-WR-TIMEZONE":
        timezone.get_current_timezone(),
        "X-WR-CALDESC":
        "http://www.kyan001.com/progress/list",
    })
    for prg in progresses:
        prg_url = "http://www.kyan001.com/progress/detail?id={}".format(prg.id)
        PRGNAME = "《{}》".format(prg.name)
        # create event create
        evnt_crt = icalendar.Event({
            "UID":
            'prg:id:{}:create'.format(prg.id),
            "DESCRIPTION":
            prg_url,
            "URL":
            prg_url,
            "DTSTART":
            icalendar.vDatetime(prg.created),
            "DTSTAMP":
            icalendar.vDatetime(prg.created),
            "SUMMARY":
            "{act} {nm}".format(act=_("开始看"), nm=PRGNAME),
        })
        cal.add_component(evnt_crt)
        # create event modify
        evnt_mdf = icalendar.Event({
            "UID":
            'prg:id:{id}:{st}'.format(id=prg.id, st=prg.status),
            "DESCRIPTION":
            prg_url,
            "URL":
            prg_url,
            "DTSTART":
            icalendar.vDatetime(prg.modified),
            "DTSTAMP":
            icalendar.vDatetime(prg.modified),
            "SUMMARY":
            generate_summery(prg.status, PRGNAME),
        })
        cal.add_component(evnt_mdf)
    # render
    return HttpResponse(cal.to_ical(), content_type='text/calendar')
Exemplo n.º 8
0
def progressIcalendar(request):  # GET
    '''生成 ical 字符串加入 google calendar'''
    userid = request.GET.get('userid')
    privatekey = request.GET.get('private') or None
    try:
        user = User.objects.get(id=userid)
    except User.DoesNotExist:
        return util.ctrl.infoMsg("用户 userid={id} 不存在".format(id=userid), title='找不到用户')
    if privatekey:  # private mode
        if privatekey != user.privatekey:
            return util.ctrl.infoMsg("用户的私钥不合法", title='无法读取')
    else:  # public mode
        if not user.getUserpermission('progressical'):
            return util.ctrl.infoMsg("此用户尚未公开其进度日历", title='获取日历失败')
    # get user's progresses
    progresses = Progress.objects.filter(userid=user.id).order_by('-modified')
    cal = icalendar.Calendar()
    cal['prodid'] = 'superfarmer.net'
    cal['version'] = '1.1'
    owner = '我' if privatekey else user.nickname
    cal['X-WR-CALNAME'] = '{}的「进度日历」'.format(owner)
    cal['X-WR-TIMEZONE'] = 'Asia/Shanghai'
    cal['X-WR-CALDESC'] = 'http://www.superfarmer.net/progress/list'
    for prg in progresses:
        opus = Opus.objects.get(id=prg.opusid)
        create_time = prg.created.strftime('%Y%m%dT%H%M%SZ')
        modify_time = prg.modified.strftime('%Y%m%dT%H%M%SZ')
        url = 'http://www.superfarmer.net/progress/detail?id={}'.format(prg.id)
        evnt_create = icalendar.Event()
        evnt_create['uid'] = 'prg:id:{}:create'.format(prg.id)
        evnt_create['description'] = url
        evnt_create['url'] = url
        evnt_create['dtstart'] = create_time
        evnt_create['dtstamp'] = create_time
        evnt_create['summary'] = '开始看《{opus.name}》'.format(opus=opus)
        cal.add_component(evnt_create)
        if prg.status == 'done':
            evnt_done = icalendar.Event()
            evnt_done['uid'] = 'prg:id:{}:done'.format(prg.id)
            evnt_done['description'] = url
            evnt_done['url'] = url
            evnt_done['dtstart'] = modify_time
            evnt_done['dtstamp'] = modify_time
            evnt_done['summary'] = '完成《{opus.name}》'.format(opus=opus)
            cal.add_component(evnt_done)
        elif prg.status == 'giveup':
            evnt_giveup = icalendar.Event()
            evnt_giveup['uid'] = 'prg:id:{}:giveup'.format(prg.id)
            evnt_giveup['description'] = url
            evnt_giveup['url'] = url
            evnt_giveup['dtstart'] = modify_time
            evnt_giveup['dtstamp'] = modify_time
            evnt_giveup['summary'] = '冻结了《{opus.name}》'.format(opus=opus)
            cal.add_component(evnt_giveup)
        elif prg.status == 'inprogress':
            evnt_inprgrss = icalendar.Event()
            evnt_inprgrss['uid'] = 'prg:id:{}:inprogress'.format(prg.id)
            evnt_inprgrss['description'] = url
            evnt_inprgrss['url'] = url
            evnt_inprgrss['dtstart'] = modify_time
            evnt_inprgrss['dtstamp'] = modify_time
            evnt_inprgrss['summary'] = '《{opus.name}》进行至 {prg.current}/{opus.total}'.format(opus=opus, prg=prg)
            cal.add_component(evnt_inprgrss)
        elif prg.status == 'follow':
            evnt_fllw = icalendar.Event()
            evnt_fllw['uid'] = 'prg:id:{}:follow'.format(prg.id)
            evnt_fllw['description'] = url
            evnt_fllw['url'] = url
            evnt_fllw['dtstart'] = modify_time
            evnt_fllw['dtstamp'] = modify_time
            evnt_fllw['summary'] = '《{opus.name}》追剧至 第 {prg.current} 集'.format(opus=opus, prg=prg)
            cal.add_component(evnt_fllw)
    # add exps
    userexp, created = UserExp.objects.get_or_create(userid=user.id, category='progress')
    _by = request.META.get('REMOTE_HOST') or request.META.get('REMOTE_ADDR')
    _word = '{by} 访问了你的「进度日历」'.format(by=_by)
    if not privatekey:
        _word += '(公开)'
    userexp.addExp(1, _word)
    # render
    return HttpResponse(cal.to_ical(), content_type='text/calendar')
Exemplo n.º 9
0
def checkLogin(request):  # POST
    """用户点击登入后:判断用户是否可以登入"""
    # get posts
    username = request.POST.get('username')
    answer = request.POST.get('answer')
    rememberme = request.POST.get('rememberme') or 'off'
    next_ = request.POST.get('next') or ''
    _failto = request.META.get('HTTP_REFERER') or '/user/signin?next=' + next_
    if not username:
        messages.error(request, _("登入失败") + _(":") + _("用户名不能为空"))
        return redirect(_failto)
    if not answer:
        messages.error(request, _("登入失败") + _(":") + _("密码/答案不能为空"))
        return redirect(_failto)
    # check username vs. answer
    user = User.objects.get_or_none(username=username)
    if not user:
        messages.error(
            request,
            _("登入失败") + _(":") + _("找不到用户名为 {} 的用户").format(username))
        return redirect(_failto)
    if user.getUserpermission(
            'signin') is False:  # None is OK, True is OK, False is not OK
        messages.error(request, _("登入失败") + _(":") + _("您已被禁止登入,请联系管理员"))
        return redirect(_failto)
    if util.user.checkAnswer(user, answer):
        util.user.rememberLogin(request, user)
    else:
        messages.error(request, _("登入失败") + _(":") + _("用户名与答案不匹配"))
        return redirect(_failto)
    # redirections
    to_ = next_ or '/'
    response = redirect(to_)
    # add exp
    util.userexp.addExp(user, 'user', 1, _("登入成功"))
    # remove old msgs
    msg_title = 'Hi, @{user.nickname}'.format(user=user)
    sysuser = Chat.objects.getSyschatUser()
    old_msg = user.getChats('received').filter(senderid=sysuser.id,
                                               title=msg_title)
    has_old_msg = old_msg.exists()
    old_msg.delete()
    # send chat
    pages = [
        {
            "name": _("我的进度"),
            "href": "/progress/list",
            "desc": _("查看进度列表"),
        },
        {
            "name": _("个人信息"),
            "href": "/user/profile",
            "desc": _("查看您的活跃度、进度统计"),
        },
        {
            "name": _("临时笔记"),
            "href": "/chat/conversation?mode=quicknote",
            "desc": _("随手记录您的想法"),
        },
    ]
    content_links = "".join([
        "<li><a href='{h}'>{n}</a> {d}</li>".format(h=p.get("href"),
                                                    n=p.get("name"),
                                                    d=p.get("desc"))
        for p in pages
    ])
    chat_content = "<br>".join([
        _("欢迎您归来,开始您的网站之旅吧!"),
        "{}".format(content_links),
        "{} @系统消息".format(_("遇到问题或想 #提建议 ,请发消息给")),
    ])
    new_msg = Chat.objects.sendBySys(user,
                                     title=msg_title,
                                     content=chat_content)
    if has_old_msg:
        new_msg.isread = True
        new_msg.save()
    # set cookie
    if rememberme == 'on':
        response = util.user.addCookieLogin(response, user=user)
    return response