Files
jellycon/resources/lib/datamanager.py

240 lines
8.2 KiB
Python
Raw Normal View History

# Gnu General Public License - see LICENSE.TXT
import json
2017-12-28 13:11:18 +11:00
from collections import defaultdict
2018-11-11 15:08:07 +11:00
import threading
import hashlib
import os
import cPickle
2018-11-21 13:23:42 +11:00
import time
#import copy
#import urllib
2014-10-30 14:29:19 +11:00
2019-01-11 10:24:42 +11:00
from .downloadutils import DownloadUtils
from .simple_logging import SimpleLogging
from .item_functions import extract_item_info
from .kodi_utils import HomeWindow
2018-11-11 15:08:07 +11:00
import xbmc
import xbmcaddon
2014-10-30 14:29:19 +11:00
log = SimpleLogging(__name__)
2017-03-10 10:45:38 +11:00
2018-11-21 13:23:42 +11:00
class CacheItem():
item_list = None
item_list_hash = None
date_saved = None
last_action = None
items_url = None
file_path = None
def __init__(self, *args):
pass
class DataManager():
2018-11-11 15:08:07 +11:00
addon_dir = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
def __init__(self, *args):
2018-11-21 13:23:42 +11:00
# log.debug("DataManager __init__")
pass
2014-10-30 14:29:19 +11:00
def loadJasonData(self, jsonData):
2017-12-28 13:11:18 +11:00
return json.loads(jsonData, object_hook=lambda d: defaultdict(lambda: None, d))
2014-10-30 14:29:19 +11:00
def GetContent(self, url):
jsonData = DownloadUtils().downloadUrl(url)
2017-12-07 19:54:09 +11:00
result = self.loadJasonData(jsonData)
return result
2017-04-19 13:23:44 +10:00
def get_items(self, url, gui_options, use_cache=False):
home_window = HomeWindow()
2018-12-25 07:22:37 +11:00
log.debug("last_content_url : use_cache={0} url={1}", use_cache, url)
home_window.setProperty("last_content_url", url)
2018-11-11 15:08:07 +11:00
2018-11-11 17:35:09 +11:00
user_id = DownloadUtils().getUserId()
2018-11-11 15:08:07 +11:00
m = hashlib.md5()
2018-11-11 17:35:09 +11:00
m.update(user_id + "|" + url)
2018-11-11 15:08:07 +11:00
url_hash = m.hexdigest()
cache_file = os.path.join(self.addon_dir, "cache_" + url_hash + ".pickle")
2018-11-18 14:03:23 +11:00
#changed_url = url + "&MinDateLastSavedForUser=" + urllib.unquote("2019-09-16T13:45:30")
#results = self.GetContent(changed_url)
#log.debug("DataManager Changes Since Date : {0}", results)
2018-11-21 13:23:42 +11:00
item_list = None
2018-11-11 15:08:07 +11:00
baseline_name = None
cache_thread = CacheManagerThread()
cache_thread.gui_options = gui_options
home_window.setProperty(cache_file, "true")
2018-11-21 13:23:42 +11:00
clear_cache = home_window.getProperty("skip_cache_for_" + url)
if clear_cache and os.path.isfile(cache_file):
log.debug("Clearing cache data and loading new data")
2018-11-21 13:23:42 +11:00
home_window.clearProperty("skip_cache_for_" + url)
os.remove(cache_file)
2018-11-21 13:23:42 +11:00
# try to load the list item data form the cache
if os.path.isfile(cache_file) and use_cache:
2018-11-15 10:01:21 +11:00
log.debug("Loading url data from cached pickle data")
2018-11-11 15:08:07 +11:00
with open(cache_file, 'rb') as handle:
2018-11-21 13:23:42 +11:00
try:
cache_item = cPickle.load(handle)
cache_thread.cached_item = cache_item
item_list = cache_item.item_list
2019-01-11 10:24:42 +11:00
except Exception as err:
2018-11-21 13:23:42 +11:00
log.debug("Pickle Data Load Failed : {0}", err)
item_list = None
# we need to load the list item data form the server
if item_list is None:
2018-11-11 15:08:07 +11:00
log.debug("Loading url data from server")
results = self.GetContent(url)
if results is None:
results = []
if isinstance(results, dict) and results.get("Items") is not None:
baseline_name = results.get("BaselineItemName")
results = results.get("Items", [])
elif isinstance(results, list) and len(results) > 0 and results[0].get("Items") is not None:
baseline_name = results[0].get("BaselineItemName")
results = results[0].get("Items")
2018-11-21 13:23:42 +11:00
item_list = []
2018-11-11 15:08:07 +11:00
for item in results:
item_data = extract_item_info(item, gui_options)
item_data.baseline_itemname = baseline_name
2018-11-11 15:08:07 +11:00
item_list.append(item_data)
2018-11-21 13:23:42 +11:00
cache_item = CacheItem()
cache_item.item_list = item_list
cache_item.file_path = cache_file
cache_item.items_url = url
cache_item.last_action = "fresh_data"
cache_item.date_saved = time.time()
cache_thread.cached_item = cache_item
# copy.deepcopy(item_list)
2018-11-11 15:08:07 +11:00
if use_cache:
cache_thread.start()
2018-11-11 15:08:07 +11:00
return cache_file, item_list
2018-11-11 15:08:07 +11:00
class CacheManagerThread(threading.Thread):
2018-11-21 13:23:42 +11:00
cached_item = None
2018-11-11 15:08:07 +11:00
gui_options = None
def __init__(self, *args):
threading.Thread.__init__(self, *args)
@staticmethod
def get_data_hash(items):
m = hashlib.md5()
for item in items:
item_string = "%s_%s_%s_%s_%s_%s" % (
2018-11-11 15:08:07 +11:00
item.name,
item.play_count,
item.favorite,
item.resume_time,
item.recursive_unplayed_items_count,
item.etag
2018-11-11 15:08:07 +11:00
)
item_string = item_string.encode("UTF-8")
m.update(item_string)
return m.hexdigest()
2018-11-21 13:23:42 +11:00
def wait_for_save(self, home_window, file_name):
loops = 0
wait_refresh = home_window.getProperty(file_name)
while wait_refresh and loops < 200 and not xbmc.Monitor().abortRequested():
xbmc.sleep(100)
loops = loops + 1
wait_refresh = home_window.getProperty(file_name)
return loops
2018-11-11 15:08:07 +11:00
def run(self):
log.debug("CacheManagerThread : Started")
home_window = HomeWindow()
2018-11-21 13:23:42 +11:00
is_fresh = False
# if the data is fresh then just save it
# if the data is to old do a reload
if (self.cached_item.date_saved is not None
and (time.time() - self.cached_item.date_saved) < 20
and self.cached_item.last_action == "fresh_data"):
is_fresh = True
2018-11-21 13:23:42 +11:00
if is_fresh:
log.debug("CacheManagerThread : Saving fresh data")
cached_hash = self.get_data_hash(self.cached_item.item_list)
self.cached_item.item_list_hash = cached_hash
self.cached_item.last_action = "cached_data"
self.cached_item.date_saved = time.time()
2018-11-21 13:23:42 +11:00
loops = self.wait_for_save(home_window, self.cached_item.file_path)
log.debug("CacheManagerThread : Saving New Data loops({0})", loops)
2018-11-21 13:23:42 +11:00
with open(self.cached_item.file_path, 'wb') as handle:
cPickle.dump(self.cached_item, handle, protocol=cPickle.HIGHEST_PROTOCOL)
2018-11-21 13:23:42 +11:00
home_window.clearProperty(self.cached_item.file_path)
2018-11-11 15:08:07 +11:00
else:
2018-11-21 13:23:42 +11:00
log.debug("CacheManagerThread : Reloading to recheck data hashes")
cached_hash = self.cached_item.item_list_hash
log.debug("CacheManagerThread : Cache Hash : {0}", cached_hash)
2018-11-11 15:08:07 +11:00
data_manager = DataManager()
2018-11-21 13:23:42 +11:00
results = data_manager.GetContent(self.cached_item.items_url)
if results is None:
results = []
2018-11-11 15:08:07 +11:00
if isinstance(results, dict) and results.get("Items") is not None:
results = results.get("Items", [])
elif isinstance(results, list) and len(results) > 0 and results[0].get("Items") is not None:
results = results[0].get("Items")
2018-11-11 15:08:07 +11:00
loaded_items = []
for item in results:
item_data = extract_item_info(item, self.gui_options)
loaded_items.append(item_data)
2018-11-11 15:08:07 +11:00
loaded_hash = self.get_data_hash(loaded_items)
log.debug("CacheManagerThread : Loaded Hash : {0}", loaded_hash)
2018-11-11 15:08:07 +11:00
# if they dont match then save the data and trigger a content reload
if cached_hash != loaded_hash:
2018-11-21 13:23:42 +11:00
log.debug("CacheManagerThread : Hashes different, saving new data and reloading container")
self.cached_item.item_list = loaded_items
self.cached_item.item_list_hash = loaded_hash
self.cached_item.last_action = "fresh_data"
self.cached_item.date_saved = time.time()
2018-11-11 15:08:07 +11:00
# we need to refresh but will wait until the main function has finished
2018-11-21 13:23:42 +11:00
loops = self.wait_for_save(home_window, self.cached_item.file_path)
with open(self.cached_item.file_path, 'wb') as handle:
cPickle.dump(self.cached_item, handle, protocol=cPickle.HIGHEST_PROTOCOL)
home_window.clearProperty(self.cached_item.file_path)
log.debug("CacheManagerThread : Sending container refresh ({0})", loops)
xbmc.executebuiltin("Container.Refresh")
2014-10-30 14:29:19 +11:00
2018-11-11 15:08:07 +11:00
log.debug("CacheManagerThread : Exited")