Am 2014-06-11 um 13:34 schrieb Samuele Kaplun <[email protected]>:

> In data mercoledì 11 giugno 2014 13:06:41, Henning Hraban Ramm ha scritto:
>> Am 2014-06-10 um 13:37 schrieb Samuele Kaplun <[email protected]>:
>>> the 8564_ fields order is unfortunately not respected by bibupload when
>>> elaborating FFT tags. See:
>>> <https://github.com/inveniosoftware/invenio/issues/1606>
>>> 
>>> Additionally, it can be quite cumbersome to use FFT tags to upload
>>> documents, which then creates 8564_ tags and then subsequently add to
>>> each field a new subfield with the position information.
>>> 
>>> One workaround could be to embed the position in the name of the file,
>>> such as prefixing them with e.g. 01- 02- ... 10-. The default behavior of
>>> Invenio it to display files (in the /files tab) in alphabetical order.
>> 
>> Our problem are mostly records where staff uploaded additional files later,
>> so FFT is no solution.
>> 
>> And the display order is always the upload order, as far as I experienced,
>> there seems no sorting involved. We already tried numbered files.
>> 
>> So, a postprocessing script („once a day“) would need to delete the whole
>> list of attachments and re-add them in (alphabetical) order.
> 
> In which context are you looking for the sorted list? Is it in the low-left 
> corner of a detailed record page? Or in the "Files" tab? Note that the low-
> left corner is implemented through the bfe_fulltext_mini.py format element, 
> that you are free to amend.

Dear Samuele,

in our layout, it’s in the right column ;-)
See e.g. https://invenio.cerebrale.net/record/2639

The list is created by BFE_DOWNLOAD_UCA (please find attached that BFE and our 
little library).
Of course I can implement sorting there, but isn’t there already something 
built in or can we use the database’s facilities?

Greetlings, Hraban

# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2006-2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## adaption for UCA eBilim
## Copyright (c) 2013, 2014 University of Central Asia
## made by fiëé visuëlle, Henning Hraban Ramm
##
"""BibFormat element - Prints links to data files and external URLs
UCA version
"""
__revision__ = "$Id$"

import os
from cgi import escape
from invenio.messages import gettext_set_language

from uca_lib import get_icon, make_link


def format_element(bfo, css_class='', separator='; '):
    """
    find attachments (fulltext, files, links) of the active record and display them as link with icon;
    depends on `get_icon` and `make_link` from `uca_lib` (also checks permission by license or user).
    
    @param css_class: CSS class of link
    @param separator: string to display between entries
    """
    _ = gettext_set_language(bfo.lang)
    out = []
    records = bfo.fields("856%_")
    for record in records:
        subformat = record.get('x', '')
        if subformat:
            # we don’t want subformats (e.g. icons, generated PDF/A)
            continue
        
        url = record.get('u', '')
        if not url:
            # e.g. we don’t need 8560.f
            continue

        p, ext = os.path.splitext(url)
        ext = ext[1:].upper()

        title = record.get('y', record.get('z', '')).strip()

        outentry = make_link(bfo,
            cls=css_class,
            href=escape(url),
            title=escape(title),
            text=get_icon(bfo, url, ext) + ' ' + ext,
        )
        if title:
            outentry += ' <span class="title">(%s)</span>' % escape(title)  # TODO: configure if show title or not?
        out.append(outentry)

    out = separator.join(out)
    # When exported to text (eg. in WebAlert emails) we do not want to
    # display the link to the fulltext:
    if out:
        out = '<!--START_NOT_FOR_TEXT-->' + out + '<!--END_NOT_FOR_TEXT-->'

    return out


def escape_values(bfo):
    """
    Called by BibFormat in order to check if output of this element
    should be escaped.
    """
    return 0
# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2007-2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## adaptions for UCA eBilim
## Copyright (c) 2014 University of Central Asia
## made by fiëé visuëlle, Henning Hraban Ramm
##
"""
UCA library: helpers for BibFormat elements
"""
import os
from invenio.config import CFG_SITE_URL, CFG_SITE_LANG
from invenio.access_control_engine import acc_authorize_action
from invenio.messages import gettext_set_language, wash_language

_ = lambda x: x

__revision__ = "$Id$"

# code : ( name, url )
LICENSE_MAP = {
    'C' : (_("Copyright"), '', ),
    'CP' : (_("Copyright, but with special permission"), '', ),
    'PD' : (_("Public Domain"), '', ),
    'CC0' : (_("Creative Commons Public Domain"), 'http://creativecommons.org/about/cc0', ),
    'CC-BY' : (_("Creative Commons Attribution"), 'http://creativecommons.org/licenses/by/3.0', ),
    'CC-BY-SA' : (_("Creative Commons Attribution-Sharealike"), 'http://creativecommons.org/licenses/by-sa/3.0', ),
    'CC-BY-ND' : (_("Creative Commons Attribution-NoDerivs"), 'http://creativecommons.org/licenses/by-nd/3.0', ),
    'CC-BY-NC' : (_("Creative Commons Attribution-NonCommercial"), 'http://creativecommons.org/licenses/by-nc/3.0', ),
    'CC-BY-NC-SA' : (_("Creative Commons Attribution-NonCommercial-ShareAlike"), 'http://creativecommons.org/licenses/by-nc-sa/3.0', ),
    'CC-BY-NC-ND' : (_("Creative Commons Attribution-NonCommercial-NoDerivs"), 'http://creativecommons.org/licenses/by-nc-nd/3.0', ),
    'PGL' : (_("Project Gutenberg License"), 'http://www.gutenberg.org/wiki/Gutenberg:The_Project_Gutenberg_License', ),
    'GPL' : (_("GNU General Public License"), 'https://www.gnu.org/licenses/gpl', ),
    'FDL' : (_("GNU Free Documentation License"), 'https://www.gnu.org/licenses/fdl-1.3', ),
    'OPL' : (_("Open Publication License"), 'http://opencontent.org/openpub/', ),
    'OCL' : (_("Open Content License"), 'http://opencontent.org/opl.shtml', ),
    'FAL' : (_("Free Art License"), _("http://artlibre.org/licence/lal/en";), ),
    #'' : (_(""), '', ),
}

def download_allowed(bfo, license):
    """
    May the public view/download a file with this license?
    
    @param bfo: optional object reference
    @param license: optional license shortcut string
    
    One of both parameters must be provided, the other may be None.
    """
    if not license:
        license = bfo.field('542__l').strip()
    return license in LICENSE_MAP and not license in ('C', 'CP',)

# mapping from file extensions to crystal icon filenames
EXT_ICON_MAP = {
                '': 'unknown',
                'avi': 'video',
                'cdr': 'mime_cdr',
                'doc': 'document',
                'docx': 'document2',
                'eps': 'postscript',
                'epub': 'misc',
                'exe': 'exec_wine',
                'flv': 'swf',
                'gif': 'image',
                'gz': 'tgz',
                'htm': 'html',
                'html': 'html',
                'jpg': 'image',
                'jpeg': 'image',
                'log': 'log',
                'mid': 'midi',
                'midi': 'midi',
                'mov': 'video', # 'quicktime',
                'mp3': 'sound',
                'mp4': 'video',
                'mpg': 'video',
                'ods': 'spreadsheet',
                'odt': 'document',
                'ogg': 'sound',
                'ogv': 'video',
                'pdf': 'pdf',
                'png': 'image',
                'pps': 'pps',
                'ps': 'ps',
                'rar': 'zip',
                'swf': 'swf',
                'tar': 'tar',
                'tex': 'tex',
                'tgz': 'tgz',
                'ttf': 'font_truetype',
                'txt': 'txt',
                'xls': 'spreadsheet',
                'zip': 'zip',
                '7z': 'zip',
                'z': 'tgz',
}

def get_icon(bfo, url, fileformat='', show_icons='yes', iconpath='/img/crystal/mimetypes/24/'):
    """
    Returns an img tag with the icon for the url’s file type (determinded by extension).
    Needs the crystal mimetype icons to be installed under `iconpath`.
    
    @param url: the url (file path would also work)
    @param fileformat: file format (avoid parsing the url)
    @param show_icons: if not 'yes', the function returns '' (default: 'yes')
    """
    _ = gettext_set_language(bfo.lang)
    file_icon = ''
    if show_icons.lower() == 'yes':
        ext = ''
        fileformat = fileformat.lower()
        if fileformat != '' and fileformat in EXT_ICON_MAP:
            file_icon = EXT_ICON_MAP[fileformat]
        else:
            if '?' in url:
                url = url[:url.find('?')]
            p, ext = os.path.splitext(url)
            ext = ext[1:].lower()
            if ext in EXT_ICON_MAP:
                file_icon = EXT_ICON_MAP[ext]
            else:
                file_icon = EXT_ICON_MAP[''] # unknown format
        file_icon = """<img class="file_icon" 
        src="%(site_url)s%(icon_path)s%(file_icon)s.png" 
        alt="%(download_text)s"/>""" % {
            'site_url': CFG_SITE_URL,
            'icon_path': iconpath,
            'file_icon': file_icon,
            'download_text': _("Download document"),
        }
    return file_icon


def make_link(bfo, **kwargs):
    """
    Required keyword arguments:
    @param href: url of the link
    @param text: text of the link (may contain HTML)
    
    Optional keyword arguments:
    @param style: CSS styles
    @param cls:   CSS class(es)
    @param title: mouseover text
    """
    _ = gettext_set_language(bfo.lang)
    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info, 'viewfulltext')
    
    if 'text' in kwargs:
        text = kwargs['text']
        del kwargs['text']
    else:
        text = ''
    if 'cls' in kwargs:
        if kwargs['cls']:
            kwargs['class'] = kwargs['cls']
        del kwargs['cls']
        
    if auth_code == 0 or download_allowed(bfo, False):
        element = 'a'
    else:
        element = 'span'
        if not 'title' in kwargs:
            kwargs['title'] = ''
        else:
            kwargs['title'] += '. '
        kwargs['title'] += _('Access is prohibited due to license/copyright restrictions.')
        if auth_code != 0:
            kwargs['title'] += ' ' + _('Download is only allowed for registered users or within UCA network.')
        if not 'class' in kwargs: kwargs['class'] = ''
        kwargs['class'] += ' restricted'
    return '<%(elm)s %(kws)s>%(txt)s</%(elm)s>' % \
        {
         'elm' : element,
         'kws' : ' '.join(('%s="%s"' % (k, kwargs[k]) for k in kwargs)), 
         'txt': text,
         }

def format_size(size):
    """
    Get human-readable string (with units B, kB, MB, GB) for the given size in Bytes
    """
    if size < 1024:
        return "%d B" % size
    elif size < 1024 * 1024:
        return "%.1f kB" % (size / 1024)
    elif size < 1024 * 1024 * 1024:
        return "%.1f MB" % (size / (1024 * 1024))
    else:
        return "%.1f GB" % (size / (1024 * 1024 * 1024))

Reply via email to