Example #1
0
    def on_broadcast_master_updated(self, item_event, item,
                                    takes_package_id=None, rewrite_id=None):
        """Runs when master item is updated.

        This event is called when the master story is corrected, published, re-written, new take/re-opened

        :param str item_event: Item operations
        :param dict item: item on which operation performed.
        :param str takes_package_id: takes_package_id.
        :param str rewrite_id: re-written story id.
        """
        status = ''

        if not item or is_genre(item, BROADCAST_GENRE):
            return

        if item_event == ITEM_CREATE and takes_package_id:
            if RE_OPENS.lower() in str(item.get('anpa_take_key', '')).lower():
                status = 'Story Re-opened'
            else:
                status = 'New Take Created'

        elif item_event == ITEM_CREATE and rewrite_id:
            status = 'Master Story Re-written'
        elif item_event == ITEM_PUBLISH:
            status = 'Master Story Published'
        elif item_event == ITEM_CORRECT:
            status = 'Master Story Corrected'

        broadcast_items = self.get_broadcast_items_from_master_story(item)

        if not broadcast_items:
            return

        processed_ids = set()
        for broadcast_item in broadcast_items:
            try:
                if broadcast_item.get('lock_user'):
                    continue

                updates = {
                    'broadcast': broadcast_item.get('broadcast'),
                }

                if status:
                    updates['broadcast']['status'] = status

                if not updates['broadcast']['takes_package_id'] and takes_package_id:
                    updates['broadcast']['takes_package_id'] = takes_package_id

                if not updates['broadcast']['rewrite_id'] and rewrite_id:
                    updates['broadcast']['rewrite_id'] = rewrite_id

                if not broadcast_item.get(config.ID_FIELD) in processed_ids:
                    self._update_broadcast_status(broadcast_item, updates)
                    # list of ids that are processed.
                    processed_ids.add(broadcast_item.get(config.ID_FIELD))
            except:
                logger.exception('Failed to update status for the broadcast item {}'.
                                 format(broadcast_item.get(config.ID_FIELD)))
    def __copy_metadata__(self, target, to, package, set_state=False):
        # if target is the first take hence default sequence is for first take.
        sequence = package.get(SEQUENCE, 1) if package else 1
        sequence = self.__next_sequence__(sequence)
        take_key = self.__strip_take_info__(target.get('anpa_take_key') or '')
        to['event_id'] = target.get('event_id')
        to['anpa_take_key'] = '{}={}'.format(take_key, sequence)
        if target.get(ITEM_STATE) in PUBLISH_STATES and not RE_OPENS.lower(
        ) in take_key.lower():
            to['anpa_take_key'] = '{} ({})={}'.format(take_key, RE_OPENS,
                                                      sequence).strip()

        if set_state:
            to[config.VERSION] = 1
            to[ITEM_STATE] = CONTENT_STATE.PROGRESS if to.get('task', {}).get(
                'desk', None) else CONTENT_STATE.DRAFT

        copy_from = package if (package.get(ITEM_STATE)
                                in PUBLISH_STATES) else target
        fields = self.fields_for_creating_take.copy()

        if copy_from.get(ITEM_STATE) == CONTENT_STATE.CORRECTED:
            fields = [
                f for f in fields
                if f not in self.excluded_fields_after_correction
            ]

        for field in fields:
            if field in copy_from:
                to[field] = copy_from.get(field)

        # if the original was flagged for SMS the new take should not be.
        if to.get('flags', {}).get('marked_for_sms', False):
            to['flags']['marked_for_sms'] = False
    def __copy_metadata__(self, target, to, package, set_state=False):
        # if target is the first take hence default sequence is for first take.
        sequence = package.get(SEQUENCE, 1) if package else 1
        sequence = self.__next_sequence__(sequence)
        take_key = self.__strip_take_info__(target.get('anpa_take_key') or '')
        to['event_id'] = target.get('event_id')
        to['anpa_take_key'] = '{}={}'.format(take_key, sequence)
        if target.get(ITEM_STATE) in PUBLISH_STATES and not RE_OPENS.lower() in take_key.lower():
            to['anpa_take_key'] = '{} ({})={}'.format(take_key, RE_OPENS, sequence).strip()

        if set_state:
            to[config.VERSION] = 1
            to[ITEM_STATE] = CONTENT_STATE.PROGRESS if to.get('task', {}).get('desk', None) else CONTENT_STATE.DRAFT

        copy_from = package if (package.get(ITEM_STATE) in PUBLISH_STATES) else target
        fields = self.fields_for_creating_take.copy()

        if copy_from.get(ITEM_STATE) == CONTENT_STATE.CORRECTED:
            fields = [f for f in fields if f not in self.excluded_fields_after_correction]

        for field in fields:
            if field in copy_from:
                to[field] = copy_from.get(field)

        # if the original was flagged for SMS the new take should not be.
        if to.get('flags', {}).get('marked_for_sms', False):
            to['flags']['marked_for_sms'] = False
    def link_as_next_take(self, target, link):
        """Makes next take to target from given link.

        Check if target has an associated takes package. If not, create it and add target as a take.
        Check if the target is the last take, if not, resolve the last take. Copy metadata from the target and add it
        as the next take and return the update link item

        :return: the updated link item
        """

        takes_package_id = self.get_take_package_id(target)
        archive_service = get_resource_service(ARCHIVE)
        takes_package = archive_service.find_one(
            req=None, _id=takes_package_id) if takes_package_id else {}

        if not takes_package:
            # setting the sequence to 1 for target.
            updates = {SEQUENCE: 1}
            if target[ITEM_STATE] in [
                    CONTENT_STATE.SPIKED, CONTENT_STATE.KILLED,
                    CONTENT_STATE.SCHEDULED, CONTENT_STATE.INGESTED
            ]:
                raise SuperdeskApiError.forbiddenError(
                    "Item isn't in a valid state for creating takes.")
            else:
                archive_service.system_update(target.get(config.ID_FIELD),
                                              updates, target)

        link_updates = {}

        if not link.get(config.ID_FIELD):
            # A new story to be linked
            self.__copy_metadata__(target, link, takes_package, set_state=True)
            link[ITEM_OPERATION] = ITEM_CREATE
            archive_service.post([link])
        else:
            self.__copy_metadata__(target,
                                   link_updates,
                                   takes_package,
                                   set_state=False)

        link.update(link_updates)

        if not takes_package_id:
            takes_package_id = self.package_story_as_a_take(
                target, takes_package, link)
        else:
            original_takes_package = deepcopy(takes_package)
            self.__link_items__(takes_package, target, link)
            del takes_package[config.ID_FIELD]
            takes_package.pop('unique_id', None)
            takes_package.pop('unique_name', None)
            takes_package.pop(PUBLISH_SCHEDULE, None)
            takes_package.pop(SCHEDULE_SETTINGS, None)

            resolve_document_version(takes_package, ARCHIVE, 'PATCH',
                                     takes_package)
            archive_service.patch(takes_package_id, takes_package)
            app.on_archive_item_updated(link_updates, original_takes_package,
                                        ITEM_LINK)
            get_resource_service(
                'archive_broadcast').on_broadcast_master_updated(
                    ITEM_CREATE, target, takes_package_id=takes_package_id)

        if link.get(SEQUENCE):
            link_updates.update({SEQUENCE: link[SEQUENCE]})
            archive_service.system_update(link[config.ID_FIELD], link_updates,
                                          link)
            app.on_archive_item_updated({'linked_to': target[config.ID_FIELD]},
                                        link, ITEM_LINK)

        insert_into_versions(id_=takes_package_id)

        if RE_OPENS.lower() in link.get('anpa_take_key', '').lower():
            app.on_archive_item_updated({'new_take_id': link[config.ID_FIELD]},
                                        target, ITEM_REOPEN)
        else:
            app.on_archive_item_updated({'new_take_id': link[config.ID_FIELD]},
                                        target, ITEM_TAKE)

        return link