Exemple #1
0
def test_delete_organisation(reindex, db, minimal_organisation_record,
                             minimal_member_record):
    """Test Organisation delete."""
    org = OrganisationWithMembers.create(minimal_organisation_record,
                                         dbcommit=True)
    member1 = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    pid1 = PersistentIdentifier.get_by_object('memb', 'rec', member1.id)
    member2 = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    pid2 = PersistentIdentifier.get_by_object('memb', 'rec', member2.id)
    member3 = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    pid3 = PersistentIdentifier.get_by_object('memb', 'rec', member3.id)
    org.add_member(member1, dbcommit=True)
    org.add_member(member2, dbcommit=True)
    org.add_member(member3, dbcommit=True)
    assert OrganisationsMembersMetadata.query.count() == 3
    assert RecordMetadata.query.count() == 4
    assert pid1.is_registered()
    assert pid2.is_registered()
    assert pid3.is_registered()
    org.delete(force=True)
    assert OrganisationsMembersMetadata.query.count() == 0
    assert RecordMetadata.query.count() == 0
    assert pid1.is_deleted()
    assert pid2.is_deleted()
    assert pid3.is_deleted()
Exemple #2
0
def test_delete_member(reindex, db, minimal_member_record,
                       minimal_location_record):
    """Test Member delete."""
    memb = MemberWithLocations.create(minimal_member_record)
    location1 = Location.create(minimal_location_record)
    memb.add_location(location1)
    pid1 = PersistentIdentifier.get_by_object('loc', 'rec', location1.id)
    location2 = Location.create(minimal_location_record)
    memb.add_location(location2)
    pid2 = PersistentIdentifier.get_by_object('loc', 'rec', location2.id)
    location3 = Location.create(minimal_location_record)
    memb.add_location(location3)
    pid3 = PersistentIdentifier.get_by_object('loc', 'rec', location3.id)
    memb.dbcommit()
    assert MembersLocationsMetadata.query.count() == 3
    assert RecordMetadata.query.count() == 4
    assert pid1.is_registered()
    assert pid2.is_registered()
    assert pid3.is_registered()
    memb.delete(force=True)
    assert MembersLocationsMetadata.query.count() == 0
    assert RecordMetadata.query.count() == 0
    assert pid1.is_deleted()
    assert pid2.is_deleted()
    assert pid3.is_deleted()
Exemple #3
0
def zenodo_doi_updater(record_uuid, data):
    """Update the DOI (only external DOIs)."""
    assert 'recid' in data
    doi = data.get('doi')
    assert doi
    assert idutils.is_doi(doi)

    # If the DOI is the same as an already generated one, do nothing
    if doi == doi_generator(data['recid']):
        return
    if is_local_doi(doi):  # Zenodo DOI, but different than recid
        # ERROR, user provided a custom ZENODO DOI!
        raise PIDValueError('doi', doi)

    doi_pid = PersistentIdentifier.get_by_object(
        pid_type='doi', object_type='rec', object_uuid=record_uuid)

    if doi_pid.pid_value != doi:
        with db.session.begin_nested():
            db.session.delete(doi_pid)
            return PersistentIdentifier.create(
                'doi',
                doi,
                object_type='rec',
                object_uuid=record_uuid,
                status=PIDStatus.RESERVED,
            )
Exemple #4
0
def zenodo_doi_updater(record_uuid, data):
    """Update the DOI (only external DOIs)."""
    assert 'recid' in data
    doi = data.get('doi')
    assert doi
    assert idutils.is_doi(doi)

    # If the DOI is the same as an already generated one, do nothing
    if doi == doi_generator(data['recid']):
        return
    if is_local_doi(doi):  # Zenodo DOI, but different than recid
        # ERROR, user provided a custom ZENODO DOI!
        raise PIDValueError('doi', doi)

    doi_pid = PersistentIdentifier.get_by_object(
        pid_type='doi', object_type='rec', object_uuid=record_uuid)

    if doi_pid.pid_value != doi:
        with db.session.begin_nested():
            db.session.delete(doi_pid)
            return PersistentIdentifier.create(
                'doi',
                doi,
                object_type='rec',
                object_uuid=record_uuid,
                status=PIDStatus.RESERVED,
            )
Exemple #5
0
def test_pid_get(app):
    """Test pid retrieval."""
    with app.app_context():
        PersistentIdentifier.create('doi', '10.1234/foo')
        assert PersistentIdentifier.get('doi', '10.1234/foo')
        pytest.raises(PIDDoesNotExistError, PersistentIdentifier.get, 'doi',
                      '10.1234/bar')

        # PID with provider
        doi = '10.1234/a'
        PersistentIdentifier.create('doi', doi, pid_provider='dcite')
        assert PersistentIdentifier.get('doi', doi)
        assert PersistentIdentifier.get('doi', doi, pid_provider='dcite')
        pytest.raises(PIDDoesNotExistError,
                      PersistentIdentifier.get,
                      'doi',
                      doi,
                      pid_provider='cref')

        # Retrieve by object
        myuuid = uuid.uuid4()
        doi = '10.1234/b'
        PersistentIdentifier.create('doi',
                                    doi,
                                    object_type='rec',
                                    object_uuid=myuuid)
        pid = PersistentIdentifier.get_by_object('doi', 'rec', myuuid)
        assert pid.pid_value == doi

        pytest.raises(PIDDoesNotExistError, PersistentIdentifier.get_by_object,
                      'doi', 'rec', uuid.uuid4())
def transfer_cp(uuid, destination):
    """Transfer the files contained in the record to the destination.

    This method is automatically called by the module to transfer the files.
    Depending on your installation, you may want to have a different behavior
    (copy among servers...). Then, you can create your own factory and link it
    into the config variable
    :py:data:`invenio_archivematica.config.ARCHIVEMATICA_TRANSFER_FACTORY`.

    :param uuid: the id of the record containing files to transfer
    :param destination: the destination folder - this will be what is
        inside the config variable
        :py:data:`invenio_archivematica.config.ARCHIVEMATICA_TRANSFER_FOLDER`.
        It needs to be a absolute path to a folder
    """
    record = Record.get_record(uuid)
    pid = PersistentIdentifier.get_by_object("recid", "rec", uuid)
    dir_name = join(destination,
                    create_accessioned_id(pid.pid_value, 'recid'))
    try:
        mkdir(dir_name)
    except:
        pass
    for fileobj in record.files:
        copyfile(fileobj.file.storage().fileurl,
                 join(dir_name, fileobj.key))
Exemple #7
0
 def get_persistent_identifier(cls, id):
     """Get Persistent Identifier."""
     return PersistentIdentifier.get_by_object(
         cls.provider.pid_type,
         cls.object_type,
         id
     )
Exemple #8
0
def cancel_action(activity_id='0', action_id=0):
    """Next action."""
    post_json = request.get_json()
    work_activity = WorkActivity()

    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_json.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_CANCELED,
                    commond=post_json.get('commond'))

    # clear deposit
    activity_detail = work_activity.get_activity_detail(activity_id)
    if activity_detail is not None:
        cancel_item_id = activity_detail.item_id
        if cancel_item_id is None:
            pid_value = post_json.get('pid_value')
            if pid_value is not None:
                pid = PersistentIdentifier.get('recid', pid_value)
                cancel_item_id = pid.object_uuid
        if cancel_item_id is not None:
            cancel_record = WekoDeposit.get_record(cancel_item_id)
            if cancel_record is not None:
                cancel_deposit = WekoDeposit(cancel_record,
                                             cancel_record.model)
                cancel_deposit.clear()
                # Remove draft child
                cancel_pid = PersistentIdentifier.get_by_object(
                    pid_type='recid',
                    object_type='rec',
                    object_uuid=cancel_item_id)
                cancel_pv = PIDVersioning(child=cancel_pid)
                if cancel_pv.exists:
                    previous_pid = cancel_pv.previous
                    if previous_pid is not None:
                        activity.update(dict(item_id=previous_pid.object_uuid))
                    cancel_pv.remove_child(cancel_pid)

    work_activity.upt_activity_action_status(
        activity_id=activity_id,
        action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_CANCELED)

    rtn = work_activity.quit_activity(activity)

    if rtn is None:
        work_activity.upt_activity_action_status(
            activity_id=activity_id,
            action_id=action_id,
            action_status=ActionStatusPolicy.ACTION_DOING)
        return jsonify(code=-1, msg=_('Error! Cannot process quit activity!'))

    return jsonify(code=0,
                   msg=_('success'),
                   data={
                       'redirect':
                       url_for('weko_workflow.display_activity',
                               activity_id=activity_id)
                   })
Exemple #9
0
    def get_persistent_identifier(cls, identifier):
        """Get persistent identifier object.

        :param identifier: Record UUID.
        :returns: PID instance of record.
        """
        return PersistentIdentifier.get_by_object(cls.provider.pid_type,
                                                  cls.object_type, identifier)
Exemple #10
0
def previous_action(activity_id='0', action_id=0, req=0):
    """Previous action."""
    post_data = request.get_json()
    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_data.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_THROWN_OUT
                    if 0 == req else ActionStatusPolicy.ACTION_RETRY,
                    commond=post_data.get('commond'))
    work_activity = WorkActivity()
    history = WorkActivityHistory()
    rtn = history.create_activity_history(activity)
    if rtn is None:
        return jsonify(code=-1, msg=_('error'))

    # next action
    activity_detail = work_activity.get_activity_detail(activity_id)
    flow = Flow()

    try:
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='doi',
            object_type='rec',
            object_uuid=activity_detail.item_id)
        with db.session.begin_nested():
            db.session.delete(pid_identifier)
        db.session.commit()
    except PIDDoesNotExistError as pidNotEx:
        current_app.logger.info(pidNotEx)

    if req == 0:
        pre_action = flow.get_previous_flow_action(
            activity_detail.flow_define.flow_id, action_id)
    else:
        pre_action = flow.get_next_flow_action(
            activity_detail.flow_define.flow_id, 1)

    if pre_action and len(pre_action) > 0:
        previous_action_id = pre_action[0].action_id
        if req == 0:
            work_activity.upt_activity_action_status(
                activity_id=activity_id,
                action_id=action_id,
                action_status=ActionStatusPolicy.ACTION_THROWN_OUT)
        else:
            work_activity.upt_activity_action_status(
                activity_id=activity_id,
                action_id=action_id,
                action_status=ActionStatusPolicy.ACTION_RETRY)
        work_activity.upt_activity_action_status(
            activity_id=activity_id,
            action_id=previous_action_id,
            action_status=ActionStatusPolicy.ACTION_DOING)
        work_activity.upt_activity_action(
            activity_id=activity_id,
            action_id=previous_action_id,
            action_status=ActionStatusPolicy.ACTION_DOING)
    return jsonify(code=0, msg=_('success'))
Exemple #11
0
def withdraw_confirm(activity_id='0', action_id='0'):
    """Check weko user info.

    :return:
    """
    try:
        post_json = request.get_json()
        password = post_json.get('passwd', None)
        if not password:
            return jsonify(code=-1, msg=_('Password not provided'))
        wekouser = ShibUser()
        if wekouser.check_weko_user(current_user.email, password):
            activity = WorkActivity()
            item_id = activity.get_activity_detail(activity_id).item_id
            identifier_actionid = get_actionid('identifier_grant')
            identifier = activity.get_action_identifier_grant(
                activity_id, identifier_actionid)
            identifier_handle = IdentifierHandle(item_id)

            if identifier_handle.delete_pidstore_doi():
                identifier['action_identifier_select'] = \
                    IDENTIFIER_GRANT_IS_WITHDRAWING
                if identifier:
                    activity.create_or_update_action_identifier(
                        activity_id, identifier_actionid, identifier)
                    current_pid = PersistentIdentifier.get_by_object(
                        pid_type='recid',
                        object_type='rec',
                        object_uuid=item_id)
                    recid = get_record_identifier(current_pid.pid_value)
                    if not recid:
                        pid_without_ver = get_record_without_version(
                            current_pid)
                        record_without_ver_activity_id = \
                            get_activity_id_of_record_without_version(
                                pid_without_ver)
                        if record_without_ver_activity_id is not None:
                            activity.create_or_update_action_identifier(
                                record_without_ver_activity_id,
                                identifier_actionid, identifier)

                return jsonify(code=0,
                               msg=_('success'),
                               data={
                                   'redirect':
                                   url_for('weko_workflow.display_activity',
                                           activity_id=activity_id)
                               })
            else:
                return jsonify(code=-1, msg=_('DOI Persistent is not exist.'))
        else:
            return jsonify(code=-1, msg=_('Invalid password'))
    except ValueError:
        current_app.logger.error('Unexpected error: {}', sys.exc_info()[0])
    return jsonify(code=-1, msg=_('Error!'))
Exemple #12
0
    def get_all_pids(cls):
        """Get all location pids."""
        members_locations = MembersLocationsMetadata.query.all()

        locs_id = []

        for member_location in members_locations:
            loc_id = member_location.location_id
            pid = PersistentIdentifier.get_by_object('loc', 'rec', loc_id)
            locs_id.append(pid.pid_value)

        return locs_id
Exemple #13
0
def migrate_record(record_uuid, logger=None):
    """Migrate a record."""
    try:
        # Migrate record
        record = Record.get_record(record_uuid)
        if '$schema' in record:
            if logger:
                logger.info("Record already migrated.")
            return
        record = transform_record(record)
        provisional_communities = record.pop('provisional_communities', None)
        record.commit()
        # Create provisional communities.
        if provisional_communities:
            for c_id in provisional_communities:
                try:
                    c = Community.get(c_id)
                    if c:
                        InclusionRequest.create(c, record, notify=False)
                    else:
                        if logger:
                            logger.warning(
                                "Community {0} does not exists "
                                "(record {1}).".format(
                                    c_id, str(record.id)))
                except InclusionRequestExistsError:
                    if logger:
                        logger.warning("Inclusion request exists.")
        # Register DOI
        doi = record.get('doi')
        if doi:
            is_internal = doi.startswith('10.5281')
            PersistentIdentifier.create(
                pid_type='doi',
                pid_value=doi,
                pid_provider='datacite' if is_internal else None,
                object_type='rec',
                object_uuid=record_uuid,
                status=(
                    PIDStatus.REGISTERED if is_internal
                    else PIDStatus.RESERVED),
            )
        db.session.commit()
    except NoResultFound:
        if logger:
            logger.info("Deleted record - no migration required.")
    except Exception:
        db.session.rollback()
        pid = PersistentIdentifier.get_by_object('recid', 'rec', record_uuid)
        pid.status = PIDStatus.RESERVED
        db.session.commit()
        raise
Exemple #14
0
def migrate_record(record_uuid, logger=None):
    """Migrate a record."""
    try:
        # Migrate record
        record = Record.get_record(record_uuid)
        if '$schema' in record:
            if logger:
                logger.info("Record already migrated.")
            return
        record = transform_record(record)
        provisional_communities = record.pop('provisional_communities', None)
        record.commit()
        # Create provisional communities.
        if provisional_communities:
            for c_id in provisional_communities:
                try:
                    c = Community.get(c_id)
                    if c:
                        InclusionRequest.create(c, record, notify=False)
                    else:
                        if logger:
                            logger.warning("Community {0} does not exists "
                                           "(record {1}).".format(
                                               c_id, str(record.id)))
                except InclusionRequestExistsError:
                    if logger:
                        logger.warning("Inclusion request exists.")
        # Register DOI
        doi = record.get('doi')
        if doi:
            is_internal = doi.startswith('10.5281')
            PersistentIdentifier.create(
                pid_type='doi',
                pid_value=doi,
                pid_provider='datacite' if is_internal else None,
                object_type='rec',
                object_uuid=record_uuid,
                status=(PIDStatus.REGISTERED
                        if is_internal else PIDStatus.RESERVED),
            )
        db.session.commit()
    except NoResultFound:
        if logger:
            logger.info("Deleted record - no migration required.")
    except Exception:
        db.session.rollback()
        pid = PersistentIdentifier.get_by_object('recid', 'rec', record_uuid)
        pid.status = PIDStatus.RESERVED
        db.session.commit()
        raise
Exemple #15
0
def getrecord_fetcher(record_id):
    """Fetch record data as dict with identity check for serialization."""
    recid = PersistentIdentifier.get_by_object(pid_type='recid',
                                               object_uuid=record_id,
                                               object_type='rec')

    try:
        result = current_rdm_records.records_service.read(
            g.identity, recid.pid_value)
    except PermissionDeniedError:
        # if it is a restricted record.
        raise PIDDoesNotExistError('recid', None)

    return result.to_dict()
Exemple #16
0
def test_delete_location(reindex, db, minimal_member_record,
                         minimal_location_record):
    """Test MembersLocations delete."""
    memb = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    location = Location.create(minimal_location_record, dbcommit=True)
    memb.add_location(location, dbcommit=True)
    pid = PersistentIdentifier.get_by_object('loc', 'rec', location.id)
    assert pid.is_registered()
    memb.remove_location(location)
    assert pid.is_deleted()
    assert memb.locations == []

    location1 = Location.create(minimal_location_record, dbcommit=True)
    memb.add_location(location1, dbcommit=True)
    location2 = Location.create(minimal_location_record, dbcommit=True)
    memb.add_location(location2, dbcommit=True)
    location3 = Location.create(minimal_location_record, dbcommit=True)
    memb.add_location(location3, dbcommit=True)
    memb.remove_location(location2)
    assert len(memb.locations) == 2
    assert memb.locations[0]['pid'] == '2'
    assert memb.locations[1]['pid'] == '4'
Exemple #17
0
def test_delete_member(reindex, db, minimal_organisation_record,
                       minimal_member_record):
    """Test OrganisationsMembers delete."""
    org = OrganisationWithMembers.create(minimal_organisation_record,
                                         dbcommit=True)
    member = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    org.add_member(member, dbcommit=True)
    pid = PersistentIdentifier.get_by_object('memb', 'rec', member.id)
    assert pid.is_registered()
    org.remove_member(member)
    assert pid.is_deleted()
    assert org.members == []

    member1 = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    org.add_member(member1, dbcommit=True)
    member2 = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    org.add_member(member2, dbcommit=True)
    member3 = MemberWithLocations.create(minimal_member_record, dbcommit=True)
    org.add_member(member3, dbcommit=True)
    org.remove_member(member2)
    assert len(org.members) == 2
    assert org.members[0]['pid'] == '2'
    assert org.members[1]['pid'] == '4'
def test_pid_get(app):
    """Test pid retrieval."""
    with app.app_context():
        PersistentIdentifier.create('doi', '10.1234/foo')
        assert PersistentIdentifier.get('doi', '10.1234/foo')
        pytest.raises(
            PIDDoesNotExistError,
            PersistentIdentifier.get,
            'doi', '10.1234/bar'
        )

        # PID with provider
        doi = '10.1234/a'
        PersistentIdentifier.create('doi', doi, pid_provider='dcite')
        assert PersistentIdentifier.get('doi', doi)
        assert PersistentIdentifier.get(
            'doi', doi, pid_provider='dcite')
        pytest.raises(
            PIDDoesNotExistError,
            PersistentIdentifier.get,
            'doi', doi, pid_provider='cref'
        )

        # Retrieve by object
        myuuid = uuid.uuid4()
        doi = '10.1234/b'
        PersistentIdentifier.create(
            'doi', doi, object_type='rec', object_uuid=myuuid)
        pid = PersistentIdentifier.get_by_object('doi', 'rec', myuuid)
        assert pid.pid_value == doi

        pytest.raises(
            PIDDoesNotExistError,
            PersistentIdentifier.get_by_object,
            'doi', 'rec', uuid.uuid4()
        )
Exemple #19
0
def delete_pid_after_record_deletion(sender, record):
    pid = PersistentIdentifier.get_by_object('recid', 'rec', record.id)
    pid.delete()
    db.session.commit()
Exemple #20
0
def next_action(activity_id='0', action_id=0):
    """Next action."""
    post_json = request.get_json()
    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_json.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_DONE,
                    commond=post_json.get('commond'))

    work_activity = WorkActivity()

    history = WorkActivityHistory()
    action = Action().get_action_detail(action_id)
    action_endpoint = action.action_endpoint

    if (1 == post_json.get('temporary_save')
            and action_endpoint != 'identifier_grant'):
        if 'journal' in post_json:
            work_activity.create_or_update_action_journal(
                activity_id=activity_id,
                action_id=action_id,
                journal=post_json.get('journal'))
        else:
            work_activity.upt_activity_action_comment(
                activity_id=activity_id,
                action_id=action_id,
                comment=post_json.get('commond'))
        return jsonify(code=0, msg=_('success'))
    elif post_json.get('journal'):
        work_activity.create_or_update_action_journal(
            activity_id=activity_id,
            action_id=action_id,
            journal=post_json.get('journal'))

    if 'begin_action' == action_endpoint:
        return jsonify(code=0, msg=_('success'))

    if 'end_action' == action_endpoint:
        work_activity.end_activity(activity)
        return jsonify(code=0, msg=_('success'))

    if 'approval' == action_endpoint:
        activity_obj = WorkActivity()
        activity_detail = activity_obj.get_activity_detail(activity_id)
        item = None
        if activity_detail is not None and activity_detail.item_id is not None:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
            pid_identifier = PersistentIdentifier.get_by_object(
                pid_type='depid', object_type='rec', object_uuid=item.id)
            record_class = import_string('weko_deposit.api:WekoRecord')
            resolver = Resolver(pid_type='recid',
                                object_type='rec',
                                getter=record_class.get_record)
            pid, approval_record = resolver.resolve(pid_identifier.pid_value)

            # TODO: Make private as default.
            # UpdateItem.publish(pid, approval_record)

    if 'item_link' == action_endpoint:
        relation_data = post_json.get('link_data'),
        activity_obj = WorkActivity()
        activity_detail = activity_obj.get_activity_detail(activity_id)
        item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        pid, item_record = resolver.resolve(pid_identifier.pid_value)
        updated_item = UpdateItem()
        updated_item.set_item_relation(relation_data, item_record)

    # save pidstore_identifier to ItemsMetadata
    idf_grant = post_json.get('identifier_grant')
    if 'identifier_grant' == action_endpoint and idf_grant is not None:
        idf_grant_jalc_doi_manual = post_json.get(
            'identifier_grant_jalc_doi_suffix')
        idf_grant_jalc_cr_doi_manual = post_json.get(
            'identifier_grant_jalc_cr_doi_suffix')
        idf_grant_jalc_dc_doi_manual = post_json.get(
            'identifier_grant_jalc_dc_doi_suffix')

        # If is action identifier_grant, then save to to database
        identifier_grant = {
            'action_identifier_select': idf_grant,
            'action_identifier_jalc_doi': idf_grant_jalc_doi_manual,
            'action_identifier_jalc_cr_doi': idf_grant_jalc_cr_doi_manual,
            'action_identifier_jalc_dc_doi': idf_grant_jalc_dc_doi_manual
        }

        work_activity.create_or_update_action_identifier(
            activity_id=activity_id,
            action_id=action_id,
            identifier=identifier_grant)
        if post_json.get('temporary_save') != 1:
            pidstore_identifier_mapping(post_json, int(idf_grant), activity_id)
        else:
            return jsonify(code=0, msg=_('success'))

    rtn = history.create_activity_history(activity)
    if rtn is None:
        return jsonify(code=-1, msg=_('error'))
    # next action
    activity_detail = work_activity.get_activity_detail(activity_id)
    work_activity.upt_activity_action_status(
        activity_id=activity_id,
        action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_DONE)
    work_activity.upt_activity_action_comment(activity_id=activity_id,
                                              action_id=action_id,
                                              comment='')
    flow = Flow()
    next_flow_action = flow.get_next_flow_action(
        activity_detail.flow_define.flow_id, action_id)
    if next_flow_action and len(next_flow_action) > 0:
        next_action_endpoint = next_flow_action[0].action.action_endpoint
        if 'end_action' == next_action_endpoint:
            if activity_detail is not None and \
                    activity_detail.item_id is not None:
                record = WekoDeposit.get_record(activity_detail.item_id)
                if record is not None:
                    deposit = WekoDeposit(record, record.model)
                    deposit.publish()
                    # For current item: Make status Public as default
                    updated_item = UpdateItem()
                    updated_item.publish(record)
                    # For previous item: Update status to Private
                    current_pid = PersistentIdentifier.get_by_object(
                        pid_type='recid',
                        object_type='rec',
                        object_uuid=activity_detail.item_id)
                    current_pv = PIDVersioning(child=current_pid)
                    if current_pv.exists and current_pv.previous is not None:
                        prev_record = WekoDeposit.get_record(
                            current_pv.previous.object_uuid)
                        if prev_record is not None:
                            updated_item.update_status(prev_record)
            activity.update(
                action_id=next_flow_action[0].action_id,
                action_version=next_flow_action[0].action_version,
            )
            work_activity.end_activity(activity)
        else:
            next_action_id = next_flow_action[0].action_id
            work_activity.upt_activity_action(
                activity_id=activity_id,
                action_id=next_action_id,
                action_status=ActionStatusPolicy.ACTION_DOING)
    return jsonify(code=0, msg=_('success'))
Exemple #21
0
def delete(pid=None, record=None, depid=None, deposit=None):
    """Delete a record."""
    # View disabled until properly implemented and tested.
    try:
        doi = PersistentIdentifier.get_by_object('doi', 'rec', record.id)
    except PIDDoesNotExistError:
        doi = None

    form = RecordDeleteForm()
    form.standard_reason.choices = current_app.config['ZENODO_REMOVAL_REASONS']
    if form.validate_on_submit():
        # Remove from index
        try:
            RecordIndexer().delete(record)
        except NotFoundError:
            pass
        try:
            RecordIndexer().delete(deposit)
        except NotFoundError:
            pass
        # Remove buckets
        record_bucket = record.files.bucket
        deposit_bucket = deposit.files.bucket
        RecordsBuckets.query.filter_by(record_id=record.id).delete()
        RecordsBuckets.query.filter_by(record_id=deposit.id).delete()
        record_bucket.locked = False
        record_bucket.remove()
        deposit_bucket.locked = False
        deposit_bucket.remove()
        # Remove PIDs
        pid.delete()
        depid.delete()
        # Remove record objects and record removal reason.
        record.clear()

        reason = form.reason.data or dict(
            current_app.config['ZENODO_REMOVAL_REASONS']
        )[form.standard_reason.data]

        record.update({
            'removal_reason': reason,
            'removed_by': current_user.get_id(),
        })
        record.commit()
        deposit.delete()
        db.session.commit()
        datacite_inactivate.delay(doi.pid_value)
        flash(
            _('Record %(recid)s and associated objects successfully deleted.',
                recid=pid.pid_value),
            category='success'
        )
        return redirect(url_for('zenodo_frontpage.index'))

    return render_template(
        'zenodo_deposit/delete.html',
        form=form,
        pid=pid,
        pids=[pid, depid, doi],
        record=record,
        deposit=deposit,
    )
Exemple #22
0
def next_action(activity_id='0', action_id=0):
    post_json = request.get_json()
    activity = dict(
        activity_id=activity_id,
        action_id=action_id,
        action_version=post_json.get('action_version'),
        action_status=ActionStatusPolicy.ACTION_DONE,
        commond=post_json.get('commond')
    )
    work_activity = WorkActivity()
    if 1 == post_json.get('temporary_save'):
        work_activity.upt_activity_action_comment(
            activity_id=activity_id,
            action_id=action_id,
            comment=post_json.get('commond')
        )
        return jsonify(code=0, msg=_('success'))
    history = WorkActivityHistory()
    action = Action().get_action_detail(action_id)
    action_endpoint = action.action_endpoint
    if 'begin_action' == action_endpoint:
        return jsonify(code=0, msg=_('success'))
    if 'end_action' == action_endpoint:
        work_activity.end_activity(activity)
        return jsonify(code=0, msg=_('success'))

    if 'approval' == action_endpoint:
        activity_obj = WorkActivity()
        activity_detail = activity_obj.get_activity_detail(activity_id)
        item = None
        if activity_detail is not None and activity_detail.item_id is not None:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
            pid_identifier = PersistentIdentifier.get_by_object(
                pid_type='depid', object_type='rec', object_uuid=item.id)
            record_class = import_string('weko_deposit.api:WekoRecord')
            resolver = Resolver(pid_type='recid', object_type='rec',
                                getter=record_class.get_record)
            pid, approval_record = resolver.resolve(pid_identifier.pid_value)
            UpdateItem.publish(pid, approval_record)

    rtn = history.create_activity_history(activity)
    if rtn is None:
        return jsonify(code=-1, msg=_('error'))
    # next action
    activity_detail = work_activity.get_activity_detail(activity_id)
    work_activity.upt_activity_action_status(
        activity_id=activity_id, action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_DONE)
    work_activity.upt_activity_action_comment(
        activity_id=activity_id,
        action_id=action_id,
        comment=''
    )
    flow = Flow()
    next_flow_action = flow.get_next_flow_action(
        activity_detail.flow_define.flow_id, action_id)
    if next_flow_action and len(next_flow_action) > 0:
        next_action_endpoint = next_flow_action[0].action.action_endpoint
        if 'end_action' == next_action_endpoint:
            activity.update(
                action_id=next_flow_action[0].action_id,
                action_version=next_flow_action[0].action_version,
            )
            work_activity.end_activity(activity)
        else:
            next_action_id = next_flow_action[0].action_id
            work_activity.upt_activity_action(
                activity_id=activity_id, action_id=next_action_id)
    return jsonify(code=0, msg=_('success'))
Exemple #23
0
def display_activity(activity_id=0):
    activity = WorkActivity()
    activity_detail = activity.get_activity_detail(activity_id)
    item = None
    if activity_detail is not None and activity_detail.item_id is not None:
        try:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        except NoResultFound as ex:
            current_app.logger.exception(str(ex))
            item = None
    steps = activity.get_activity_steps(activity_id)
    history = WorkActivityHistory()
    histories = history.get_activity_history_list(activity_id)
    workflow = WorkFlow()
    workflow_detail = workflow.get_workflow_by_id(
        activity_detail.workflow_id)
    if ActivityStatusPolicy.ACTIVITY_FINALLY != activity_detail.activity_status:
        activity_detail.activity_status_str = \
            request.args.get('status', 'ToDo')
    else:
        activity_detail.activity_status_str = _('End')
    cur_action = activity_detail.action
    action_endpoint = cur_action.action_endpoint
    action_id = cur_action.id
    temporary_comment = activity.get_activity_action_comment(
        activity_id=activity_id, action_id=action_id)
    if temporary_comment:
        temporary_comment = temporary_comment.action_comment
    cur_step = action_endpoint
    step_item_login_url = None
    approval_record = []
    pid = None
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        activity_session = dict(
            activity_id=activity_id,
            action_id=activity_detail.action_id,
            action_version=cur_action.action_version,
            action_status=ActionStatusPolicy.ACTION_DOING,
            commond=''
        )
        session['activity_info'] = activity_session
        step_item_login_url = url_for(
            'weko_items_ui.iframe_index',
            item_type_id=workflow_detail.itemtype_id)
        if item:
            pid_identifier = PersistentIdentifier.get_by_object(
                pid_type='depid', object_type='rec', object_uuid=item.id)
            step_item_login_url = url_for(
                'invenio_deposit_ui.iframe_depid',
                pid_value=pid_identifier.pid_value)
    # if 'approval' == action_endpoint:
    if item:
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid', object_type='rec',
                            getter=record_class.get_record)
        pid, approval_record = resolver.resolve(pid_identifier.pid_value)

    res_check = check_authority_action(activity_id,action_id)

    getargs = request.args
    ctx = {'community': None}
    community_id = ""
    if 'community' in getargs:
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        community_id=request.args.get('community')
        ctx = {'community': comm}
        community_id = comm.id
    return render_template(
        'weko_workflow/activity_detail.html',
        activity=activity_detail,
        item=item,
        steps=steps,
        action_id=action_id,
        cur_step=cur_step,
        temporary_comment=temporary_comment,
        record=approval_record,
        step_item_login_url=step_item_login_url,
        histories=histories,
        res_check=res_check,
        pid=pid,
        community_id=community_id,
        **ctx
    )
Exemple #24
0
def delete(pid=None, record=None, depid=None, deposit=None):
    """Delete a record."""
    # View disabled until properly implemented and tested.
    try:
        doi = PersistentIdentifier.get_by_object('doi', 'rec', record.id)
    except PIDDoesNotExistError:
        doi = None

    form = RecordDeleteForm()
    form.standard_reason.choices = current_app.config['ZENODO_REMOVAL_REASONS']
    if form.validate_on_submit():
        # Remove from index
        try:
            RecordIndexer().delete(record)
        except NotFoundError:
            pass
        try:
            RecordIndexer().delete(deposit)
        except NotFoundError:
            pass
        # Remove buckets
        record_bucket = record.files.bucket
        deposit_bucket = deposit.files.bucket
        RecordsBuckets.query.filter_by(record_id=record.id).delete()
        RecordsBuckets.query.filter_by(record_id=deposit.id).delete()
        record_bucket.locked = False
        record_bucket.remove()
        deposit_bucket.locked = False
        deposit_bucket.remove()
        # Remove PIDs
        pid.delete()
        depid.delete()
        # Remove record objects and record removal reason.
        record.clear()

        reason = form.reason.data or dict(
            current_app.config['ZENODO_REMOVAL_REASONS'])[
                form.standard_reason.data]

        record.update({
            'removal_reason': reason,
            'removed_by': current_user.get_id(),
        })
        record.commit()
        deposit.delete()
        db.session.commit()
        datacite_inactivate.delay(doi.pid_value)
        flash(_(
            'Record %(recid)s and associated objects successfully deleted.',
            recid=pid.pid_value),
              category='success')
        return redirect(url_for('zenodo_frontpage.index'))

    return render_template(
        'zenodo_deposit/delete.html',
        form=form,
        pid=pid,
        pids=[pid, depid, doi],
        record=record,
        deposit=deposit,
    )
Exemple #25
0
def next_action(activity_id='0', action_id=0):
    """Next action."""
    work_activity = WorkActivity()
    history = WorkActivityHistory()

    post_json = request.get_json()
    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_json.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_DONE,
                    commond=post_json.get('commond'))

    action = Action().get_action_detail(action_id)
    action_endpoint = action.action_endpoint

    if action_endpoint == 'begin_action':
        return jsonify(code=0, msg=_('success'))

    if action_endpoint == 'end_action':
        work_activity.end_activity(activity)
        return jsonify(code=0, msg=_('success'))

    if action_endpoint == 'item_login':
        register_hdl(activity_id)

    activity_detail = work_activity.get_activity_detail(activity_id)
    item_id = None
    recid = None
    record = None
    pid_without_ver = None
    if activity_detail and activity_detail.item_id:
        item_id = activity_detail.item_id
        current_pid = PersistentIdentifier.get_by_object(pid_type='recid',
                                                         object_type='rec',
                                                         object_uuid=item_id)
        recid = get_record_identifier(current_pid.pid_value)
        record = WekoDeposit.get_record(item_id)
        if record:
            pid_without_ver = get_record_without_version(current_pid)
            deposit = WekoDeposit(record, record.model)

    if post_json.get('temporary_save') == 1 \
            and action_endpoint != 'identifier_grant':
        if 'journal' in post_json:
            work_activity.create_or_update_action_journal(
                activity_id=activity_id,
                action_id=action_id,
                journal=post_json.get('journal'))
        else:
            work_activity.upt_activity_action_comment(
                activity_id=activity_id,
                action_id=action_id,
                comment=post_json.get('commond'))
        return jsonify(code=0, msg=_('success'))
    elif post_json.get('journal'):
        work_activity.create_or_update_action_journal(
            activity_id=activity_id,
            action_id=action_id,
            journal=post_json.get('journal'))

    if action_endpoint == 'approval' and item_id:
        item = ItemsMetadata.get_record(id_=item_id)
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        _pid, _approval_record = resolver.resolve(pid_identifier.pid_value)

        action_feedbackmail = work_activity.get_action_feedbackmail(
            activity_id=activity_id, action_id=ITEM_REGISTRATION_ACTION_ID)
        if action_feedbackmail:
            FeedbackMailList.update(
                item_id=item_id,
                feedback_maillist=action_feedbackmail.feedback_maillist)
            if not recid and pid_without_ver:
                FeedbackMailList.update(
                    item_id=pid_without_ver.object_uuid,
                    feedback_maillist=action_feedbackmail.feedback_maillist)

        if record:
            deposit.update_feedback_mail()
            deposit.update_jpcoar_identifier()
        # TODO: Make private as default.
        # UpdateItem.publish(pid, approval_record)

    if action_endpoint == 'item_link' and record:
        current_pid = PersistentIdentifier.get_by_object(pid_type='recid',
                                                         object_type='rec',
                                                         object_uuid=item_id)

        if not pid_without_ver:
            pid_without_ver = get_record_without_version(current_pid)

        item_link = ItemLink(pid_without_ver.pid_value)
        relation_data = post_json.get('link_data')
        if relation_data:
            errors = item_link.update(relation_data)
            if errors:
                return jsonify(code=-1, msg=_(errors))

    # save pidstore_identifier to ItemsMetadata
    identifier_select = post_json.get('identifier_grant')
    if 'identifier_grant' == action_endpoint and identifier_select:
        idf_grant_jalc_doi_manual = post_json.get(
            'identifier_grant_jalc_doi_suffix')
        idf_grant_jalc_cr_doi_manual = post_json.get(
            'identifier_grant_jalc_cr_doi_suffix')
        idf_grant_jalc_dc_doi_manual = post_json.get(
            'identifier_grant_jalc_dc_doi_suffix')
        idf_grant_ndl_jalc_doi_manual = post_json.get(
            'identifier_grant_ndl_jalc_doi_suffix')

        # If is action identifier_grant, then save to to database
        identifier_grant = {
            'action_identifier_select': identifier_select,
            'action_identifier_jalc_doi': idf_grant_jalc_doi_manual,
            'action_identifier_jalc_cr_doi': idf_grant_jalc_cr_doi_manual,
            'action_identifier_jalc_dc_doi': idf_grant_jalc_dc_doi_manual,
            'action_identifier_ndl_jalc_doi': idf_grant_ndl_jalc_doi_manual
        }

        work_activity.create_or_update_action_identifier(
            activity_id=activity_id,
            action_id=action_id,
            identifier=identifier_grant)

        error_list = item_metadata_validation(item_id, identifier_select)

        if post_json.get('temporary_save') == 1:
            return jsonify(code=0, msg=_('success'))

        if isinstance(error_list, str):
            return jsonify(code=-1, msg=_(error_list))

        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if error_list:
            sessionstore.put('updated_json_schema_{}'.format(activity_id),
                             json.dumps(error_list).encode('utf-8'),
                             ttl_secs=300)
            return previous_action(activity_id=activity_id,
                                   action_id=action_id,
                                   req=-1)
        else:
            if sessionstore.redis.exists(
                    'updated_json_schema_{}'.format(activity_id)):
                sessionstore.delete(
                    'updated_json_schema_{}'.format(activity_id))

        if identifier_select != IDENTIFIER_GRANT_SELECT_DICT['NotGrant'] \
                and item_id is not None:
            record_without_version = item_id
            if record and pid_without_ver and not recid:
                record_without_version = pid_without_ver.object_uuid
            saving_doi_pidstore(item_id, record_without_version, post_json,
                                int(identifier_select))

    rtn = history.create_activity_history(activity)
    if not rtn:
        return jsonify(code=-1, msg=_('error'))
    # next action
    work_activity.upt_activity_action_status(
        activity_id=activity_id,
        action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_DONE)
    work_activity.upt_activity_action_comment(activity_id=activity_id,
                                              action_id=action_id,
                                              comment='')
    flow = Flow()
    next_flow_action = flow.get_next_flow_action(
        activity_detail.flow_define.flow_id, action_id)
    if next_flow_action and len(next_flow_action) > 0:
        next_action_endpoint = next_flow_action[0].action.action_endpoint
        if 'end_action' == next_action_endpoint:
            new_activity_id = None
            if record:
                deposit.publish()
                updated_item = UpdateItem()
                # publish record without version ID when registering newly
                if recid:
                    # new record attached version ID
                    ver_attaching_record = deposit.newversion(current_pid)
                    new_activity_id = ver_attaching_record.model.id
                    ver_attaching_deposit = WekoDeposit(
                        ver_attaching_record, ver_attaching_record.model)
                    ver_attaching_deposit.publish()
                    record_bucket_id = merge_buckets_by_records(
                        current_pid.object_uuid,
                        ver_attaching_record.model.id,
                        sub_bucket_delete=True)
                    if not record_bucket_id:
                        return jsonify(code=-1, msg=_('error'))
                    # Record without version: Make status Public as default
                    updated_item.publish(record)
                else:
                    # update to record without version ID when editing
                    new_activity_id = record.model.id
                    if pid_without_ver:
                        record_without_ver = WekoDeposit.get_record(
                            pid_without_ver.object_uuid)
                        deposit_without_ver = WekoDeposit(
                            record_without_ver, record_without_ver.model)
                        deposit_without_ver['path'] = deposit.get('path', [])
                        parent_record = deposit_without_ver.\
                            merge_data_to_record_without_version(current_pid)
                        deposit_without_ver.publish()

                        set_bucket_default_size(new_activity_id)
                        merge_buckets_by_records(new_activity_id,
                                                 pid_without_ver.object_uuid)
                        updated_item.publish(parent_record)
                delete_unregister_buckets(new_activity_id)
            activity.update(
                action_id=next_flow_action[0].action_id,
                action_version=next_flow_action[0].action_version,
                item_id=new_activity_id,
            )
            work_activity.end_activity(activity)
        else:
            next_action_id = next_flow_action[0].action_id
            work_activity.upt_activity_action(
                activity_id=activity_id,
                action_id=next_action_id,
                action_status=ActionStatusPolicy.ACTION_DOING)
    # delete session value
    if session.get('itemlogin_id'):
        del session['itemlogin_id']
        del session['itemlogin_activity']
        del session['itemlogin_item']
        del session['itemlogin_steps']
        del session['itemlogin_action_id']
        del session['itemlogin_cur_step']
        del session['itemlogin_record']
        del session['itemlogin_res_check']
        del session['itemlogin_pid']
        del session['itemlogin_community_id']
    return jsonify(code=0, msg=_('success'))
Exemple #26
0
def display_activity(activity_id=0):
    """Display activity."""
    activity = WorkActivity()
    activity_detail = activity.get_activity_detail(activity_id)
    item = None
    if activity_detail and activity_detail.item_id:
        try:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        except NoResultFound as ex:
            current_app.logger.exception(str(ex))
            item = None

    steps = activity.get_activity_steps(activity_id)
    history = WorkActivityHistory()
    histories = history.get_activity_history_list(activity_id)
    workflow = WorkFlow()
    workflow_detail = workflow.get_workflow_by_id(activity_detail.workflow_id)

    if activity_detail.activity_status == \
        ActivityStatusPolicy.ACTIVITY_FINALLY \
        or activity_detail.activity_status == \
            ActivityStatusPolicy.ACTIVITY_CANCEL:
        activity_detail.activity_status_str = _('End')
    else:
        activity_detail.activity_status_str = \
            request.args.get('status', 'ToDo')
    cur_action = activity_detail.action
    action_endpoint = cur_action.action_endpoint
    action_id = cur_action.id
    temporary_comment = activity.get_activity_action_comment(
        activity_id=activity_id, action_id=action_id)

    # display_activity of Identifier grant
    identifier_setting = None
    if action_endpoint == 'identifier_grant' and item:
        community_id = request.args.get('community', None)
        if not community_id:
            community_id = 'Root Index'
        identifier_setting = get_identifier_setting(community_id)

        # valid date pidstore_identifier data
        if identifier_setting:
            text_empty = '<Empty>'
            if not identifier_setting.jalc_doi:
                identifier_setting.jalc_doi = text_empty
            if not identifier_setting.jalc_crossref_doi:
                identifier_setting.jalc_crossref_doi = text_empty
            if not identifier_setting.jalc_datacite_doi:
                identifier_setting.jalc_datacite_doi = text_empty
            if not identifier_setting.ndl_jalc_doi:
                identifier_setting.ndl_jalc_doi = text_empty

    temporary_identifier_select = 0
    temporary_identifier_inputs = []
    last_identifier_setting = activity.get_action_identifier_grant(
        activity_id=activity_id, action_id=action_id)
    if last_identifier_setting:
        temporary_identifier_select = last_identifier_setting.get(
            'action_identifier_select')
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_jalc_doi'))
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_jalc_cr_doi'))
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_jalc_dc_doi'))
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_ndl_jalc_doi'))

    temporary_journal = activity.get_action_journal(activity_id=activity_id,
                                                    action_id=action_id)
    if temporary_journal:
        temporary_journal = temporary_journal.action_journal

    cur_step = action_endpoint
    step_item_login_url = None
    approval_record = []
    pid = None
    record = {}
    need_file = False
    need_billing_file = False
    json_schema = ''
    schema_form = ''
    item_save_uri = ''
    files = []
    endpoints = {}
    links = None
    need_thumbnail = False
    files_thumbnail = []
    allow_multi_thumbnail = False
    show_autofill_metadata = True
    is_hidden_pubdate_value = False
    item_type_name = get_item_type_name(workflow_detail.itemtype_id)

    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        activity_session = dict(activity_id=activity_id,
                                action_id=activity_detail.action_id,
                                action_version=cur_action.action_version,
                                action_status=ActionStatusPolicy.ACTION_DOING,
                                commond='')
        show_autofill_metadata = is_show_autofill_metadata(item_type_name)
        is_hidden_pubdate_value = is_hidden_pubdate(item_type_name)
        session['activity_info'] = activity_session
        # get item edit page info.
        step_item_login_url, need_file, need_billing_file, \
            record, json_schema, schema_form,\
            item_save_uri, files, endpoints, need_thumbnail, files_thumbnail, \
            allow_multi_thumbnail \
            = item_login(item_type_id=workflow_detail.itemtype_id)
        if item:
            # Remove the unused local variable
            # _pid_identifier = PersistentIdentifier.get_by_object(
            #     pid_type='depid', object_type='rec', object_uuid=item.id)
            record = item

        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if sessionstore.redis.exists(
            'updated_json_schema_{}'.format(activity_id)) \
            and sessionstore.get(
                'updated_json_schema_{}'.format(activity_id)):
            json_schema = (json_schema + "/{}").format(activity_id)

    # if 'approval' == action_endpoint:
    if item:
        # get record data for the first time access to editing item screen
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        pid, approval_record = resolver.resolve(pid_identifier.pid_value)

        files = to_files_js(approval_record)

        # get files data after click Save btn
        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if sessionstore.redis.exists('activity_item_' + str(activity_id)):
            item_str = sessionstore.get('activity_item_' + str(activity_id))
            item_json = json.loads(item_str.decode('utf-8'))
            if 'files' in item_json:
                files = item_json.get('files')
        if not files:
            deposit = WekoDeposit.get_record(item.id)
            if deposit:
                files = to_files_js(deposit)

        if files and not files_thumbnail:
            files_thumbnail = [
                i for i in files
                if 'is_thumbnail' in i.keys() and i['is_thumbnail']
            ]

        from weko_deposit.links import base_factory
        links = base_factory(pid)

    res_check = check_authority_action(str(activity_id), str(action_id))

    getargs = request.args
    ctx = {'community': None}
    community_id = ""
    if 'community' in getargs:
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        ctx = {'community': comm}
        community_id = comm.id
    # be use for index tree and comment page.
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        session['itemlogin_id'] = activity_id
        session['itemlogin_activity'] = activity_detail
        session['itemlogin_item'] = item
        session['itemlogin_steps'] = steps
        session['itemlogin_action_id'] = action_id
        session['itemlogin_cur_step'] = cur_step
        session['itemlogin_record'] = approval_record
        session['itemlogin_histories'] = histories
        session['itemlogin_res_check'] = res_check
        session['itemlogin_pid'] = pid
        session['itemlogin_community_id'] = community_id

    from weko_theme.utils import get_design_layout
    # Get the design for widget rendering
    page, render_widgets = get_design_layout(
        community_id or current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])
    list_license = get_list_licence()

    if item and item.get('pid'):
        pid_without_ver = item['pid']['value'].split('.')[0]
        item_link = ItemLink.get_item_link_info(pid_without_ver)
        ctx['item_link'] = item_link

    return render_template(
        'weko_workflow/activity_detail.html',
        page=page,
        render_widgets=render_widgets,
        activity=activity_detail,
        item=item,
        steps=steps,
        action_id=action_id,
        cur_step=cur_step,
        temporary_comment=temporary_comment,
        temporary_journal=temporary_journal,
        temporary_idf_grant=temporary_identifier_select,
        temporary_idf_grant_suffix=temporary_identifier_inputs,
        idf_grant_data=identifier_setting,
        idf_grant_input=IDENTIFIER_GRANT_LIST,
        idf_grant_method=IDENTIFIER_GRANT_SUFFIX_METHOD,
        record=approval_record,
        records=record,
        step_item_login_url=step_item_login_url,
        need_file=need_file,
        need_billing_file=need_billing_file,
        jsonschema=json_schema,
        schemaform=schema_form,
        id=workflow_detail.itemtype_id,
        item_save_uri=item_save_uri,
        files=files,
        endpoints=endpoints,
        error_type='item_login_error',
        links=links,
        histories=histories,
        res_check=res_check,
        pid=pid,
        community_id=community_id,
        need_thumbnail=need_thumbnail,
        files_thumbnail=files_thumbnail,
        allow_multi_thumbnail=allow_multi_thumbnail,
        enable_feedback_maillist=current_app.
        config['WEKO_WORKFLOW_ENABLE_FEEDBACK_MAIL'],
        enable_contributor=current_app.
        config['WEKO_WORKFLOW_ENABLE_CONTRIBUTOR'],
        show_automatic_metadata_input=show_autofill_metadata,
        is_hidden_pubdate=is_hidden_pubdate_value,
        list_license=list_license,
        **ctx)
Exemple #27
0
def display_activity(activity_id=0):
    """Display activity."""
    activity = WorkActivity()
    activity_detail = activity.get_activity_detail(activity_id)
    item = None
    if activity_detail is not None and activity_detail.item_id is not None:
        try:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        except NoResultFound as ex:
            current_app.logger.exception(str(ex))
            item = None

    steps = activity.get_activity_steps(activity_id)
    history = WorkActivityHistory()
    histories = history.get_activity_history_list(activity_id)
    workflow = WorkFlow()
    workflow_detail = workflow.get_workflow_by_id(activity_detail.workflow_id)
    if activity_detail.activity_status == \
        ActivityStatusPolicy.ACTIVITY_FINALLY \
        or activity_detail.activity_status == \
            ActivityStatusPolicy.ACTIVITY_CANCEL:
        activity_detail.activity_status_str = _('End')
    else:
        activity_detail.activity_status_str = \
            request.args.get('status', 'ToDo')
    cur_action = activity_detail.action
    action_endpoint = cur_action.action_endpoint
    action_id = cur_action.id
    temporary_comment = activity.get_activity_action_comment(
        activity_id=activity_id, action_id=action_id)

    # display_activity of Identifier grant
    idf_grant_data = None
    if 'identifier_grant' == action_endpoint and item:
        path = WekoRecord.get_record(item.id).get('path')
        if len(path) > 1:
            community_id = 'Root Index'
        else:
            index_address = path.pop(-1).split('/')
            index_id = Index.query.filter_by(id=index_address.pop()).one()
            community_id = get_community_id_by_index(
                index_id.index_name_english)
        idf_grant_data = Identifier.query.filter_by(
            repository=community_id).one_or_none()

        # valid date pidstore_identifier data
        if idf_grant_data is not None:
            if not idf_grant_data.jalc_doi:
                idf_grant_data.jalc_doi = '<Empty>'
            if not idf_grant_data.jalc_crossref_doi:
                idf_grant_data.jalc_crossref_doi = '<Empty>'
            if not idf_grant_data.jalc_datacite_doi:
                idf_grant_data.jalc_datacite_doi = '<Empty>'
            if not idf_grant_data.cnri:
                idf_grant_data.cnri = '<Empty>'
            if not idf_grant_data.suffix:
                idf_grant_data.suffix = '<Empty>'

    temporary_idf_grant = 0
    temporary_idf_grant_suffix = []
    temporary_identifier = activity.get_action_identifier_grant(
        activity_id=activity_id, action_id=action_id)
    if temporary_identifier:
        temporary_idf_grant = temporary_identifier.get(
            'action_identifier_select')
        temporary_idf_grant_suffix.append(
            temporary_identifier.get('action_identifier_jalc_doi'))
        temporary_idf_grant_suffix.append(
            temporary_identifier.get('action_identifier_jalc_cr_doi'))
        temporary_idf_grant_suffix.append(
            temporary_identifier.get('action_identifier_jalc_dc_doi'))

    temporary_journal = activity.get_action_journal(activity_id=activity_id,
                                                    action_id=action_id)
    if temporary_journal:
        temporary_journal = temporary_journal.action_journal

    cur_step = action_endpoint
    step_item_login_url = None
    approval_record = []
    pid = None
    record = {}
    need_file = False
    json_schema = ''
    schema_form = ''
    item_save_uri = ''
    files = []
    endpoints = {}
    links = None
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        activity_session = dict(activity_id=activity_id,
                                action_id=activity_detail.action_id,
                                action_version=cur_action.action_version,
                                action_status=ActionStatusPolicy.ACTION_DOING,
                                commond='')
        session['activity_info'] = activity_session
        # get item edit page info.
        step_item_login_url, need_file, record, json_schema, \
            schema_form, item_save_uri, files, endpoints = item_login(
                item_type_id=workflow_detail.itemtype_id)
        if item:
            pid_identifier = PersistentIdentifier.get_by_object(
                pid_type='depid', object_type='rec', object_uuid=item.id)
            record = item
    # if 'approval' == action_endpoint:
    if item:
        # get record data for the first time access to editing item screen
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        pid, approval_record = resolver.resolve(pid_identifier.pid_value)

        files = to_files_js(approval_record)

        # get files data after click Save btn
        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if sessionstore.redis.exists('activity_item_' + str(activity_id)):
            item_str = sessionstore.get('activity_item_' + str(activity_id))
            item_json = json.loads(item_str.decode('utf-8'))
            if 'files' in item_json:
                files = item_json.get('files')
        if not files:
            deposit = WekoDeposit.get_record(item.id)
            if deposit is not None:
                files = to_files_js(deposit)

        from weko_deposit.links import base_factory
        links = base_factory(pid)

    res_check = check_authority_action(activity_id, action_id)

    getargs = request.args
    ctx = {'community': None}
    community_id = ""
    if 'community' in getargs:
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        community_id = request.args.get('community')
        ctx = {'community': comm}
        community_id = comm.id
    # be use for index tree and comment page.
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        session['itemlogin_id'] = activity_id
        session['itemlogin_activity'] = activity_detail
        session['itemlogin_item'] = item
        session['itemlogin_steps'] = steps
        session['itemlogin_action_id'] = action_id
        session['itemlogin_cur_step'] = cur_step
        session['itemlogin_record'] = approval_record
        session['itemlogin_histories'] = histories
        session['itemlogin_res_check'] = res_check
        session['itemlogin_pid'] = pid
        session['itemlogin_community_id'] = community_id

    return render_template(
        'weko_workflow/activity_detail.html',
        render_widgets=True,
        activity=activity_detail,
        item=item,
        steps=steps,
        action_id=action_id,
        cur_step=cur_step,
        temporary_comment=temporary_comment,
        temporary_journal=temporary_journal,
        temporary_idf_grant=temporary_idf_grant,
        temporary_idf_grant_suffix=temporary_idf_grant_suffix,
        idf_grant_data=idf_grant_data,
        idf_grant_input=IDENTIFIER_GRANT_LIST,
        idf_grant_method=IDENTIFIER_GRANT_SUFFIX_METHOD,
        record=approval_record,
        records=record,
        step_item_login_url=step_item_login_url,
        need_file=need_file,
        jsonschema=json_schema,
        schemaform=schema_form,
        id=workflow_detail.itemtype_id,
        item_save_uri=item_save_uri,
        files=files,
        endpoints=endpoints,
        error_type='item_login_error',
        links=links,
        histories=histories,
        res_check=res_check,
        pid=pid,
        community_id=community_id,
        **ctx)