Пример #1
0
def set_product_query(query,
                      company,
                      user=None,
                      navigation_id=None,
                      product_type=None):
    """
    Checks the user for admin privileges
    If user is administrator then there's no filtering
    If user is not administrator then products apply if user has a company
    If user is not administrator and has no company then everything will be filtered
    :param query: search query
    :param company: company
    :param user: user to check against (used for notification checking)
    :param navigation_id: navigation to filter products
    :param product_type: product_type to filter products
    If not provided session user will be checked
    """
    products = None

    if product_type and company:
        products = get_products_by_company(company['_id'],
                                           product_type=product_type)
    else:
        if is_admin(user):
            if navigation_id:
                products = get_products_by_navigation(navigation_id)
            else:
                return  # admin will see everything by default

        if company:
            products = get_products_by_company(company['_id'], navigation_id)
        else:
            # user does not belong to a company so blocking all stories
            abort(403, gettext('User does not belong to a company.'))

    query['bool']['should'] = []
    product_ids = [
        p['sd_product_id'] for p in products if p.get('sd_product_id')
    ]
    if product_ids:
        query['bool']['should'].append(
            {'terms': {
                'products.code': product_ids
            }})

    for product in products:
        if product.get('query'):
            if product['query'] == '_featured':
                if navigation_id:  # only return featured when nav item is selected
                    raise FeaturedQuery
            else:
                query['bool']['should'].append(query_string(product['query']))

    query['bool']['minimum_should_match'] = 1

    if not query['bool']['should']:
        abort(403, gettext('Your company doesn\'t have any products defined.'))
Пример #2
0
def get_home_data():
    user = get_user()
    cards = list(query_resource('cards', lookup={'dashboard': 'newsroom'}))
    company_id = str(user['company']) if user and user.get('company') else None
    items_by_card = get_items_by_card(cards)

    return {
        'cards':
        cards,
        'itemsByCard':
        items_by_card,
        'products':
        get_products_by_company(company_id),
        'user':
        str(user['_id']) if user else None,
        'userType':
        user.get('user_type'),
        'company':
        company_id,
        'formats': [{
            'format': f['format'],
            'name': f['name'],
            'types': f['types'],
            'assets': f['assets']
        } for f in app.download_formatters.values()],
        'context':
        'wire',
    }
Пример #3
0
    def prefill_search_products(self, search):
        """ Prefill the search products

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

        if search.args.get('requested_products'):
            products = search.args['requested_products']
            if isinstance(products, list):
                search.requested_products = products
            elif getattr(products, 'split', None):
                search.requested_products = list(products.split(','))
            else:
                raise BadParameterValueError(
                    'Invalid requested_products parameter')

        if search.is_admin:
            if len(search.navigation_ids):
                search.products = get_products_by_navigation(
                    search.navigation_ids, product_type=search.section)
            else:
                # admin will see everything by default,
                # regardless of company products
                search.products = []
        elif search.company:
            search.products = get_products_by_company(
                search.company.get('_id'),
                search.navigation_ids,
                product_type=search.section)
        else:
            search.products = []
Пример #4
0
def check_association_permission(item):
    """
    Check if any of the products that the passed image item matches are permissioned superdesk products for the
     company
    :param item:
    :return:
    """
    if not app.config.get('NEWS_API_IMAGE_PERMISSIONS_ENABLED'):
        return True

    if ((item.get('associations') or {}).get('featuremedia')
            or {}).get('products'):
        # Extract the products that the image matched in Superdesk
        im_products = [
            p.get('code')
            for p in ((item.get('associations') or {}).get('featuremedia')
                      or {}).get('products')
        ]

        # Check if the one of the companies products that has a superdesk product id matches one of the
        # image product id's
        sd_products = [
            p.get('sd_product_id')
            for p in get_products_by_company(g.user, None, 'news_api')
            if p.get('sd_product_id')
        ]

        return True if len(set(im_products) & set(sd_products)) else False
    else:
        return True
Пример #5
0
def get_navigations_by_company(company_id, product_type='wire'):
    """
    Returns list of navigations for given company id
    Navigations will contain the list of product ids
    """
    products = get_products_by_company(company_id, None, product_type)

    # Get the navigation ids used across products
    navigation_ids = []

    if current_app.config.get(
            'AGENDA_FEATURED_STORY_NAVIGATION_POSITION_OVERRIDE'
    ) and product_type == 'agenda':
        navigations = []
        featured_navigation_ids = []

        # fetch navigations for featured products
        [
            featured_navigation_ids.extend(p.get('navigations', []))
            for p in products if p.get('query') == '_featured'
        ]
        navigations.extend(get_navigations_by_ids(featured_navigation_ids))

        # fetch all other navigations
        [
            navigation_ids.extend(p.get('navigations', [])) for p in products
            if p.get('query') != '_featured'
        ]
        navigations.extend(get_navigations_by_ids(navigation_ids))

        return navigations
    else:
        [navigation_ids.extend(p.get('navigations', [])) for p in products]
        return get_navigations_by_ids(navigation_ids)
Пример #6
0
def get_home_data():
    cards = list(superdesk.get_resource_service('cards').get(None, None))
    user = get_user()
    company_id = str(user['company']) if user and user.get('company') else None

    itemsByCard = {}
    for card in cards:
        itemsByCard[card['label']] = superdesk.get_resource_service('wire_search').\
            get_product_items(ObjectId(card['config']['product']), card['config']['size'])

    return {
        'cards':
        cards,
        'itemsByCard':
        itemsByCard,
        'products':
        get_products_by_company(company_id),
        'user':
        str(user['_id']) if user else None,
        'company':
        company_id,
        'formats': [{
            'format': f['format'],
            'name': f['name']
        } for f in app.download_formatters.values()],
    }
Пример #7
0
def get_navigations_by_company(company_id,
                               product_type='wire',
                               events_only=False):
    """
    Returns list of navigations for given company id
    Navigations will contain the list of product ids
    """
    products = get_products_by_company(company_id, None, product_type)

    # Get the navigation ids used across products
    navigation_ids = []
    [navigation_ids.extend(p.get('navigations', [])) for p in products]
    return get_navigations_by_ids(navigation_ids)
Пример #8
0
    def prefill_search_products(self, search):
        """ Prefill the search products

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

        if search.company:
            search.products = get_products_by_company(
                search.company.get('_id'),
                search.navigation_ids,
                product_type=search.section)
        else:
            search.products = []
Пример #9
0
def set_product_query(query, company):
    if company:
        products = get_products_by_company(company['_id'])
        product_ids = [
            p['sd_product_id'] for p in products if p.get('sd_product_id')
        ]
        query['bool']['must'].append(
            {'bool': {
                'should': [{
                    'terms': {
                        'products.id': product_ids
                    }
                }]
            }})

        for product in products:
            if product.get('query'):
                query['bool']['must'][0]['bool']['should'].append(
                    _query_string(product['query']))
Пример #10
0
def get_view_data():
    user = get_user()
    topics = get_user_topics(user['_id']) if user else []
    company_id = str(user['company']) if user and user.get('company') else None

    return {
        'user': str(user['_id']) if user else None,
        'user_type': (user or {}).get('user_type') or 'public',
        'company': company_id,
        'topics': [t for t in topics if t.get('topic_type') == 'wire'],
        'formats': [{'format': f['format'], 'name': f['name'], 'assets': f['assets']}
                    for f in app.download_formatters.values()
                    if 'wire' in f['types']],
        'navigations': get_navigations_by_company(company_id, product_type='wire'),
        'products': get_products_by_company(company_id),
        'saved_items': get_bookmarks_count(user['_id'], 'wire'),
        'context': 'wire',
        'ui_config': get_resource_service('ui_config').getSectionConfig('wire'),
        'groups': app.config.get('WIRE_GROUPS', []),
    }
Пример #11
0
    def prefill_search_products(self, search):
        """ Prefill the search products

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

        if search.args.get('products'):
            search.products = list(get_resource_service('products').get(req=None, lookup={
                'is_enabled': True,
                'companies': str(search.company['_id']),
                '_id': {
                    '$in': [
                        ObjectId(pid)
                        for pid in search.args['products'].split(',')
                    ]
                }
            }))
        else:
            search.products = get_products_by_company(
                search.company.get('_id'),
                product_type=search.section
            )
Пример #12
0
def get_home_data():
    user = get_user()
    cards = list(superdesk.get_resource_service('cards').get(None, None))
    company_id = str(user['company']) if user and user.get('company') else None
    items_by_card = get_items_by_card(cards)

    return {
        'photos':
        get_photos(),
        'cards':
        cards,
        'itemsByCard':
        items_by_card,
        'products':
        get_products_by_company(company_id),
        'user':
        str(user['_id']) if user else None,
        'company':
        company_id,
        'formats': [{
            'format': f['format'],
            'name': f['name']
        } for f in app.download_formatters.values()],
    }
Пример #13
0
def set_product_query(query,
                      company,
                      section,
                      user=None,
                      navigation_id=None,
                      events_only=False):
    """
    Checks the user for admin privileges
    If user is administrator then there's no filtering
    If user is not administrator then products apply if user has a company
    If user is not administrator and has no company then everything will be filtered
    :param query: search query
    :param company: company
    :param section: section i.e. wire, agenda, marketplace etc
    :param user: user to check against (used for notification checking)
    :param navigation_id: navigation to filter products
    :param events_only: From agenda to display events only or not
    If not provided session user will be checked
    """
    products = None

    if is_admin(user):
        if navigation_id:
            products = get_products_by_navigation(navigation_id)
        else:
            return  # admin will see everything by default

    if company:
        products = get_products_by_company(company['_id'],
                                           navigation_id,
                                           product_type=section)
    else:
        # user does not belong to a company so blocking all stories
        abort(403, gettext('User does not belong to a company.'))

    query['bool']['should'] = []
    product_ids = [
        p['sd_product_id'] for p in products if p.get('sd_product_id')
    ]
    if product_ids:
        query['bool']['should'].append(
            {'terms': {
                'products.code': product_ids
            }})

    # add company type filters (if any)
    if company and company.get('company_type'):
        for company_type in app.config.get('COMPANY_TYPES', []):
            if company_type['id'] == company['company_type']:
                if company_type.get('wire_must'):
                    query['bool']['must'].append(company_type['wire_must'])
                if company_type.get('wire_must_not'):
                    query['bool']['must_not'].append(
                        company_type['wire_must_not'])

    planning_items_should = []
    for product in products:
        if product.get('query'):
            query['bool']['should'].append(query_string(product['query']))
            if product.get('planning_item_query') and not events_only:
                # form the query for the agenda planning items
                planning_items_should.append(
                    planning_items_query_string(
                        product.get('planning_item_query')))

    if planning_items_should:
        query['bool']['should'].append(
            nested_query('planning_items', {
                'bool': {
                    'should': planning_items_should,
                    'minimum_should_match': 1
                }
            },
                         name='products'))

    query['bool']['minimum_should_match'] = 1

    wire_time_limit_days = get_setting('wire_time_limit_days')
    if company and not is_admin(user) and not company.get(
            'archive_access', False) and wire_time_limit_days:
        query['bool']['must'].append({
            'range': {
                'versioncreated': {
                    'gte': 'now-%dd/d' % int(wire_time_limit_days),
                }
            }
        })

    if not query['bool']['should']:
        abort(403, gettext('Your company doesn\'t have any products defined.'))
Пример #14
0
    def get(self, req, lookup):
        query = _items_query()
        user = get_user()
        company = get_user_company(user)
        set_product_query(query, company)

        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'])

        if req.args.get('navigation'):
            if company:
                products = get_products_by_company(company['_id'])
                navigation_id = req.args['navigation']
                selected_products = []

                for product in products:
                    if navigation_id in product.get('navigations', []):
                        if product and product.get('query'):
                            query['bool']['must'].append(
                                _query_string(product.get('query')))
                        if product and product.get('sd_product_id'):
                            selected_products.append(
                                product.get('sd_product_id'))

                if selected_products:
                    query['bool']['must'].append(
                        {'terms': {
                            'products.id': selected_products
                        }})

        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)