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