Пример #1
0
def group_recommend(request):
    """
    Recommend a file or directory to a group.
    """
    if request.method != 'POST':
        raise Http404

    next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = SITE_ROOT
    
    form = GroupRecommendForm(request.POST)
    if form.is_valid():
        repo_id = form.cleaned_data['repo_id']
        attach_type = form.cleaned_data['attach_type']
        path = form.cleaned_data['path']
        message = form.cleaned_data['message']
        groups = request.POST.getlist('groups') # groups is a group_id list, e.g. [u'1', u'7']
        username = request.user.username

        # Check group id format
        for group_id in groups:
            try:
                group_id = int(group_id)
            except ValueError:
                messages.error(request, _(u'Error: wrong group id'))
                return HttpResponseRedirect(next)

            # Get that group
            group = get_group(group_id)

            # TODO: Check whether repo is in the group and Im in the group
            if not is_group_user(group_id, username):
                err_msg = _(u'Error: you are not in group %s.')
                messages.error(request, err_msg %  group.group_name)
                continue

            # save message to group
            gm = GroupMessage(group_id=group_id, from_email=username,
                              message=message)
            gm.save()

            # send signal
            grpmsg_added.send(sender=GroupMessage, group_id=group_id,
                              from_email=request.user.username)
                    
            # save attachment
            ma = MessageAttachment(group_message=gm, repo_id=repo_id,
                                   attach_type=attach_type, path=path,
                                   src='recommend')
            ma.save()

            group_url = reverse('group_info', args=[group_id])
            msg = _(u'Successfully recommended to <a href="%(url)s" target="_blank">%(name)s</a>.') %\
                {'url':group_url, 'name':group.group_name}
            messages.add_message(request, messages.INFO, msg)

    else:
        messages.add_message(request, messages.ERROR, _(u'Failed to recommend.'))
    return HttpResponseRedirect(next)
Пример #2
0
def group_info(request, group_id):
    if request.method == 'POST':
        form = MessageForm(request.POST)

        if form.is_valid():
            msg = form.cleaned_data['message']
            message = GroupMessage()
            message.group_id = group_id
            message.from_email = request.user.username
            message.message = msg
            message.save()

            # send signal
            grpmsg_added.send(sender=GroupMessage, group_id=group_id,
                              from_email=request.user.username)
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data.
            return HttpResponseRedirect(reverse('group_info', args=[group_id]))
    else:
        form = MessageForm()
        
        op = request.GET.get('op', '')
        if op == 'delete':
            return group_remove(request, group_id)
        elif op == 'dismiss':
            return group_dismiss(request, group_id)
        elif op == 'quit':
            return group_quit(request, group_id)

    return render_group_info(request, group_id, form)
Пример #3
0
def group_add_discussion(request, group):
    if not request.is_ajax() or request.method != 'POST':
        raise Http404

    # only login user can post to public group
    if group.view_perm == "pub" and not request.user.is_authenticated():
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    username = request.user.username

    #form = MessageForm(request.POST)
    msg = request.POST.get('message')
    selected = request.POST.getlist('selected') # files selected as attachment

    if not msg:
        result['error'] = _(u'Discussion is required.')
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    gm = GroupMessage()
    gm.group_id = group.id
    gm.from_email = username
    gm.message = msg
    gm.save()

    # send signal
    grpmsg_added.send(sender=GroupMessage, group_id=group.id,
                      from_email=username, message=msg)

    gm.attachments = []
    if selected:
        for item in selected:
            if item[-1] == '/': # dir is not allowed, for now
                continue

            repo_id = item[0:36]
            path = item[36:]
            ma = MessageAttachment(group_message=gm, repo_id=repo_id,
                attach_type='file', path=path, src='recommend')
            ma.save()
            ma.name = os.path.basename(path)
            gm.attachments.append(ma)

    ctx = { 'msg': gm }
    msg_html = render_to_string("group/new_discussion_con.html", ctx,
         context_instance=RequestContext(request))
    return HttpResponse(json.dumps({'msg_id': gm.id, 'msg_con': msg_html}), content_type=content_type)
Пример #4
0
def group_add_discussion(request, group):
    if not request.is_ajax() or request.method != 'POST':
        raise Http404

    # only login user can post to public group
    if group.view_perm == "pub" and not request.user.is_authenticated():
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    username = request.user.username

    #form = MessageForm(request.POST)
    msg = request.POST.get('message')
    selected = request.POST.getlist('selected') # files selected as attachment

    if not msg:
        result['error'] = _(u'Discussion is required.')
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    gm = GroupMessage()
    gm.group_id = group.id
    gm.from_email = username
    gm.message = msg
    gm.save()

    # send signal
    grpmsg_added.send(sender=GroupMessage, group_id=group.id,
                      from_email=username, message=msg)

    gm.attachments = []
    if selected:
        for item in selected:
            if item[-1] == '/': # dir is not allowed, for now
                continue

            repo_id = item[0:36]
            path = item[36:]
            ma = MessageAttachment(group_message=gm, repo_id=repo_id,
                attach_type='file', path=path, src='recommend')
            ma.save()
            ma.name = os.path.basename(path)
            gm.attachments.append(ma)

    ctx = { 'msg': gm }
    msg_html = render_to_string("group/new_discussion_con.html", ctx,
         context_instance=RequestContext(request))
    return HttpResponse(json.dumps({'msg_id': gm.id, 'msg_con': msg_html}), content_type=content_type)
Пример #5
0
def group_recommend(request):
    """
    Get or post file/directory discussions to a group.
    """
    content_type = "application/json; charset=utf-8"
    result = {}
    if request.method == "POST":

        form = GroupRecommendForm(request.POST)
        if form.is_valid():
            repo_id = form.cleaned_data["repo_id"]
            attach_type = form.cleaned_data["attach_type"]
            path = form.cleaned_data["path"]
            message = form.cleaned_data["message"]
            # groups is a group_id list, e.g. [u'1', u'7']
            groups = request.POST.getlist("groups")
            username = request.user.username

            groups_not_in = []
            groups_posted_to = []
            for group_id in groups:
                # Check group id format
                try:
                    group_id = int(group_id)
                except ValueError:
                    result["error"] = _(u"Error: wrong group id")
                    return HttpResponse(json.dumps(result), status=400, content_type=content_type)

                group = get_group(group_id)
                if not group:
                    result["error"] = _(u"Error: the group does not exist.")
                    return HttpResponse(json.dumps(result), status=400, content_type=content_type)

                # TODO: Check whether repo is in the group and Im in the group
                if not is_group_user(group_id, username):
                    groups_not_in.append(group.group_name)
                    continue

                # save message to group
                gm = GroupMessage(group_id=group_id, from_email=username, message=message)
                gm.save()

                # send signal
                grpmsg_added.send(sender=GroupMessage, group_id=group_id, from_email=username, message=message)

                # save attachment
                ma = MessageAttachment(
                    group_message=gm, repo_id=repo_id, attach_type=attach_type, path=path, src="recommend"
                )
                ma.save()

                # save discussion
                fd = FileDiscuss(group_message=gm, repo_id=repo_id, path=path)
                fd.save()

                group_url = reverse("group_discuss", args=[group_id])
                groups_posted_to.append(
                    u'<a href="%(url)s" target="_blank">%(name)s</a>' % {"url": group_url, "name": group.group_name}
                )

            if len(groups_posted_to) > 0:
                result["success"] = _(u"Successfully posted to %(groups)s.") % {"groups": ", ".join(groups_posted_to)}

            if len(groups_not_in) > 0:
                result["error"] = _(u"Error: you are not in group %s.") % (", ".join(groups_not_in))

        else:
            result["error"] = str(form.errors)
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    # request.method == 'GET'
    else:
        repo_id = request.GET.get("repo_id")
        path = request.GET.get("path", None)
        repo = get_repo(repo_id)
        if not repo:
            result["error"] = _(u"Error: the library does not exist.")
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)
        if path is None:
            result["error"] = _(u"Error: no path.")
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    # get discussions & replies
    path_hash = calc_file_path_hash(path)
    discussions = FileDiscuss.objects.filter(path_hash=path_hash, repo_id=repo_id)
    msg_ids = [e.group_message_id for e in discussions]

    grp_msgs = GroupMessage.objects.filter(id__in=msg_ids).order_by("-timestamp")
    msg_replies = MessageReply.objects.filter(reply_to__in=grp_msgs)
    for msg in grp_msgs:
        msg.replies = []
        for reply in msg_replies:
            if msg.id == reply.reply_to_id:
                msg.replies.append(reply)
        msg.reply_cnt = len(msg.replies)
        msg.replies = msg.replies[-3:]

    ctx = {}
    ctx["messages"] = grp_msgs
    html = render_to_string("group/discussion_list.html", ctx)
    result["html"] = html
    return HttpResponse(json.dumps(result), content_type=content_type)
Пример #6
0
def group_recommend(request):
    """
    Get or post file/directory discussions to a group.
    """
    content_type = 'application/json; charset=utf-8'
    result = {}
    if request.method == 'POST':

        form = GroupRecommendForm(request.POST)
        if form.is_valid():
            repo_id = form.cleaned_data['repo_id']
            attach_type = form.cleaned_data['attach_type']
            path = form.cleaned_data['path']
            message = form.cleaned_data['message']
            # groups is a group_id list, e.g. [u'1', u'7']
            groups = request.POST.getlist('groups')
            username = request.user.username

            groups_not_in = []
            groups_posted_to = []
            for group_id in groups:
                # Check group id format
                try:
                    group_id = int(group_id)
                except ValueError:
                    result['error'] = _(u'Error: wrong group id')
                    return HttpResponse(json.dumps(result), status=400,
                                        content_type=content_type)

                group = get_group(group_id)
                if not group:
                    result['error'] = _(u'Error: the group does not exist.')
                    return HttpResponse(json.dumps(result), status=400,
                                        content_type=content_type)

                # TODO: Check whether repo is in the group and Im in the group
                if not is_group_user(group_id, username):
                    groups_not_in.append(group.group_name)
                    continue

                # save message to group
                gm = GroupMessage(group_id=group_id, from_email=username,
                                  message=message)
                gm.save()

                # send signal
                grpmsg_added.send(sender=GroupMessage, group_id=group_id,
                                  from_email=username, message=message)

                # save attachment
                ma = MessageAttachment(group_message=gm, repo_id=repo_id,
                                       attach_type=attach_type, path=path,
                                       src='recommend')
                ma.save()

                # save discussion
                fd = FileDiscuss(group_message=gm, repo_id=repo_id, path=path)
                fd.save()

                group_url = reverse('group_discuss', args=[group_id])
                groups_posted_to.append(u'<a href="%(url)s" target="_blank">%(name)s</a>' % \
                {'url':group_url, 'name':group.group_name})

            if len(groups_posted_to) > 0:
                result['success'] = _(u'Successfully posted to %(groups)s.') % {'groups': ', '.join(groups_posted_to)}

            if len(groups_not_in) > 0:
                result['error'] = _(u'Error: you are not in group %s.') % (', '.join(groups_not_in))

        else:
            result['error'] = str(form.errors)
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    # request.method == 'GET'
    else:
        repo_id = request.GET.get('repo_id')
        path = request.GET.get('path', None)
        repo = get_repo(repo_id)
        if not repo:
            result['error'] = _(u'Error: the library does not exist.')
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)
        if path is None:
            result['error'] = _(u'Error: no path.')
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)

    # get discussions & replies
    path_hash = calc_file_path_hash(path)
    discussions = FileDiscuss.objects.filter(path_hash=path_hash, repo_id=repo_id)
    msg_ids = [ e.group_message_id for e in discussions ]

    grp_msgs = GroupMessage.objects.filter(id__in=msg_ids).order_by('-timestamp')
    msg_replies = MessageReply.objects.filter(reply_to__in=grp_msgs)
    for msg in grp_msgs:
        msg.replies = []
        for reply in msg_replies:
            if msg.id == reply.reply_to_id:
                msg.replies.append(reply)
        msg.reply_cnt = len(msg.replies)
        msg.replies = msg.replies[-3:]

    ctx = {}
    ctx['messages'] = grp_msgs
    html = render_to_string("group/discussion_list.html", ctx)
    result['html'] = html
    return HttpResponse(json.dumps(result), content_type=content_type)
Пример #7
0
def group_discuss(request, group_id):
    if request.method == 'POST':
        form = MessageForm(request.POST)

        if form.is_valid():
            msg = form.cleaned_data['message']
            message = GroupMessage()
            message.group_id = group_id
            message.from_email = request.user.username
            message.message = msg
            message.save()

            # send signal
            grpmsg_added.send(sender=GroupMessage, group_id=group_id,
                              from_email=request.user.username)
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data.
            return HttpResponseRedirect(reverse('group_discuss', args=[group_id]))
    else:
        form = MessageForm()
        
        op = request.GET.get('op', '')
        if op == 'delete':
            return group_remove(request, group_id)
        elif op == 'dismiss':
            return group_dismiss(request, group_id)
        elif op == 'quit':
            return group_quit(request, group_id)

    group_id_int = int(group_id) # Checkeb by URL Conf

    # remove user notifications
    UserNotification.objects.filter(to_user=request.user.username,
                                    msg_type='group_msg',
                                    detail=str(group_id)).delete()
    
    group = get_group(group_id_int)
    if not group:
        return HttpResponseRedirect(reverse('group_list', args=[]))
    
    # Check whether user belongs to the group.
    joined = is_group_user(group_id_int, request.user.username)
    if not joined and not request.user.is_staff:
        # Return group public info page.
        return render_to_response('group/group_pubinfo.html', {
                'members': members,
                'group': group,
                }, context_instance=RequestContext(request))

    # Get all group members.
    members = get_group_members(group_id_int)
    is_staff = True if check_group_staff(group.id, request.user) else False
        
    """group messages"""
    # Show 15 group messages per page.
    paginator = Paginator(GroupMessage.objects.filter(
            group_id=group_id).order_by('-timestamp'), 15)

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        group_msgs = paginator.page(page)
    except (EmptyPage, InvalidPage):
        group_msgs = paginator.page(paginator.num_pages)

    group_msgs.page_range = paginator.get_page_range(group_msgs.number)

    # Force evaluate queryset to fix some database error for mysql.        
    group_msgs.object_list = list(group_msgs.object_list) 

    attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list)

    msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list)
    reply_to_list = [ r.reply_to_id for r in msg_replies ]
    
    for msg in group_msgs.object_list:
        msg.reply_cnt = reply_to_list.count(msg.id)
        msg.replies = []
        for r in msg_replies:
            if msg.id == r.reply_to_id:
                msg.replies.append(r)
        msg.replies = msg.replies[-3:]
            
        for att in attachments:
            if msg.id == att.group_message_id:
                # Attachment name is file name or directory name.
                # If is top directory, use repo name instead.
                path = att.path
                if path == '/':
                    repo = get_repo(att.repo_id)
                    if not repo:
                        # TODO: what should we do here, tell user the repo
                        # is no longer exists?
                        continue
                    att.name = repo.name
                else:
                    # cut out last '/'
                    if path[-1] == '/':
                        path = path[:-1]
                    att.name = os.path.basename(path)
                msg.attachment = att

    return render_to_response("group/group_discuss.html", {
            "members": members,
            "group_id": group_id,
            "group" : group,
            "is_staff": is_staff,
            "group_msgs": group_msgs,
            "form": form,
            'group_members_default_display': GROUP_MEMBERS_DEFAULT_DISPLAY,
            }, context_instance=RequestContext(request));