Advertisement
aip1000

plugin.video.amazon - updated

Jan 19th, 2013
551
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from BeautifulSoup import BeautifulStoneSoup
  4. from BeautifulSoup import BeautifulSoup
  5. import cookielib
  6. import mechanize
  7. #import operator
  8. import sys
  9. import urllib
  10. import urllib2
  11. import re
  12. import os.path
  13. import xbmcplugin
  14. import xbmcgui
  15. import xbmcaddon
  16. import xbmc
  17.  
  18. import binascii
  19. import hmac
  20. try:
  21.     import hashlib.sha1 as sha1
  22. except:
  23.     import sha as sha1
  24.  
  25. import base64
  26. import demjson
  27.  
  28. print sys.argv
  29. addon = xbmcaddon.Addon('plugin.video.amazon')
  30. pluginpath = addon.getAddonInfo('path')
  31.  
  32. pluginhandle = int(sys.argv[1])
  33.  
  34. COOKIEFILE = os.path.join(xbmc.translatePath(pluginpath),'resources','cache','cookies.lwp')
  35.  
  36. BASE_URL = 'http://www.amazon.com'
  37.                      
  38. class _Info:
  39.     def __init__( self, *args, **kwargs ):
  40.         print "common.args"
  41.         print kwargs
  42.         self.__dict__.update( kwargs )
  43.  
  44. exec "args = _Info(%s)" % (urllib.unquote_plus(sys.argv[2][1:].replace("&", ", ").replace('"',"\"")) , )
  45.  
  46. def getURL( url , host='www.amazon.com',useCookie=False):
  47.     print 'getURL: '+url
  48.     cj = cookielib.LWPCookieJar()
  49.     if useCookie and os.path.isfile(COOKIEFILE):
  50.         cj.load(COOKIEFILE, ignore_discard=True, ignore_expires=True)
  51.     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  52.     opener.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)'),
  53.                          ('Host', host)]
  54.     usock = opener.open(url)#,timeout=30)
  55.     response = usock.read()
  56.     usock.close()
  57.     return response
  58.  
  59. def getATVURL( url , values = None ):
  60.     try:
  61.         #proxy = 'http://192.168.2.104:8888'
  62.         #proxy_handler = urllib2.ProxyHandler({'http':proxy})
  63.         #opener = urllib2.build_opener(proxy_handler)
  64.         opener = urllib2.build_opener()
  65.         print 'ATVURL --> url = '+url
  66.         opener.addheaders = [('x-android-sign', androidsig(url) )]
  67.         if values == None:
  68.             usock=opener.open(url)
  69.         else:
  70.             data = urllib.urlencode(values)
  71.             usock=opener.open(url,postdata)
  72.         response=usock.read()
  73.         usock.close()
  74.     except urllib2.URLError, e:
  75.         print 'Error reason: ', e
  76.         return False
  77.     else:
  78.         return response
  79.  
  80. def androidsig(url):
  81.     hmac_key = binascii.unhexlify('f5b0a28b415e443810130a4bcb86e50d800508cc')
  82.     sig = hmac.new(hmac_key, url, sha1)
  83.     return base64.encodestring(sig.digest()).replace('\n','')
  84.  
  85. def addDir(name, mode, sitemode, url='', thumb='', fanart='', infoLabels=False, totalItems=0, cm=False ,page=1):
  86.     u  = sys.argv[0]
  87.     u += '?url="'+urllib.quote_plus(url)+'"'
  88.     u += '&mode="'+mode+'"'
  89.     u += '&sitemode="'+sitemode+'"'
  90.     u += '&name="'+urllib.quote_plus(name)+'"'
  91.     u += '&page="'+urllib.quote_plus(str(page))+'"'
  92.     if fanart == '' or fanart == None:
  93.         try:fanart = args.fanart
  94.         except:fanart = os.path.join(addon.getAddonInfo('path'),'fanart.jpg')
  95.     else:u += '&fanart="'+urllib.quote_plus(fanart)+'"'
  96.     if thumb == '' or thumb == None:
  97.         try:thumb = args.thumb
  98.         except:thumb = os.path.join(addon.getAddonInfo('path'),'icon.png')
  99.     else:u += '&thumb="'+urllib.quote_plus(thumb)+'"'
  100.     item=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=thumb)
  101.     item.setProperty('fanart_image',fanart)
  102.     if not infoLabels:
  103.         infoLabels={ "Title": name}
  104.     if cm:
  105.         item.addContextMenuItems( cm, replaceItems=True  )
  106.     item.setInfo( type="Video", infoLabels=infoLabels)
  107.     xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=item,isFolder=True,totalItems=totalItems)
  108.  
  109. def addVideo(name,url,poster='',fanart='',infoLabels=False,totalItems=0,cm=False,traileronly=False):
  110.     if not infoLabels:
  111.         infoLabels={ "Title": name}
  112.     u  = sys.argv[0]
  113.     u += '?url="'+urllib.quote_plus(url)+'"'
  114.     u += '&mode="play"'
  115.     u += '&name="'+urllib.quote_plus(name)+'"'
  116.     utrailer = u+'&sitemode="PLAYTRAILER"'
  117.     if traileronly:
  118.         u += '&sitemode="PLAYTRAILER_RESOLVE"'        
  119.     else:
  120.         u += '&sitemode="PLAYVIDEO"'
  121.     infoLabels['Trailer']=utrailer
  122.     liz=xbmcgui.ListItem(name, thumbnailImage=poster)
  123.     liz.setInfo( type="Video", infoLabels=infoLabels)
  124.     try:
  125.         if fanart <> '' or fanart <> None:
  126.             liz.setProperty('fanart_image',fanart)
  127.     except:
  128.         print 'invalid fanart'
  129.     liz.setProperty('IsPlayable', 'true')
  130.     if cm:
  131.         liz.addContextMenuItems( cm , replaceItems=True )
  132.     xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz,isFolder=False,totalItems=totalItems)    
  133.  
  134. def setCustomer(check=False):
  135.     if check:
  136.         url = 'http://www.amazon.com'
  137.         data = getURL(url,useCookie=True)
  138.         customerId = re.compile('"customerID" ?: ?"(.*?)"').findall(data)[0]
  139.         if customerId <> addon.getSetting("customerId"):
  140.             addon.setSetting("customerId",customerId)
  141.             return False
  142.         else:
  143.             return True
  144.     elif addon.getSetting("customerId"):
  145.         return addon.getSetting("customerId")
  146.     else:
  147.         url = 'http://www.amazon.com'
  148.         data = getURL(url,useCookie=True)
  149.         customerId = re.compile('"customerID" ?: ?"(.*?)"').findall(data)[0]
  150.         addon.setSetting("customerId",customerId)
  151.         return customerId
  152.  
  153. def addMovieWatchlist():
  154.     addWatchlist('movie')
  155.  
  156. def addTVWatchlist():
  157.     addWatchlist('tv')
  158.  
  159. def addWatchlist(prodType,asin=False):
  160.     if not asin:
  161.         asin=args.asin
  162.     customerid=setCustomer()
  163.     url = 'http://www.amazon.com/gp/video/watchlist/ajax/addRemove.html'
  164.     url += '?dataType=json&addItem=10&ASIN='+asin
  165.     url += '&custID='+customerid
  166.     url += '&prodType='+prodType #movie or tv
  167.     data = getURL(url,useCookie=True)
  168.     json = demjson.decode(data)
  169.     if json['AsinStatus'] == 0:
  170.         getURL(url,useCookie=True)
  171.  
  172. def removeMovieWatchlist():
  173.     removeWatchlist('movie')
  174.  
  175. def removeTVWatchlist():
  176.     removeWatchlist('tv')
  177.  
  178. def removeWatchlist(prodType,asin=False):
  179.     if not asin:
  180.         asin=args.asin
  181.     customerid=setCustomer()
  182.     url = 'http://www.amazon.com/gp/video/watchlist/ajax/addRemove.html'
  183.     url += '?dataType=json&ASIN='+asin
  184.     url += '&custID='+customerid
  185.     url += '&prodType='+prodType #movie or tv
  186.     data = getURL(url,useCookie=True)
  187.     json = demjson.decode(data)
  188.     if json['AsinStatus'] == 1:
  189.         getURL(url,useCookie=True)
  190.        
  191. def makeGUID():
  192.     import random
  193.     guid = ''
  194.     for i in range(3):
  195.         number = "%X" % (int( ( 1.0 + random.random() ) * 0x10000) | 0)
  196.         guid += number[1:]
  197.     return guid
  198.  
  199. def gen_id():
  200.     if not addon.getSetting("GenDeviceID"):
  201.         addon.setSetting("GenDeviceID",makeGUID())
  202.  
  203. def mechanizeLogin():
  204.     succeeded = dologin()
  205.     retrys = 0
  206.     while succeeded == False:
  207.         xbmc.sleep(1000)
  208.         retrys += 1
  209.         print 'Login Retry: '+str(retrys)
  210.         succeeded = dologin()
  211.         if retrys >= 3:
  212.             xbmcgui.Dialog().ok('Login Error','Failed to Login')
  213.             succeeded=True
  214.  
  215. def dologin():
  216.     try:
  217.         if os.path.isfile(COOKIEFILE):
  218.             os.remove(COOKIEFILE)
  219.         cj = cookielib.LWPCookieJar()
  220.         br = mechanize.Browser()  
  221.         br.set_handle_robots(False)
  222.         br.set_cookiejar(cj)
  223.         br.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)')]  
  224.         sign_in = br.open("http://www.amazon.com/gp/flex/sign-out.html")
  225.         #print sign_in.read()  
  226.         br.select_form(name="sign-in")  
  227.         br["email"] = addon.getSetting("login_name")
  228.         br["password"] = addon.getSetting("login_pass")
  229.         logged_in = br.submit()  
  230.         error_str = "The e-mail address and password you entered do not match any accounts on record."  
  231.         if error_str in logged_in.read():
  232.             xbmcgui.Dialog().ok('Login Error',error_str)
  233.             print error_str
  234.             return True
  235.         else:
  236.             cj.save(COOKIEFILE, ignore_discard=True, ignore_expires=True)
  237.             setCustomer(check=True)
  238.             gen_id()
  239.             return True
  240.     except:
  241.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement