mkv

i dont know what you mean by scope so i'll leave that to you

mkv
Sep 3rd, 2012
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.70 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import re
  3. import time
  4. import logging
  5. import html.parser
  6. import urllib.request
  7. import mysql.connector
  8. from urllib.error import HTTPError
  9. from multiprocessing.dummy import Pool
  10. from MultiDict import OrderedMultiDict
  11. from functools import reduce
  12.  
  13. config_mysql = {
  14.     'user'      : 'ed',
  15.     'host'      : '127.0.0.1',
  16.     'database'  : 'ed'
  17. }
  18.  
  19. ch = 1
  20. idd = -1
  21. idm = -1
  22. oldd = ''
  23. oldm = ''
  24. dbg = ' #'
  25. lastpush = 0;
  26.  
  27. def passed(s):
  28.     s = time.time() - s;
  29.     while (s > 1700):
  30.         s -= 3600
  31.     while (s < -1700):
  32.         s += 3600
  33.     return s
  34.  
  35. if __name__ == '__main__':
  36.     mc = mysql.connector.connect(**config_mysql)
  37.     while True:
  38.         while lastpush > 0 and passed(lastpush) < 30:
  39.             time.sleep(0.25)
  40.         lastpush = time.time()
  41.         exec_update(mc)
  42.        
  43. def exec_update(mc):
  44.     doit = False
  45.     st = get_status()
  46.     n = AsyncListeners()
  47.     n.relay_list = [
  48.         ('http://stream1.r-a-d.io:1130/','/radio.ogg'),
  49.         ('http://stream2.r-a-d.io:1130/','/relay.mp3'),
  50.         ('http://stream3.r-a-d.io:1130/','/relay.mp3')
  51.     ]
  52.     relayclients = n.async_get_all_listener_count()
  53.     meta = fixmeta(st['/main.mp3']['Current Song'])
  54.     listeners = st['/main.mp3']['Current Listeners']
  55.     q = (
  56.         "select di, ti,                             "
  57.         "   timestampdiff(second, t2, now()) sec    "
  58.         "from np                                    "
  59.         "where ch = '%s'                            "
  60.         "order by id desc                           "
  61.         "limit 1                                    ")
  62.     with mc.cursor() as cur:
  63.         cur.execute(q, (ch,))
  64.         for (di, ti, sec) in cur:
  65.             idd, idm = di, ti
  66.             doit = sec > 300 or sec < 50
  67.     doit = doit or idd < 0
  68.     if not doit:
  69.         print("stacking_queue")
  70.         return
  71.     if idd >= 0:
  72.         q = (
  73.             "select v from npd                      "
  74.             "where i = '%s' limit 1                 ")
  75.         with mc.cursor() as cur:
  76.             cur.execute(q, (idd,))
  77.             for (v,) in cur:
  78.                 oldd = v
  79.     if idm >= 0:
  80.         q = (
  81.             "select v from npm                      "
  82.             "where i = '%s' limit 1                 ")
  83.         with mc.cursor() as cur:
  84.             cur.execute(q, (idm,))
  85.             for (v,) in cur:
  86.                 oldm = v
  87.     if re.match('^[0-9]*$', listeners):
  88.         q = (
  89.             "insert into npl values                 "
  90.             "   ('', now(), '%s', '%s')             ")
  91.         with mc.cursor() as cur:
  92.             cur.execute(q, (listeners, relayclients))
  93.     else:
  94.         print("assert_listeners_numeric")
  95.         return
  96.     if meta.lower() == oldm.lower():
  97.         q = (
  98.             "update np                              "
  99.             "set t2=now()                           "
  100.             "where ch = '%s'                        "
  101.             "order by id desc                       "
  102.             "limit 1                                ")
  103.         with mc.cursor() as cur:
  104.             cur.execute(q, (ch,))
  105.         print("meta_unchanged/{}:{}".format
  106.             (listeners, relayclients))
  107.         return
  108.     else:
  109.         print("-- ({})".format(oldm))
  110.         print("-- ({})".format(meta))
  111.  
  112.     idm = -1
  113.     q = (
  114.         "select i from npm                          "
  115.         "where v = '%s' limit 1                     ")
  116.     with mc.cursor() as cur:
  117.         cur.execute(q, (meta,))
  118.         for (i) in cur:
  119.             idm = i
  120.     if idm < 0:
  121.         q = (
  122.             "insert into npm values                 "
  123.             "   ('', '%s')                          ")
  124.         with mc.cursor() as cur:
  125.             cur.execute(q, (meta,))
  126.             idm = cur.lastrowid
  127.    
  128.     idd = -1
  129.     q = (
  130.         "select i from npd                          "
  131.         "where v = '%s' limit 1                     ")
  132.     with mc.cursor() as cur:
  133.         cur.execute(q, (dj,))
  134.         for (i) in cur:
  135.             idd = i
  136.     if idd < 0:
  137.         q = (
  138.             "insert into npd values                 "
  139.             "   ('', '%s')                          ")
  140.         with mc.cursor() as cur:
  141.             cur.execute(q, (dj,))
  142.             idd = cur.lastrowid
  143.    
  144.     if idm < 0:
  145.         print("assert_idm_gt_0")
  146.         return
  147.     if idd < 0:
  148.         print("assert_idd_gt_0")
  149.         return
  150.     q = (
  151.         "insert into np values                      "
  152.         "   ('', now(), now(), '%s', '%s', '%s')    ")
  153.     penis = -1
  154.     with mc.cursor() as cur:
  155.         cur.execute(q, (ch, idm, idd))
  156.         penis = cur.lastrowid
  157.     print("np_dj{}_meta{}_{}/{}:{}".format
  158.         (idd, idm, penis, listeners, relayclients))
  159.  
  160.  
  161. def get_listener_count(
  162.       server = 'http://stream0.r-a-d.io:1130',
  163.        mount = "/main.mp3",
  164.      timeout = None
  165.     ):
  166.     try:
  167.         request = urllib.request.Request(server, headers = {'User-Agent' : 'Mozilla'})
  168.         result = urllib.request.urlopen(request, timeout = timeout)
  169.     except:
  170.         logging.debug('HTTP access fault: ' + server_name);
  171.         #raise
  172.     else:
  173.         incoming = result.read().decode('utf8').split('\n')
  174.         parser = StatusParser()
  175.         for line in incoming:
  176.             parser.feed(line)
  177.         parser.close()
  178.         result = parser.result
  179.         if mount in result:
  180.             if 'Current Listeners' in result[mount]:
  181.                 listeners = int(result[mount]['Current Listeners'])
  182.                 return listeners
  183.         else:
  184.             logging.debug('Server does not have listener count: ' + server_name)
  185.             return -1
  186.     logging.debug('Failed to fetch  ' + server_name)
  187.     return -1
  188.  
  189.  
  190. class AsyncListeners(object):
  191.     relay_list = []
  192.     timeout = 10.0
  193.     def __init__(self, threads = 5):
  194.         super(AsyncListeners, self).__init__()
  195.         self.pool = Pool(threads)
  196.     def async_get_all_listener_count(self, timeout = 10.0):
  197.         result_list = []
  198.         counts, timer = 0, 0.0
  199.         for relay, mount in self.relay_list:
  200.             result_list.append(self.pool.apply_async(
  201.                 get_listener_count,
  202.                 kwds = {
  203.                     'server'  : relay,
  204.                     'timeout' : timeout,
  205.                     'mount'   : mount
  206.                 }))
  207.             #print(result_list)
  208.         while True:
  209.             if len(result_list) == 0:
  210.                 break
  211.             for result in result_list[:]:
  212.                 if result.ready():
  213.                     if result.successful():
  214.                         counts += result.get()
  215.                         result_list.remove(result)
  216.                         #print("LOL " + result)
  217.                     else:
  218.                         print("oh shit")
  219.                 #else:
  220.                     # nothing yet
  221.                     #print(result)
  222.             timer += 0.5
  223.             if timer > self.timeout:
  224.                 break
  225.             time.sleep(0.5)
  226.         return counts
  227.  
  228.  
  229. def get_status(icecast_server = 'http://stream0.r-a-d.io:1130/'):
  230.     try:
  231.         request = urllib.request.Request(icecast_server,
  232.             headers = { 'User-Agent' : 'Mozilla' })
  233.         result = urllib.request.urlopen(request)
  234.     except HTTPError as e:
  235.         if e.code == 403: #full server
  236.             logging.warning("Listener limit reached? " + icecast_server)
  237.             f = OrderedMultiDict()
  238.             f['Stream Title'] = 'r/a/dio'
  239.             f['Current Listeners'] = '500'
  240.             f['Current Song'] = 'py'
  241.             return { '/main.mp3' : f }
  242.         else:
  243.             logging.exception("HTTPError " + e.code + " in status fetch")
  244.     except:
  245.         logging.exception("Connection to status page failed")
  246.     else:
  247.         incoming = result.read().decode('utf8').split('\n')
  248.         parser = StatusParser()
  249.         for line in incoming:
  250.             parser.feed(line)
  251.         parser.close()
  252.         result = parser.result
  253. #       if '/main.mp3' in result:
  254. #           all_listeners = get_all_listener_count()
  255. #           total_count = reduce(lambda x,y:
  256. #               x+y if x > 0 and y > 0 else x,
  257. #               list(all_listeners.values()))
  258. #           result[config.icecast_mount]['Current Listeners'] = str(total_count)
  259.         return parser.result or {}
  260.     return {}
  261.  
  262.  
  263. class StatusParser(html.parser.HTMLParser):
  264.     def __init__(self):
  265.         html.parser.HTMLParser.__init__(self)
  266.         self._current_mount = None
  267.         self.result = {}
  268.         self._td = False
  269.         self._mount = False
  270.         self._enter = False
  271.     def handle_starttag(self, tag, attrs):
  272.         attrs = OrderedMultiDict(attrs)
  273.         if (tag == "td"):
  274.             self._td = Tag(attrs)
  275.             self._td['class'] = None
  276.         elif (tag == "h3") and (self._td):
  277.             self._mount = Tag(attrs)
  278.     def handle_endtag(self, tag):
  279.         if (tag == "td"):
  280.             self._td = None
  281.         elif (tag == "h3") and (self._td):
  282.             self._mount = None
  283.         elif (tag == "table") and (self._current_mount):
  284.             if (self._enter):
  285.                 self._enter = False
  286.             else:
  287.                 self._enter = True
  288.     def handle_data(self, data):
  289.         if (self._mount) and (self._td):
  290.             self._current_mount = data.split(" ")[2]
  291.             self.result[self._current_mount] = OrderedMultiDict()
  292.         elif (self._enter) and (self._td) and (self._current_mount):
  293.             if ("streamdata" in self._td.getall("class")):
  294.                 self.result[self._current_mount][self._type] = data
  295.             else:
  296.                 self._type = data[:-1]
  297.  
  298.  
  299. class Tag(object):
  300.     attr = OrderedMultiDict()
  301.     def __init__(self, attrs):
  302.         self.attr = attrs
  303.     def __getattr__(self, name):
  304.         return getattr(self.attr, name)
  305.     def __setitem__(self, name, value):
  306.         self.attr[name] = value
  307.  
  308. def fixmeta(meta):
  309.     meta = meta.encode('iso_8859-1')
  310.     try:
  311.         try:
  312.             meta = meta.decode('utf-8', 'strict')
  313.         except (UnicodeDecodeError):
  314.             meta = meta.decode('sjis', 'xmlcharrefreplace')
  315.     except (TypeError):
  316.         meta = meta.strip()
  317.     return meta
  318.  
  319. # http://dev.mysql.com/doc/connector-python/en/myconnpy_example_connecting.html
Advertisement
Add Comment
Please, Sign In to add comment