def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        original_id = request.view_args['original_id']
        update_document = doc.get('update')

        archive_service = get_resource_service(ARCHIVE)
        original = archive_service.find_one(req=None, _id=original_id)
        self._validate_rewrite(original, update_document)

        digital = TakesPackageService().get_take_package(original)
        rewrite = self._create_rewrite_article(original, digital,
                                               existing_item=update_document,
                                               desk_id=doc.get('desk_id'))

        if update_document:
            # process the existing story
            archive_service.patch(update_document[config.ID_FIELD], rewrite)
            rewrite[config.ID_FIELD] = update_document[config.ID_FIELD]
            ids = [update_document[config.ID_FIELD]]
        else:
            ids = archive_service.post([rewrite])
            build_custom_hateoas(CUSTOM_HATEOAS, rewrite)

        self._add_rewritten_flag(original, digital, rewrite)
        get_resource_service('archive_broadcast').on_broadcast_master_updated(ITEM_CREATE,
                                                                              item=original,
                                                                              rewrite_id=ids[0])
        return [rewrite]
Esempio n. 2
0
 def create(self, docs, **kwargs):
     user = get_user(required=True)
     auth = get_auth()
     item_id = request.view_args['item_id']
     item = get_component(ItemHold).hold({'_id': item_id}, user['_id'], auth['_id'])
     build_custom_hateoas(custom_hateoas, item)
     return [item['_id']]
Esempio n. 3
0
    def create(self, docs, **kwargs):
        target_id = request.view_args['target_id']
        doc = docs[0]
        link_id = doc.get('link_id')
        desk_id = doc.get('desk')
        service = get_resource_service(ARCHIVE)
        target = service.find_one(req=None, _id=target_id)
        self._validate_link(target, target_id)
        link = {}

        if is_genre(target, BROADCAST_GENRE):
            raise SuperdeskApiError.badRequestError("Cannot add new take to the story with genre as broadcast.")

        if desk_id:
            link = {'task': {'desk': desk_id}}
            user = get_user()
            lookup = {'_id': desk_id, 'members.user': user['_id']}
            desk = get_resource_service('desks').find_one(req=None, **lookup)
            if not desk:
                raise SuperdeskApiError.forbiddenError("No privileges to create new take on requested desk.")

            link['task']['stage'] = desk['working_stage']

        if link_id:
            link = service.find_one(req=None, _id=link_id)

        linked_item = self.packageService.link_as_next_take(target, link)
        doc.update(linked_item)
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [linked_item['_id']]
Esempio n. 4
0
    def create(self, docs, **kwargs):
        target_id = request.view_args['target_id']
        doc = docs[0]
        link_id = doc.get('link_id')
        desk_id = doc.get('desk')
        service = get_resource_service(ARCHIVE)
        target = service.find_one(req=None, _id=target_id)
        self._validate_link(target, target_id)
        link = {}

        if desk_id:
            link = {'task': {'desk': desk_id}}
            user = get_user()
            lookup = {'_id': desk_id, 'members.user': user['_id']}
            desk = get_resource_service('desks').find_one(req=None, **lookup)
            if not desk:
                raise SuperdeskApiError.forbiddenError("No privileges to create new take on requested desk.")

            link['task']['stage'] = desk['working_stage']

        if link_id:
            link = service.find_one(req=None, _id=link_id)

        linked_item = self.packageService.link_as_next_take(target, link)
        insert_into_versions(id_=linked_item[config.ID_FIELD])
        doc.update(linked_item)
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [linked_item['_id']]
Esempio n. 5
0
    def create(self, docs, **kwargs):
        target_id = request.view_args['target_id']
        doc = docs[0]
        link_id = doc.get('link_id')
        desk_id = doc.get('desk')
        service = get_resource_service(ARCHIVE)
        target = service.find_one(req=None, _id=target_id)
        self._validate_link(target, target_id)
        link = {}

        if is_genre(target, BROADCAST_GENRE):
            raise SuperdeskApiError.badRequestError(
                "Cannot add new take to the story with genre as broadcast.")

        if desk_id:
            link = {'task': {'desk': desk_id}}
            user = get_user()
            lookup = {'_id': desk_id, 'members.user': user['_id']}
            desk = get_resource_service('desks').find_one(req=None, **lookup)
            if not desk:
                raise SuperdeskApiError.forbiddenError(
                    "No privileges to create new take on requested desk.")

            link['task']['stage'] = desk['working_stage']

        if link_id:
            link = service.find_one(req=None, _id=link_id)

        linked_item = self.packageService.link_as_next_take(target, link)
        doc.update(linked_item)
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [linked_item['_id']]
Esempio n. 6
0
    def create(self, docs, **kwargs):
        target_id = request.view_args['target_id']
        doc = docs[0]
        link_id = doc.get('link_id')
        desk_id = doc.get('desk')
        service = get_resource_service(ARCHIVE)
        target = service.find_one(req=None, _id=target_id)
        self._validate_link(target, target_id)
        link = {}

        if desk_id:
            link = {'task': {'desk': desk_id}}
            user = get_user()
            lookup = {'_id': desk_id, 'members.user': user['_id']}
            desk = get_resource_service('desks').find_one(req=None, **lookup)
            if not desk:
                raise SuperdeskApiError.forbiddenError(
                    "No privileges to create new take on requested desk.")

            link['task']['stage'] = desk['working_stage']

        if link_id:
            link = service.find_one(req=None, _id=link_id)

        linked_item = self.packageService.link_as_next_take(target, link)
        insert_into_versions(id_=linked_item[config.ID_FIELD])
        doc.update(linked_item)
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [linked_item['_id']]
Esempio n. 7
0
    def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        template_name = doc.get('template_name')
        item = doc.get('item') or {}
        item['desk_name'] = get_resource_service('desks').get_desk_name(item.get('task', {}).get('desk'))

        if not template_name:
            SuperdeskApiError.badRequestError(message='Invalid Template Name')

        if not item:
            SuperdeskApiError.badRequestError(message='Invalid Item')

        template = superdesk.get_resource_service('content_templates').get_template_by_name(template_name)
        if not template:
            SuperdeskApiError.badRequestError(message='Invalid Template')

        updates = render_content_template(item, template)
        item.update(updates)

        if template_name == 'kill':
            apply_null_override_for_kill(item)

        docs[0] = item
        build_custom_hateoas(CUSTOM_HATEOAS, docs[0])
        return [docs[0].get(config.ID_FIELD)]
Esempio n. 8
0
    def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        original_id = request.view_args['original_id']
        update_document = doc.get('update')

        archive_service = get_resource_service(ARCHIVE)
        original = archive_service.find_one(req=None, _id=original_id)
        self._validate_rewrite(original, update_document)

        digital = TakesPackageService().get_take_package(original)
        rewrite = self._create_rewrite_article(original,
                                               digital,
                                               existing_item=update_document,
                                               desk_id=doc.get('desk_id'))

        if update_document:
            # process the existing story
            archive_service.patch(update_document[config.ID_FIELD], rewrite)
            rewrite[config.ID_FIELD] = update_document[config.ID_FIELD]
            ids = [update_document[config.ID_FIELD]]
        else:
            ids = archive_service.post([rewrite])
            build_custom_hateoas(CUSTOM_HATEOAS, rewrite)

        self._add_rewritten_flag(original, digital, rewrite)
        get_resource_service('archive_broadcast').on_broadcast_master_updated(
            ITEM_CREATE, item=original, rewrite_id=ids[0])
        return [rewrite]
Esempio n. 9
0
    def get(self, req, lookup):
        imd = req.args.items()
        for key in imd:
            if key[1][97:104] == 'comment':  # TODO: fix
                if lookup.get('blog_id'):
                    lookup['client_blog'] = ObjectId(lookup['blog_id'])
                    del lookup['blog_id']
        if lookup.get('blog_id'):
            lookup['blog'] = ObjectId(lookup['blog_id'])
            del lookup['blog_id']
        docs = super().get(req, lookup)
        related_items = self._related_items_map(docs)

        for doc in docs:
            build_custom_hateoas(self.custom_hateoas, doc, location='posts')
            for assoc in self.packageService._get_associations(doc):
                ref_id = assoc.get('residRef', None)
                if ref_id is not None:
                    assoc['item'] = related_items[ref_id]

            self.extract_author_ids(doc)

        # now that we have authors id, let's hit db once
        self.generate_authors_map()
        self.attach_authors(docs)

        return docs
    def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        template_name = doc.get("template_name")
        item = doc.get("item") or {}
        item["desk_name"] = get_resource_service("desks").get_desk_name(
            item.get("task", {}).get("desk"))

        if not template_name:
            SuperdeskApiError.badRequestError(message="Invalid Template Name")

        if not item:
            SuperdeskApiError.badRequestError(message="Invalid Item")

        template = superdesk.get_resource_service(
            "content_templates").get_template_by_name(template_name)
        if not template:
            SuperdeskApiError.badRequestError(message="Invalid Template")

        updates = render_content_template(item, template)
        item.update(updates)

        editor_utils.generate_fields(item, reload=True)

        if template_name == "kill":
            apply_null_override_for_kill(item)

        docs[0] = item
        build_custom_hateoas(CUSTOM_HATEOAS, docs[0])
        return [docs[0].get(config.ID_FIELD)]
Esempio n. 11
0
    def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        template_name = doc.get('template_name')
        item = doc.get('item') or {}
        item['desk_name'] = get_resource_service('desks').get_desk_name(item.get('task', {}).get('desk'))

        if not template_name:
            SuperdeskApiError.badRequestError(message='Invalid Template Name')

        if not item:
            SuperdeskApiError.badRequestError(message='Invalid Item')

        template = superdesk.get_resource_service('content_templates').get_template_by_name(template_name)
        if not template:
            SuperdeskApiError.badRequestError(message='Invalid Template')

        updates = render_content_template(item, template)
        item.update(updates)

        if template_name == 'kill':
            apply_null_override_for_kill(item)

        docs[0] = item
        build_custom_hateoas(CUSTOM_HATEOAS, docs[0])
        return [docs[0].get(config.ID_FIELD)]
Esempio n. 12
0
    def fetch(self, docs, id=None, **kwargs):
        id_of_fetched_items = []

        for doc in docs:
            id_of_item_to_be_fetched = doc.get(config.ID_FIELD) if id is None else id

            desk_id = doc.get('desk')
            stage_id = doc.get('stage')

            ingest_service = get_resource_service('ingest')
            ingest_doc = ingest_service.find_one(req=None, _id=id_of_item_to_be_fetched)

            if not ingest_doc:
                raise SuperdeskApiError.notFoundError(
                    _('Fail to found ingest item with _id: {id}').format(id=id_of_item_to_be_fetched))

            if not is_workflow_state_transition_valid('fetch_from_ingest', ingest_doc[ITEM_STATE]):
                raise InvalidStateTransitionError()

            if doc.get('macro'):  # there is a macro so transform it
                ingest_doc = get_resource_service('macros').execute_macro(
                    ingest_doc,
                    doc.get('macro'),
                    dest_desk_id=desk_id,
                    dest_stage_id=stage_id,
                )

            dest_doc = fetch_item(ingest_doc, desk_id, stage_id, state=doc.get(ITEM_STATE), target=doc.get('target'))

            id_of_fetched_items.append(dest_doc[config.ID_FIELD])
            ingest_service.patch(id_of_item_to_be_fetched, {'archived': dest_doc['versioncreated']})

            dest_doc[FAMILY_ID] = ingest_doc[config.ID_FIELD]
            dest_doc[INGEST_ID] = self.__strip_version_from_guid(ingest_doc[GUID_FIELD], ingest_doc.get('version'))
            dest_doc[INGEST_VERSION] = ingest_doc.get('version')

            self.__fetch_items_in_package(dest_doc, desk_id, stage_id,
                                          doc.get(ITEM_STATE, CONTENT_STATE.FETCHED))

            self.__fetch_associated_items(dest_doc, desk_id, stage_id, doc.get(ITEM_STATE, CONTENT_STATE.FETCHED))

            desk = get_resource_service('desks').find_one(req=None, _id=desk_id)
            if desk and desk.get('default_content_profile'):
                dest_doc.setdefault('profile', desk['default_content_profile'])

            if dest_doc.get('type', 'text') in MEDIA_TYPES:
                dest_doc['profile'] = None

            get_resource_service(ARCHIVE).post([dest_doc])
            insert_into_versions(doc=dest_doc)
            build_custom_hateoas(custom_hateoas, dest_doc)
            superdesk.item_fetched.send(self, item=dest_doc, ingest_item=ingest_doc)
            doc.update(dest_doc)

        if kwargs.get('notify', True):
            ingest_doc.update({'task': dest_doc.get('task')})
            push_item_move_notification(ingest_doc, doc, 'item:fetch')

        return id_of_fetched_items
Esempio n. 13
0
 def create(self, docs, **kwargs):
     user = get_user(required=True)
     auth = get_auth()
     item_id = request.view_args['item_id']
     item = get_component(ItemHold).hold({'_id': item_id}, user['_id'],
                                         auth['_id'])
     build_custom_hateoas(custom_hateoas, item)
     return [item['_id']]
Esempio n. 14
0
    def fetch(self, docs, id=None, **kwargs):
        id_of_fetched_items = []

        for doc in docs:
            id_of_item_to_be_fetched = doc.get('_id') if id is None else id

            desk_id = doc.get('desk')
            stage_id = doc.get('stage')

            ingest_service = get_resource_service('ingest')
            ingest_doc = ingest_service.find_one(req=None,
                                                 _id=id_of_item_to_be_fetched)

            if not ingest_doc:
                raise SuperdeskApiError.notFoundError(
                    'Fail to found ingest item with _id: %s' %
                    id_of_item_to_be_fetched)

            if not is_workflow_state_transition_valid(
                    'fetch_from_ingest', ingest_doc[config.CONTENT_STATE]):
                raise InvalidStateTransitionError()

            if doc.get('macro'):  # there is a macro so transform it
                ingest_doc = get_resource_service('macros').execute_macro(
                    ingest_doc, doc.get('macro'))

            archived = utcnow()
            ingest_service.patch(id_of_item_to_be_fetched,
                                 {'archived': archived})

            dest_doc = dict(ingest_doc)
            new_id = generate_guid(type=GUID_TAG)
            id_of_fetched_items.append(new_id)
            dest_doc['_id'] = new_id
            dest_doc['guid'] = new_id
            dest_doc['destination_groups'] = doc.get('destination_groups')
            generate_unique_id_and_name(dest_doc)

            dest_doc[config.VERSION] = 1
            send_to(dest_doc, desk_id, stage_id)
            dest_doc[config.CONTENT_STATE] = doc.get('state', STATE_FETCHED)
            dest_doc[INGEST_ID] = dest_doc[FAMILY_ID] = ingest_doc['_id']

            remove_unwanted(dest_doc)
            set_original_creator(dest_doc)
            self.__fetch_items_in_package(dest_doc, desk_id, stage_id,
                                          doc.get('state', STATE_FETCHED),
                                          doc.get('destination_groups'))

            get_resource_service(ARCHIVE).post([dest_doc])
            insert_into_versions(doc=dest_doc)
            build_custom_hateoas(custom_hateoas, dest_doc)
            doc.update(dest_doc)

        if kwargs.get('notify', True):
            push_notification('item:fetch', fetched=1)

        return id_of_fetched_items
Esempio n. 15
0
 def _build_hateoas(self, doc):
     build_custom_hateoas(
         {
             'self': {
                 'title': 'Content Profile',
                 'href': '/content_types/{_id}'
             }
         }, doc)
     return doc
Esempio n. 16
0
 def _build_hateoas(self, doc):
     build_custom_hateoas(
         {
             "self": {
                 "title": "Content Profile",
                 "href": "/content_types/{_id}"
             }
         }, doc)
     return doc
Esempio n. 17
0
    def on_fetched(self, doc):
        """
        Overriding to add HATEOS for each individual item in the response.

        :param doc: response doc
        :type doc: dict
        """

        docs = doc[app.config["ITEMS"]]
        for item in docs:
            build_custom_hateoas({"self": {"title": item["_type"], "href": "/{}/{{_id}}".format(item["_type"])}}, item)
Esempio n. 18
0
    def on_fetched(self, doc):
        """
        Overriding to add HATEOS for each individual item in the response.

        :param doc: response doc
        :type doc: dict
        """

        docs = doc[app.config['ITEMS']]
        for item in docs:
            build_custom_hateoas({'self': {'title': item['_type'], 'href': '/{}/{{_id}}'.format(item['_type'])}}, item)
Esempio n. 19
0
    def create(self, docs):
        service = get_resource_service(SOURCE)
        item_id = request.view_args["item_id"]
        item = service.find_one(req=None, _id=item_id)
        doc = docs[0]

        self._valid_broadcast_item(item)

        desk_id = doc.get("desk")
        desk = None

        if desk_id:
            desk = get_resource_service("desks").find_one(req=None,
                                                          _id=desk_id)

        doc.pop("desk", None)
        doc["task"] = {}
        if desk:
            doc["task"]["desk"] = desk.get(config.ID_FIELD)
            doc["task"]["stage"] = desk.get("working_stage")

        doc["task"]["user"] = get_user().get("_id")
        genre_list = get_resource_service("vocabularies").find_one(
            req=None, _id="genre") or {}
        broadcast_genre = [
            {
                "qcode": genre.get("qcode"),
                "name": genre.get("name")
            } for genre in genre_list.get("items", [])
            if genre.get("qcode") == BROADCAST_GENRE and genre.get("is_active")
        ]

        if not broadcast_genre:
            raise SuperdeskApiError.badRequestError(
                message=_("Cannot find the {genre} genre.").format(
                    genre=BROADCAST_GENRE))

        doc["broadcast"] = {
            "status": "",
            "master_id": item_id,
            "rewrite_id": item.get("rewritten_by")
        }

        doc["genre"] = broadcast_genre
        doc["family_id"] = item.get("family_id")

        for key in FIELDS_TO_COPY:
            doc[key] = item.get(key)

        resolve_document_version(document=doc, resource=SOURCE, method="POST")
        service.post(docs)
        insert_into_versions(id_=doc[config.ID_FIELD])
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [doc[config.ID_FIELD]]
Esempio n. 20
0
 def create(self, docs, **kwargs):
     original_id = request.view_args['original_id']
     archive_service = get_resource_service('archive')
     original = archive_service.find_one(req=None, _id=original_id)
     self._validate_rewrite(original)
     digital = TakesPackageService().get_take_package(original)
     rewrite = self._create_rewrite_article(original, digital)
     archive_service.post([rewrite])
     build_custom_hateoas(CUSTOM_HATEOAS, rewrite)
     self._add_rewritten_flag(original, digital, rewrite)
     return [rewrite]
Esempio n. 21
0
    def create(self, docs):
        service = get_resource_service(SOURCE)
        item_id = request.view_args['item_id']
        item = service.find_one(req=None, _id=item_id)
        doc = docs[0]

        self._valid_broadcast_item(item)

        desk_id = doc.get('desk')
        desk = None

        if desk_id:
            desk = get_resource_service('desks').find_one(req=None,
                                                          _id=desk_id)

        doc.pop('desk', None)
        doc['task'] = {}
        if desk:
            doc['task']['desk'] = desk.get(config.ID_FIELD)
            doc['task']['stage'] = desk.get('working_stage')

        doc['task']['user'] = get_user().get('_id')
        genre_list = get_resource_service('vocabularies').find_one(
            req=None, _id='genre') or {}
        broadcast_genre = [
            {
                'qcode': genre.get('qcode'),
                'name': genre.get('name')
            } for genre in genre_list.get('items', [])
            if genre.get('qcode') == BROADCAST_GENRE and genre.get('is_active')
        ]

        if not broadcast_genre:
            raise SuperdeskApiError.badRequestError(
                message=_("Cannot find the {genre} genre.").format(
                    genre=BROADCAST_GENRE))

        doc['broadcast'] = {
            'status': '',
            'master_id': item_id,
            'rewrite_id': item.get('rewritten_by')
        }

        doc['genre'] = broadcast_genre
        doc['family_id'] = item.get('family_id')

        for key in FIELDS_TO_COPY:
            doc[key] = item.get(key)

        resolve_document_version(document=doc, resource=SOURCE, method='POST')
        service.post(docs)
        insert_into_versions(id_=doc[config.ID_FIELD])
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [doc[config.ID_FIELD]]
Esempio n. 22
0
 def create(self, docs, **kwargs):
     original_id = request.view_args["original_id"]
     archive_service = get_resource_service("archive")
     original = archive_service.find_one(req=None, _id=original_id)
     self._validate_rewrite(original)
     digital = TakesPackageService().get_take_package(original)
     rewrite = self._create_rewrite_article(original, digital)
     archive_service.post([rewrite])
     build_custom_hateoas(CUSTOM_HATEOAS, rewrite)
     self._add_rewritten_flag(original, digital, rewrite)
     return [rewrite]
Esempio n. 23
0
    def fetch(self, docs, id=None, **kwargs):
        id_of_fetched_items = []

        for doc in docs:
            id_of_item_to_be_fetched = doc.get('_id') if id is None else id

            desk_id = doc.get('desk')
            stage_id = doc.get('stage')

            ingest_service = get_resource_service('ingest')
            ingest_doc = ingest_service.find_one(req=None, _id=id_of_item_to_be_fetched)

            if not ingest_doc:
                raise SuperdeskApiError.notFoundError('Fail to found ingest item with _id: %s' %
                                                      id_of_item_to_be_fetched)

            if not is_workflow_state_transition_valid('fetch_from_ingest', ingest_doc[config.CONTENT_STATE]):
                raise InvalidStateTransitionError()

            if doc.get('macro'):  # there is a macro so transform it
                ingest_doc = get_resource_service('macros').execute_macro(ingest_doc, doc.get('macro'))

            archived = utcnow()
            ingest_service.patch(id_of_item_to_be_fetched, {'archived': archived})

            dest_doc = dict(ingest_doc)
            new_id = generate_guid(type=GUID_TAG)
            id_of_fetched_items.append(new_id)
            dest_doc['_id'] = new_id
            dest_doc['guid'] = new_id
            dest_doc['destination_groups'] = doc.get('destination_groups')
            generate_unique_id_and_name(dest_doc)

            dest_doc[config.VERSION] = 1
            send_to(dest_doc, desk_id, stage_id)
            dest_doc[config.CONTENT_STATE] = doc.get('state', STATE_FETCHED)
            dest_doc[INGEST_ID] = dest_doc[FAMILY_ID] = ingest_doc['_id']

            remove_unwanted(dest_doc)
            set_original_creator(dest_doc)
            self.__fetch_items_in_package(dest_doc, desk_id, stage_id,
                                          doc.get('state', STATE_FETCHED),
                                          doc.get('destination_groups'))

            get_resource_service(ARCHIVE).post([dest_doc])
            insert_into_versions(doc=dest_doc)
            build_custom_hateoas(custom_hateoas, dest_doc)
            doc.update(dest_doc)

        if kwargs.get('notify', True):
            push_notification('item:fetch', fetched=1)

        return id_of_fetched_items
Esempio n. 24
0
 def get(self, req, lookup):
     if lookup.get('blog_id'):
         lookup['blog'] = ObjectId(lookup['blog_id'])
         del lookup['blog_id']
     docs = super().get(req, lookup)
     for doc in docs:
         build_custom_hateoas(self.custom_hateoas, doc, location='posts')
         for assoc in self.packageService._get_associations(doc):
             if assoc.get('residRef'):
                 item = get_resource_service('archive').find_one(req=None, _id=assoc['residRef'])
                 assoc['item'] = item
     return docs
Esempio n. 25
0
def complete_flag_info(flag):
    if not flag:
        return

    users = []
    if 'users' in flag:
        for userId in flag['users']:
            users.append(get_resource_service('users').find_one(req=None, _id=userId))
        flag['users'] = users

    # so this we have _links available for other methods in frontend
    build_custom_hateoas(PostFlagService.custom_hateoas, flag, location='post_flags')
Esempio n. 26
0
    def fetch(self, docs, id=None, **kwargs):
        id_of_fetched_items = []

        for doc in docs:
            id_of_item_to_be_fetched = doc.get("_id") if id is None else id

            desk_id = doc.get("desk")
            stage_id = doc.get("stage")

            ingest_service = get_resource_service("ingest")
            ingest_doc = ingest_service.find_one(req=None, _id=id_of_item_to_be_fetched)

            if not ingest_doc:
                raise SuperdeskApiError.notFoundError(
                    "Fail to found ingest item with _id: %s" % id_of_item_to_be_fetched
                )

            if not is_workflow_state_transition_valid("fetch_from_ingest", ingest_doc[ITEM_STATE]):
                raise InvalidStateTransitionError()

            if doc.get("macro"):  # there is a macro so transform it
                ingest_doc = get_resource_service("macros").execute_macro(ingest_doc, doc.get("macro"))

            archived = utcnow()
            ingest_service.patch(id_of_item_to_be_fetched, {"archived": archived})

            dest_doc = dict(ingest_doc)
            new_id = generate_guid(type=GUID_TAG)
            id_of_fetched_items.append(new_id)
            dest_doc["_id"] = new_id
            dest_doc["guid"] = new_id
            generate_unique_id_and_name(dest_doc)

            dest_doc[config.VERSION] = 1
            send_to(doc=dest_doc, desk_id=desk_id, stage_id=stage_id)
            dest_doc[ITEM_STATE] = doc.get(ITEM_STATE, CONTENT_STATE.FETCHED)
            dest_doc[INGEST_ID] = dest_doc[FAMILY_ID] = ingest_doc["_id"]
            dest_doc[ITEM_OPERATION] = ITEM_FETCH

            remove_unwanted(dest_doc)
            set_original_creator(dest_doc)
            self.__fetch_items_in_package(dest_doc, desk_id, stage_id, doc.get(ITEM_STATE, CONTENT_STATE.FETCHED))

            get_resource_service(ARCHIVE).post([dest_doc])
            insert_into_versions(doc=dest_doc)
            build_custom_hateoas(custom_hateoas, dest_doc)
            doc.update(dest_doc)

        if kwargs.get("notify", True):
            push_notification("item:fetch", fetched=1)

        return id_of_fetched_items
Esempio n. 27
0
 def create(self, docs, **kwargs):
     original_id = request.view_args['original_id']
     archive_service = get_resource_service(ARCHIVE)
     original = archive_service.find_one(req=None, _id=original_id)
     self._validate_rewrite(original)
     digital = TakesPackageService().get_take_package(original)
     rewrite = self._create_rewrite_article(original, digital)
     ids = archive_service.post([rewrite])
     build_custom_hateoas(CUSTOM_HATEOAS, rewrite)
     self._add_rewritten_flag(original, digital, rewrite)
     get_resource_service('archive_broadcast').on_broadcast_master_updated(
         ITEM_CREATE, item=original, rewrite_id=ids[0])
     return [rewrite]
Esempio n. 28
0
 def get(self, req, lookup):
     if lookup.get('blog_id'):
         lookup['blog'] = ObjectId(lookup['blog_id'])
         del lookup['blog_id']
     docs = super().get(req, lookup)
     for doc in docs:
         build_custom_hateoas(self.custom_hateoas, doc, location='posts')
         for assoc in self.packageService._get_associations(doc):
             if assoc.get('residRef'):
                 item = get_resource_service('archive').find_one(
                     req=None, _id=assoc['residRef'])
                 assoc['item'] = item
     return docs
Esempio n. 29
0
    def _get_subscribers_by_filter_condition(self, filter_condition):
        """
        Searches all subscribers that has a content filter with the given filter condition

        If filter condition is used in a global filter then it returns all
        subscribers that not disabled the global filter.
        :param filter_condition: Filter condition to test
        :return: List of subscribers
        """
        req = ParsedRequest()
        all_subscribers = list(super().get(req=req, lookup=None))
        selected_products = {}
        selected_subscribers = {}
        selected_content_filters = {}

        filter_condition_service = get_resource_service('filter_conditions')
        content_filter_service = get_resource_service('content_filters')
        product_service = get_resource_service('products')

        existing_products = list(product_service.get(req=req, lookup=None))
        existing_filter_conditions = filter_condition_service.check_similar(filter_condition)
        for fc in existing_filter_conditions:
            existing_content_filters = content_filter_service.get_content_filters_by_filter_condition(fc['_id'])
            for pf in existing_content_filters:
                selected_content_filters[pf['_id']] = pf

                if pf.get('is_global', False):
                    for s in all_subscribers:
                        gfs = s.get('global_filters', {})
                        if gfs.get(str(pf['_id']), True):
                            build_custom_hateoas({'self': {'title': 'subscribers', 'href': '/subscribers/{_id}'}}, s)
                            selected_subscribers[s['_id']] = s

                for product in existing_products:
                    if product.get('content_filter') and \
                        'filter_id' in product['content_filter'] and \
                            product['content_filter']['filter_id'] == pf['_id']:
                        selected_products[product['_id']] = product

                for s in all_subscribers:
                    all_subscriber_products = list(set(s.get('products') or []) | set(s.get('api_products') or []))
                    for p in all_subscriber_products:
                        if p in selected_products:
                            build_custom_hateoas({'self': {'title': 'subscribers', 'href': '/subscribers/{_id}'}}, s)
                            selected_subscribers[s['_id']] = s

        res = {'filter_conditions': existing_filter_conditions,
               'content_filters': list(selected_content_filters.values()),
               'products': list(selected_products.values()),
               'selected_subscribers': list(selected_subscribers.values())}
        return [res]
Esempio n. 30
0
    def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        original_id = request.view_args["original_id"]
        update_document = doc.get("update")

        archive_service = get_resource_service(ARCHIVE)
        original = archive_service.find_one(req=None, _id=original_id)
        self._validate_rewrite(original, update_document)

        rewrite = self._create_rewrite_article(original,
                                               existing_item=update_document,
                                               desk_id=doc.get("desk_id"))

        # sync editor state
        copy_fields(original, rewrite, ignore_empty=True)

        if update_document:
            # copy editor state from existing item to preserve those
            copy_fields(update_document, rewrite, ignore_empty=True)

        if rewrite.get("fields_meta"):
            generate_fields(rewrite, force=True)

        update_associations(rewrite)

        # signal
        item_rewrite.send(self, item=rewrite, original=original)

        if update_document:
            # process the existing story
            archive_service.patch(update_document[config.ID_FIELD], rewrite)
            app.on_archive_item_updated(rewrite, update_document, ITEM_LINK)
            rewrite[config.ID_FIELD] = update_document[config.ID_FIELD]
            ids = [update_document[config.ID_FIELD]]
        else:
            # Set the version.
            resolve_document_version(rewrite, ARCHIVE, "POST")
            ids = archive_service.post([rewrite])
            insert_into_versions(doc=rewrite)
            build_custom_hateoas(CUSTOM_HATEOAS, rewrite)

            app.on_archive_item_updated(
                {"rewrite_of": rewrite.get("rewrite_of")}, rewrite, ITEM_LINK)

        self._add_rewritten_flag(original, rewrite)
        get_resource_service("archive_broadcast").on_broadcast_master_updated(
            ITEM_CREATE, item=original, rewrite_id=ids[0])

        doc.clear()
        doc.update(rewrite)
        return ids
Esempio n. 31
0
 def create(self, docs, **kwargs):
     original_id = request.view_args['original_id']
     archive_service = get_resource_service('archive')
     original = archive_service.find_one(req=None, _id=original_id)
     self._validate_rewrite(original)
     digital = TakesPackageService().get_take_package(original)
     rewrite = self._create_rewrite_article(original, digital)
     ids = archive_service.post([rewrite])
     build_custom_hateoas(CUSTOM_HATEOAS, rewrite)
     self._add_rewritten_flag(original, digital, rewrite)
     get_resource_service('archive_broadcast').on_broadcast_master_updated(ITEM_CREATE,
                                                                           item=original,
                                                                           rewrite_id=ids[0])
     return [rewrite]
Esempio n. 32
0
    def _add_flags_info(self, post, flags_map):
        # time to get info from editing flags
        flag = flags_map.get(post['_id'])

        # let's replace users id with real information
        if (flag):
            users = []
            for userId in flag['users']:
                users.append(get_resource_service('users').find_one(req=None, _id=userId))
            flag['users'] = users

            # so this we have _links available for other methods in frontend
            build_custom_hateoas(PostFlagService.custom_hateoas, flag, location='post_flags')
            post['edit_flag'] = flag

        return post
Esempio n. 33
0
    def _parse_hits(self, hits):
        schemas = {
            'planning': self._get_resource_schema('planning'),
            'events': self._get_resource_schema('events')
        }

        docs = []
        for hit in hits.get('hits', {}).get('hits', []):
            item_type = hit.get('_type')
            schema = schemas.get(item_type)
            dates = get_dates(schema)
            doc = format_doc(hit, schema, dates)
            build_custom_hateoas({'self': {'title': doc['_type'], 'href': '/{}/{{_id}}'.format(doc['_type'])}}, doc)
            docs.append(doc)

        return ElasticCursor(hits, docs)
Esempio n. 34
0
    def create(self, docs):
        service = get_resource_service(SOURCE)
        item_id = request.view_args['item_id']
        item = service.find_one(req=None, _id=item_id)
        doc = docs[0]

        self._valid_broadcast_item(item)

        desk_id = doc.get('desk')
        desk = None

        if desk_id:
            desk = get_resource_service('desks').find_one(req=None, _id=desk_id)

        doc.pop('desk', None)
        doc['task'] = {}
        if desk:
            doc['task']['desk'] = desk.get(config.ID_FIELD)
            doc['task']['stage'] = desk.get('working_stage')

        doc['task']['user'] = get_user().get('_id')
        genre_list = get_resource_service('vocabularies').find_one(req=None, _id='genre') or {}
        broadcast_genre = [{'qcode': genre.get('qcode'), 'name': genre.get('name')}
                           for genre in genre_list.get('items', [])
                           if genre.get('qcode') == BROADCAST_GENRE and genre.get('is_active')]

        if not broadcast_genre:
            raise SuperdeskApiError.badRequestError(message="Cannot find the {} genre.".format(BROADCAST_GENRE))

        doc['broadcast'] = {
            'status': '',
            'master_id': item_id,
            'takes_package_id': self.takesService.get_take_package_id(item),
            'rewrite_id': item.get('rewritten_by')
        }

        doc['genre'] = broadcast_genre
        doc['family_id'] = item.get('family_id')

        for key in FIELDS_TO_COPY:
            doc[key] = item.get(key)

        resolve_document_version(document=doc, resource=SOURCE, method='POST')
        service.post(docs)
        insert_into_versions(id_=doc[config.ID_FIELD])
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [doc[config.ID_FIELD]]
Esempio n. 35
0
 def get(self, req, lookup):
     imd = req.args.items()
     for key in imd:
         if key[1][97:104] == 'comment':  # TODO: fix
             if lookup.get('blog_id'):
                 lookup['client_blog'] = ObjectId(lookup['blog_id'])
                 del lookup['blog_id']
     if lookup.get('blog_id'):
         lookup['blog'] = ObjectId(lookup['blog_id'])
         del lookup['blog_id']
     docs = super().get(req, lookup)
     for doc in docs:
         build_custom_hateoas(self.custom_hateoas, doc, location='posts')
         for assoc in self.packageService._get_associations(doc):
             if assoc.get('residRef'):
                 item = get_resource_service('archive').find_one(req=None, _id=assoc['residRef'])
                 assoc['item'] = item
     return docs
Esempio n. 36
0
    def create(self, docs, **kwargs):
        target_id = request.view_args['target_id']
        doc = docs[0]
        link_id = doc.get('link_id')
        desk_id = doc.get('desk')
        service = get_resource_service(ARCHIVE)
        target = service.find_one(req=None, _id=target_id)
        self._validate_link(target, target_id)

        link = {'task': {'desk': desk_id}} if desk_id else {}

        if link_id:
            link = service.find_one(req=None, _id=link_id)

        linked_item = self.packageService.link_as_next_take(target, link)
        doc.update(linked_item)
        build_custom_hateoas(CUSTOM_HATEOAS, doc)
        return [linked_item['_id']]
Esempio n. 37
0
    def create(self, docs, **kwargs):
        doc = docs[0] if len(docs) > 0 else {}
        original_id = request.view_args['original_id']
        update_document = doc.get('update')

        archive_service = get_resource_service(ARCHIVE)
        original = archive_service.find_one(req=None, _id=original_id)
        self._validate_rewrite(original, update_document)

        rewrite = self._create_rewrite_article(original,
                                               existing_item=update_document,
                                               desk_id=doc.get('desk_id'))

        if 'body_html' in rewrite:
            if 'fields_meta' in original:
                rewrite['fields_meta'] = original['fields_meta']
            update_associations(rewrite)

        # signal
        item_rewrite.send(self, item=rewrite, original=original)

        if update_document:
            # process the existing story
            archive_service.patch(update_document[config.ID_FIELD], rewrite)
            app.on_archive_item_updated(rewrite, update_document, ITEM_LINK)
            rewrite[config.ID_FIELD] = update_document[config.ID_FIELD]
            ids = [update_document[config.ID_FIELD]]
        else:
            # Set the version.
            resolve_document_version(rewrite, ARCHIVE, "POST")
            ids = archive_service.post([rewrite])
            insert_into_versions(doc=rewrite)
            build_custom_hateoas(CUSTOM_HATEOAS, rewrite)

            app.on_archive_item_updated(
                {'rewrite_of': rewrite.get('rewrite_of')}, rewrite, ITEM_LINK)

        self._add_rewritten_flag(original, rewrite)
        get_resource_service('archive_broadcast').on_broadcast_master_updated(
            ITEM_CREATE, item=original, rewrite_id=ids[0])

        doc.clear()
        doc.update(rewrite)
        return ids
Esempio n. 38
0
    def get(self, req, **lookup):
        content_view_id = lookup['lookup']['content_view_id']
        view_items = superdesk.get_resource_service('content_view').find_one(req=None, _id=content_view_id)
        if not view_items:
            raise superdesk.SuperdeskError(payload='Invalid content view id.')
        additional_query = view_items.get('filter')

        query = None
        if req.args.get('source'):
            query = json.loads(req.args.get('source'))

        query = apply_additional_query(query, additional_query)
        parsed_request = init_parsed_request(query)
        location = view_items.get('location', 'archive')
        docs = superdesk.get_resource_service(location).get(req=parsed_request, lookup={})

        for doc in docs:
            build_custom_hateoas(self.custom_hateoas, doc, location=location)
        return docs
Esempio n. 39
0
    def get(self, req, **lookup):
        content_view_id = lookup['lookup']['content_view_id']
        view_items = superdesk.get_resource_service('content_view').find_one(
            req=None, _id=content_view_id)
        if not view_items:
            raise superdesk.SuperdeskError(payload='Invalid content view id.')
        additional_query = view_items.get('filter')

        query = None
        if req.args.get('source'):
            query = json.loads(req.args.get('source'))

        query = apply_additional_query(query, additional_query)
        parsed_request = init_parsed_request(query)
        location = view_items.get('location', 'archive')
        docs = superdesk.get_resource_service(location).get(req=parsed_request,
                                                            lookup={})

        for doc in docs:
            build_custom_hateoas(self.custom_hateoas, doc, location=location)
        return docs
Esempio n. 40
0
 def on_created(self, docs):
     build_custom_hateoas(CUSTOM_HATEOAS_EVENTS,
                          docs[0],
                          _id=str(docs[0][config.ID_FIELD]))
Esempio n. 41
0
 def enhance_items(self, items):
     super().enhance_items(items)
     for item in items:
         build_custom_hateoas(CUSTOM_HATEOAS, item)
Esempio n. 42
0
    def _get_subscribers_by_filter_condition(self, filter_condition):
        """
        Searches all subscribers that has a content filter with the given filter condition

        If filter condition is used in a global filter then it returns all
        subscribers that not disabled the global filter.
        :param filter_condition: Filter condition to test
        :return: List of subscribers
        """
        req = ParsedRequest()
        all_subscribers = list(super().get(req=req, lookup=None))
        selected_products = {}
        selected_subscribers = {}
        selected_content_filters = {}

        filter_condition_service = get_resource_service("filter_conditions")
        content_filter_service = get_resource_service("content_filters")
        product_service = get_resource_service("products")

        existing_products = list(product_service.get(req=req, lookup=None))
        existing_filter_conditions = filter_condition_service.check_similar(
            filter_condition)
        for fc in existing_filter_conditions:
            existing_content_filters = content_filter_service.get_content_filters_by_filter_condition(
                fc["_id"])
            for pf in existing_content_filters:
                selected_content_filters[pf["_id"]] = pf

                if pf.get("is_global", False):
                    for s in all_subscribers:
                        gfs = s.get("global_filters", {})
                        if gfs.get(str(pf["_id"]), True):
                            build_custom_hateoas(
                                {
                                    "self": {
                                        "title": "subscribers",
                                        "href": "/subscribers/{_id}"
                                    }
                                }, s)
                            selected_subscribers[s["_id"]] = s

                for product in existing_products:
                    if (product.get("content_filter")
                            and "filter_id" in product["content_filter"]
                            and product["content_filter"]["filter_id"]
                            == pf["_id"]):
                        selected_products[product["_id"]] = product

                for s in all_subscribers:
                    all_subscriber_products = list(
                        set(s.get("products") or [])
                        | set(s.get("api_products") or []))
                    for p in all_subscriber_products:
                        if p in selected_products:
                            build_custom_hateoas(
                                {
                                    "self": {
                                        "title": "subscribers",
                                        "href": "/subscribers/{_id}"
                                    }
                                }, s)
                            selected_subscribers[s["_id"]] = s

        res = {
            "filter_conditions": existing_filter_conditions,
            "content_filters": list(selected_content_filters.values()),
            "products": list(selected_products.values()),
            "selected_subscribers": list(selected_subscribers.values()),
        }
        return [res]
Esempio n. 43
0
def update_returned_document(doc, item, custom_hateoas):
    doc.clear()
    doc.update(item)
    build_custom_hateoas(custom_hateoas, doc)
    return [doc['_id']]
Esempio n. 44
0
    def _get_subscribers_by_filter_condition(self, filter_condition):
        """
        Searches all subscribers that has a content filter with the given filter condition

        If filter condition is used in a global filter then it returns all
        subscribers that not disabled the global filter.
        :param filter_condition: Filter condition to test
        :return: List of subscribers
        """
        req = ParsedRequest()
        all_subscribers = list(super().get(req=req, lookup=None))
        selected_products = {}
        selected_subscribers = {}
        selected_content_filters = {}

        filter_condition_service = get_resource_service('filter_conditions')
        content_filter_service = get_resource_service('content_filters')
        product_service = get_resource_service('products')

        existing_products = list(product_service.get(req=req, lookup=None))
        existing_filter_conditions = filter_condition_service.check_similar(
            filter_condition)
        for fc in existing_filter_conditions:
            existing_content_filters = content_filter_service.get_content_filters_by_filter_condition(
                fc['_id'])
            for pf in existing_content_filters:
                selected_content_filters[pf['_id']] = pf

                if pf.get('is_global', False):
                    for s in all_subscribers:
                        gfs = s.get('global_filters', {})
                        if gfs.get(str(pf['_id']), True):
                            build_custom_hateoas(
                                {
                                    'self': {
                                        'title': 'subscribers',
                                        'href': '/subscribers/{_id}'
                                    }
                                }, s)
                            selected_subscribers[s['_id']] = s

                for product in existing_products:
                    if product.get('content_filter') and \
                        'filter_id' in product['content_filter'] and \
                            product['content_filter']['filter_id'] == pf['_id']:
                        selected_products[product['_id']] = product

                for s in all_subscribers:
                    all_subscriber_products = list(
                        set(s.get('products') or [])
                        | set(s.get('api_products') or []))
                    for p in all_subscriber_products:
                        if p in selected_products:
                            build_custom_hateoas(
                                {
                                    'self': {
                                        'title': 'subscribers',
                                        'href': '/subscribers/{_id}'
                                    }
                                }, s)
                            selected_subscribers[s['_id']] = s

        res = {
            'filter_conditions': existing_filter_conditions,
            'content_filters': list(selected_content_filters.values()),
            'products': list(selected_products.values()),
            'selected_subscribers': list(selected_subscribers.values())
        }
        return [res]