Commit [b88de9] Maximize Restore History

[plugin.video.giantbomb] updated to version 2.1

spiff spiff 2011-08-31

added plugin.video.giantbomb/fanart.jpg
changed plugin.video.giantbomb/LICENSE.txt
changed plugin.video.giantbomb/addon.xml
changed plugin.video.giantbomb/icon.png
changed .gitignore
copied plugin.video.giantbomb/addon.py -> plugin.video.giantbomb/default.py
plugin.video.giantbomb/fanart.jpg Diff Switch to side-by-side view
Loading...
plugin.video.giantbomb/LICENSE.txt Diff Switch to side-by-side view
Loading...
plugin.video.giantbomb/addon.xml Diff Switch to side-by-side view
Loading...
plugin.video.giantbomb/icon.png Diff Switch to side-by-side view
Loading...
.gitignore Diff Switch to side-by-side view
Loading...
plugin.video.giantbomb/addon.py to plugin.video.giantbomb/default.py
--- a/plugin.video.giantbomb/addon.py
+++ b/plugin.video.giantbomb/default.py
@@ -1,368 +1,212 @@
-# Giant Bomb Addon for XBMC v1.0.0
-# Copyright (C) 2010 Anders Bugge
-# 
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-
-# Contact Info
-# E-Mail: whimais@gmail.com
-
-# Thanks To
-# http://www.whiskeymedia.com/
-# http://www.giantbomb.com/
-# http://www.comicvine.com/
-
-_id='plugin.video.giantbomb'
-_resdir = "special://home/addons/" + _id + "/resources"
-_datadir = "special://profile/addon_data/" + _id
-
-# SYS imports
-import sys
 import urllib
-
-# XBMC imports
-import xbmc
+import urllib2
+import simplejson
+import xbmcplugin
 import xbmcgui
-import xbmcplugin
-import xbmcaddon
-
-# Simplejson
-sys.path.append(_resdir + "/lib/whimai")
-import simplejson as json
-
-# API interface imports
-sys.path.append( _resdir + "/lib/")
-import whimai.wm as wm
-import whimai.gb as gb
-
-# Variables
-template_url = "http://media.giantbomb.com/video/%(url)s"
-justin_url = "http://api.justin.tv/api/channel/archives/giantbomb.json?limit=%(lim)s&offset=%(off)s"
-settings_url = "http://whimais.googlecode.com/svn/plugin%20data/branches/giantbomb%20-%20xbmc/giantbomb_settings.json"
-
-settings_file_backup = _resdir + "/data/settings.backup"
-settings_script = _resdir + "/lib/settings.py"
-settings_file = _datadir + "/settings.json"
-video_file = _datadir + "/video.dat"
-
-mon = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"}
-startswith = "?url=&mode=2&name="
-search_cat_pos = 1
-
-class Main:
-	
-	def __init__( self ):
-		self.__settings__ = xbmcaddon.Addon(id=_id)
-		self.__language__ = self.__settings__.getLocalizedString
-		bug_cQuality = self.__settings__.getSetting('vquality')
-		
-		self._path = sys.argv[ 0 ]
-		self._handle = int(sys.argv[ 1 ])
-		self._argv = sys.argv[ 2 ]
-			
-		if not self._argv:
-			self.__settings__.setSetting('isSearch', "")
-			self.updateVideoList()
-			self.__settings__.setSetting('t_cat', str(self.cat))
-			for i in range(len(self.cat)):
-				self.addDir(self.cat[i]["name"])
-				
-		elif self._argv.startswith(startswith):
-			name = urllib.unquote_plus( self._argv[ len(startswith): ] )
-			self.cat = eval(self.__settings__.getSetting('t_cat'))
-			must = False
-			
-			if name == "Search" and self.__settings__.getSetting('isSearch') == "":
-				self.__settings__.setSetting('isSearch', "1")
-				keyboard = xbmc.Keyboard( "", self.__language__(30101), False )
-				keyboard.doModal()
-				if ( keyboard.isConfirmed() ):
-					filt = keyboard.getText().rsplit(" ")
-					self.cat[search_cat_pos]["filters"] = filt
-					self.__settings__.setSetting('t_cat', str(self.cat))
-				must = True
-			
-			elif self.__settings__.getSetting('isSearch') == "1":
-				name = "Search"
-				must = True
-			
-			else:
-				self.__settings__.setSetting('isSearch', "")
-			
-			# Add videos
-			for i in range(len(self.cat)):
-				if name == self.cat[i]["name"]:
-					self.addVideosFile(self.cat[i]["filters"], must)
-					break
-		
-			# Add sort methods
-			xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_DATE)
-			xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
-			
-			# Add catagory
-			xbmcplugin.setPluginCategory(self._handle,name)
-		
-		xbmcplugin.endOfDirectory(self._handle, cacheToDisc=False)
-		self.__settings__.setSetting('vquality',bug_cQuality)
-	
-	def addLink(self, name, url, iconimage, date, deck, totalItems):
-		liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
-		liz.setInfo( type="Video", infoLabels={ "Title": name , "Date": date, "Plot": deck} )
-		ok=xbmcplugin.addDirectoryItem(handle=self._handle,url=url,listitem=liz,totalItems=int(totalItems))
-		return ok
-	
-	def addDir(self, name):
-		u=self._path+"?url="+urllib.quote_plus('')+"&mode="+str(2)+"&name="+urllib.quote_plus(name)
-		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage='')
-		liz.setInfo( type="Video", infoLabels={ "Title": name } )
-		liz.addContextMenuItems([(self.__language__(30100),"XBMC.RunScript(%s)" % settings_script,)], True)
-		ok=xbmcplugin.addDirectoryItem(handle=self._handle,url=u,listitem=liz,isFolder=True)
-		return ok
-		
-	def addVideosFile(self, filt, mustPassAllFilters=False):
-		# Justin.tv list
-		if (filt == ["live_cat"]):
-			try:
-				# Checking Justin.tv
-				limit = 100
-				offset = 0
-				done = False
-				j_list = []
-				while done == False:
-					s = urllib.urlopen( justin_url%{ 'lim': limit , 'off': offset } )
-					tmp = eval( s.read() )
-					if len(tmp) is 0:
-						done = True
-					else:
-						j_list.extend( tmp )
-						offset += limit
-			
-			except:
-				print "JUSTIN UPDATE ERROR"
-				return
-			
-			else:
-				print "JUSTIN UPDATE OK"
-				
-				total = len( j_list )
-				video_count = 0
-				for i in range(0, len(j_list)):
-					video_count += 1
-					try:
-					    name = j_list[i]["title"]
-					except:
-						name = "Archived video stream from " + j_list[i]["created_on"]
-					url = j_list[i]["video_file_url"]
-					image = j_list[i]["image_url_medium"]
-					date = j_list[i]["created_on"][8:10] + "-" + mon[j_list[i]["created_on"][4:7]] + "-" + j_list[i]["created_on"][24:28]
-					deck = "Archived video stream from " + j_list[i]["created_on"]
-					self.addLink(name, url, image, date, deck, (total*video_count)/(i+1))
-			
-			return 
-		
-		# Get video quality setting
-		cQuality = self.__settings__.getSetting('vquality')
-		if (cQuality == "true") :
-			endString = "_1500.mp4"
-		else:
-			endString = "_700.mp4"
-	
-		# Read to the data file
-		try:
-			FILE = open(video_file, 'r+')
-			file_content = FILE.read()
-			FILE.close()
-			total = json.loads(file_content, object_hook=wm.E('total').as_e)
-			videos = json.loads(file_content, object_hook=wm.E('videos').as_e)
-			
-			# Test file integrati
-			if total != len(videos):
-				raise ValueError
-			
-		except:
-			print "ERROR IN DATA FILE"
-			FILE = open(video_file, 'w')
-			FILE.write("")
-			FILE.close()
-			return
-		
-		video_count = 0
-		for i in range(0,total):
-			found = False
-			name = videos[i]["name"]
-		
-			# All videos
-			if (filt == ""):
-				found = True
-				
-			# Latest
-			elif (filt == ["latest_cat"]):
-				if (i>total-26):
-					found = True
-					
-			# Custom catagories
-			else:
-				for x in range(0, len(filt)):
-					if( name.lower().find(filt[x].lower()) != -1):
-						found = True
-					else:
-						if mustPassAllFilters is True:
-							found = False
-							break
-			
-			if (found is True):
-				video_count += 1
-				url = template_url%{ 'url': videos[i]["url"].replace(".mp4",endString) }
-				image = videos[i]["image"]["super_url"]
-				date = videos[i]["publish_date"][8:10] + '-' + videos[i]["publish_date"][5:7] + '-' + videos[i]["publish_date"][0:4]
-				deck = videos[i]["deck"].encode('utf-8')
-				self.addLink(name, url, image, date, deck, (total*video_count)/(i+1))
-				
-	def updateVideoList(self):
-		pDialog = xbmcgui.DialogProgress()
-		pDialog.create(self.__language__(30102),self.__language__(30103),self.__language__(30104))
-			
-		# Settings
-		SETT = ""
-		load_local = False
-		if self.__settings__.getSetting('ucat'):
-			# Get settings from web
-			try:
-				s = urllib.urlopen( settings_url )
-				SETT = s.read()
-				
-				#Check if data is ok
-				json.loads(SETT, object_hook=wm.E('categories').as_e)[0]
-			
-			except:
-				print "SETTINGS UPDATE ERROR"
-				load_local = True
-			
-			else:
-				print "SETTINGS UPDATE OK"
-				FILE = open( settings_file, 'w' )
-				FILE.write( SETT )
-				FILE.close()
-		else:
-			load_local = True
-		
-		if load_local is True:
-			# Load settings from file
-			try:
-				# Read settings from local file
-				FILE = open( settings_file, 'r+' )
-				SETT = FILE.read()
-				FILE.close()
-				
-			except:
-				print "SETTINGS FILE ERROR, LOADING BACKUP"
-				# Read settings from local backup file
-				FILE = open( settings_file_backup, 'r+' )
-				SETT = FILE.read()
-				FILE.close()
-	
-			else:
-				print "SETTINGS FILE OK"
-			
-		# Collectiong categori information
-		self.cat = json.loads(SETT, object_hook=wm.E('categories').as_e)
-	
-		# Init video list setup and get total number of videos
-		list = gb.List("videos")
-		list.extra = "field_list=deck,image,name,publish_date,url&sort=publish_date"
-		ok = list.update(0,0)
-		if ok is False:
-			print "ERROR UPDATING VIDEO DATA"
-			del pDialog
-			return
-		
-		total = list.getTotal()
-	
-		videos = []
-		limit = 100
-		
-		# Compare total to local total
-		try:
-			FILE = open(video_file, 'r+')
-			file_content = FILE.read()
-			FILE.close()
-			offset = json.loads(file_content, object_hook=wm.E('total').as_e)
-			
-			# Test file integrati
-			if offset != len(json.loads(file_content, object_hook=wm.E('videos').as_e)):
-				raise ValueError
-				
-			# Test video filename
-			if( file_content.find(".flv") != -1):
-				print "OLD FILENAMES"
-				raise ValueError
-			
-		except:
-			print "ERROR IN DATA FILE"
-			offset = 0
-		
-		# if no new videos return
-		if total == offset:
-			print "NO NEW VIDEOS"
-			del pDialog
-			return
-			
-		# get old videos from file
-		if offset != 0:
-			try:
-				videos.extend(json.loads(file_content, object_hook=wm.E('videos').as_e))
-				
-				# Remove videos from the latest date
-				last_date = videos[len(videos)-1]["publish_date"][0:10]
-				for i in range(len(videos)-1,0,-1):
-					if videos[i]["publish_date"][0:10] != last_date:
-						break
-					del videos[i]
-				offset = len(videos)
-			
-			except:
-				print "ERROR IN DATA FILE"
-				videos = []
-				offset = 0
-		
-		start_cnt = offset
-		total_cnt = total - offset	
-		# get the remaning videos
-		while (offset < total):
-			if pDialog.iscanceled():
-				del pDialog
-				return
-				
-			ok = list.update(offset,limit)
-			if ok is False:
-				print "ERROR UPDATING VIDEO DATA"
-				del pDialog
-				return
-			
-			videos.extend(list.results)
-			offset += limit
-			i_pct = int(( float(offset-start_cnt) / float(total_cnt))*100.0+0.5)
-			pDialog.update(i_pct, self.__language__(30105), self.__language__(30104)) 
-			
-		# Create json formated video data and write to file
-		video_list = { 'total': total, 'videos': videos }
-		FILE = open(video_file, 'w')
-		FILE.write( json.dumps( video_list ) )
-		FILE.close()
-		
-		del pDialog
-
-if ( __name__ == "__main__" ):
-	Main()
-
+import shelve
+import os
+
+API_PATH = 'http://api.giantbomb.com'
+API_KEY = 'fa96542d69b4af7f31c2049ace5d89e84e225bef' # Default API key
+
+def CATEGORIES():
+    account_linked = False
+    filename = os.path.abspath('user_data.db')
+    d = shelve.open(filename)
+    if d.has_key('api_key'):
+        response = urllib2.urlopen(API_PATH + '/chats/?api_key=' + d['api_key'] + '&format=json')
+        data = simplejson.loads(response.read())
+        if data['status_code'] == 100:
+            # Revert to the default key
+            del d['api_key']
+        else:
+            global API_KEY
+            API_KEY = d['api_key']
+            account_linked = True
+    d.close()
+
+    response = urllib2.urlopen(API_PATH + '/video_types/?api_key=' + API_KEY + '&format=json')
+    category_data = simplejson.loads(response.read())['results']
+    response.close()
+
+    name = 'Latest'
+    url = API_PATH + '/videos/?api_key=' + API_KEY + '&sort=-publish_date&format=json'
+    iconimage = ''
+    addDir(name, url, 2, '')
+
+    for cat in category_data:
+        name = cat['name']
+        url = API_PATH + '/videos/?api_key=' + API_KEY + '&video_type=' + str(cat['id']) + '&sort=-publish_date&format=json'
+        iconimage = ''
+        if str(cat['id']) == '5':
+            addDir(name, '5', 1, '')
+        else:
+            addDir(name, url, 2, '')
+
+    name = 'Search'
+    iconimage = ''
+    addDir(name, 'search', 1, '')
+
+    if not account_linked:
+        name = 'Link Account'
+        iconimage = ''
+        addDir(name, 'link', 1, '')
+
+def GET_API_KEY(link_code):
+    if link_code and len(link_code) == 6:
+        try:
+            response = urllib2.urlopen(API_PATH + '/validate?link_code=' + link_code + '&format=json')
+            data = simplejson.loads(response.read())
+            api_key = data['api_key']
+            filename = os.path.abspath('user_data.db')
+            d = shelve.open(filename)
+            d['api_key'] = api_key
+            d.close()
+            return True
+        except:
+            return False
+    else:
+        return False
+
+def INDEX(url):
+    filename = os.path.abspath('user_data.db')
+    d = shelve.open(filename)
+    if d.has_key('api_key'):
+        API_KEY = d['api_key']
+    d.close()
+
+    if url == 'search':
+        keyboard = xbmc.Keyboard("", 'Search', False)
+        keyboard.doModal()
+        if keyboard.isConfirmed():
+            query = keyboard.getText().replace(' ', '%20')
+            url = API_PATH + '/search/?api_key=' + API_KEY + '&resources=video&query=' + query + '&format=json'
+            VIDEOLINKS(url, 'search')
+
+    elif url == 'link':
+        dialog = xbmcgui.Dialog()
+        ok = dialog.ok("Let's do this.", "To link your account, visit", "www.giantbomb.com/xbmc to get a link code.", "Enter this code on the next screen.")
+
+        keyboard = xbmc.Keyboard("", 'Enter your link code.', False)
+        keyboard.doModal()
+        if keyboard.isConfirmed():
+            link_code = keyboard.getText().upper()
+            if GET_API_KEY(link_code):
+                ok = dialog.ok("Success!", "Your account is now linked!", "If you are a premium member,", "you should now have premium privileges.")
+            else:
+                ok = dialog.ok("We're really sorry, but...", "We could not link your account.", "Make sure the code you entered is correct", "and try again.")
+            CATEGORIES()
+    else:
+        addDir('Deadly Premonition', url + '&DP', 2, '')
+        addDir('Persona 4', url + '&P4', 2, '')
+        addDir('The Matrix Online: Not Like This', url + '&MO', 2, '')
+
+def VIDEOLINKS(url, name):
+    filename = os.path.abspath('user_data.db')
+    d = shelve.open(filename)
+    if d.has_key('api_key'):
+        API_KEY = d['api_key']
+    d.close()
+
+    if url.endswith('&DP'):
+        response = urllib2.urlopen(API_PATH + '/videos/?api_key=' + API_KEY + '&video_type=5&offset=161&format=json')
+        video_data = simplejson.loads(response.read())['results']
+        response.close()
+    elif url.endswith('&P4'):
+        response = urllib2.urlopen(API_PATH + '/videos/?api_key=' + API_KEY + '&video_type=5&format=json')
+        video_data = simplejson.loads(response.read())['results']
+        response.close()
+
+        response = urllib2.urlopen(API_PATH + '/videos/?api_key=' + API_KEY + '&video_type=5&offset=100&limit=61&format=json')
+        video_data += simplejson.loads(response.read())['results']
+        response.close()
+
+        video_data = [video for video in video_data if not video['name'].startswith('The Matrix Online')]
+    elif url.endswith('&MO'):
+        response = urllib2.urlopen(API_PATH + '/videos/?api_key=' + API_KEY + '&video_type=5&offset=105&limit=21&format=json')
+        video_data = simplejson.loads(response.read())['results']
+        response.close()
+
+        video_data = [video for video in video_data if video['name'].startswith('The Matrix Online')]
+    else:
+        response = urllib2.urlopen(url)
+        video_data = simplejson.loads(response.read())['results']
+        response.close()
+
+    for vid in video_data:
+        name = vid['name']
+        if 'hd_url' in vid:
+            url = vid['hd_url'] + '&api_key=' + API_KEY
+        else:
+            url = vid['high_url']
+        thumbnail = vid['image']['super_url']
+        addLink(name,url,thumbnail)
+
+def get_params():
+    param=[]
+    paramstring=sys.argv[2]
+    if len(paramstring)>=2:
+        params=sys.argv[2]
+        cleanedparams=params.replace('?','')
+        if (params[len(params)-1]=='/'):
+            params=params[0:len(params)-2]
+        pairsofparams=cleanedparams.split('&')
+        param={}
+        for i in range(len(pairsofparams)):
+            splitparams={}
+            splitparams=pairsofparams[i].split('=')
+            if (len(splitparams))==2:
+                param[splitparams[0]]=splitparams[1]
+
+    return param
+
+def addLink(name, url, iconimage):
+    ok=True
+    liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
+    liz.setInfo( type="Video", infoLabels={ "Title": name } )
+    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
+    return ok
+
+def addDir(name, url, mode, iconimage):
+    u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
+    ok=True
+    liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
+    liz.setInfo( type="Video", infoLabels={ "Title": name } )
+    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
+    return ok
+
+params=get_params()
+url=None
+name=None
+mode=None
+
+try:
+    url=urllib.unquote_plus(params["url"])
+except:
+    pass
+try:
+    name=urllib.unquote_plus(params["name"])
+except:
+    pass
+try:
+    mode=int(params["mode"])
+except:
+    pass
+
+print "Mode: "+str(mode)
+print "URL: "+str(url)
+print "Name: "+str(name)
+
+if mode==None or url==None or len(url)<1:
+    print ""
+    CATEGORIES()
+
+elif mode==1:
+    print ""+url
+    INDEX(url)
+
+elif mode==2:
+    print ""+url
+    VIDEOLINKS(url,name)
+
+xbmcplugin.endOfDirectory(int(sys.argv[1]))