cut back to basics

This commit is contained in:
shaun
2017-03-04 13:08:08 +11:00
parent 8d532cc74f
commit 4db9175a13
17 changed files with 34 additions and 1785 deletions

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="plugin.video.mbcon"
<addon id="plugin.video.embycon"
name="MBCon"
version="1.0.2"
provider-name="null_pointer">

View File

@@ -25,7 +25,7 @@ import xbmcplugin
import xbmcgui
import xbmcaddon
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__settings__ = xbmcaddon.Addon(id='plugin.video.embycon')
__cwd__ = __settings__.getAddonInfo('path')
BASE_RESOURCE_PATH = xbmc.translatePath( os.path.join( __cwd__, 'resources', 'lib' ) )
sys.path.append(BASE_RESOURCE_PATH)

View File

@@ -1,606 +0,0 @@
#################################################################################################
# Start of BackgroundRotationThread
# Sets a backgound property to a fan art link
#################################################################################################
import xbmc
import xbmcgui
import xbmcaddon
import json
import threading
from datetime import datetime
import urllib
import urllib2
import random
import time
from DownloadUtils import DownloadUtils
class ArtworkRotationThread(threading.Thread):
item_details_store = {}
item_art_links = {}
current_item_art = 0;
global_art_links = []
current_global_art = 0
linksLoaded = False
logLevel = 0
currentFilteredIndex = {}
def __init__(self, *args):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
self.getString = self.addonSettings.getLocalizedString
level = addonSettings.getSetting('logLevel')
self.logLevel = 0
if(level != None):
self.logLevel = int(level)
xbmc.log("MBCon BackgroundRotationThread -> Log Level:" + str(self.logLevel))
threading.Thread.__init__(self, *args)
def logMsg(self, msg, level = 1):
if(self.logLevel >= level):
xbmc.log("MBCon BackgroundRotationThread -> " + msg)
def run(self):
try:
self.run_internal()
except Exception, e:
xbmcgui.Dialog().ok(self.getString(30203), str(e))
raise
def run_internal(self):
self.logMsg("Started")
try:
self.loadLastBackground()
except Exception, e:
self.logMsg("loadLastBackground Exception : " + str(e), level=0)
WINDOW = xbmcgui.Window( 10000 )
filterOnParent_Last = WINDOW.getProperty("MB3.Background.Collection")
last_id = ""
self.updateArtLinks()
# if no saved background art then set a new one
if(WINDOW.getProperty("MB3.Background.Global.FanArt") == None or WINDOW.getProperty("MB3.Background.Global.FanArt") == ""):
self.setBackgroundLink(filterOnParent_Last)
lastRun = datetime.today()
itemLastRun = datetime.today()
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
backgroundRefresh = int(addonSettings.getSetting('backgroundRefresh'))
if(backgroundRefresh < 10):
backgroundRefresh = 10
itemBackgroundRefresh = 5
lastUserName = addonSettings.getSetting('username')
while (xbmc.abortRequested == False):
# only do stuff if not playing
if(xbmc.Player().isPlaying() == False):
td = datetime.today() - lastRun
td2 = datetime.today() - itemLastRun
secTotal = td.seconds
secTotal2 = td2.seconds
userName = addonSettings.getSetting('username')
self.logMsg("Server details string : (" + userName + ") (" + lastUserName + ")", level=2)
Collection = WINDOW.getProperty("MB3.Background.Collection")
if(secTotal > backgroundRefresh or filterOnParent_Last != Collection or userName != lastUserName):
lastUserName = userName
if(self.linksLoaded == False):
self.updateArtLinks()
lastRun = datetime.today()
filterOnParent_Last = Collection
backgroundRefresh = int(addonSettings.getSetting('backgroundRefresh'))
self.setBackgroundLink(Collection)
if(backgroundRefresh < 10):
backgroundRefresh = 10
# update item BG every 7 seconds
if(secTotal2 > itemBackgroundRefresh):
self.setItemBackgroundLink()
itemLastRun = datetime.today()
# update item BG on selected item changes
if xbmc.getInfoLabel('ListItem.Property(id)') != None:
current_id = xbmc.getInfoLabel('ListItem.Property(id)')
elif xbmc.getInfoLabel('ListItem.Property(ItemGUID)') != None:
current_id=xbmc.getInfoLabel('ListItem.Property(ItemGUID)')
else:
current_id = ''
if current_id != last_id:
self.setItemBackgroundLink()
self.setItemDetailsProps()
itemLastRun = datetime.today()
last_id = current_id
if(xbmc.abortRequested == True):
break
xbmc.sleep(500)
if(xbmc.abortRequested == True):
break
try:
self.saveLastBackground()
except Exception, e:
self.logMsg("saveLastBackground Exception : " + str(e), level=0)
self.logMsg("Exited")
def loadLastBackground(self):
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__addondir__ = xbmc.translatePath( __addon__.getAddonInfo('profile') )
lastDataPath = __addondir__ + "LastBgLinks.json"
dataFile = open(lastDataPath, 'r')
jsonData = dataFile.read()
dataFile.close()
self.logMsg(jsonData)
result = json.loads(jsonData)
WINDOW = xbmcgui.Window( 10000 )
if(result.get("global") != None):
WINDOW.setProperty("MB3.Background.Global.FanArt", result.get("global")["url"])
self.logMsg("MB3.Background.Global.FanArt=" + result.get("global")["url"], level=2)
WINDOW.setProperty("MB3.Background.Global.FanArt.Poster", result.get("global")["poster"])
self.logMsg("MB3.Background.Global.FanArt.Poster=" + result.get("global")["poster"], level=2)
WINDOW.setProperty("MB3.Background.Global.FanArt.Action", result.get("global")["action"])
self.logMsg("MB3.Background.Global.FanArt.Action=" + result.get("global")["action"], level=2)
def saveLastBackground(self):
data = {}
if(len(self.global_art_links) > 0):
data["global"] = self.global_art_links[self.current_global_art]
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__addondir__ = xbmc.translatePath( __addon__.getAddonInfo('profile') )
lastDataPath = __addondir__ + "LastBgLinks.json"
dataFile = open(lastDataPath, 'w')
stringdata = json.dumps(data)
self.logMsg("Last Background Links : " + stringdata)
dataFile.write(stringdata)
dataFile.close()
def setBackgroundLink(self, filterOnParent):
WINDOW = xbmcgui.Window( 10000 )
if(len(self.global_art_links) > 0):
self.logMsg("setBackgroundLink index global_art_links " + str(self.current_global_art + 1) + " of " + str(len(self.global_art_links)), level=2)
next, nextItem = self.findNextLink(self.global_art_links, self.current_global_art, filterOnParent)
#nextItem = self.global_art_links[self.current_global_art]
self.current_global_art = next
backGroundUrl = nextItem["url"]
posterUrl = nextItem["poster"]
actionUrl = nextItem["action"]
WINDOW.setProperty("MB3.Background.Global.FanArt", backGroundUrl)
self.logMsg("MB3.Background.Global.FanArt=" + backGroundUrl)
WINDOW.setProperty("MB3.Background.Global.FanArt.Poster", posterUrl)
self.logMsg("MB3.Background.Global.FanArt.Poster=" + posterUrl)
WINDOW.setProperty("MB3.Background.Global.FanArt.Action", actionUrl)
self.logMsg("MB3.Background.Global.FanArt.Action=" + actionUrl)
def findNextLink(self, linkList, startIndex, filterOnParent):
if(filterOnParent == None or filterOnParent == ""):
filterOnParent = "empty"
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
backgroundRefresh = int(addonSettings.getSetting('backgroundRefresh'))
if(backgroundRefresh < 10):
backgroundRefresh = 10
# first check the cache if we are filtering
if(self.currentFilteredIndex.get(filterOnParent) != None):
cachedItem = self.currentFilteredIndex.get(filterOnParent)
self.logMsg("filterOnParent=existing=" + filterOnParent + "=" + str(cachedItem))
cachedIndex = cachedItem[0]
dateStamp = cachedItem[1]
td = datetime.today() - dateStamp
secTotal = td.seconds
if(secTotal < backgroundRefresh):
# use the cached background index
self.logMsg("filterOnParent=using=" + filterOnParent + "=" + str(secTotal))
return (cachedIndex, linkList[cachedIndex])
currentIndex = startIndex
isParentMatch = False
#xbmc.log("findNextLink : filterOnParent=" + str(filterOnParent) + " isParentMatch=" + str(isParentMatch))
while(isParentMatch == False):
currentIndex = currentIndex + 1
if(currentIndex == len(linkList)):
currentIndex = 0
if(currentIndex == startIndex):
return (currentIndex, linkList[currentIndex]) # we checked everything and nothing was ok so return the first one again
isParentMatch = True
# if filter on not empty then make sure we have a bg from the correct collection
if(filterOnParent != "empty"):
isParentMatch = filterOnParent in linkList[currentIndex]["collections"]
# save the cached index
cachedItem = [currentIndex, datetime.today()]
self.logMsg("filterOnParent=adding=" + filterOnParent + "=" + str(cachedItem))
self.currentFilteredIndex[filterOnParent] = cachedItem
nextIndex = currentIndex + 1
if(nextIndex == len(linkList)):
nextIndex = 0
return (nextIndex, linkList[currentIndex])
def updateArtLinks(self):
t1 = time.time()
result01 = self.updateCollectionArtLinks()
t2 = time.time()
diff = t2 - t1
self.logMsg("TIME_DIFF : " + str(diff))
if(result01):
self.logMsg("BackgroundRotationThread Update Links Worked")
self.linksLoaded = True
else:
self.logMsg("BackgroundRotationThread Update Links Failed")
self.linksLoaded = False
def updateActionUrls(self):
xbmc.log("BackgroundRotationThread updateActionUrls Called")
WINDOW = xbmcgui.Window( 10000 )
for x in range(0, 10):
contentUrl = WINDOW.getProperty("mbcon_collection_menuitem_content_" + str(x))
if(contentUrl != None):
index = contentUrl.find("SessionId=(")
if(index > -1):
index = index + 11
index2 = contentUrl.find(")", index+1)
timeNow = time.time()
newContentUrl = contentUrl[:index] + str(timeNow) + contentUrl[index2:]
xbmc.log("mbcon_collection_menuitem_content_" + str(x) + "=" + newContentUrl)
WINDOW.setProperty("mbcon_collection_menuitem_content_" + str(x), newContentUrl)
def updateCollectionArtLinks(self):
self.logMsg("updateCollectionArtLinks Called")
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
mb3Host = addonSettings.getSetting('ipaddress')
mb3Port = addonSettings.getSetting('port')
userName = addonSettings.getSetting('username')
downloadUtils = DownloadUtils()
# get the user ID
userid = downloadUtils.getUserId()
self.logMsg("updateCollectionArtLinks UserID : " + userid)
userUrl = "http://" + mb3Host + ":" + mb3Port + "/mediabrowser/Users/" + userid + "/Items/Root?format=json"
jsonData = downloadUtils.downloadUrl(userUrl, suppress=True, popup=0 )
self.logMsg("updateCollectionArtLinks UserData : " + str(jsonData), 2)
if(len(jsonData) == 0):
return False
result = json.loads(jsonData)
parentid = result.get("Id")
self.logMsg("updateCollectionArtLinks ParentID : " + str(parentid), 2)
userRootPath = ("http://" + mb3Host + ":" + mb3Port +
"/mediabrowser/Users/" + userid +
"/items?ParentId=" + parentid +
"&SortBy=SortName&Fields=CollectionType,RecursiveItemCount&format=json")
jsonData = downloadUtils.downloadUrl(userRootPath, suppress=True, popup=0 )
self.logMsg("updateCollectionArtLinks userRootPath : " + str(jsonData), 2)
result = json.loads(jsonData)
result = result.get("Items")
artLinks = {}
collection_count = 0
WINDOW = xbmcgui.Window( 10000 )
# process collections
for item in result:
collectionType = item.get("CollectionType", "")
name = item.get("Name")
childCount = item.get("RecursiveItemCount")
self.logMsg("updateCollectionArtLinks Name : " + name, level=1)
self.logMsg("updateCollectionArtLinks RecursiveItemCount : " + str(childCount), level=1)
if(childCount == None or childCount == 0):
continue
self.logMsg("updateCollectionArtLinks Processing Collection : " + name + " of type : " + collectionType, level=2)
#####################################################################################################
# Process collection item menu item
timeNow = time.time()
contentUrl = "plugin://plugin.video.mbcon?mode=WIDGET_CONTENT&ParentId=" + item.get("Id") + "&CollectionType=" + collectionType + "&SessionId=(" + str(timeNow) + ")"
actionUrl = ("ActivateWindow(VideoLibrary, plugin://plugin.video.mbcon/?mode=PARENT_CONTENT&ParentId=" + item.get("Id") + "&Name=" + name + ",return)").encode('utf-8')
xbmc.log("COLLECTION actionUrl: " + actionUrl)
WINDOW.setProperty("mbcon_collection_menuitem_name_" + str(collection_count), name)
WINDOW.setProperty("mbcon_collection_menuitem_action_" + str(collection_count), actionUrl)
WINDOW.setProperty("mbcon_collection_menuitem_collection_" + str(collection_count), name)
WINDOW.setProperty("mbcon_collection_menuitem_content_" + str(collection_count), contentUrl)
#####################################################################################################
#####################################################################################################
# Process collection item backgrounds
collectionUrl = ("http://" + mb3Host + ":" + mb3Port +
"/mediabrowser/Users/" + userid +
"/items?ParentId=" + item.get("Id") +
"&IncludeItemTypes=Movie,Series&Fields=ParentId,Overview&Recursive=true&CollapseBoxSetItems=false&format=json")
jsonData = downloadUtils.downloadUrl(collectionUrl, suppress=False, popup=1 )
collectionResult = json.loads(jsonData)
collectionResult = collectionResult.get("Items")
if(collectionResult == None):
collectionResult = []
for col_item in collectionResult:
id = col_item.get("Id")
name = col_item.get("Name")
images = col_item.get("BackdropImageTags")
# store item info
itemData = ItemInfoData()
itemData.Name = col_item.get("Name")
itemData.Plot = col_item.get("Overview")
self.item_details_store[id] = itemData
if(images != None and len(images) > 0):
stored_item = artLinks.get(id)
if(stored_item == None):
stored_item = {}
collections = []
collections.append(item.get("Name"))
stored_item["collections"] = collections
links = []
images = col_item.get("BackdropImageTags")
parentID = col_item.get("ParentId")
name = col_item.get("Name")
if (images == None):
images = []
index = 0
# build poster image link
posterImage = ""
actionUrl = ""
if(col_item.get("Type") == "Movie" or col_item.get("Type") == "MusicVideo" or col_item.get("Type") == "Video"):
posterImage = downloadUtils.getArtwork(col_item, "Primary")
url = mb3Host + ":" + mb3Port + ',;' + id
url = urllib.quote(url)
#actionUrl = "ActivateWindow(VideoLibrary, plugin://plugin.video.mbcon/?mode=PLAY&url=" + url + " ,return)"
actionUrl = "RunPlugin(plugin://plugin.video.mbcon/?mode=PLAY&url=" + url + ")"
elif(col_item.get("Type") == "Series"):
posterImage = downloadUtils.getArtwork(col_item, "Primary")
actionUrl = "ActivateWindow(VideoLibrary, plugin://plugin.video.mbcon/?mode=PARENT_CONTENT&ParentId=" + id + "&Name=" + name + ",return)"
# action is show info
selectAction = addonSettings.getSetting('selectAction')
if(selectAction == "1"):
actionUrl = "RunPlugin(plugin://plugin.video.mbcon/?id=" + id + "&mode=ITEM_DETAILS)"
for backdrop in images:
info = {}
info["url"] = downloadUtils.getArtwork(col_item, "Backdrop", index=str(index))
info["poster"] = posterImage
info["action"] = actionUrl
info["index"] = index
info["id"] = id
info["parent"] = parentID
info["name"] = name
links.append(info)
index = index + 1
stored_item["links"] = links
artLinks[id] = stored_item
else:
stored_item["collections"].append(item.get("Name"))
#####################################################################################################
collection_count = collection_count + 1
# build global link list
final_global_art = []
art_items = {}
for id in artLinks:
item = artLinks.get(id)
collections = item.get("collections")
links = item.get("links")
art_items[id] = links
for link_item in links:
link_item["collections"] = collections
final_global_art.append(link_item)
#xbmc.log("COLLECTION_DATA GROUPS " + str(link_item))
self.global_art_links = final_global_art
random.shuffle(self.global_art_links)
self.item_art_links = art_items
self.logMsg("Background Global Art Links : " + str(len(self.global_art_links)))
self.logMsg("Background Item Data Store Size : " + str(len(self.item_details_store)))
return True
def setItemDetailsProps(self):
id = xbmc.getInfoLabel('ListItem.Property(ItemGUID)')
self.logMsg("setItemDetailsProps ItemGUID : " + id, 0)
if id != None and id != "":
WINDOW = xbmcgui.Window( 10000 )
itemData = self.item_details_store.get(id)
if(itemData != None):
WINDOW.setProperty("MB3.Selected.Item.Name", itemData.Name)
WINDOW.setProperty("MB3.Selected.Item.Plot", itemData.Plot)
#self.logMsg("MB3.Selected.Item.Name=" + itemData.Name, 0)
else:
#self.logMsg("MB3.Selected.Item.Name Cleared", 0)
WINDOW.clearProperty("MB3.Selected.Item.Name")
WINDOW.clearProperty("MB3.Selected.Item.Plot")
def setItemBackgroundLink(self):
id = xbmc.getInfoLabel('ListItem.Property(ItemGUID)')
self.logMsg("setItemBackgroundLink ItemGUID : " + id, 1)
WINDOW = xbmcgui.Window( 10000 )
if id != None and id != "":
listOfBackgrounds = self.item_art_links.get(id)
# if for some reson the item is not in the cache try to load it now
if(listOfBackgrounds == None or len(listOfBackgrounds) == 0):
self.loadItemBackgroundLinks(id)
listOfBackgrounds = self.item_art_links.get(id)
if(listOfBackgrounds != None and len(listOfBackgrounds) > 0):
self.logMsg("setItemBackgroundLink Image " + str(self.current_item_art + 1) + " of " + str(len(listOfBackgrounds)), 1)
try:
artUrl = listOfBackgrounds[self.current_item_art]["url"]
except IndexError:
self.current_item_art = 0
artUrl = listOfBackgrounds[self.current_item_art]["url"]
WINDOW.setProperty("MB3.Background.Item.FanArt", artUrl)
self.logMsg("setItemBackgroundLink MB3.Background.Item.FanArt=" + artUrl, 1)
self.current_item_art = self.current_item_art + 1
if(self.current_item_art == len(listOfBackgrounds)):
self.current_item_art = 0
else:
self.logMsg("setItemBackgroundLink Resetting MB3.Background.Item.FanArt", 1)
WINDOW.clearProperty("MB3.Background.Item.FanArt")
else:
self.logMsg("setItemBackgroundLink Resetting MB3.Background.Item.FanArt", 1)
WINDOW.clearProperty("MB3.Background.Item.FanArt")
def loadItemBackgroundLinks(self, id):
if(id == None or len(id) == 0):
self.logMsg("loadItemBackgroundLinks id was empty")
return
self.logMsg("loadItemBackgroundLinks Called for id : " + id)
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
mb3Host = addonSettings.getSetting('ipaddress')
mb3Port = addonSettings.getSetting('port')
userName = addonSettings.getSetting('username')
downloadUtils = DownloadUtils()
userid = downloadUtils.getUserId()
itemUrl = "http://" + mb3Host + ":" + mb3Port + "/mediabrowser/Users/" + userid + "/Items/" + id + "?Fields=ParentId,Overview&format=json"
jsonData = downloadUtils.downloadUrl(itemUrl, suppress=False, popup=1 )
item = json.loads(jsonData)
self.logMsg("loadItemBackgroundLinks found item : " + str(item), 2);
if(item == None):
item = []
#for item in result:
images = item.get("BackdropImageTags")
id = item.get("Id")
urlid = id
parentID = item.get("ParentId")
origid = id
name = item.get("Name")
if (images == None or images == []):
images = item.get("ParentBackdropImageTags")
urlid = item.get("ParentBackdropItemId")
if (images == None):
images = []
index = 0
url = mb3Host + ":" + mb3Port + ',;' + id
url = urllib.quote(url)
actionUrl = "RunPlugin(plugin://plugin.video.mbcon/?mode=PLAY&url=" + url + ")"
posterImage = downloadUtils.getArtwork(item, "Primary")
# action is show info
selectAction = addonSettings.getSetting('selectAction')
if(selectAction == "1"):
actionUrl = "RunPlugin(plugin://plugin.video.mbcon/?id=" + id + "&mode=ITEM_DETAILS)"
newBgLinks = []
for backdrop in images:
info = {}
info["url"] = downloadUtils.getArtwork(item, "Backdrop", index=str(index))
info["poster"] = posterImage
info["action"] = actionUrl
info["index"] = index
info["id"] = urlid
info["parent"] = parentID
info["name"] = name
self.logMsg("BG Item Image Info : " + str(info), level=2)
newBgLinks.append(info)
index = index + 1
if(len(newBgLinks) > 0):
self.item_art_links[origid] = newBgLinks
#store item info
itemData = ItemInfoData()
itemData.Name = item.get("Name")
itemData.Plot = item.get("Overview")
self.item_details_store[id] = itemData
class ItemInfoData:
Name = ""
Plot = ""

View File

@@ -13,7 +13,7 @@ class ClientInformation():
if(clientId == None or clientId == ""):
xbmc.log("CLIENT_ID - > No Client ID in WINDOW")
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
clientId = addonSettings.getSetting("client_id")
if(clientId == None or clientId == ""):
@@ -30,5 +30,5 @@ class ClientInformation():
return clientId
def getVersion(self):
version = xbmcaddon.Addon(id="plugin.video.mbcon").getAddonInfo("version")
version = xbmcaddon.Addon(id="plugin.video.embycon").getAddonInfo("version")
return version

View File

@@ -19,8 +19,8 @@ class DataManager():
logLevel = 0
def __init__(self, *args):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
level = addonSettings.getSetting('logLevel')
self.logLevel = 0
if(level != None):
@@ -59,7 +59,7 @@ class DataManager():
self.logMsg(itemString, level=2)
dataHashString = dataHashString + itemString
else:
itemCount = itemCount + item.get("RecursiveItemCount")
itemCount = itemCount + item.get("RecursiveItemCount", 0)
unwatchedItemCount = unwatchedItemCount + userData.get("UnplayedItemCount")
PlayedPercentage = userData.get("PlayedPercentage")
if PlayedPercentage == None:
@@ -90,7 +90,7 @@ class DataManager():
urlHash = m.hexdigest()
# build cache data path
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__addon__ = xbmcaddon.Addon(id='plugin.video.embycon')
__addondir__ = xbmc.translatePath( __addon__.getAddonInfo('profile'))
if not os.path.exists(os.path.join(__addondir__, "cache")):
os.makedirs(os.path.join(__addondir__, "cache"))
@@ -141,8 +141,8 @@ class CacheManagerThread(threading.Thread):
logLevel = 0
def __init__(self, *args):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
level = addonSettings.getSetting('logLevel')
self.logLevel = 0
if(level != None):

View File

@@ -14,7 +14,7 @@ def loadSkinDefaults():
defaultViewData = {}
# load current default views
# add a hash of xbmc.getSkinDir() to file name to make it skin specific
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__addon__ = xbmcaddon.Addon(id='plugin.video.embycon')
__addondir__ = xbmc.translatePath( __addon__.getAddonInfo('profile'))
view_list_path = os.path.join(__addondir__, "default_views.json")
if os.path.exists(view_list_path):
@@ -106,7 +106,7 @@ class DefaultViews(xbmcgui.WindowXMLDialog):
self.setViewId("Seasons", 3013)
self.setViewId("Episodes", 3014)
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__addon__ = xbmcaddon.Addon(id='plugin.video.embycon')
__addondir__ = xbmc.translatePath( __addon__.getAddonInfo('profile'))
view_list_path = os.path.join(__addondir__, "default_views.json")
dataFile = open(view_list_path, 'w')

View File

@@ -1,95 +0,0 @@
import xbmcplugin
import xbmcgui
import xbmcaddon
import xbmc
import threading
import sys
class DisplayItems(xbmcgui.WindowXMLDialog):
actionThread = None
def __init__(self,strXMLname, strFallbackPath, strDefaultName, forceFallback):
# Changing the three varibles passed won't change, anything
# Doing strXMLname = "bah.xml" will not change anything.
# don't put GUI sensitive stuff here (as the xml hasn't been read yet
# Idea to initialize your variables here
pass
def onInit(self):
# Put your List Populating code/ and GUI startup stuff here
self.actionThread = BackgroundItemThread()
self.actionThread.setWindow(self)
self.actionThread.start()
pass
def onAction(self, action):
aId = action.getId()
#xbmc.log("Windows Action : " + str(aId))
if aId == 10 or aId == 92:
self.close()
else:
pass
def onClick(self, controlID):
"""
Notice: onClick not onControl
Notice: it gives the ID of the control not the control object
"""
pass
def onFocus(self, controlID):
pass
class BackgroundItemThread(threading.Thread):
rootWindow = None
def setWindow(self, window):
self.rootWindow = window
def run(self):
xbmc.log("BackgroundItemThread Started")
#self.rootWindow.setProperty('content','movies')
#xbmc.executebuiltin("Container.SetContent(movies)")
#xbmc.executebuiltin("Container.SetViewMode(522)")
itemList = self.rootWindow.getControl(50)
thumbPath = "http://192.168.0.27:8096/mediabrowser/Items/924b2d98a64ae17fc31417b3cce02783/Images/Primary/0/0e5801646b3f1b8361a8bc73ff86a9e4/original/10000/10000/0"
for x in range(0, 500):
listItem = xbmcgui.ListItem(label="Test-" + str(x), label2="Test2-" + str(x), iconImage=thumbPath, thumbnailImage=thumbPath)
infolabels = { "title": "My Movie-" + str(x), "Plot": "Some plot inof", "plotoutline": "short plot", "tvshowtitle": "My TV Title", "originaltitle": "Original Title"}
listItem.setInfo( type="movies", infoLabels=infolabels )
listItem.setProperty('IsPlayable', 'true')
#selected = itemList.getSelectedItem()
selected = itemList.getSelectedPosition()
xbmc.log("SELECTED 01: " + str(selected))
itemList.addItem(listItem)
if(selected != -1):
#item = itemList.getListItem(selected)
#selected = itemList.getSelectedItem()
#xbmc.log("SELECTED 02: " + str(item))
itemList.selectItem(selected)
#item.select(True)
xbmc.sleep(200)
xbmc.log("BackgroundItemThread Exiting")

View File

@@ -18,7 +18,7 @@ class DownloadUtils():
getString = None
def __init__(self, *args):
self.addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
self.getString = self.addonSettings.getLocalizedString
level = self.addonSettings.getSetting('logLevel')
self.logLevel = 0

View File

@@ -50,17 +50,13 @@ import xbmcaddon
import xbmc
from DownloadUtils import DownloadUtils
from ItemInfo import ItemInfo
from Utils import PlayUtils
from ClientInformation import ClientInformation
from PersonInfo import PersonInfo
from SearchDialog import SearchDialog
from DisplayItems import DisplayItems
from DataManager import DataManager
import DefaultViews
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__settings__ = xbmcaddon.Addon(id='plugin.video.embycon')
__addon__ = xbmcaddon.Addon(id='plugin.video.embycon')
__language__ = __addon__.getLocalizedString
__addondir__ = xbmc.translatePath( __addon__.getAddonInfo('profile'))
__cwd__ = __settings__.getAddonInfo('path')
@@ -138,16 +134,8 @@ def mainEntryPoint():
xbmc.executebuiltin("Container.Refresh")
elif sys.argv[1] == "showsetviews":
showSetViews()
elif mode == "CAST_LIST":
getCastList(sys.argv[0], int(sys.argv[1]), params)
elif mode == "PERSON_DETAILS":
showPersonInfo(sys.argv[0], int(sys.argv[1]), params)
elif mode == "WIDGET_CONTENT":
getWigetContent(sys.argv[0], int(sys.argv[1]), params)
elif mode == "ITEM_DETAILS":
showItemInfo(sys.argv[0], int(sys.argv[1]), params)
elif mode == "SHOW_SEARCH":
showSearch(sys.argv[0], int(sys.argv[1]), params)
elif mode == "PARENT_CONTENT":
#ptvsd.enable_attach(secret = "shaun")
#ptvsd.wait_for_attach()
@@ -385,19 +373,13 @@ def addGUIItem( url, details, extraData, folder=True ):
else:
mode="&mode=%s" % extraData['mode']
# play or show info
selectAction = __settings__.getSetting('selectAction')
#Create the URL to pass to the item
if 'SETVIEWS' in url:
u = sys.argv[0] + "?url=" + url + '&mode=SETVIEWS'
elif url.startswith('http'):
u = sys.argv[0] + "?url=" + urllib.quote(url) + mode
else:
if(selectAction == "1"):
u = sys.argv[0] + "?id=" + extraData.get('id') + "&mode=ITEM_DETAILS"
else:
u = sys.argv[0] + "?url=" + url + '&mode=PLAY'
u = sys.argv[0] + "?url=" + url + '&mode=PLAY'
#Create the ListItem that will be displayed
thumbPath=str(extraData.get('thumb',''))
@@ -534,7 +516,7 @@ def addContextMenu(details, extraData, folder):
if item_id != None:
scriptToRun = PLUGINPATH + "/default.py"
pluginCastLink = "XBMC.Container.Update(plugin://plugin.video.mbcon?mode=CAST_LIST&id=" + str(extraData.get('id')) + ")"
pluginCastLink = "XBMC.Container.Update(plugin://plugin.video.embycon?mode=CAST_LIST&id=" + str(extraData.get('id')) + ")"
commands.append(("Show People", pluginCastLink))
# watched/unwatched
@@ -1188,7 +1170,7 @@ def getCastList(pluginName, handle, params):
else:
item = xbmcgui.ListItem(label=displayName)
actionUrl = "plugin://plugin.video.mbcon?mode=PERSON_DETAILS&name=" + baseName
actionUrl = "plugin://plugin.video.embycon?mode=PERSON_DETAILS&name=" + baseName
item.setProperty('IsPlayable', 'false')
item.setProperty('IsFolder', 'false')
@@ -1198,7 +1180,7 @@ def getCastList(pluginName, handle, params):
url = "http://" + host + ":" + port + "/mediabrowser/Users/" + userid + "/Items/?Recursive=True&Person=PERSON_NAME&Fields=" + detailsString + "&format=json"
url = urllib.quote(url)
url = url.replace("PERSON_NAME", baseName)
pluginCastLink = "XBMC.Container.Update(plugin://plugin.video.mbcon?mode=GET_CONTENT&url=" + url + ")"
pluginCastLink = "XBMC.Container.Update(plugin://plugin.video.embycon?mode=GET_CONTENT&url=" + url + ")"
commands.append(( "Show Other Library Items", pluginCastLink))
item.addContextMenuItems( commands, True )
@@ -1210,56 +1192,12 @@ def getCastList(pluginName, handle, params):
xbmcplugin.addDirectoryItems(handle, listItems)
xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
def showItemInfo(pluginName, handle, params):
printDebug("showItemInfo Called" + str(params))
xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
infoPage = ItemInfo("ItemInfo.xml", __cwd__, "default", "720p")
infoPage.setId(params.get("id"))
infoPage.doModal()
if(infoPage.containerNeedsRefresh):
printDebug("showItemInfo Sending container refresh")
#WINDOW = xbmcgui.Window( 10000 )
#WINDOW.setProperty("force_data_reload", "true")
xbmc.executebuiltin("Container.Refresh")
del infoPage
def showSearch(pluginName, handle, params):
printDebug("showSearch Called" + str(params))
xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
searchDialog = SearchDialog("SearchDialog.xml", __cwd__, "default", "720p")
searchDialog.doModal()
del searchDialog
#items = DisplayItems("DisplayItems.xml", __cwd__, "default", "720p")
#items.doModal()
#del items
def showSetViews():
printDebug("showSetViews Called")
defaultViews = DefaultViews.DefaultViews("DefaultViews.xml", __cwd__, "default", "720p")
defaultViews.doModal()
del defaultViews
def showPersonInfo(pluginName, handle, params):
printDebug("showPersonInfo Called" + str(params))
xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
infoPage = PersonInfo("PersonInfo.xml", __cwd__, "default", "720p")
infoPage.setPersonName(params.get("name"))
infoPage.doModal()
if(infoPage.showMovies == True):
xbmc.log("RUNNING_PLUGIN: " + infoPage.pluginCastLink)
xbmc.executebuiltin(infoPage.pluginCastLink)
del infoPage
def getWigetContent(pluginName, handle, params):
printDebug("getWigetContent Called" + str(params))
@@ -1406,12 +1344,8 @@ def getWigetContent(pluginName, handle, params):
cappedPercentage = 90
list_item.setProperty("complete_percentage", str(cappedPercentage))
selectAction = __settings__.getSetting('selectAction')
if(selectAction == "1"):
playUrl = "plugin://plugin.video.mbcon/?id=" + item_id + '&mode=ITEM_DETAILS'
else:
url = server + ',;' + item_id
playUrl = "plugin://plugin.video.mbcon/?url=" + url + '&mode=PLAY'
url = server + ',;' + item_id
playUrl = "plugin://plugin.video.embycon/?url=" + url + '&mode=PLAY'
itemTupple = (playUrl, list_item, False)
listItems.append(itemTupple)

View File

@@ -1,316 +0,0 @@
import sys
import xbmc
import xbmcgui
import xbmcaddon
import json as json
import urllib
from DownloadUtils import DownloadUtils
class ItemInfo(xbmcgui.WindowXMLDialog):
id = ""
playUrl = ""
downloadUtils = DownloadUtils()
itemWatched = False
itemFavorite = False
containerNeedsRefresh = False
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
xbmc.log("WINDOW INITIALISED")
def onInit(self):
self.action_exitkeys_id = [10, 13]
self.updateContent()
def setId(self, id):
self.id = id
def onFocus(self, controlId):
pass
def doAction(self):
pass
def closeDialog(self):
self.close()
def onClick(self, controlID):
if(controlID == 3002):
# close all dialogs when playing an item
xbmc.executebuiltin("Dialog.Close(all,true)")
xbmc.executebuiltin("RunPlugin(" + self.playUrl + ")")
self.close()
elif(controlID == 3230):
peopleList = self.getControl(3230)
item = peopleList.getSelectedItem()
action = item.getProperty("ActionUrl")
xbmc.log(action)
xbmc.executebuiltin("RunPlugin(" + action + ")")
elif(controlID == 3004):
xbmc.log("Item_Info Setting watched state")
self.containerNeedsRefresh = True
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
port = __settings__.getSetting('port')
host = __settings__.getSetting('ipaddress')
server = host + ":" + port
userId = self.downloadUtils.getUserId()
if(self.itemWatched == True):
url = "http://" + server + "/mediabrowser/Users/" + userId + "/PlayedItems/" + self.id
self.downloadUtils.downloadUrl(url, type="DELETE")
xbmc.log("Item_Info Sent DELETE request : " + url)
else:
url = "http://" + server + "/mediabrowser/Users/" + userId + "/PlayedItems/" + self.id
self.downloadUtils.downloadUrl(url, postBody="", type="POST")
xbmc.log("Item_Info Sent POST request : " + url)
self.updateContent()
elif(controlID == 3005):
xbmc.log("Item_Info Setting fav state")
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
port = __settings__.getSetting('port')
host = __settings__.getSetting('ipaddress')
server = host + ":" + port
self.containerNeedsRefresh = True
userId = self.downloadUtils.getUserId()
if(self.itemFavorite == True):
url = "http://" + server + "/mediabrowser/Users/" + userId + "/FavoriteItems/" + self.id
self.downloadUtils.downloadUrl(url, type="DELETE")
xbmc.log("Item_Info Sent DELETE request : " + url)
else:
url = "http://" + server + "/mediabrowser/Users/" + userId + "/FavoriteItems/" + self.id
self.downloadUtils.downloadUrl(url, postBody="", type="POST")
xbmc.log("Item_Info Sent POST request : " + url)
self.updateContent()
elif(controlID == 3006):
xbmc.log("Item_Info Setting play position")
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
port = __settings__.getSetting('port')
host = __settings__.getSetting('ipaddress')
server = host + ":" + port
userId = self.downloadUtils.getUserId()
url = "http://" + server + "/mediabrowser/Users/" + userId + "/PlayingItems/" + self.id + "/Progress?PositionTicks=0"
self.downloadUtils.downloadUrl(url, postBody="", type="POST")
self.containerNeedsRefresh = True
self.updateContent()
pass
def updateContent(self):
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
port = __settings__.getSetting('port')
host = __settings__.getSetting('ipaddress')
server = host + ":" + port
userid = self.downloadUtils.getUserId()
jsonData = self.downloadUtils.downloadUrl("http://" + server + "/mediabrowser/Users/" + userid + "/Items/" + self.id + "?format=json", suppress=False, popup=1 )
item = json.loads(jsonData)
id = item.get("Id")
name = item.get("Name")
image = self.downloadUtils.getArtwork(item, "Primary")
fanArt = self.downloadUtils.getArtwork(item, "Backdrop")
# calculate the percentage complete
userData = item.get("UserData")
cappedPercentage = 0
itemPlayed = False
itemIsFavorite = False
if(userData != None):
itemPlayed = userData.get("Played")
itemIsFavorite = userData.get("IsFavorite")
playBackTicks = float(userData.get("PlaybackPositionTicks"))
if(playBackTicks != None and playBackTicks > 0):
runTimeTicks = float(item.get("RunTimeTicks", "0"))
if(runTimeTicks > 0):
percentage = int((playBackTicks / runTimeTicks) * 100.0)
cappedPercentage = percentage
'''
cappedPercentage = percentage - (percentage % 10)
if(cappedPercentage == 0):
cappedPercentage = 10
if(cappedPercentage == 100):
cappedPercentage = 90
'''
# set matched button text
if(itemPlayed):
self.getControl(3004).setLabel("Watched")
self.itemWatched = True
else:
self.getControl(3004).setLabel("Not Watched")
self.itemWatched = False
# set Favorite button text
if(itemIsFavorite):
self.getControl(3005).setLabel("Favorite")
self.itemFavorite = True
else:
self.getControl(3005).setLabel("Not Favorite")
self.itemFavorite = False
# set reset play position button
if(cappedPercentage == None or cappedPercentage == 0):
self.getControl(3006).setEnabled(False)
episodeInfo = ""
type = item.get("Type")
if(type == "Episode" or type == "Season"):
name = item.get("SeriesName") + ": " + name
season = str(item.get("ParentIndexNumber")).zfill(2)
episodeNum = str(item.get("IndexNumber")).zfill(2)
episodeInfo = "S" + season + "xE" + episodeNum
url = server + ',;' + id
url = urllib.quote(url)
self.playUrl = "plugin://plugin.video.mbcon/?url=" + url + '&mode=PLAY'
self.peopleUrl = "XBMC.Container.Update(plugin://plugin.video.mbcon?mode=CAST_LIST&id=" + id + ")"
#self.peopleUrl = "XBMC.RunPlugin(plugin://plugin.video.mbcon?mode=CAST_LIST&id=" + id + ")"
# all all the media stream info
mediaList = self.getControl(3220)
mediaList.reset()
mediaStreams = item.get("MediaStreams")
if(mediaStreams != None):
for mediaStream in mediaStreams:
if(mediaStream.get("Type") == "Video"):
videocodec = mediaStream.get("Codec")
if(videocodec == "mpeg2video"):
videocodec = "mpeg2"
height = str(mediaStream.get("Height"))
width = str(mediaStream.get("Width"))
aspectratio = mediaStream.get("AspectRatio")
fr = mediaStream.get("RealFrameRate")
videoInfo = width + "x" + height + " " + videocodec + " " + str(round(fr, 2))
listItem = xbmcgui.ListItem("Video:", videoInfo)
mediaList.addItem(listItem)
if(mediaStream.get("Type") == "Audio"):
audiocodec = mediaStream.get("Codec")
channels = mediaStream.get("Channels")
lang = mediaStream.get("Language")
audioInfo = audiocodec + " " + str(channels)
if(lang != None and len(lang) > 0 and lang != "und"):
audioInfo = audioInfo + " " + lang
listItem = xbmcgui.ListItem("Audio:", audioInfo)
mediaList.addItem(listItem)
if(mediaStream.get("Type") == "Subtitle"):
lang = mediaStream.get("Language")
codec = mediaStream.get("Codec")
subInfo = codec
if(lang != None and len(lang) > 0 and lang != "und"):
subInfo = subInfo + " " + lang
listItem = xbmcgui.ListItem("Sub:", subInfo)
mediaList.addItem(listItem)
#for x in range(0, 10):
# listItem = xbmcgui.ListItem("Test:", "Test 02 " + str(x))
# mediaList.addItem(listItem)
# add overview
overview = item.get("Overview")
self.getControl(3223).setText(overview)
# add people
peopleList = self.getControl(3230)
peopleList.reset()
people = item.get("People")
for person in people:
displayName = person.get("Name")
role = person.get("Role")
id = person.get("Id")
tag = person.get("PrimaryImageTag")
baseName = person.get("Name")
baseName = baseName.replace(" ", "+")
baseName = baseName.replace("&", "_")
baseName = baseName.replace("?", "_")
baseName = baseName.replace("=", "_")
actionUrl = "plugin://plugin.video.mbcon?mode=PERSON_DETAILS&name=" + baseName
if(tag != None and len(tag) > 0):
thumbPath = self.downloadUtils.imageUrl(id, "Primary", 0, 400, 400, tag)
listItem = xbmcgui.ListItem(label=displayName, label2=role, iconImage=thumbPath, thumbnailImage=thumbPath)
else:
listItem = xbmcgui.ListItem(label=displayName, label2=role)
listItem.setProperty("ActionUrl", actionUrl)
peopleList.addItem(listItem)
# add general info
infoList = self.getControl(3226)
listItem = xbmcgui.ListItem("Year:", str(item.get("ProductionYear")))
infoList.addItem(listItem)
listItem = xbmcgui.ListItem("Rating:", str(item.get("CommunityRating")))
infoList.addItem(listItem)
listItem = xbmcgui.ListItem("MPAA:", str(item.get("OfficialRating")))
infoList.addItem(listItem)
duration = str(int(item.get("RunTimeTicks", "0"))/(10000000*60))
listItem = xbmcgui.ListItem("RunTime:", str(duration) + " Minutes")
infoList.addItem(listItem)
genre = ""
genres = item.get("Genres")
if(genres != None):
for genre_string in genres:
if genre == "": #Just take the first genre
genre = genre_string
else:
genre = genre + " / " + genre_string
listItem = xbmcgui.ListItem("Genre:", genre)
infoList.addItem(listItem)
path = item.get('Path')
listItem = xbmcgui.ListItem("Path:", path)
infoList.addItem(listItem)
# add resume percentage text to name
addResumePercent = __settings__.getSetting('addResumePercent') == 'true'
if (addResumePercent and cappedPercentage != 0):
name = name + " (" + str(cappedPercentage) + "%)"
self.getControl(3000).setLabel(name)
self.getControl(3003).setLabel(episodeInfo)
self.getControl(3001).setImage(fanArt)
if(type == "Episode"):
self.getControl(3009).setImage(image)
self.getControl(3010).setImage("Progress\progress_" + str(cappedPercentage) + ".png")
else:
self.getControl(3011).setImage(image)
self.getControl(3012).setImage("Progress\progress_" + str(cappedPercentage) + ".png")
# disable play button
if(type == "Season" or type == "Series"):
self.setFocusId(3226)
self.getControl(3002).setEnabled(False)

View File

@@ -1,125 +0,0 @@
#################################################################################################
# menu item loader thread
# this loads the favourites.xml and sets the windows props for the menus to auto display in skins
#################################################################################################
import xbmc
import xbmcgui
import xbmcaddon
import xml.etree.ElementTree as xml
import os
import threading
from datetime import datetime
class LoadMenuOptionsThread(threading.Thread):
logLevel = 0
addonSettings = None
getString = None
def __init__(self, *args):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
self.addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
level = addonSettings.getSetting('logLevel')
self.logLevel = 0
self.getString = self.addonSettings.getLocalizedString
if(level != None):
self.logLevel = int(level)
xbmc.log("MBCon LoadMenuOptionsThread -> Log Level:" + str(self.logLevel))
threading.Thread.__init__(self, *args)
def logMsg(self, msg, level = 1):
if(self.logLevel >= level):
xbmc.log("MBCon LoadMenuOptionsThread -> " + msg)
def run(self):
try:
self.run_internal()
except Exception, e:
xbmcgui.Dialog().ok(self.getString(30205), str(e))
raise
def run_internal(self):
self.logMsg("LoadMenuOptionsThread Started")
lastFavPath = ""
favourites_file = os.path.join(xbmc.translatePath('special://profile'), "favourites.xml")
self.loadMenuOptions(favourites_file)
lastFavPath = favourites_file
try:
lastModLast = os.stat(favourites_file).st_mtime
except:
lastModLast = 0;
lastRun = datetime.today()
while (xbmc.abortRequested == False):
td = datetime.today() - lastRun
secTotal = td.seconds
if(secTotal > 10):
favourites_file = os.path.join(xbmc.translatePath('special://profile'), "favourites.xml")
try:
lastMod = os.stat(favourites_file).st_mtime
except:
lastMod = 0;
if(lastFavPath != favourites_file or lastModLast != lastMod):
self.loadMenuOptions(favourites_file)
lastFavPath = favourites_file
lastModLast = lastMod
lastRun = datetime.today()
xbmc.sleep(500)
self.logMsg("LoadMenuOptionsThread Exited")
def loadMenuOptions(self, pathTofavourites):
self.logMsg("LoadMenuOptionsThread -> Loading menu items from : " + pathTofavourites)
WINDOW = xbmcgui.Window( 10000 )
menuItem = 0
try:
tree = xml.parse(pathTofavourites)
rootElement = tree.getroot()
except Exception, e:
self.logMsg("LoadMenuOptionsThread -> Error Parsing favourites.xml : " + str(e), level=0)
for x in range(0, 10):
WINDOW.setProperty("mbcon_menuitem_name_" + str(x), "")
WINDOW.setProperty("mbcon_menuitem_action_" + str(x), "")
WINDOW.setProperty("mbcon_menuitem_collection_" + str(x), "")
return
for child in rootElement.findall('favourite'):
name = child.get('name')
action = child.text
if(len(name) > 1 and name[0:1] != '-'):
WINDOW.setProperty("mbcon_menuitem_name_" + str(menuItem), name)
WINDOW.setProperty("mbcon_menuitem_action_" + str(menuItem), action)
WINDOW.setProperty("mbcon_menuitem_collection_" + str(menuItem), name)
self.logMsg("mbcon_menuitem_name_" + str(menuItem) + " : " + name)
self.logMsg("mbcon_menuitem_action_" + str(menuItem) + " : " + action)
self.logMsg("mbcon_menuitem_collection_" + str(menuItem) + " : " + name)
menuItem = menuItem + 1
for x in range(menuItem, menuItem+10):
WINDOW.setProperty("mbcon_menuitem_name_" + str(x), "")
WINDOW.setProperty("mbcon_menuitem_action_" + str(x), "")
self.logMsg("mbcon_menuitem_name_" + str(x) + " : ")
self.logMsg("mbcon_menuitem_action_" + str(x) + " : ")
self.logMsg("mbcon_menuitem_collection_" + str(x) + " : ")

View File

@@ -1,185 +0,0 @@
import sys
import xbmc
import xbmcgui
import xbmcaddon
import json as json
import urllib
from DownloadUtils import DownloadUtils
class PersonInfo(xbmcgui.WindowXMLDialog):
pluginCastLink = ""
showMovies = False
personName = ""
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
def onInit(self):
self.action_exitkeys_id = [10, 13]
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
port = __settings__.getSetting('port')
host = __settings__.getSetting('ipaddress')
server = host + ":" + port
downloadUtils = DownloadUtils()
userid = downloadUtils.getUserId()
jsonData = downloadUtils.downloadUrl("http://" + server + "/mediabrowser/Persons/" + self.personName + "?format=json", suppress=False, popup=1 )
result = json.loads(jsonData)
name = result.get("Name")
id = result.get("Id")
# other lib items count
contentCounts = ""
if(result.get("AdultVideoCount") != None and result.get("AdultVideoCount") > 0):
contentCounts = contentCounts + "\nAdult Count : " + str(result.get("AdultVideoCount"))
if(result.get("MovieCount") != None and result.get("MovieCount") > 0):
contentCounts = contentCounts + "\nMovie Count : " + str(result.get("MovieCount"))
if(result.get("SeriesCount") != None and result.get("SeriesCount") > 0):
contentCounts = contentCounts + "\nSeries Count : " + str(result.get("SeriesCount"))
if(result.get("EpisodeCount") != None and result.get("EpisodeCount") > 0):
contentCounts = contentCounts + "\nEpisode Count : " + str(result.get("EpisodeCount"))
if(len(contentCounts) > 0):
contentCounts = "Total Library Counts:" + contentCounts
#overview
overview = ""
if(len(contentCounts) > 0):
overview = contentCounts + "\n\n"
over = result.get("Overview")
if(over == None or over == ""):
overview = overview + "No details available"
else:
overview = overview + over
#person image
image = downloadUtils.getArtwork(result, "Primary")
#get other movies
encoded = name.encode("utf-8")
encoded = urllib.quote(encoded)
url = "http://" + server + "/mediabrowser/Users/" + userid + "/Items/?Recursive=True&Person=" + encoded + "&format=json&IsMissing=false"
xbmc.log("URL: " + url)
jsonData = downloadUtils.downloadUrl(url, suppress=False, popup=1 )
otherMovieResult = json.loads(jsonData)
baseName = name.replace(" ", "+")
baseName = baseName.replace("&", "_")
baseName = baseName.replace("?", "_")
baseName = baseName.replace("=", "_")
#detailsString = getDetailsString()
#search_url = "http://" + host + ":" + port + "/mediabrowser/Users/" + userid + "/Items/?Recursive=True&Person=PERSON_NAME&Fields=" + detailsString + "&format=json"
search_url = "http://" + host + ":" + port + "/mediabrowser/Users/" + userid + "/Items/?Recursive=True&Person=PERSON_NAME&format=json"
search_url = urllib.quote(search_url)
search_url = search_url.replace("PERSON_NAME", baseName)
self.pluginCastLink = "XBMC.Container.Update(plugin://plugin.video.mbcon?mode=GET_CONTENT&url=" + search_url + ")"
otherItemsList = None
try:
otherItemsList = self.getControl(3010)
items = otherMovieResult.get("Items")
if(items == None):
items = []
for item in items:
item_id = item.get("Id")
item_name = item.get("Name")
type_info = ""
image_id = None
image_Tag = None
item_type = item.get("Type")
if(item_type == "Season"):
image_id = item.get("SeriesId")
image_Tag = item.get("SeriesPrimaryImageTag")
season = item.get("IndexNumber")
type_info = "Season " + str(season).zfill(2)
elif(item_type == "Series"):
image_id = item.get("Id")
imageTags = item.get("ImageTags")
if(imageTags != None and imageTags.get("Primary") != None):
image_Tag = imageTags.get("Primary")
type_info = "Series"
elif(item_type == "Movie"):
image_id = item.get("Id")
imageTags = item.get("ImageTags")
if(imageTags != None and imageTags.get("Primary") != None):
image_Tag = imageTags.get("Primary")
type_info = "Movie"
elif(item_type == "Episode"):
image_id = item.get("SeriesId")
image_Tag = item.get("SeriesPrimaryImageTag")
season = item.get("ParentIndexNumber")
eppNum = item.get("IndexNumber")
type_info = "S" + str(season).zfill(2) + "E" + str(eppNum).zfill(2)
thumbPath = ""
if(image_Tag != None):
thumbPath = downloadUtils.imageUrl(image_id, "Primary", 0, 200, 200, image_Tag)
#thumbPath = downloadUtils.getArtwork(item, "Primary", width=200, height=200)
listItem = xbmcgui.ListItem(label=item_name, label2=type_info, iconImage=thumbPath, thumbnailImage=thumbPath)
actionUrl = "plugin://plugin.video.mbcon?id=" + item_id + "&mode=ITEM_DETAILS"
listItem.setProperty("ActionUrl", actionUrl)
otherItemsList.addItem(listItem)
except Exception, e:
xbmc.log("Exception : " + str(e))
pass
# set the dialog data
self.getControl(3000).setLabel(name)
self.getControl(3001).setText(overview)
self.getControl(3009).setImage(image)
def setPersonName(self, name):
self.personName = name
def setInfo(self, data):
self.details = data
def onFocus(self, controlId):
pass
def doAction(self):
pass
def closeDialog(self):
self.close()
def onClick(self, controlID):
if(controlID == 3002):
self.showMovies = True
xbmc.executebuiltin('Dialog.Close(movieinformation)')
self.close()
elif(controlID == 3010):
#xbmc.executebuiltin("Dialog.Close(all,true)")
itemList = self.getControl(3010)
item = itemList.getSelectedItem()
action = item.getProperty("ActionUrl")
xbmc.executebuiltin("RunPlugin(" + action + ")")
self.close()
pass

View File

@@ -1,348 +0,0 @@
import sys
import xbmc
import xbmcgui
import xbmcaddon
import json as json
import urllib
from DownloadUtils import DownloadUtils
import threading
class SearchDialog(xbmcgui.WindowXMLDialog):
searchThread = None
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
def onInit(self):
self.action_exitkeys_id = [10, 13]
self.searchThread = BackgroundSearchThread()
self.searchThread.setDialog(self)
self.searchThread.start()
def onFocus(self, controlId):
pass
def onAction(self, action):
#xbmc.log("onAction : " + str(action.getId()) + " " + str(action.getButtonCode()) + " " + str(action))
ACTION_PREVIOUS_MENU = 10
ACTION_SELECT_ITEM = 7
ACTION_PARENT_DIR = 9
if action == ACTION_PREVIOUS_MENU or action.getId() == 92:
searchTerm = self.getControl(3010).getText()
if(len(searchTerm) == 0):
self.close()
else:
searchTerm = searchTerm[:-1]
self.getControl(3010).setText(searchTerm)
self.searchThread.setSearch(searchTerm)
#self.getControl(3010).setLabel(str(action.getButtonCode()))
def closeDialog(self):
thread.stopRunning()
self.close()
def onClick(self, controlID):
if(controlID == 3020):
self.addCharacter("a")
elif(controlID == 3021):
self.addCharacter("b")
elif(controlID == 3022):
self.addCharacter("c")
elif(controlID == 3023):
self.addCharacter("d")
elif(controlID == 3024):
self.addCharacter("e")
elif(controlID == 3025):
self.addCharacter("f")
elif(controlID == 3026):
self.addCharacter("g")
elif(controlID == 3027):
self.addCharacter("h")
elif(controlID == 3028):
self.addCharacter("i")
elif(controlID == 3029):
self.addCharacter("j")
elif(controlID == 3030):
self.addCharacter("k")
elif(controlID == 3031):
self.addCharacter("l")
elif(controlID == 3032):
self.addCharacter("m")
elif(controlID == 3033):
self.addCharacter("n")
elif(controlID == 3034):
self.addCharacter("o")
elif(controlID == 3035):
self.addCharacter("p")
elif(controlID == 3036):
self.addCharacter("q")
elif(controlID == 3037):
self.addCharacter("r")
elif(controlID == 3038):
self.addCharacter("s")
elif(controlID == 3039):
self.addCharacter("t")
elif(controlID == 3040):
self.addCharacter("u")
elif(controlID == 3041):
self.addCharacter("v")
elif(controlID == 3042):
self.addCharacter("w")
elif(controlID == 3043):
self.addCharacter("x")
elif(controlID == 3044):
self.addCharacter("y")
elif(controlID == 3045):
self.addCharacter("z")
elif(controlID == 3046):
self.addCharacter("0")
elif(controlID == 3047):
self.addCharacter("1")
elif(controlID == 3048):
self.addCharacter("2")
elif(controlID == 3049):
self.addCharacter("3")
elif(controlID == 3050):
self.addCharacter("4")
elif(controlID == 3051):
self.addCharacter("5")
elif(controlID == 3052):
self.addCharacter("6")
elif(controlID == 3053):
self.addCharacter("7")
elif(controlID == 3054):
self.addCharacter("8")
elif(controlID == 3055):
self.addCharacter("9")
elif(controlID == 3056):
searchTerm = self.getControl(3010).getText()
searchTerm = searchTerm[:-1]
self.getControl(3010).setText(searchTerm)
self.searchThread.setSearch(searchTerm)
elif(controlID == 3057):
self.addCharacter(" ")
elif(controlID == 3058):
self.getControl(3010).setText("")
self.searchThread.setSearch("")
elif(controlID == 3010):
searchTerm = self.getControl(3010).getText()
self.searchThread.setSearch(searchTerm)
elif(controlID == 3110):
#xbmc.executebuiltin("Dialog.Close(all,true)")
itemList = self.getControl(3110)
item = itemList.getSelectedItem()
action = item.getProperty("ActionUrl")
xbmc.executebuiltin("RunPlugin(" + action + ")")
elif(controlID == 3111):
#xbmc.executebuiltin("Dialog.Close(all,true)")
itemList = self.getControl(3111)
item = itemList.getSelectedItem()
action = item.getProperty("ActionUrl")
xbmc.executebuiltin("RunPlugin(" + action + ")")
elif(controlID == 3112):
#xbmc.executebuiltin("Dialog.Close(all,true)")
itemList = self.getControl(3112)
item = itemList.getSelectedItem()
action = item.getProperty("ActionUrl")
xbmc.executebuiltin("RunPlugin(" + action + ")")
pass
def addCharacter(self, char):
searchTerm = self.getControl(3010).getText()
searchTerm = searchTerm + char
self.getControl(3010).setText(searchTerm)
self.searchThread.setSearch(searchTerm)
class BackgroundSearchThread(threading.Thread):
active = True
searchDialog = None
searchString = ""
def __init__(self, *args):
#xbmc.log("BackgroundSearchThread Init")
threading.Thread.__init__(self, *args)
def setSearch(self, searchFor):
self.searchString = searchFor
def stopRunning(self):
self.active = False
def setDialog(self, searchDialog):
self.searchDialog = searchDialog
def run(self):
#xbmc.log("BackgroundSearchThread Started")
lastSearchString = ""
while(xbmc.abortRequested == False and self.active == True):
currentSearch = self.searchString
if(currentSearch != lastSearchString):
lastSearchString = currentSearch
self.doSearch(currentSearch)
xbmc.sleep(2000)
#xbmc.log("BackgroundSearchThread Exited")
def doSearch(self, searchTerm):
movieResultsList = self.searchDialog.getControl(3110)
while(movieResultsList.size() > 0):
movieResultsList.removeItem(0)
#movieResultsList.reset()
seriesResultsList = self.searchDialog.getControl(3111)
while(seriesResultsList.size() > 0):
seriesResultsList.removeItem(0)
#seriesResultsList.reset()
episodeResultsList = self.searchDialog.getControl(3112)
while(episodeResultsList.size() > 0):
episodeResultsList.removeItem(0)
#episodeResultsList.reset()
if(len(searchTerm) == 0):
return
__settings__ = xbmcaddon.Addon(id='plugin.video.mbcon')
port = __settings__.getSetting('port')
host = __settings__.getSetting('ipaddress')
server = host + ":" + port
downloadUtils = DownloadUtils()
#
# Process movies
#
search = urllib.quote(searchTerm)
url = "http://" + server + "/mediabrowser/Search/Hints?SearchTerm=" + search + "&Limit=10&IncludeItemTypes=Movie&format=json"
jsonData = downloadUtils.downloadUrl(url, suppress=False, popup=1)
result = json.loads(jsonData)
items = result.get("SearchHints")
if(items == None or len(items) == 0):
item = []
for item in items:
#xbmc.log("Search_Result_Item : " + str(item))
item_id = item.get("ItemId")
item_name = item.get("Name")
item_type = item.get("Type")
item_Tag = item.get("PrimaryImageTag")
typeLabel = "Movie"
thumbPath = ""
if(item_Tag != None):
thumbPath = downloadUtils.imageUrl(item_id, "Primary", 0, 200, 200, item_Tag)
#xbmc.log(thumbPath)
listItem = xbmcgui.ListItem(label=item_name, label2=typeLabel, iconImage=thumbPath, thumbnailImage=thumbPath)
actionUrl = "plugin://plugin.video.mbcon?id=" + item_id + "&mode=ITEM_DETAILS"
listItem.setProperty("ActionUrl", actionUrl)
movieResultsList.addItem(listItem)
#
# Process series
#
search = urllib.quote(searchTerm)
url = "http://" + server + "/mediabrowser/Search/Hints?SearchTerm=" + search + "&Limit=10&IncludeItemTypes=Series&format=json"
jsonData = downloadUtils.downloadUrl(url, suppress=False, popup=1 )
result = json.loads(jsonData)
items = result.get("SearchHints")
if(items == None or len(items) == 0):
item = []
for item in items:
#xbmc.log(str(item))
item_id = item.get("ItemId")
item_name = item.get("Name")
item_type = item.get("Type")
item_Tag = item.get("PrimaryImageTag")
typeLabel = ""
image_id = ""
image_id = item.get("ItemId")
typeLabel = "Series"
thumbPath = ""
if(item_Tag != None):
thumbPath = downloadUtils.imageUrl(item_id, "Primary", 0, 200, 200, item_Tag)
#xbmc.log(thumbPath)
listItem = xbmcgui.ListItem(label=item_name, label2=typeLabel, iconImage=thumbPath, thumbnailImage=thumbPath)
actionUrl = "plugin://plugin.video.mbcon?id=" + item_id + "&mode=ITEM_DETAILS"
listItem.setProperty("ActionUrl", actionUrl)
seriesResultsList.addItem(listItem)
#
# Process episodes
#
search = urllib.quote(searchTerm)
url = "http://" + server + "/mediabrowser/Search/Hints?SearchTerm=" + search + "&Limit=10&IncludeItemTypes=Episode&format=json"
jsonData = downloadUtils.downloadUrl(url, suppress=False, popup=1)
result = json.loads(jsonData)
items = result.get("SearchHints")
if(items == None or len(items) == 0):
item = []
for item in items:
#xbmc.log(str(item))
item_id = item.get("ItemId")
item_name = item.get("Name")
item_type = item.get("Type")
item_Tag = item.get("PrimaryImageTag")
image_id = item.get("ThumbImageItemId")
image_tag = item.get("ThumbImageTag")
season = item.get("ParentIndexNumber")
eppNum = item.get("IndexNumber")
typeLabel = "S" + str(season).zfill(2) + "E" + str(eppNum).zfill(2)
thumbPath = ""
if(image_tag != None):
thumbPath = downloadUtils.imageUrl(image_id, "Primary", 0, 200, 200, image_tag)
#xbmc.log(thumbPath)
listItem = xbmcgui.ListItem(label=item_name, label2=typeLabel, iconImage=thumbPath, thumbnailImage=thumbPath)
actionUrl = "plugin://plugin.video.mbcon?id=" + item_id + "&mode=ITEM_DETAILS"
listItem.setProperty("ActionUrl", actionUrl)
episodeResultsList.addItem(listItem)

View File

@@ -21,7 +21,7 @@ class PlayUtils():
def getPlayUrl(self, server, id, result):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
# if the path is local and depending on the video quality play we can direct play it do so-
xbmc.log("MBCon getPlayUrl")
@@ -84,7 +84,7 @@ class PlayUtils():
# get the addon video quality
def getVideoBitRate(self):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
videoQuality = addonSettings.getSetting('videoBitRate')
if (videoQuality == "0"):
return '664'

View File

@@ -21,7 +21,7 @@ class WebSocketThread(threading.Thread):
keepRunning = True
def __init__(self, *args):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
level = addonSettings.getSetting('logLevel')
self.logLevel = 0
if(level != None):
@@ -127,7 +127,7 @@ class WebSocketThread(threading.Thread):
startPositionTicks = data.get("StartPositionTicks")
self.logMsg("Playing Media With ID : " + itemIds[0])
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
mb3Host = addonSettings.getSetting('ipaddress')
mb3Port = addonSettings.getSetting('port')
@@ -137,7 +137,7 @@ class WebSocketThread(threading.Thread):
else:
url += ",;" + str(startPositionTicks)
playUrl = "plugin://plugin.video.mbcon/?url=" + url + '&mode=PLAY'
playUrl = "plugin://plugin.video.embycon/?url=" + url + '&mode=PLAY'
playUrl = playUrl.replace("\\\\","smb://")
playUrl = playUrl.replace("\\","/")
@@ -170,7 +170,7 @@ class WebSocketThread(threading.Thread):
messageData = {}
messageData["MessageType"] = "Identity"
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
deviceName = addonSettings.getSetting('deviceName')
deviceName = deviceName.replace("\"", "_")
@@ -182,7 +182,7 @@ class WebSocketThread(threading.Thread):
downloadUtils = DownloadUtils()
# get session ID
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
mb3Host = addonSettings.getSetting('ipaddress')
mb3Port = addonSettings.getSetting('port')
@@ -211,7 +211,7 @@ class WebSocketThread(threading.Thread):
while(self.keepRunning and xbmc.abortRequested == False):
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
mb3Host = addonSettings.getSetting('ipaddress')
mb3Port = addonSettings.getSetting('port')

View File

@@ -3,7 +3,7 @@
<category label="30014"> <!-- MediaBrowser -->
<setting id="ipaddress" type="text" label="30000" default="&lt;none&gt;" visible="true" enable="true" />
<setting id="port" type="text" label="30030" default="8096" visible="true" enable="true" />
<setting label="Detect Server" type="action" action="RunScript(plugin.video.mbcon,check_server)"/>
<setting label="Detect Server" type="action" action="RunScript(plugin.video.embycon,check_server)"/>
<setting type="sep" />
<setting id="username" type="text" label="30024" />
<setting id="password" type="text" option="hidden" label="30025" />
@@ -13,7 +13,6 @@
<setting id="smbpassword" type="text" label="30008" default="" option="hidden" visible="true" enable="true" />
</category>
<category label="30110">
<setting id="selectAction" type="enum" label="30151" values="Play|Info" default="1" />
<setting id="resumeJumpBack" type="number" label="30114" default="10" visible="true" enable="true" />
<setting id="addCounts" type="bool" label="30116" default="true" visible="true" enable="true" />
<setting id="addSeasonNumber" type="bool" label="30162" default="false" visible="true" enable="true" />

View File

@@ -21,15 +21,13 @@ from random import randint
import random
import urllib2
__cwd__ = xbmcaddon.Addon(id='plugin.video.mbcon').getAddonInfo('path')
__addon__ = xbmcaddon.Addon(id='plugin.video.mbcon')
__cwd__ = xbmcaddon.Addon(id='plugin.video.embycon').getAddonInfo('path')
__addon__ = xbmcaddon.Addon(id='plugin.video.embycon')
__language__ = __addon__.getLocalizedString
BASE_RESOURCE_PATH = xbmc.translatePath( os.path.join( __cwd__, 'resources', 'lib' ) )
sys.path.append(BASE_RESOURCE_PATH)
from ArtworkLoader import ArtworkRotationThread
from WebSocketClient import WebSocketThread
from MenuLoad import LoadMenuOptionsThread
from DownloadUtils import DownloadUtils
downloadUtils = DownloadUtils()
@@ -44,12 +42,7 @@ except Exception, e:
newWebSocketThread = WebSocketThread()
newWebSocketThread.start()
newMenuThread = LoadMenuOptionsThread()
newMenuThread.start()
artworkRotationThread = ArtworkRotationThread()
artworkRotationThread.start()
def hasData(data):
if(data == None or len(data) == 0 or data == "None"):
return False
@@ -61,7 +54,7 @@ def stopAll(played_information):
if(len(played_information) == 0):
return
addonSettings = xbmcaddon.Addon(id='plugin.video.mbcon')
addonSettings = xbmcaddon.Addon(id='plugin.video.embycon')
xbmc.log ("MBCon Service -> played_information : " + str(played_information))
for item_url in played_information:
@@ -76,8 +69,6 @@ def stopAll(played_information):
if(hasData(item_id)):
xbmc.log("MBCon Service -> Playback Stopped at :" + str(int(currentPossition * 10000000)))
newWebSocketThread.playbackStopped(item_id, str(int(currentPossition * 10000000)))
artworkRotationThread.updateActionUrls()
played_information.clear()