예제 #1
0
파일: indy_server.py 프로젝트: EQ4/DRR
def stream_download(callsign, url, my_pid, file_name):
    # Curl interfacing which downloads the stream to disk.
    # Follows redirects and parses out basic m3u.
    pid = misc.change_proc_name("%s-download" % callsign)

    nl = {'stream': None, 'curl_handle': None}

    def dl_stop(signal, frame):
        sys.exit(0)

    def cback(data):

        if not misc.params['shutdown_time']:
            if not misc.download_ipc.empty():
                what, value = misc.download_ipc.get(False)
                if what == 'shutdown_time':
                    misc.params['shutdown_time'] = value

        elif TS.unixtime('dl') > misc.params['shutdown_time']:
            sys.exit(0)

        if misc.params['isFirst'] == True:
            misc.params['isFirst'] = False

            if len(data) < 800:
                if re.match('https?://', data):
                    # If we are getting a redirect then we don't mind, we
                    # just put it in the stream and then we leave
                    misc.queue.put(('stream', data.strip()))
                    return True

                # A pls style playlist
                elif re.findall('File\d', data, re.M):
                    logging.info('Found a pls, using the File1 parameter')
                    matches = re.findall('File1=(.*)\n', data, re.M)
                    misc.queue.put(('stream', matches[0].strip()))
                    return True

        # This provides a reliable way to determine bitrate.  We look at how much
        # data we've received between two time periods
        misc.queue.put(('heartbeat', (TS.unixtime('hb'), len(data))))

        if not nl['stream']:
            try:
                nl['stream'] = open(file_name, 'w')

            except Exception as exc:
                logging.critical(
                    "Unable to open %s. Can't record. Must exit." % file_name)
                sys.exit(-1)

        nl['stream'].write(data)

        if not misc.manager_is_running():
            misc.shutdown()

    # signal.signal(signal.SIGTERM, dl_stop)
    misc.params['isFirst'] = True
    curl_handle = pycurl.Curl()
    curl_handle.setopt(curl_handle.URL, url)
    curl_handle.setopt(pycurl.WRITEFUNCTION, cback)
    curl_handle.setopt(pycurl.FOLLOWLOCATION, True)
    nl['curl_handle'] = curl_handle

    try:
        curl_handle.perform()

    except TypeError as exc:
        logging.info('Properly shutting down.')

    except Exception as exc:
        logging.warning("Couldn't resolve or connect to %s." % url)

    curl_handle.close()

    if nl['stream'] and type(nl['stream']) != bool:
        nl['stream'].close()
        # This is where we are sure of the stats on this file, because
        # we just closed it ... so we can register it here.
        info = audio.stream_info(file_name)

        DB.register_stream(info)
예제 #2
0
파일: indy_server.py 프로젝트: EQ4/DRR
def stream_download(callsign, url, my_pid, file_name):
  # Curl interfacing which downloads the stream to disk. 
  # Follows redirects and parses out basic m3u.
  pid = misc.change_proc_name("%s-download" % callsign)

  nl = {'stream': None, 'curl_handle': None}

  def dl_stop(signal, frame):
    sys.exit(0)

  def cback(data): 

    if not misc.params['shutdown_time']:
      if not misc.download_ipc.empty():
        what, value = misc.download_ipc.get(False)
        if what == 'shutdown_time':
          misc.params['shutdown_time'] = value

    elif TS.unixtime('dl') > misc.params['shutdown_time']:
      sys.exit(0)

    if misc.params['isFirst'] == True:
      misc.params['isFirst'] = False

      if len(data) < 800:
        if re.match('https?://', data):
          # If we are getting a redirect then we don't mind, we
          # just put it in the stream and then we leave
          misc.queue.put(('stream', data.strip()))
          return True

        # A pls style playlist
        elif re.findall('File\d', data, re.M):
          logging.info('Found a pls, using the File1 parameter')
          matches = re.findall('File1=(.*)\n', data, re.M)
          misc.queue.put(('stream', matches[0].strip()))
          return True

    # This provides a reliable way to determine bitrate.  We look at how much 
    # data we've received between two time periods
    misc.queue.put(('heartbeat', (TS.unixtime('hb'), len(data))))

    if not nl['stream']:
      try:
        nl['stream'] = open(file_name, 'w')

      except Exception as exc:
        logging.critical("Unable to open %s. Can't record. Must exit." % file_name)
        sys.exit(-1)

    nl['stream'].write(data)

    if not misc.manager_is_running():
      misc.shutdown()

  # signal.signal(signal.SIGTERM, dl_stop)
  misc.params['isFirst'] = True
  curl_handle = pycurl.Curl()
  curl_handle.setopt(curl_handle.URL, url)
  curl_handle.setopt(pycurl.WRITEFUNCTION, cback)
  curl_handle.setopt(pycurl.FOLLOWLOCATION, True)
  nl['curl_handle'] = curl_handle

  try:
    curl_handle.perform()

  except TypeError as exc:
    logging.info('Properly shutting down.')

  except Exception as exc:
    logging.warning("Couldn't resolve or connect to %s." % url)

  curl_handle.close()

  if nl['stream'] and type(nl['stream']) != bool:
    nl['stream'].close()
    # This is where we are sure of the stats on this file, because
    # we just closed it ... so we can register it here.
    info = audio.stream_info(file_name)

    DB.register_stream(info)
예제 #3
0
파일: indy_server.py 프로젝트: EQ4/DRR
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "-c",
            "--config",
            default="./indy_config.txt",
            help="Configuration file (default ./indy_config.txt)")
        parser.add_argument('--version',
                            action='version',
                            version='indycast %s :: Aug 2015' %
                            misc.__version__)
        parser.add_argument("--daemon",
                            action='store_true',
                            help="run as daemon")
        args = parser.parse_args()
        if args.daemon:
            Popen(filter(lambda x: x != '--daemon', sys.argv))
            sys.exit(0)

        read_config(args.config)
        del (read_config)

        pid = misc.change_proc_name("%s-manager" % misc.config['callsign'])

        # This is the pid that should be killed to shut the system
        # down.
        misc.manager_is_running(pid)
        with open(misc.PIDFILE_MANAGER, 'w+') as f:
            f.write(str(pid))

        stream_manager()
예제 #4
0
파일: indy_server.py 프로젝트: EQ4/DRR
  if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
    server_manager(misc.config)

  else: 
    # Ignore all test scaffolding
    misc.IS_TEST = False
    misc.start_time = TS.unixtime()

    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--config", default="./indy_config.txt", help="Configuration file (default ./indy_config.txt)")
    parser.add_argument('--version', action='version', version='indycast %s :: Aug 2015' % misc.__version__)
    parser.add_argument("--daemon", action='store_true',  help="run as daemon")
    args = parser.parse_args()
    if args.daemon:
      Popen( filter(lambda x: x != '--daemon', sys.argv) )
      sys.exit(0)

    read_config(args.config)      
    del(read_config)

    pid = misc.change_proc_name("%s-manager" % misc.config['callsign'])

    # This is the pid that should be killed to shut the system
    # down.
    misc.manager_is_running(pid)
    with open(misc.PIDFILE_MANAGER, 'w+') as f:
      f.write(str(pid))

    stream_manager()