Beispiel #1
0
def edit(request, comment_id):
    """
    Edit a comment.
    """
    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)
    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False),
        'site': Site(responses[request.site_url]),
    }

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment_request = Comment.from_edit_form(form.cleaned_data)
            try:
                comment = comment_request.update(request.get_host(), access_token=request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)

            try:
                process_attachments(request, comment)
            except ValidationError:
                try:
                    responses = response_list_to_dict(grequests.map(request.view_requests))
                except APIException as exc:
                    return respond_with_error(request, exc)
                comment_form = CommentForm(
                    initial = {
                        'itemId': comment.item_id,
                        'itemType': comment.item_type,
                        'comment_id': comment.id,
                        'markdown': request.POST['markdown'],
                        })
                view_data = {
                    'user': Profile(responses[request.whoami_url], summary=False),
                    'site': Site(responses[request.site_url]),
                    'content': comment,
                    'comment_form': comment_form,
                    'error': 'Sorry, one of your files was over 5MB. Please try again.',
                }
                return render(request, form_template, view_data)

            if comment.meta.links.get('commentPage'):
                return HttpResponseRedirect(build_comment_location(comment))
            else:
                return HttpResponseRedirect(reverse('single-comment', args=(comment.id,)))
        else:
            view_data['form'] = form
            return render(request, form_template, view_data)

    if request.method == 'GET':
        try:
            comment = Comment.retrieve(request.get_host(), comment_id, access_token=request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        view_data['form'] = CommentForm(comment.as_dict)
        return render(request, form_template, view_data)
Beispiel #2
0
def create(request):
    """
    Create a comment, processing any attachments (including deletion of attachments) and
    redirecting to the single comment form if there are any validation errors.
    """

    # TODO: determine whether the single comment creation form will use this view.
    # Remove the conditional if not.
    if request.method == 'POST':
        form = CommentForm(request.POST)

        # If invalid, load single comment view showing validation errors.
        if not form.is_valid():
            try:
                responses = response_list_to_dict(grequests.map(request.view_requests))
            except APIException as exc:
                return respond_with_error(request, exc)
            view_data = {
                'user': Profile(responses[request.whoami_url], summary=False),
                'site': Site(responses[request.site_url]),
                'form': form,
            }
            return render(request, form_template, view_data)

        # Create comment with API.
        comment_request = Comment.from_create_form(form.cleaned_data)
        try:
            comment = comment_request.create(request.get_host(), access_token=request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)

        try:
            process_attachments(request, comment)
        except ValidationError:
            try:
                responses = response_list_to_dict(grequests.map(request.view_requests))
            except APIException as exc:
                return respond_with_error(request, exc)
            comment_form = CommentForm(
                initial = {
                    'itemId': comment.item_id,
                    'itemType': comment.item_type,
                    'comment_id': comment.id,
                    'markdown': request.POST['markdown'],
                }
            )
            view_data = {
                'user': Profile(responses[request.whoami_url], summary=False),
                'site': Site(responses[request.site_url]),
                'content': comment,
                'comment_form': comment_form,
                'error': 'Sorry, one of your files was over 5MB. Please try again.',
                }
            return render(request, form_template, view_data)

        # API returns which page in the thread this comments appear in, so redirect there.
        if comment.meta.links.get('commentPage'):
            return HttpResponseRedirect(build_comment_location(comment))
Beispiel #3
0
def single(request, conversation_id):

    # Offset of comments.
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0

    conversation_url, params, headers = Conversation.build_request(
        request.get_host(),
        id=conversation_id,
        offset=offset,
        access_token=request.access_token)
    request.view_requests.append(
        grequests.get(conversation_url, params=params, headers=headers))

    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)

    conversation = Conversation.from_api_response(responses[conversation_url])
    comment_form = CommentForm(
        initial=dict(itemId=conversation_id, itemType='conversation'))

    # get attachments
    attachments = {}
    for comment in conversation.comments.items:
        c = comment.as_dict
        if 'attachments' in c:
            c_attachments = Attachment.retrieve(
                request.get_host(),
                "comments",
                c['id'],
                access_token=request.access_token)
            attachments[str(c['id'])] = c_attachments

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'content':
        conversation,
        'comment_form':
        comment_form,
        'pagination':
        build_pagination_links(
            responses[conversation_url]['comments']['links'],
            conversation.comments),
        'item_type':
        'conversation',
        'attachments':
        attachments
    }
    return render(request, single_template, view_data)
Beispiel #4
0
def single(request, comment_id):
    """
    Display a single comment.
    """

    url, params, headers = Comment.build_request(
        request.get_host(), id=comment_id, access_token=request.access_token)
    request.view_requests.append(
        grequests.get(url, params=params, headers=headers))
    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)
    content = Comment.from_api_response(responses[url])
    comment_form = CommentForm(
        initial={
            'itemId': content.item_id,
            'itemType': content.item_type,
            'comment_id': content.id,
        })

    # Fetch any attachments on the comment.
    attachments = {}
    c = content.as_dict
    if 'attachments' in c:
        c_attachments = Attachment.retrieve(request.get_host(),
                                            "comments",
                                            c['id'],
                                            access_token=request.access_token)
        attachments[str(c['id'])] = c_attachments

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'content':
        content,
        'comment_form':
        comment_form,
        'attachments':
        attachments
    }

    return render(request, single_template, view_data)
Beispiel #5
0
def single(request, huddle_id):

    # Comment offset.
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0

    huddle_url, params, headers = Huddle.build_request(request.get_host(), id=huddle_id, offset=offset,
        access_token=request.access_token)
    request.view_requests.append(grequests.get(huddle_url, params=params, headers=headers))
    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)

    huddle = Huddle.from_api_response(responses[huddle_url])
    comment_form = CommentForm(initial=dict(itemId=huddle_id, itemType='huddle'))

    # Fetch attachments.
    attachments = {}
    for comment in huddle.comments.items:
        c = comment.as_dict
        if 'attachments' in c:
            c_attachments = Attachment.retrieve(request.get_host(), "comments", c['id'],
                access_token=request.access_token)
            attachments[str(c['id'])] = c_attachments

    # Fetch huddle participants.
    participants_json = [p.as_dict for p in huddle.participants]

    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False) if request.whoami_url else None,
        'site': Site(responses[request.site_url]),
        'content': huddle,
        'comment_form': comment_form,
        'pagination': build_pagination_links(responses[huddle_url]['comments']['links'], huddle.comments),
        'item_type': 'huddle',
        'attachments': attachments,
        'participants_json': json.dumps(participants_json)
    }

    return render(request, single_template, view_data)
Beispiel #6
0
def edit(request, comment_id):
    """
    Edit a comment.
    """
    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)
    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False),
        'site': Site(responses[request.site_url]),
    }

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment_request = Comment.from_edit_form(form.cleaned_data)
            try:
                comment = comment_request.update(
                    request.get_host(), access_token=request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)

            try:
                process_attachments(request, comment)
            except ValidationError:
                try:
                    responses = response_list_to_dict(
                        grequests.map(request.view_requests))
                except APIException as exc:
                    return respond_with_error(request, exc)
                comment_form = CommentForm(
                    initial={
                        'itemId': comment.item_id,
                        'itemType': comment.item_type,
                        'comment_id': comment.id,
                        'markdown': request.POST['markdown'],
                    })
                view_data = {
                    'user':
                    Profile(responses[request.whoami_url], summary=False),
                    'site':
                    Site(responses[request.site_url]),
                    'content':
                    comment,
                    'comment_form':
                    comment_form,
                    'error':
                    'Sorry, one of your files was over 5MB. Please try again.',
                }
                return render(request, form_template, view_data)

            if comment.meta.links.get('commentPage'):
                return HttpResponseRedirect(build_comment_location(comment))
            else:
                return HttpResponseRedirect(
                    reverse('single-comment', args=(comment.id, )))
        else:
            view_data['form'] = form
            return render(request, form_template, view_data)

    if request.method == 'GET':
        try:
            comment = Comment.retrieve(request.get_host(),
                                       comment_id,
                                       access_token=request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        view_data['form'] = CommentForm(comment.as_dict)
        return render(request, form_template, view_data)
Beispiel #7
0
def create(request):
    """
    Create a comment, processing any attachments (including deletion of attachments) and
    redirecting to the single comment form if there are any validation errors.
    """

    # TODO: determine whether the single comment creation form will use this view.
    # Remove the conditional if not.
    if request.method == 'POST':
        form = CommentForm(request.POST)

        # If invalid, load single comment view showing validation errors.
        if not form.is_valid():
            try:
                responses = response_list_to_dict(
                    grequests.map(request.view_requests))
            except APIException as exc:
                return respond_with_error(request, exc)
            view_data = {
                'user': Profile(responses[request.whoami_url], summary=False),
                'site': Site(responses[request.site_url]),
                'form': form,
            }
            return render(request, form_template, view_data)

        # Create comment with API.
        comment_request = Comment.from_create_form(form.cleaned_data)
        try:
            comment = comment_request.create(request.get_host(),
                                             access_token=request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)

        try:
            process_attachments(request, comment)
        except ValidationError:
            try:
                responses = response_list_to_dict(
                    grequests.map(request.view_requests))
            except APIException as exc:
                return respond_with_error(request, exc)
            comment_form = CommentForm(
                initial={
                    'itemId': comment.item_id,
                    'itemType': comment.item_type,
                    'comment_id': comment.id,
                    'markdown': request.POST['markdown'],
                })
            view_data = {
                'user':
                Profile(responses[request.whoami_url], summary=False),
                'site':
                Site(responses[request.site_url]),
                'content':
                comment,
                'comment_form':
                comment_form,
                'error':
                'Sorry, one of your files was over 5MB. Please try again.',
            }
            return render(request, form_template, view_data)

        # API returns which page in the thread this comments appear in, so redirect there.
        if comment.meta.links.get('commentPage'):
            return HttpResponseRedirect(build_comment_location(comment))
Beispiel #8
0
def create(request, microcosm_id):
    """
    Create a conversation and first comment in the conversation.
    """

    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)
    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False),
        'site': Site(responses[request.site_url]),
    }

    if request.method == 'POST':
        form = create_form(request.POST)
        if form.is_valid():
            conv_req = Conversation.from_create_form(form.cleaned_data)
            try:
                conv = conv_req.create(request.get_host(),
                                       request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)

            if request.POST.get('firstcomment') and len(
                    request.POST.get('firstcomment')) > 0:
                payload = {
                    'itemType': 'conversation',
                    'itemId': conv.id,
                    'markdown': request.POST.get('firstcomment'),
                    'inReplyTo': 0,
                }
                comment_req = Comment.from_create_form(payload)
                try:
                    comment = comment_req.create(request.get_host(),
                                                 request.access_token)
                except APIException as exc:
                    return respond_with_error(request, exc)

                try:
                    process_attachments(request, comment)
                except ValidationError:
                    responses = response_list_to_dict(
                        grequests.map(request.view_requests))
                    comment_form = CommentForm(
                        initial={
                            'itemId': comment.item_id,
                            'itemType': comment.item_type,
                            'comment_id': comment.id,
                            'markdown': request.POST['markdown'],
                        })
                    view_data = {
                        'user':
                        Profile(responses[request.whoami_url], summary=False),
                        'site':
                        Site(responses[request.site_url]),
                        'content':
                        comment,
                        'comment_form':
                        comment_form,
                        'error':
                        'Sorry, one of your files was over 5MB. Please try again.',
                    }
                    return render(request, form_template, view_data)

            return HttpResponseRedirect(
                reverse('single-conversation', args=(conv.id, )))

        else:
            view_data['form'] = form
            return render(request, form_template, view_data)

    if request.method == 'GET':
        view_data['form'] = create_form(initial=dict(microcosmId=microcosm_id))
        view_data['microcosm_id'] = microcosm_id
        return render(request, form_template, view_data)
Beispiel #9
0
def create(request):
    """
    Create a huddle.
    """

    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)

    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False),
        'site': Site(responses[request.site_url]),
    }

    if request.method == 'POST':
        form = create_form(request.POST)
        if form.is_valid():
            hud_request = Huddle.from_create_form(form.cleaned_data)
            try:
                hud_response = hud_request.create(request.get_host(), request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)

            if request.POST.get('invite'):
                ids = [int(x) for x in request.POST.get('invite').split(',')]
                Huddle.invite(request.get_host(), hud_response.id, ids, request.access_token)

            if request.POST.get('firstcomment') and len(request.POST.get('firstcomment')) > 0:
                payload = {
                    'itemType': 'huddle',
                    'itemId': hud_response.id,
                    'markdown': request.POST.get('firstcomment'),
                    'inReplyTo': 0
                }
                comment_req = Comment.from_create_form(payload)
                try:
                    comment = comment_req.create(request.get_host(), request.access_token)
                except APIException as exc:
                    return respond_with_error(request, exc)

                try:
                    process_attachments(request, comment)
                except ValidationError:
                    responses = response_list_to_dict(grequests.map(request.view_requests))
                    comment_form = CommentForm(
                        initial={
                            'itemId': comment.item_id,
                            'itemType': comment.item_type,
                            'comment_id': comment.id,
                            'markdown': request.POST['markdown'],
                        }
                    )
                    view_data = {
                        'user': Profile(responses[request.whoami_url], summary=False),
                        'site': Site(responses[request.site_url]),
                        'content': comment,
                        'comment_form': comment_form,
                        'error': 'Sorry, one of your files was over 3MB. Please try again.',
                    }
                    return render(request, form_template, view_data)

            return HttpResponseRedirect(reverse('single-huddle', args=(hud_response.id,)))
        else:
            view_data['form'] = form
            return render(request, form_template, view_data)

    if request.method == 'GET':
        if request.GET.get('to'):
            recipients = []
            list_of_recipient_ids = request.GET.get('to').split(",")

            for recipient_id in list_of_recipient_ids:
                try:
                    recipient_profile = Profile.retrieve(request.get_host(), recipient_id)
                except APIException:
                    # Skip this recipient, but don't return as we may be able to load the others.
                    continue
                recipients.append({
                    'id': recipient_profile.id,
                    'profileName': recipient_profile.profile_name,
                    'avatar': recipient_profile.avatar
                })
            view_data['recipients_json'] = json.dumps(recipients)

        view_data['form'] = create_form(initial=dict())
        return render(request, form_template, view_data)
Beispiel #10
0
def single(request, event_id):
    """
    Display a single event with comments and attendees.
    """

    # Comment offset.
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0

    # Create request for event resource.
    event_url, event_params, event_headers = Event.build_request(
        request.get_host(),
        id=event_id,
        offset=offset,
        access_token=request.access_token)
    request.view_requests.append(
        grequests.get(event_url, params=event_params, headers=event_headers))

    # Create request for event attendees.
    att_url, att_params, att_headers = Event.build_attendees_request(
        request.get_host(), event_id, request.access_token)
    request.view_requests.append(
        grequests.get(att_url, params=att_params, headers=att_headers))

    # Perform requests and instantiate view objects.
    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)
    event = Event.from_api_response(responses[event_url])
    comment_form = CommentForm(initial=dict(itemId=event_id, itemType='event'))

    user = Profile(responses[request.whoami_url],
                   summary=False) if request.whoami_url else None

    attendees = AttendeeList(responses[att_url])
    attendees_yes = []
    attendees_invited = []
    user_is_attending = False

    for attendee in attendees.items.items:
        if attendee.rsvp == 'yes':
            attendees_yes.append(attendee)
            if request.whoami_url:
                if attendee.profile.id == user.id:
                    user_is_attending = True
        elif attendee.rsvp == 'maybe':
            attendees_invited.append(attendee)

    # Determine whether the event spans more than one day and if it has expired.
    # TODO: move stuff that is purely rendering to the template.
    today = datetime.datetime.now()
    if hasattr(event, 'when'):
        end_date = event.when + datetime.timedelta(minutes=event.duration)

        is_same_day = False
        if end_date.strftime('%d%m%y') == event.when.strftime('%d%m%y'):
            is_same_day = True

        event_dates = {
            'type': 'multiple' if not is_same_day else 'single',
            'end': end_date
        }

        is_expired = True if int(end_date.strftime('%s')) < int(
            today.strftime('%s')) else False
    else:
        event_dates = {'type': 'tba'}
        is_expired = False

    # Why is this a minimum of 10%?
    rsvp_percentage = event.rsvp_percentage
    if len(attendees_yes) and event.rsvp_percentage < 10:
        rsvp_percentage = 10

    # Fetch attachments for all comments on this page.
    # TODO: the code that does this should be in one place.
    attachments = {}
    for comment in event.comments.items:
        c = comment.as_dict
        if 'attachments' in c:
            c_attachments = Attachment.retrieve(
                request.get_host(),
                "comments",
                c['id'],
                access_token=request.access_token)
            attachments[str(c['id'])] = c_attachments

    view_data = {
        'user':
        user,
        'site':
        Site(responses[request.site_url]),
        'content':
        event,
        'comment_form':
        comment_form,
        'pagination':
        build_pagination_links(responses[event_url]['comments']['links'],
                               event.comments),
        'item_type':
        'event',
        'attendees':
        attendees,
        'attendees_yes':
        attendees_yes,
        'attendees_invited':
        attendees_invited,
        'user_is_attending':
        user_is_attending,
        'event_dates':
        event_dates,
        'rsvp_num_attending':
        len(attendees_yes),
        'rsvp_num_invited':
        len(attendees_invited),
        'rsvp_percentage':
        rsvp_percentage,
        'is_expired':
        is_expired,
        'attachments':
        attachments
    }

    return render(request, single_template, view_data)
Beispiel #11
0
def create(request, microcosm_id):
    """
    Create an event within a microcosm.
    """

    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)
    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False),
        'site': Site(responses[request.site_url]),
    }
    user = Profile(responses[request.whoami_url],
                   summary=False) if request.whoami_url else None

    if request.method == 'POST':
        form = create_form(request.POST)
        if form.is_valid():
            event_request = Event.from_create_form(form.cleaned_data)
            try:
                event_response = event_request.create(request.get_host(),
                                                      request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)
            # invite attendees
            invites = request.POST.get('invite')
            if len(invites.strip()) > 0:
                invited_list = invites.split(",")
                attendees = []
                if len(invited_list) > 0:
                    for userid in invited_list:
                        if userid != "":
                            attendees.append({
                                'rsvp': 'maybe',
                                'profileId': int(userid)
                            })
                    if len(attendees) > 0:
                        try:
                            response = Event.rsvp_api(
                                request.get_host(),
                                event_response.id,
                                user.id,
                                attendees,
                                access_token=request.access_token)
                        except APIException as exc:
                            return respond_with_error(request, exc)
                        if response.status_code != requests.codes.ok:
                            return HttpResponseBadRequest()

            # create comment
            if request.POST.get('firstcomment') and len(
                    request.POST.get('firstcomment')) > 0:
                payload = {
                    'itemType': 'event',
                    'itemId': event_response.id,
                    'markdown': request.POST.get('firstcomment'),
                    'inReplyTo': 0
                }
                comment_req = Comment.from_create_form(payload)
                try:
                    comment = comment_req.create(request.get_host(),
                                                 request.access_token)
                except APIException as exc:
                    return respond_with_error(request, exc)

                try:
                    process_attachments(request, comment)
                except ValidationError:
                    responses = response_list_to_dict(
                        grequests.map(request.view_requests))
                    comment_form = CommentForm(
                        initial={
                            'itemId': comment.item_id,
                            'itemType': comment.item_type,
                            'comment_id': comment.id,
                            'markdown': request.POST['markdown'],
                        })
                    view_data = {
                        'user':
                        Profile(responses[request.whoami_url], summary=False),
                        'site':
                        Site(responses[request.site_url]),
                        'content':
                        comment,
                        'comment_form':
                        comment_form,
                        'error':
                        'Sorry, one of your files was over 5MB. Please try again.',
                    }
                    return render(request, form_template, view_data)

            return HttpResponseRedirect(
                reverse('single-event', args=(event_response.id, )))

        else:
            print 'Event form is not valid'
            view_data['form'] = form
            view_data['microcosm_id'] = microcosm_id
            return render(request, form_template, view_data)

    if request.method == 'GET':
        view_data['form'] = create_form(initial=dict(microcosmId=microcosm_id))
        view_data['microcosm_id'] = microcosm_id
        return render(request, form_template, view_data)