예제 #1
0
    def prefill_search_company(self, search):
        """ Prefill the search company

        :param SearchQuery search: The search query instance
        """

        search.company = get_user_company(search.user)
예제 #2
0
def get_view_data():
    user = get_user()
    topics = get_user_topics(user['_id']) if user else []
    company = get_user_company(user) or {}
    return {
        'user':
        str(user['_id']) if user else None,
        'company':
        str(user['company']) if user and user.get('company') else None,
        'topics': [t for t in topics if t.get('topic_type') == 'agenda'],
        'formats': [{
            'format': f['format'],
            'name': f['name']
        } for f in app.download_formatters.values() if 'agenda' in f['types']],
        'navigations':
        get_navigations_by_company(
            str(user['company']) if user and user.get('company') else None,
            product_type='agenda',
            events_only=company.get('events_only', False)),
        'saved_items':
        get_resource_service('agenda').get_saved_items_count(),
        'events_only':
        company.get('events_only', False),
        'locators':
        get_vocabulary('locators'),
        'ui_config':
        get_resource_service('ui_config').getSectionConfig('agenda')
    }
예제 #3
0
    def get(self, req, lookup, size=25, aggs=True):
        query = _items_query()
        user = get_user()
        company = get_user_company(user)
        set_product_query(query,
                          company,
                          navigation_id=req.args.get('navigation'),
                          product_type=req.args.get('section')
                          if req.args.get('bookmarks') else None)

        if req.args.get('q'):
            query['bool']['must'].append(query_string(req.args['q']))

        if req.args.get('newsOnly') and not (req.args.get('navigation')
                                             or req.args.get('product_type')):
            for f in app.config.get('NEWS_ONLY_FILTERS', []):
                query['bool']['must_not'].append(f)

        if req.args.get('bookmarks'):
            set_bookmarks_query(query, req.args['bookmarks'])

        filters = None

        if req.args.get('filter'):
            filters = json.loads(req.args['filter'])

        if not app.config.get('FILTER_BY_POST_FILTER', False):
            if filters:
                query['bool']['must'] += _filter_terms(filters)

            if req.args.get('created_from') or req.args.get('created_to'):
                query['bool']['must'].append(versioncreated_range(req.args))

        source = {'query': query}
        source['sort'] = [{'versioncreated': 'desc'}]
        source['size'] = size
        source['from'] = int(req.args.get('from', 0))

        if app.config.get('FILTER_BY_POST_FILTER', False):
            if filters or req.args.get('created_from') or req.args.get(
                    'created_to'):
                source['post_filter'] = {'bool': {'must': []}}
            if filters:
                source['post_filter']['bool']['must'] += _filter_terms(filters)
            if req.args.get('created_from') or req.args.get('created_to'):
                source['post_filter']['bool']['must'].append(
                    versioncreated_range(req.args))

        if source['from'] >= 1000:
            # https://www.elastic.co/guide/en/elasticsearch/guide/current/pagination.html#pagination
            return abort(400)

        if not source[
                'from'] and aggs:  # avoid aggregations when handling pagination
            source['aggs'] = aggregations

        internal_req = ParsedRequest()
        internal_req.args = {'source': json.dumps(source)}
        return super().get(internal_req, lookup)
예제 #4
0
 def get_saved_items_count(self):
     query = _agenda_query()
     user = get_user()
     company = get_user_company(user)
     set_product_query(query, company)
     set_saved_items_query(query, str(user['_id']))
     cursor = self.get_items_by_query(query, size=0)
     return cursor.count()
예제 #5
0
def get_services(user):
    services = app.config['SERVICES']
    for service in services:
        service.setdefault('is_active', True)
    company = get_user_company(user)
    if company and company.get('services'):
        for service in services:
            service['is_active'] = bool(company['services'].get(service['code']))
    return services
예제 #6
0
파일: agenda.py 프로젝트: mdhaman/newsroom
 def get_saved_items_count(self):
     query = _agenda_query()
     get_resource_service('section_filters').apply_section_filter(query, self.section)
     user = get_user()
     company = get_user_company(user)
     set_product_query(query, company, self.section)
     set_saved_items_query(query, str(user['_id']))
     cursor = self.get_items_by_query(query, size=0)
     return cursor.count()
예제 #7
0
 def get_bookmarks_count(self, user_id):
     query = _items_query()
     user = get_user()
     company = get_user_company(user)
     set_product_query(query, company)
     _set_bookmarks_query(query, user_id)
     source = {'query': query, 'size': 0}
     internal_req = ParsedRequest()
     internal_req.args = {'source': json.dumps(source)}
     return super().get(internal_req, None).count()
예제 #8
0
def send_coverage_request_email(user, message, item):
    """
    Forms and sends coverage request email
    :param user: User that makes the request
    :param message: Request message
    :param item: agenda item that request is made against
    :return:
    """

    general_settings = get_settings_collection().find_one(
        GENERAL_SETTINGS_LOOKUP)
    if not general_settings:
        return

    recipients = general_settings.get('values').get(
        'coverage_request_recipients').split(',')
    assert recipients
    assert isinstance(recipients, list)
    url = url_for_agenda({'_id': item['_id']}, _external=True)
    name = '{} {}'.format(user.get('first_name'), user.get('last_name'))
    email = user.get('email')

    item_name = item.get('name') or item.get('slugline')
    subject = gettext('Coverage inquiry: {}'.format(item_name))
    user_company = get_user_company(user)
    if user_company:
        user_company = user_company.get('name')

    text_body = render_template('coverage_request_email.txt',
                                name=name,
                                email=email,
                                message=message,
                                url=url,
                                company=user_company,
                                recipients=recipients,
                                subject=subject,
                                item_name=item_name)
    html_body = render_template('coverage_request_email.html',
                                name=name,
                                email=email,
                                message=message,
                                url=url,
                                company=user_company,
                                recipients=recipients,
                                subject=subject,
                                item_name=item_name)

    send_email(to=recipients,
               subject=subject,
               text_body=text_body,
               html_body=html_body)
예제 #9
0
 def get_bookmarks_count(self, user_id):
     query = _items_query()
     user = get_user()
     get_resource_service('section_filters').apply_section_filter(
         query, self.section)
     company = get_user_company(user)
     try:
         set_product_query(query, company, self.section)
     except Forbidden:
         return 0
     set_bookmarks_query(query, user_id)
     source = {'query': query, 'size': 0}
     internal_req = ParsedRequest()
     internal_req.args = {'source': json.dumps(source)}
     return super().get(internal_req, None).count()
예제 #10
0
    def get(self, req, lookup):
        query = _agenda_query()
        user = get_user()
        company = get_user_company(user)
        try:
            set_product_query(query,
                              company,
                              navigation_id=req.args.get('navigation'))
        except FeaturedQuery:
            return self.featured(req, lookup)

        if req.args.get('q'):
            query['bool']['must'].append(query_string(req.args['q']))

        if req.args.get('id'):
            query['bool']['must'].append({'term': {'_id': req.args['id']}})

        if req.args.get('bookmarks'):
            set_saved_items_query(query, req.args['bookmarks'])

        if req.args.get('date_from'):
            query['bool']['should'].append(_event_date_range(req.args))
            query['bool']['should'].append(_display_date_range(req.args))

        if req.args.get('created_from') or req.args.get('created_to'):
            query['bool']['must'].append(versioncreated_range(req.args))

        source = {'query': query}
        source['sort'] = [{'dates.start': 'asc'}]
        source['size'] = 100  # we should fetch all items for given date
        source['from'] = req.args.get('from', 0, type=int)

        set_post_filter(source, req)

        if source['from'] >= 1000:
            # https://www.elastic.co/guide/en/elasticsearch/guide/current/pagination.html#pagination
            return abort(400)

        if not source['from'] and not req.args.get(
                'bookmarks'):  # avoid aggregations when handling pagination
            source['aggs'] = aggregations

        internal_req = ParsedRequest()
        internal_req.args = {'source': json.dumps(source)}
        return super().get(internal_req, lookup)
예제 #11
0
파일: views.py 프로젝트: mdhaman/newsroom
def item(_id):
    item = get_entity_or_404(_id, 'agenda')

    user = get_user()
    company = get_user_company(user)
    if not is_admin_or_internal(user):
        item.get('event', {}).pop('files', None)
        planning_items = item.get('planning_items', [])
        [item.pop('internal_note', None) for item in planning_items]
        coverages = item.get('coverages', [])
        [c.get('planning', {}).pop('internal_note', None) for c in coverages]
        item.get('event', {}).pop('internal_note', None)

    if company and not is_admin(user) and company.get('events_only', False):
        # if the company has permission events only permission then
        # remove planning items and coverages.
        if not item.get('event'):
            # for adhoc planning items abort the request
            flask.abort(403)

        item.pop('planning_items', None)
        item.pop('coverages', None)

    if is_json_request(flask.request):
        return flask.jsonify(item)

    if 'print' in flask.request.args:
        map = flask.request.args.get('map')
        template = 'agenda_item_print.html'
        update_action_list([_id], 'prints', force_insert=True)
        return flask.render_template(
            template,
            item=item,
            map=map,
            dateString=get_agenda_dates(item),
            location=get_location_string(item),
            contacts=get_public_contacts(item),
            links=get_links(item),
            is_admin=is_admin_or_internal(user)
        )

    data = get_view_data()
    data['item'] = item
    return flask.render_template('agenda_index.html', data=data, title=item.get('name', item.get('headline')))
예제 #12
0
    def get(self, req, lookup):
        query = _items_query()
        user = get_user()
        company = get_user_company(user)
        _set_product_query(query, company, navigation_id=req.args.get('navigation'))

        if req.args.get('q'):
            query['bool']['must'].append(_query_string(req.args['q']))
            query['bool']['must_not'].append({'term': {'pubstatus': 'canceled'}})

        if req.args.get('bookmarks'):
            _set_bookmarks_query(query, req.args['bookmarks'])

        source = {'query': query}
        source['sort'] = [{'versioncreated': 'desc'}]
        source['size'] = 25
        source['from'] = int(req.args.get('from', 0))
        source['post_filter'] = {'bool': {'must': []}}

        if source['from'] >= 1000:
            # https://www.elastic.co/guide/en/elasticsearch/guide/current/pagination.html#pagination
            return abort(400)

        if not source['from']:  # avoid aggregations when handling pagination
            source['aggs'] = aggregations

        if req.args.get('filter'):
            filters = json.loads(req.args['filter'])
            if filters:
                source['post_filter']['bool']['must'] += _filter_terms(filters)

        if req.args.get('created_from') or req.args.get('created_to'):
            source['post_filter']['bool']['must'].append(_versioncreated_range(req.args))

        internal_req = ParsedRequest()
        internal_req.args = {'source': json.dumps(source)}
        return super().get(internal_req, lookup)
예제 #13
0
    def featured(self, req, lookup, featured):
        """Return featured items.

        :param ParsedRequest req: The parsed in request instance from the endpoint
        :param dict lookup: The parsed in lookup dictionary from the endpoint
        :param dict featured: list featured items
        """

        user = get_user()
        company = get_user_company(user)
        if is_events_only_access(user, company):
            abort(403)

        if not featured or not featured.get('items'):
            return ListCursor([])

        query = _agenda_query()
        get_resource_service('section_filters').apply_section_filter(query, self.section)
        planning_items_query = nested_query(
            'planning_items',
            {
                'bool': {'must': [{'terms': {'planning_items.guid': featured['items']}}]}
            },
            name='featured'
        )
        if req.args.get('q'):
            query['bool']['must'].append(query_string(req.args['q']))
            planning_items_query['nested']['query']['bool']['must'].append(planning_items_query_string(req.args['q']))

        query['bool']['must'].append(planning_items_query)

        source = {'query': query}
        set_post_filter(source, req)
        source['size'] = len(featured['items'])
        source['from'] = req.args.get('from', 0, type=int)
        if not source['from']:
            source['aggs'] = aggregations

        if company and not is_admin(user) and company.get('events_only', False):
            # no adhoc planning items and remove planning items and coverages fields
            query['bool']['must'].append({'exists': {'field': 'event'}})
            _remove_fields(source, PLANNING_ITEMS_FIELDS)

        internal_req = ParsedRequest()
        internal_req.args = {'source': json.dumps(source)}
        cursor = self.internal_get(internal_req, lookup)

        docs_by_id = {}
        for doc in cursor.docs:
            for p in (doc.get('planning_items') or []):
                docs_by_id[p.get('guid')] = doc

            # make the items display on the featured day,
            # it's used in ui instead of dates.start and dates.end
            doc.update({
                '_display_from': featured['display_from'],
                '_display_to': featured['display_to'],
            })

        docs = []
        agenda_ids = set()
        for _id in featured['items']:
            if docs_by_id.get(_id) and docs_by_id.get(_id).get('_id') not in agenda_ids:
                docs.append(docs_by_id.get(_id))
                agenda_ids.add(docs_by_id.get(_id).get('_id'))

        cursor.docs = docs
        return cursor
예제 #14
0
파일: agenda.py 프로젝트: mdhaman/newsroom
    def get(self, req, lookup):
        if req.args.get('featured'):
            return self.get_featured_stories(req, lookup)

        query = _agenda_query()
        user = get_user()
        company = get_user_company(user)
        is_events_only = is_events_only_access(user, company) or req.args.get('eventsOnlyView')
        get_resource_service('section_filters').apply_section_filter(query, self.section)
        product_query = {'bool': {'must': [], 'should': []}}

        set_product_query(
            product_query,
            company,
            self.section,
            navigation_id=req.args.get('navigation'),
            events_only=is_events_only
        )
        query['bool']['must'].append(product_query)

        if req.args.get('q'):
            test_query = {'or': []}
            try:
                q = json.loads(req.args.get('q'))
                if isinstance(q, dict):
                    # used for product testing
                    if q.get('query'):
                        test_query['or'].append(query_string(q.get('query')))
                    if q.get('planning_item_query'):
                        test_query['or'].append(
                            nested_query(
                                'planning_items',
                                planning_items_query_string(q.get('planning_item_query')),
                                name='product_test'
                            )
                        )
                    if test_query['or']:
                        query['bool']['must'].append(test_query)
            except Exception:
                pass

            if not test_query.get('or'):
                query['bool']['must'].append(get_agenda_query(req.args['q'], is_events_only))

        if req.args.get('id'):
            query['bool']['must'].append({'term': {'_id': req.args['id']}})

        if req.args.get('bookmarks'):
            set_saved_items_query(query, req.args['bookmarks'])

        if req.args.get('date_from') or req.args.get('date_to'):
            query['bool']['should'].extend(_event_date_range(req.args))
            if not is_events_only:
                query['bool']['should'].append(_display_date_range(req.args))

        source = {'query': query}
        source['sort'] = [{'dates.start': 'asc'}]
        source['size'] = 100  # we should fetch all items for given date
        source['from'] = req.args.get('from', 0, type=int)

        set_post_filter(source, req, is_events_only)

        if source['from'] >= 1000:
            # https://www.elastic.co/guide/en/elasticsearch/guide/current/pagination.html#pagination
            return abort(400)

        if not source['from'] and not req.args.get('bookmarks'):  # avoid aggregations when handling pagination
            source['aggs'] = get_agenda_aggregations(is_events_only)

        if not is_admin_or_internal(user):
            _remove_fields(source, PRIVATE_FIELDS)

        if is_events_only:
            # no adhoc planning items and remove planning items and coverages fields
            query['bool']['must'].append({'exists': {'field': 'event_id'}})
            _remove_fields(source, PLANNING_ITEMS_FIELDS)

        internal_req = ParsedRequest()
        internal_req.args = {'source': json.dumps(source)}
        cursor = super().get(internal_req, lookup)

        if req.args.get('date_from') and req.args.get('date_to'):
            date_range = _get_date_filters(req.args)
            for doc in cursor.docs:
                # make the items display on the featured day,
                # it's used in ui instead of dates.start and dates.end
                doc.update({
                    '_display_from': date_range.get('gt'),
                    '_display_to': date_range.get('lt'),
                })
        return cursor