Esempio n. 1
0
 def new(*args):
     # new_args = args
     new_args = (args[0], copy.copy(
         args[1])) if len(args) == 2 else (args[0], copy.copy(args[1]),
                                           args[2:])
     if hasattr(args[0], 'baseFilename'):
         return fn(*args)
     levelno = new_args[1].levelno
     if levelno >= 50:
         color = '\x1b[31m'  # CRITICAL red
     elif levelno >= 40:
         color = '\x1b[31m'  # ERROR ligth red
     elif levelno >= 30:
         color = '\x1b[33m'  # WARNING light yellow
     elif levelno >= 20:
         color = '\x1b[32m'  # INFO green
     elif levelno >= 10:
         color = '\x1b[90m'  # DEBUG light gray
     else:
         color = '\x1b[0m'  # normal
     try:
         new_args[1].msg = color + ensure_text(
             args[1].msg) + '\x1b[0m'  # normal
     except Exception as e:
         raise e
     return fn(*new_args)
Esempio n. 2
0
    def handle(self, connection, headers_only=False):
        play = False
        # 30 minutes cache
        if not self.playlist or (gevent.time.time() - self.playlisttime > 30 * 60):
           if not self.Playlistparser(): connection.dieWithError(); return

        url = urlparse(connection.path)
        path = url.path[0:-1] if url.path.endswith('/') else url.path
        params = parse_qs(connection.query)

        if path.startswith('/%s/channel/' % connection.reqtype):
           if not path.endswith('.ts'):
              connection.dieWithError(404, 'Invalid path: %s' % unquote(path), logging.ERROR)
              return
           name = ensure_text(unquote(path[path.rfind('/')+1:]))
           url = self.channels.get('.'.join(name.split('.')[:-1]))
           if url is None:
              connection.dieWithError(404, 'Unknown channel: ' + name, logging.ERROR)
              return
           elif url.startswith('acestream://'):
              connection.path = '/content_id/%s/%s' % (url.split('/')[2], name)
           elif url.startswith('infohash://'):
              connection.path = '/infohash/%s/%s' % (url.split('/')[2], name)
           elif url.startswith(('http://', 'https://')) and url.endswith(('.acelive', '.acestream', '.acemedia', '.torrent')):
              connection.path = '/url/%s/%s' % (quote(url,''), name)
           connection.splittedpath = connection.path.split('/')
           connection.reqtype = connection.splittedpath[1].lower()
           name = name.split('.')[0]
           play = True
        elif self.etag == connection.headers.get('If-None-Match'):
           self.logger.debug('ETag matches - returning 304')
           connection.send_response(304)
           connection.send_header('Connection', 'close')
           connection.end_headers()
           return
        else:
           hostport = connection.headers['Host']
           path = '' if not self.channels else '/%s/channel' % connection.reqtype
           add_ts = True if path.endswith('/ts') else False
           exported = self.playlist.exportm3u(hostport=hostport, path=path, add_ts=add_ts, header=config.m3uheadertemplate, fmt=params.get('fmt', [''])[0])
           response_headers = { 'Content-Type': 'audio/mpegurl; charset=utf-8', 'Connection': 'close', 'Content-Length': len(exported),
                                'Access-Control-Allow-Origin': '*', 'ETag': self.etag }
           try:
              h = connection.headers.get('Accept-Encoding').split(',')[0]
              compress_method = { 'zlib': zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS),
                                  'deflate': zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS),
                                  'gzip': zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) }
              exported = compress_method[h].compress(exported) + compress_method[h].flush()
              response_headers['Content-Length'] = len(exported)
              response_headers['Content-Encoding'] = h
           except: pass

           connection.send_response(200)
           gevent.joinall([gevent.spawn(connection.send_header, k, v) for (k,v) in response_headers.items()])
           connection.end_headers()

        if play: connection.handleRequest(headers_only, name, self.picons.get(name), fmt=params.get('fmt', [''])[0])
        elif not headers_only:
           self.logger.debug('Exporting torrent-telik.m3u playlist')
           connection.wfile.write(exported)
Esempio n. 3
0
    def handle(self, connection):
        # 30 minutes cache
        if not self.playlist or (gevent.time.time() - self.playlisttime > 30 * 60):
           if not self.Playlistparser():
              logging.info('Parser failed to parse')
              connection.send_error()

        connection.ext = query_get(connection.query, 'ext', 'ts')
        if connection.path.startswith('/{reqtype}/channel/'.format(**connection.__dict__)):
           if not connection.path.endswith(connection.ext):
              logging.info('Invalid path')
              connection.send_error(404, 'Invalid path: {path}'.format(**connection.__dict__), logging.ERROR)
           name = ensure_text(unquote(os.path.splitext(os.path.basename(connection.path))[0]))
           url = self.channels.get(name)
           if url is None:
              logging.info('Unknown channel')
              connection.send_error(404, '[%s]: unknown channel: %s' % (self.__class__.__name__, name), logging.ERROR)
           connection.__dict__.update({'channelName': name,
                                       'channelIcon': self.picons.get(name),
                                       'path': {'acestream': '/content_id/%s/%s.%s' % (urlparse(url).netloc, name, connection.ext),
                                                'infohash' : '/infohash/%s/%s.%s' % (urlparse(url).netloc, name, connection.ext),
                                                'http'     : '/url/%s/%s.%s' % (quote(url,''), name, connection.ext),
                                                'https'    : '/url/%s/%s.%s' % (quote(url,''), name, connection.ext),
                                               }[urlparse(url).scheme]})
           connection.__dict__.update({'splittedpath': connection.path.split('/')})
           connection.__dict__.update({'reqtype': connection.splittedpath[1].lower()})
           return

        elif self.etag == connection.headers.get('If-None-Match'):
           logging.debug('[%s]: ETag matches. Return 304 to [%s]' % (self.__class__.__name__, connection.clientip))
           connection.send_response(304)
           connection.send_header('Connection', 'close')
           connection.end_headers()
           return

        else:
           host_port = connection.headers['Host']
           exported = self.playlist.exportm3u( hostport=host_port,
                                               path='' if not self.channels else '/{reqtype}/channel'.format(**connection.__dict__),
                                               header=config.m3uheadertemplate.format(get_epg_url(host_port, config, config.tvgurl), config.tvgshift),
                                               query=connection.query
                                              )
           response_headers = {'Content-Type': 'audio/mpegurl; charset=utf-8', 'Connection': 'close', 'Access-Control-Allow-Origin': '*'}
           try:
              h = connection.headers.get('Accept-Encoding').split(',')[0]
              compress_method = { 'zlib': zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS),
                                  'deflate': zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS),
                                  'gzip': zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) }
              exported = compress_method[h].compress(exported) + compress_method[h].flush()
              response_headers['Content-Encoding'] = h
           except: pass
           response_headers['Content-Length'] = len(exported)
           if connection.request_version == 'HTTP/1.1':
              response_headers['ETag'] = self.etag
           connection.send_response(200)
           gevent.joinall([gevent.spawn(connection.send_header, k, v) for (k,v) in response_headers.items()])
           connection.end_headers()
           connection.wfile.write(exported)
           logging.debug('[%s]: plugin sent playlist to [%s]' % (self.__class__.__name__, connection.clientip))
Esempio n. 4
0
        def _add_client_data(c):
            if not c.clientInfo:
                if self.ip_is_local(c.clientip):
                    c.clientInfo = {
                        'vendor': self.get_vendor_Info(c.clientip),
                        'country_code': '',
                        'country_name': '',
                        'city': ''
                    }
                else:
                    try:
                        headers = {'User-Agent': 'API Browser'}
                        with requests.get('https://geoip-db.com/jsonp/%s' %
                                          c.clientip,
                                          headers=headers,
                                          stream=False,
                                          timeout=5) as r:
                            if r.encoding is None: r.encoding = 'utf-8'
                            c.clientInfo = json.loads(
                                r.text.split('(', 1)[1].strip(')'))
                            c.clientInfo['vendor'] = ''
                    except:
                        c.clientInfo = {
                            'vendor': '',
                            'country_code': '',
                            'country_name': '',
                            'city': ''
                        }

            return {
                'sessionID':
                c.sessionID,
                'channelIcon':
                c.channelIcon,
                'channelName':
                ensure_text(c.channelName),
                'clientIP':
                c.clientip,
                'clientInfo':
                c.clientInfo,
                #'clientBuff': c.q.qsize()*100/self.config.videotimeout,
                'startTime':
                time.strftime('%d/%m/%Y %H:%M:%S',
                              time.localtime(c.connectionTime)),
                'durationTime':
                time.strftime('%H:%M:%S',
                              time.gmtime(time.time() - c.connectionTime)),
                'stat':
                c.ace.GetSTATUS(),
            }
Esempio n. 5
0
 def _changeItemByDict(item, key, replacementsDict, setKey=None):
     if len(replacementsDict) > 0:
        value = replacementsDict.get(item.get(key))
        if not setKey: setKey = key
        if value: item[setKey] = ensure_text(value)