Example #1
0
def mark_read(request):
    """
    Mark a scope (e.g. site or microcosm) as read for the authenticated user.
    """

    scope = {
        'itemType': request.POST.get('item_type'),
        'itemId': int(request.POST.get('item_id')),
    }
    try:
        Profile.mark_read(request.get_host(), scope, request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    return HttpResponseRedirect(request.POST.get('return_path'))
Example #2
0
def mark_read(request):
    """
    Mark a scope (e.g. site or microcosm) as read for the authenticated user.
    """

    scope = {
        'itemType': request.POST.get('item_type'),
        'itemId': int(request.POST.get('item_id')),
    }
    try:
        Profile.mark_read(request.get_host(), scope, request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)
    return HttpResponseRedirect(request.POST.get('return_path'))
Example #3
0
    def list(request):
        # TODO: need a user friendly error page for unregistered users
        # TODO: remove 'site_section'
        if not request.access_token:
            responses = response_list_to_dict(grequests.map(request.view_requests))
            view_data = {
                'user': False,
                'site_section': 'updates',
                'site': Site(responses[request.site_url]),
                }
        else:
            # pagination offset
            try:
                offset = int(request.GET.get('offset', 0))
            except ValueError:
                offset = 0

            url, params, headers = UpdateList.build_request(request.get_host(), offset=offset,
                                                            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))
            updates_list = UpdateList(responses[url])

            view_data = {
                'user': Profile(responses[request.whoami_url], summary=False),
                'content': updates_list,
                'pagination': build_pagination_links(responses[url]['updates']['links'], updates_list.updates),
                'site_section': 'updates',
                'site': Site(responses[request.site_url]),
                }

        return render(request, UpdateView.list_template, view_data)
Example #4
0
def ignored(request):

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

    url, params, headers = Ignored.build_request(
        request.get_host(), offset=offset, 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)
    ignoredItems = Ignored.from_api_response(responses[url])

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'content':
        ignoredItems,
        'pagination':
        build_pagination_links(responses[url]['ignored']['links'],
                               ignoredItems),
        'site_section':
        'ignored',
    }

    return render(request, template_name, view_data)
Example #5
0
def list(request):
    # Offset for paging of huddles
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0
    unread = bool(request.GET.get('unread', False))

    huddle_url, params, headers = HuddleList.build_request(request.get_host(), offset=offset,
        unread=unread, access_token=request.access_token)

    request.view_requests.append(grequests.get(huddle_url, params=params, headers=headers))
    try:
        responses = response_list_to_dict(grequests.map(request.view_requests))
    except APIException as exc:
        return respond_with_error(request, exc)

    huddles = HuddleList(responses[huddle_url])
    
    filter_name = []

    if unread:
        filter_name.append("unread")

    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False) if request.whoami_url else None,
        'site': Site(responses[request.site_url]),
        'content': huddles,
        'unread': unread,
        'pagination': build_pagination_links(responses[huddle_url]['huddles']['links'], huddles.huddles)
    }
    return render(request, list_template, view_data)
Example #6
0
def single(request, profile_id):
    """
    Display a single profile by ID.
    """

    # Fetch profile details.
    profile_url, params, headers = Profile.build_request(request.get_host(), profile_id, access_token=request.access_token)
    request.view_requests.append(grequests.get(profile_url, params=params, headers=headers))

    # Fetch items created by this profile.
    search_q = 'type:conversation type:event type:huddle type:comment authorId:%s' % profile_id
    search_params = {'limit': 10, 'q': search_q, 'sort': 'date'}
    search_url, params, headers = Search.build_request(request.get_host(), search_params,
        access_token=request.access_token)
    request.view_requests.append(grequests.get(search_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)

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

    view_data = {
        'user': user,
        'content': profile,
        'item_type': 'profile',
        'site': Site(responses[request.site_url]),
        'search': Search.from_api_response(responses[search_url]),
        'site_section': 'people'
    }
    return render(request, single_template, view_data)
Example #7
0
def patch(request, profile_id):
    """
    Patch a user profile (member status).
    """

    if request.method == 'POST':
        form = patch_form(request.POST)
        if form.is_valid():
            # Update the actual profile resource.
            data = {
                'id': profile_id,
                'member': (form.cleaned_data['member'] == 'true'),
            }
            profile = Profile(data)
            profile.patch(request.get_host(), request.access_token)
        return HttpResponseRedirect(reverse('single-profile', args=(profile_id,)))
Example #8
0
    def single(request, doc_name):
        if not doc_name in ['cookies', 'privacy', 'terms']:
            return HttpResponseNotFound()

        url, params, headers = Legal.build_request(request.get_host(),
                                                   doc=doc_name)
        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)

        legal = Legal.from_api_response(responses[url])

        view_data = {
            'site':
            Site(responses[request.site_url]),
            'user':
            Profile(responses[request.whoami_url], summary=False)
            if request.whoami_url else None,
            'content':
            legal,
            'site_section':
            'legal',
            'page_section':
            doc_name
        }
        return render(request, LegalView.single_template, view_data)
Example #9
0
    def forbidden(request):
        view_data = {}
        view_requests = []

        if request.COOKIES.has_key('access_token'):
            request.access_token = request.COOKIES['access_token']
            whoami_url, params, headers = WhoAmI.build_request(
                request.get_host(), request.access_token)
            view_requests.append(
                grequests.get(whoami_url, params=params, headers=headers))

        site_url, params, headers = Site.build_request(request.get_host())
        view_requests.append(
            grequests.get(request.site_url, params=params, headers=headers))

        responses = response_list_to_dict(grequests.map(view_requests))
        if request.whoami_url:
            profile = Profile(responses[whoami_url], summary=False)
            view_data['user'] = profile
            newrelic.agent.add_custom_parameter('profile_name',
                                                profile.profile_name)
            newrelic.agent.add_custom_parameter('profile_id', profile.id)
            newrelic.agent.add_custom_parameter('user_id', profile.user_id)

        site = Site(responses[site_url])
        view_data['site'] = site
        newrelic.agent.add_custom_parameter('site', site.subdomain_key)

        context = RequestContext(request, view_data)
        return HttpResponseForbidden(
            loader.get_template('403.html').render(context))
Example #10
0
def create_microcosm(request, parent_id=0):
    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 = microcosm_create_form(request.POST)
        if form.is_valid():
            microcosm_request = Microcosm.from_create_form(form.cleaned_data)
            try:
                microcosm_response = microcosm_request.create(
                    request.get_host(), request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)
            return HttpResponseRedirect(
                reverse('single-microcosm', args=(microcosm_response.id, )))
        else:
            view_data['form'] = form
            return render(request, microcosm_form_template, view_data)

    if request.method == 'GET':
        view_data['form'] = microcosm_create_form(initial=dict(
            parentId=parent_id))
        view_data['parentId'] = parent_id

        return render(request, microcosm_form_template, view_data)
Example #11
0
def single(request):

    searchParams = dict(request.GET._iterlists())
    if searchParams.get('defaults'):
        searchParams['inTitle'] = 'true'
        searchParams['sort'] = 'date'

    url, params, headers = Search.build_request(
        request.get_host(),
        params=searchParams,
        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)
    search = Search.from_api_response(responses[url])

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

    if responses[url].get('results'):
        view_data['pagination'] = build_pagination_links(
            responses[url]['results']['links'], search.results)

    return render(request, single_template, view_data)
Example #12
0
def edit_microcosm(request, microcosm_id):
    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 = microcosm_edit_form(request.POST)
        if not form.is_valid():
            view_data['form'] = form
            return render(request, microcosm_form_template, view_data)

        payload = form.cleaned_data

        if request.POST.get('remove_logo'):
            payload['logoUrl'] = ''
            payload['removeLogo'] = True
        elif request.FILES.has_key('logo'):
            file_request = FileMetadata.from_create_form(
                request.FILES['logo'], )
            try:
                metadata = file_request.create(
                    request.get_host(),
                    request.access_token,
                    width=64,
                    height=64,
                )
            except APIException as exc:
                return respond_with_error(request, exc)

            logo_url = get_subdomain_url(
                request.get_host()) + '/api/v1/files/' + metadata.file_hash
            if hasattr(metadata, 'file_ext'):
                logo_url = logo_url + '.' + metadata.file_ext
            payload['logoUrl'] = logo_url

        microcosm_request = Microcosm.from_edit_form(payload)
        try:
            microcosm_response = microcosm_request.update(
                request.get_host(), request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        return HttpResponseRedirect(
            reverse('single-microcosm', args=(microcosm_response.id, )))

    if request.method == 'GET':
        try:
            microcosm = Microcosm.retrieve(request.get_host(),
                                           id=microcosm_id,
                                           access_token=request.access_token)
        except APIException as exc:
            return respond_with_error(request, exc)
        view_data['form'] = microcosm_edit_form(microcosm.as_dict)

        return render(request, microcosm_form_template, view_data)
Example #13
0
def patch(request, profile_id):
    """
    Patch a user profile (member status).
    """

    if request.method == 'POST':
        form = patch_form(request.POST)
        if form.is_valid():
            # Update the actual profile resource.
            data = {
                'id': profile_id,
                'member': (form.cleaned_data['member'] == 'true'),
            }
            profile = Profile(data)
            profile.patch(request.get_host(), request.access_token)
        return HttpResponseRedirect(
            reverse('single-profile', args=(profile_id, )))
Example #14
0
def single(request, conversation_id):

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

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

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

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

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

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'content':
        conversation,
        'comment_form':
        comment_form,
        'pagination':
        build_pagination_links(
            responses[conversation_url]['comments']['links'],
            conversation.comments),
        'item_type':
        'conversation',
        'attachments':
        attachments
    }
    return render(request, single_template, view_data)
Example #15
0
def list_members(request, microcosm_id):
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0

    microcosm_url, params, headers = Microcosm.build_request(
        request.get_host(),
        id=microcosm_id,
        offset=offset,
        access_token=request.access_token)
    request.view_requests.append(
        grequests.get(microcosm_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)
    microcosm = Microcosm.from_api_response(responses[microcosm_url])

    roles_url, params, headers = RoleList.build_request(
        request.META['HTTP_HOST'],
        id=microcosm_id,
        offset=offset,
        access_token=request.access_token)
    request.view_requests.append(
        grequests.get(roles_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)
    roles = RoleList.from_api_response(responses[roles_url])

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'site_section':
        'memberships',
        'content':
        microcosm,
        'memberships':
        roles,
        'item_type':
        'microcosm',
        'pagination':
        build_pagination_links(responses[roles_url]['roles']['links'],
                               roles.items)
    }

    return render(request, members_list_template, view_data)
Example #16
0
def single(request, profile_id):
    """
    Display a single profile by ID.
    """

    # Fetch profile details.
    profile_url, params, headers = Profile.build_request(
        request.get_host(), profile_id, access_token=request.access_token)
    request.view_requests.append(
        grequests.get(profile_url, params=params, headers=headers))

    # Fetch items created by this profile.
    search_q = 'type:conversation type:event type:huddle type:comment authorId:%s' % profile_id
    search_params = {'limit': 10, 'q': search_q, 'sort': 'date'}
    search_url, params, headers = Search.build_request(
        request.get_host(), search_params, access_token=request.access_token)
    request.view_requests.append(
        grequests.get(search_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)

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

    view_data = {
        'user': user,
        'content': profile,
        'item_type': 'profile',
        'site': Site(responses[request.site_url]),
        'search': Search.from_api_response(responses[search_url]),
        'site_section': 'people'
    }
    return render(request, single_template, view_data)
Example #17
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)
Example #18
0
    def list(request):
        try:
            responses = response_list_to_dict(
                grequests.map(request.view_requests))
        except APIException as exc:
            return respond_with_error(request, exc)

        view_data = {
            'site':
            Site(responses[request.site_url]),
            'user':
            Profile(responses[request.whoami_url], summary=False)
            if request.whoami_url else None,
            'site_section':
            'legal'
        }
        return render(request, LegalView.list_template, view_data)
Example #19
0
def list(request):
    url, params, headers = Trending.build_request(request.get_host(), 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)
    trending = Trending.from_api_response(responses[url])

    view_data = {
        'user': Profile(responses[request.whoami_url], summary=False) if request.whoami_url else None,
        'site': Site(responses[request.site_url]),
        'content': trending,
        'pagination': build_pagination_links(responses[url]['items']['links'], trending.items),
        'site_section': 'trending'
    }

    return render(request, list_template, view_data)
Example #20
0
def single(request, huddle_id):

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

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

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

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

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

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

    return render(request, single_template, view_data)
Example #21
0
    def settings(request):

        if request.method == 'POST':
            for x in range(1, 10):
                if request.POST.get('id_' + str(x)):
                    postdata = {
                        'id': int(request.POST['id_' + str(x)]),
                        'sendEmail': bool(request.POST.get('send_email_' + str(x))),
                        'sendSMS': False,
                        }
                    UpdatePreference.update(
                        request.get_host(),
                        request.POST['id_' + str(x)],
                        postdata,
                        request.access_token
                    )

            postdata = {
                'sendEmail': bool(request.POST.get('profile_receive_email')),
                'sendSMS': False,
                }
            GlobalOptions.update(request.get_host(), postdata, request.access_token)
            return HttpResponseRedirect(reverse('updates-settings'))

        if request.method == 'GET':
            url, params, headers = UpdatePreference.build_request(request.get_host(), request.access_token)
            request.view_requests.append(grequests.get(url, params=params, headers=headers))

            url2, params2, headers2 = GlobalOptions.build_request(request.get_host(), request.access_token)
            request.view_requests.append(grequests.get(url2, params=params2, headers=headers2))

            responses = response_list_to_dict(grequests.map(request.view_requests))
            preference_list = UpdatePreference.from_list(responses[url])
            global_options = GlobalOptions.from_api_response(responses[url2])

            view_data = {
                'user': Profile(responses[request.whoami_url], summary=False),
                'site': Site(responses[request.site_url]),
                'content': preference_list,
                'globaloptions': global_options,
                }
            return render(request, UpdatePreferenceView.list_template, view_data)
Example #22
0
def edit(request, conversation_id):
    """
    Edit a 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]),
        'state_edit': True,
    }

    if request.method == 'POST':
        form = edit_form(request.POST)

        if form.is_valid():
            conv_request = Conversation.from_edit_form(form.cleaned_data)
            try:
                conv_response = conv_request.update(request.get_host(),
                                                    request.access_token)
            except APIException as exc:
                return respond_with_error(request, exc)
            return HttpResponseRedirect(
                reverse('single-conversation', args=(conv_response.id, )))
        else:
            view_data['form'] = form
            return render(request, form_template, view_data)

    if request.method == 'GET':
        conversation = Conversation.retrieve(request.get_host(),
                                             id=conversation_id,
                                             access_token=request.access_token)
        view_data['form'] = edit_form.from_conversation_instance(conversation)

        return render(request, form_template, view_data)
Example #23
0
    def list(request):

        if request.method == 'POST':
            if 'watcher_id' in request.POST:
                watchers = request.POST.getlist('watcher_id')
                # TODO: get rid of casts
                for w in watchers:
                    if request.POST.get('delete_watcher_' + str(w)):
                        Watcher.delete(request.get_host(), w, request.access_token)
                    else:
                        postdata = {
                            'id': int(w),
                            'sendEmail': bool(request.POST.get('send_email_' + str(w))),
                            'receiveSMS': False,
                            }
                        Watcher.update(request.get_host(), int(w), postdata, request.access_token)
            return HttpResponseRedirect(reverse('list-watchers'))

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

            url, params, headers = WatcherList.build_request(request.get_host(), offset=offset,
                                                             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))
            watchers_list = WatcherList(responses[url])

            view_data = {
                'user': Profile(responses[request.whoami_url], summary=False),
                'site': Site(responses[request.site_url]),
                'content': watchers_list,
                'pagination': build_pagination_links(responses[url]['watchers']['links'], watchers_list.watchers)
            }

            return render(request, WatcherView.list_template, view_data)
Example #24
0
def root_microcosm(request):

    # Pagination offset of items within the microcosm.
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        offset = 0

    microcosm_id = 0
    microcosm_url, params, headers = Microcosm.build_request(
        request.get_host(),
        id=microcosm_id,
        offset=offset,
        access_token=request.access_token)
    request.view_requests.append(
        grequests.get(microcosm_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)

    microcosm = Microcosm.from_api_response(responses[microcosm_url])

    view_data = {
        'user':
        Profile(responses[request.whoami_url], summary=False)
        if request.whoami_url else None,
        'site':
        Site(responses[request.site_url]),
        'content':
        microcosm,
        'item_type':
        'microcosm',
        'pagination':
        build_pagination_links(responses[microcosm_url]['items']['links'],
                               microcosm.items)
    }

    return render(request, microcosm_root_template, view_data)
Example #25
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, )))
Example #26
0
def single(request):

    searchParams = request.GET.dict()
    searchParams['type'] = ['conversation', 'event', 'profile', 'huddle']
    searchParams['since'] = -1

    url, params, headers = Search.build_request(
        request.get_host(),
        params=searchParams,
        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)
    search = Search.from_api_response(responses[url])

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

    if responses[url].get('results'):
        view_data['pagination'] = build_pagination_links(
            responses[url]['results']['links'], search.results)

    return render(request, single_template, view_data)
Example #27
0
 def testProfileAsDict(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'profile.json')).read())['data']
     profile = Profile(data)
     profile.as_dict
Example #28
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))
Example #29
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)
Example #30
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)
Example #31
0
def edit_members(request, microcosm_id, group_id):

    if request.method == 'POST':
        pass
    elif request.method == 'GET':
        try:
            offset = int(request.GET.get('offset', 0))
        except ValueError:
            offset = 0

        microcosm_url, params, headers = Microcosm.build_request(
            request.get_host(),
            id=microcosm_id,
            offset=offset,
            access_token=request.access_token)
        request.view_requests.append(
            grequests.get(microcosm_url, params=params, headers=headers))

        role_url, params, headers = Role.build_request(
            request.get_host(),
            microcosm_id=microcosm_id,
            id=group_id,
            offset=offset,
            access_token=request.access_token)
        request.view_requests.append(
            grequests.get(role_url, params=params, headers=headers))

        criteria_url, params, headers = RoleCriteriaList.build_request(
            request.get_host(),
            microcosm_id=microcosm_id,
            id=group_id,
            offset=offset,
            access_token=request.access_token)
        request.view_requests.append(
            grequests.get(criteria_url, params=params, headers=headers))

        profiles_url, params, headers = RoleProfileList.build_request(
            request.get_host(),
            microcosm_id=microcosm_id,
            id=group_id,
            offset=offset,
            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)

        microcosm = Microcosm.from_api_response(responses[microcosm_url])
        role = Role.from_api_response(responses[role_url])
        criteria = RoleCriteriaList(responses[criteria_url])
        profiles = RoleProfileList(responses[profiles_url])

        view_data = {
            'user':
            Profile(responses[request.whoami_url], summary=False)
            if request.whoami_url else None,
            'site':
            Site(responses[request.site_url]),
            'site_section':
            'memberships',
            'content':
            microcosm,
            'role':
            role,
            'criteria':
            criteria,
            'profiles':
            profiles,
            'item_type':
            'memberships',
            'state_edit':
            True,
            'pagination':
            build_pagination_links(responses[microcosm_url]['items']['links'],
                                   microcosm.items)
        }

        return render(request, members_form_template, view_data)
Example #32
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)
Example #33
0
 def testWhoamiInit(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'whoami.json')).read())['data']
     Profile(data)
Example #34
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)
Example #35
0
 def testProfileSummaryInit(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data',
                           'profile.json')).read())['data']
     Profile(data, summary=True)