Exemple #1
0
def freeze_project_and_entity_metadata(project_id, entity_uuids=None):
    """Freeze project and entity metadata.

    Given a project id and an entity uuid (should be a main entity) this function
    retrieves all metadata related to these entities and stores it into Elasticsearch
    as :class:`~designafe.libs.elasticsearch.docs.publications.BaseESPublication`

    :param str project_id: Project id.
    :param list of entity_uuid strings: Entity uuids.
    """
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    pub_doc = BaseESPublication(project_id=project_id)
    publication = pub_doc.to_dict()

    if entity_uuids:
        # clear any existing entities in publication
        entity = mgr.get_entity_by_uuid(entity_uuids[0])
        pub_entities_field_name = FIELD_MAP[entity.name]
        publication[pub_entities_field_name] = []

        for ent_uuid in entity_uuids:
            entity = None
            entity = mgr.get_entity_by_uuid(ent_uuid)
            entity_json = entity.to_body_dict()

            if entity:
                pub_entities_field_name = FIELD_MAP[entity.name]
                publication['authors'] = entity_json['value']['authors'][:]
                entity_json['authors'] = []

                _populate_entities_in_publication(entity, publication)
                _transform_authors(entity_json, publication)

                if entity_json['value']['dois']:
                    entity_json['doi'] = entity_json['value']['dois'][-1]

                _delete_unused_fields(entity_json)
                publication[pub_entities_field_name].append(entity_json)

    prj_json = prj.to_body_dict()
    _delete_unused_fields(prj_json)

    award_number = publication.get('project', {}).get('value', {}).pop(
        'awardNumber', []) or []

    if not isinstance(award_number, list):
        award_number = []

    prj_json['value']['awardNumbers'] = award_number
    prj_json['value'].pop('awardNumber', None)
    if publication.get('project'):
        publication['project'].update(prj_json)
    else:
        publication['project'] = prj_json

    pub_doc.update(**publication)
    return pub_doc
Exemple #2
0
def _populate_entities_in_publication(entity, publication):
    """Populate entities in publication dict.

    :param entity: Entity resource instance.
    :param dict publication: Publication dict.
    """
    mgr = ProjectsManager(service_account())

    reverse_field_attrs = entity._meta._reverse_fields
    reverse_fields = []
    for attr in reverse_field_attrs:
        try:
            field = getattr(entity, attr)
        except AttributeError:
            LOG.exception("No field '%(attr)s' in '%(ent)s'", {
                "attr": attr,
                "ent": entity
            })
        reverse_fields.append(field.rel_cls.model_name)

    for field_name in reverse_fields:
        for pent in publication.get(FIELD_MAP[field_name], []):
            ent = mgr.get_entity_by_uuid(pent['uuid'])
            ent_dict = ent.to_body_dict()
            _delete_unused_fields(ent_dict)
            pent.update(ent_dict)
Exemple #3
0
def publish_resource(project_id, entity_uuid=None):
    """Publish a resource.

    Retrieves a project and/or an entity and set any saved DOIs
    as published. If no DOIs are saved in the specified project or entity
    it will fail silently. We need to specify the project id because
    this function also changes the status of the locally saved publication
    to `"published"` that way it shows up in the published listing.

    :param str project_id: Project Id to publish.
    :param str entity_uuid: Entity uuid to publish.
    """
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    entity = None
    if entity_uuid:
        entity = mgr.get_entity_by_uuid(entity_uuid)
    responses = []
    for doi in prj.dois:
        res = DataciteManager.publish_doi(doi)
        responses.append(res)

    if entity:
        for doi in entity.dois:
            res = DataciteManager.publish_doi(doi)
            responses.append(res)

    pub = BaseESPublication(project_id=project_id)
    pub.update(status='published')

    for res in responses:
        LOG.info("DOI published: %(doi)s", {"doi": res['data']['id']})
    return responses
Exemple #4
0
def publish_resource(project_id, entity_uuids=None, publish_dois=False, revision=None):
    """Publish a resource.

    Retrieves a project and/or an entity and set any saved DOIs
    as published. If no DOIs are saved in the specified project or entity
    it will fail silently. We need to specify the project id because
    this function also changes the status of the locally saved publication
    to `"published"` that way it shows up in the published listing.

    If publish_dois is False Datacite will keep the newly created DOIs in
    "DRAFT" status, and not "PUBLISHED". A DOI on DataCite can only be
    deleted if it is in "DRAFT" status. Once a DOI is set to "PUBLISHED"
    or "RESERVED" it can't be deleted.

    :param str project_id: Project Id to publish.
    :param list entity_uuids: list of str Entity uuids to publish.
    :param int revision: Revision number to publish.
    """
    es_client = new_es_client()

    # If revision number passed, set status to "published" for specified revision and
    # set status to "revised" for old versions
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    responses = []

    if publish_dois:
        if entity_uuids:
            for ent_uuid in entity_uuids:
                entity = None
                if ent_uuid:
                    entity = mgr.get_entity_by_uuid(ent_uuid)

                if entity:
                    for doi in entity.dois:
                        res = DataciteManager.publish_doi(doi)
                        responses.append(res)

        for doi in prj.dois:
            res = DataciteManager.publish_doi(doi)
            responses.append(res)

    pub = BaseESPublication(project_id=project_id, revision=revision, using=es_client)
    pub.update(status='published', using=es_client)
    IndexedPublication._index.refresh(using=es_client)

    if revision:
        # Revising a publication sets the status of the previous document to 'archived'
        last_revision = revision - 1 if revision > 2 else 0
        archived_pub = BaseESPublication(project_id=project_id, revision=last_revision)
        archived_pub.update(status='archived')

    for res in responses:
        logger.info(
            "DOI published: %(doi)s",
            {"doi": res['data']['id']}
        )
    return responses
Exemple #5
0
    def create_metadata():
        mgr = ProjectsManager(service_account())
        pub_dict = pub._wrapped.to_dict()
        meta_dict = {}

        entity_type_map = {
            'experimental': 'experimentsList',
            'simulation': 'simulations',
            'hybrid_simulation': 'hybrid_simulations',
            'field_recon': 'missions',
        }

        project_uuid = pub_dict['project']['uuid']
        try:
            logger.debug("Creating metadata for {}".format(pub.projectId))
            if pub_dict['project']['value']['projectType'] in entity_type_map:
                ent_type = entity_type_map[pub_dict['project']['value']
                                           ['projectType']]
                entity_uuids = []
                if ent_type in pub_dict.keys():
                    entity_uuids = [x['uuid'] for x in pub_dict[ent_type]]
                meta_dict = mgr.get_entity_by_uuid(
                    project_uuid).to_datacite_json()
                meta_dict['published_resources'] = []
                meta_dict['url'] = TARGET_BASE.format(
                    project_id=pub_dict['project_id'])
                for uuid in entity_uuids:
                    entity = mgr.get_entity_by_uuid(uuid)
                    ent_json = entity.to_datacite_json()
                    ent_json['doi'] = entity.dois[0]
                    ent_json['url'] = ENTITY_TARGET_BASE.format(
                        project_id=pub_dict['project_id'], entity_uuid=uuid)
                    meta_dict['published_resources'].append(ent_json)
            else:
                project = mgr.get_entity_by_uuid(project_uuid)
                meta_dict = project.to_datacite_json()
                meta_dict['doi'] = project.dois[0]
                meta_dict['url'] = TARGET_BASE.format(
                    project_id=pub_dict['project_id'])

            with open(metadata_path, 'w') as meta_file:
                json.dump(meta_dict, meta_file)
        except:
            logger.exception("Failed to create metadata!")
Exemple #6
0
def amend_publication(project_id, amendments=None, authors=None, revision=None):
    """Amend a Publication
    
    Update Amendable fields on a publication and the corrosponding DataCite
    records. These changes do not produce a new version of a publication, but
    they do allow for limited changes to a published project. This is currently
    configured to support "Other" publications only.
    
    :param str project_id: Project uuid to amend
    :param int revision: Revision number to amend
    """
    es_client = new_es_client()
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    pub = BaseESPublication(project_id=project_id, revision=revision, using=es_client)

    prj_dict = prj.to_body_dict()
    pub_dict = pub.to_dict()
    _delete_unused_fields(prj_dict)

    if pub.project.value.projectType != 'other':
        pub_entity_uuids = pub.entities()
        for uuid in pub_entity_uuids:
            if uuid in amendments:
                entity = amendments[uuid]
            else:
                entity = mgr.get_entity_by_uuid(uuid)
                entity = entity.to_body_dict()
            _delete_unused_fields(entity)

            for pub_ent in pub_dict[FIELD_MAP[entity['name']]]:
                if pub_ent['uuid'] == entity['uuid']:
                    for key in entity['value']:
                        ent_type = 'entity' if 'dois' in entity['value'] else 'subentity'
                        if key not in UNAMENDABLE_FIELDS[ent_type]:
                            pub_ent['value'][key] = entity['value'][key]
                    if 'authors' in entity['value']:
                        pub_ent['value']['authors'] = authors[entity['uuid']]
                        _set_authors(pub_ent, pub_dict)
            
    # weird key swap for old issues with awardnumber(s)
    award_number = prj.award_number or []
    if not isinstance(award_number, list):
        award_number = []
    prj_dict['value']['awardNumbers'] = award_number
    prj_dict['value'].pop('awardNumber', None)

    for key in prj_dict['value']:
        if key not in UNAMENDABLE_FIELDS['project']:
            pub_dict['project']['value'][key] = prj_dict['value'][key]
    if authors and prj_dict['value']['projectType'] == 'other':
        pub_dict['project']['value']['teamOrder'] = authors

    pub.update(**pub_dict)
    IndexedPublication._index.refresh(using=es_client)
    return pub
Exemple #7
0
def publish_resource(project_id, entity_uuids=None, publish_dois=False):
    """Publish a resource.

    Retrieves a project and/or an entity and set any saved DOIs
    as published. If no DOIs are saved in the specified project or entity
    it will fail silently. We need to specify the project id because
    this function also changes the status of the locally saved publication
    to `"published"` that way it shows up in the published listing.

    If publish_dois is False Datacite will keep the newly created DOIs in
    "DRAFT" status, but they will not be set to "PUBLISHED". A DOI on
    DataCite can only be deleted if it is in "DRAFT" status. Once a DOI
    is set to "PUBLISHED" or "RESERVED" it can't be deleted.

    :param str project_id: Project Id to publish.
    :param list entity_uuids: list of str Entity uuids to publish.
    """
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    responses = []

    if publish_dois:
        for ent_uuid in entity_uuids:
            entity = None
            if ent_uuid:
                entity = mgr.get_entity_by_uuid(ent_uuid)
            
            if entity:
                for doi in entity.dois:
                    res = DataciteManager.publish_doi(doi)
                    responses.append(res)
        
        for doi in prj.dois:
            res = DataciteManager.publish_doi(doi)
            responses.append(res)


    pub = BaseESPublication(project_id=project_id)
    pub.update(status='published')

    for res in responses:
        LOG.info(
            "DOI published: %(doi)s",
            {"doi": res['data']['id']}
        )
    return responses
Exemple #8
0
def draft_publication(
    project_id,
    main_entity_uuid=None,
    project_doi=None,
    main_entity_doi=None,
    upsert_project_doi=False,
    upsert_main_entity_doi=True,
):
    """Reserve a publication.

    A publication is reserved by creating a DOI through Datacite.
    For some of the projects a DOI is only created for the main entity
    e.g. Mission or Simulation. For some other projects we also (or only)
    get a DOI for the project.
    - If :param:`project_doi` and/or :param:`main_entity_doi` values are given
    then those dois will be updated (or created if they don't exist in datacite).
    - If :param:`upsert_project_doi` and/or :param:`upsert_main_entity_doi` are
    set to `True` then any saved DOIs will be updated (even if there's multiple
    unless a specific DOI is given). If there are no saved DOIs then a new DOI
    will be created. Meaning, it will act as update or insert.
    - If :param:`project_id` is given **but** :param:`main_entity_uuid` is ``None``
    then a project DOI will be created or updated.

    .. warning:: This funciton only creates a *Draft* DOI and not a public one.

    .. warning:: An entity *might* have multiple DOIs, if this is the case and
    :param:`upsert_project_doi` or :param:`upsert_main_entity_doi` are set to True
    then *all* saved dois will be updated.

    .. note:: In theory a single resource *should not* have multiple DOIs
    but we don't know how this will change in the future, hence, we are
    supporting multiple DOIs.

    .. note:: If no :param:`main_entity_uuid` is given then a project DOI will be
    created.

    :param str project_id: Project Id
    :param str main_entity_uuid: Uuid of main entity.
    :param str project_doi: Custom doi for project.
    :param str main_entity_doi: Custom doi for main entity.
    :param bool upsert_project_doi: Update or insert project doi.
    :param bool upsert_main_entity_doi: Update or insert main entity doi.
    """
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    entity = None
    if main_entity_uuid:
        entity = mgr.get_entity_by_uuid(main_entity_uuid)
    else:
        upsert_project_doi = True

    responses = []
    prj_url = TARGET_BASE.format(project_id=project_id)
    if entity:
        entity_url = ENTITY_TARGET_BASE.format(project_id=project_id,
                                               entity_uuid=main_entity_uuid)
    prj_datacite_json = prj.to_datacite_json()
    prj_datacite_json['url'] = prj_url
    if entity:
        ent_datacite_json = entity.to_datacite_json()
        ent_datacite_json['url'] = entity_url

    if upsert_project_doi and project_doi:
        prj_res = DataciteManager.create_or_update_doi(prj_datacite_json,
                                                       project_doi)
        prj.dois += [project_doi]
        prj.dois = list(set(prj.dois))
        prj.save(service_account())
        responses.append(prj_res)
    elif upsert_project_doi and prj.dois:
        for doi in prj.dois:
            prj_res = DataciteManager.create_or_update_doi(
                prj_datacite_json, doi)
            responses.append(prj_res)
    elif upsert_project_doi and not prj.dois:
        prj_res = DataciteManager.create_or_update_doi(prj_datacite_json)
        prj.dois += [prj_res['data']['id']]
        prj.save(service_account())
        responses.append(prj_res)

    if entity and upsert_main_entity_doi and main_entity_doi:
        me_res = DataciteManager.create_or_update_doi(ent_datacite_json,
                                                      main_entity_doi)
        entity.dois += [main_entity_doi]
        entity.dois = list(set(entity.dois))
        entity.save(service_account())
        responses.append(me_res)
    elif entity and upsert_main_entity_doi and entity.dois:
        for doi in entity.dois:
            me_res = DataciteManager.create_or_update_doi(
                ent_datacite_json, doi)
            responses.append(me_res)
    elif entity and upsert_main_entity_doi and not entity.dois:
        me_res = DataciteManager.create_or_update_doi(ent_datacite_json)
        entity.dois += [me_res['data']['id']]
        entity.save(service_account())
        responses.append(me_res)

    for res in responses:
        LOG.info("DOI created or updated: %(doi)s", {"doi": res['data']['id']})
    return responses
Exemple #9
0
def freeze_project_and_entity_metadata(project_id, entity_uuids=None):
    """Freeze project and entity metadata.

    Given a project id and an entity uuid (should be a main entity) this function
    retrieves all metadata related to these entities and stores it into Elasticsearch
    as :class:`~designafe.libs.elasticsearch.docs.publications.BaseESPublication`

    When publishing for the first time or publishing over an existing publication. We
    will clear any existing entities (if any) from the published metadata. We'll use entity_uuids
    (the entities getting DOIs) to rebuild the rest of the publication. These entities
    usually do not have files associated to them (except published reports/documents).

    :param str project_id: Project id.
    :param list of entity_uuid strings: Entity uuids.
    """
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    pub_doc = BaseESPublication(project_id=project_id)
    publication = pub_doc.to_dict()

    if entity_uuids:
        # clear any existing sub entities in publication and keep updated fileObjs
        fields_to_clear = []
        entities_with_files = []
        for key in list(FIELD_MAP.keys()):
            if FIELD_MAP[key] in list(publication.keys()):
                fields_to_clear.append(FIELD_MAP[key])
        fields_to_clear = set(fields_to_clear)

        for field in fields_to_clear:
            for ent in publication[field]:
                if 'fileObjs' in ent:
                    entities_with_files.append(ent)
                if ent['uuid'] in entity_uuids:
                    publication[field] = []

        for ent_uuid in entity_uuids:
            entity = None
            entity = mgr.get_entity_by_uuid(ent_uuid)

            if entity:
                entity_json = entity.to_body_dict()
                pub_entities_field_name = FIELD_MAP[entity.name]

                for e in entities_with_files:
                    if e['uuid'] == entity_json['uuid']:
                        entity_json['fileObjs'] = e['fileObjs']

                publication['authors'] = list(entity_json['value']['authors'])
                entity_json['authors'] = []

                _populate_entities_in_publication(entity, publication)
                _transform_authors(entity_json, publication)

                if entity_json['value']['dois']:
                    entity_json['doi'] = entity_json['value']['dois'][-1]
                
                _delete_unused_fields(entity_json)
                publication[pub_entities_field_name].append(entity_json)

    prj_json = prj.to_body_dict()
    _delete_unused_fields(prj_json)

    award_number = publication.get('project', {}).get('value', {}).pop(
        'awardNumber', []
    ) or []

    if not isinstance(award_number, list):
        award_number = []

    prj_json['value']['awardNumbers'] = award_number
    prj_json['value'].pop('awardNumber', None)
    if publication.get('project'):
        publication['project'].update(prj_json)
    else:
        publication['project'] = prj_json

    pub_doc.update(**publication)
    return pub_doc
Exemple #10
0
def draft_publication(
    project_id,
    main_entity_uuids=None,
    project_doi=None,
    main_entity_doi=None,
    upsert_project_doi=False,
    upsert_main_entity_doi=True,
    revision=None,
    revised_authors=None
):
    """Reserve a publication.

    A publication is reserved by creating a DOI through Datacite.
    For some of the projects a DOI is only created for the main entity
    e.g. Mission or Simulation. For some other projects we also (or only)
    get a DOI for the project.
    - If :param:`project_doi` and/or :param:`main_entity_doi` values are given
    then those dois will be updated (or created if they don't exist in datacite).
    - If :param:`upsert_project_doi` and/or :param:`upsert_main_entity_doi` are
    set to `True` then any saved DOIs will be updated (even if there's multiple
    unless a specific DOI is given). If there are no saved DOIs then a new DOI
    will be created. Meaning, it will act as update or insert.
    - If :param:`project_id` is given **but** :param:`main_entity_uuids` is ``None``
    then a project DOI will be created or updated.

    .. warning:: This funciton only creates a *Draft* DOI and not a public one.

    .. warning:: An entity *might* have multiple DOIs, if this is the case and
    :param:`upsert_project_doi` or :param:`upsert_main_entity_doi` are set to True
    then *all* saved dois will be updated.

    .. note:: In theory a single resource *should not* have multiple DOIs
    but we don't know how this will change in the future, hence, we are
    supporting multiple DOIs.

    .. note:: If no :param:`main_entity_uuids` is given then a project DOI will be
    created.

    :param str project_id: Project Id
    :param list main_entity_uuids: uuid strings of main entities.
    :param str project_doi: Custom doi for project.
    :param str main_entity_doi: Custom doi for main entity.
    :param bool upsert_project_doi: Update or insert project doi.
    :param bool upsert_main_entity_doi: Update or insert main entity doi.
    """
    mgr = ProjectsManager(service_account())
    prj = mgr.get_project_by_id(project_id)
    responses = []

    if main_entity_uuids:
        ### Draft Entity DOI(s) ###
        pub = BaseESPublication(project_id=project_id, revision=revision)
        for ent_uuid in main_entity_uuids:
            entity = mgr.get_entity_by_uuid(ent_uuid)
            if entity:
                if revision:
                    entity_url = ENTITY_TARGET_BASE.format(
                        project_id='{}v{}'.format(project_id, revision),
                        entity_uuid=ent_uuid
                    )
                    original_entities = getattr(pub, FIELD_MAP[entity.name])
                    pub_ent = next(ent for ent in original_entities if ent.uuid == ent_uuid)

                    entity.title = pub_ent.value.title
                    entity.authors = revised_authors[ent_uuid]
                else:
                    entity_url = ENTITY_TARGET_BASE.format(
                        project_id=project_id,
                        entity_uuid=ent_uuid
                    )
                ent_datacite_json = entity.to_datacite_json()
                ent_datacite_json['url'] = entity_url
                # ent_datacite_json['version'] = str(revision) # omitting version number per Maria

                if upsert_main_entity_doi and main_entity_doi:
                    me_res = DataciteManager.create_or_update_doi(
                        ent_datacite_json,
                        main_entity_doi
                    )
                    entity.dois += [main_entity_doi]
                    entity.dois = list(set(entity.dois))
                    entity.save(service_account())
                    responses.append(me_res)
                elif upsert_main_entity_doi and entity.dois:
                    for doi in entity.dois:
                        me_res = DataciteManager.create_or_update_doi(
                            ent_datacite_json,
                            doi
                        )
                        responses.append(me_res)
                elif upsert_main_entity_doi and not entity.dois:
                    me_res = DataciteManager.create_or_update_doi(
                        ent_datacite_json
                    )
                    entity.dois += [me_res['data']['id']]
                    entity.save(service_account())
                    responses.append(me_res)
    else:
        ### Draft Project DOI ###
        upsert_project_doi = True
        if revision:
            # Versions should not update certain fields
            # Add version number to DataCite info
            prj_url = TARGET_BASE.format(project_id='{}v{}'.format(project_id, revision))
            pub = BaseESPublication(project_id=project_id, revision=revision)
            prj.title = pub.project.value.title
            prj.team_order = pub.project.value.teamOrder
            if revised_authors:
                prj.team_order = revised_authors
            prj_datacite_json = prj.to_datacite_json()
            prj_datacite_json['url'] = prj_url
            prj_datacite_json['version'] = str(revision)
            # append links to previous versions in DOI...
            relatedIdentifiers = []
            for ver in range(1, revision):
                id = '{}v{}'.format(project_id, ver) if ver!=1 else project_id
                relatedIdentifiers.append(
                    {
                    'relatedIdentifierType': 'URL',
                    'relationType': 'IsNewVersionOf',
                    'relatedIdentifier': TARGET_BASE.format(project_id=id),
                    }
                )
            prj_datacite_json['relatedIdentifiers'] = relatedIdentifiers
        else:
            # format project for publication
            prj_url = TARGET_BASE.format(project_id=project_id)
            prj_datacite_json = prj.to_datacite_json()
            prj_datacite_json['url'] = prj_url


    if upsert_project_doi and project_doi:
        prj_res = DataciteManager.create_or_update_doi(
            prj_datacite_json,
            project_doi
        )
        prj.dois += [project_doi]
        prj.dois = list(set(prj.dois))
        prj.save(service_account())
        responses.append(prj_res)
    elif upsert_project_doi and prj.dois:
        for doi in prj.dois:
            prj_res = DataciteManager.create_or_update_doi(
                prj_datacite_json,
                doi
            )
            responses.append(prj_res)
    elif upsert_project_doi and not prj.dois:
        prj_res = DataciteManager.create_or_update_doi(prj_datacite_json)
        prj.dois += [prj_res['data']['id']]
        prj.save(service_account())
        responses.append(prj_res)

    for res in responses:
        logger.info(
            "DOI created or updated: %(doi)s",
            {"doi": res['data']['id']}
        )
    return responses