0rx

youtube.py

0rx
Dec 4th, 2013
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. #
  2.  
  3. # Includes
  4.  
  5. #
  6.  
  7. from urllib.request import urlopen
  8.  
  9. import re
  10.  
  11.  
  12.  
  13. #
  14.  
  15. # Exceptions
  16.  
  17. #
  18.  
  19. class YoutubeException(Exception): pass
  20.  
  21.  
  22.  
  23. #
  24.  
  25. # Regex
  26.  
  27. #
  28.  
  29. def tag_regex_construct(tag):
  30.  
  31.     return re.compile(r"<%s ?[^>]*>(.*?)</%s>" %(tag, tag), re.IGNORECASE | re.DOTALL )
  32.  
  33.  
  34.  
  35. title_re = tag_regex_construct("title")
  36.  
  37. desc_re  = tag_regex_construct("content")
  38.  
  39. auth_re  = tag_regex_construct("name")
  40.  
  41.  
  42.  
  43. #
  44.  
  45. # Video class
  46.  
  47. #
  48.  
  49. class Video:
  50.  
  51.     def __init__(self, vid, update = True):
  52.  
  53.         self.vid = vid
  54.  
  55.         if(update): self.update()
  56.  
  57.    
  58.  
  59.     def update(self):
  60.  
  61.         resp = urlopen(self.get_api_link())
  62.  
  63.         if(resp):
  64.  
  65.             data = resp.read().decode()
  66.  
  67.             self.title = title_re.search(data).group(1)
  68.  
  69.             try:
  70.  
  71.                 self.desc = desc_re.search(data).group(1)
  72.  
  73.             except:
  74.  
  75.                 self.desc = "No description avaiable."
  76.  
  77.             self.auth = auth_re.search(data).group(1)
  78.  
  79.         else:
  80.  
  81.             raise YoutubeException("video id seems invalid")
  82.  
  83.  
  84.  
  85.     def get_api_link(self):
  86.  
  87.         return "http://gdata.youtube.com/feeds/api/videos/%s" %(self.vid)
  88.  
  89.        
  90.  
  91.     def get_id(self):
  92.  
  93.         return self.vid
  94.  
  95.        
  96.  
  97.     def get_title(self):
  98.  
  99.         return self.title
  100.  
  101.  
  102.  
  103.     def get_desc(self):
  104.  
  105.         return self.desc
  106.  
  107.  
  108.  
  109.     def get_auth(self):
  110.  
  111.         return self.auth
Add Comment
Please, Sign In to add comment