Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: Python  |  size: 5.19 KB  |  hits: 12  |  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. from app import latinToAscii
  2. from app.config.cplog import CPLog
  3. from string import ascii_letters, digits
  4. from urllib2 import URLError
  5. import cherrypy
  6. import math
  7. import os
  8. import platform
  9. import re
  10. import time
  11. import unicodedata
  12. import urllib2
  13. import xml.etree.ElementTree as XMLTree
  14.  
  15. log = CPLog(__name__)
  16.  
  17. class rss:
  18.  
  19.     timeout = 10
  20.  
  21.     lastUse = 0
  22.     timeBetween = 1
  23.  
  24.     available = True
  25.     availableCheck = 0
  26.  
  27.     def toSaveString(self, string):
  28.         string = latinToAscii(string)
  29.         string = ''.join((c for c in unicodedata.normalize('NFD', unicode(string)) if unicodedata.category(c) != 'Mn'))
  30.         safe_chars = ascii_letters + digits + '_ -.,\':!?'
  31.         r = ''.join([char if char in safe_chars else ' ' for char in string])
  32.         return re.sub('\s+' , ' ', r)
  33.  
  34.     def toSearchString(self, string):
  35.         string = latinToAscii(string)
  36.         string = ''.join((c for c in unicodedata.normalize('NFD', unicode(string)) if unicodedata.category(c) != 'Mn'))
  37.         safe_chars = ascii_letters + digits + ' \''
  38.         r = ''.join([char if char in safe_chars else ' ' for char in string])
  39.         return re.sub('\s+' , ' ', r).replace('\'s', 's').replace('\'', ' ')
  40.  
  41.     def simplifyString(self, original):
  42.         split = re.split('\W+', original.lower())
  43.         return ' '.join(split)
  44.  
  45.     def gettextelements(self, xml, path):
  46.         ''' Find elements and return tree'''
  47.  
  48.         textelements = []
  49.         try:
  50.             elements = xml.findall(path)
  51.         except:
  52.             return
  53.         for element in elements:
  54.             textelements.append(element.text)
  55.         return textelements
  56.  
  57.     def gettextelement(self, xml, path):
  58.         ''' Find element and return text'''
  59.  
  60.         try:
  61.             return xml.find(path).text
  62.         except:
  63.             return
  64.  
  65.     def getItems(self, data, path = 'channel/item'):
  66.         try:
  67.             return XMLTree.parse(data).findall(path)
  68.         except Exception, e:
  69.             log.error('Error parsing RSS. %s' % e)
  70.             return []
  71.  
  72.     def wait(self):
  73.         now = time.time()
  74.         wait = math.ceil(self.lastUse - now + self.timeBetween)
  75.         if wait > 0:
  76.             log.debug('Waiting for %s, %d seconds' % (self.name, wait))
  77.             time.sleep(wait)
  78.  
  79.     def isAvailable(self, testUrl):
  80.  
  81.         if cherrypy.config.get('debug'): return True
  82.  
  83.         now = time.time()
  84.  
  85.         if self.availableCheck < now - 900:
  86.             self.availableCheck = now
  87.             try:
  88.                 self.urlopen(testUrl, 30)
  89.                 self.available = True
  90.             except (IOError, URLError):
  91.                 log.error('%s unavailable, trying again in an 15 minutes.' % self.name)
  92.                 self.available = False
  93.  
  94.         return self.available
  95.  
  96.  
  97.     def urlopen(self, url, timeout = 10, username = '', password = ''):
  98.  
  99.         self.wait()
  100.  
  101.         try:
  102.            
  103.             # Add CP version to request                                                                                
  104.             if os.name == 'nt': platf = 'windows'                                                                      
  105.             elif 'Darwin' in platform.platform(): platf = 'osx'                                                        
  106.             else: platf = 'linux'                                                                                      
  107.                                                                                                                        
  108.             req = urllib2.Request(url)                                                                                
  109.             req.add_header('User-Agent', 'CouchPotato v1')                                                                
  110.             req.add_header('X-CP-Version', 'CouchPotato (%s - %s)' % (platf, cherrypy.config.get('updater').getVersion().rstrip()))
  111.  
  112.             if username is not '' and password is not '':
  113.                 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
  114.                 passman.add_password(None, url, username, password)
  115.                 authhandler = urllib2.HTTPBasicAuthHandler(passman)
  116.                 opener = urllib2.build_opener(authhandler)
  117.                 urllib2.install_opener(opener)
  118.                 log.debug('Opening "%s" with password' % url)
  119.             else:
  120.                 log.debug('Opening "%s"' % url)
  121.                
  122.             data = urllib2.urlopen(req, timeout = self.timeout)
  123.  
  124.         except IOError, e:
  125.             log.error('Something went wrong in urlopen: %s' % e)
  126.             data = ''
  127.  
  128.         self.lastUse = time.time()
  129.  
  130.         return data
  131.  
  132.     def correctName(self, checkName, movieName):
  133.  
  134.         checkWords = re.split('\W+', self.toSearchString(checkName).lower())
  135.         movieWords = re.split('\W+', self.toSearchString(movieName).lower())
  136.  
  137.         found = 0
  138.         for word in movieWords:
  139.             if word in checkWords:
  140.                 found += 1
  141.  
  142.         return found == len(movieWords)
  143.  
  144.     class feedItem(dict):
  145.         ''' NZB item '''
  146.  
  147.         def __getattr__(self, attr):
  148.             return self.get(attr, None)
  149.  
  150.         __setattr__ = dict.__setitem__
  151.         __delattr__ = dict.__delitem__