Пример #1
0
    def get_items_metadata(self):
        """Get the metadata of items to bulk update."""
        def get_file_data(meta):
            file_data = {}
            for key in meta:
                if isinstance(meta.get(key), list):
                    for item in meta.get(key):
                        if isinstance(item, dict) and 'filename' in item:
                            file_data[key] = meta.get(key)
                            break
            return file_data

        pids = request.values.get('pids')
        pid_list = []
        if pids is not None:
            pid_list = pids.split('/')

        data = {}
        for pid in pid_list:
            record = WekoRecord.get_record_by_pid(pid)
            indexes = []
            if isinstance(record.get('path'), list):
                for path in record.get('path'):
                    indexes.append(path.split('/')[-1])

            pidObject = PersistentIdentifier.get('recid', pid)
            meta = ItemsMetadata.get_record(pidObject.object_uuid)

            if meta:
                data[pid] = {}
                data[pid]['meta'] = meta
                data[pid]['index'] = {"index": indexes}
                data[pid]['contents'] = get_file_data(meta)

        return jsonify(data)
Пример #2
0
    def save_or_update_item_metadata(self):
        """Save or update item metadata.

        Save when register a new item type, Update when edit an item
        type.
        """
        if self.is_edit:
            obj = ItemsMetadata.get_record(self.id)
            obj.update(self.data)
            obj.commit()
        else:
            ItemsMetadata.create(self.data, id_=self.pid.object_uuid,
                                 item_type_id=self.get('item_type_id'))
Пример #3
0
def get_item_pidstore_identifier(object_uuid):
    """
    Get identifier value from ItemsMetadata.

    :param: index_name_english
    :return: dict of item type info
    """
    with db.session.no_autoflush:
        action_status = Activity.query.filter_by(
            item_id=object_uuid).one_or_none()
        meta = ItemsMetadata.get_record(object_uuid)
        if meta and action_status:
            pidstore_identifier = meta.get('pidstore_identifier')
            if pidstore_identifier is not None \
                and action_status.action_status == \
                    ActionStatusPolicy.ACTION_DONE:
                identifier = pidstore_identifier.get('identifier')
                if identifier:
                    return identifier.get('value')

    return None
Пример #4
0
Файл: api.py Проект: mhaya/weko
    def save_or_update_item_metadata(self):
        """Save or update item metadata.

        Save when register a new item type, Update when edit an item
        type.
        """
        if current_user:
            current_user_id = current_user.get_id()
        else:
            current_user_id = '1'
        if current_user_id:
            dc_owner = self.data.get("owner", None)
            if not dc_owner:
                self.data.update(dict(owner=current_user_id))

        if ItemMetadata.query.filter_by(id=self.id).first():
            obj = ItemsMetadata.get_record(self.id)
            obj.update(self.data)
            obj.commit()
        else:
            ItemsMetadata.create(self.data,
                                 id_=self.pid.object_uuid,
                                 item_type_id=self.get('item_type_id'))
Пример #5
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'))
Пример #6
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
    )
Пример #7
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'))
Пример #8
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)
Пример #9
0
Файл: api.py Проект: mhaya/weko
    def newversion(self, pid=None):
        """Create a new version deposit."""
        deposit = None
        try:
            if not self.is_published():
                raise PIDInvalidAction()

            # Check that there is not a newer draft version for this record
            # and this is the latest version
            pv = PIDVersioning(child=pid)
            if pv.exists and not pv.draft_child and pid == pv.last_child:
                last_pid = pv.last_child
                # Get copy of the latest record
                latest_record = WekoDeposit.get_record(last_pid.object_uuid)
                if latest_record is not None:
                    data = latest_record.dumps()

                    owners = data['_deposit']['owners']
                    keys_to_remove = ('_deposit', 'doi', '_oai', '_files',
                                      '_buckets', '$schema')
                    for k in keys_to_remove:
                        data.pop(k, None)

                    # NOTE: We call the superclass `create()` method, because we
                    # don't want a new empty bucket, but an unlocked snapshot of
                    # the old record's bucket.
                    deposit = super(WekoDeposit, self).create(data)
                    # Injecting owners is required in case of creating new
                    # version this outside of request context
                    deposit['_deposit']['owners'] = owners

                    recid = PersistentIdentifier.get(
                        'recid', str(data['_deposit']['id']))
                    depid = PersistentIdentifier.get(
                        'depid', str(data['_deposit']['id']))
                    PIDVersioning(parent=pv.parent).insert_draft_child(
                        child=recid)
                    RecordDraft.link(recid, depid)

                    # Create snapshot from the record's bucket and update data
                    snapshot = latest_record.files.bucket.snapshot(lock=False)
                    snapshot.locked = False
                    deposit['_buckets'] = {'deposit': str(snapshot.id)}
                    RecordsBuckets.create(record=deposit.model,
                                          bucket=snapshot)
                    if 'extra_formats' in latest_record['_buckets']:
                        extra_formats_snapshot = \
                            latest_record.extra_formats.bucket.snapshot(
                                lock=False)
                        deposit['_buckets']['extra_formats'] = \
                            str(extra_formats_snapshot.id)
                        RecordsBuckets.create(record=deposit.model,
                                              bucket=extra_formats_snapshot)
                    index = {
                        'index':
                        self.get('path', []),
                        'actions':
                        'private' if self.get('publish_status', '1') == '1'
                        else 'publish'
                    }
                    if 'activity_info' in session:
                        del session['activity_info']
                    item_metadata = ItemsMetadata.get_record(
                        last_pid.object_uuid).dumps()
                    args = [index, item_metadata]
                    deposit.update(*args)
                    deposit.commit()
            return deposit
        except SQLAlchemyError as ex:
            current_app.logger.debug(ex)
            db.session.rollback()
            return None
Пример #10
0
Файл: api.py Проект: mhaya/weko
 def item_metadata(self):
     """Return the Item metadata."""
     return ItemsMetadata.get_record(self.id).dumps()
Пример #11
0
def make_combined_pdf(pid, obj_file_uri, fileobj, obj, lang_user):
    """Make the cover-page-combined PDF file.

    :param pid: PID object
    :param file_uri: URI of the file object
    :param lang_user: LANGUAGE of access user
    :return: cover-page-combined PDF file object
    """
    lang_filepath = current_app.config['PDF_COVERPAGE_LANG_FILEPATH']\
        + lang_user + current_app.config['PDF_COVERPAGE_LANG_FILENAME']

    pidObject = PersistentIdentifier.get('recid', pid.pid_value)
    item_metadata_json = ItemsMetadata.get_record(pidObject.object_uuid)
    item_type = ItemsMetadata.get_by_object_id(pidObject.object_uuid)
    item_type_id = item_type.item_type_id
    type_mapping = Mapping.get_record(item_type_id)
    item_map = get_mapping(type_mapping, "jpcoar_mapping")

    with open(lang_filepath) as json_datafile:
        lang_data = json.loads(json_datafile.read())

    # Initialize Instance
    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    pdf.set_margins(20.0, 20.0)
    pdf.set_fill_color(100, 149, 237)

    pdf.add_font(
        'IPAexg',
        '',
        current_app.config["JPAEXG_TTF_FILEPATH"],
        uni=True)
    pdf.add_font(
        'IPAexm',
        '',
        current_app.config["JPAEXM_TTF_FILEPATH"],
        uni=True)

    # Parameters such as width and height of rows/columns
    w1 = 40  # width of the left column
    w2 = 130  # width of the right column
    footer_w = 90  # width of the footer cell
    # url_oapolicy_h = 7  # height of the URL & OA-policy
    # height of the URL & OA-policy
    url_oapolicy_h = current_app.config['URL_OA_POLICY_HEIGHT']
    # title_h = 8  # height of the title
    title_h = current_app.config['TITLE_HEIGHT']  # height of the title
    # header_h = 20  # height of the header cell
    header_h = current_app.config['HEADER_HEIGHT']  # height of the header cell
    # footer_h = 4  # height of the footer cell
    footer_h = current_app.config['FOOTER_HEIGHT']  # height of the footer cell
    # meta_h = 9  # height of the metadata cell
    # height of the metadata cell
    meta_h = current_app.config['METADATA_HEIGHT']
    max_letters_num = 51    # number of maximum letters that can be contained \
    # in the right column
    cc_logo_xposition = 160  # x-position of Creative Commons logos

    # Get the header settings
    record = PDFCoverPageSettings.find(1)
    header_display_type = record.header_display_type
    header_output_string = record.header_output_string
    header_output_image = record.header_output_image
    header_display_position = record.header_display_position

    # Set the header position
    positions = {}
    if header_display_position == 'left':
        positions['str_position'] = 'L'
        positions['img_position'] = 20
    elif header_display_position == 'center' or header_display_position is None:
        positions['str_position'] = 'C'
        positions['img_position'] = 85
    elif header_display_position == 'right':
        positions['str_position'] = 'R'
        positions['img_position'] = 150

    # Show header(string or image)
    if header_display_type == 'string':
        pdf.set_font('IPAexm', '', 22)
        pdf.multi_cell(
            w1 + w2,
            header_h,
            header_output_string,
            0,
            positions['str_position'],
            False)
    else:
        pdf.image(
            header_output_image,
            x=positions['img_position'],
            y=None,
            w=0,
            h=30,
            type='')
        pdf.set_y(55)

    # Title settings
    title = item_metadata_json['title']
    pdf.set_font('IPAexm', '', 20)
    pdf.multi_cell(w1 + w2, title_h, title, 0, 'L', False)
    pdf.ln(h='15')

    # Metadata
    fg = WekoFeedGenerator()
    fe = fg.add_entry()

    _file = 'file.URI.@value'
    _file_item_id = None
    if _file in item_map:
        _file_item_id = item_map[_file].split('.')[0]
        _file_item_id = _file_item_id.replace('fileinfo', 'files')

    _creator = 'creator.creatorName.@value'
    _creator_item_id = None
    if _creator in item_map:
        _creator_item_id = item_map[_creator].split('.')[0]

    publisher_attr_lang = '[email protected]:lang'
    publisher_value = 'publisher.@value'
    publisher_item_id = None
    publisher_lang_id = None
    publisher_text_id = None

    keyword_attr_lang = '[email protected]:lang'
    keyword_attr_value = 'subject.@value'
    keyword_base = None
    keyword_lang = None

    pdf.set_font('Arial', '', 14)
    pdf.set_font('IPAexg', '', 14)

    if item_metadata_json['lang'] == 'en':
        item_metadata_json['lang'] = 'English'
    elif item_metadata_json['lang'] == 'ja':
        item_metadata_json['lang'] = 'Japanese'
    try:
        lang_field = item_map['language.@value'].split('.')
        if item_metadata_json[lang_field[0]][lang_field[1]] == 'eng':
            item_metadata_json['lang'] = 'English'
        elif item_metadata_json[lang_field[0]][lang_field[1]] == 'jpn':
            item_metadata_json['lang'] = 'Japanese'
    except BaseException:
        pass
    try:
        lang = item_metadata_json.get('lang')
    except (KeyError, IndexError):
        lang = None
    try:
        publisher_item_id = item_map[publisher_attr_lang].split('.')[0]
        publisher_lang_ids = item_map[publisher_attr_lang].split('.')[1:]
        publisher_text_ids = item_map[publisher_value].split('.')[1:]
        publisher = None
        default_publisher = None
        publishers = item_metadata_json[publisher_item_id]
        pair_name_language_publisher = get_pair_value(publisher_text_ids,
                                                      publisher_lang_ids,
                                                      publishers)
        for publisher_name, publisher_lang in pair_name_language_publisher:
            if publisher_lang == lang_user:
                publisher = publisher_name
            if publisher_lang == 'en':
                default_publisher = publisher_name

        if publisher is None:
            publisher = default_publisher
    except (KeyError, IndexError):
        publisher = None
    try:
        pubdate = item_metadata_json.get('pubdate')
    except (KeyError, IndexError):
        pubdate = None
    try:
        keyword_item_id = item_map[keyword_attr_lang].split('.')[0]
        keyword_item_langs = item_map[keyword_attr_lang].split('.')[1:]
        keyword_item_values = item_map[keyword_attr_value].split('.')[1:]
        keyword_base = item_metadata_json.get(keyword_item_id)
        keywords_ja = None
        keywords_en = None

        pair_name_language_keyword = get_pair_value(keyword_item_values,
                                                    keyword_item_langs,
                                                    keyword_base)

        for name, lang in pair_name_language_keyword:
            keyword_lang = lang
            if keyword_lang == 'ja':
                keywords_ja = name
            elif keyword_lang == 'en':
                keywords_en = name

    except (KeyError, IndexError):
        pass
    creator_items = item_metadata_json.get(_creator_item_id)
    if type(creator_items) is dict:
        creator_items = [creator_items]
    creator_mail_list = []
    creator_name_list = []
    creator_affiliation_list = []
    for creator_item in creator_items:
        # Get creator mail
        if creator_item.get('creatorMails'):
            for creator_mail in creator_item.get('creatorMails'):
                if creator_mail.get('creatorMail'):
                    creator_mail_list.append(creator_mail.get('creatorMail'))
        # Get creator name
        default_creator_name_list = []
        if creator_item.get('creatorNames'):
            for creator_name in creator_item.get('creatorNames'):
                if creator_name.get('creatorNameLang') == lang_user:
                    creator_name_list.append(creator_name.get('creatorName'))
                if creator_name.get('creatorNameLang') == 'en':
                    default_creator_name_list.append(creator_name.get(
                        'creatorName'))
        if not creator_name_list and default_creator_name_list:
            creator_name_list = default_creator_name_list
        # Get creator affiliation
        default_creator_affiliation_list = []
        if creator_item.get('affiliation'):
            for creator_affiliation in creator_item.get('affiliation'):
                if creator_affiliation.get('affiliationNameLang') == lang_user:
                    creator_affiliation_list.append(creator_affiliation.get(
                        'affiliationName'))
                if creator_affiliation.get('affiliationNameLang') == 'en':
                    default_creator_affiliation_list.\
                        append(creator_affiliation.get('affiliationName'))
        if not creator_affiliation_list and default_creator_affiliation_list:
            creator_affiliation_list = default_creator_affiliation_list

    seperator = ', '
    metadata_dict = {
        "lang": lang,
        "publisher": publisher,
        "pubdate": pubdate,
        "keywords_ja": keywords_ja,
        "keywords_en": keywords_en,
        "creator_mail": seperator.join(creator_mail_list),
        "creator_name": seperator.join(creator_name_list),
        "affiliation": seperator.join(creator_affiliation_list)
    }

    # Change the values from None to '' for printing
    for key in metadata_dict:
        if metadata_dict[key] is None:
            metadata_dict[key] = ''
    metadata_list = [
        "{}: {}".format(lang_data["Metadata"]["LANG"], metadata_dict["lang"]),
        "{}: {}".format(
            lang_data["Metadata"]["PUBLISHER"],
            metadata_dict["publisher"]),
        "{}: {}".format(
            lang_data["Metadata"]["PUBLICDATE"],
            metadata_dict["pubdate"]),
        "{} (Ja): {}".format(
            lang_data["Metadata"]["KEY"],
            metadata_dict["keywords_ja"]),
        "{} (En): {}".format(
            lang_data["Metadata"]["KEY"],
            metadata_dict["keywords_en"]),
        "{}: {}".format(
            lang_data["Metadata"]["AUTHOR"],
            metadata_dict["creator_name"]),
        "{}: {}".format(
            lang_data["Metadata"]["EMAIL"],
            metadata_dict["creator_mail"]),
        "{}: {}".format(
            lang_data["Metadata"]["AFFILIATED"],
            metadata_dict["affiliation"])
    ]

    metadata = '\n'.join(metadata_list)
    metadata_lfnum = int(metadata.count('\n'))
    for item in metadata_list:
        metadata_lfnum += int(get_east_asian_width_count(item)
                              ) // max_letters_num

    url = ''  # will be modified later
    url_lfnum = int(get_east_asian_width_count(url)) // max_letters_num

    oa_policy = ''  # will be modified later
    oa_policy_lfnum = int(
        get_east_asian_width_count(oa_policy)) // max_letters_num

    # Save top coordinate
    top = pdf.y
    # Calculate x position of next cell
    offset = pdf.x + w1
    pdf.multi_cell(w1,
                   meta_h,
                   lang_data["Title"]["METADATA"]
                   + '\n' * (metadata_lfnum + 1),
                   1,
                   'C',
                   True)
    # Reset y coordinate
    pdf.y = top
    # Move to computed offset
    pdf.x = offset
    pdf.multi_cell(w2, meta_h, metadata, 1, 'L', False)
    top = pdf.y
    pdf.multi_cell(w1,
                   url_oapolicy_h,
                   lang_data["Title"]["URL"] + '\n' * (url_lfnum + 1),
                   1,
                   'C',
                   True)
    pdf.y = top
    pdf.x = offset
    pdf.multi_cell(w2, url_oapolicy_h, url, 1, 'L', False)
    top = pdf.y
    pdf.multi_cell(w1,
                   url_oapolicy_h,
                   lang_data["Title"]["OAPOLICY"]
                   + '\n' * (oa_policy_lfnum + 1),
                   1,
                   'C',
                   True)
    pdf.y = top
    pdf.x = offset
    pdf.multi_cell(w2, url_oapolicy_h, oa_policy, 1, 'L', False)
    pdf.ln(h=1)

    # Footer
    pdf.set_font('Courier', '', 10)
    pdf.set_x(108)

    try:
        license = item_metadata_json[_file_item_id][0].get('licensetype')
    except (KeyError, IndexError, TypeError):
        license = None

    list_license_dict = current_app.config['WEKO_RECORDS_UI_LICENSE_DICT']
    for item in list_license_dict:
        if item['value'] == license:
            get_license_pdf(license, item_metadata_json, pdf, _file_item_id,
                            footer_w, footer_h, cc_logo_xposition, item)
            break
    else:
        pdf.multi_cell(footer_w, footer_h, '', 0, 'L', False)

    """ Convert PDF cover page data as bytecode """
    output = pdf.output(dest='S').encode('latin-1')
    b_output = io.BytesIO(output)

    # Combine cover page and existing pages
    cover_page = PdfFileReader(b_output)
    f = open(obj_file_uri, "rb")
    existing_pages = PdfFileReader(f)

    # In the case the PDF file is encrypted by the password, ''(i.e. not
    # encrypted intentionally)
    if existing_pages.isEncrypted:
        try:
            existing_pages.decrypt('')
        except BaseException:  # Errors such as NotImplementedError
            return ObjectResource.send_object(
                obj.bucket, obj,
                expected_chksum=fileobj.get('checksum'),
                logger_data={
                    'bucket_id': obj.bucket_id,
                    'pid_type': pid.pid_type,
                    'pid_value': pid.pid_value,
                },
                as_attachment=False
            )

    # In the case the PDF file is encrypted by the password except ''
    if existing_pages.isEncrypted:
        return ObjectResource.send_object(
            obj.bucket, obj,
            expected_chksum=fileobj.get('checksum'),
            logger_data={
                'bucket_id': obj.bucket_id,
                'pid_type': pid.pid_type,
                'pid_value': pid.pid_value,
            },
            as_attachment=False
        )

    combined_pages = PdfFileWriter()
    combined_pages.addPage(cover_page.getPage(0))
    for page_num in range(existing_pages.numPages):
        existing_page = existing_pages.getPage(page_num)
        combined_pages.addPage(existing_page)

    # Download the newly generated combined PDF file
    try:
        combined_filename = 'CV_' + datetime.now().strftime('%Y%m%d') + '_' + \
                            item_metadata_json[_file_item_id][0].get("filename")

    except (KeyError, IndexError):
        combined_filename = 'CV_' + title + '.pdf'
    combined_filepath = "/code/invenio/{}.pdf".format(combined_filename)
    combined_file = open(combined_filepath, "wb")
    combined_pages.write(combined_file)
    combined_file.close()

    return send_file(
        combined_filepath,
        as_attachment=True,
        attachment_filename=combined_filename,
        mimetype='application/pdf',
        cache_timeout=-1)
Пример #12
0
def pidstore_identifier_mapping(post_json, idf_grant=0, activity_id='0'):
    """
    Mapp pidstore identifier data to ItemMetadata.

    :param post_json: request data
    :param idf_grant: identifier selected
    :param activity_id: activity id number
    """
    activity_obj = WorkActivity()
    activity_detail = activity_obj.get_activity_detail(activity_id)
    item = ItemsMetadata.get_record(id_=activity_detail.item_id)

    # transfer to JPCOAR format
    res = {'pidstore_identifier': {}}
    tempdata = IDENTIFIER_ITEMSMETADATA_FORM
    flag_del_pidstore = False

    if idf_grant == 0:
        res['pidstore_identifier'] = tempdata
    elif idf_grant == 1:  # identifier_grant_jalc_doi
        jalcdoi_link = post_json.get('identifier_grant_jalc_doi_link')
        if jalcdoi_link:
            jalcdoi_tail = (jalcdoi_link.split('//')[1]).split('/')
            tempdata['identifier']['value'] = jalcdoi_link
            tempdata['identifier']['properties']['identifierType'] = 'DOI'
            tempdata['identifierRegistration']['value'] = \
                jalcdoi_tail[1:]
            tempdata['identifierRegistration']['properties'][
                'identifierType'] = 'JaLC'
            res['pidstore_identifier'] = tempdata
    elif idf_grant == 2:  # identifier_grant_jalc_cr
        jalcdoi_cr_link = post_json.get('identifier_grant_jalc_cr_doi_link')
        if jalcdoi_cr_link:
            jalcdoi_cr_tail = (jalcdoi_cr_link.split('//')[1]).split('/')
            tempdata['identifier']['value'] = jalcdoi_cr_link
            tempdata['identifier']['properties']['identifierType'] = 'DOI'
            tempdata['identifierRegistration']['value'] = \
                jalcdoi_cr_tail[1:]
            tempdata['identifierRegistration']['properties'][
                'identifierType'] = 'Crossref'
            res['pidstore_identifier'] = tempdata
    elif idf_grant == 3:  # identifier_grant_jalc_dc_doi
        jalcdoi_dc_link = post_json.get('identifier_grant_jalc_dc_doi_link')
        if jalcdoi_dc_link:
            jalcdoi_dc_tail = (jalcdoi_dc_link.split('//')[1]).split('/')
            tempdata['identifier']['value'] = jalcdoi_dc_link
            tempdata['identifier']['properties']['identifierType'] = 'DOI'
            tempdata['identifierRegistration']['value'] = \
                jalcdoi_dc_tail[1:]
            tempdata['identifierRegistration']['properties'][
                'identifierType'] = 'Datacite'
            res['pidstore_identifier'] = tempdata
    elif idf_grant == 4:  # identifier_grant_crni
        jalcdoi_crni_link = post_json.get('identifier_grant_crni_link')
        if jalcdoi_crni_link:
            tempdata['identifier']['value'] = jalcdoi_crni_link
            tempdata['identifier']['properties']['identifierType'] = 'HDL'
            del tempdata['identifierRegistration']
            res['pidstore_identifier'] = tempdata
    elif idf_grant == -1:  # with draw identifier_grant
        pidstore_identifier = item.get('pidstore_identifier')
        res['pidstore_identifier'] = tempdata
        flag_del_pidstore = del_invenio_pidstore(
            pidstore_identifier['identifier']['value'])
    else:
        current_app.logger.error(_('Identifier datas are empty!'))
        pidstore_identifier = item.get('pidstore_identifier')
        res['pidstore_identifier'] = tempdata
        flag_del_pidstore = del_invenio_pidstore(
            pidstore_identifier['identifier']['value'])
    try:
        if not flag_del_pidstore:
            reg_invenio_pidstore(tempdata['identifier']['value'], item.id)

        with db.session.begin_nested():
            item.update(res)
            item.commit()
        db.session.commit()
    except Exception as ex:
        current_app.logger.exception(str(ex))
        db.session.rollback()
Пример #13
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'))
Пример #14
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)