Advertisement
Guest User

Untitled

a guest
Feb 10th, 2012
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.97 KB | None | 0 0
  1. #import modules
  2. import socket
  3. import xbmc
  4. import xbmcgui
  5. import xbmcaddon
  6. import unicodedata
  7. import urllib2
  8. import sys
  9.  
  10. # Use json instead of simplejson when python v2.7 or greater
  11. if sys.version_info < (2, 7):
  12. import json as simplejson
  13. else:
  14. import simplejson
  15.  
  16. ### get addon info
  17. __addon__ = ( sys.modules[ "__main__" ].__addon__ )
  18. __addonname__ = ( sys.modules[ "__main__" ].__addonname__ )
  19. __icon__ = ( sys.modules[ "__main__" ].__icon__ )
  20. __localize__ = ( sys.modules[ "__main__" ].__localize__ )
  21.  
  22. ### import libraries
  23. from urllib2 import HTTPError, URLError, urlopen
  24. from resources.lib.script_exceptions import *
  25.  
  26. # Commoncache plugin import
  27. try:
  28. import StorageServer
  29. except:
  30. import storageserverdummy as StorageServer
  31.  
  32. cache = StorageServer.StorageServer("ArtworkDownloader",24)
  33.  
  34. ### adjust default timeout to stop script hanging
  35. timeout = 20
  36. socket.setdefaulttimeout(timeout)
  37. ### Declare dialog
  38. dialog = xbmcgui.DialogProgress()
  39.  
  40.  
  41. # Fixes unicode problems
  42. def _unicode( text, encoding='utf-8' ):
  43. try:
  44. text = unicode( text, encoding )
  45. except:
  46. pass
  47. return text
  48.  
  49. def _normalize_string( text ):
  50. try:
  51. text = unicodedata.normalize( 'NFKD', _unicode( text ) ).encode( 'ascii', 'ignore' )
  52. except:
  53. pass
  54. return text
  55.  
  56. # Define log messages
  57. def _log(txt, severity=xbmc.LOGDEBUG):
  58. try:
  59. message = ('%s: %s' % (__addonname__,txt) )
  60. xbmc.log(msg=message, level=severity)
  61. except UnicodeEncodeError:
  62. try:
  63. message = _normalize_string('%s: %s' % (__addonname__,txt) )
  64. xbmc.log(msg=message, level=severity)
  65. except:
  66. message = ('%s: UnicodeEncodeError' %__addonname__)
  67. xbmc.log(msg=message, level=xbmc.LOGWARNING)
  68.  
  69. # Define dialogs
  70. def _dialog(action, percentage = 0, line0 = '', line1 = '', line2 = '', line3 = '', background = False, nolabel = __localize__(32026), yeslabel = __localize__(32025) ):
  71. # Fix possible unicode errors
  72. line0 = line0.encode( 'utf-8', 'ignore' )
  73. line1 = line1.encode( 'utf-8', 'ignore' )
  74. line2 = line2.encode( 'utf-8', 'ignore' )
  75. line3 = line3.encode( 'utf-8', 'ignore' )
  76.  
  77. # Dialog logic
  78. if not line0 == '':
  79. line0 = __addonname__ + line0
  80. else:
  81. line0 = __addonname__
  82. if not background:
  83. if action == 'create':
  84. dialog.create( __addonname__, line1, line2, line3 )
  85. if action == 'update':
  86. dialog.update( percentage, line1, line2, line3 )
  87. if action == 'close':
  88. dialog.close()
  89. if action == 'iscanceled':
  90. if dialog.iscanceled():
  91. return True
  92. else:
  93. return False
  94. if action == 'okdialog':
  95. xbmcgui.Dialog().ok(line0, line1, line2, line3)
  96. if action == 'yesno':
  97. return xbmcgui.Dialog().yesno(line0, line1, line2, line3, nolabel, yeslabel)
  98. if background:
  99. if (action == 'create' or action == 'okdialog'):
  100. if line2 == '':
  101. msg = line1
  102. else:
  103. msg = line1 + ': ' + line2
  104. xbmc.executebuiltin("XBMC.Notification(%s, %s, 7500, %s)" % (line0, msg, __icon__))
  105.  
  106. # order preserving and get unique entry
  107. def _getUniq(seq):
  108. seen = []
  109. result = []
  110. for item in seq:
  111. if item in seen: continue
  112. seen.append( item )
  113. result.append( item )
  114. return result
  115.  
  116. # Retrieve JSON data from cache function
  117. def _get_json(url):
  118. _log('API: %s'% url)
  119. result = cache.cacheFunction( _get_json_new, url )
  120. if len(result) == 0:
  121. result = []
  122. return result
  123. else:
  124. return result
  125.  
  126. # Retrieve JSON data from site
  127. def _get_json_new(url):
  128. _log('Cache expired. Retrieving new data')
  129. try:
  130. request = urllib2.Request(url)
  131. request.add_header("Accept", "application/json")
  132. req = urllib2.urlopen(request)
  133. json_string = req.read()
  134. req.close()
  135. except HTTPError, e:
  136. if e.code == 404:
  137. raise HTTP404Error(url)
  138. elif e.code == 503:
  139. raise HTTP503Error(url)
  140. else:
  141. raise DownloadError(str(e))
  142. except:
  143. json_string = []
  144. try:
  145. parsed_json = simplejson.loads(json_string)
  146. except:
  147. parsed_json = []
  148. return parsed_json
  149.  
  150. # Retrieve XML data from cache function
  151. def _get_xml(url):
  152. _log('API: %s'% url)
  153. result = cache.cacheFunction( _get_xml_new, url )
  154. if len(result) == 0:
  155. result = []
  156. return result
  157. else:
  158. return result
  159.  
  160. # Retrieve XML data from site
  161. def _get_xml_new(url):
  162. _log('Cache expired. Retrieving new data')
  163. try:
  164. client = urlopen(url)
  165. data = client.read()
  166. client.close()
  167. return data
  168. except HTTPError, e:
  169. if e.code == 404:
  170. raise HTTP404Error( url )
  171. elif e.code == 503:
  172. raise HTTP503Error( url )
  173. elif e.code == 400:
  174. raise HTTP400Error( url )
  175. else:
  176. raise DownloadError( str(e) )
  177. except URLError:
  178. raise HTTPTimeout( url )
  179. except socket.timeout, e:
  180. raise HTTPTimeout( url )
  181.  
  182. # Clean filenames for illegal character in the safest way for windows
  183. def _clean_filename( filename ):
  184. illegal_char = '<>:"/\|?*'
  185. for char in illegal_char:
  186. filename = filename.replace( char , '' )
  187. return filename
  188.  
  189. def _save_nfo_file( data, target ):
  190. try:
  191. # open source path for writing
  192. file_object = open( target.encode( "utf-8" ), "w" )
  193. # write xmlSource
  194. file_object.write( data.encode( "utf-8" ) )
  195. # close file object
  196. file_object.close()
  197. # return successful
  198. return True
  199. except Exception, e:
  200. # oops, notify user what error occurred
  201. log( str( e ), xbmc.LOGERROR )
  202. # return failed
  203. return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement