Exemplo n.º 1
0
def check_compatibility(gevent_version, psutil_version):

    if not 'dev' in gevent_version:
        # Check gevent for compatibility.
        major, minor, patch = map(int, gevent_version.split('.')[:3])
        # gevent >= 1.3.3
        assert (major, minor, patch) >= (1, 3, 3)

    # Check psutil for compatibility.
    major, minor, patch = map(int, psutil_version.split('.')[:3])
    # psutil >= 5.3.0
    assert (major, minor, patch) >= (5, 3, 0) and (major, minor,
                                                   patch) < (6, 0, 0)
Exemplo n.º 2
0
def check_compatibility(gevent_version, psutil_version):

    # Check gevent for compatibility.
    major, minor, patch = map(int, gevent_version.split('.')[:3])
    # gevent >= 1.2.2
    assert major == 1
    assert minor >= 2
    assert minor >= 2

    # Check psutil for compatibility.
    major, minor, patch = map(int, psutil_version.split('.')[:3])
    # psutil >= 5.3.0
    assert major == 5
    assert minor >= 3
    assert patch >= 0
Exemplo n.º 3
0
                                                                 AceProxy)
        except Exception as err:
            logger.error("Can't load plugin %s: %s" % (plugname, repr(err)))
        else:
            logger.debug('[%-15.15s]: Plugin loaded' % plugname)
            return {j: plugininstance for j in plugininstance.handlers}


# Creating dict of handlers
pluginslist = [
    os.path.splitext(os.path.basename(x))[0]
    for x in glob.glob('plugins/*_plugin.py')
]
AceProxy.pluginshandlers = {
    key: val
    for k in map(add_handler, pluginslist) for key, val in k.items()
}
# Server setup
AceProxy.server = StreamServer((AceConfig.httphost, AceConfig.httpport),
                               handle=HTTPHandler,
                               spawn=AceProxy.pool)
# Capture  signal handlers (SIGINT, SIGQUIT etc.)
gevent.signal_handler(signal.SIGTERM, shutdown)
gevent.signal_handler(signal.SIGINT, shutdown)
if AceConfig.osplatform != 'Windows':
    gevent.signal_handler(signal.SIGQUIT, shutdown)
    gevent.signal_handler(signal.SIGHUP, _reloadconfig)
AceProxy.server.start()
logger.info('Server started at {}:{} Use <Ctrl-C> to stop'.format(
    AceConfig.httphost, AceConfig.httpport))
# Start complite. Wating for requests
Exemplo n.º 4
0
 def _recvData(self, timeout=30):
     '''
     Data receiver method for greenlet
     '''
     while 1:
         # Destroy socket connection if AceEngine STATE 0 (IDLE) and we didn't read anything from socket until Nsec
         with gevent.Timeout(timeout, False):
             try:
                 self._recvbuffer = self._socket.read_until('\r\n',
                                                            None).strip()
             except gevent.Timeout:
                 self.destroy()
             except gevent.socket.timeout:
                 pass
             except:
                 raise
             else:
                 logging.debug('<<< %s' % unquote(self._recvbuffer))
                 # Parsing everything only if the string is not empty
                 # HELLOTS
                 if self._recvbuffer.startswith('HELLOTS'):
                     #version=engine_version version_code=version_code key=request_key http_port=http_port
                     self._auth.set({
                         k: v
                         for k, v in (x.split('=')
                                      for x in self._recvbuffer.split()
                                      if '=' in x)
                     })
                 # NOTREADY
                 elif self._recvbuffer.startswith('NOTREADY'):
                     self._auth.set('NOTREADY')
                     # AUTH
                 elif self._recvbuffer.startswith('AUTH'):
                     self._auth.set(
                         self._recvbuffer.split()[1])  # user_auth_level
                     # START
                 elif self._recvbuffer.startswith('START'):
                     # url [ad=1 [interruptable=1]] [stream=1] [pos=position]
                     params = {
                         k: v
                         for k, v in (x.split('=')
                                      for x in self._recvbuffer.split()
                                      if '=' in x)
                     }
                     if not self._seekback or self._started_again.ready(
                     ) or params.get('stream', '') is not '1':
                         # If seekback is disabled, we use link in first START command.
                         # If seekback is enabled, we wait for first START command and
                         # ignore it, then do seekback in first EVENT position command
                         # AceStream sends us STOP and START again with new link.
                         # We use only second link then.
                         self._url.set(
                             self._recvbuffer.split()[1])  # url for play
                 # LOADRESP
                 elif self._recvbuffer.startswith('LOADRESP'):
                     self._loadasync.set(
                         json.loads(
                             unquote(''.join(
                                 self._recvbuffer.split()[2:]))))
                 # STATE
                 elif self._recvbuffer.startswith('STATE'):
                     self._state.set(self._recvbuffer.split()
                                     [1])  # STATE state_id -> STATE_NAME
                 # STATUS
                 elif self._recvbuffer.startswith('STATUS'):
                     self._tempstatus = self._recvbuffer.split()[1]
                     stat = [self._tempstatus.split(';')[0].split(':')[1]
                             ]  # main:????
                     if self._tempstatus.startswith('main:idle'): pass
                     elif self._tempstatus.startswith('main:loading'): pass
                     elif self._tempstatus.startswith('main:starting'): pass
                     elif self._tempstatus.startswith('main:check'): pass
                     elif self._tempstatus.startswith('main:err'):
                         pass  # err;error_id;error_message
                     elif self._tempstatus.startswith('main:dl'):  #dl;
                         stat.extend(
                             map(int,
                                 self._tempstatus.split(';')[1:]))
                     elif self._tempstatus.startswith(
                             'main:wait'):  #wait;time;
                         stat.extend(
                             map(int,
                                 self._tempstatus.split(';')[2:]))
                     elif self._tempstatus.startswith(
                         ('main:prebuf', 'main:buf')):  #buf;progress;time;
                         stat.extend(
                             map(int,
                                 self._tempstatus.split(';')[3:]))
                     try:
                         self._status.set({
                             k: v
                             for k, v in zip(AceConst.STATUS, stat)
                         })  # dl, wait, buf, prebuf
                     except:
                         self._status.set(
                             {'status':
                              stat[0]})  # idle, loading, starting, check
                 # CID
                 elif self._recvbuffer.startswith('##'):
                     self._cid.set(self._recvbuffer)
                     # INFO
                 elif self._recvbuffer.startswith('INFO'):
                     pass
                     # EVENT
                 elif self._recvbuffer.startswith('EVENT'):
                     self._tempevent = self._recvbuffer.split()
                     if self._seekback and not self._started_again.ready(
                     ) and 'livepos' in self._tempevent:
                         params = {
                             k: v
                             for k, v in (x.split('=')
                                          for x in self._tempevent
                                          if '=' in x)
                         }
                         self._write(
                             AceMessage.request.LIVESEEK(
                                 int(params['last']) - self._seekback))
                         self._started_again.set()
                     elif 'getuserdata' in self._tempevent:
                         self._write(
                             AceMessage.request.USERDATA(
                                 self._gender, self._age))
                     elif 'cansave' in self._tempevent:
                         pass
                     elif 'showurl' in self._tempevent:
                         pass
                     elif 'download_stopped' in self._tempevent:
                         pass
                 # PAUSE
                 elif self._recvbuffer.startswith('PAUSE'):
                     pass  #self._write(AceMessage.request.EVENT('pause'))
                     # RESUME
                 elif self._recvbuffer.startswith('RESUME'):
                     pass  #self._write(AceMessage.request.EVENT('play'))
                     # STOP
                 elif self._recvbuffer.startswith('STOP'):
                     pass  #self._write(AceMessage.request.EVENT('stop'))
                     # SHUTDOWN
                 elif self._recvbuffer.startswith('SHUTDOWN'):
                     self._socket.close()
                     break
    def exportm3u(self, **params):
        '''
        Exports m3u playlist
        params: hostport= '', path='', empty_header=False, archive=False, parse_url=True, header=None, query=None
        '''
        def line_generator(item):
            '''
            Generates EXTINF line with url
            '''
            item = item.copy(
            )  # {'group': XXX, 'tvg': XXX, 'logo': XXX, 'name': XXX, 'tvgid': XXX, 'url': XXX}
            params.update({
                'name':
                quote(
                    ensure_str(
                        item.get('name').replace('"', "'").replace(',', '.')),
                    '')
            })
            url = item['url']
            if not params.get('parse_url'):
                if params.get('path').endswith(
                        'channel'):  # For plugins  channel name maping
                    params.update({'value': url})
                    item['url'] = urlunparse(
                        u'{schema};{netloc};{path}/{value}.{ext};;{query};'.
                        format(**params).split(';'))
                elif url.startswith(('http://', 'https://')) and url.endswith(
                    ('.acelive', '.acestream', '.acemedia',
                     '.torrent')):  # For .acelive and .torrent
                    params.update({'value': quote(url, '')})
                    item['url'] = urlunparse(
                        u'{schema};{netloc};/url/{value}/{name}.{ext};;{query};'
                        .format(**params).split(';'))
                elif url.startswith('infohash://'):  # For INFOHASHes
                    params.update({'value': url.split('/')[2]})
                    item['url'] = urlunparse(
                        u'{schema};{netloc};/infohash/{value}/{name}.{ext};;{query};'
                        .format(**params).split(';'))
                elif url.startswith('acestream://'):  # For PIDs
                    params.update({'value': url.split('/')[2]})
                    item['url'] = urlunparse(
                        u'{schema};{netloc};/content_id/{value}/{name}.{ext};;{query};'
                        .format(**params).split(';'))
                elif params.get('archive') and url.isdigit(
                ):  # For archive channel id's
                    item['url'] = urlunparse(
                        u'{schema};{netloc};/archive/play?id={url};;{query};'.
                        format(**params).split(';'))
                elif not params.get('archive') and url.isdigit(
                ):  # For channel id's
                    item['url'] = urlunparse(
                        u'{schema};{netloc};/channels/play?id={url};;{query};'.
                        format(**params).split(';'))

            return self.m3uchanneltemplate.format(**item)

        params.update({
            'schema': 'http',
            'netloc': params.get('hostport'),
            'ext': query_get(params.get('query', ''), 'ext', 'ts')
        })
        return ensure_binary(
            params.get(
                'header', self.m3uemptyheader if params.
                get('empty_header') else self.m3uheader) +
            ''.join(map(line_generator, self.sort(self.itemlist))))
Exemplo n.º 6
0
except: pass
sys.path.insert(0, 'plugins')
logger.info('Load Ace Stream HTTP Proxy plugins .....')

def add_handler(name):
    # isidentifier() Py2/Py3 compatible
    if requests.utils.re.match(r'^\w+$', name, requests.utils.re.UNICODE) and not name[0].isdigit() and name not in sys.modules:
       try:
          plugname = name.split('_')[0].capitalize()
          plugininstance = getattr(__import__(name), plugname)(AceConfig, AceProxy)
       except Exception as err: logger.error("Can't load plugin %s: %s" % (plugname, repr(err)))
       else:
          logger.debug('[%-15.15s]: Plugin loaded' % plugname)
          return {j:plugininstance for j in plugininstance.handlers}

# Creating dict of handlers
pluginslist = [os.path.splitext(os.path.basename(x))[0] for x in glob.glob('plugins/*_plugin.py')]
AceProxy.pluginshandlers = {key:val for k in map(add_handler, pluginslist) for key,val in k.items()}
# Server setup
AceProxy.server = StreamServer((AceConfig.httphost, AceConfig.httpport), handle=HTTPHandler, spawn=AceProxy.pool)
# Capture  signal handlers (SIGINT, SIGQUIT etc.)
gevent.signal_handler(signal.SIGTERM, shutdown)
gevent.signal_handler(signal.SIGINT, shutdown)
if AceConfig.osplatform != 'Windows':
   gevent.signal_handler(signal.SIGQUIT, shutdown)
   gevent.signal_handler(signal.SIGHUP, _reloadconfig)
AceProxy.server.start()
logger.info('Server started at {}:{} Use <Ctrl-C> to stop'.format(AceConfig.httphost, AceConfig.httpport))
# Start complite. Wating for requests
gevent.wait()
Exemplo n.º 7
0
    def getStatusJSON(self):
        # Sys Info
        clients = self.AceProxy.clientcounter.getAllClientsList(
        )  # Get connected clients list
        statusJSON = {}
        statusJSON['status'] = 'success'
        statusJSON['sys_info'] = {
            'os_platform': self.AceConfig.osplatform,
            'cpu_nums': psutil.cpu_count(),
            'cpu_percent': psutil.cpu_percent(interval=0, percpu=True),
            'cpu_freq': {
                k: v
                for k, v in psutil.cpu_freq()._asdict().items()
                if k in ('current', 'min', 'max')
            } if psutil.cpu_freq() else {},
            'mem_info': {
                k: v
                for k, v in psutil.virtual_memory()._asdict().items()
                if k in ('total', 'used', 'available')
            },
            'disk_info': {
                k: v
                for k, v in psutil.disk_usage(getcwdb())._asdict().items()
                if k in ('total', 'used', 'free')
            }
        }

        statusJSON['connection_info'] = {
            'max_clients': self.AceConfig.maxconns,
            'total_clients': len(clients),
        }

        def _add_client_data(c):
            if not c.clientDetail:
                if Stat.ip_is_local(c.clientip):
                    c.clientDetail = {
                        'vendor': Stat.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.clientDetail = json.loads(
                                r.text.split('(', 1)[1].strip(')'))
                            c.clientDetail['vendor'] = ''
                    except:
                        c.clientDetail = {
                            'vendor': '',
                            'country_code': '',
                            'country_name': '',
                            'city': ''
                        }

            return {
                'sessionID':
                c.sessionID,
                'channelIcon':
                c.channelIcon,
                'channelName':
                c.channelName,
                'clientIP':
                c.clientip,
                'clientInfo':
                c.clientDetail,
                #'clientBuff': c.q.qsize()*100/self.AceConfig.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(),
            }

        statusJSON['clients_data'] = list(map(_add_client_data, clients))
        return statusJSON