def site_license_check(): # site license permission check obj = ItemTypes.get_by_id(record.get('item_type_id')) if obj.item_type_name.has_site_license: return check_site_license_permission( ) | check_user_group_permission(fjson.get('groups')) return False
def create_work_flow(item_type_id): """Handle create work flow. :argument item_type_id -- {str} item_type_id. :return """ flow_define = FlowDefine.query.filter_by( flow_name='Registration Flow').first() it = ItemTypes.get_by_id(item_type_id) if flow_define and it: try: data = WorkFlow() data.flows_id = uuid.uuid4() data.flows_name = it.item_type_name.name data.itemtype_id = it.id data.flow_id = flow_define.id db.session.add(data) db.session.commit() except Exception as ex: db.session.rollback() current_app.logger.error("create work flow error") current_app.logger.error(ex)
def weko_view_method(pid, record, template=None, **kwargs): r"""Display Weko view. Sends record_viewed signal and renders template. :param pid: PID object. :param record: Record object. :param template: Template to render. :returns: The rendered template. """ flst = FilesMetadata.get_records(pid.pid_value) frecord = [] if len(flst) > 0: for fj in flst: frecord.append(fj.dumps()) item_type = ItemTypes.get_by_id(id_=record['item_type_id']) item_type_info = "{}({})".format(item_type.item_type_name.name, item_type.tag) return render_template(template, pid=pid, record=record, files=frecord, item_type_info=item_type_info)
def index(item_type_id=0): """Renders an item register view. :param item_type_id: Item type ID. (Default: 0) :return: The rendered template. """ try: lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) need_file = False if 'filename' in json.dumps(item_type.schema): need_file = True return render_template( current_app.config['WEKO_ITEMS_UI_FORM_TEMPLATE'], render_widgets=True, need_file=need_file, record={}, jsonschema=json_schema, schemaform=schema_form, lists=lists, id=item_type_id, files=[]) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def get_schema_form(item_type_id=0): """Get schema form. :param item_type_id: Item type ID. (Default: 0) :return: The json object. """ try: cur_lang = current_i18n.language result = None if item_type_id > 0: result = ItemTypes.get_by_id(item_type_id) if result is None: return '["*"]' schema_form = result.form filemeta_form = schema_form[0] if 'filemeta' == filemeta_form.get('key'): group_list = Group.get_group_list() filemeta_form_group = filemeta_form.get('items')[-1] filemeta_form_group['type'] = 'select' filemeta_form_group['titleMap'] = group_list if 'default' != cur_lang: for elem in schema_form: if 'title_i18n' in elem and cur_lang in elem['title_i18n']\ and len(elem['title_i18n'][cur_lang]) > 0: elem['title'] = elem['title_i18n'][cur_lang] if 'items' in elem: for sub_elem in elem['items']: if 'title_i18n' in sub_elem and cur_lang in \ sub_elem['title_i18n'] and len( sub_elem['title_i18n'][cur_lang]) > 0: sub_elem['title'] = sub_elem['title_i18n'][ cur_lang] if sub_elem.get('title') == 'Group/Price': for sub_item in sub_elem['items']: if sub_item['title'] == "価格" and \ 'validationMessage_i18n' in sub_item and \ cur_lang in sub_item[ 'validationMessage_i18n'] and\ len(sub_item['validationMessage_i18n'] [cur_lang]) > 0: sub_item['validationMessage'] = sub_item[ 'validationMessage_i18n'][cur_lang] if 'items' in sub_elem: for sub_item in sub_elem['items']: if 'title_i18n' in sub_item and cur_lang in \ sub_item['title_i18n'] and len( sub_item['title_i18n'][cur_lang]) > 0: sub_item['title'] = sub_item['title_i18n'][ cur_lang] return jsonify(schema_form) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def is_billing_item(item_type_id): """Checks if item is a billing item based on its meta data schema.""" item_type = ItemTypes.get_by_id(id_=item_type_id) if item_type: properties = item_type.schema['properties'] for meta_key in properties: if properties[meta_key]['type'] == 'object' and \ 'groupsprice' in properties[meta_key]['properties'] or \ properties[meta_key]['type'] == 'array' and 'groupsprice' in \ properties[meta_key]['items']['properties']: return True return False
def render(item_type_id=0): result = None if item_type_id > 0: result = ItemTypes.get_by_id(id_=item_type_id) if result is None: result = { 'table_row': [], 'table_row_map': {}, 'meta_list': {}, 'schemaeditor': { 'schema': {} } } return jsonify(result.render)
def iframe_index(item_type_id=0): """Renders an item register view. :param item_type_id: Item type ID. (Default: 0) :return: The rendered template. """ try: item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return render_template('weko_items_ui/iframe/error.html', error_type='no_itemtype') json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) 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')))) record = {} files = [] endpoints = {} activity_session = session['activity_info'] activity_id = activity_session.get('activity_id', None) if activity_id and sessionstore.redis.exists( 'activity_item_'+activity_id): item_str = sessionstore.get('activity_item_'+activity_id) item_json = json.loads(item_str) if 'metainfo' in item_json: record = item_json.get('metainfo') if 'files' in item_json: files = item_json.get('files') if 'endpoints' in item_json: endpoints = item_json.get('endpoints') need_file = False if 'filename' in json.dumps(item_type.schema): need_file = True return render_template( 'weko_items_ui/iframe/item_edit.html', need_file=need_file, record=record, jsonschema=json_schema, schemaform=schema_form, id=item_type_id, item_save_uri=url_for('.iframe_save_model'), files=files, endpoints=endpoints ) except: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def render_itemtype(self, item_type_id=0): """Renderer.""" result = None if item_type_id > 0: result = ItemTypes.get_by_id(id_=item_type_id) if result is None: result = { 'table_row': [], 'table_row_map': {}, 'meta_list': {}, 'schemaeditor': { 'schema': {} } } else: result = result.render return jsonify(result)
def item_login(item_type_id=0): """Return information that item register need. :param item_type_id: Item type ID. (Default: 0) """ template_url = 'weko_items_ui/iframe/item_edit.html' need_file = False record = {} json_schema = '' schema_form = '' item_save_uri = url_for('weko_items_ui.iframe_save_model') files = [] endpoints = {} try: item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: template_url = 'weko_items_ui/iframe/error.html' json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) 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')))) activity_session = session['activity_info'] activity_id = activity_session.get('activity_id', None) if activity_id and sessionstore.redis.exists( 'activity_item_' + activity_id): item_str = sessionstore.get('activity_item_' + activity_id) item_json = json.loads(item_str) if 'metainfo' in item_json: record = item_json.get('metainfo') if 'files' in item_json: files = item_json.get('files') if 'endpoints' in item_json: endpoints = item_json.get('endpoints') if 'filename' in json.dumps(item_type.schema): need_file = True except Exception as e: template_url = 'weko_items_ui/iframe/error.html' current_app.logger.debug(str(e)) return template_url, need_file, record, json_schema, \ schema_form, item_save_uri, files, endpoints
def get_item_type(item_type_id=0) -> dict: """Get item type. :param item_type_id: Item type ID. (Default: 0). :return: The json object. """ result = None if item_type_id > 0: itemtype = ItemTypes.get_by_id(item_type_id) if itemtype and itemtype.schema \ and itemtype.item_type_name.name and item_type_id: result = { 'schema': itemtype.schema, 'name': itemtype.item_type_name.name, 'item_type_id': item_type_id } if result is None: return {} return result
def mapping_index(ItemTypeID=0): """Renders an item type mapping view. :param ItemTypeID: Item type ID. (Default: 0) :return: The rendered template. """ lists = ItemTypes.get_all() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMTYPES_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(ItemTypeID) if item_type is None: return redirect(url_for('.mapping_index', ItemTypeID=lists[0].id)) item_type_mapping = Mapping.get_record(ItemTypeID) mapping = json.dumps(item_type_mapping, indent=4, ensure_ascii=False) current_app.logger.debug(mapping) return render_template( current_app.config['WEKO_ITEMTYPES_UI_MAPPING_TEMPLATE'], lists=lists, mapping=mapping, id=ItemTypeID)
def get_cinii_record_data(naid, item_type_id): """Get record data base on CiNii API. :param naid: The CiNii ID :param item_type_id: The item type ID :return: """ result = list() api_response = CiNiiURL(naid).get_data() if api_response["error"] \ or not isinstance(api_response['response'], dict): return result api_data = get_cinii_data_by_key(api_response, 'all') items = ItemTypes.get_by_id(item_type_id) if items is None: return result elif items.form is not None: autofill_key_tree = get_autofill_key_tree( items.form, get_cinii_autofill_item(item_type_id)) result = build_record_model(autofill_key_tree, api_data) return result
def render_itemtype(self, item_type_id=0): """Renderer.""" result = None if item_type_id > 0: result = ItemTypes.get_by_id(id_=item_type_id, with_deleted=True) if result is None: result = { 'table_row': [], 'table_row_map': {}, 'meta_list': {}, 'schemaeditor': { 'schema': {} }, 'edit_notes': {} } else: edit_notes = result.latest_edit_history result = result.render result['edit_notes'] = edit_notes return jsonify(result)
def get_json_schema(item_type_id=0): """Get json schema. :param item_type_id: Item type ID. (Default: 0) :return: The json object. """ try: result = None json_schema = None cur_lang = current_i18n.language if item_type_id > 0: if item_type_id == 20: result = ItemTypes.get_by_id(item_type_id) if result is None: return '{}' json_schema = result.schema properties = json_schema.get('properties') for key, value in properties.items(): if 'validationMessage_i18n' in value: value['validationMessage'] =\ value['validationMessage_i18n'][cur_lang] else: result = ItemTypes.get_record(item_type_id) if 'filemeta' in json.dumps(result): group_list = Group.get_group_list() group_enum = list(group_list.keys()) filemeta_group = result.get('properties').get( 'filemeta').get('items').get('properties').get( 'groups') filemeta_group['enum'] = group_enum json_schema = result if result is None: return '{}' return jsonify(json_schema) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def get_schema_form(item_type_id=0): """Get schema form. :param item_type_id: Item type ID. (Default: 0) :return: The json object. """ try: # cur_lang = 'default' # if current_app.config['I18N_SESSION_KEY'] in session: # cur_lang = session[current_app.config['I18N_SESSION_KEY']] cur_lang = current_i18n.language result = None if item_type_id > 0: result = ItemTypes.get_by_id(item_type_id) if result is None: return '["*"]' schema_form = result.form filemeta_form = schema_form[0] if 'filemeta' == filemeta_form.get('key'): group_list = Group.get_group_list() filemeta_form_group = filemeta_form.get('items')[-1] filemeta_form_group['type'] = 'select' filemeta_form_group['titleMap'] = group_list if 'default' != cur_lang: for elem in schema_form: if 'title_i18n' in elem: if cur_lang in elem['title_i18n']: if len(elem['title_i18n'][cur_lang]) > 0: elem['title'] = elem['title_i18n'][cur_lang] if 'items' in elem: for sub_elem in elem['items']: if 'title_i18n' in sub_elem: if cur_lang in sub_elem['title_i18n']: if len(sub_elem['title_i18n'][cur_lang]) > 0: sub_elem['title'] = sub_elem['title_i18n'][ cur_lang] return jsonify(schema_form) except: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def index(item_type_id=0): """Renders an item register view. :param item_type_id: Item type ID. (Default: 0) :return: The rendered template. """ try: from weko_theme.utils import get_design_layout # Get the design for widget rendering page, render_widgets = get_design_layout( current_app.config['WEKO_THEME_DEFAULT_COMMUNITY']) lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) need_file, need_billing_file = is_schema_include_key(item_type.schema) return render_template( current_app.config['WEKO_ITEMS_UI_FORM_TEMPLATE'], page=page, render_widgets=render_widgets, need_file=need_file, need_billing_file=need_billing_file, record={}, jsonschema=json_schema, schemaform=schema_form, lists=lists, id=item_type_id, files=[]) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def mapping_register(self): """Register an item type mapping.""" if request.headers['Content-Type'] != 'application/json': current_app.logger.debug(request.headers['Content-Type']) return jsonify(msg=_('Header Error')) data = request.get_json() item_type = ItemTypes.get_by_id(data.get('item_type_id')) meta_system = item_type.render.get('meta_system') lst_duplicate = check_duplicate_mapping(data.get('mapping'), meta_system, item_type) if len(lst_duplicate) > 0: return jsonify(duplicate=True, err_items=lst_duplicate, msg=_('Duplicate mapping as below:')) try: Mapping.create(item_type_id=data.get('item_type_id'), mapping=data.get('mapping')) db.session.commit() except BaseException: db.session.rollback() return jsonify(msg=_('Unexpected error occurred.')) return jsonify(msg=_('Successfully saved new mapping.'))
def default_view_method(pid, record, template=None): """Default view method. Sends ``record_viewed`` signal and renders template. """ record_viewed.send( current_app._get_current_object(), pid=pid, record=record, ) item_type_id = record.get('item_type_id') lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE'] ) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) need_file = False # if 'filemeta' in json.dumps(item_type.schema): if 'filename' in json.dumps(item_type.schema): need_file = True return render_template( template, need_file=need_file, record=record.item_metadata, jsonschema=json_schema, schemaform=schema_form, lists=lists, links=to_links_js(pid), id=item_type_id, files=to_files_js(record), pid=pid )
def get_crossref_record_data(pid, doi, item_type_id): """Get record data base on CrossRef API. :param pid: The PID :param doi: The DOI ID :param item_type_id: The item type ID :return: """ result = list() api_response = CrossRefOpenURL(pid, doi).get_data() if api_response["error"]: return result api_data = get_crossref_data_by_key(api_response, 'all') with db.session.no_autoflush: items = ItemTypes.get_by_id(item_type_id) if items is None: return result elif items.form is not None: autofill_key_tree = get_autofill_key_tree( items.form, get_crossref_autofill_item(item_type_id)) result = build_record_model(autofill_key_tree, api_data) return result
def mapping_index(ItemTypeID=0): """Renders an item type mapping view. :param ItemTypeID: Item type ID. (Default: 0) :return: The rendered template. """ try: lists = ItemTypes.get_latest() # ItemTypes.get_all() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMTYPES_UI_ERROR_TEMPLATE'] ) item_type = ItemTypes.get_by_id(ItemTypeID) if item_type is None: return redirect(url_for('.mapping_index', ItemTypeID=lists[0].id)) itemtype_list = [] itemtype_prop = item_type.schema.get('properties') for key, prop in itemtype_prop.items(): cur_lang = current_i18n.language schema_form = item_type.form elemStr = '' if 'default' != cur_lang: for elem in schema_form: if 'items' in elem: for sub_elem in elem['items']: if 'key' in sub_elem and sub_elem['key'] == key: if 'title_i18n' in sub_elem: if cur_lang in sub_elem['title_i18n']: if len(sub_elem['title_i18n'][cur_lang]) > 0: elemStr = sub_elem['title_i18n'][ cur_lang] else: elemStr = sub_elem['title'] break else: if elem['key'] == key: if 'title_i18n' in elem: if cur_lang in elem['title_i18n']: if len(elem['title_i18n'][cur_lang]) > 0: elemStr = elem['title_i18n'][ cur_lang] else: elemStr = elem['title'] if elemStr != '': break if elemStr == '': elemStr = prop.get('title') itemtype_list.append((key, elemStr)) # itemtype_list.append((key, prop.get('title'))) # jpcoar_list = [] mapping_name = request.args.get('mapping_type', 'jpcoar_mapping') jpcoar_xsd = WekoSchema.get_all() jpcoar_lists = {} for item in jpcoar_xsd: jpcoar_lists[item.schema_name] = json.loads(item.xsd) # jpcoar_prop = json.loads(jpcoar_xsd.model.xsd) # for key in jpcoar_prop.keys(): # jpcoar_list.append((key, key)) item_type_mapping = Mapping.get_record(ItemTypeID) # mapping = json.dumps(item_type_mapping, indent=4, ensure_ascii=False) return render_template( current_app.config['WEKO_ITEMTYPES_UI_MAPPING_TEMPLATE'], lists=lists, hide_mapping_prop=item_type_mapping, mapping_name=mapping_name, hide_itemtype_prop=itemtype_prop, jpcoar_prop_lists=remove_xsd_prefix(jpcoar_lists), itemtype_list=itemtype_list, id=ItemTypeID ) except: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def prepare_edit_item(): """Prepare_edit_item. Host the api which provide 2 service: Create new activity for editing flow Check permission: check if user is owner/admin/shared user request: header: Content type must be json data: pid_value: pid_value return: The result json: code: status code, msg: meassage result, data: url redirect """ def _get_workflow_by_item_type_id(item_type_name_id, item_type_id): """Get workflow settings by item type id.""" workflow = WorkFlow.query.filter_by(itemtype_id=item_type_id).first() if not workflow: item_type_list = ItemTypes.get_by_name_id(item_type_name_id) id_list = [x.id for x in item_type_list] workflow = (WorkFlow.query.filter( WorkFlow.itemtype_id.in_(id_list)).order_by( WorkFlow.itemtype_id.desc()).order_by( WorkFlow.flow_id.asc()).first()) return workflow if request.headers['Content-Type'] != 'application/json': """Check header of request""" return jsonify(code=-1, msg=_('Header Error')) post_activity = request.get_json() pid_value = post_activity.get('pid_value') if pid_value: try: record = WekoRecord.get_record_by_pid(pid_value) owner = str(record.get('owner')) shared_id = str(record.get('weko_shared_id')) user_id = str(get_current_user()) is_admin = get_user_roles() activity = WorkActivity() pid_object = PersistentIdentifier.get('recid', pid_value) latest_pid = PIDVersioning(child=pid_object).last_child # check user's permission if user_id != owner and not is_admin[0] and user_id != shared_id: return jsonify( code=-1, msg=_(r"You are not allowed to edit this item.")) lists = ItemTypes.get_latest() if not lists: return jsonify(code=-1, msg=_(r"You do not even have an Itemtype.")) item_type_id = record.get('item_type_id') item_type = ItemTypes.get_by_id(item_type_id) if not item_type: return jsonify(code=-1, msg=_(r"This itemtype isn't found.")) # check item is being editied item_id = latest_pid.object_uuid workflow_activity = activity.get_workflow_activity_by_item_id( item_id) if not workflow_activity: # get workflow of first record attached version ID: x.1 workflow_activity = activity.get_workflow_activity_by_item_id( pid_object.object_uuid) # if workflow of the item is not found # use default settings of item type to which the item belongs else: # show error when has stt is Begin or Doing if workflow_activity.action_status == \ ActionStatusPolicy.ACTION_BEGIN \ or workflow_activity.action_status == \ ActionStatusPolicy.ACTION_DOING: return jsonify(code=-1, msg=_(r"The workflow is being edited.")) # prepare params for new workflow activity if workflow_activity: post_activity['workflow_id'] = workflow_activity.workflow_id post_activity['flow_id'] = workflow_activity.flow_id else: workflow = _get_workflow_by_item_type_id( item_type.name_id, item_type_id) if not workflow: return jsonify(code=-1, msg=_('Workflow setting does not exist.')) post_activity['workflow_id'] = workflow.id post_activity['flow_id'] = workflow.flow_id post_activity['itemtype_id'] = item_type_id getargs = request.args community = getargs.get('community', None) # Create a new version of a record. record = WekoDeposit.get_record(item_id) if not record: return jsonify(code=-1, msg=_('Record does not exist.')) deposit = WekoDeposit(record, record.model) draft_record = deposit.newversion(pid_object) if not draft_record: return jsonify(code=-1, msg=_('An error has occurred.')) # Create snapshot bucket for draft record from invenio_records_files.models import RecordsBuckets try: with db.session.begin_nested(): from weko_workflow.utils import delete_bucket draft_deposit = WekoDeposit(draft_record, draft_record.model) snapshot = record.files.bucket.snapshot(lock=False) snapshot.locked = False draft_deposit['_buckets'] = {'deposit': str(snapshot.id)} draft_record_bucket = RecordsBuckets.create( record=draft_record.model, bucket=snapshot) # Remove duplicated buckets draft_record_buckets = RecordsBuckets.query.filter_by( record_id=draft_record.model.id).all() for record_bucket in draft_record_buckets: if record_bucket != draft_record_bucket: delete_bucket_id = record_bucket.bucket_id RecordsBuckets.query.filter_by( bucket_id=delete_bucket_id).delete() delete_bucket(delete_bucket_id) draft_deposit.commit() except Exception as ex: db.session.rollback() current_app.logger.exception(str(ex)) return jsonify(code=-1, msg=_('An error has occurred.')) # Create a new workflow activity. rtn = activity.init_activity(post_activity, community, draft_record.model.id) if rtn: # GOTO: TEMPORARY EDIT MODE FOR IDENTIFIER identifier_actionid = get_actionid('identifier_grant') if workflow_activity: identifier = activity.get_action_identifier_grant( workflow_activity.activity_id, identifier_actionid) else: identifier = activity.get_action_identifier_grant( '', identifier_actionid) if identifier: if identifier.get('action_identifier_select') > \ IDENTIFIER_GRANT_DOI: identifier['action_identifier_select'] = \ IDENTIFIER_GRANT_CAN_WITHDRAW elif identifier.get('action_identifier_select') == \ IDENTIFIER_GRANT_IS_WITHDRAWING: identifier['action_identifier_select'] = \ IDENTIFIER_GRANT_WITHDRAWN activity.create_or_update_action_identifier( rtn.activity_id, identifier_actionid, identifier) mail_list = FeedbackMailList.get_mail_list_by_item_id( item_id=pid_object.object_uuid) if mail_list: activity.create_or_update_action_feedbackmail( activity_id=rtn.activity_id, action_id=ITEM_REGISTRATION_ACTION_ID, feedback_maillist=mail_list) if community: comm = GetCommunity.get_community_by_id(community) url_redirect = url_for('weko_workflow.display_activity', activity_id=rtn.activity_id, community=comm.id) else: url_redirect = url_for('weko_workflow.display_activity', activity_id=rtn.activity_id) return jsonify(code=0, msg='success', data={'redirect': url_redirect}) except Exception as e: current_app.logger.error('Unexpected error: ', str(e)) return jsonify(code=-1, msg=_('An error has occurred.'))
def default_view_method(pid, record, template=None): """Default view method. Sends ``record_viewed`` signal and renders template. """ check_site_license_permission() send_info = dict() send_info['site_license_flag'] = True \ if hasattr(current_user, 'site_license_flag') else False send_info['site_license_name'] = current_user.site_license_name \ if hasattr(current_user, 'site_license_name') else '' record_viewed.send(current_app._get_current_object(), pid=pid, record=record, info=send_info) item_type_id = record.get('item_type_id') lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) 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')))) files = to_files_js(record) record = record.item_metadata endpoints = {} activity_session = session['activity_info'] activity_id = activity_session.get('activity_id', None) if activity_id and sessionstore.redis.exists('activity_item_' + activity_id): item_str = sessionstore.get('activity_item_' + activity_id) item_json = json.loads(item_str) if 'metainfo' in item_json: record = item_json.get('metainfo') if 'files' in item_json: files = item_json.get('files') if 'endpoints' in item_json: endpoints = item_json.get('endpoints') need_file, need_billing_file = is_schema_include_key(item_type.schema) return render_template( template, need_file=need_file, need_billing_file=need_billing_file, record=record, jsonschema=json_schema, schemaform=schema_form, lists=lists, links=to_links_js(pid), id=item_type_id, files=files, pid=pid, item_save_uri=url_for('weko_items_ui.iframe_save_model'), endpoints=endpoints)
def get_schema_form(item_type_id=0): """Get schema form. :param item_type_id: Item type ID. (Default: 0) :return: The json object. """ try: cur_lang = current_i18n.language result = None if item_type_id > 0: result = ItemTypes.get_by_id(item_type_id) if result is None: return '["*"]' schema_form = result.form filemeta_form = schema_form[0] if 'filemeta' == filemeta_form.get('key'): group_list = Group.get_group_list() filemeta_form_group = filemeta_form.get('items')[-1] filemeta_form_group['type'] = 'select' filemeta_form_group['titleMap'] = group_list from .utils import recursive_form recursive_form(schema_form) # Check role for input(5 item type) update_sub_items_by_user_role(item_type_id, schema_form) # hidden option hidden_subitem = [ 'subitem_thumbnail', 'subitem_systemidt_identifier', 'subitem_systemfile_datetime', 'subitem_systemfile_filename', 'subitem_system_id_rg_doi', 'subitem_system_date_type', 'subitem_system_date', 'subitem_system_identifier_type', 'subitem_system_identifier', 'subitem_system_text' ] for i in hidden_subitem: hidden_items = [ schema_form.index(form) for form in schema_form if form.get('items') and form['items'][0]['key'].split('.')[1] in i ] if hidden_items and i in json.dumps(schema_form): schema_form = update_schema_remove_hidden_item( schema_form, result.render, hidden_items) for elem in schema_form: set_multi_language_name(elem, cur_lang) if 'items' in elem: items = elem['items'] for item in items: set_multi_language_name(item, cur_lang) if 'default' != cur_lang: for elem in schema_form: if 'title_i18n' in elem and cur_lang in elem['title_i18n']\ and len(elem['title_i18n'][cur_lang]) > 0: elem['title'] = elem['title_i18n'][cur_lang] if 'items' in elem: for sub_elem in elem['items']: if 'title_i18n' in sub_elem and cur_lang in \ sub_elem['title_i18n'] and len( sub_elem['title_i18n'][cur_lang]) > 0: sub_elem['title'] = sub_elem['title_i18n'][ cur_lang] if sub_elem.get('title') == 'Group/Price': for sub_item in sub_elem['items']: if sub_item['title'] == "価格" and \ 'validationMessage_i18n' in sub_item and \ cur_lang in sub_item[ 'validationMessage_i18n'] and\ len(sub_item['validationMessage_i18n'] [cur_lang]) > 0: sub_item['validationMessage'] = sub_item[ 'validationMessage_i18n'][cur_lang] if 'items' in sub_elem: for sub_item in sub_elem['items']: if 'title_i18n' in sub_item and cur_lang in \ sub_item['title_i18n'] and len( sub_item['title_i18n'][cur_lang]) > 0: sub_item['title'] = sub_item['title_i18n'][ cur_lang] return jsonify(schema_form) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def prepare_edit_item(): """Prepare_edit_item. Host the api which provide 2 service: Create new activity for editing flow Check permission: check if user is owner/admin/shared user request: header: Content type must be json data: pid_value: pid_value return: The result json: code: status code, msg: meassage result, data: url redirect """ if request.headers['Content-Type'] != 'application/json': """Check header of request""" return jsonify(code=-1, msg=_('Header Error')) post_activity = request.get_json() pid_value = post_activity.get('pid_value') if pid_value: try: record = WekoRecord.get_record_by_pid(pid_value) owner = str(record.get('owner')) shared_id = str(record.get('weko_shared_id')) user_id = str(get_current_user()) is_admin = get_user_roles() activity = WorkActivity() pid_object = PersistentIdentifier.get('recid', pid_value) # check item is being editied item_id = pid_object.object_uuid workflow_action_stt = \ activity.get_workflow_activity_status_by_item_id( item_id=item_id) # show error when has stt is Begin or Doing if workflow_action_stt is not None and \ (workflow_action_stt == ActionStatusPolicy.ACTION_BEGIN or workflow_action_stt == ActionStatusPolicy.ACTION_DOING): return jsonify(code=-13, msg=_('The workflow is being edited. ')) if user_id != owner and not is_admin[0] and user_id != shared_id: return jsonify(code=-1, msg=_('You are not allowed to edit this item.')) lists = ItemTypes.get_latest() if not lists: return jsonify(code=-1, msg=_('You do not even have an itemtype.')) item_type_id = record.get('item_type_id') item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return jsonify(code=-1, msg=_('This itemtype not found.')) upt_current_activity = activity.upt_activity_detail( item_id=pid_object.object_uuid) if upt_current_activity is not None: post_activity['workflow_id'] = upt_current_activity.workflow_id post_activity['flow_id'] = upt_current_activity.flow_id post_activity['itemtype_id'] = item_type_id getargs = request.args community = getargs.get('community', None) # Create a new version of a record. record = WekoDeposit.get_record(item_id) if record is None: return jsonify(code=-1, msg=_('Record does not exist.')) deposit = WekoDeposit(record, record.model) new_record = deposit.newversion(pid_object) if new_record is None: return jsonify(code=-1, msg=_('An error has occurred.')) rtn = activity.init_activity(post_activity, community, new_record.model.id) if rtn: # GOTO: TEMPORARY EDIT MODE FOR IDENTIFIER identifier_actionid = get_actionid('identifier_grant') identifier = activity.get_action_identifier_grant( upt_current_activity.activity_id, identifier_actionid) if identifier: if identifier.get('action_identifier_select') > \ IDENTIFIER_GRANT_DOI: identifier['action_identifier_select'] = \ IDENTIFIER_GRANT_CAN_WITHDRAW elif identifier.get('action_identifier_select') == \ IDENTIFIER_GRANT_IS_WITHDRAWING: identifier['action_identifier_select'] = \ IDENTIFIER_GRANT_WITHDRAWN activity.create_or_update_action_identifier( rtn.activity_id, identifier_actionid, identifier) if community: comm = GetCommunity.get_community_by_id(community) url_redirect = url_for( 'weko_workflow.display_activity', activity_id=rtn.activity_id, community=comm.id) else: url_redirect = url_for( 'weko_workflow.display_activity', activity_id=rtn.activity_id) return jsonify(code=0, msg='success', data={'redirect': url_redirect}) except Exception as e: current_app.logger.error('Unexpected error: ', str(e)) return jsonify(code=-1, msg=_('An error has occurred.'))
def item_type_info(self): """Return the information of item type.""" item_type = ItemTypes.get_by_id(self.get('item_type_id')) return '{}({})'.format(item_type.item_type_name.name, item_type.tag)
def item_login(item_type_id=0): """Return information that item register need. :param item_type_id: Item type ID. (Default: 0) """ template_url = 'weko_items_ui/iframe/item_edit.html' need_file = False need_billing_file = False record = {} json_schema = '' schema_form = '' item_save_uri = url_for('weko_items_ui.iframe_save_model') files = [] endpoints = {} need_thumbnail = False files_thumbnail = [] allow_multi_thumbnail = False try: item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: template_url = 'weko_items_ui/iframe/error.html' json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) 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')))) activity_session = session['activity_info'] activity_id = activity_session.get('activity_id', None) if activity_id and sessionstore.redis.exists('activity_item_' + activity_id): item_str = sessionstore.get('activity_item_' + activity_id) item_json = json.loads(item_str) if 'metainfo' in item_json: record = item_json.get('metainfo') if 'files' in item_json: files = item_json.get('files') files_thumbnail = [ i for i in files if 'is_thumbnail' in i.keys() and i['is_thumbnail'] ] if 'endpoints' in item_json: endpoints = item_json.get('endpoints') need_file, need_billing_file = is_schema_include_key(item_type.schema) if 'subitem_thumbnail' in json.dumps(item_type.schema): need_thumbnail = True key = [ i[0].split('.')[0] for i in find_items(item_type.form) if 'subitem_thumbnail' in i[0] ] option = item_type.render.get('meta_list', {}). \ get(key[0].split('[')[0], {}).get('option') if option: allow_multi_thumbnail = option.get('multiple') except Exception as e: template_url = 'weko_items_ui/iframe/error.html' current_app.logger.debug(str(e)) return template_url, need_file, need_billing_file, \ record, json_schema, schema_form, \ item_save_uri, files, endpoints, need_thumbnail, files_thumbnail, \ allow_multi_thumbnail
def index(self, ItemTypeID=0): """Renders an item type mapping view. :param ItemTypeID: Item type ID. (Default: 0) :return: The rendered template. """ try: lists = ItemTypes.get_latest() # ItemTypes.get_all() if lists is None or len(lists) == 0: return self.render( current_app.config['WEKO_ITEMTYPE' 'S_UI_ADMIN_ERROR_TEMPLATE'] ) item_type = ItemTypes.get_by_id(ItemTypeID) if item_type is None: current_app.logger.info(lists[0].item_type[0]) return redirect(url_for('itemtypesmapping.index', ItemTypeID=lists[0].item_type[0].id)) itemtype_list = [] itemtype_prop = item_type.schema.get('properties') sys_admin = current_app.config['WEKO_ADMIN_PERMISSION_ROLE_SYSTEM'] is_admin = False with db.session.no_autoflush: for role in list(current_user.roles or []): if role.name == sys_admin: is_admin = True break cur_lang = current_i18n.language meta_system = item_type.render.get('meta_system') table_rows = ['pubdate'] render_table_row = item_type.render.get('table_row') meta_system_items = ['system_identifier_doi', 'system_identifier_hdl', 'system_identifier_uri', 'system_file', 'updated_date', 'created_date', 'persistent_identifier_doi', 'persistent_identifier_h', 'ranking_page_url', 'belonging_index_info'] for key in meta_system_items: if isinstance(meta_system, dict) and meta_system.get(key) \ and isinstance(meta_system[key], dict): if meta_system[key]['title_i18n'] and cur_lang in \ meta_system[key]['title_i18n'] and \ meta_system[key]['title_i18n'][cur_lang] and \ meta_system[key]['title_i18n'][cur_lang].strip(): meta_system[key]['title'] = \ meta_system[key]['title_i18n'][cur_lang] else: meta_system[key]['title'] = \ meta_system[key]['title_i18n']['en'] if \ meta_system[key]['title_i18n'] and \ meta_system[key]['title_i18n']['en'] else '' if isinstance(render_table_row, list): table_rows.extend(render_table_row) for key in table_rows: prop = itemtype_prop.get(key) schema_form = item_type.form elem_str = '' if 'default' != cur_lang: for elem in schema_form: if 'items' in elem: if elem['key'] == key: if 'title_i18n' in elem: if cur_lang in elem['title_i18n']: if len(elem['title_i18n'] [cur_lang]) > 0: elem_str = elem['title_i18n'][ cur_lang] else: elem_str = elem['title'] for sub_elem in elem['items']: if 'key' in sub_elem and \ sub_elem['key'] == key: if 'title_i18n' in sub_elem: if cur_lang in sub_elem['title_i18n']: if len( sub_elem['title_i18n'][ cur_lang]) > 0: elem_str = \ sub_elem['title_i18n'][ cur_lang] else: elem_str = sub_elem['title'] break else: if elem['key'] == key: if 'title_i18n' in elem: if cur_lang in elem['title_i18n']: if len(elem['title_i18n'] [cur_lang]) > 0: elem_str = elem['title_i18n'][ cur_lang] else: elem_str = elem['title'] if elem_str != '': break if elem_str == '': elem_str = prop.get('title') itemtype_list.append((key, elem_str)) mapping_name = request.args.get('mapping_type', 'jpcoar_mapping') jpcoar_xsd = WekoSchema.get_all() jpcoar_lists = {} for item in jpcoar_xsd: jpcoar_lists[item.schema_name] = json.loads(item.xsd) item_type_mapping = Mapping.get_record(ItemTypeID) return self.render( current_app.config['WEKO_ITEMTYPES_UI_ADMIN_MAPPING_TEMPLATE'], lists=lists, hide_mapping_prop=item_type_mapping, mapping_name=mapping_name, hide_itemtype_prop=itemtype_prop, jpcoar_prop_lists=remove_xsd_prefix(jpcoar_lists), meta_system=meta_system, itemtype_list=itemtype_list, id=ItemTypeID, is_system_admin=is_admin, lang_code=session.get('selected_language', 'en') # Set default ) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def index(self, ItemTypeID=0): """Renders an item type mapping view. :param ItemTypeID: Item type ID. (Default: 0) :return: The rendered template. """ try: lists = ItemTypes.get_latest() # ItemTypes.get_all() if lists is None or len(lists) == 0: return self.render( current_app. config['WEKO_ITEMTYPES_UI_ADMIN_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(ItemTypeID) if item_type is None: current_app.logger.info(lists[0].item_type[0]) return redirect( url_for('itemtypesmapping.index', ItemTypeID=lists[0].item_type[0].id)) itemtype_list = [] itemtype_prop = item_type.schema.get('properties') table_rows = ['pubdate'] render_table_row = item_type.render.get('table_row') if isinstance(render_table_row, list): table_rows.extend(render_table_row) for key in table_rows: prop = itemtype_prop.get(key) cur_lang = current_i18n.language schema_form = item_type.form elemStr = '' if 'default' != cur_lang: for elem in schema_form: if 'items' in elem: for sub_elem in elem['items']: if 'key' in sub_elem and sub_elem['key'] == key: if 'title_i18n' in sub_elem: if cur_lang in sub_elem['title_i18n']: if len(sub_elem['title_i18n'] [cur_lang]) > 0: elemStr = sub_elem[ 'title_i18n'][cur_lang] else: elemStr = sub_elem['title'] break else: if elem['key'] == key: if 'title_i18n' in elem: if cur_lang in elem['title_i18n']: if len(elem['title_i18n'] [cur_lang]) > 0: elemStr = elem['title_i18n'][ cur_lang] else: elemStr = elem['title'] if elemStr != '': break if elemStr == '': elemStr = prop.get('title') itemtype_list.append((key, elemStr)) mapping_name = request.args.get('mapping_type', 'jpcoar_mapping') jpcoar_xsd = WekoSchema.get_all() jpcoar_lists = {} for item in jpcoar_xsd: jpcoar_lists[item.schema_name] = json.loads(item.xsd) item_type_mapping = Mapping.get_record(ItemTypeID) return self.render( current_app.config['WEKO_ITEMTYPES_UI_ADMIN_MAPPING_TEMPLATE'], lists=lists, hide_mapping_prop=item_type_mapping, mapping_name=mapping_name, hide_itemtype_prop=itemtype_prop, jpcoar_prop_lists=remove_xsd_prefix(jpcoar_lists), itemtype_list=itemtype_list, id=ItemTypeID, lang_code=session.get('selected_language', 'en') # Set default ) except BaseException as e: current_app.logger.error('Unexpected error: ', e) return abort(400)