コード例 #1
0
ファイル: views.py プロジェクト: rapharacing/microweb
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)
コード例 #2
0
ファイル: tests.py プロジェクト: rapharacing/microweb
 def testProfileSummaryInit(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'profile.json')).read())['data']
     Profile(data, summary=True)
コード例 #3
0
ファイル: views.py プロジェクト: rapharacing/microweb
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))
コード例 #4
0
ファイル: tests.py プロジェクト: rapharacing/microweb
 def testWhoamiInit(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'whoami.json')).read())['data']
     Profile(data)
コード例 #5
0
ファイル: tests.py プロジェクト: rapharacing/microweb
 def testProfileAsDict(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'profile.json')).read())['data']
     profile = Profile(data)
     profile.as_dict
コード例 #6
0
ファイル: views.py プロジェクト: rapharacing/microweb
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)
コード例 #7
0
ファイル: views.py プロジェクト: rapharacing/microweb
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)
コード例 #8
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)
コード例 #9
0
def edit(request, event_id):
    """
    Edit an event.
    """

    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]),
        'state_edit': True
    }

    if request.method == 'POST':
        form = edit_form(request.POST)
        if form.is_valid():
            event_request = Event.from_edit_form(form.cleaned_data)
            try:
                event_response = event_request.update(request.get_host(),
                                                      request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)
            return HttpResponseRedirect(
                reverse('single-event', args=(event_response.id, )))
        else:
            view_data['form'] = form
            view_data['microcosm_id'] = form['microcosmId']

            return render(request, form_template, view_data)

    if request.method == 'GET':
        try:
            event = Event.retrieve(request.get_host(),
                                   id=event_id,
                                   access_token=request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        view_data['form'] = edit_form.from_event_instance(event)
        view_data['microcosm_id'] = event.microcosm_id

        try:
            view_data['attendees'] = Event.get_attendees(
                host=request.get_host(),
                id=event_id,
                access_token=request.access_token)

            attendees_json = []
            for attendee in view_data['attendees'].items.items:
                attendees_json.append({
                    'id': attendee.profile.id,
                    'profileName': attendee.profile.profile_name,
                    'avatar': attendee.profile.avatar,
                    'sticky': 'true'
                })

            if len(attendees_json) > 0:
                view_data['attendees_json'] = json.dumps(attendees_json)
        except APIException:
            # Missing RSVPs is not critical, but we should know if it doesn't work.
            logger.error(str(APIException))
            pass

        return render(request, form_template, view_data)
コード例 #10
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)
コード例 #11
0
def list(request):

    # Record offset for paging of profiles.
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0
    top = bool(request.GET.get('top', False))
    q = request.GET.get('q', "")
    following = bool(request.GET.get('following', False))
    online = bool(request.GET.get('online', False))

    profiles_url, params, headers = ProfileList.build_request(
        request.get_host(),
        offset=offset,
        top=top,
        q=q,
        following=following,
        online=online,
        access_token=request.access_token)

    request.view_requests.append(
        grequests.get(profiles_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)

    profiles = ProfileList(responses[profiles_url])

    subtitle = False
    if q != "" and len(q) == 1:
        subtitle = "names starting with %s" % (q.upper())

    filter_name = []

    if following:
        filter_name.append("following")

    if online:
        filter_name.append("online now")

    if top:
        filter_name.append("most comments")

    if len(filter_name) < 1:
        filter_name.append("sorted alphabetically")

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'content':
        profiles,
        'pagination':
        build_pagination_links(responses[profiles_url]['profiles']['links'],
                               profiles.profiles),
        'q':
        q,
        'top':
        top,
        'following':
        following,
        'alphabet':
        string.ascii_lowercase,
        'site_section':
        'people',
        'filter_name':
        ", ".join(filter_name),
        'subtitle':
        subtitle,
        'online':
        online
    }

    return render(request, list_template, view_data)
コード例 #12
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)