This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

own3d.py

By: codemonkey on Nov 9th, 2011  |  syntax: Python  |  size: 4.42 KB  |  views: 59  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # =======
  2. # Imports
  3. # =======
  4.  
  5. import sys, os
  6. import urllib2
  7. from own3dSettings import *
  8. import urllib2
  9. from urllib2 import URLError
  10. from xml.dom.minidom import parseString
  11. from django.utils.html import strip_tags
  12.  
  13. # ======
  14. # Django
  15. # ======
  16.  
  17. # Paths
  18. honsapp = os.path.abspath(os.path.dirname(__file__))
  19. honstreams = os.path.abspath(os.path.join(honsapp, '../'))
  20.  
  21. if honstreams not in sys.path:
  22.     sys.path.append(honstreams)
  23.  
  24. # Django settings module
  25. os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
  26.  
  27. # Import models
  28. from honsapp.models import Stream, StreamInfo
  29.  
  30. # ==========
  31. # Exceptions
  32. # ==========
  33.  
  34. # If the channel name was not found
  35. class ChannelNotFoundError(Exception):
  36.     def __init__(self, message=None):
  37.         self.message = message
  38.  
  39. # If the live_id was not found in the channel
  40. class StreamNotFoundError(Exception):
  41.     def __init__(self, message=None):
  42.         self.message = message
  43.  
  44. # =========
  45. # Functions
  46. # =========
  47.  
  48. def getStreamStatus(stream):
  49.     """
  50.    Gets the status of the input stream.
  51.    
  52.    Returns tuple: <status, viewers>
  53.       status    Boolean - True for live, False for offline
  54.       viewers   Integer - The number of viewers currently watching
  55.    """
  56.    
  57.     # Compose URL
  58.     request = API_STATUS % stream.live_id
  59.    
  60.     try:
  61.         # Connect to API
  62.         connection = urllib2.urlopen(request, timeout=10)
  63.        
  64.         # Read the response
  65.         xmlstring = connection.read()
  66.     except URLError as e:
  67.         # Couldn't connect
  68.         raise e
  69.    
  70.     # Parse the XML
  71.     xml = parseString(xmlstring)
  72.    
  73.     # Get the viewer count
  74.     viewers = _getNodeText(xml.getElementsByTagName('liveViewers')[0])
  75.     viewers = int(viewers)
  76.    
  77.     # Get the status
  78.     live = _getNodeText(xml.getElementsByTagName('isLive')[0])
  79.     live = True if live == 'true' else False
  80.  
  81.     # Return status
  82.     return (live, viewers)
  83.  
  84. def getStreamInfo(stream):
  85.     """
  86.    Returns a StreamInfo object with the latest information about the input
  87.    stream
  88.    """
  89.    
  90.     # Compose URL
  91.     request = API_LIVE % stream.name
  92.     tries = 0
  93.    
  94.     # Try three times to make contact
  95.     while True:
  96.         try:
  97.             # Connect to API
  98.             connection = urllib2.urlopen(request, timeout=10)
  99.             xmlstring = connection.read()
  100.         except URLError as e:
  101.             tries += 1
  102.             if tries >= 3:
  103.                 sys.stderr.write(
  104.                           'own3dStreamsUpdater: Fatal error: Repeated timeouts')
  105.                 exit()
  106.    
  107.     # Make a document out of the XML
  108.     xml = parseString(xmlstring)
  109.    
  110.     # Fetch all the items
  111.     items = xml.getElementsByTagName('item')
  112.     correctItem = False
  113.    
  114.     # An item represents a stream, so anything < 1 is unacceptable
  115.     if len(items) < 1:
  116.         raise ChannelNotFoundError()
  117.    
  118.     # In case multiple streams were found, narrow it down with the guid
  119.     for item in items:
  120.         # Dig out the guid from the xml item
  121.         guidNode = item.getElementsByTagName('guid')[0]
  122.         guid = _getNodeText(guidNode).split('/')[-1]
  123.        
  124.         if str(guid) == str(stream.live_id):
  125.             correctItem = item
  126.             break
  127.    
  128.     # Must have found the right item by now
  129.     if not correctItem:
  130.         raise StreamNotFoundError()
  131.    
  132.     # Now assemble the streaminfo
  133.     title = _getNodeText(correctItem.getElementsByTagName('title')[0])
  134.     desc = _getNodeText(correctItem.getElementsByTagName('description')[0])
  135.     desc = strip_tags(desc) # Remove HTML
  136.     about = None
  137.     link = _getNodeText(correctItem.getElementsByTagName('link')[0])
  138.     channelImage = '/static/images/honlogo.png'
  139.     screenCap = _getNodeText(correctItem.getElementsByTagName('thumbnail')[0])
  140.    
  141.     si = StreamInfo()
  142.     si.title = title
  143.     si.description = desc
  144.     si.about = about
  145.     si.stream_url = link
  146.     si.channelImage = channelImage
  147.     si.screenCap = screenCap
  148.    
  149.     # Return the StreamInfo object
  150.     return si
  151.  
  152. def _getNodeText(node):
  153.     "Returns the text content in an XML node"
  154.    
  155.     textNode = node.childNodes[0]
  156.     text = textNode.nodeValue
  157.     return text
  158.  
  159. # =======================
  160. # Debugging / development
  161. # =======================
  162. if __name__ == '__main__':
  163.    
  164.     # Get the own3d stream
  165.     stream = Stream.objects.filter(network__name='own3d')[0]
  166.    
  167.     print getStreamStatus(stream)
  168.  
  169.  
clone this paste RAW Paste Data