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