Skip to content

Commit

Permalink
Improve menu/track listing performance
Browse files Browse the repository at this point in the history
By delaying module importing whenever possible
  • Loading branch information
foreverguest committed Jan 9, 2014
1 parent 311d5d0 commit 61ff50d
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 57 deletions.
103 changes: 55 additions & 48 deletions GoogleMusicApi.py
@@ -1,13 +1,32 @@
import sys
import GoogleMusicLogin

class GoogleMusicApi():
def __init__(self):
self.main = sys.modules["__main__"]
self.storage = self.main.storage
self.login = GoogleMusicLogin.GoogleMusicLogin()
self.gmusicapi = self.login.getApi()

self.api = None
self.device = None
self.login = None

def getApi(self):
if self.api == None :
import GoogleMusicLogin
self.login = GoogleMusicLogin.GoogleMusicLogin()
self.login.login()
self.api = self.login.getApi()
self.device = self.login.getDevice()
return self.api

def getDevice(self):
if self.device == None:
self.getApi()
return self.device

def getLogin(self):
if self.login == None:
self.getApi()
return self.login

def getPlaylistSongs(self, playlist_id, forceRenew=False):
if playlist_id in ('thumbsup','lastadded','mostplayed','freepurchased'):
return self.storage.getAutoPlaylistSongs(playlist_id)
Expand All @@ -21,7 +40,8 @@ def getPlaylistSongs(self, playlist_id, forceRenew=False):

def getPlaylistsByType(self, playlist_type, forceRenew=False):
if playlist_type == 'auto':
return [['thumbsup','Highly Rated'],['lastadded','Last Added'],['freepurchased','Free and Purchased'],['mostplayed','Most Played']]
return [['thumbsup','Highly Rated'],['lastadded','Last Added'],
['freepurchased','Free and Purchased'],['mostplayed','Most Played']]

if forceRenew:
self.updatePlaylists(playlist_type)
Expand All @@ -35,50 +55,41 @@ def getPlaylistsByType(self, playlist_type, forceRenew=False):

def getSong(self, song_id):
return self.storage.getSong(song_id)

def loadLibrary(self):
#gen = self.gmusicapi.get_all_songs(incremental=True)
#for chunk in gen:
# for song in chunk:
#print song
# api_songs.append(song)
# break
#api_songs = [song for chunk in api_songs for song in chunk]
api_songs = self.getApi().get_all_songs()
self.main.log("Library Size: "+repr(len(api_songs)))
self.main.log("First Song: "+repr(api_songs[0]))
self.storage.storeApiSongs(api_songs, 'all_songs')

def updatePlaylistSongs(self, playlist_id):
api_songs = []

self.login.login()
if playlist_id == 'all_songs':
#gen = self.gmusicapi.get_all_songs(incremental=True)
#for chunk in gen:
# for song in chunk:
#print song
# api_songs.append(song)
# break
#api_songs = [song for chunk in api_songs for song in chunk]
api_songs = self.gmusicapi.get_all_songs()
self.main.log("Library Size: "+repr(len(api_songs)))
self.main.log("First Song: "+repr(api_songs[0]))
if self.getDevice():
self.storage.storePlaylistSongs(self.api.get_all_user_playlist_contents())
else:
if self.login.getDevice():
self.storage.storePlaylistSongs(self.gmusicapi.get_all_user_playlist_contents())
else:
api_songs = self.gmusicapi.get_playlist_songs(playlist_id)

if api_songs:
self.storage.storeApiSongs(api_songs, playlist_id)
self.storage.storeApiSongs(self.api.get_playlist_songs(playlist_id), playlist_id)

def updatePlaylists(self, playlist_type):
self.login.login()
if self.login.getDevice():
self.storage.storePlaylistSongs(self.gmusicapi.get_all_user_playlist_contents())
if self.getDevice():
self.storage.storePlaylistSongs(self.api.get_all_user_playlist_contents())
else:
playlists = self.gmusicapi.get_all_playlist_ids(playlist_type)
playlists = self.api.get_all_playlist_ids(playlist_type)
self.storage.storePlaylists(playlists[playlist_type], playlist_type)

def getSongStreamUrl(self, song_id):

self.login.login()

device_id = self.login.getDevice()
device_id = self.getDevice()
self.main.log("getSongStreamUrl device: "+device_id)

if device_id:
stream_url = self.gmusicapi.get_stream_url(song_id, device_id)
stream_url = self.api.get_stream_url(song_id, device_id)
else:
streams = self.gmusicapi.get_stream_urls(song_id)
streams = self.api.get_stream_urls(song_id)
if len(streams) > 1:
self.main.xbmc.executebuiltin("XBMC.Notification("+plugin+",'All Access track not playable')")
raise Exception('All Access track not playable, no mobile device found in account!')
Expand All @@ -89,9 +100,7 @@ def getSongStreamUrl(self, song_id):
return stream_url

def getFilterSongs(self, filter_type, filter_criteria):
songs = self.storage.getFilterSongs(filter_type, filter_criteria)

return songs
return self.storage.getFilterSongs(filter_type, filter_criteria)

def getCriteria(self, criteria, artist=''):
return self.storage.getCriteria(criteria,artist)
Expand All @@ -101,27 +110,25 @@ def getSearch(self, query):

def clearCache(self):
self.storage.clearCache()
self.login.clearCookie()
self.clearCookie()

def clearCookie(self):
self.login.clearCookie()
self.getLogin().clearCookie()

def getStations(self):
self.login.login()
stations = {}
try:
stations = self.gmusicapi.get_all_stations()
stations = self.getApi().get_all_stations()
#self.main.log("STATIONS: "+repr(stations))
except Exception as e:
self.main.log("*** NO STATIONS *** "+repr(e))
self.main.log("STATIONS: "+repr(stations))
return stations

def getStationTracks(self, station_id):
self.login.login()
tracks = {}
try:
tracks = self.gmusicapi.get_station_tracks(station_id)
self.main.log("TRACKS *** "+repr(tracks))
tracks = self.getApi().get_station_tracks(station_id)
#self.main.log("TRACKS *** "+repr(tracks))
except Exception as e:
self.main.log("*** NO TRACKS *** "+repr(e))
return tracks
return tracks
12 changes: 4 additions & 8 deletions GoogleMusicNavigation.py
@@ -1,9 +1,7 @@
import os
import sys
import urllib
import CommonFunctions as common
import GoogleMusicApi
from gmusicapi.utils.utils import id_or_nid

class GoogleMusicNavigation():
def __init__(self):
Expand Down Expand Up @@ -39,7 +37,7 @@ def listMenu(self, params={}):

if self.path == "root":
listItems = self.getMenuItems(self.main_menu)
if self.api.login.getDevice():
if self.api.getDevice():
listItems.insert(1,self.addFolderListItem(self.language(30203),{'path':"playlists",'playlist_type':"radio"}))
elif self.path == "library":
listItems = self.getMenuItems(self.lib_menu)
Expand All @@ -60,6 +58,7 @@ def listMenu(self, params={}):
elif self.path in ["genre","artist","album"]:
listItems = self.listFilterSongs(self.path,get('name'))
elif self.path == "search":
import CommonFunctions as common
query = common.getUserInput(self.language(30208), '')
if query:
listItems = self.getSearch(query)
Expand Down Expand Up @@ -104,8 +103,6 @@ def executeAction(self, params={}):
self.main.log("Invalid action: " + get("action"))

def addFolderListItem(self, name, params={}, contextMenu=[], album_art_url=""):
if not name:
name = 'Unknown'
li = self.xbmcgui.ListItem(label=name, iconImage=album_art_url, thumbnailImage=album_art_url)
li.setProperty("Folder", "true")

Expand Down Expand Up @@ -219,20 +216,19 @@ def getSearch(self, query):
def getStations(self):
listItems = []
stations = self.api.getStations()
#stations = [{'name':'Teste','id':'1287yed82d'}]
for rs in stations:
listItems.append(self.addFolderListItem(rs['name'], {'path':"station",'id':rs['id']}))
return listItems

def getStationTracks(self,station_id):
import gmusicapi.utils.utils as utils
listItems = []
tracks = self.api.getStationTracks(station_id)
#tracks = [{'title':'Teste1','id':'f5d1db5a-77d6-3b89-993b-b6ee45b3abce'},{'title':'Teste2','id':'kf7fi765'}]
for track in tracks:
li = self.xbmcgui.ListItem(track['title'])
li.setProperty('IsPlayable', 'true')
li.setProperty('Music', 'true')
url = '%s?action=play_song&song_id=%s&title=%s' % (sys.argv[0],id_or_nid(track).encode('utf8'),track['title'].encode('utf8'))
url = '%s?action=play_song&song_id=%s&title=%s' % (sys.argv[0],utils.id_or_nid(track).encode('utf8'),track['title'].encode('utf8'))
li.setPath(url)
listItems.append([url,li])
return listItems
2 changes: 1 addition & 1 deletion default.py
Expand Up @@ -73,7 +73,7 @@ def log(message):
if not storage.isPlaylistFetched('all_songs'):
xbmc.executebuiltin("XBMC.Notification("+plugin+",'Loading library',5000,"+__icon__ +")")
log('Loading library')
navigation.api.updatePlaylistSongs('all_songs')
navigation.api.loadLibrary()

navigation.listMenu()
elif (get("action")):
Expand Down

0 comments on commit 61ff50d

Please sign in to comment.