gmyth-stream/server/0.3/lib/request_handler.py
author morphbr
Wed Jul 04 09:09:48 2007 +0100 (2007-07-04)
branchtrunk
changeset 775 7cd98c74da22
parent 774 366b0fd1eead
child 795 2b4e9d183146
permissions -rw-r--r--
[svn r781] - More bug fixes to file_info
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@773
    68
            "/get_file_info.do": self.serve_file_info,
morphbr@723
    69
            }
morphbr@723
    70
morphbr@723
    71
        try:
morphbr@723
    72
            url[self.path](body)
morphbr@748
    73
        except KeyError:
morphbr@744
    74
            try:
morphbr@744
    75
                action = self.query.get("action", None)
morphbr@744
    76
                if action and "stream.do" in action:
morphbr@744
    77
                    self.serve_stream(body)
morphbr@744
    78
                elif os.path.exists("html/%s" % self.path):
morphbr@744
    79
                    data = open("html/%s" % self.path)
morphbr@744
    80
                    self.wfile.write(data.read())
morphbr@744
    81
                else:
morphbr@744
    82
                    self.send_error(404, "File not found")
morphbr@744
    83
            except Exception, e:
morphbr@744
    84
                self.log.error(e)
morphbr@723
    85
morphbr@718
    86
    # do_dispatch()
morphbr@718
    87
morphbr@718
    88
morphbr@718
    89
    def do_GET(self):
morphbr@718
    90
        self.do_dispatch(True)
morphbr@718
    91
    # do_GET()
morphbr@718
    92
morphbr@718
    93
morphbr@718
    94
    def do_HEAD(self):
morphbr@718
    95
        self.do_dispatch(False)
morphbr@718
    96
    # do_HEAD()
morphbr@718
    97
morphbr@718
    98
morphbr@718
    99
    def _nav_items(self):
morphbr@718
   100
        ret = ""
morphbr@718
   101
        for name, url in self.menu.items():
morphbr@718
   102
            ret += utils.getHTML("menu", {"name": name, "url": url})
morphbr@718
   103
        return ret
morphbr@718
   104
    # _nav_items()
morphbr@718
   105
morphbr@723
   106
morphbr@718
   107
    def serve_main(self, body):
morphbr@718
   108
        self.send_response(200)
morphbr@718
   109
        self.send_header("Content-Type", "text/html")
morphbr@718
   110
        self.send_header('Connection', 'close')
morphbr@718
   111
        self.end_headers()
morphbr@718
   112
        if body:
morphbr@718
   113
            self.wfile.write(utils.getHTML("index", {"menu": self._nav_items()}))
morphbr@718
   114
    # serve_main()
morphbr@718
   115
morphbr@723
   116
morphbr@718
   117
    def serve_version(self, body):
morphbr@718
   118
        self.send_response(200)
morphbr@718
   119
        self.send_header("Content-Type", "text/html")
morphbr@718
   120
        self.send_header('Connection', 'close')
morphbr@718
   121
        self.end_headers()
morphbr@718
   122
        if body:
morphbr@718
   123
            self.wfile.write("Version: %s" %  __version__)
morphbr@723
   124
    # serve_version
morphbr@718
   125
morphbr@718
   126
morphbr@718
   127
    def serve_shutdown(self, body):
morphbr@718
   128
        self.send_response(200)
morphbr@718
   129
        self.send_header("Content-Type", "text/html")
morphbr@718
   130
        self.send_header('Connection', 'close')
morphbr@718
   131
        self.end_headers()
morphbr@718
   132
        if body:
morphbr@718
   133
            self.wfile.write(utils.getHTML("shutdown"))
morphbr@718
   134
        self.server.server_close()
morphbr@718
   135
    # serve_shutdown()
morphbr@718
   136
morphbr@718
   137
morphbr@723
   138
    def serve_list(self, body):
morphbr@723
   139
        self.send_response(200)
morphbr@723
   140
        self.send_header("Content-Type", "text/html")
morphbr@723
   141
        self.send_header('Connection', 'close')
morphbr@723
   142
        self.end_headers()
morphbr@724
   143
morphbr@724
   144
        if body:
morphbr@723
   145
            file_list = []
morphbr@724
   146
            files.list_media_files(".transcoded", file_list)
morphbr@723
   147
            output = files.FileList(map(lambda x, y: x+y, file_list,
morphbr@723
   148
                                        ["<br>"]*len(file_list)))
morphbr@724
   149
            self.wfile.write(output)
morphbr@723
   150
morphbr@723
   151
    # serve_list()
morphbr@723
   152
morphbr@723
   153
morphbr@718
   154
    def serve_stop_all_transcoders(self, body):
morphbr@718
   155
        self.send_response(200)
morphbr@718
   156
        self.send_header("Content-Type", "text/html")
morphbr@718
   157
        self.send_header('Connection', 'close')
morphbr@718
   158
        self.end_headers()
morphbr@718
   159
        if body:
morphbr@718
   160
            self.server.stop_transcoders()
morphbr@723
   161
            self.wfile.write(utils.getHTML("stop_all",
morphbr@723
   162
                                           {"menu": self._nav_items()}))
morphbr@718
   163
    # serve_stop_all_transcoders()
morphbr@718
   164
morphbr@718
   165
morphbr@718
   166
    def serve_stop_selected_transcoders(self, body, tids=[]):
morphbr@718
   167
        self.send_response(200)
morphbr@718
   168
        self.send_header("Content-Type", "text/html")
morphbr@718
   169
        self.send_header('Connection', 'close')
morphbr@718
   170
        self.end_headers()
morphbr@718
   171
        opts = ""
morphbr@718
   172
        if body:
morphbr@718
   173
            transcoders = self.server.get_transcoders()
morphbr@718
   174
morphbr@718
   175
            for tid in tids:
morphbr@718
   176
                for t, r in transcoders:
morphbr@718
   177
                    if t.tid == int(tid):
morphbr@718
   178
                        try:
morphbr@718
   179
                            t.stop()
morphbr@718
   180
                        except Exception, e:
morphbr@718
   181
                            self.log.info("Plugin already stopped")
morphbr@718
   182
morphbr@718
   183
                        opts += utils._create_html_item("%s" % t)
morphbr@718
   184
morphbr@718
   185
                        break
morphbr@718
   186
morphbr@718
   187
                self.wfile.write(utils.getHTML("stop_selected",
morphbr@718
   188
                                               {"menu": self._nav_items(),
morphbr@718
   189
                                                "opts": opts}))
morphbr@718
   190
    # serve_stop_selected_transcoders()
morphbr@718
   191
morphbr@718
   192
morphbr@718
   193
    def serve_stop_transcoder(self, body):
morphbr@718
   194
        req = self.query.get("request", None)
morphbr@718
   195
        tid = self.query.get("tid", None)
morphbr@718
   196
        if req and "all" in req:
morphbr@718
   197
            self.serve_stop_all_transcoders(body)
morphbr@718
   198
        elif tid:
morphbr@718
   199
            self.serve_stop_selected_transcoders(body, tid[0].split(";"))
morphbr@718
   200
        else:
morphbr@718
   201
            self.serve_status(body)
morphbr@718
   202
    # serve_stop_transcoder()
morphbr@718
   203
morphbr@718
   204
morphbr@718
   205
    def serve_status(self, body):
morphbr@718
   206
        self.send_response(200)
morphbr@718
   207
        self.send_header("Content-Type", "text/html")
morphbr@718
   208
        self.send_header('Connection', 'close')
morphbr@718
   209
        self.end_headers()
morphbr@718
   210
        stopone = ""
morphbr@732
   211
        running = ""
morphbr@732
   212
        stopall = ""
morphbr@718
   213
morphbr@718
   214
        if body:
morphbr@718
   215
            tl = self.server.get_transcoders()
morphbr@741
   216
            if not tl and not self.query.get("tid", None) and \
morphbr@741
   217
                   not self.query.get("running", None):
morphbr@718
   218
                running = "<p>No running transcoder.</p>\n"
morphbr@718
   219
morphbr@741
   220
            elif not tl and self.query.get("tid", None):
morphbr@724
   221
                tids = self.query.get("tid")
morphbr@724
   222
                for tid in tids:
morphbr@724
   223
                    stat = self.transcoders_log.get_status(int(tid))
morphbr@729
   224
                    self.wfile.write("%s<br>" % stat)
morphbr@743
   225
                return True
morphbr@723
   226
morphbr@741
   227
            elif self.query.get("running", None):
morphbr@741
   228
                for transcoder, request in tl:
morphbr@741
   229
                    outf = transcoder.params_first("outfile")
morphbr@741
   230
                    tid = transcoder.tid
morphbr@741
   231
                    self.wfile.write("%s:%s<br>" % (tid, outf))
morphbr@741
   232
                return True
morphbr@741
   233
morphbr@718
   234
            elif self.query.get("tid", None):
morphbr@724
   235
                req_tid = self.query.get("tid")
morphbr@718
   236
                for transcoder, request in tl:
morphbr@724
   237
                    if str(transcoder.tid) in req_tid:
morphbr@734
   238
                        self.wfile.write("Status:%s:%s %%" % (\
morphbr@724
   239
                            transcoder.tid, transcoder.status))
morphbr@724
   240
                return True
morphbr@718
   241
morphbr@718
   242
            else:
morphbr@718
   243
                running = "<p>Running transcoders:</p>\n"
morphbr@718
   244
                stopall = utils._create_html_item("<a href='%s?request=all'>"
morphbr@718
   245
                                                 "[STOP ALL]</a>" %
morphbr@718
   246
                                                 self.menu["Stop"])
morphbr@718
   247
morphbr@718
   248
                for transcoder, request in tl:
morphbr@718
   249
                    stopone += utils._create_html_item("%s;"
morphbr@718
   250
                                                       "<a href='%s?tid=%s'>"
morphbr@718
   251
                                                       " [STOP] </a>") % (
morphbr@718
   252
                        transcoder, self.menu["Stop"], transcoder.tid)
morphbr@718
   253
morphbr@718
   254
            self.wfile.write(utils.getHTML("status",
morphbr@718
   255
                                           {"menu": self._nav_items(),
morphbr@718
   256
                                            "running": running,
morphbr@718
   257
                                            "stopall": stopall,
morphbr@718
   258
                                            "stopone": stopone}))
morphbr@718
   259
    # serve_status()
morphbr@718
   260
morphbr@718
   261
morphbr@718
   262
    def _get_transcoder(self):
morphbr@718
   263
        # get transcoder option: mencoder is the default
morphbr@718
   264
        request_transcoders = self.query.get("transcoder", ["mencoder"])
morphbr@718
   265
morphbr@718
   266
        for t in request_transcoders:
morphbr@718
   267
            transcoder = self.transcoders.get(t)
morphbr@718
   268
            if transcoder:
morphbr@718
   269
                return transcoder
morphbr@718
   270
morphbr@718
   271
        if not transcoder:
morphbr@718
   272
            return self.transcoders[self.def_transcoder]
morphbr@718
   273
    # _get_transcoder()
morphbr@718
   274
morphbr@718
   275
morphbr@718
   276
    def _get_new_id(self, tid):
morphbr@718
   277
        self.server.last_tid = utils.create_tid(tid)
morphbr@718
   278
        self.tid_queue.append(self.server.last_tid)
morphbr@718
   279
        return self.server.last_tid
morphbr@718
   280
    # _get_new_id()
morphbr@718
   281
morphbr@718
   282
morphbr@718
   283
    def serve_new_id(self, body):
morphbr@718
   284
        self.send_response(200)
morphbr@718
   285
        self.send_header("Content-Type", "text/html")
morphbr@718
   286
        self.send_header('Connection', 'close')
morphbr@718
   287
        self.end_headers()
morphbr@718
   288
morphbr@718
   289
        if body:
morphbr@718
   290
            self.wfile.write("%s" % self._get_new_id(self.server.last_tid))
morphbr@718
   291
    # serve_new_id()
morphbr@718
   292
morphbr@718
   293
    def serve_get_log(self, body):
morphbr@718
   294
        self.send_response(200)
morphbr@718
   295
        self.send_header("Content-Type", "text/html")
morphbr@718
   296
        self.send_header('Connection', 'close')
morphbr@718
   297
        self.end_headers()
morphbr@718
   298
morphbr@718
   299
        if body:
morphbr@718
   300
            if self.query.get("tid", None):
morphbr@718
   301
                tid = int(self.query.get("tid")[0])
morphbr@718
   302
                stat = self.transcoders_log.get_status(tid)
morphbr@723
   303
                self.wfile.write("Status: %s" % stat)
morphbr@718
   304
            else:
morphbr@718
   305
                stat = self.transcoders_log.get_status()
morphbr@718
   306
                for rtid, status in stat.iteritems():
morphbr@718
   307
                    self.wfile.write("<b>%s</b>: %s<br><br>" % (rtid, status))
morphbr@718
   308
    # serve_get_log()
morphbr@718
   309
morphbr@718
   310
    def serve_get_all_log(self, body):
morphbr@718
   311
        self.send_response(200)
morphbr@718
   312
        self.send_header("Content-Type", "text/html")
morphbr@718
   313
        self.send_header('Connection', 'close')
morphbr@718
   314
        self.end_headers()
morphbr@718
   315
morphbr@718
   316
        if body:
morphbr@718
   317
            if self.query.get("tid", None):
morphbr@718
   318
                tid = int(self.query.get("tid")[0])
morphbr@718
   319
                stat = self.transcoders_log.get_status(tid, True)
morphbr@718
   320
                for status in stat:
morphbr@718
   321
                    self.wfile.write("%s<br><br>" % status)
morphbr@718
   322
            else:
morphbr@718
   323
                stat = self.transcoders_log.get_status(None, True)
morphbr@718
   324
                for rtid, history in stat.iteritems():
morphbr@718
   325
                    for status in history:
morphbr@718
   326
                        self.wfile.write("<b>%s</b>: %s<br>" % (rtid, status))
morphbr@718
   327
                    self.wfile.write("<br><br>")
morphbr@718
   328
    # serve_get_all_log()
morphbr@718
   329
morphbr@773
   330
morphbr@773
   331
    def serve_file_info(self, body):
morphbr@773
   332
        if body:
morphbr@773
   333
morphbr@773
   334
            file_dat = self.query.get("file", None)
morphbr@773
   335
morphbr@773
   336
            if file_dat:
morphbr@773
   337
                self.send_response(200)
morphbr@773
   338
                self.send_header("Content-Type", "text/html")
morphbr@773
   339
                self.send_header('Connection', 'close')
morphbr@773
   340
                self.end_headers()
morphbr@773
   341
morphbr@773
   342
                try:
morphbr@775
   343
                    opts = files.TranscodedFile(file_dat[0], self.query).opts
morphbr@773
   344
                    for key in opts.keys():
morphbr@775
   345
                        self.wfile.write("%s=%s<br>" % (key, opts.get(key, "None")[0]))
morphbr@775
   346
morphbr@774
   347
                except Exception, e:
morphbr@773
   348
                    self.send_error(500, str(e))
morphbr@773
   349
                    return
morphbr@773
   350
    # serve_file_info()
morphbr@773
   351
morphbr@718
   352
    def serve_stream(self, body):
morphbr@718
   353
        transcoder = self._get_transcoder()
morphbr@718
   354
        try:
morphbr@718
   355
            obj = transcoder(self.query)
morphbr@718
   356
        except Exception, e:
morphbr@718
   357
            self.send_error(500, str(e))
morphbr@718
   358
            return
morphbr@718
   359
morphbr@718
   360
        self.send_response(200)
morphbr@718
   361
        self.send_header("Content-Type", obj.get_mimetype())
renatofilho@768
   362
	self.send_header("Cache-Control","no-cache")
morphbr@765
   363
morphbr@765
   364
        if (obj.name == "gmencoder"):
morphbr@765
   365
            self.send_header("Transfer-Encoding", "chunked")
morphbr@765
   366
morphbr@743
   367
        self.send_header("Connection", "close")
morphbr@718
   368
        self.end_headers()
morphbr@718
   369
morphbr@718
   370
        if body:
morphbr@742
   371
morphbr@744
   372
            test_tid = int(self.query.get("tid", "0")[0])
morphbr@744
   373
            if test_tid == 0 or test_tid not in self.tid_queue:
morphbr@744
   374
                test_tid = self._get_new_id(self.server.last_tid)
morphbr@744
   375
morphbr@748
   376
morphbr@724
   377
            if self.query.get("transcoder", None):
morphbr@724
   378
                self.transcoders_log.insert(test_tid, "gms.%s" % obj.name)
morphbr@724
   379
                obj.tid = test_tid
morphbr@724
   380
                obj.log = self.transcoders_log
morphbr@718
   381
morphbr@724
   382
                self.server.add_transcoders(self, obj)
morphbr@724
   383
                obj.start(self.wfile)
morphbr@724
   384
                self.server.del_transcoders(self, obj)
morphbr@726
   385
                files.TranscodedFile("", self.query)
morphbr@724
   386
morphbr@724
   387
            elif self.query.get("type", "")[0] == "file" and \
morphbr@724
   388
                     self.query.get("uri", None):
morphbr@745
   389
morphbr@745
   390
                filename = self.query.get("uri", None)[0]
morphbr@745
   391
                self.transcoders_log.insert(test_tid, "gms.%s" % filename)
morphbr@745
   392
morphbr@742
   393
                try:
morphbr@744
   394
                    media = open(filename)
morphbr@744
   395
                    data_in = " "
morphbr@744
   396
                    total_read = 0
morphbr@744
   397
                    size = int(os.path.getsize(filename))
morphbr@744
   398
morphbr@744
   399
                    while data_in != "":
morphbr@744
   400
                        data_in = media.read(4096)
morphbr@744
   401
                        total_read += 4096
morphbr@744
   402
                        self.wfile.write(data_in)
morphbr@744
   403
                        status = utils.progress_bar(total_read, size, 50)
morphbr@744
   404
                        msg_status = "Status:%s:%s%%" % (test_tid, status)
morphbr@744
   405
                        self.transcoders_log._update_status(test_tid,
morphbr@744
   406
                                                            msg_status)
morphbr@744
   407
morphbr@745
   408
                    self.transcoders_log._update_status(test_tid, "OK: Done")
morphbr@745
   409
morphbr@743
   410
                except Exception, e:
morphbr@742
   411
                    self.log.error("Stream error: %s" %e)
morphbr@745
   412
                    self.transcoders_log._update_status(test_tid,
morphbr@745
   413
                                                        "Error: %s" % e)
morphbr@718
   414
    # serve_stream()
morphbr@718
   415
morphbr@718
   416
morphbr@718
   417
    def log_request(self, code='-', size='-'):
morphbr@718
   418
        self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
morphbr@718
   419
    # log_request()
morphbr@718
   420
morphbr@718
   421
morphbr@718
   422
    def log_error(self, format, *args):
morphbr@718
   423
        self.log.error("%s: %s" % (self.address_string(), format % args))
morphbr@718
   424
    # log_error()
morphbr@718
   425
morphbr@718
   426
morphbr@718
   427
    def log_message(self, format, *args):
morphbr@718
   428
        self.log.info("%s: %s" % (self.address_string(), format % args))
morphbr@718
   429
    # log_message()
morphbr@724
   430
morphbr@718
   431
# RequestHandler