Example #1
0
def default_view_method(pid, record, template=None):
    """Default view method for updating record.

    Sends ``record_viewed`` signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    """
    # Fetch deposit id from record and resolve deposit record and pid.
    depid = zenodo_deposit_fetcher(None, record)
    if not depid:
        abort(404)

    depid, deposit = Resolver(
        pid_type=depid.pid_type,
        object_type='rec',
        getter=ZenodoDeposit.get_record,
    ).resolve(depid.pid_value)

    # Put deposit in edit mode if not already.
    if deposit['_deposit']['status'] != 'draft':
        deposit = deposit.edit()
        db.session.commit()

    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )
    return render_template(
        template,
        pid=pid,
        record=record,
    )
Example #2
0
def doc_item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :return: The rendered template.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)

    viewcode = kwargs['viewcode']

    record['available'] = record.is_available(viewcode)

    holdings = [
        Holding.get_record_by_pid(holding_pid).replace_refs()
        for holding_pid in Holding.get_holdings_by_document_by_view_code(
            document_pid=pid.pid_value, viewcode=viewcode)
    ]

    return render_template(template,
                           pid=pid,
                           record=record,
                           holdings=holdings,
                           viewcode=viewcode,
                           recordType='documents')
Example #3
0
def holding_view_method(pid, record, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param **kwargs: Additional view arguments based on URL rule.
    :return: The rendered template.
    """
    record_viewed.send(
        current_app._get_current_object(), pid=pid, record=record
    )
    document_pid = extracted_data_from_ref(record.get('document'))
    document = Document.get_record_by_pid(document_pid)
    location_pid = extracted_data_from_ref(record.get('location'))
    location = Location.get_record_by_pid(location_pid)
    library_pid = extracted_data_from_ref(location.get('library'))
    library = Library.get_record_by_pid(library_pid)
    item_type_pid = extracted_data_from_ref(record.get('circulation_category'))
    circulation_category = ItemType.get_record_by_pid(item_type_pid)
    items = record.get_items_filter_by_viewcode(kwargs['viewcode'])
    return render_template(
        template, pid=pid, record=record, document=document,
        location=location, circulation_category=circulation_category,
        library=library, viewcode=kwargs['viewcode'], items=items)
Example #4
0
def item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)
    document = Document.get_record_by_pid(
        record.replace_refs()['document']['pid'])
    item = record.replace_refs()
    location = Location.get_record_by_pid(item['location']['pid'])
    library = Library.get_record_by_pid(
        location.replace_refs()['library']['pid'])
    item_type = ItemType.get_record_by_pid(item['item_type']['pid'])
    return render_template(template,
                           pid=pid,
                           record=record,
                           document=document,
                           location=location,
                           library=library,
                           item_type=item_type)
Example #5
0
def default_view_method(pid, record, template=None):
    """Default view method for updating record.

    Sends ``record_viewed`` signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    """
    # Fetch deposit id from record and resolve deposit record and pid.
    depid = zenodo_deposit_fetcher(None, record)
    if not depid:
        abort(404)

    depid, deposit = Resolver(
        pid_type=depid.pid_type,
        object_type='rec',
        getter=ZenodoDeposit.get_record,
    ).resolve(depid.pid_value)

    # Put deposit in edit mode if not already.
    if deposit['_deposit']['status'] != 'draft':
        deposit = deposit.edit()
        db.session.commit()

    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )
    return render_template(
        template,
        pid=pid,
        record=record,
    )
Example #6
0
def doc_item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(
        current_app._get_current_object(), pid=pid, record=record)
    items = [
        Item.get_record_by_pid(item_pid)
        for item_pid in Item.get_items_pid_by_document_pid(pid.pid_value)
    ]
    viewcode = kwargs['viewcode']
    # Item(s) filter
    if viewcode != current_app.config.get('RERO_ILS_SEARCH_GLOBAL_VIEW_CODE'):
        org_pid = Organisation.get_record_by_viewcode(viewcode)['pid']
        items = document_items_filter(org_pid, items)

    return render_template(
        template,
        pid=pid,
        record=record,
        items=items,
        viewcode=viewcode
    )
Example #7
0
def contribution_view_method(pid, record, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)

    # Get contribution persons documents
    search = DocumentsSearch().filter('term',
                                      contribution__agent__pid=pid.pid_value)

    viewcode = kwargs['viewcode']
    if (viewcode !=
            current_app.config.get('RERO_ILS_SEARCH_GLOBAL_VIEW_CODE')):
        org_pid = Organisation.get_record_by_viewcode(viewcode)['pid']
        search = search \
            .filter('term', holdings__organisation__organisation_pid=org_pid)
    search = search \
        .params(preserve_order=True)\
        .sort({'sort_title': {"order": "asc"}})

    record['documents'] = list(search.scan())
    return render_template(template, record=record, viewcode=viewcode)
Example #8
0
def holding_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)
    document = Document.get_record_by_pid(
        record.replace_refs()['document']['pid'])
    holding = record.replace_refs()
    location = Location.get_record_by_pid(holding['location']['pid'])
    library = Library.get_record_by_pid(
        location.replace_refs()['library']['pid'])
    circulation_category = ItemType.get_record_by_pid(
        holding['circulation_category']['pid'])
    items = record.get_items_filter_by_viewcode(kwargs['viewcode'])
    return render_template(template,
                           pid=pid,
                           record=record,
                           document=document,
                           location=location,
                           circulation_category=circulation_category,
                           library=library,
                           viewcode=kwargs['viewcode'],
                           items=items)
Example #9
0
def similar_records(pid, record, template=None, **kwargs):
    """Render similar records for given record
    
    Based on /home/daniel/git/zenodo-dev/zenodo/zenodo/config.py see records_ui_export
    """
    formats = current_app.config.get('ZENODO_RECORDS_EXPORTFORMATS')
    fmt = request.view_args.get('format')

    if formats.get(fmt) is None:
        return render_template(
            'zenodo_records/records_export_unsupported.html'), 410
    else:
        serializer = import_string(formats[fmt]['serializer'])
        data = serializer.serialize(pid, record)
        if isinstance(data, six.binary_type):
            data = data.decode('utf8')

        # emit record_viewed event
        record_viewed.send(
            current_app._get_current_object(),
            pid=pid,
            record=record,
        )
        return render_template(
            template, pid=pid, record=record,
            data=data, format_title=formats[fmt]['title'])
Example #10
0
def collection_view_method(pid, record, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)

    viewcode = kwargs['viewcode']
    org_pid = Organisation.get_record_by_viewcode(viewcode)['pid']
    rec = record.replace_refs()
    libraries = []

    if org_pid != rec.get('organisation').get('pid'):
        abort(404, 'The collections is not referenced for this organisation')
    # Get items and document title
    rec['items'] = record.get_items()
    for item in rec['items']:
        item['document'] = Document.get_record_by_pid(
            item.replace_refs().get('document').get('pid'))
    # Get libraries names
    for library in rec.get('libraries'):
        libraries.append(Library.get_record_by_pid(library['pid']).get('name'))
    rec['libraries'] = ', '.join(libraries)
    # Format date
    rec['date'] = _start_end_date(record.get('start_date'),
                                  record.get('end_date'))

    return render_template(template, record=rec, viewcode=viewcode)
Example #11
0
def project_view(pid, record, template=None, **kwargs):
    """Edit project view."""
    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )
    return render_template(
        template,
        pid=pid,
        record=record,
        record_type='project',
    )
Example #12
0
def detail(pid, record, template=None, **kwargs):
    r"""Document detailed view.

    Sends record_viewed signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    # Add restriction, link and thumbnail to files
    if record.get('_files'):
        # Check if organisation's record forces to point file to an external
        # url
        record['external_url'] = has_external_urls_for_files(record)

        populate_files_properties(record)

    # Import is here to avoid a circular reference error.
    from sonar.modules.documents.serializers import google_scholar_v1, \
        schemaorg_v1

    # Get schema org data
    schema_org_data = json.dumps(
        schemaorg_v1.transform_record(record['pid'], record))

    # Get scholar data
    google_scholar_data = google_scholar_v1.transform_record(
        record['pid'], record)

    # Resolve $ref properties
    record = record.replace_refs()

    # Record is masked
    if record.is_masked:
        abort(403)

    # Send signal when record is viewed
    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )

    return render_template(template,
                           pid=pid,
                           record=record,
                           view=kwargs.get('view'),
                           schema_org_data=schema_org_data,
                           google_scholar_data=google_scholar_data)
Example #13
0
def doc_item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :return: The rendered template.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)

    viewcode = kwargs['viewcode']
    organisation = None
    if viewcode != current_app.config.get('RERO_ILS_SEARCH_GLOBAL_VIEW_CODE'):
        organisation = Organisation.get_record_by_viewcode(viewcode)

    record['available'] = record.is_available(viewcode)

    # TODO: later Refactoring this part
    # Use ES to order holdings records
    # Pass directly the ES holdings to the template
    # and create some pipe to process record
    from ..holdings.api import HoldingsSearch
    query = results = HoldingsSearch()\
        .filter('term', document__pid=pid.pid_value)
    if organisation:
        query = query.filter('term', organisation__pid=organisation.pid)
    results = query\
        .sort({'library_location': {"order": "asc"}})\
        .source('pid').scan()

    holdings = [
        Holding.get_record_by_pid(holding_pid).replace_refs()
        for holding_pid in [r.pid for r in results]
    ]

    return render_template(template,
                           pid=pid,
                           record=record,
                           holdings=holdings,
                           viewcode=viewcode,
                           recordType='documents')
Example #14
0
def doc_item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)
    items = [
        Item.get_record_by_pid(item_pid)
        for item_pid in Item.get_items_pid_by_document_pid(pid.pid_value)
    ]
    return render_template(template, pid=pid, record=record, items=items)
Example #15
0
def item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )
    document = DocumentsWithItems.get_document_by_itemid(record.id)
    return render_template(template, pid=pid, record=record, document=document)
Example #16
0
def records_ui_export(pid, record, template=None, **kwargs):
    """Record serialization view.

    Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:

    .. code-block:: python

        RECORDS_UI_ENDPOINTS = dict(
            recid=dict(
                # ...
                route='/records/<pid_value/files/<filename>',
                view_imp='zenodo.modules.records.views.records_ui_export',
            )
        )
    """
    formats = current_app.config.get('ZENODO_RECORDS_EXPORTFORMATS')
    fmt = request.view_args.get('format')

    if formats.get(fmt) is None:
        return render_template(
            'zenodo_records/records_export_unsupported.html'), 410
    else:
        serializer = import_string(formats[fmt]['serializer'])
        # Pretty print if JSON
        if isinstance(serializer, ZenodoJSONSerializer):
            json_data = serializer.transform_record(pid, record)
            data = json.dumps(json_data, indent=2, separators=(', ', ': '))
        else:
            data = serializer.serialize(pid, record)
        if isinstance(data, six.binary_type):
            data = data.decode('utf8')

        # emit record_viewed event
        record_viewed.send(
            current_app._get_current_object(),
            pid=pid,
            record=record,
        )
        return render_template(template,
                               pid=pid,
                               record=record,
                               data=data,
                               format_code=fmt,
                               format_title=formats[fmt]['title'])
Example #17
0
def doc_item_view_method(pid, record, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param **kwargs: Additional view arguments based on URL rule.
    :return: The rendered template.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)

    viewcode = kwargs['viewcode']
    organisation = None
    if viewcode != current_app.config.get('RERO_ILS_SEARCH_GLOBAL_VIEW_CODE'):
        organisation = Organisation.get_record_by_viewcode(viewcode)

    record['available'] = Document.is_available(record.pid, viewcode)

    # build provision activity
    provision_activities = record.get('provisionActivity', [])
    for provision_activity in provision_activities:
        pub_state_text = publication_statement_text(provision_activity)
        if pub_state_text:
            provision_activity['_text'] = pub_state_text

    # Counting holdings to display the get button
    from ..holdings.api import HoldingsSearch
    query = HoldingsSearch()\
        .filter('term', document__pid=pid.pid_value)
    query = query.filter('bool', must_not=[Q('term', _masked=True)])
    if organisation:
        query = query.filter('term', organisation__pid=organisation.pid)
    holdings_count = query.count()

    return render_template(template,
                           pid=pid,
                           record=record,
                           holdings_count=holdings_count,
                           viewcode=viewcode,
                           recordType='documents')
Example #18
0
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,
    )

    deposit_type = request.values.get('type')

    return render_template(
        template,
        pid=pid,
        record=record,
        jsonschema=current_deposit.jsonschemas[deposit_type],
        schemaform=current_deposit.schemaforms[deposit_type],
    )
Example #19
0
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,
    )

    deposit_type = request.values.get('type')

    return render_template(
        template,
        pid=pid,
        record=record,
        jsonschema=current_deposit.jsonschemas[deposit_type],
        schemaform=current_deposit.schemaforms[deposit_type],
    )
Example #20
0
def records_ui_export(pid, record, template=None, **kwargs):
    """Record serialization view.

    Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:

    .. code-block:: python

        RECORDS_UI_ENDPOINTS = dict(
            recid=dict(
                # ...
                route='/records/<pid_value/files/<filename>',
                view_imp='zenodo.modules.records.views.records_ui_export',
            )
        )
    """
    formats = current_app.config.get('ZENODO_RECORDS_EXPORTFORMATS')
    fmt = request.view_args.get('format')

    if formats.get(fmt) is None:
        return render_template(
            'zenodo_records/records_export_unsupported.html'), 410
    else:
        serializer = import_string(formats[fmt]['serializer'])
        # Pretty print if JSON
        if isinstance(serializer, ZenodoJSONSerializer):
            json_data = serializer.transform_record(pid, record)
            data = json.dumps(json_data, indent=2, separators=(', ', ': '))
        else:
            data = serializer.serialize(pid, record)
        if isinstance(data, six.binary_type):
            data = data.decode('utf8')

        # emit record_viewed event
        record_viewed.send(
            current_app._get_current_object(),
            pid=pid,
            record=record,
        )
        return render_template(
            template, pid=pid, record=record,
            data=data, format_code=fmt, format_title=formats[fmt]['title'])
Example #21
0
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
    )
Example #22
0
def detail(pid, record, template=None, **kwargs):
    r"""Project detail view.

    Sends record_viewed signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    service = sonar.service('projects')
    item = service.result_item(service, g.identity, record)

    # Send signal when record is viewed
    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )

    return render_template(template, pid=pid, record=item.data['metadata'])
Example #23
0
def default_view_method(pid, record, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )

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

    return render_template(template,
                           pid=pid,
                           record=record,
                           community_id=community_id,
                           **ctx,
                           **kwargs,
                           width=width)
Example #24
0
def edit_view_method(pid, record, template=None):
    """View method for updating record.

    Sends ``record_viewed`` signal and renders template.

    :param pid: PID object ('depid'-type PID).
    :param record: Record object (Deposit API).
    :param template: Template to render.

    Taken from zenodo/zenodo
    """
    # Put deposit in edit mode if not already.
    if record['_deposit']['status'] != 'draft':
        record = record.edit()
        db.session.commit()

    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )

    return render_template(template, pid=pid, record=record)
Example #25
0
def doc_item_view_method(pid, record, template=None, **kwargs):
    r"""Display default view.

    Sends record_viewed signal and renders template.

    :param pid: PID object.
    :param record: Record object.
    :param template: Template to render.
    :param \*\*kwargs: Additional view arguments based on URL rule.
    :returns: The rendered template.
    """
    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )
    members = Member.get_all_members()
    return render_template(
        template,
        pid=pid,
        record=record,
        members=members
    )
Example #26
0
def person_view_method(pid, record, template=None, **kwargs):
    """Display default view.

    Sends record_viewed signal and renders template.
    :param pid: PID object.
    """
    record_viewed.send(current_app._get_current_object(),
                       pid=pid,
                       record=record)

    # Get author documents
    search = DocumentsSearch().filter('term', authors__pid=pid.pid_value)

    viewcode = kwargs['viewcode']
    if (viewcode !=
            current_app.config.get('RERO_ILS_SEARCH_GLOBAL_VIEW_CODE')):
        org_pid = Organisation.get_record_by_viewcode(viewcode)['pid']
        search = search.filter(
            'term', holdings__organisation__organisation_pid=org_pid)

    record['documents'] = list(search.scan())

    return render_template(template, record=record, viewcode=viewcode)
Example #27
0
def default_view_method(pid, record, template=None):
    """Default view method for updating record.

    Sends ``record_viewed`` signal and renders template.

    :param pid: PID object ('depid'-type PID).
    :param record: Record object (Deposit API).
    :param template: Template to render.
    """
    # Put deposit in edit mode if not already.
    if record['_deposit']['status'] != 'draft':
        record = record.edit()
        db.session.commit()

    record_viewed.send(
        current_app._get_current_object(),
        pid=pid,
        record=record,
    )
    return render_template(
        template,
        pid=pid,
        record=record,
    )
Example #28
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)
Example #29
0
def default_view_method(pid, record, filename=None, template=None, **kwargs):
    r"""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.
    """
    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)
    getargs = request.args
    community_id = ""
    ctx = {'community': None}
    if 'community' in getargs:
        from weko_workflow.api import GetCommunity
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        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('')

    weko_indexer = WekoIndexer()
    res = weko_indexer.get_item_link_info(pid=record.get("control_number"))
    if res is not None:
        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 is not None \
        and pdfcoverpage_set_rec.avail != 'disable'

    # Get item meta data
    record['permalink_uri'] = None
    pidstore_identifier = get_item_pidstore_identifier(pid.object_uuid)
    if not pidstore_identifier:
        record['permalink_uri'] = request.url
    else:
        record['permalink_uri'] = pidstore_identifier

    from invenio_files_rest.permissions import has_update_version_role
    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

    return render_template(template,
                           pid=pid,
                           record=record,
                           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,
                           community_id=community_id,
                           width=width,
                           detail_condition=detail_condition,
                           height=height,
                           google_scholar_meta=google_scholar_meta,
                           **ctx,
                           **kwargs)
Example #30
0
def create_stats_fixtures(metadata, n_records, n_versions, n_files,
                          event_data, start_date, end_date, interval,
                          do_process_events=True, do_aggregate_events=True,
                          do_update_record_statistics=True):
    """Generate configurable statistics fixtures.

    :param dict metadata: Base metadata for the created records.
    :param int n_records: Number of records that will be created.
    :param int n_versions: Number of versions for each record.
    :param int n_files: Number of files for each record version.
    :param dict event_data: Base event metadata (e.g. user, user agent, etc).
    :param datetime start_date: Start date for the generated events.
    :param datetime end_date: End date for the generated events.
    :param timedelta interval: Interval between each group of events.
    :param bool do_process_events: ``True`` will run the ``process_events``
        task.
    :param bool do_aggregate_events: ``True`` will run the ``aggregate_events``
        task.
    :param bool do_update_record_statistics: ``True`` will run the
        ``update_record_statistics`` task.
    """
    records = _create_records(
        metadata, total=n_records, versions=n_versions, files=n_files)

    @contextmanager
    def _patch_stats_publish():
        original_publish = current_stats.publish

        event_batches = defaultdict(list)

        def _patched_publish(self, event_type, events):
            events[0].update(event_data)
            event_batches[event_type].append(events[0])
        current_stats.publish = MethodType(_patched_publish, current_stats)
        yield
        current_stats.publish = original_publish
        for event_type, events in event_batches.items():
            current_stats.publish(event_type, events)

    with _patch_stats_publish():
        for ts in _gen_date_range(start_date, end_date, interval):
            event_data['timestamp'] = ts.isoformat()
            for recid, record, file_objects in records:
                with current_app.test_request_context():
                    record_viewed.send(current_app._get_current_object(),
                                       pid=recid, record=record)
                    for obj in file_objects:
                        file_downloaded.send(
                            current_app._get_current_object(),
                            obj=obj, record=record)
    if do_process_events:
        process_events(['record-view', 'file-download'])
        current_search.flush_and_refresh(index='events-stats-*')

    if do_aggregate_events:
        aggregate_events(
            ['record-view-agg', 'record-view-all-versions-agg',
             'record-download-agg', 'record-download-all-versions-agg'])
        current_search.flush_and_refresh(index='stats-*')

    if do_update_record_statistics:
        update_record_statistics(start_date=start_date.isoformat(),
                                 end_date=end_date.isoformat())
        RecordIndexer().process_bulk_queue()
        current_search.flush_and_refresh(index='records')

    return records
Example #31
0
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)
Example #32
0
def create_stats_fixtures(metadata, n_records, n_versions, n_files,
                          event_data, start_date, end_date, interval,
                          do_process_events=True, do_aggregate_events=True,
                          do_update_record_statistics=True):
    """Generate configurable statistics fixtures.

    :param dict metadata: Base metadata for the created records.
    :param int n_records: Number of records that will be created.
    :param int n_versions: Number of versions for each record.
    :param int n_files: Number of files for each record version.
    :param dict event_data: Base event metadata (e.g. user, user agent, etc).
    :param datetime start_date: Start date for the generated events.
    :param datetime end_date: End date for the generated events.
    :param timedelta interval: Interval between each group of events.
    :param bool do_process_events: ``True`` will run the ``process_events``
        task.
    :param bool do_aggregate_events: ``True`` will run the ``aggregate_events``
        task.
    :param bool do_update_record_statistics: ``True`` will run the
        ``update_record_statistics`` task.
    """
    records = _create_records(
        metadata, total=n_records, versions=n_versions, files=n_files)

    @contextmanager
    def _patch_stats_publish():
        original_publish = current_stats.publish

        event_batches = defaultdict(list)

        def _patched_publish(self, event_type, events):
            events[0].update(event_data)
            event_batches[event_type].append(events[0])
        current_stats.publish = MethodType(_patched_publish, current_stats)
        yield
        current_stats.publish = original_publish
        for event_type, events in event_batches.items():
            current_stats.publish(event_type, events)

    with _patch_stats_publish():
        for ts in _gen_date_range(start_date, end_date, interval):
            event_data['timestamp'] = ts.isoformat()
            for recid, record, file_objects in records:
                with current_app.test_request_context():
                    record_viewed.send(current_app._get_current_object(),
                                       pid=recid, record=record)
                    for obj in file_objects:
                        file_downloaded.send(
                            current_app._get_current_object(),
                            obj=obj, record=record)
    if do_process_events:
        process_events(['record-view', 'file-download'])
        current_search.flush_and_refresh(index='events-stats-*')

    if do_aggregate_events:
        aggregate_events(
            ['record-view-agg', 'record-view-all-versions-agg',
             'record-download-agg', 'record-download-all-versions-agg'])
        current_search.flush_and_refresh(index='stats-*')

    if do_update_record_statistics:
        update_record_statistics(start_date=start_date.isoformat(),
                                 end_date=end_date.isoformat())
        RecordIndexer().process_bulk_queue()
        current_search.flush_and_refresh(index='records')

    return records