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