Exemplo n.º 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)
Exemplo n.º 2
0
def incontext(request, comment_id):
    """
    Get redirected to the first unread post in a conversation
    """

    try:
        response = Comment.incontext(request.get_host(), comment_id, access_token=request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    #because redirects are always followed, we can't just get the 'location' value
    response = response['comments']['links']
    for link in response:
        if link['rel'] == 'self':
            response = link['href']
    response = str.replace(str(response), '/api/v1', '')
    pr = urlparse(response)
    queries = parse_qs(pr[4])
    frag = ""
    if queries.get('comment_id'):
        frag = 'comment' + queries['comment_id'][0]
        del queries['comment_id']
        # queries is a dictionary of 1-item lists (as we don't re-use keys in our query string)
    # urlencode will encode the lists into the url (offset=[25]) etc.  So get the values straight.
    for (key, value) in queries.items():
        queries[key] = value[0]
    queries = urlencode(queries)
    response = urlunparse((pr[0], pr[1], pr[2], pr[3], queries, frag))
    return HttpResponseRedirect(response)
Exemplo n.º 3
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)
Exemplo n.º 4
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))
Exemplo n.º 5
0
def source(request, comment_id):
    """
    Retrieve the markdown source for a comment.
    """

    try:
        response = Comment.source(request.get_host(), comment_id, request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    return HttpResponse(response, content_type='application/json')
Exemplo n.º 6
0
def source(request, comment_id):
    """
    Retrieve the markdown source for a comment.
    """

    try:
        response = Comment.source(request.get_host(), comment_id,
                                  request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    return HttpResponse(response, content_type='application/json')
Exemplo n.º 7
0
def incontext(request, comment_id):
    """
    Redirect to the user's first unread comment in a list of comments.
    """

    try:
        response = Comment.incontext(request.get_host(), comment_id, access_token=request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    redirect = build_newest_comment_link(response, request)
    return HttpResponseRedirect(redirect)
Exemplo n.º 8
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)
Exemplo n.º 9
0
def incontext(request, comment_id):
    """
    Redirect to the user's first unread comment in a list of comments.
    """

    try:
        response = Comment.incontext(request.get_host(),
                                     comment_id,
                                     access_token=request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    redirect = build_newest_comment_link(response, request)
    return HttpResponseRedirect(redirect)
Exemplo n.º 10
0
def delete(request, comment_id):
    """
    Delete a comment and be redirected to the item.
    """

    try:
        comment = Comment.retrieve(request.get_host(), comment_id, access_token=request.access_token)
        comment.delete(request.get_host(), request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    if comment.item_type == 'event':
        return HttpResponseRedirect(reverse('single-event', args=(comment.item_id,)))
    elif comment.item_type == 'conversation':
        return HttpResponseRedirect(reverse('single-conversation', args=(comment.item_id,)))
    else:
        return HttpResponseRedirect(reverse('microcosm-list'))
Exemplo n.º 11
0
def delete(request, comment_id):
    """
    Delete a comment and be redirected to the item.
    """

    try:
        comment = Comment.retrieve(request.get_host(),
                                   comment_id,
                                   access_token=request.access_token)
        comment.delete(request.get_host(), request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    if comment.item_type == 'event':
        return HttpResponseRedirect(
            reverse('single-event', args=(comment.item_id, )))
    elif comment.item_type == 'conversation':
        return HttpResponseRedirect(
            reverse('single-conversation', args=(comment.item_id, )))
    else:
        return HttpResponseRedirect(reverse('microcosm-list'))
Exemplo n.º 12
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)
Exemplo n.º 13
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))
Exemplo n.º 14
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:
                            Event.rsvp(request.get_host(), event_response.id, user.id, attendees,
                                access_token=request.access_token)
                        except APIException as exc:
                            return respond_with_error(request, exc)

            # 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)
Exemplo n.º 15
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)
Exemplo n.º 16
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)
Exemplo n.º 17
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)
Exemplo n.º 18
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)
Exemplo n.º 19
0
def edit(request, profile_id):
    """
    Edit a user profile (profile name or avatar).
    """

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

    if request.method == 'POST':
        form = edit_form(request.POST)
        if form.is_valid():
            # Upload new avatar if present.
            if request.FILES.has_key('avatar'):
                file_request = FileMetadata.from_create_form(request.FILES['avatar'])
                file_metadata = file_request.create(request.get_host(), request.access_token, 100, 100)
                try:
                    Attachment.create(request.get_host(), file_metadata.file_hash, profile_id=user.id,
                        access_token=request.access_token, file_name=request.FILES['avatar'].name)
                except APIException as exc:
                    return respond_with_error(request, exc)

            # Update the actual profile resource.
            profile_request = Profile(form.cleaned_data)
            profile_response = profile_request.update(request.get_host(), request.access_token)

            # Create, update or delete comment on profile (single comment acts as a bio).
            if request.POST.has_key('markdown'):
                profile_comment = {
                    'itemType': 'profile',
                    'itemId': profile_response.id,
                    'markdown': request.POST['markdown'],
                    'inReplyTo': 0
                }

                # If profile already has an attached comment update it, otherwise create a new one.
                if hasattr(profile_response, 'profile_comment'):
                    profile_comment['id'] = profile_response.profile_comment.id
                    comment_request = Comment.from_edit_form(profile_comment)
                    try:
                        if profile_comment['markdown']:
                            comment_request.update(request.get_host(), access_token=request.access_token)
                        else:
                            # If the comment body is empty, assume the user wants to delete it.
                            comment_request.delete(request.get_host(), request.access_token)
                    except APIException as exc:
                        return respond_with_error(request, exc)
                else:
                    if profile_comment['markdown']:
                        comment = Comment.from_create_form(profile_comment)
                        try:
                            comment.create(request.get_host(), request.access_token)
                        except APIException as exc:
                            return respond_with_error(request, exc)

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

    if request.method == 'GET':
        try:
            user_profile = Profile.retrieve(request.get_host(), profile_id, request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        view_data['form'] = edit_form(user_profile.as_dict)
        return render(request, form_template, view_data)
Exemplo n.º 20
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)
Exemplo n.º 21
0
def edit(request, profile_id):
    """
    Edit a user profile (profile name or avatar).
    """

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

    if request.method == 'POST':
        form = edit_form(request.POST)
        if form.is_valid():
            # Upload new avatar if present.
            if request.FILES.has_key('avatar'):
                file_request = FileMetadata.from_create_form(
                    request.FILES['avatar'])
                file_metadata = file_request.create(request.get_host(),
                                                    request.access_token, 100,
                                                    100)
                try:
                    Attachment.create(request.get_host(),
                                      file_metadata.file_hash,
                                      profile_id=user.id,
                                      access_token=request.access_token,
                                      file_name=request.FILES['avatar'].name)
                except APIException as exc:
                    return respond_with_error(request, exc)

            # Update the actual profile resource.
            profile_request = Profile(form.cleaned_data)
            profile_response = profile_request.update(request.get_host(),
                                                      request.access_token)

            # Create, update or delete comment on profile (single comment acts as a bio).
            if request.POST.has_key('markdown'):
                profile_comment = {
                    'itemType': 'profile',
                    'itemId': profile_response.id,
                    'markdown': request.POST['markdown'],
                    'inReplyTo': 0
                }

                # If profile already has an attached comment update it, otherwise create a new one.
                if hasattr(profile_response, 'profile_comment'):
                    profile_comment['id'] = profile_response.profile_comment.id
                    comment_request = Comment.from_edit_form(profile_comment)
                    try:
                        if profile_comment['markdown']:
                            comment_request.update(
                                request.get_host(),
                                access_token=request.access_token)
                        else:
                            # If the comment body is empty, assume the user wants to delete it.
                            comment_request.delete(request.get_host(),
                                                   request.access_token)
                    except APIException as exc:
                        return respond_with_error(request, exc)
                else:
                    if profile_comment['markdown']:
                        comment = Comment.from_create_form(profile_comment)
                        try:
                            comment.create(request.get_host(),
                                           request.access_token)
                        except APIException as exc:
                            return respond_with_error(request, exc)

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

    if request.method == 'GET':
        try:
            user_profile = Profile.retrieve(request.get_host(), profile_id,
                                            request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        view_data['form'] = edit_form(user_profile.as_dict)
        return render(request, form_template, view_data)