def brief_internal_routing(item: dict, **kwargs):
    guid = item.get('guid', 'unknown')
    logger.info('macro started item=%s', guid)

    try:
        assert str(item['profile']) == str(
            _get_profile_id(TEXT_PROFILE)), 'profile is not text'
        assert get_word_count(item['body_html']) < 301, 'body is too long'
    except AssertionError as err:
        logger.info('macro stop on assert item=%s error=%s', guid, err)
        raise StopDuplication()
    except KeyError as err:
        logger.error(err)
        raise StopDuplication()

    item.setdefault('subject', [])
    item['urgency'] = 2
    item['profile'] = _get_profile_id(BRIEF_PROFILE)
    item['subject'] = _get_product_subject(
        _get_brief_subject(item.get('subject')))
    item['status'] = CONTENT_STATE.SCHEDULED
    item['operation'] = 'publish'

    _fix_headline(item)
    _fix_body_html(item)

    # schedule +30m
    UTC_FIELD = 'utc_{}'.format(PUBLISH_SCHEDULE)
    try:
        published_at = item[SCHEDULE_SETTINGS][UTC_FIELD]
    except KeyError:
        published_at = utcnow()
    item[SCHEDULE_SETTINGS] = {
        'time_zone': 'Europe/Brussels',
    }
    item[PUBLISH_SCHEDULE] = utc_to_local(item[SCHEDULE_SETTINGS]['time_zone'],
                                          published_at + timedelta(minutes=30))
    update_schedule_settings(item, PUBLISH_SCHEDULE, item[PUBLISH_SCHEDULE])
    item[PUBLISH_SCHEDULE] = item[PUBLISH_SCHEDULE].replace(tzinfo=None)

    # publish
    try:
        internal_destination_auto_publish(item)
    except StopDuplication:
        logger.info('macro done item=%s', guid)
    except DocumentError as err:
        logger.error('validation error when creating brief item=%s error=%s',
                     guid, err)
    except Exception as err:
        logger.exception(err)

    # avoid another item to be created
    raise StopDuplication()
Esempio n. 2
0
def broadcast_auto_publish(item, **kwargs):
    """Broadcast auto publish macro.

    :param item:
    :param kwargs:
    :return:
    """
    if item.get(ITEM_TYPE) != CONTENT_TYPE.TEXT or item.get(
            FORMAT) != FORMATS.HTML:
        return

    formatter = AAPBulletinBuilderFormatter()
    body_text = formatter.get_text_content(formatter.append_body_footer(item))
    word_count = get_text_word_count(body_text)
    max_word_count = config.MIN_BROADCAST_TEXT_WORD_COUNT
    item['genre'] = [{'name': 'Broadcast Script', 'qcode': 'Broadcast Script'}]
    if item[ITEM_STATE] not in {CONTENT_STATE.KILLED, CONTENT_STATE.RECALLED} and \
            not (item.get('flags') or {}).get('marked_for_legal'):
        if word_count > max_word_count and \
                not (item.get('flags') or {}).get('marked_for_legal'):
            lines = body_text.splitlines()
            new_body_html = []
            for line in lines:
                para = line.strip()
                if not para:
                    continue

                new_body_html.append('<p>{}</p>'.format(para))
                word_count = get_text_word_count(''.join(new_body_html))
                if word_count > max_word_count:
                    if len(new_body_html):
                        item['body_html'] = ''.join(new_body_html)
                        item['word_count'] = word_count
                    break
    elif item[ITEM_STATE] in {CONTENT_STATE.KILLED, CONTENT_STATE.RECALLED}:
        lines = body_text.splitlines()
        lines = [
            '<p>{}</p>'.format(line.strip()) for line in lines if line.strip()
        ]
        # remove the first line/paragraph of kill message
        lines = lines[1:]
        item['body_html'] = ''.join(lines)
        fields_to_remove = ['embargo', 'dateline', 'slugline', 'genre']
        for field in fields_to_remove:
            item.pop(field, None)

    internal_destination_auto_publish(item, **kwargs)
def broadcast_auto_publish(item, **kwargs):
    """Broadcast auto publish macro.

    :param item:
    :param kwargs:
    :return:
    """
    if item.get(ITEM_TYPE) != CONTENT_TYPE.TEXT or item.get(FORMAT) != FORMATS.HTML:
        return

    formatter = AAPBulletinBuilderFormatter()
    body_text = formatter.get_text_content(formatter.append_body_footer(item))
    word_count = get_text_word_count(body_text)
    max_word_count = config.MIN_BROADCAST_TEXT_WORD_COUNT
    item['genre'] = [{'name': 'Broadcast Script', 'qcode': 'Broadcast Script'}]
    if item[ITEM_STATE] not in {CONTENT_STATE.KILLED, CONTENT_STATE.RECALLED} and \
            not (item.get('flags') or {}).get('marked_for_legal'):
        if word_count > max_word_count and \
                not (item.get('flags') or {}).get('marked_for_legal'):
            lines = body_text.splitlines()
            new_body_html = []
            for line in lines:
                para = line.strip()
                if not para:
                    continue

                new_body_html.append('<p>{}</p>'.format(para))
                word_count = get_text_word_count(''.join(new_body_html))
                if word_count > max_word_count:
                    if len(new_body_html):
                        item['body_html'] = ''.join(new_body_html)
                        item['word_count'] = word_count
                    break
    elif item[ITEM_STATE] in {CONTENT_STATE.KILLED, CONTENT_STATE.RECALLED}:
        lines = body_text.splitlines()
        lines = ['<p>{}</p>'.format(line.strip()) for line in lines if line.strip()]
        # remove the first line/paragraph of kill message
        lines = lines[1:]
        item['body_html'] = ''.join(lines)
        fields_to_remove = ['embargo', 'dateline', 'slugline', 'genre']
        for field in fields_to_remove:
            item.pop(field, None)

    internal_destination_auto_publish(item, **kwargs)
def broadcast_auto_publish(item, **kwargs):
    """Broadcast auto publish macro.

    :param item:
    :param kwargs:
    :return:
    """
    if item.get(ITEM_TYPE) != CONTENT_TYPE.TEXT or item.get(
            FORMAT) != FORMATS.HTML:
        return

    max_word_count = config.MIN_BROADCAST_TEXT_WORD_COUNT
    item['genre'] = [{'name': 'Broadcast Script', 'qcode': 'Broadcast Script'}]
    if item[ITEM_STATE] not in {CONTENT_STATE.KILLED, CONTENT_STATE.RECALLED} and \
            not (item.get('flags') or {}).get('marked_for_legal'):
        formatter = AAPBulletinBuilderFormatter()
        body_text = formatter.get_text_content(
            formatter.append_body_footer(item))
        word_count = get_text_word_count(body_text)
        if word_count > max_word_count and \
                not (item.get('flags') or {}).get('marked_for_legal'):
            lines = body_text.splitlines()
            new_body_html = []
            for line in lines:
                para = line.strip()
                if not para:
                    continue

                new_body_html.append('<p>{}</p>'.format(para))
                word_count = get_text_word_count(''.join(new_body_html))
                if word_count > max_word_count:
                    if len(new_body_html):
                        item['body_html'] = ''.join(new_body_html)
                        item['word_count'] = word_count
                    break

    internal_destination_auto_publish(item, **kwargs)
def brief_internal_routing(item: dict, **kwargs):
    guid = item.get('guid', 'unknown')
    logger.info('macro started item=%s', guid)

    try:
        assert str(item['profile']) == str(
            _get_profile_id(TEXT_PROFILE)), 'profile is not text'
        assert get_word_count(item['body_html']) < 301, 'body is too long'
    except AssertionError as err:
        logger.info('macro stop on assert item=%s error=%s', guid, err)
        raise StopDuplication()
    except KeyError as err:
        logger.error(err)
        raise StopDuplication()

    item.setdefault('subject', [])
    item['urgency'] = 2
    item['profile'] = _get_profile_id(BRIEF_PROFILE)
    item['subject'] = _get_product_subject(
        _get_brief_subject(item.get('subject', [])))
    item['status'] = CONTENT_STATE.SCHEDULED
    item['operation'] = 'publish'

    _fix_headline(item)
    _fix_body_html(item)

    UTC_FIELD = 'utc_{}'.format(PUBLISH_SCHEDULE)
    try:
        published_at = item[SCHEDULE_SETTINGS][UTC_FIELD]
    except KeyError:
        published_at = utcnow()
    item[SCHEDULE_SETTINGS] = {
        'time_zone': 'Europe/Brussels',
    }

    # Set item publish schedule to 7:30 am for autopublish between 4 to 7 am
    is_press_headline = item.get(
        'headline') and 'press' in item['headline'].lower()
    current_datetime = utc_to_local(superdesk.app.config['DEFAULT_TIMEZONE'],
                                    utcnow())
    if is_press_headline and time(4, 00) <= current_datetime.time() <= time(
            7, 00):
        item[PUBLISH_SCHEDULE] = current_datetime.replace(hour=7,
                                                          minute=30,
                                                          second=00)
        logger.info(
            'Set publish schedule to 7:30 am for autopublish between 4 to 7 am item=%s',
            item.get('guid', 'unknown'))
    else:
        # schedule +30m
        item[PUBLISH_SCHEDULE] = utc_to_local(
            item[SCHEDULE_SETTINGS]['time_zone'],
            published_at + timedelta(minutes=30))

    update_schedule_settings(item, PUBLISH_SCHEDULE, item[PUBLISH_SCHEDULE])
    item[PUBLISH_SCHEDULE] = item[PUBLISH_SCHEDULE].replace(tzinfo=None)

    # remove text in () brackets along with brackets
    if item.get("headline"):
        title = re.sub(r"\([^()]*\)", "", item['headline'])
        item['headline'] = " ".join(title.split())

    # publish
    try:
        internal_destination_auto_publish(item)
    except StopDuplication:
        logger.info('macro done item=%s', guid)
    except DocumentError as err:
        logger.error('validation error when creating brief item=%s error=%s',
                     guid, err)
    except Exception as err:
        logger.exception(err)

    # avoid another item to be created
    raise StopDuplication()