示例#1
0
文件: views.py 项目: mattrco/microweb
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)
示例#2
0
文件: views.py 项目: allanw/microweb
def confirm(request):
    """
    View for moderation actions on a single item.
    """

    if request.method == 'GET':
        if request.GET.get('item_type') == 'conversation':
            url, params, headers = Conversation.build_request(
                request.get_host(),
                request.GET.get('item_id'),
                access_token=request.access_token
            )
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Conversation.from_api_response(responses[url])

        elif request.GET.get('item_type') == 'event':
            url, params, headers = Event.build_request(
                request.get_host(),
                request.GET.get('item_id'),
                access_token=request.access_token
            )
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Event.from_api_response(responses[url])

        elif request.GET.get('item_type') == 'microcosm':
            url, params, headers = Microcosm.build_request(
                request.get_host(),
                request.GET.get('item_id'),
                access_token=request.access_token
            )
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Microcosm.from_api_response(responses[url])

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

        if request.GET.get('action') == 'move':
            # Fetch list of microcosms to supply in form.
            view_data['microcosms'] = MicrocosmList.retrieve(
                request.get_host(),
                access_token=request.access_token
            )

        return render(request, 'forms/moderation_item.html', view_data)
示例#3
0
文件: views.py 项目: mattrco/microweb
def rsvp(request, event_id):
    """
    Create an attendee (RSVP) for an event. An attendee can be in one of four states:
    invited, yes, maybe, no.
    """
    responses = response_list_to_dict(grequests.map(request.view_requests))
    user = Profile(responses[request.whoami_url], summary=False)

    attendee = [dict(rsvp=request.POST['rsvp'],profileId=user.id),]
    try:
        Event.rsvp(request.get_host(), event_id, user.id, attendee, access_token=request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    return HttpResponseRedirect(reverse('single-event', args=(event_id,)))
示例#4
0
文件: views.py 项目: mattrco/microweb
def newest(request, event_id):
    """
    Get redirected to the first unread post in an event.
    """

    try:
        response = Event.newest(request.get_host(), event_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 use Location.
    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)
示例#5
0
文件: views.py 项目: mattrco/microweb
def delete(request, event_id):
    """
    Delete an event and be redirected to the parent microcosm.
    """

    event = Event.retrieve(request.get_host(), event_id, access_token=request.access_token)
    try:
        event.delete(request.get_host(), request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    return HttpResponseRedirect(reverse('single-microcosm', args=(event.microcosm_id,)))
示例#6
0
def newest(request, event_id):
    """
    Get redirected to the first unread post in an event.
    """

    try:
        response = Event.newest(request.get_host(), event_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)
示例#7
0
def delete(request, event_id):
    """
    Delete an event and be redirected to the parent microcosm.
    """

    event = Event.retrieve(request.get_host(),
                           event_id,
                           access_token=request.access_token)
    try:
        event.delete(request.get_host(), request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    return HttpResponseRedirect(
        reverse('single-microcosm', args=(event.microcosm_id, )))
示例#8
0
def newest(request, event_id):
    """
    Get redirected to the first unread post in an event.
    """

    try:
        response = Event.newest(request.get_host(),
                                event_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)
示例#9
0
def rsvp(request, event_id):
    """
    Create an attendee (RSVP) for an event. An attendee can be in one of four states:
    invited, yes, maybe, no.
    """
    responses = response_list_to_dict(grequests.map(request.view_requests))
    user = Profile(responses[request.whoami_url], summary=False)

    attendee = [
        dict(rsvp=request.POST['rsvp'], profileId=user.id),
    ]

    try:
        response = Event.rsvp_api(request.get_host(),
                                  event_id,
                                  user.id,
                                  attendee,
                                  access_token=request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    if response.status_code != requests.codes.ok:
        return HttpResponseBadRequest()

    return HttpResponseRedirect(reverse('single-event', args=(event_id, )))
示例#10
0
 def testCommentedEventInit(self):
     data = json.loads(open(os.path.join(TEST_ROOT, "data", "event_with_comment.json")).read())["data"]
     Event.from_api_response(data)
示例#11
0
文件: views.py 项目: mattrco/microweb
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)
示例#12
0
文件: tests.py 项目: mattrco/microweb
 def testEventAsDict(self):
     data = json.loads(open(os.path.join(TEST_ROOT, 'data', 'event_without_comment.json')).read())['data']
     event = Event.from_api_response(data)
     event.as_dict()
示例#13
0
文件: tests.py 项目: mattrco/microweb
 def testCommentedEventInit(self):
     data = json.loads(open(os.path.join(TEST_ROOT, 'data', 'event_with_comment.json')).read())['data']
     Event.from_api_response(data)
示例#14
0
def confirm(request):
    """
    View for moderation actions on a single item.
    """

    if request.method == 'POST':
        if request.POST.get('item_type') == 'conversation':
            url, params, headers = Conversation.build_request(
                request.get_host(),
                request.POST.get('item_id'),
                access_token=request.access_token
            )
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Conversation.from_api_response(responses[url])

        elif request.POST.get('item_type') == 'event':
            url, params, headers = Event.build_request(
                request.get_host(),
                request.POST.get('item_id'),
                access_token=request.access_token
            )
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Event.from_api_response(responses[url])

        elif request.POST.get('item_type') == 'microcosm':
            url, params, headers = Microcosm.build_request(
                request.get_host(),
                request.POST.get('item_id'),
                access_token=request.access_token
            )
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Microcosm.from_api_response(responses[url])

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

        if request.POST.get('action') == 'move':
            # Fetch list of microcosms to supply in form.
            microcosms = MicrocosmList.retrieve(
                request.get_host(),
                access_token=request.access_token
            )

            if request.POST.get('item_type') == 'microcosm':
                newlist = []
                nuke = content.id
                found = False
                for m in microcosms.microcosms:
                    if m['id'] == nuke:
                        found = True
                        nuke = m['id']
                    elif m.get('parent_id') and m['parent_id'] == nuke:
                        found = True
                        nuke = m['id']
                    else:
                        if found:
                            nuke = 0
                        newlist.append(m)
                microcosms.microcosms = newlist


            view_data['microcosms'] = microcosms

        return render(request, 'forms/moderation_item.html', view_data)
示例#15
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)
示例#16
0
def moderate(request):
    """
    View for moderation actions on a single item.
    """
    microcosm_id = request.POST.get('microcosm_id')

    if request.method == 'POST':

        if request.POST.get('action') == 'move':

            if request.POST.get('item_type') == 'event':

                event = Event()
                event.id = int(request.POST.get('item_id'))
                event.microcosm_id = int(microcosm_id)
                event.meta = {'editReason': 'Moderator moved item'}
                event.update(request.get_host(), request.access_token)

            elif request.POST.get('item_type') == 'conversation':

                conversation = Conversation()
                conversation.id = int(request.POST.get('item_id'))
                conversation.microcosm_id = int(microcosm_id)
                conversation.meta = {'editReason': 'Moderator moved item'}
                conversation.update(request.get_host(), request.access_token)

            elif request.POST.get('item_type') == 'microcosm':

                microcosm = Microcosm()
                microcosm.id = int(request.POST.get('item_id'))
                microcosm.parent_id = int(microcosm_id)
                microcosm.meta = {'editReason': 'Moderator moved item'}
                microcosm.update(request.get_host(), request.access_token)

        else:
            # These are all PATCH requests and we need the item in question first
            if request.POST.get('item_type') == 'conversation':
                url, params, headers = Conversation.build_request(
                    request.get_host(),
                    request.POST.get('item_id'),
                    access_token=request.access_token)
            if request.POST.get('item_type') == 'event':
                url, params, headers = Event.build_request(
                    request.get_host(),
                    request.POST.get('item_id'),
                    access_token=request.access_token)
            if request.POST.get('item_type') == 'microcosm':
                url, params, headers = Microcosm.build_request(
                    request.get_host(),
                    request.POST.get('item_id'),
                    access_token=request.access_token)

            # And then to execute the PATCH against the item
            if request.POST.get('action') == 'delete':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/deleted',
                    'value': True
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'undelete':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/deleted',
                    'value': False
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'approve':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/moderated',
                    'value': False
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'pin':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/sticky',
                    'value': True
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'unpin':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/sticky',
                    'value': False
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'open':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/open',
                    'value': True
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'close':
                payload = json.dumps([{
                    'op': 'replace',
                    'path': '/meta/flags/open',
                    'value': False
                }])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

        return HttpResponseRedirect(
            reverse('single-microcosm', args=(microcosm_id, )))
示例#17
0
文件: views.py 项目: mattrco/microweb
def item(request):
    """
    View for moderation actions on a single item.
    """

    if request.method == 'POST':
        if request.POST.get('action') == 'move':
            if request.POST.get('item_type') == 'event':
                event = Event.retrieve(request.get_host(), request.POST.get('item_id'),
                    access_token=request.access_token)
                event.microcosm_id = int(request.POST.get('microcosm_id'))
                event.meta = {'editReason': 'Moderator moved item'}
                event.update(request.get_host(), request.access_token)
            elif request.POST.get('item_type') == 'conversation':
                conversation = Conversation.retrieve(request.get_host(), request.POST.get('item_id'),
                    access_token=request.access_token)
                conversation.microcosm_id = int(request.POST.get('microcosm_id'))
                conversation.meta = {'editReason': 'Moderator moved item'}
                conversation.update(request.get_host(), request.access_token)

        elif request.POST.get('action') == 'delete':
            if request.POST.get('item_type') == 'conversation':
                url, params, headers = Conversation.build_request(request.get_host(), request.POST.get('item_id'),
                    access_token=request.access_token)
            if request.POST.get('item_type') == 'event':
                url, params, headers = Event.build_request(request.get_host(), request.POST.get('item_id'),
                    access_token=request.access_token)
            payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/deleted', 'value': True}])
            headers['Content-Type'] = 'application/json'
            requests.patch(url, payload, headers=headers)

        return HttpResponseRedirect(reverse('single-microcosm', args=(request.POST.get('microcosm_id'),)))

    if request.method == 'GET':
        if request.GET.get('item_type') == 'conversation':
            url, params, headers = Conversation.build_request(request.get_host(), request.GET.get('item_id'),
                access_token=request.access_token)
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Conversation.from_api_response(responses[url])

        elif request.GET.get('item_type') == 'event':
            url, params, headers = Event.build_request(request.get_host(), request.GET.get('item_id'),
                access_token=request.access_token)
            request.view_requests.append(grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(grequests.map(request.view_requests))
            content = Event.from_api_response(responses[url])

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

        if request.GET.get('action') == 'move':
            # Fetch list of microcosms to supply in form.
            view_data['microcosms'] = MicrocosmList.retrieve(request.get_host(), access_token=request.access_token)

        return render(request, 'forms/moderation_item.html', view_data)
示例#18
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)
示例#19
0
 def testCommentedEventInit(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'event_with_comment.json')).read())['data']
     Event.from_api_response(data)
示例#20
0
 def testEventAsDict(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'event_without_comment.json')).read())['data']
     event = Event.from_api_response(data)
     event.as_dict()
示例#21
0
文件: views.py 项目: mattrco/microweb
def single(request, event_id):
    """
    Display a single event with comments and attendees.
    """

    # Comment offset.
    offset = int(request.GET.get('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)
示例#22
0
def moderate(request):
    """
    View for moderation actions on a single item.
    """
    microcosm_id = request.POST.get('microcosm_id')

    if request.method == 'POST':

        if request.POST.get('action') == 'move':

            if request.POST.get('item_type') == 'event':

                event = Event()
                event.id = int(request.POST.get('item_id'))
                event.microcosm_id = int(microcosm_id)
                event.meta = {'editReason': 'Moderator moved item'}
                event.update(request.get_host(), request.access_token)

            elif request.POST.get('item_type') == 'conversation':

                conversation = Conversation()
                conversation.id = int(request.POST.get('item_id'))
                conversation.microcosm_id = int(microcosm_id)
                conversation.meta = {'editReason': 'Moderator moved item'}
                conversation.update(request.get_host(), request.access_token)

            elif request.POST.get('item_type') == 'microcosm':

                microcosm = Microcosm()
                microcosm.id = int(request.POST.get('item_id'))
                microcosm.parent_id = int(microcosm_id)
                microcosm.meta = {'editReason': 'Moderator moved item'}
                microcosm.update(request.get_host(), request.access_token)

        else:
            # These are all PATCH requests and we need the item in question first
            if request.POST.get('item_type') == 'conversation':
                url, params, headers = Conversation.build_request(
                    request.get_host(),
                    request.POST.get('item_id'),
                    access_token=request.access_token
                )
            if request.POST.get('item_type') == 'event':
                url, params, headers = Event.build_request(
                    request.get_host(),
                    request.POST.get('item_id'),
                    access_token=request.access_token
                )
            if request.POST.get('item_type') == 'microcosm':
                url, params, headers = Microcosm.build_request(
                    request.get_host(),
                    request.POST.get('item_id'),
                    access_token=request.access_token
                )

            # And then to execute the PATCH against the item
            if request.POST.get('action') == 'delete':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/deleted', 'value': True}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'undelete':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/deleted', 'value': False}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'approve':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/moderated', 'value': False}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'pin':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/sticky', 'value': True}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'unpin':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/sticky', 'value': False}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'open':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/open', 'value': True}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

            elif request.POST.get('action') == 'close':
                payload = json.dumps([{'op': 'replace', 'path': '/meta/flags/open', 'value': False}])
                headers['Content-Type'] = 'application/json'
                requests.patch(url, payload, headers=headers)

        return HttpResponseRedirect(reverse('single-microcosm', args=(microcosm_id,)))
示例#23
0
def confirm(request):
    """
    View for moderation actions on a single item.
    """

    if request.method == 'POST':
        if request.POST.get('item_type') == 'conversation':
            url, params, headers = Conversation.build_request(
                request.get_host(),
                request.POST.get('item_id'),
                access_token=request.access_token)
            request.view_requests.append(
                grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(
                grequests.map(request.view_requests))
            content = Conversation.from_api_response(responses[url])

        elif request.POST.get('item_type') == 'event':
            url, params, headers = Event.build_request(
                request.get_host(),
                request.POST.get('item_id'),
                access_token=request.access_token)
            request.view_requests.append(
                grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(
                grequests.map(request.view_requests))
            content = Event.from_api_response(responses[url])

        elif request.POST.get('item_type') == 'microcosm':
            url, params, headers = Microcosm.build_request(
                request.get_host(),
                request.POST.get('item_id'),
                access_token=request.access_token)
            request.view_requests.append(
                grequests.get(url, params=params, headers=headers))
            responses = response_list_to_dict(
                grequests.map(request.view_requests))
            content = Microcosm.from_api_response(responses[url])

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

        if request.POST.get('action') == 'move':
            # Fetch list of microcosms to supply in form.
            microcosms = MicrocosmList.retrieve(
                request.get_host(), access_token=request.access_token)

            if request.POST.get('item_type') == 'microcosm':
                newlist = []
                nuke = content.id
                found = False
                for m in microcosms.microcosms:
                    if m['id'] == nuke:
                        found = True
                        nuke = m['id']
                    elif m.get('parent_id') and m['parent_id'] == nuke:
                        found = True
                        nuke = m['id']
                    else:
                        if found:
                            nuke = 0
                        newlist.append(m)
                microcosms.microcosms = newlist

            view_data['microcosms'] = microcosms

        return render(request, 'forms/moderation_item.html', view_data)
示例#24
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)