gmyth-stream/server/lib/utils.py
author ali@juiblex.co.uk
Wed Dec 16 10:06:21 2009 +0000 (2009-12-16)
branchtrunk
changeset 951 7b0d87ef5e63
parent 815 7f290a3a34b1
permissions -rw-r--r--
Add rules and upcoming lists to gmyth_ls
morphbr@718
     1
#!/usr/bin/env
morphbr@718
     2
morphbr@718
     3
__author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
morphbr@718
     4
__author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
morphbr@718
     5
__license__ = "GPL"
morphbr@718
     6
__version__ = "0.3"
morphbr@718
     7
morphbr@718
     8
import os
morphbr@718
     9
import stat
morphbr@718
    10
import sys
morphbr@718
    11
import logging
morphbr@718
    12
import urllib
morphbr@718
    13
import gobject
morphbr@718
    14
import imp
morphbr@718
    15
renatofilho@815
    16
import gmsconfig
renatofilho@815
    17
morphbr@718
    18
log = logging.getLogger("gms.utils")
renatofilho@815
    19
config = gmsconfig.GmsConfig()
morphbr@718
    20
morphbr@723
    21
__all__ = ("which", "load_plugins", "PluginSet", "getHTML",
morphbr@723
    22
           "progress_bar", "create_tid", "list_media_files")
morphbr@718
    23
morphbr@718
    24
def which(app):
morphbr@718
    25
    """Function to implement which(1) unix command"""
morphbr@718
    26
    pl = os.environ["PATH"].split(os.pathsep)
morphbr@718
    27
    for p in pl:
morphbr@718
    28
        path = os.path.join(p, app)
morphbr@718
    29
        if os.path.isfile(path):
morphbr@718
    30
            st = os.stat(path)
morphbr@718
    31
            if st[stat.ST_MODE] & 0111:
morphbr@718
    32
                return path
morphbr@718
    33
    return ""
morphbr@718
    34
# which()
morphbr@718
    35
morphbr@718
    36
morphbr@718
    37
def _load_module(pathlist, name):
morphbr@718
    38
    fp, path, desc = imp.find_module(name, pathlist)
morphbr@718
    39
    try:
morphbr@718
    40
        module = imp.load_module(name, fp, path, desc)
morphbr@718
    41
        return module
morphbr@718
    42
    finally:
morphbr@718
    43
        if fp:
morphbr@718
    44
            fp.close()
morphbr@718
    45
# _load_module()
morphbr@718
    46
morphbr@718
    47
morphbr@718
    48
class PluginSet(object):
morphbr@718
    49
    def __init__(self, basetype, *items):
morphbr@718
    50
        self.basetype = basetype
morphbr@718
    51
        self.map = {}
morphbr@718
    52
        self.list = []
morphbr@718
    53
morphbr@718
    54
        for i in items:
morphbr@718
    55
            self._add(i)
morphbr@718
    56
        self._sort()
morphbr@718
    57
    # __init__()
morphbr@718
    58
morphbr@718
    59
morphbr@718
    60
    def _add(self, item):
morphbr@718
    61
        self.map[item.name] = item
morphbr@718
    62
        self.list.append(item)
morphbr@718
    63
    # _add()
morphbr@718
    64
morphbr@718
    65
morphbr@718
    66
    def add(self, item):
morphbr@718
    67
        self._add()
morphbr@718
    68
        self._sort()
morphbr@718
    69
    # add()
morphbr@718
    70
morphbr@718
    71
morphbr@718
    72
    def __getitem__(self, spec):
morphbr@718
    73
        if isinstance(spec, basestring):
morphbr@718
    74
            return self.map[spec]
morphbr@718
    75
        else:
morphbr@718
    76
            return self.list[spec]
morphbr@718
    77
    # __getitem__()
morphbr@718
    78
morphbr@718
    79
morphbr@718
    80
    def get(self, name, default=None):
morphbr@718
    81
        return self.map.get(name, default)
morphbr@718
    82
    # get()
morphbr@718
    83
morphbr@718
    84
morphbr@718
    85
    def __iter__(self):
morphbr@718
    86
        return self.list.__iter__()
morphbr@718
    87
    # __iter__()
morphbr@718
    88
morphbr@718
    89
morphbr@718
    90
    def __len__(self):
morphbr@718
    91
        return len(self.list)
morphbr@718
    92
    # __len__()
morphbr@718
    93
morphbr@718
    94
morphbr@718
    95
    def _sort(self):
morphbr@718
    96
        self.list.sort(lambda a, b: cmp(a.priority, b.priority))
morphbr@718
    97
    # _sort()
morphbr@718
    98
morphbr@718
    99
morphbr@718
   100
    def update(self, pluginset):
morphbr@718
   101
        self.map.update(pluginset.map)
morphbr@718
   102
        self.list.extend(pluginset.list)
morphbr@718
   103
        self._sort()
morphbr@718
   104
    # update()
morphbr@718
   105
morphbr@718
   106
morphbr@718
   107
    def load_from_directory(self, directory):
morphbr@718
   108
        for i in load_plugins(directory, self.basetype):
morphbr@718
   109
            self._add(i)
morphbr@718
   110
        self._sort()
morphbr@718
   111
    # load_from_directory()
morphbr@718
   112
morphbr@718
   113
morphbr@718
   114
    def __str__(self):
morphbr@718
   115
        lst = []
morphbr@718
   116
        for o in self.list:
morphbr@718
   117
            lst.append('"%s" (%s)' % (o.name, o.__name__))
morphbr@718
   118
morphbr@718
   119
        return "%s(basetype=%s, items=[%s])" % \
morphbr@718
   120
               (self.__class__.__name__,
morphbr@718
   121
                self.basetype.__name__,
morphbr@718
   122
                ", ".join(lst))
morphbr@718
   123
    # __str__()
morphbr@718
   124
# PluginSet
morphbr@718
   125
morphbr@718
   126
morphbr@718
   127
def load_plugins(directory, basetype):
morphbr@718
   128
    """Function to load plugins from a given directory"""
morphbr@718
   129
    tn = basetype.__name__
morphbr@718
   130
    log.debug("Loading plugins from %s, type=%s" % (directory, tn))
morphbr@718
   131
morphbr@718
   132
morphbr@718
   133
    plugins = []
morphbr@718
   134
    for d in os.listdir(directory):
morphbr@718
   135
        if not d.endswith(".py"):
morphbr@718
   136
            continue
morphbr@718
   137
morphbr@718
   138
        name = d[0: -3]
morphbr@718
   139
        if name == "__init__":
morphbr@718
   140
            continue
morphbr@718
   141
morphbr@718
   142
        directory.replace(os.path.sep, ".")
morphbr@718
   143
        mod = _load_module([directory], name)
morphbr@718
   144
        for sym in dir(mod):
morphbr@718
   145
            cls = getattr(mod, sym)
morphbr@718
   146
            if isinstance(cls, type) and issubclass(cls, basetype) and \
morphbr@718
   147
                cls != basetype:
morphbr@718
   148
                plugins.append(cls)
morphbr@718
   149
                log.info("Loaded %s (%s) from %s" % \
morphbr@718
   150
                         (cls.__name__, tn, os.path.join(directory, d)))
morphbr@718
   151
morphbr@718
   152
    return plugins
morphbr@718
   153
# load_plugins()
morphbr@718
   154
morphbr@718
   155
def getHTML(html_file, params={}):
morphbr@718
   156
    """This function parses an html file with the given
morphbr@718
   157
    parameters and returns a formated web-page"""
morphbr@718
   158
    try:
morphbr@718
   159
        filename = os.path.join(sys.path[0], "html", html_file + ".html")
morphbr@718
   160
        html = open(filename).read() % params
morphbr@718
   161
        return html
morphbr@718
   162
    except Exception, e:
morphbr@718
   163
        return "HTML format error. Wrong keys: %s" % e
morphbr@718
   164
morphbr@718
   165
# getHTML
morphbr@718
   166
morphbr@718
   167
def _create_html_item(opt):
morphbr@718
   168
    """Create an <li> item using HTML."""
morphbr@718
   169
    return "<li>%s</li>\n" % opt
morphbr@718
   170
# _create_html_item
morphbr@718
   171
morphbr@723
   172
def progress_bar(value, max, barsize):
morphbr@718
   173
    """Creates and displays a progressbar. By OSantana"""
morphbr@718
   174
    chars = int(value * barsize / float(max))
morphbr@718
   175
    percent = int((value / float(max)) * 100)
morphbr@718
   176
    sys.stdout.write("#" * chars)
morphbr@718
   177
    sys.stdout.write(" " * (barsize - chars + 2))
morphbr@718
   178
    if value >= max:
morphbr@718
   179
        sys.stdout.write("done.\n\n")
morphbr@718
   180
    else:
morphbr@718
   181
        sys.stdout.write("[%3i%%]\r" % (percent))
morphbr@718
   182
        sys.stdout.flush()
morphbr@718
   183
    return percent
morphbr@718
   184
# progress_bar() by osantana
morphbr@718
   185
morphbr@718
   186
def create_tid(last_tid):
morphbr@718
   187
    """Function to generate TIDs (ids for transcoders).
morphbr@718
   188
    At first it just do +1 on last_tid but can be implemented
morphbr@718
   189
    to generate more sparse TIDs"""
morphbr@718
   190
    tid = last_tid + 1
morphbr@718
   191
    return tid
morphbr@718
   192
# create_id()
morphbr@723
   193