gmyth-stream/server/0.3/lib/request_handler.py
author leo_sobral
Tue Aug 07 16:00:18 2007 +0100 (2007-08-07)
branchtrunk
changeset 796 2c1686735af6
parent 775 7cd98c74da22
child 800 2b1824e138b1
permissions -rw-r--r--
[svn r802] - Fixed typos
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))
melunko@795
   240
                        return True
melunko@795
   241
                stat = self.transcoders_log.get_status(int(req_tid[0]))
melunko@795
   242
                self.wfile.write("%s<br>" % stat)
morphbr@724
   243
                return True
morphbr@718
   244
morphbr@718
   245
            else:
morphbr@718
   246
                running = "<p>Running transcoders:</p>\n"
morphbr@718
   247
                stopall = utils._create_html_item("<a href='%s?request=all'>"
morphbr@718
   248
                                                 "[STOP ALL]</a>" %
morphbr@718
   249
                                                 self.menu["Stop"])
morphbr@718
   250
morphbr@718
   251
                for transcoder, request in tl:
morphbr@718
   252
                    stopone += utils._create_html_item("%s;"
morphbr@718
   253
                                                       "<a href='%s?tid=%s'>"
morphbr@718
   254
                                                       " [STOP] </a>") % (
morphbr@718
   255
                        transcoder, self.menu["Stop"], transcoder.tid)
morphbr@718
   256
morphbr@718
   257
            self.wfile.write(utils.getHTML("status",
morphbr@718
   258
                                           {"menu": self._nav_items(),
morphbr@718
   259
                                            "running": running,
morphbr@718
   260
                                            "stopall": stopall,
morphbr@718
   261
                                            "stopone": stopone}))
morphbr@718
   262
    # serve_status()
morphbr@718
   263
morphbr@718
   264
morphbr@718
   265
    def _get_transcoder(self):
morphbr@718
   266
        # get transcoder option: mencoder is the default
morphbr@718
   267
        request_transcoders = self.query.get("transcoder", ["mencoder"])
morphbr@718
   268
morphbr@718
   269
        for t in request_transcoders:
morphbr@718
   270
            transcoder = self.transcoders.get(t)
morphbr@718
   271
            if transcoder:
morphbr@718
   272
                return transcoder
morphbr@718
   273
morphbr@718
   274
        if not transcoder:
morphbr@718
   275
            return self.transcoders[self.def_transcoder]
morphbr@718
   276
    # _get_transcoder()
morphbr@718
   277
morphbr@718
   278
morphbr@718
   279
    def _get_new_id(self, tid):
morphbr@718
   280
        self.server.last_tid = utils.create_tid(tid)
morphbr@718
   281
        self.tid_queue.append(self.server.last_tid)
morphbr@718
   282
        return self.server.last_tid
morphbr@718
   283
    # _get_new_id()
morphbr@718
   284
morphbr@718
   285
morphbr@718
   286
    def serve_new_id(self, body):
morphbr@718
   287
        self.send_response(200)
morphbr@718
   288
        self.send_header("Content-Type", "text/html")
morphbr@718
   289
        self.send_header('Connection', 'close')
morphbr@718
   290
        self.end_headers()
morphbr@718
   291
morphbr@718
   292
        if body:
morphbr@718
   293
            self.wfile.write("%s" % self._get_new_id(self.server.last_tid))
morphbr@718
   294
    # serve_new_id()
morphbr@718
   295
morphbr@718
   296
    def serve_get_log(self, body):
morphbr@718
   297
        self.send_response(200)
morphbr@718
   298
        self.send_header("Content-Type", "text/html")
morphbr@718
   299
        self.send_header('Connection', 'close')
morphbr@718
   300
        self.end_headers()
morphbr@718
   301
morphbr@718
   302
        if body:
morphbr@718
   303
            if self.query.get("tid", None):
morphbr@718
   304
                tid = int(self.query.get("tid")[0])
morphbr@718
   305
                stat = self.transcoders_log.get_status(tid)
morphbr@723
   306
                self.wfile.write("Status: %s" % stat)
morphbr@718
   307
            else:
morphbr@718
   308
                stat = self.transcoders_log.get_status()
morphbr@718
   309
                for rtid, status in stat.iteritems():
morphbr@718
   310
                    self.wfile.write("<b>%s</b>: %s<br><br>" % (rtid, status))
morphbr@718
   311
    # serve_get_log()
morphbr@718
   312
morphbr@718
   313
    def serve_get_all_log(self, body):
morphbr@718
   314
        self.send_response(200)
morphbr@718
   315
        self.send_header("Content-Type", "text/html")
morphbr@718
   316
        self.send_header('Connection', 'close')
morphbr@718
   317
        self.end_headers()
morphbr@718
   318
morphbr@718
   319
        if body:
morphbr@718
   320
            if self.query.get("tid", None):
morphbr@718
   321
                tid = int(self.query.get("tid")[0])
morphbr@718
   322
                stat = self.transcoders_log.get_status(tid, True)
morphbr@718
   323
                for status in stat:
morphbr@718
   324
                    self.wfile.write("%s<br><br>" % status)
morphbr@718
   325
            else:
morphbr@718
   326
                stat = self.transcoders_log.get_status(None, True)
morphbr@718
   327
                for rtid, history in stat.iteritems():
morphbr@718
   328
                    for status in history:
morphbr@718
   329
                        self.wfile.write("<b>%s</b>: %s<br>" % (rtid, status))
morphbr@718
   330
                    self.wfile.write("<br><br>")
morphbr@718
   331
    # serve_get_all_log()
morphbr@718
   332
morphbr@773
   333
morphbr@773
   334
    def serve_file_info(self, body):
morphbr@773
   335
        if body:
morphbr@773
   336
morphbr@773
   337
            file_dat = self.query.get("file", None)
morphbr@773
   338
morphbr@773
   339
            if file_dat:
morphbr@773
   340
                self.send_response(200)
morphbr@773
   341
                self.send_header("Content-Type", "text/html")
morphbr@773
   342
                self.send_header('Connection', 'close')
morphbr@773
   343
                self.end_headers()
morphbr@773
   344
morphbr@773
   345
                try:
morphbr@775
   346
                    opts = files.TranscodedFile(file_dat[0], self.query).opts
morphbr@773
   347
                    for key in opts.keys():
morphbr@775
   348
                        self.wfile.write("%s=%s<br>" % (key, opts.get(key, "None")[0]))
morphbr@775
   349
morphbr@774
   350
                except Exception, e:
morphbr@773
   351
                    self.send_error(500, str(e))
morphbr@773
   352
                    return
morphbr@773
   353
    # serve_file_info()
morphbr@773
   354
morphbr@718
   355
    def serve_stream(self, body):
morphbr@718
   356
        transcoder = self._get_transcoder()
morphbr@718
   357
        try:
morphbr@718
   358
            obj = transcoder(self.query)
morphbr@718
   359
        except Exception, e:
morphbr@718
   360
            self.send_error(500, str(e))
morphbr@718
   361
            return
morphbr@718
   362
morphbr@718
   363
        self.send_response(200)
morphbr@718
   364
        self.send_header("Content-Type", obj.get_mimetype())
renatofilho@768
   365
	self.send_header("Cache-Control","no-cache")
morphbr@765
   366
morphbr@765
   367
        if (obj.name == "gmencoder"):
morphbr@765
   368
            self.send_header("Transfer-Encoding", "chunked")
morphbr@765
   369
morphbr@743
   370
        self.send_header("Connection", "close")
morphbr@718
   371
        self.end_headers()
morphbr@718
   372
morphbr@718
   373
        if body:
morphbr@742
   374
morphbr@744
   375
            test_tid = int(self.query.get("tid", "0")[0])
morphbr@744
   376
            if test_tid == 0 or test_tid not in self.tid_queue:
morphbr@744
   377
                test_tid = self._get_new_id(self.server.last_tid)
morphbr@744
   378
morphbr@748
   379
morphbr@724
   380
            if self.query.get("transcoder", None):
morphbr@724
   381
                self.transcoders_log.insert(test_tid, "gms.%s" % obj.name)
morphbr@724
   382
                obj.tid = test_tid
morphbr@724
   383
                obj.log = self.transcoders_log
morphbr@718
   384
morphbr@724
   385
                self.server.add_transcoders(self, obj)
morphbr@724
   386
                obj.start(self.wfile)
morphbr@724
   387
                self.server.del_transcoders(self, obj)
morphbr@726
   388
                files.TranscodedFile("", self.query)
morphbr@724
   389
morphbr@724
   390
            elif self.query.get("type", "")[0] == "file" and \
morphbr@724
   391
                     self.query.get("uri", None):
morphbr@745
   392
morphbr@745
   393
                filename = self.query.get("uri", None)[0]
morphbr@745
   394
                self.transcoders_log.insert(test_tid, "gms.%s" % filename)
morphbr@745
   395
morphbr@742
   396
                try:
morphbr@744
   397
                    media = open(filename)
morphbr@744
   398
                    data_in = " "
morphbr@744
   399
                    total_read = 0
morphbr@744
   400
                    size = int(os.path.getsize(filename))
morphbr@744
   401
morphbr@744
   402
                    while data_in != "":
morphbr@744
   403
                        data_in = media.read(4096)
morphbr@744
   404
                        total_read += 4096
morphbr@744
   405
                        self.wfile.write(data_in)
morphbr@744
   406
                        status = utils.progress_bar(total_read, size, 50)
morphbr@744
   407
                        msg_status = "Status:%s:%s%%" % (test_tid, status)
morphbr@744
   408
                        self.transcoders_log._update_status(test_tid,
morphbr@744
   409
                                                            msg_status)
morphbr@744
   410
morphbr@745
   411
                    self.transcoders_log._update_status(test_tid, "OK: Done")
morphbr@745
   412
morphbr@743
   413
                except Exception, e:
morphbr@742
   414
                    self.log.error("Stream error: %s" %e)
morphbr@745
   415
                    self.transcoders_log._update_status(test_tid,
morphbr@745
   416
                                                        "Error: %s" % e)
morphbr@718
   417
    # serve_stream()
morphbr@718
   418
morphbr@718
   419
morphbr@718
   420
    def log_request(self, code='-', size='-'):
morphbr@718
   421
        self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
morphbr@718
   422
    # log_request()
morphbr@718
   423
morphbr@718
   424
morphbr@718
   425
    def log_error(self, format, *args):
morphbr@718
   426
        self.log.error("%s: %s" % (self.address_string(), format % args))
morphbr@718
   427
    # log_error()
morphbr@718
   428
morphbr@718
   429
morphbr@718
   430
    def log_message(self, format, *args):
morphbr@718
   431
        self.log.info("%s: %s" % (self.address_string(), format % args))
morphbr@718
   432
    # log_message()
morphbr@724
   433
morphbr@718
   434
# RequestHandler