Beispiel #1
0
def create():
    data = get_json_or_400()
    if not data.get('name'):
        return jsonify(gettext('Name not found')), 400

    ids = get_resource_service('navigations').post([data])
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #2
0
def watch_coverage():
    user_id = get_user_id()
    data = get_json_or_400()
    assert data.get('item_id')
    assert data.get('coverage_id')
    item = get_entity_or_404(data['item_id'], 'agenda')

    if item.get('watches') and user_id in item['watches']:
        return flask.jsonify({
            'error':
            gettext('Cannot edit coverage watch when watching a parent item.')
        }), 403

    try:
        coverage_index = [
            c['coverage_id'] for c in (item.get('coverages') or [])
        ].index(data['coverage_id'])
    except ValueError:
        return flask.jsonify({'error': gettext('Coverage not found.')}), 404

    updates = {'coverages': item['coverages']}
    if request.method == 'POST':
        updates['coverages'][coverage_index]['watches'] = list(
            set((updates['coverages'][coverage_index].get('watches') or []) +
                [user_id]))
    else:
        try:
            updates['coverages'][coverage_index]['watches'].remove(user_id)
        except Exception:
            return flask.jsonify({'error':
                                  gettext('Error removing watch.')}), 404

    get_resource_service('agenda').patch(data['item_id'], updates)
    return flask.jsonify(), 200
Beispiel #3
0
def update():
    token = flask.request.args.get('token')
    try:
        data = loads(json.dumps(get_json_or_400()))
        return jsonify(get_resource_service(API_TOKENS).patch(token, data)), 200
    except Exception as ex:
        return jsonify({'error': ex}), 500
Beispiel #4
0
def update_topic(id):
    """ Updates a followed topic """
    data = get_json_or_400()
    user_id = session['user']

    if not is_user_topic(id, user_id):
        abort(403)

    # If notifications are enabled, check to see if user is configured to receive emails
    if data.get('notifications'):
        user = get_resource_service('users').find_one(req=None, _id=user_id)
        if not user.get('receive_email'):
            return "", gettext(
                'Please enable \'Receive notifications via email\' option in your profile to receive topic notifications'
            )  # noqa

    updates = {
        'label': data.get('label'),
        'notifications': data.get('notifications', False),
        'query': data.get('query')
    }

    get_resource_service('topics').patch(id=ObjectId(id), updates=updates)
    push_user_notification('topics')
    return jsonify({'success': True}), 200
Beispiel #5
0
def share():
    current_user = get_user(required=True)
    data = get_json_or_400()
    assert data.get('users')
    assert data.get('items')
    topic = get_entity_or_404(data.get('items')['_id'], 'topics')
    for user_id in data['users']:
        user = get_resource_service('users').find_one(req=None, _id=user_id)
        if not user or not user.get('email'):
            continue

        template_kwargs = {
            'recipient': user,
            'sender': current_user,
            'topic': topic,
            'url': get_topic_url(topic),
            'message': data.get('message'),
            'app_name': app.config['SITE_NAME'],
        }
        send_email(
            [user['email']],
            gettext('From %s: %s' % (app.config['SITE_NAME'], topic['label'])),
            render_template('share_topic.txt', **template_kwargs),
        )
    return jsonify(), 201
Beispiel #6
0
def share():
    current_user = get_user(required=True)
    data = get_json_or_400()
    assert data.get('users')
    assert data.get('items')
    topic = get_entity_or_404(data.get('items')[0]['_id'], 'topics')
    with app.mail.connect() as connection:
        for user_id in data['users']:
            user = get_resource_service('users').find_one(req=None, _id=user_id)
            if not user or not user.get('email'):
                continue
            template_kwargs = {
                'recipient': user,
                'sender': current_user,
                'topic': topic,
                'url': '{}/?q={}'.format(app.config['CLIENT_URL'], parse.quote(topic['query'])),
                'message': data.get('message'),
                'app_name': app.config['SITE_NAME'],
            }
            send_email(
                [user['email']],
                gettext('From %s: %s' % (app.config['SITE_NAME'], topic['label'])),
                render_template('share_topic.txt', **template_kwargs),
                sender=current_user['email'],
                connection=connection
            )
    return jsonify(), 201
Beispiel #7
0
def share():
    current_user = get_user(required=True)
    data = get_json_or_400()
    assert data.get('users')
    assert data.get('items')
    items = [get_entity_or_404(_id, 'items') for _id in data.get('items')]
    with app.mail.connect() as connection:
        for user_id in data['users']:
            user = superdesk.get_resource_service('users').find_one(
                req=None, _id=user_id)
            if not user or not user.get('email'):
                continue
            template_kwargs = {
                'recipient': user,
                'sender': current_user,
                'items': items,
                'message': data.get('message'),
            }
            send_email(
                [user['email']],
                gettext('From %s: %s' %
                        (app.config['SITE_NAME'], items[0]['headline'])),
                flask.render_template('share_item.txt', **template_kwargs),
                sender=current_user['email'],
                connection=connection)
    update_action_list(data.get('items'), 'shares')
    return flask.jsonify(), 201
Beispiel #8
0
def remove_wire_items():
    data = get_json_or_400()
    assert data.get('items')

    items_service = get_resource_service('items')
    versions_service = get_resource_service('items_versions')

    ids = []
    for doc in items_service.get_from_mongo(
            req=None, lookup={'_id': {
                '$in': data['items']
            }}):
        ids.append(doc['_id'])
        ids.extend(doc.get('ancestors') or [])

    if not ids:
        flask.abort(404, gettext('Not found'))

    docs = list(doc for doc in items_service.get_from_mongo(
        req=None, lookup={'_id': {
            '$in': ids
        }}))

    for doc in docs:
        items_service.on_delete(doc)

    items_service.delete({'_id': {'$in': ids}})

    for doc in docs:
        items_service.on_deleted(doc)
        versions_service.on_item_deleted(doc)

    push_notification('items_deleted', ids=ids)

    return flask.jsonify(), 200
Beispiel #9
0
def request_coverage():
    user = get_user(required=True)
    data = get_json_or_400()
    assert data.get('item')
    assert data.get('message')
    item = get_entity_or_404(data.get('item'), 'agenda')
    send_coverage_request_email(user, data.get('message'), item['_id'])
    return flask.jsonify(), 201
Beispiel #10
0
def bookmark():
    data = get_json_or_400()
    assert data.get('items')
    update_action_list(data.get('items'), 'bookmarks', item_type='agenda')
    push_user_notification(
        'saved_items',
        count=get_resource_service('agenda').get_saved_items_count())
    return flask.jsonify(), 200
Beispiel #11
0
def create():
    try:
        data = loads(json.dumps(get_json_or_400()))
        new_token = get_resource_service(API_TOKENS).post([data])
        return jsonify({'token': new_token[0]}), 201
    except BadParameterValueError:
        return jsonify({'error': 'Bad request'}), 400
    except Exception as ex:
        return jsonify({'error': ex}), 500
Beispiel #12
0
def create():
    section_filter = get_json_or_400()

    validation = validate_section_filter(section_filter)
    if validation:
        return validation

    ids = get_resource_service('section_filters').post([section_filter])
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #13
0
def update_values():
    values = get_json_or_400()
    get_settings_collection().update_one(GENERAL_SETTINGS_LOOKUP,
                                         {'$set': {
                                             'values': values
                                         }},
                                         upsert=True)
    flask.g.settings = None  # reset cache on update
    return flask.jsonify(values)
Beispiel #14
0
def create():
    company = get_json_or_400()
    errors = get_errors_company(company)
    if errors:
        return errors

    new_company = get_company_updates(company)
    set_original_creator(new_company)
    ids = get_resource_service('companies').post([new_company])
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #15
0
def create():
    data = get_json_or_400()
    if not data.get('label'):
        return jsonify(gettext('Label not found')), 400

    if not data.get('type'):
        return jsonify(gettext('Type not found')), 400

    ids = get_resource_service('cards').post([data])
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #16
0
def post_topic(_id):
    """Creates a user topic"""
    if flask.session['user'] != str(_id):
        flask.abort(403)

    topic = get_json_or_400()
    topic['user'] = ObjectId(_id)

    ids = get_resource_service('topics').post([topic])
    push_user_notification('topic_created')
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #17
0
def create():
    params = get_json_or_400()
    if not params.get('item') or not params.get('action') or not params.get(
            'section'):
        return "", gettext('Activity History: Inavlid request')

    get_resource_service('history').create_history_record([params['item']],
                                                          params['action'],
                                                          get_user(),
                                                          params['section'])
    return jsonify({'success': True}), 201
Beispiel #18
0
def bookmark():
    """Bookmark an item.

    Stores user id into item.bookmarks array.
    Uses mongodb to update the array and then pushes updated array to elastic.
    """
    data = get_json_or_400()
    assert data.get('items')
    update_action_list(data.get('items'), 'bookmarks', item_type='items')
    user_id = get_user_id()
    push_user_notification('saved_items', count=get_bookmarks_count(user_id, 'media_releases'))
    return flask.jsonify(), 200
Beispiel #19
0
def save_navigation_products(id):
    get_entity_or_404(id, 'navigations')
    data = get_json_or_400()
    products = list(query_resource('products', max_results=200))

    db = app.data.get_mongo_collection('products')
    for product in products:
        if str(product['_id']) in data.get('products', []):
            db.update_one({'_id': product['_id']}, {'$addToSet': {'navigations': id}})
        else:
            db.update_one({'_id': product['_id']}, {'$pull': {'navigations': id}})

    return jsonify(), 200
Beispiel #20
0
def share():
    current_user = get_user(required=True)
    item_type = get_type()
    data = get_json_or_400()
    assert data.get('users')
    assert data.get('items')
    items = get_items_for_user_action(data.get('items'), item_type)
    for user_id in data['users']:
        user = superdesk.get_resource_service('users').find_one(req=None,
                                                                _id=user_id)
        subject = items[0].get('headline')

        # If it's an event, 'name' is the subject
        if items[0].get('event'):
            subject = items[0]['name']

        if not user or not user.get('email'):
            continue
        template_kwargs = {
            'recipient': user,
            'sender': current_user,
            'items': items,
            'message': data.get('message'),
            'section': request.args.get('type', 'wire')
        }
        if item_type == 'agenda':
            template_kwargs['maps'] = data.get('maps')
            template_kwargs['dateStrings'] = [
                get_agenda_dates(item) for item in items
            ]
            template_kwargs['locations'] = [
                get_location_string(item) for item in items
            ]
            template_kwargs['contactList'] = [
                get_public_contacts(item) for item in items
            ]
            template_kwargs['linkList'] = [get_links(item) for item in items]
            template_kwargs['is_admin'] = is_admin_or_internal(user)

        send_email(
            [user['email']],
            gettext('From %s: %s' % (app.config['SITE_NAME'], subject)),
            text_body=flask.render_template('share_{}.txt'.format(item_type),
                                            **template_kwargs),
            html_body=flask.render_template('share_{}.html'.format(item_type),
                                            **template_kwargs),
        )
    update_action_list(data.get('items'), 'shares', item_type=item_type)
    get_resource_service('history').create_history_record(
        items, 'share', current_user, request.args.get('type', 'wire'))
    return flask.jsonify(), 201
Beispiel #21
0
def share():
    data = get_json_or_400()
    assert data.get('users')
    assert data.get('items')
    assert data.get('monitoring_profile')
    current_user = get_user(required=True)
    monitoring_profile = get_entity_or_404(data.get('monitoring_profile'),
                                           'monitoring')
    items = get_items_for_monitoring_report(data.get('items'),
                                            monitoring_profile)

    for user_id in data['users']:
        user = get_resource_service('users').find_one(req=None, _id=user_id)
        template_kwargs = {
            'recipient': user,
            'sender': current_user,
            'message': data.get('message'),
            'item_name': 'Monitoring Report',
        }
        formatter = app.download_formatters['monitoring_pdf']['formatter']
        monitoring_profile['format_type'] = 'monitoring_pdf'
        _file = get_monitoring_file(monitoring_profile, items)
        attachment = base64.b64encode(_file.read())

        send_email(
            [user['email']],
            gettext(
                'From %s: %s' % (app.config['SITE_NAME'],
                                 monitoring_profile.get(
                                     'subject', monitoring_profile['name']))),
            text_body=flask.render_template('share_items.txt',
                                            **template_kwargs),
            html_body=flask.render_template('share_items.html',
                                            **template_kwargs),
            attachments_info=[{
                'file':
                attachment,
                'file_name':
                formatter.format_filename(None),
                'content_type':
                'application/{}'.format(formatter.FILE_EXTENSION),
                'file_desc':
                'Monitoring Report'
            }],
        )

    update_action_list(data.get('items'), 'shares')
    get_resource_service('history').create_history_record(
        items, 'share', current_user, 'monitoring')
    return jsonify({'success': True}), 200
Beispiel #22
0
def create():
    product = get_json_or_400()

    validation = validate_product(product)
    if validation:
        return validation

    if product.get('navigations'):
        product['navigations'] = [str(get_entity_or_404(_id, 'navigations')['_id'])
                                  for _id in product.get('navigations').split(',')]

    set_original_creator(product)
    ids = get_resource_service('products').post([product])
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #23
0
def create():
    section_filter = get_json_or_400()

    validation = validate_section_filter(section_filter)
    if validation:
        return validation

    section = next((s for s in current_app.sections
                    if s['_id'] == section_filter.get('filter_type')), None)
    if section and section.get('search_type'):
        section_filter['search_type'] = section['search_type']

    set_original_creator(section_filter)
    ids = get_resource_service('section_filters').post([section_filter])
    return jsonify({'success': True, '_id': ids[0]}), 201
Beispiel #24
0
def edit(id):
    navigation = get_entity_or_404(id, 'navigations')

    if not navigation.get('name'):
        return jsonify(gettext('Name not found')), 400

    data = get_json_or_400()
    updates = {
        'name': data.get('name'),
        'description': data.get('description'),
        'is_enabled': data.get('is_enabled'),
    }

    get_resource_service('navigations').patch(id=ObjectId(id), updates=updates)
    return jsonify({'success': True}), 200
Beispiel #25
0
def edit(id):
    company = find_one('companies', _id=ObjectId(id))

    if not company:
        return NotFound(gettext('Company not found'))

    if flask.request.method == 'POST':
        company = get_json_or_400()
        validate_company(company)
        updates = get_company_updates(company)

        get_resource_service('companies').patch(id=ObjectId(id),
                                                updates=updates)
        return jsonify({'success': True}), 200
    return jsonify(company), 200
Beispiel #26
0
def update_values():
    values = get_json_or_400()

    error = validate_general_settings(values)
    if error:
        return "", error

    updates = {'values': values}
    set_version_creator(updates)
    updates['_updated'] = utcnow()

    get_settings_collection().update_one(GENERAL_SETTINGS_LOOKUP,
                                         {'$set': updates},
                                         upsert=True)
    flask.g.settings = None  # reset cache on update
    return flask.jsonify(updates)
Beispiel #27
0
def update_topic(id):
    """ Updates a followed topic """
    data = get_json_or_400()

    if not is_user_topic(id, session['user']):
        abort(403)

    updates = {
        'label': data.get('label'),
        'notifications': data.get('notifications', False),
        'query': data.get('query')
    }

    get_resource_service('topics').patch(id=ObjectId(id), updates=updates)
    push_user_notification('topics')
    return jsonify({'success': True}), 200
Beispiel #28
0
def edit(id):
    get_entity_or_404(id, 'products')
    data = get_json_or_400()
    updates = {
        'name': data.get('name'),
        'description': data.get('description'),
        'sd_product_id': data.get('sd_product_id'),
        'query': data.get('query'),
        'is_enabled': data.get('is_enabled'),
    }

    validation = validate_product(updates)
    if validation:
        return validation

    get_resource_service('products').patch(id=ObjectId(id), updates=updates)
    return jsonify({'success': True}), 200
Beispiel #29
0
def edit(_id):
    company = find_one('companies', _id=ObjectId(_id))

    if not company:
        return NotFound(gettext('Company not found'))

    if flask.request.method == 'POST':
        company = get_json_or_400()
        errors = get_errors_company(company)
        if errors:
            return errors

        updates = get_company_updates(company)
        set_version_creator(updates)
        get_resource_service('companies').patch(ObjectId(_id), updates=updates)
        app.cache.delete(_id)
        return jsonify({'success': True}), 200
    return jsonify(company), 200
Beispiel #30
0
def edit(id):
    card = get_entity_or_404(id, 'cards')

    if not card.get('label'):
        return jsonify(gettext('Label not found')), 400

    if not card.get('type'):
        return jsonify(gettext('Type not found')), 400

    data = get_json_or_400()
    updates = {
        'label': data.get('label'),
        'type': data.get('type'),
        'config': data.get('config'),
        'order': data.get('order'),
    }

    get_resource_service('cards').patch(id=ObjectId(id), updates=updates)
    return jsonify({'success': True}), 200