Esempio n. 1
0
    def server_error(request, exception=None):
        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)

        # Provide detailed error if returned in the response.
        if hasattr(exception, 'detail'):
            if 'errorDetail' in exception.detail:
                view_data['detail'] = exception.detail['errorDetail']

        context = RequestContext(request, view_data)
        return HttpResponseServerError(
            loader.get_template('500.html').render(context))
Esempio n. 2
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))
Esempio n. 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)
Esempio n. 4
0
    def requires_login(request):
        view_data = {}
        view_requests = []

        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))
        view_data['site'] = Site(responses[site_url])
        view_data['logout'] = True

        context = RequestContext(request, view_data)
        return HttpResponseForbidden(
            loader.get_template('403.html').render(context))
Esempio n. 5
0
    def process_request(self, request):

        host = request.get_host()

        # Only look at requests to example.microco.sm
        if host.endswith(settings.API_DOMAIN_NAME):

            # Fetch site from cache
            try:
                site = self.mc.get(host)
            except memcache.Error as e:
                logger.error('Memcached GET error: %s' % str(e))
                site = None

            # Not in cache or retrieval failed
            if site is None:
                try:
                    site = Site.retrieve(host)
                    try:
                        self.mc.set(host, site, time=300)
                    except memcache.Error as e:
                        logger.error('Memcached SET error: %s' % str(e))
                except APIException, e:
                    # HTTP 400 indicates a non-existent site.
                    if e.status_code == 404:
                        return HttpResponseRedirect('http://microco.sm')
                    logger.error('APIException: %s' % e.message)
                    return HttpResponseRedirect(reverse('server-error'))
                except RequestException, e:
                    logger.error('RequestException: %s' % e.message)
                    return HttpResponseRedirect(reverse('server-error'))
Esempio n. 6
0
    def process_request(self, request):

        host = request.get_host()

        # Only look at requests to example.microco.sm
        if host.endswith(settings.API_DOMAIN_NAME):

            # Fetch site from cache
            try:
                site = self.mc.get(host)
            except memcache.Error as e:
                logger.error('Memcached GET error: %s' % str(e))
                site = None

            # Not in cache or retrieval failed
            if site is None:
                try:
                    site = Site.retrieve(host)
                    try:
                        self.mc.set(host, site, time=300)
                    except memcache.Error as e:
                        logger.error('Memcached SET error: %s' % str(e))
                except APIException, e:
                    # HTTP 400 indicates a non-existent site.
                    if e.status_code == 400:
                        return HttpResponseRedirect('http://microco.sm')
                    logger.error('APIException: %s' % e.message)
                    return HttpResponseRedirect(reverse('server-error'))
                except RequestException, e:
                    logger.error('RequestException: %s' % e.message)
                    return HttpResponseRedirect(reverse('server-error'))
Esempio n. 7
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)
Esempio n. 8
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)
Esempio n. 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))
Esempio n. 10
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)
Esempio n. 11
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)
Esempio n. 12
0
    def process_request(self, request):
        """
        Checks for access_token cookie and appends it to the request object if present.

        All request objects have a view_requests attribute which is a list of requests
        that will be executed by grequests to fetch data for the view.
        """

        request.access_token = None
        request.whoami_url = ''
        request.view_requests = []

        if request.COOKIES.has_key('access_token'):
            # Clean up empty access token.
            if request.COOKIES['access_token'] == '':
                response = HttpResponseRedirect('/')
                response.set_cookie('access_token', '', expires="Thu, 01 Jan 1970 00:00:00 GMT")
                return response
            request.access_token = request.COOKIES['access_token']
            request.whoami_url, params, headers = WhoAmI.build_request(request.get_host(), request.access_token)
            request.view_requests.append(grequests.get(request.whoami_url, params=params, headers=headers))
            newrelic.agent.add_custom_parameter('access_token', request.access_token[:6])

        request.site_url, params, headers = Site.build_request(request.get_host())
        request.view_requests.append(grequests.get(request.site_url, params=params, headers=headers))
Esempio n. 13
0
    def process_request(self, request):
        """
        Checks for access_token cookie and appends it to the request object if present.

        All request objects have a view_requests attribute which is a list of requests
        that will be executed by grequests to fetch data for the view.
        """

        request.access_token = None
        request.whoami_url = ''
        request.view_requests = []

        if request.COOKIES.has_key('access_token'):
            # Clean up empty access token.
            if request.COOKIES['access_token'] == '':
                response = HttpResponseRedirect('/')
                response.set_cookie('access_token',
                                    '',
                                    expires="Thu, 01 Jan 1970 00:00:00 GMT")
                return response
            request.access_token = request.COOKIES['access_token']
            request.whoami_url, params, headers = WhoAmI.build_request(
                request.get_host(), request.access_token)
            request.view_requests.append(
                grequests.get(request.whoami_url,
                              params=params,
                              headers=headers))
            # newrelic.agent.add_custom_parameter('access_token', request.access_token[:6])

        request.site_url, params, headers = Site.build_request(
            request.get_host())
        request.view_requests.append(
            grequests.get(request.site_url, params=params, headers=headers))
Esempio n. 14
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)
Esempio n. 15
0
    def server_error(request, exception=None):
        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)

        # Provide detailed error if returned in the response.
        if hasattr(exception, 'detail'):
            if 'errorDetail' in exception.detail:
                view_data['detail'] = exception.detail['errorDetail']

        context = RequestContext(request, view_data)
        return HttpResponseServerError(loader.get_template('500.html').render(context))
Esempio n. 16
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)
Esempio n. 17
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)
Esempio n. 18
0
    def requires_login(request):
        view_data = {}
        view_requests = []

        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))
        view_data['site'] = Site(responses[site_url])
        view_data['logout'] = True

        context = RequestContext(request, view_data)
        return HttpResponseForbidden(loader.get_template('403.html').render(context))
Esempio n. 19
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)
Esempio n. 20
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)
Esempio n. 21
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)
Esempio n. 22
0
    def server_error(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))
        view_data['user'] = Profile(responses[whoami_url], summary=False) if request.whoami_url else None
        view_data['site'] = Site(responses[site_url])

        context = RequestContext(request, view_data)
        return HttpResponseServerError(loader.get_template('500.html').render(context))
Esempio n. 23
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)
Esempio n. 24
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)
Esempio n. 25
0
    def process_request(self, request):
        """
        Checks for access_token cookie and appends it to the request object if present.

        All request objects have a view_requests attribute which is a list of requests
        that will be executed by grequests to fetch data for the view.
        """

        request.access_token = None
        request.whoami_url = ''
        request.view_requests = []

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

        request.site_url, params, headers = Site.build_request(request.get_host())
        request.view_requests.append(grequests.get(request.site_url, params=params, headers=headers))
Esempio n. 26
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)
Esempio n. 27
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)
Esempio n. 28
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)
Esempio n. 29
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)
Esempio n. 30
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)
Esempio n. 31
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)
Esempio n. 32
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)
Esempio n. 33
0
def redirect_or_404(request):

    host = request.get_host()

    # If the request host is already a microcosm subdomain, this is not
    # a request for an imported site, so return not found.
    if host.endswith(settings.API_DOMAIN_NAME):
        return ErrorView.not_found(request)

    # Get site subdomain key based on host.
    try:
        microcosm_host = Site.resolve_cname(host)
    except APIException:
        logger.error(str(APIException))

    # Reverse the effect of APPEND_SLASH on the path.
    url_parts = urlparse.urlsplit(request.build_absolute_uri())
    path = url_parts.path
    redirect_request = ''
    if path.endswith('/'):
        redirect_request = path[:-1]
    if url_parts.query:
        redirect_request += '?' + url_parts.query

    # Handle errors in API request.
    try:
        resource = Redirect.get(host, redirect_request, request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    # Handle non-successful redirects (e.g. invalid path, forbidden).
    if resource['status'] == 404:
        return ErrorView.not_found(request)
    if resource['status'] == 403:
        return ErrorView.forbidden(request)
    if resource['status'] != 301:
        return ErrorView.server_error(request)

    # Attachments just go to the URL
    if resource['itemType'] == 'attachment':
        return HttpResponseRedirect(resource['redirect']['href'])

    # Construct the 301 based on the resource.
    redirect_path = '/' + RESOURCE_PLURAL[resource['itemType']]
    if resource.has_key('itemId'):
        redirect_path += '/' + str(resource['itemId'])

    # Hack comments to show in context.
    if resource['itemType'] == 'comment' and resource.has_key('itemId'):
        redirect_path += '/' + 'incontext'

    # Build query parameters.
    query_dict = {}

    # Query parameter actions.
    if resource.has_key('action'):
        if resource.has_key('search'):
            query_dict['q'] = resource['search']
        if resource.has_key('online'):
            query_dict['online'] = 'true'

    # Record offset.
    if resource.has_key('offset'):
        query_dict['offset'] = str(resource['offset'])

    # Reconstruct the URL, dropping query parameters and path fragment.
    parts = (url_parts.scheme, url_parts.netloc, redirect_path,
             urllib.urlencode(query_dict), '')
    redirect_url = urlparse.urlunsplit(parts)

    #print "Redirecting %s to %s" % (request.get_full_path(), redirect_url)
    return HttpResponseRedirect(redirect_url)
Esempio n. 34
0
 def testSiteInit(self):
     data = json.loads(
         open(os.path.join(TEST_ROOT, 'data', 'site.json')).read())['data']
     Site(data)
Esempio n. 35
0
def redirect_or_404(request):

    host = request.get_host()
    
    # If the request host is already a microcosm subdomain, this is not
    # a request for an imported site, so return not found.
    if host.endswith(settings.API_DOMAIN_NAME):
        return ErrorView.not_found(request)

    # Get site subdomain key based on host.
    try:
        microcosm_host = Site.resolve_cname(host)
    except APIException:
        logger.error(str(APIException))

    # Reverse the effect of APPEND_SLASH on the path.
    url_parts = urlparse.urlsplit(request.build_absolute_uri())
    path = url_parts.path
    redirect_request = ''
    if path.endswith('/'):
        redirect_request = path[:-1]
    if url_parts.query:
        redirect_request += '?' + url_parts.query

    # Handle errors in API request.
    try:
        resource = Redirect.get(host, redirect_request, request.access_token)
    except APIException as exc:
        return respond_with_error(request, exc)

    # Handle non-successful redirects (e.g. invalid path, forbidden).
    if resource['status'] == 404:
        return ErrorView.not_found(request)
    if resource['status'] == 403:
        return ErrorView.forbidden(request)
    if resource['status'] != 301:
        return ErrorView.server_error(request)

    # Attachments just go to the URL
    if resource['itemType'] == 'attachment':
        return HttpResponseRedirect(resource['redirect']['href'])

    # Construct the 301 based on the resource.
    redirect_path = '/' + RESOURCE_PLURAL[resource['itemType']]
    if resource.has_key('itemId'):
        redirect_path += '/' + str(resource['itemId'])

    # Hack comments to show in context.
    if resource['itemType'] == 'comment' and resource.has_key('itemId'):
        redirect_path += '/' + 'incontext'

    # Build query parameters.
    query_dict = {}

    # Query parameter actions.
    if resource.has_key('action'):
        if resource.has_key('search'):
            query_dict['q'] = resource['search']
        if resource.has_key('online'):
            query_dict['online'] = 'true'

    # Record offset.
    if resource.has_key('offset'):
        query_dict['offset'] = str(resource['offset'])

    # Reconstruct the URL, dropping query parameters and path fragment.
    parts = (url_parts.scheme, url_parts.netloc, redirect_path, urllib.urlencode(query_dict), '')
    redirect_url = urlparse.urlunsplit(parts)

    #print "Redirecting %s to %s" % (request.get_full_path(), redirect_url)
    return HttpResponseRedirect(redirect_url)
Esempio n. 36
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))
Esempio n. 37
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)
Esempio n. 38
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)