gmyth-stream/server/0.3/lib/request_handler.py
author morphbr
Thu May 31 19:36:03 2007 +0100 (2007-05-31)
branchtrunk
changeset 728 6e54ca4a4e9a
parent 724 64b061775d06
child 729 8ef808220720
permissions -rw-r--r--
[svn r734] * GMyth-Streamer
- Close socket when transcoding to file (bug fix)
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@723
    72
        except KeyError, e:
morphbr@718
    73
            action = self.query.get("action", None)
morphbr@718
    74
            if action and "stream.do" in action:
morphbr@718
    75
                self.serve_stream(body)
morphbr@718
    76
            else:
morphbr@718
    77
                self.send_error(404, "File not found")
morphbr@723
    78
morphbr@718
    79
    # do_dispatch()
morphbr@718
    80
morphbr@718
    81
morphbr@718
    82
    def do_GET(self):
morphbr@718
    83
        self.do_dispatch(True)
morphbr@718
    84
    # do_GET()
morphbr@718
    85
morphbr@718
    86
morphbr@718
    87
    def do_HEAD(self):
morphbr@718
    88
        self.do_dispatch(False)
morphbr@718
    89
    # do_HEAD()
morphbr@718
    90
morphbr@718
    91
morphbr@718
    92
    def _nav_items(self):
morphbr@718
    93
        ret = ""
morphbr@718
    94
        for name, url in self.menu.items():
morphbr@718
    95
            ret += utils.getHTML("menu", {"name": name, "url": url})
morphbr@718
    96
        return ret
morphbr@718
    97
    # _nav_items()
morphbr@718
    98
morphbr@723
    99
morphbr@718
   100
    def serve_main(self, body):
morphbr@718
   101
        self.send_response(200)
morphbr@718
   102
        self.send_header("Content-Type", "text/html")
morphbr@718
   103
        self.send_header('Connection', 'close')
morphbr@718
   104
        self.end_headers()
morphbr@718
   105
        if body:
morphbr@718
   106
            self.wfile.write(utils.getHTML("index", {"menu": self._nav_items()}))
morphbr@718
   107
    # serve_main()
morphbr@718
   108
morphbr@723
   109
morphbr@718
   110
    def serve_version(self, body):
morphbr@718
   111
        self.send_response(200)
morphbr@718
   112
        self.send_header("Content-Type", "text/html")
morphbr@718
   113
        self.send_header('Connection', 'close')
morphbr@718
   114
        self.end_headers()
morphbr@718
   115
        if body:
morphbr@718
   116
            self.wfile.write("Version: %s" %  __version__)
morphbr@723
   117
    # serve_version
morphbr@718
   118
morphbr@718
   119
morphbr@718
   120
    def serve_shutdown(self, body):
morphbr@718
   121
        self.send_response(200)
morphbr@718
   122
        self.send_header("Content-Type", "text/html")
morphbr@718
   123
        self.send_header('Connection', 'close')
morphbr@718
   124
        self.end_headers()
morphbr@718
   125
        if body:
morphbr@718
   126
            self.wfile.write(utils.getHTML("shutdown"))
morphbr@718
   127
        self.server.server_close()
morphbr@718
   128
    # serve_shutdown()
morphbr@718
   129
morphbr@718
   130
morphbr@723
   131
    def serve_list(self, body):
morphbr@723
   132
        self.send_response(200)
morphbr@723
   133
        self.send_header("Content-Type", "text/html")
morphbr@723
   134
        self.send_header('Connection', 'close')
morphbr@723
   135
        self.end_headers()
morphbr@724
   136
morphbr@724
   137
        if body:
morphbr@723
   138
            file_list = []
morphbr@724
   139
            files.list_media_files(".transcoded", file_list)
morphbr@723
   140
            output = files.FileList(map(lambda x, y: x+y, file_list,
morphbr@723
   141
                                        ["<br>"]*len(file_list)))
morphbr@724
   142
            self.wfile.write(output)
morphbr@723
   143
morphbr@723
   144
    # serve_list()
morphbr@723
   145
morphbr@723
   146
morphbr@718
   147
    def serve_stop_all_transcoders(self, body):
morphbr@718
   148
        self.send_response(200)
morphbr@718
   149
        self.send_header("Content-Type", "text/html")
morphbr@718
   150
        self.send_header('Connection', 'close')
morphbr@718
   151
        self.end_headers()
morphbr@718
   152
        if body:
morphbr@718
   153
            self.server.stop_transcoders()
morphbr@723
   154
            self.wfile.write(utils.getHTML("stop_all",
morphbr@723
   155
                                           {"menu": self._nav_items()}))
morphbr@718
   156
    # serve_stop_all_transcoders()
morphbr@718
   157
morphbr@718
   158
morphbr@718
   159
    def serve_stop_selected_transcoders(self, body, tids=[]):
morphbr@718
   160
        self.send_response(200)
morphbr@718
   161
        self.send_header("Content-Type", "text/html")
morphbr@718
   162
        self.send_header('Connection', 'close')
morphbr@718
   163
        self.end_headers()
morphbr@718
   164
        opts = ""
morphbr@718
   165
        if body:
morphbr@718
   166
            transcoders = self.server.get_transcoders()
morphbr@718
   167
morphbr@718
   168
            for tid in tids:
morphbr@718
   169
                for t, r in transcoders:
morphbr@718
   170
                    if t.tid == int(tid):
morphbr@718
   171
                        try:
morphbr@718
   172
                            t.stop()
morphbr@718
   173
                        except Exception, e:
morphbr@718
   174
                            self.log.info("Plugin already stopped")
morphbr@718
   175
morphbr@718
   176
                        opts += utils._create_html_item("%s" % t)
morphbr@718
   177
morphbr@718
   178
                        break
morphbr@718
   179
morphbr@718
   180
                self.wfile.write(utils.getHTML("stop_selected",
morphbr@718
   181
                                               {"menu": self._nav_items(),
morphbr@718
   182
                                                "opts": opts}))
morphbr@718
   183
    # serve_stop_selected_transcoders()
morphbr@718
   184
morphbr@718
   185
morphbr@718
   186
    def serve_stop_transcoder(self, body):
morphbr@718
   187
        req = self.query.get("request", None)
morphbr@718
   188
        tid = self.query.get("tid", None)
morphbr@718
   189
        if req and "all" in req:
morphbr@718
   190
            self.serve_stop_all_transcoders(body)
morphbr@718
   191
        elif tid:
morphbr@718
   192
            self.serve_stop_selected_transcoders(body, tid[0].split(";"))
morphbr@718
   193
        else:
morphbr@718
   194
            self.serve_status(body)
morphbr@718
   195
    # serve_stop_transcoder()
morphbr@718
   196
morphbr@718
   197
morphbr@718
   198
    def serve_status(self, body):
morphbr@718
   199
        self.send_response(200)
morphbr@718
   200
        self.send_header("Content-Type", "text/html")
morphbr@718
   201
        self.send_header('Connection', 'close')
morphbr@718
   202
        self.end_headers()
morphbr@718
   203
        stopone = ""
morphbr@718
   204
morphbr@718
   205
        if body:
morphbr@718
   206
            tl = self.server.get_transcoders()
morphbr@723
   207
            if not tl and not self.query.get("tid", None):
morphbr@718
   208
                running = "<p>No running transcoder.</p>\n"
morphbr@718
   209
                stopall = ""
morphbr@718
   210
                stopone = ""
morphbr@718
   211
morphbr@723
   212
            elif self.query.get("tid", None) and not tl:
morphbr@724
   213
                tids = self.query.get("tid")
morphbr@724
   214
                for tid in tids:
morphbr@724
   215
                    stat = self.transcoders_log.get_status(int(tid))
morphbr@724
   216
                    self.wfile.write("Running: %s<br>" % stat)
morphbr@723
   217
morphbr@718
   218
            elif self.query.get("tid", None):
morphbr@724
   219
                req_tid = self.query.get("tid")
morphbr@718
   220
                for transcoder, request in tl:
morphbr@724
   221
                    if str(transcoder.tid) in req_tid:
morphbr@724
   222
                        self.wfile.write("%s:Status: %s %%" % (\
morphbr@724
   223
                            transcoder.tid, transcoder.status))
morphbr@724
   224
                return True
morphbr@718
   225
morphbr@718
   226
            else:
morphbr@718
   227
                running = "<p>Running transcoders:</p>\n"
morphbr@718
   228
                stopall = utils._create_html_item("<a href='%s?request=all'>"
morphbr@718
   229
                                                 "[STOP ALL]</a>" %
morphbr@718
   230
                                                 self.menu["Stop"])
morphbr@718
   231
morphbr@718
   232
                for transcoder, request in tl:
morphbr@718
   233
                    stopone += utils._create_html_item("%s;"
morphbr@718
   234
                                                       "<a href='%s?tid=%s'>"
morphbr@718
   235
                                                       " [STOP] </a>") % (
morphbr@718
   236
                        transcoder, self.menu["Stop"], transcoder.tid)
morphbr@718
   237
morphbr@718
   238
            self.wfile.write(utils.getHTML("status",
morphbr@718
   239
                                           {"menu": self._nav_items(),
morphbr@718
   240
                                            "running": running,
morphbr@718
   241
                                            "stopall": stopall,
morphbr@718
   242
                                            "stopone": stopone}))
morphbr@718
   243
    # serve_status()
morphbr@718
   244
morphbr@718
   245
morphbr@718
   246
    def _get_transcoder(self):
morphbr@718
   247
        # get transcoder option: mencoder is the default
morphbr@718
   248
        request_transcoders = self.query.get("transcoder", ["mencoder"])
morphbr@718
   249
morphbr@718
   250
        for t in request_transcoders:
morphbr@718
   251
            transcoder = self.transcoders.get(t)
morphbr@718
   252
            if transcoder:
morphbr@718
   253
                return transcoder
morphbr@718
   254
morphbr@718
   255
        if not transcoder:
morphbr@718
   256
            return self.transcoders[self.def_transcoder]
morphbr@718
   257
    # _get_transcoder()
morphbr@718
   258
morphbr@718
   259
morphbr@718
   260
    def _get_new_id(self, tid):
morphbr@718
   261
        self.server.last_tid = utils.create_tid(tid)
morphbr@718
   262
        self.tid_queue.append(self.server.last_tid)
morphbr@718
   263
        return self.server.last_tid
morphbr@718
   264
    # _get_new_id()
morphbr@718
   265
morphbr@718
   266
morphbr@718
   267
    def serve_new_id(self, body):
morphbr@718
   268
        self.send_response(200)
morphbr@718
   269
        self.send_header("Content-Type", "text/html")
morphbr@718
   270
        self.send_header('Connection', 'close')
morphbr@718
   271
        self.end_headers()
morphbr@718
   272
morphbr@718
   273
        if body:
morphbr@718
   274
            self.wfile.write("%s" % self._get_new_id(self.server.last_tid))
morphbr@718
   275
    # serve_new_id()
morphbr@718
   276
morphbr@718
   277
    def serve_get_log(self, body):
morphbr@718
   278
        self.send_response(200)
morphbr@718
   279
        self.send_header("Content-Type", "text/html")
morphbr@718
   280
        self.send_header('Connection', 'close')
morphbr@718
   281
        self.end_headers()
morphbr@718
   282
morphbr@718
   283
        if body:
morphbr@718
   284
            if self.query.get("tid", None):
morphbr@718
   285
                tid = int(self.query.get("tid")[0])
morphbr@718
   286
                stat = self.transcoders_log.get_status(tid)
morphbr@723
   287
                self.wfile.write("Status: %s" % stat)
morphbr@718
   288
            else:
morphbr@718
   289
                stat = self.transcoders_log.get_status()
morphbr@718
   290
                for rtid, status in stat.iteritems():
morphbr@718
   291
                    self.wfile.write("<b>%s</b>: %s<br><br>" % (rtid, status))
morphbr@718
   292
    # serve_get_log()
morphbr@718
   293
morphbr@718
   294
    def serve_get_all_log(self, body):
morphbr@718
   295
        self.send_response(200)
morphbr@718
   296
        self.send_header("Content-Type", "text/html")
morphbr@718
   297
        self.send_header('Connection', 'close')
morphbr@718
   298
        self.end_headers()
morphbr@718
   299
morphbr@718
   300
        if body:
morphbr@718
   301
            if self.query.get("tid", None):
morphbr@718
   302
                tid = int(self.query.get("tid")[0])
morphbr@718
   303
                stat = self.transcoders_log.get_status(tid, True)
morphbr@718
   304
                for status in stat:
morphbr@718
   305
                    self.wfile.write("%s<br><br>" % status)
morphbr@718
   306
            else:
morphbr@718
   307
                stat = self.transcoders_log.get_status(None, True)
morphbr@718
   308
                for rtid, history in stat.iteritems():
morphbr@718
   309
                    for status in history:
morphbr@718
   310
                        self.wfile.write("<b>%s</b>: %s<br>" % (rtid, status))
morphbr@718
   311
                    self.wfile.write("<br><br>")
morphbr@718
   312
    # serve_get_all_log()
morphbr@718
   313
morphbr@718
   314
    def serve_stream(self, body):
morphbr@718
   315
        transcoder = self._get_transcoder()
morphbr@718
   316
        try:
morphbr@718
   317
            obj = transcoder(self.query)
morphbr@718
   318
        except Exception, e:
morphbr@718
   319
            self.send_error(500, str(e))
morphbr@718
   320
            return
morphbr@718
   321
morphbr@718
   322
        self.send_response(200)
morphbr@718
   323
        self.send_header("Content-Type", obj.get_mimetype())
morphbr@718
   324
        self.send_header('Connection', 'close')
morphbr@718
   325
        self.end_headers()
morphbr@718
   326
morphbr@718
   327
        if body:
morphbr@724
   328
            if self.query.get("transcoder", None):
morphbr@724
   329
                test_tid = int(self.query.get("tid", "0")[0])
morphbr@724
   330
                if test_tid == 0 or test_tid not in self.tid_queue:
morphbr@724
   331
                    test_tid = self._get_new_id(self.server.last_tid)
morphbr@718
   332
morphbr@724
   333
                self.transcoders_log.insert(test_tid, "gms.%s" % obj.name)
morphbr@724
   334
                obj.tid = test_tid
morphbr@724
   335
                obj.log = self.transcoders_log
morphbr@718
   336
morphbr@724
   337
                self.server.add_transcoders(self, obj)
morphbr@724
   338
                obj.start(self.wfile)
morphbr@724
   339
                self.server.del_transcoders(self, obj)
morphbr@726
   340
                files.TranscodedFile("", self.query)
morphbr@724
   341
morphbr@724
   342
            elif self.query.get("type", "")[0] == "file" and \
morphbr@724
   343
                     self.query.get("uri", None):
morphbr@724
   344
                media = open(self.query.get("uri", None)[0])
morphbr@724
   345
                self.wfile.write(media.read())
morphbr@718
   346
    # serve_stream()
morphbr@718
   347
morphbr@718
   348
morphbr@718
   349
    def log_request(self, code='-', size='-'):
morphbr@718
   350
        self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
morphbr@718
   351
    # log_request()
morphbr@718
   352
morphbr@718
   353
morphbr@718
   354
    def log_error(self, format, *args):
morphbr@718
   355
        self.log.error("%s: %s" % (self.address_string(), format % args))
morphbr@718
   356
    # log_error()
morphbr@718
   357
morphbr@718
   358
morphbr@718
   359
    def log_message(self, format, *args):
morphbr@718
   360
        self.log.info("%s: %s" % (self.address_string(), format % args))
morphbr@718
   361
    # log_message()
morphbr@724
   362
morphbr@718
   363
# RequestHandler