コード例 #1
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def list_activity():
    """List activity."""
    activity = WorkActivity()
    getargs = request.args
    conditions = {}
    list_key_condition = [
        'createdfrom', 'createdto', 'workflow', 'user', 'item', 'status',
        'tab', 'sizewait', 'sizetodo', 'sizeall', 'pagesall', 'pagestodo',
        'pageswait'
    ]
    for args in getargs:
        for key in list_key_condition:
            if key in args:
                filter_condition(conditions, key, request.args.get(args))

    activities, maxpage, size, pages, name_param = activity.get_activity_list(
        conditions=conditions)

    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'])
    tab = request.args.get('tab')
    tab = 'todo' if not tab else tab
    return render_template('weko_workflow/activity_list.html',
                           page=page,
                           pages=pages,
                           name_param=name_param,
                           size=size,
                           tab=tab,
                           maxpage=maxpage,
                           render_widgets=render_widgets,
                           activities=activities)
コード例 #2
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def items_index(pid_value='0'):
    """Items index."""
    try:
        if pid_value == '0' or pid_value == 0:
            return redirect(url_for('.index'))

        record = WekoRecord.get_record_by_pid(pid_value)
        action = 'private' if record.get('publish_status', '1') == '1' \
            else 'publish'

        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'])

        if request.method == 'GET':
            return render_template(
                current_app.config['WEKO_ITEMS_UI_INDEX_TEMPLATE'],
                page=page,
                render_widgets=render_widgets,
                pid_value=pid_value,
                action=action)

        if request.headers['Content-Type'] != 'application/json':
            flash(_('Invalid request'), 'error')
            return render_template(
                current_app.config['WEKO_ITEMS_UI_INDEX_TEMPLATE'],
                page=page,
                render_widgets=render_widgets)

        data = request.get_json()
        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 request.method == 'PUT':
            """update index of item info."""
            item_str = sessionstore.get('item_index_{}'.format(pid_value))
            sessionstore.delete('item_index_{}'.format(pid_value))
            current_app.logger.debug(item_str)
            item = json.loads(item_str)
            item['index'] = data
            current_app.logger.debug(item)
        elif request.method == 'POST':
            """update item data info."""
            sessionstore.put('item_index_{}'.format(pid_value),
                             json.dumps(data),
                             ttl_secs=300)
        return jsonify(data)
    except BaseException:
        current_app.logger.error('Unexpected error: ', sys.exc_info()[0])
    return abort(400)
コード例 #3
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def index():
    """Render a basic view."""
    activity = WorkActivity()
    getargs = request.args

    conditions = {}
    list_key_condition = [
        'createdfrom', 'createdto', 'workflow', 'user', 'item', 'status',
        'tab', 'sizewait', 'sizetodo', 'sizeall', 'pagesall', 'pagestodo',
        'pageswait'
    ]
    for args in getargs:
        for key in list_key_condition:
            if key in args:
                filter_condition(conditions, key, request.args.get(args))

    ctx = {'community': None}
    community_id = ""
    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'])

    tab = request.args.get('tab')
    tab = WEKO_WORKFLOW_TODO_TAB if not tab else tab
    if 'community' in getargs:
        activities, maxpage, size, pages, name_param = activity \
            .get_activity_list(request.args.get('community'),
                               conditions=conditions)
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        ctx = {'community': comm}
        community_id = comm.id
    else:
        activities, maxpage, size, pages, name_param = activity \
            .get_activity_list(conditions=conditions)
    return render_template('weko_workflow/activity_list.html',
                           page=page,
                           pages=pages,
                           name_param=name_param,
                           size=size,
                           tab=tab,
                           maxpage=maxpage,
                           render_widgets=render_widgets,
                           activities=activities,
                           community_id=community_id,
                           **ctx)
コード例 #4
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def export():
    """Item export view."""
    export_settings = AdminSettings.get('item_export_settings') or \
        AdminSettings.Dict2Obj(
            current_app.config['WEKO_ADMIN_DEFAULT_ITEM_EXPORT_SETTINGS'])
    if not export_settings.allow_item_exporting:
        return abort(403)

    if request.method == 'POST':
        return export_items(request.form.to_dict())

    from weko_search_ui.api import SearchSetting
    search_type = request.args.get('search_type', '0')  # TODO: Refactor
    community_id = ""
    ctx = {'community': None}
    cur_index_id = search_type if search_type not in (
        '0',
        '1',
    ) else None
    if 'community' in request.args:
        from weko_workflow.api import GetCommunity
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        ctx = {'community': comm}
        community_id = comm.id

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

    sort_options, display_number = SearchSetting.get_results_setting()
    disply_setting = dict(size=display_number)

    return render_template(
        current_app.config['WEKO_ITEMS_UI_EXPORT_TEMPLATE'],
        page=page,
        render_widgets=render_widgets,
        index_id=cur_index_id,
        community_id=community_id,
        sort_option=sort_options,
        disply_setting=disply_setting,
        enable_contents_exporting=export_settings.enable_contents_exporting,
        max_export_num=_get_max_export_items(),
        **ctx)
コード例 #5
0
ファイル: ui.py プロジェクト: weko3-dev35/weko
def community_list():
    """Index page with uploader and list of existing depositions."""
    ctx = mycommunities_ctx()
    from weko_theme.utils import get_design_layout
    # Get the design for widget rendering
    render_page, render_widgets = get_design_layout(
        current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])
    p = request.args.get('p', type=str)
    so = request.args.get('so', type=str)
    page = request.args.get('page', type=int, default=1)

    so = so or current_app.config.get('COMMUNITIES_DEFAULT_SORTING_OPTION')

    communities = Community.filter_communities(p, so)
    featured_community = FeaturedCommunity.get_featured_or_none()
    form = SearchForm(p=p)
    per_page = 10
    page = max(page, 1)
    p = Pagination(page, per_page, communities.count())

    ctx.update({
        'r_from':
        max(p.per_page * (p.page - 1), 0),
        'r_to':
        min(p.per_page * p.page, p.total_count),
        'r_total':
        p.total_count,
        'pagination':
        p,
        'form':
        form,
        'title':
        _('Communities'),
        'communities':
        communities.slice(per_page * (page - 1), per_page * page).all(),
        'featured_community':
        featured_community,
    })

    return render_template('invenio_communities/communities_list.html',
                           page=render_page,
                           render_widgets=render_widgets,
                           **ctx)
コード例 #6
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def iframe_success():
    """Renders an item register view.

    :return: The rendered template.
    """
    # get session value
    history = WorkActivityHistory()
    histories = history.get_activity_history_list(session['itemlogin_id'])
    activity = session['itemlogin_activity']
    item = session['itemlogin_item']
    steps = session['itemlogin_steps']
    action_id = session['itemlogin_action_id']
    cur_step = session['itemlogin_cur_step']
    record = session['itemlogin_record']
    res_check = session['itemlogin_res_check']
    pid = session['itemlogin_pid']
    community_id = session.get('itemlogin_community_id')

    ctx = {'community': None}
    if community_id:
        comm = GetCommunity.get_community_by_id(community_id)
        ctx = {'community': comm}

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

    return render_template('weko_workflow/item_login_success.html',
                           page=page,
                           render_widgets=render_widgets,
                           activity=activity,
                           item=item,
                           steps=steps,
                           action_id=action_id,
                           cur_step=cur_step,
                           record=record,
                           histories=histories,
                           res_check=res_check,
                           pid=pid,
                           community_id=community_id,
                           **ctx)
コード例 #7
0
ファイル: views.py プロジェクト: weko3-dev35/weko
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)
コード例 #8
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def new_activity():
    """New activity."""
    workflow = WorkFlow()
    workflows = workflow.get_workflow_list()
    getargs = request.args
    ctx = {'community': None}
    community_id = ""
    if 'community' in getargs:
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        ctx = {'community': comm}
        community_id = comm.id

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

    return render_template('weko_workflow/workflow_list.html',
                           page=page,
                           render_widgets=render_widgets,
                           workflows=workflows,
                           community_id=community_id,
                           **ctx)
コード例 #9
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def ranking():
    """Ranking page view."""
    # get ranking settings
    settings = RankingSettings.get()
    # get statistical period
    end_date = date.today()  # - timedelta(days=1)
    start_date = end_date - timedelta(days=int(settings.statistical_period))

    from weko_theme.utils import get_design_layout
    # Get the design for widget rendering -- Always default
    page, render_widgets = get_design_layout(
        current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])

    rankings = {}
    # most_reviewed_items
    if settings.rankings['most_reviewed_items']:
        result = QueryRecordViewReportHelper.get(
            start_date=start_date.strftime('%Y-%m-%d'),
            end_date=end_date.strftime('%Y-%m-%d'),
            agg_size=settings.display_rank,
            agg_sort={'value': 'desc'})
        rankings['most_reviewed_items'] = \
            parse_ranking_results(result, settings.display_rank,
                                  list_name='all',
                                  title_key='record_name',
                                  count_key='total_all', pid_key='pid_value')

    # most_downloaded_items
    if settings.rankings['most_downloaded_items']:
        result = QueryItemRegReportHelper.get(
            start_date=start_date.strftime('%Y-%m-%d'),
            end_date=end_date.strftime('%Y-%m-%d'),
            target_report='3',
            unit='Item',
            agg_size=settings.display_rank,
            agg_sort={'_count': 'desc'})
        rankings['most_downloaded_items'] = \
            parse_ranking_results(result, settings.display_rank,
                                  list_name='data', title_key='col2',
                                  count_key='col3', pid_key='col1')

    # created_most_items_user
    if settings.rankings['created_most_items_user']:
        result = QueryItemRegReportHelper.get(
            start_date=start_date.strftime('%Y-%m-%d'),
            end_date=end_date.strftime('%Y-%m-%d'),
            target_report='0',
            unit='User',
            agg_size=settings.display_rank,
            agg_sort={'_count': 'desc'})
        rankings['created_most_items_user'] = \
            parse_ranking_results(result, settings.display_rank,
                                  list_name='data',
                                  title_key='user_id', count_key='count')

    # most_searched_keywords
    if settings.rankings['most_searched_keywords']:
        result = QuerySearchReportHelper.get(
            start_date=start_date.strftime('%Y-%m-%d'),
            end_date=end_date.strftime('%Y-%m-%d'),
            agg_size=settings.display_rank,
            agg_sort={'value': 'desc'})
        rankings['most_searched_keywords'] = \
            parse_ranking_results(result, settings.display_rank,
                                  list_name='all',
                                  title_key='search_key', count_key='count')

    # new_items
    if settings.rankings['new_items']:
        new_item_start_date = end_date - \
            timedelta(days=int(settings.new_item_period) - 1)
        if new_item_start_date < start_date:
            new_item_start_date = start_date
        result = get_new_items_by_date(
            new_item_start_date.strftime('%Y-%m-%d'),
            end_date.strftime('%Y-%m-%d'))
        rankings['new_items'] = \
            parse_ranking_results(result, settings.display_rank,
                                  list_name='all', title_key='record_name',
                                  pid_key='pid_value', date_key='create_date')

    return render_template(
        current_app.config['WEKO_ITEMS_UI_RANKING_TEMPLATE'],
        page=page,
        render_widgets=render_widgets,
        is_show=settings.is_show,
        start_date=start_date,
        end_date=end_date,
        rankings=rankings)
コード例 #10
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def iframe_items_index(pid_value='0'):
    """Iframe items index."""
    try:
        if pid_value == '0' or pid_value == 0:
            return redirect(url_for('.iframe_index'))

        record = WekoRecord.get_record_by_pid(pid_value)
        action = 'private' if record.get('publish_status', '1') == '1' \
            else 'publish'

        community_id = session.get('itemlogin_community_id')
        ctx = {'community': None}
        if community_id:
            comm = GetCommunity.get_community_by_id(community_id)
            ctx = {'community': comm}

        if request.method == 'GET':
            cur_activity = session['itemlogin_activity']
            # If enable auto set index feature
            # and activity is usage application item type
            steps = session['itemlogin_steps']
            contain_application_endpoint = False
            for step in steps:
                if step.get('ActionEndpoint') == 'item_login_application':
                    contain_application_endpoint = True
            enable_auto_set_index = current_app.config.get(
                'WEKO_WORKFLOW_ENABLE_AUTO_SET_INDEX_FOR_ITEM_TYPE')
            if enable_auto_set_index and contain_application_endpoint:
                index_id = get_index_id(cur_activity.activity_id)
                update_index_tree_for_record(pid_value, index_id)
                return redirect(url_for('weko_workflow.iframe_success'))
            # Get the design for widget rendering
            from weko_theme.utils import get_design_layout

            page, render_widgets = get_design_layout(
                community_id
                or current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])
            return render_template('weko_items_ui/iframe/item_index.html',
                                   page=page,
                                   render_widgets=render_widgets,
                                   pid_value=pid_value,
                                   action=action,
                                   activity=session['itemlogin_activity'],
                                   item=session['itemlogin_item'],
                                   steps=session['itemlogin_steps'],
                                   action_id=session['itemlogin_action_id'],
                                   cur_step=session['itemlogin_cur_step'],
                                   record=session['itemlogin_record'],
                                   histories=session['itemlogin_histories'],
                                   res_check=session['itemlogin_res_check'],
                                   pid=session['itemlogin_pid'],
                                   community_id=community_id,
                                   **ctx)

        if request.headers['Content-Type'] != 'application/json':
            flash(_('Invalid Request'), 'error')
            from weko_theme.utils import get_design_layout
            page, render_widgets = get_design_layout(
                current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])
            return render_template('weko_items_ui/iframe/item_index.html',
                                   page=page,
                                   render_widgets=render_widgets,
                                   community_id=community_id,
                                   **ctx)

        data = request.get_json()
        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 request.method == 'PUT':
            """update index of item info."""
            item_str = sessionstore.get('item_index_{}'.format(pid_value))
            sessionstore.delete('item_index_{}'.format(pid_value))
            item = json.loads(item_str)
            item['index'] = data
        elif request.method == 'POST':
            """update item data info."""
            sessionstore.put('item_index_{}'.format(pid_value),
                             json.dumps(data),
                             ttl_secs=300)
        return jsonify(data)
    except BaseException:
        current_app.logger.error('Unexpected error: ', sys.exc_info()[0])
    return abort(400)
コード例 #11
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def display_activity(activity_id=0):
    """Display activity."""
    activity = WorkActivity()
    activity_detail = activity.get_activity_detail(activity_id)
    item = None
    if activity_detail and activity_detail.item_id:
        try:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        except NoResultFound as ex:
            current_app.logger.exception(str(ex))
            item = None

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

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

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

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

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

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

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

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

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

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

        files = to_files_js(approval_record)

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

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

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

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

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

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

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

    return render_template(
        'weko_workflow/activity_detail.html',
        page=page,
        render_widgets=render_widgets,
        activity=activity_detail,
        item=item,
        steps=steps,
        action_id=action_id,
        cur_step=cur_step,
        temporary_comment=temporary_comment,
        temporary_journal=temporary_journal,
        temporary_idf_grant=temporary_identifier_select,
        temporary_idf_grant_suffix=temporary_identifier_inputs,
        idf_grant_data=identifier_setting,
        idf_grant_input=IDENTIFIER_GRANT_LIST,
        idf_grant_method=IDENTIFIER_GRANT_SUFFIX_METHOD,
        record=approval_record,
        records=record,
        step_item_login_url=step_item_login_url,
        need_file=need_file,
        need_billing_file=need_billing_file,
        jsonschema=json_schema,
        schemaform=schema_form,
        id=workflow_detail.itemtype_id,
        item_save_uri=item_save_uri,
        files=files,
        endpoints=endpoints,
        error_type='item_login_error',
        links=links,
        histories=histories,
        res_check=res_check,
        pid=pid,
        community_id=community_id,
        need_thumbnail=need_thumbnail,
        files_thumbnail=files_thumbnail,
        allow_multi_thumbnail=allow_multi_thumbnail,
        enable_feedback_maillist=current_app.
        config['WEKO_WORKFLOW_ENABLE_FEEDBACK_MAIL'],
        enable_contributor=current_app.
        config['WEKO_WORKFLOW_ENABLE_CONTRIBUTOR'],
        show_automatic_metadata_input=show_autofill_metadata,
        is_hidden_pubdate=is_hidden_pubdate_value,
        list_license=list_license,
        **ctx)
コード例 #12
0
ファイル: views.py プロジェクト: weko3-dev35/weko
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)
コード例 #13
0
ファイル: views.py プロジェクト: weko3-dev35/weko
def search():
    """Index Search page ui."""
    search_type = request.args.get('search_type',
                                   WEKO_SEARCH_TYPE_DICT['FULL_TEXT'])
    get_args = request.args
    community_id = ""
    ctx = {'community': None}
    cur_index_id = search_type if search_type not in \
        (WEKO_SEARCH_TYPE_DICT['FULL_TEXT'], WEKO_SEARCH_TYPE_DICT[
            'KEYWORD'], ) else None
    if 'community' in get_args:
        from weko_workflow.api import GetCommunity
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        ctx = {'community': comm}
        community_id = comm.id

    # Get the design for widget rendering
    page, render_widgets = get_design_layout(
        community_id or current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])

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

    # add at 1206 for search management
    sort_options, display_number = SearchSetting.get_results_setting()
    ts = time.time()
    disply_setting = dict(size=display_number, timestamp=ts)

    detail_condition = get_search_detail_keyword('')

    export_settings = AdminSettings.get('item_export_settings') or \
        AdminSettings.Dict2Obj(
            current_app.config['WEKO_ADMIN_DEFAULT_ITEM_EXPORT_SETTINGS'])

    height = style.height if style else None
    if 'item_link' in get_args:
        from weko_workflow.api import WorkActivity

        activity_id = request.args.get('item_link')
        workflow_activity = WorkActivity()
        activity_detail, item, steps, action_id, cur_step, temporary_comment,\
            approval_record, step_item_login_url, histories, res_check, pid, \
            community_id, ctx = workflow_activity.get_activity_index_search(
                activity_id=activity_id)

        # Get ex-Item Links
        recid = item['pid'].get('value') if item.get('pid') else None
        if recid:
            pid_without_ver = recid.split('.')[0]
            item_link = ItemLink.get_item_link_info(pid_without_ver)
            ctx['item_link'] = item_link

        return render_template(
            'weko_workflow/activity_detail.html',
            page=page,
            render_widgets=render_widgets,
            activity=activity_detail,
            item=item,
            steps=steps,
            action_id=action_id,
            cur_step=cur_step,
            temporary_comment=temporary_comment,
            record=approval_record,
            step_item_login_url=step_item_login_url,
            histories=histories,
            res_check=res_check,
            pid=pid,
            index_id=cur_index_id,
            community_id=community_id,
            width=width,
            height=height,
            allow_item_exporting=export_settings.allow_item_exporting,
            is_permission=check_permission(),
            is_login=bool(current_user.get_id()),
            **ctx)
    else:
        journal_info = None
        index_display_format = '1'
        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 ''
        if search_type in WEKO_SEARCH_TYPE_DICT.values():
            searched.send(current_app._get_current_object(),
                          search_args=get_args,
                          info=send_info)
            if search_type == WEKO_SEARCH_TYPE_DICT['INDEX']:
                cur_index_id = request.args.get('q', '0')
                journal_info = get_journal_info(cur_index_id)
                index_info = Indexes.get_index(cur_index_id)
                if index_info:
                    index_display_format = index_info.display_format
                    if index_display_format == '2':
                        disply_setting = dict(size=100, timestamp=ts)

        if hasattr(current_i18n, 'language'):
            index_link_list = get_index_link_list(current_i18n.language)
        else:
            index_link_list = get_index_link_list()
        return render_template(
            current_app.config['SEARCH_UI_SEARCH_TEMPLATE'],
            page=page,
            render_widgets=render_widgets,
            index_id=cur_index_id,
            community_id=community_id,
            sort_option=sort_options,
            disply_setting=disply_setting,
            detail_condition=detail_condition,
            width=width,
            height=height,
            index_link_enabled=style.index_link_enabled,
            index_link_list=index_link_list,
            journal_info=journal_info,
            index_display_format=index_display_format,
            allow_item_exporting=export_settings.allow_item_exporting,
            is_permission=check_permission(),
            is_login=bool(current_user.get_id()),
            **ctx)