Example #1
0
def citation(record, pid, style=None, ln=None):
    """Render citation for record according to style and language."""
    locale = ln or "en-US"  # ln or current_i18n.language
    style = style or "aapg-bulletin"  # style or 'science'
    try:
        _record = WekoRecord.get_record(pid.object_uuid)
        return citeproc_v1.serialize(pid, _record, style=style, locale=locale)
    except Exception:
        current_app.logger.exception(
            'Citation formatting for record {0} failed.'.format(str(
                record.id)))
        return None
Example #2
0
    def get(self, pid_value, **kwargs):
        """Render citation for record according to style and language."""
        style = request.values.get('style', 1)  # style or 'science'
        locale = request.values.get('locale', 2)
        try:
            pid = PersistentIdentifier.get('depid', pid_value)
            record = WekoRecord.get_record(pid.object_uuid)

            result = citeproc_v1.serialize(pid,
                                           record,
                                           style=style,
                                           locale=locale)
            return make_response(jsonify(result), 200)
        except Exception:
            current_app.logger.exception(
                'Citation formatting for record {0} failed.'.format(
                    str(record.id)))
            return make_response(jsonify("Not found"), 404)
Example #3
0
    def _is_record_in_index(self, record_id):
        """
        Check record has register index.

        :param record_id: Identifier of record
        :return: True if record has register index_id
        """
        from .utils import get_real_path, get_pid
        if self.repository_id == current_app.config.get(
                "WEKO_ROOT_INDEX", WEKO_ROOT_INDEX):
            return True
        if self.status:

            record_pid = get_pid(record_id)
            if record_pid:
                record = WekoRecord.get_record(record_pid.object_uuid)
                if record and record.get("path"):
                    list_path = get_real_path(record.get("path"))
                    if str(self.repository_id) in list_path:
                        return True
        return False
Example #4
0
def listrecords(**kwargs):
    """Create OAI-PMH response for verb ListRecords."""
    def get_error_code_msg():
        """Get error by type."""
        code = current_app.config.get('OAISERVER_CODE_NO_RECORDS_MATCH')
        msg = current_app.config.get('OAISERVER_MESSAGE_NO_RECORDS_MATCH')
        return [(code, msg)]

    def append_deleted_record(e_listrecords, pid_object, rec):
        """Append attribute [status="deleted] for 'header' tag."""
        e_record = SubElement(e_listrecords, etree.QName(NS_OAIPMH, 'record'))
        header(e_record,
               identifier=pid_object.pid_value,
               datestamp=rec.updated,
               sets=rec.get('_oai', {}).get('sets', []),
               deleted=True)

    record_dumper = serializer(kwargs['metadataPrefix'])
    e_tree, e_listrecords = verb(**kwargs)
    result = get_records(**kwargs)
    identify = OaiIdentify.get_all()
    if not result.total or not identify or \
            (identify and not identify.outPutSetting):
        return error(get_error_code_msg(), **kwargs)
    for record in result.items:
        try:
            pid = oaiid_fetcher(record['id'], record['json']['_source'])
            pid_object = OAIIDProvider.get(pid_value=pid.pid_value).pid
            rec = WekoRecord.get_record(record['id'])
            set_identifier(record, rec)
            # Check output delete, noRecordsMatch
            if not is_private_index(rec):
                if is_deleted_workflow(pid_object) or \
                        is_private_workflow(rec):
                    append_deleted_record(e_listrecords, pid_object, rec)
                    continue
            else:
                append_deleted_record(e_listrecords, pid_object, rec)
                continue
            e_record = SubElement(e_listrecords,
                                  etree.QName(NS_OAIPMH, 'record'))
            header(
                e_record,
                identifier=pid.pid_value,
                datestamp=record['updated'],
                sets=record['json']['_source'].get('_oai', {}).get('sets', []),
            )
            e_metadata = SubElement(e_record,
                                    etree.QName(NS_OAIPMH, 'metadata'))
            etree_record = copy.deepcopy(record['json'])
            # Merge licensetype and licensefree
            handle_license_free(etree_record['_source']['_item_metadata'])
            e_metadata.append(record_dumper(pid, etree_record))
        except Exception:
            current_app.logger.error(traceback.print_exc())
            current_app.logger.error('Error when exporting item id ' +
                                     str(record['id']))
    # Check <record> tag not exist.
    if len(e_listrecords) == 0:
        return error(get_error_code_msg(), **kwargs)
    resumption_token(e_listrecords, result, **kwargs)
    return e_tree
Example #5
0
    def get_change_dump_manifest_xml(self, record_id):
        """Get change dump manifest xml.

        :param record_id: Identifier of record
        :return xml
        """
        if not self._is_record_in_index(record_id) or not self._validation():
            return None
        cdm = ChangeDumpManifest()
        cdm.up = '{}resync/{}/changedump.xml'.format(request.url_root,
                                                     self.repository_id)
        if self.change_dump_manifest:
            prev_id, prev_ver_id = record_id.split(".")
            current_record = WekoRecord.get_record_by_pid(record_id)
            from .utils import get_pid
            prev_record_pid = get_pid('{}.{}'.format(prev_id,
                                                     str(int(prev_ver_id) -
                                                         1)))
            if prev_record_pid:
                prev_record = WekoRecord.get_record(
                    id_=prev_record_pid.object_uuid)
            else:
                prev_record = None
            if current_record:
                list_file = [file for file in current_record.files]
                current_checksum = [
                    file.info().get('checksum')
                    for file in current_record.files
                ]
                prev_checksum = []
                if prev_record:
                    list_file.extend([file for file in prev_record.files])
                    prev_checksum = [
                        file.info().get('checksum')
                        for file in prev_record.files
                    ]
                for file in list_file:
                    file_info = file.info()
                    change = None
                    if file_info.get('checksum') in prev_checksum:
                        if file_info.get('checksum') in current_checksum:
                            change = None
                        if file_info.get('checksum') not in current_checksum:
                            change = 'deleted'
                    else:
                        if file_info.get('checksum') in current_checksum:
                            change = 'created'
                    path = 'recid_{}/{}'.format(current_record.get('recid'),
                                                file_info.get('key'))
                    lastmod = str(datetime.datetime.utcnow().replace(
                        tzinfo=datetime.timezone.utc).isoformat())
                    if change:
                        re = Resource(
                            '{}record/{}/files/{}'.format(
                                request.url_root, current_record.get('recid'),
                                file_info.get('key')),
                            lastmod=lastmod,
                            sha256=file_info.get('checksum').split(':')[1],
                            length=str(file_info.get('size')),
                            path=path if change != 'delete' else '',
                            change=change)
                        cdm.add(re)
        return cdm.as_xml()
Example #6
0
File: views.py Project: mhaya/weko
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)
Example #7
0
def default_view_method(pid, record, filename=None, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param filename: File name.
    :param template: Template to render.
    :param kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    # Get PID version object to retrieve all versions of item
    pid_ver = PIDVersioning(child=pid)
    if not pid_ver.exists or pid_ver.is_last_child:
        abort(404)
    active_versions = list(pid_ver.children or [])
    all_versions = list(
        pid_ver.get_children(ordered=True, pid_status=None) or [])
    try:
        if WekoRecord.get_record(id_=active_versions[-1].object_uuid
                                 )['_deposit']['status'] == 'draft':
            active_versions.pop()
        if WekoRecord.get_record(id_=all_versions[-1].object_uuid
                                 )['_deposit']['status'] == 'draft':
            all_versions.pop()
    except Exception:
        pass
    if active_versions:
        # active_versions.remove(pid_ver.last_child)
        active_versions.pop()

    check_site_license_permission()
    check_items_settings()
    send_info = {}
    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)
    community_arg = request.args.get('community')
    community_id = ""
    ctx = {'community': None}
    if community_arg:
        from weko_workflow.api import GetCommunity
        comm = GetCommunity.get_community_by_id(community_arg)
        ctx = {'community': comm}
        community_id = comm.id

    # Get index style
    style = IndexStyle.get(
        current_app.config['WEKO_INDEX_TREE_STYLE_OPTIONS']['id'])
    width = style.width if style else '3'
    height = style.height if style else None

    detail_condition = get_search_detail_keyword('')

    # Add Item Reference data to Record Metadata
    pid_without_ver = record.get("recid").split('.')[0]
    res = ItemLink.get_item_link_info(pid_without_ver)
    if res:
        record["relation"] = res
    else:
        record["relation"] = {}

    google_scholar_meta = _get_google_scholar_meta(record)

    pdfcoverpage_set_rec = PDFCoverPageSettings.find(1)
    # Check if user has the permission to download original pdf file
    # and the cover page setting is set and its value is enable (not disabled)
    can_download_original = check_original_pdf_download_permission(record) \
        and pdfcoverpage_set_rec and pdfcoverpage_set_rec.avail != 'disable'

    # Get item meta data
    record['permalink_uri'] = None
    permalink = get_record_permalink(record)
    if not permalink:
        record['permalink_uri'] = request.url
    else:
        record['permalink_uri'] = permalink

    can_update_version = has_update_version_role(current_user)

    datastore = RedisStore(
        redis.StrictRedis.from_url(current_app.config['CACHE_REDIS_URL']))
    cache_key = current_app.config['WEKO_ADMIN_CACHE_PREFIX'].\
        format(name='display_stats')
    if datastore.redis.exists(cache_key):
        curr_display_setting = datastore.get(cache_key).decode('utf-8')
        display_stats = True if curr_display_setting == 'True' else False
    else:
        display_stats = True

    groups_price = get_groups_price(record)
    billing_files_permission = get_billing_file_download_permission(
        groups_price) if groups_price else None
    billing_files_prices = get_min_price_billing_file_download(
        groups_price, billing_files_permission) if groups_price else None

    from weko_theme.utils import get_design_layout
    # Get the design for widget rendering
    page, render_widgets = get_design_layout(
        request.args.get('community')
        or current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])

    if hasattr(current_i18n, 'language'):
        index_link_list = get_index_link_list(current_i18n.language)
    else:
        index_link_list = get_index_link_list()

    files_thumbnail = []
    if record.files:
        files_thumbnail = ObjectVersion.get_by_bucket(
            record.get('_buckets').get('deposit')).\
            filter_by(is_thumbnail=True).all()
    files = []
    for f in record.files:
        if check_file_permission(record, f.data) or is_open_restricted(f.data):
            files.append(f)
    # Flag: can edit record
    can_edit = True if pid == get_record_without_version(pid) else False

    open_day_display_flg = current_app.config.get('OPEN_DATE_DISPLAY_FLG')

    return render_template(template,
                           pid=pid,
                           pid_versioning=pid_ver,
                           active_versions=active_versions,
                           all_versions=all_versions,
                           record=record,
                           files=files,
                           display_stats=display_stats,
                           filename=filename,
                           can_download_original_pdf=can_download_original,
                           is_logged_in=current_user
                           and current_user.is_authenticated,
                           can_update_version=can_update_version,
                           page=page,
                           render_widgets=render_widgets,
                           community_id=community_id,
                           width=width,
                           detail_condition=detail_condition,
                           height=height,
                           index_link_enabled=style.index_link_enabled,
                           index_link_list=index_link_list,
                           google_scholar_meta=google_scholar_meta,
                           billing_files_permission=billing_files_permission,
                           billing_files_prices=billing_files_prices,
                           files_thumbnail=files_thumbnail,
                           can_edit=can_edit,
                           open_day_display_flg=open_day_display_flg,
                           **ctx,
                           **kwargs)