Beispiel #1
0
def format_metadata(f,details,text):
    '''
    Formatea los metadatos de los archivos
    '''
    def searchable(value,details):
        '''
        Añade un enlace a la busqueda si es necesario
        '''
        if details:
            return '<a href="%s">%s</a>' % (url_for("files.search",q=value), value)
        else:
            return value

    view_md = f['view']['md'] = {}
    file_type = f['view']['file_type'] if 'file_type' in f['view'] else None
    if 'md' in f['file']:
        #si viene con el formato tipo:metadato se le quita el tipo
        file_md = {(meta.split(":")[-1] if ":" in meta else meta): value for meta, value in f['file']['md'].iteritems()}

        # Duración para vídeo e imágenes
        put_duration = False
        duration = [0, 0, 0] # h, m, s

        try:
            if "seconds" in file_md:
                put_duration = True
                duration[-1] = float(file_md["seconds"])
            if "minutes" in file_md:
                put_duration = True
                duration[-2] = float(file_md["minutes"])
            if "hours" in file_md:
                put_duration = True
                duration[-3] = float(file_md["hours"])
        except BaseException as e:
            logging.warn(e, extra=file_md)
        if not put_duration and "length" in file_md:
            # Si recibo length y no la he recibido duration de otra forma
            try:
                duration[-1] = to_seconds(file_md["length"])
                put_duration = True
            except BaseException as e:
                logging.error("Problema al parsear duración: 'length'", extra=file_md)
        if not put_duration and "duration" in file_md:
            # Si recibo duration y no la he recibido de otra forma
            try:
                duration[-1] = to_seconds(file_md["duration"])
                put_duration = True
            except BaseException as e:
                logging.error("Problema al parsear duración: 'duration'", extra=file_md)
        if put_duration:
            carry = 0
            for i in xrange(len(duration)-1,-1,-1):
                unit = long(duration[i]) + carry
                duration[i] = unit%60
                carry = unit/60
            view_md["length"] = "%d:%02d:%02d" % tuple(duration) if duration[-3] > 0 else "%02d:%02d" % tuple(duration[-2:])

        # Tamaño para vídeos e imágenes
        if "width" in file_md and 'height' in file_md:
            try:
                width = (
                    int(file_md["width"].replace("pixels","").replace("px",""))
                    if isinstance(file_md["width"], basestring)
                    else int(file_md["width"]))
                height = (
                    int(file_md["height"].replace("pixels","").replace("px",""))
                    if isinstance(file_md["width"], basestring)
                    else int(file_md["height"]))
                view_md["size"] = "%dx%dpx" % (width, height)
            except BaseException as e:
                logging.warn(e)

        # Metadatos que no cambian
        try:
            view_md.update((meta, file_md[meta]) for meta in (
                ("folders","description","fileversion","os","files","pages","format")
                if details else ("files","pages","format")) if meta in file_md)
        except BaseException as e:
            logging.warn(e)

        # Metadatos multimedia
        try:
            if file_type in ("audio", "video", "image"):
                view_md.update((meta, file_md[meta]) for meta in
                    ("genre", "track", "artist", "author", "colors")
                    if meta in file_md)
        except BaseException as e:
            logging.warn(e)

        # No muestra titulo si es igual al nombre del fichero
        title = None
        if "name" in file_md:
            title = u(file_md["name"])
        elif "title" in file_md:
            title = u(file_md["title"])

        if title:
            show_title = True
            text_longer = title
            text_shorter = f["view"]["fn"]
            if len(text_shorter)>len(text_longer): text_longer, text_shorter = text_shorter, text_longer

            if text_longer.startswith(text_shorter):
                text_longer = text_longer[len(text_shorter):]
                if len(text_longer)==0 or (len(text_longer)>0 and text_longer.startswith(".") and text_longer[1:] in EXTENSIONS):
                    show_title = False

            if show_title:
                view_md["title"] = title

        # Los que cambian o son especificos de un tipo
        try:
            if file_type == 'audio': #album, year, bitrate, seconds, track, genre, length
                if 'album' in file_md:
                    year = 0
                    if "year" in file_md:
                        md_year = u(file_md["year"]).strip().split()
                        for i in md_year:
                            if i.isdigit() and len(i) == 4:
                                year = int(i)
                                break
                    album = file_md["album"]
                    view_md["album"] = ("%s (%d)" % (album, year)) if 1900 <  year < 2100 else album
                if 'bitrate' in file_md:
                    bitrate = "%s kbps" % u(file_md["bitrate"]).replace("~","")
                    view_md["quality"] = ( # bitrate o bitrate - soundtype
                        ("%s - %s" % (bitrate, file_md["soundtype"]))
                        if details and "soundtype" in file_md else bitrate)
            elif file_type == 'archive': #title, name, unpackedsize, folders, files
                if "unpackedsize" in file_md:
                    view_md["unpackedsize"] = file_md["unpackedsize"]
            elif file_type == 'document': #title, author, pages, format, version
                if details:
                    if "format" in file_md:
                        view_md["format"] = "%s%s" % (file_md["format"],
                            " %s" % file_md["formatversion"]
                            if "formatversion" in file_md else "")
                    version = []
                    if "version" in file_md: version.append(u(file_md["version"]))
                    if "revision" in file_md: version.append(u(file_md["revision"]))
                    if version: view_md["version"] = " ".join(version)
            elif file_type == 'image': #title, artist, description, width, height, colors
                pass
            elif file_type == 'software': #title, version, fileversion, os
                if "title" in view_md and "version" in file_md:
                     view_md["title"] += " %s" % file_md["version"]
            elif file_type == 'video':
                if details:
                    quality = []
                    try:
                        if 'framerate' in file_md: quality.append("%d fps" % int(float(file_md["framerate"])))
                    except BaseException as e:
                        logging.warn(e)
                    if 'codec' in file_md: quality.append(u(file_md["codec"]))
                    if quality: view_md["quality"] = " - ".join(quality)
                view_md.update((i, file_md[i]) for i in ("series", "episode", "season") if i in file_md)

        except BaseException as e:
            logging.warn("%s\n\t%s\n\t%s" % (e, f, view_md))

        #if len(view_md)>0:
        f['view']['mdh']={}
        for metadata,value in view_md.items():
            if isinstance(value, basestring):
                final_value = Markup(value).striptags()
                final_value = searchable(highlight(text,final_value) if text else final_value, details)
            else:
                final_value = value
            f['view']['mdh'][metadata] = final_value
Beispiel #2
0
def format_metadata(f,details):
    '''
    Formatea los metadatos de los archivos
    '''
    def searchable(value,details):
        '''
        Añadie un enlace a la busqueda si es necesario
        '''
        if details:
            return "<a href='%s'>%s</a>" % (url_for(".search",q=value), value)
        else:
            return value

    view_md = f['view']['md'] = {}
    file_type = f['view']['file_type'] if 'file_type' in f['view'] else None
    if 'md' in f['file']:
        #si viene con el formato tipo:metadato se le quita el tipo
        file_md = {(meta.split(":")[-1] if ":" in meta else meta): value
            for meta, value in f['file']['md'].iteritems()}

        # Duración para vídeo e imágenes
        put_duration = False
        duration = [0, 0, 0] # h, m, s
        try:
            if "seconds" in file_md:
                put_duration = True
                duration[-1] = float(file_md["seconds"])
            if "minutes" in file_md:
                put_duration = True
                duration[-2] = float(file_md["minutes"])
            if "hours" in file_md:
                put_duration = True
                duration[-3] = float(file_md["hours"])
        except BaseException as e:
            logging.exception(e)
        if "duration" in file_md and not put_duration:
            # Si recibo duration y no la he recibido de otra forma
            try:
                duration[-1] = to_seconds(file_md["duration"])
                put_duration = True
            except BaseException as e:
                logging.exception(e)
        if put_duration:
            carry = 0
            for i in xrange(len(duration)-1,-1,-1):
                unit = duration[i] + carry
                duration[i] = unit%60
                carry = unit/60
            view_md["length"] = ":".join("%02d" % i for i in (duration if duration[-3] > 0 else duration[-2:]))

        # Tamaño para vídeos e imágenes
        if "width" in file_md and 'height' in file_md:
            try:
                width = (
                    int(file_md["width"].replace("pixels","").replace("px",""))
                    if isinstance(file_md["width"], basestring)
                    else int(file_md["width"]))
                height = (
                    int(file_md["height"].replace("pixels","").replace("px",""))
                    if isinstance(file_md["width"], basestring)
                    else int(file_md["height"]))
                view_md["size"] = "%dx%dpx" % (width, height)
            except BaseException as e:
                logging.exception(e)

        # Metadatos que no cambian
        try:
            view_md.update((meta, file_md[meta]) for meta in (
                ("folders","description","fileversion","os","files","pages","format")
                if details else ("files","pages","format")) if meta in file_md)
        except BaseException as e:
            logging.exception(e)

        # Metadatos multimedia
        try:
            if file_type in ("audio", "video", "image"):
                view_md.update((meta, file_md[meta]) for meta in
                    ("genre", "length", "track", "artist", "title", "author", "colors")
                    if meta in file_md)
        except BaseException as e:
            logging.exception(e)

        # Los que cambian o son especificos de un tipo
        try:
            if file_type == 'audio': #album, year, bitrate, seconds, track, genre, length
                if 'album' in file_md:
                    year = int(file_md["year"]) if "year" in file_md and str(file_md["year"]).isdigit() else 0
                    album = searchable(file_md["album"], details)
                    view_md["album"] = ("%s (%d)" % (album, year)) if 1900 <  year < 2100 else album
                if 'bitrate' in file_md:
                    bitrate = "%s kbps" % str(file_md["bitrate"]).replace("~","")
                    view_md["quality"] = ( # bitrate o bitrate - soundtype
                        ("%s - %s" % (bitrate, file_md["soundtype"]))
                        if details and "soundtype" in file_md else bitrate)
            elif file_type == 'archive': #title, name, unpackedsize, folders, files
                if "title" in file_md or "name" in file_md:
                    view_md["title"] = searchable(file_md["title" if "title" in file_md else "name"], details)
                if "unpackedsize" in file_md:
                    view_md["unpackedsize"] = file_md["unpackedsize"]
            elif file_type == 'document': #title, author, pages, format, version
                if details:
                    if "format" in file_md:
                        view_md["format"] = "%s%s" % (file_md["format"],
                            " %s" % file_md["formatversion"]
                            if "formatversion" in file_md else "")
                    version = []
                    if "version" in file_md: version.append(float(file_md["version"]))
                    if "revision" in file_md: version.append(float(file_md["revision"]))
                    if version: view_md["revision"] = " ".join(version)
            elif file_type == 'image': #title, artist, description, width, height, colors
                pass
            elif file_type == 'software': #title, version, fileversion, os
                if "title" in file_md:
                     view_md["title"] = "%s%s" % (
                        searchable(file_md["title"], details),
                        " %s" % file_md["version"] if "version" in file_md else "")
            elif file_type == 'video':
                if details:
                    quality = []
                    if 'framerate' in file_md: quality.append("%d fps" % float(file_md["framerate"]))
                    if 'codec' in file_md: quality.append(str(file_md["codec"]))
                    if quality: view_md["quality"] = " - ".join(quality)
        except BaseException as e:
            logging.exception(e)