gmyth-stream/server/0.3/lib/request_handler.py
author morphbr
Tue Jun 26 14:32:33 2007 +0100 (2007-06-26)
branchtrunk
changeset 759 6620b7037407
parent 745 c764b0a92282
child 763 4ac83e3152c0
permissions -rw-r--r--
[svn r765] * Removed Multicast feature
morphbr@718
     1
#!/usr/bin/env python
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@723
     6
__version__ = "0.3"
morphbr@718
     7
morphbr@718
     8
import os
morphbr@723
     9
import cgi
morphbr@723
    10
import socket
morphbr@723
    11
import logging
morphbr@723
    12
import urlparse
morphbr@718
    13
import threading
morphbr@718
    14
import SocketServer
morphbr@718
    15
import BaseHTTPServer
morphbr@723
    16
morphbr@718
    17
import lib.utils as utils
morphbr@723
    18
import lib.file_handler as files
morphbr@723
    19
import lib.transcoder as transcoder
morphbr@718
    20
morphbr@718
    21
from log import Log
morphbr@718
    22
morphbr@718
    23
__all__ = ("RequestHandler")
morphbr@718
    24
morphbr@718
    25
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
morphbr@718
    26
    """Class that implements an HTTP request handler for our server."""
morphbr@718
    27
    log = logging.getLogger("gms.request")
morphbr@718
    28
    def_transcoder = None
morphbr@718
    29
    transcoders = utils.PluginSet(transcoder.Transcoder)
morphbr@718
    30
    transcoders_log = Log()
morphbr@718
    31
    tid_queue = []
morphbr@718
    32
morphbr@718
    33
    menu = {
morphbr@718
    34
        "Log": "/get_log.do",
morphbr@718
    35
        "Stop": "/stop-transcoder.do",
morphbr@718
    36
        "Status": "/status.do",
morphbr@718
    37
        "All Log": "/get_all_log.do",
morphbr@718
    38
        "Version": "/version.do",
morphbr@718
    39
        "Shutdown": "/shutdown.do"
morphbr@718
    40
        }
morphbr@718
    41
morphbr@718
    42
    @classmethod
morphbr@718
    43
    def load_plugins_transcoders(cls, directory):
morphbr@718
    44
        cls.transcoders.load_from_directory(directory)
morphbr@718
    45
morphbr@718
    46
        if cls.def_transcoder is None and cls.transcoders:
morphbr@718
    47
            cls.def_transcoder = cls.transcoders[0].name
morphbr@718
    48
    # load_plugins_transcoders()
morphbr@718
    49
morphbr@718
    50
morphbr@718
    51
    def do_dispatch(self, body):
morphbr@718
    52
        self.url = self.path
morphbr@718
    53
        pieces = urlparse.urlparse(self.path)
morphbr@718
    54
        self.path = pieces[2]
morphbr@718
    55
        self.query = cgi.parse_qs(pieces[4])
morphbr@718
    56
morphbr@723
    57
        url = {
morphbr@723
    58
            "/": self.serve_main,
morphbr@723
    59
            "/shutdown.do": self.serve_shutdown,
morphbr@723
    60
            "/stop-transcoder.do": self.serve_stop_transcoder,
morphbr@723
    61
            "/status.do": self.serve_status,
morphbr@723
    62
            "/version.do": self.serve_version,
morphbr@723
    63
            "/new_id.do": self.serve_new_id,
morphbr@723
    64
            "/get_log.do": self.serve_get_log,
morphbr@723
    65
            "/get_all_log.do": self.serve_get_all_log,
morphbr@723
    66
            "/stream.do": self.serve_stream,
morphbr@723
    67
            "/list.do": self.serve_list,
morphbr@723
    68
            }
morphbr@723
    69
morphbr@723
    70
        try:
morphbr@723
    71
            url[self.path](body)
morphbr@748
    72
        except KeyError:
morphbr@744
    73
            try:
morphbr@744
    74
                action = self.query.get("action", None)
morphbr@744
    75
                if action and "stream.do" in action:
morphbr@744
    76
                    self.serve_stream(body)
morphbr@744
    77
                elif os.path.exists("html/%s" % self.path):
morphbr@744
    78
                    data = open("html/%s" % self.path)
morphbr@744
    79
                    self.wfile.write(data.read())
morphbr@744
    80
                else:
morphbr@744
    81
                    self.send_error(404, "File not found")
morphbr@744
    82
            except Exception, e:
morphbr@744
    83
                self.log.error(e)
morphbr@723
    84
morphbr@718
    85
    # do_dispatch()
morphbr@718
    86
morphbr@718
    87
morphbr@718
    88
    def do_GET(self):
morphbr@718
    89
        self.do_dispatch(True)
morphbr@718
    90
    # do_GET()
morphbr@718
    91
morphbr@718
    92
morphbr@718
    93
    def do_HEAD(self):
morphbr@718
    94
        self.do_dispatch(False)
morphbr@718
    95
    # do_HEAD()
morphbr@718
    96
morphbr@718
    97
morphbr@718
    98
    def _nav_items(self):
morphbr@718
    99
        ret = ""
morphbr@718
   100
        for name, url in self.menu.items():
morphbr@718
   101
            ret += utils.getHTML("menu", {"name": name, "url": url})
morphbr@718
   102
        return ret
morphbr@718
   103
    # _nav_items()
morphbr@718
   104
morphbr@723
   105
morphbr@718
   106
    def serve_main(self, body):
morphbr@718
   107
        self.send_response(200)
morphbr@718
   108
        self.send_header("Content-Type", "text/html")
morphbr@718
   109
        self.send_header('Connection', 'close')
morphbr@718
   110
        self.end_headers()
morphbr@718
   111
        if body:
morphbr@718
   112
            self.wfile.write(utils.getHTML("index", {"menu": self._nav_items()}))
morphbr@718
   113
    # serve_main()
morphbr@718
   114
morphbr@723
   115
morphbr@718
   116
    def serve_version(self, body):
morphbr@718
   117
        self.send_response(200)
morphbr@718
   118
        self.send_header("Content-Type", "text/html")
morphbr@718
   119
        self.send_header('Connection', 'close')
morphbr@718
   120
        self.end_headers()
morphbr@718
   121
        if body:
morphbr@718
   122
            self.wfile.write("Version: %s" %  __version__)
morphbr@723
   123
    # serve_version
morphbr@718
   124
morphbr@718
   125
morphbr@718
   126
    def serve_shutdown(self, body):
morphbr@718
   127
        self.send_response(200)
morphbr@718
   128
        self.send_header("Content-Type", "text/html")
morphbr@718
   129
        self.send_header('Connection', 'close')
morphbr@718
   130
        self.end_headers()
morphbr@718
   131
        if body:
morphbr@718
   132
            self.wfile.write(utils.getHTML("shutdown"))
morphbr@718
   133
        self.server.server_close()
morphbr@718
   134
    # serve_shutdown()
morphbr@718
   135
morphbr@718
   136
morphbr@723
   137
    def serve_list(self, body):
morphbr@723
   138
        self.send_response(200)
morphbr@723
   139
        self.send_header("Content-Type", "text/html")
morphbr@723
   140
        self.send_header('Connection', 'close')
morphbr@723
   141
        self.end_headers()
morphbr@724
   142
morphbr@724
   143
        if body:
morphbr@723
   144
            file_list = []
morphbr@724
   145
            files.list_media_files(".transcoded", file_list)
morphbr@723
   146
            output = files.FileList(map(lambda x, y: x+y, file_list,
morphbr@723
   147
                                        ["<br>"]*len(file_list)))
morphbr@724
   148
            self.wfile.write(output)
morphbr@723
   149
morphbr@723
   150
    # serve_list()
morphbr@723
   151
morphbr@723
   152
morphbr@718
   153
    def serve_stop_all_transcoders(self, body):
morphbr@718
   154
        self.send_response(200)
morphbr@718
   155
        self.send_header("Content-Type", "text/html")
morphbr@718
   156
        self.send_header('Connection', 'close')
morphbr@718
   157
        self.end_headers()
morphbr@718
   158
        if body:
morphbr@718
   159
            self.server.stop_transcoders()
morphbr@723
   160
            self.wfile.write(utils.getHTML("stop_all",
morphbr@723
   161
                                           {"menu": self._nav_items()}))
morphbr@718
   162
    # serve_stop_all_transcoders()
morphbr@718
   163
morphbr@718
   164
morphbr@718
   165
    def serve_stop_selected_transcoders(self, body, tids=[]):
morphbr@718
   166
        self.send_response(200)
morphbr@718
   167
        self.send_header("Content-Type", "text/html")
morphbr@718
   168
        self.send_header('Connection', 'close')
morphbr@718
   169
        self.end_headers()
morphbr@718
   170
        opts = ""
morphbr@718
   171
        if body:
morphbr@718
   172
            transcoders = self.server.get_transcoders()
morphbr@718
   173
morphbr@718
   174
            for tid in tids:
morphbr@718
   175
                for t, r in transcoders:
morphbr@718
   176
                    if t.tid == int(tid):
morphbr@718
   177
                        try:
morphbr@718
   178
                            t.stop()
morphbr@718
   179
                        except Exception, e:
morphbr@718
   180
                            self.log.info("Plugin already stopped")
morphbr@718
   181
morphbr@718
   182
                        opts += utils._create_html_item("%s" % t)
morphbr@718
   183
morphbr@718
   184
                        break
morphbr@718
   185
morphbr@718
   186
                self.wfile.write(utils.getHTML("stop_selected",
morphbr@718
   187
                                               {"menu": self._nav_items(),
morphbr@718
   188
                                                "opts": opts}))
morphbr@718
   189
    # serve_stop_selected_transcoders()
morphbr@718
   190
morphbr@718
   191
morphbr@718
   192
    def serve_stop_transcoder(self, body):
morphbr@718
   193
        req = self.query.get("request", None)
morphbr@718
   194
        tid = self.query.get("tid", None)
morphbr@718
   195
        if req and "all" in req:
morphbr@718
   196
            self.serve_stop_all_transcoders(body)
morphbr@718
   197
        elif tid:
morphbr@718
   198
            self.serve_stop_selected_transcoders(body, tid[0].split(";"))
morphbr@718
   199
        else:
morphbr@718
   200
            self.serve_status(body)
morphbr@718
   201
    # serve_stop_transcoder()
morphbr@718
   202
morphbr@718
   203
morphbr@718
   204
    def serve_status(self, body):
morphbr@718
   205
        self.send_response(200)
morphbr@718
   206
        self.send_header("Content-Type", "text/html")
morphbr@718
   207
        self.send_header('Connection', 'close')
morphbr@718
   208
        self.end_headers()
morphbr@718
   209
        stopone = ""
morphbr@732
   210
        running = ""
morphbr@732
   211
        stopall = ""
morphbr@718
   212
morphbr@718
   213
        if body:
morphbr@718
   214
            tl = self.server.get_transcoders()
morphbr@741
   215
            if not tl and not self.query.get("tid", None) and \
morphbr@741
   216
                   not self.query.get("running", None):
morphbr@718
   217
                running = "<p>No running transcoder.</p>\n"
morphbr@718
   218
morphbr@741
   219
            elif not tl and self.query.get("tid", None):
morphbr@724
   220
                tids = self.query.get("tid")
morphbr@724
   221
                for tid in tids:
morphbr@724
   222
                    stat = self.transcoders_log.get_status(int(tid))
morphbr@729
   223
                    self.wfile.write("%s<br>" % stat)
morphbr@743
   224
                return True
morphbr@723
   225
morphbr@741
   226
            elif self.query.get("running", None):
morphbr@741
   227
                for transcoder, request in tl:
morphbr@741
   228
                    outf = transcoder.params_first("outfile")
morphbr@741
   229
                    tid = transcoder.tid
morphbr@741
   230
                    self.wfile.write("%s:%s<br>" % (tid, outf))
morphbr@741
   231
                return True
morphbr@741
   232
morphbr@718
   233
            elif self.query.get("tid", None):
morphbr@724
   234
                req_tid = self.query.get("tid")
morphbr@718
   235
                for transcoder, request in tl:
morphbr@724
   236
                    if str(transcoder.tid) in req_tid:
morphbr@734
   237
                        self.wfile.write("Status:%s:%s %%" % (\
morphbr@724
   238
                            transcoder.tid, transcoder.status))
morphbr@724
   239
                return True
morphbr@718
   240
morphbr@718
   241
            else:
morphbr@718
   242
                running = "<p>Running transcoders:</p>\n"
morphbr@718
   243
                stopall = utils._create_html_item("<a href='%s?request=all'>"
morphbr@718
   244
                                                 "[STOP ALL]</a>" %
morphbr@718
   245
                                                 self.menu["Stop"])
morphbr@718
   246
morphbr@718
   247
                for transcoder, request in tl:
morphbr@718
   248
                    stopone += utils._create_html_item("%s;"
morphbr@718
   249
                                                       "<a href='%s?tid=%s'>"
morphbr@718
   250
                                                       " [STOP] </a>") % (
morphbr@718
   251
                        transcoder, self.menu["Stop"], transcoder.tid)
morphbr@718
   252
morphbr@718
   253
            self.wfile.write(utils.getHTML("status",
morphbr@718
   254
                                           {"menu": self._nav_items(),
morphbr@718
   255
                                            "running": running,
morphbr@718
   256
                                            "stopall": stopall,
morphbr@718
   257
                                            "stopone": stopone}))
morphbr@718
   258
    # serve_status()
morphbr@718
   259
morphbr@718
   260
morphbr@718
   261
    def _get_transcoder(self):
morphbr@718
   262
        # get transcoder option: mencoder is the default
morphbr@718
   263
        request_transcoders = self.query.get("transcoder", ["mencoder"])
morphbr@718
   264
morphbr@718
   265
        for t in request_transcoders:
morphbr@718
   266
            transcoder = self.transcoders.get(t)
morphbr@718
   267
            if transcoder:
morphbr@718
   268
                return transcoder
morphbr@718
   269
morphbr@718
   270
        if not transcoder:
morphbr@718
   271
            return self.transcoders[self.def_transcoder]
morphbr@718
   272
    # _get_transcoder()
morphbr@718
   273
morphbr@718
   274
morphbr@718
   275
    def _get_new_id(self, tid):
morphbr@718
   276
        self.server.last_tid = utils.create_tid(tid)
morphbr@718
   277
        self.tid_queue.append(self.server.last_tid)
morphbr@718
   278
        return self.server.last_tid
morphbr@718
   279
    # _get_new_id()
morphbr@718
   280
morphbr@718
   281
morphbr@718
   282
    def serve_new_id(self, body):
morphbr@718
   283
        self.send_response(200)
morphbr@718
   284
        self.send_header("Content-Type", "text/html")
morphbr@718
   285
        self.send_header('Connection', 'close')
morphbr@718
   286
        self.end_headers()
morphbr@718
   287
morphbr@718
   288
        if body:
morphbr@718
   289
            self.wfile.write("%s" % self._get_new_id(self.server.last_tid))
morphbr@718
   290
    # serve_new_id()
morphbr@718
   291
morphbr@718
   292
    def serve_get_log(self, body):
morphbr@718
   293
        self.send_response(200)
morphbr@718
   294
        self.send_header("Content-Type", "text/html")
morphbr@718
   295
        self.send_header('Connection', 'close')
morphbr@718
   296
        self.end_headers()
morphbr@718
   297
morphbr@718
   298
        if body:
morphbr@718
   299
            if self.query.get("tid", None):
morphbr@718
   300
                tid = int(self.query.get("tid")[0])
morphbr@718
   301
                stat = self.transcoders_log.get_status(tid)
morphbr@723
   302
                self.wfile.write("Status: %s" % stat)
morphbr@718
   303
            else:
morphbr@718
   304
                stat = self.transcoders_log.get_status()
morphbr@718
   305
                for rtid, status in stat.iteritems():
morphbr@718
   306
                    self.wfile.write("<b>%s</b>: %s<br><br>" % (rtid, status))
morphbr@718
   307
    # serve_get_log()
morphbr@718
   308
morphbr@718
   309
    def serve_get_all_log(self, body):
morphbr@718
   310
        self.send_response(200)
morphbr@718
   311
        self.send_header("Content-Type", "text/html")
morphbr@718
   312
        self.send_header('Connection', 'close')
morphbr@718
   313
        self.end_headers()
morphbr@718
   314
morphbr@718
   315
        if body:
morphbr@718
   316
            if self.query.get("tid", None):
morphbr@718
   317
                tid = int(self.query.get("tid")[0])
morphbr@718
   318
                stat = self.transcoders_log.get_status(tid, True)
morphbr@718
   319
                for status in stat:
morphbr@718
   320
                    self.wfile.write("%s<br><br>" % status)
morphbr@718
   321
            else:
morphbr@718
   322
                stat = self.transcoders_log.get_status(None, True)
morphbr@718
   323
                for rtid, history in stat.iteritems():
morphbr@718
   324
                    for status in history:
morphbr@718
   325
                        self.wfile.write("<b>%s</b>: %s<br>" % (rtid, status))
morphbr@718
   326
                    self.wfile.write("<br><br>")
morphbr@718
   327
    # serve_get_all_log()
morphbr@718
   328
morphbr@718
   329
    def serve_stream(self, body):
morphbr@718
   330
        transcoder = self._get_transcoder()
morphbr@718
   331
        try:
morphbr@718
   332
            obj = transcoder(self.query)
morphbr@718
   333
        except Exception, e:
morphbr@718
   334
            self.send_error(500, str(e))
morphbr@718
   335
            return
morphbr@718
   336
morphbr@718
   337
        self.send_response(200)
morphbr@718
   338
        self.send_header("Content-Type", obj.get_mimetype())
morphbr@743
   339
        self.send_header("Connection", "close")
morphbr@718
   340
        self.end_headers()
morphbr@718
   341
morphbr@718
   342
        if body:
morphbr@742
   343
morphbr@744
   344
            test_tid = int(self.query.get("tid", "0")[0])
morphbr@744
   345
            if test_tid == 0 or test_tid not in self.tid_queue:
morphbr@744
   346
                test_tid = self._get_new_id(self.server.last_tid)
morphbr@744
   347
morphbr@748
   348
morphbr@724
   349
            if self.query.get("transcoder", None):
morphbr@724
   350
                self.transcoders_log.insert(test_tid, "gms.%s" % obj.name)
morphbr@724
   351
                obj.tid = test_tid
morphbr@724
   352
                obj.log = self.transcoders_log
morphbr@718
   353
morphbr@724
   354
                self.server.add_transcoders(self, obj)
morphbr@724
   355
                obj.start(self.wfile)
morphbr@724
   356
                self.server.del_transcoders(self, obj)
morphbr@726
   357
                files.TranscodedFile("", self.query)
morphbr@724
   358
morphbr@724
   359
            elif self.query.get("type", "")[0] == "file" and \
morphbr@724
   360
                     self.query.get("uri", None):
morphbr@745
   361
morphbr@745
   362
                filename = self.query.get("uri", None)[0]
morphbr@745
   363
                self.transcoders_log.insert(test_tid, "gms.%s" % filename)
morphbr@745
   364
morphbr@742
   365
                try:
morphbr@744
   366
                    media = open(filename)
morphbr@744
   367
                    data_in = " "
morphbr@744
   368
                    total_read = 0
morphbr@744
   369
                    size = int(os.path.getsize(filename))
morphbr@744
   370
morphbr@744
   371
                    while data_in != "":
morphbr@744
   372
                        data_in = media.read(4096)
morphbr@744
   373
                        total_read += 4096
morphbr@744
   374
                        self.wfile.write(data_in)
morphbr@744
   375
                        status = utils.progress_bar(total_read, size, 50)
morphbr@744
   376
                        msg_status = "Status:%s:%s%%" % (test_tid, status)
morphbr@744
   377
                        self.transcoders_log._update_status(test_tid,
morphbr@744
   378
                                                            msg_status)
morphbr@744
   379
morphbr@745
   380
                    self.transcoders_log._update_status(test_tid, "OK: Done")
morphbr@745
   381
morphbr@743
   382
                except Exception, e:
morphbr@742
   383
                    self.log.error("Stream error: %s" %e)
morphbr@745
   384
                    self.transcoders_log._update_status(test_tid,
morphbr@745
   385
                                                        "Error: %s" % e)
morphbr@718
   386
    # serve_stream()
morphbr@718
   387
morphbr@718
   388
morphbr@718
   389
    def log_request(self, code='-', size='-'):
morphbr@718
   390
        self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
morphbr@718
   391
    # log_request()
morphbr@718
   392
morphbr@718
   393
morphbr@718
   394
    def log_error(self, format, *args):
morphbr@718
   395
        self.log.error("%s: %s" % (self.address_string(), format % args))
morphbr@718
   396
    # log_error()
morphbr@718
   397
morphbr@718
   398
morphbr@718
   399
    def log_message(self, format, *args):
morphbr@718
   400
        self.log.info("%s: %s" % (self.address_string(), format % args))
morphbr@718
   401
    # log_message()
morphbr@724
   402
morphbr@718
   403
# RequestHandler