Initial version

This commit is contained in:
Arne Bultman 2011-12-26 12:45:54 +01:00
commit 2dd34be950
15 changed files with 2127 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*.pyo
*.pyc

18
addon.xml Normal file
View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="plugin.makemkvbluray" name="BluRay Player with MakeMKV"
version="1.1.0" provider-name="Magnetism">
<requires>
<import addon="xbmc.python" version="2.0" />
</requires>
<extension point="xbmc.python.pluginsource" library="default.py">
<provides>video</provides>
</extension>
<extension point="xbmc.service"
library="service.py">
</extension>
<extension point="xbmc.addon.metadata">
<summary>Play BluRays from XBMC with MakeMKV</summary>
<description>Awesomeness </description>
<platform>all</platform>
</extension>
</addon>

200
default.py Normal file
View file

@ -0,0 +1,200 @@
import xbmc, xbmcgui, subprocess, os, time, sys, urllib, re
import xbmcplugin, xbmcaddon
# Shared resources
BASE_RESOURCE_PATH = os.path.join( xbmcaddon.Addon().getAddonInfo('path'), "resources" )
sys.path.append( os.path.join( BASE_RESOURCE_PATH, "lib" ) )
__scriptname__ = "MakeMKV BluRay Watch Plugin"
__scriptID__ = "plugin.makemkvbluray"
__author__ = "Magnetism"
__url__ = "http://bultsblog.com/arne"
__credits__ = ""
__version__ = "0.1"
__addon__ = xbmcaddon.Addon(__scriptID__)
__language__ = __addon__.getLocalizedString
_ = sys.modules[ "__main__" ].__language__
import settings, file, mkvparser, brlog, makemkv
_log = brlog.BrLog()
_log.info('Starting the BluRay script') #@UndefinedVariable
class BluRayStarter:
def __init__(self):
_log.info('Staring') #@UndefinedVariable
self.settings = settings.BluRaySettings()
self.makemkv = makemkv.MakeMkvInteraction()
def killAndStart(self, mkvStart):
if self.settings.local:
_log.info('Running makemkvcon locally') #@UndefinedVariable
self.killMkv()
# Determine if we're doing the disc or if we're browsing..
_log.info(mkvStart) #@UndefinedVariable
return subprocess.Popen(mkvStart, shell=True)
else:
_log.info('connecting to remote stream, returning fake file browse class..') #@UndefinedVariable
return file.FakeFile()
def killMkv(self):
# Linux
try :
_log.info('attempting linux kill of makemkvcon') #@UndefinedVariable
subprocess.call('killall -9 makemkvcon', shell=True)
_log.info('Linux call successful') #@UndefinedVariable
except:
pass
#Windows.
try :
_log.info('attempting windows kill of makemkvcon') #@UndefinedVariable
subprocess.call('taskkill /F /IM makemkvcon.exe', shell=True)
_log.info('Windows call successful') #@UndefinedVariable
except:
pass
def browse(self, url) :
_log.info('starting browser handler') #@UndefinedVariable
h = mkvparser.BrowseHandler()
h.start(url)
for k,v in h.titleMap.iteritems() : #@UnusedVariable
self.addLink("%s %s, %s %s" %(_(50005), v['duration'], _(50006), v['chaptercount']),v['file'])
def getMainFeatureTitle(self, url):
h = mkvparser.BrowseHandler()
h.start(url)
# Play the longest feature on the disc:
largest = 0
largestTitle = ''
for k,v in h.titleMap.iteritems() : #@UnusedVariable
m = re.search('(\d+):(\d+):(\d+)', v['duration'])
length = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + int(m.group(3))
if length > largest :
largest = length
largestTitle = v['file']
_log.info('largest: %d, %s' %(largest,largestTitle))
return largestTitle
def handleListing(self):
mode = self.settings.paramMode
_log.info( 'mode: ' + str(mode))
if mode ==None:
_log.info('Showing categories')
self.CATEGORIES()
_log.info('Showing categories done')
# _log.info(__addon__.)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
if mode == 1 :
_log.info( 'Entering Disc mode')
self.process(self.makemkv.startStream(self.settings.disc))
elif mode == 3 :
_log.info( 'Entering Remote mode')
mystarter = BluRayStarter()
mystarter.process('')
elif mode == 2:
_log.info( 'Entering Browse mode')
d = xbmcgui.Dialog() #@UndefinedVariable
choice = d.browse(1, 'Select folder', 'video', 'index.bdmv|.iso|.isoRenamedMeansSkip!|.MDS|.CUE|.CDI|.CCD', False, False, '')
if choice <> '':
self.process(self.makemkv.startFileStream(choice))
if mode == 20:
self.settings.showSettings()
def process(self, ready):
try :
if ready:
_log.info( 'Stream ready. ')
# the Stream has started, start auto playback?
if self.settings.autoPlay:
_log.info( 'Autoplay selected')
title = self.getMainFeatureTitle(self.settings.rootURL)
_log.info( 'Main feature determined to be : ' + title)
opener = urllib.URLopener()
testfile = ''
try:
testfile = title
opener.open(testfile)
except IOError:
testfile = ''
del opener
if testfile<>'':
_log.info( 'Playing file ' + testfile)
li = xbmcgui.ListItem(path = testfile)
li.setProperty('IsPlayable', 'true')
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li) #@UndefinedVariable
else:
self.message(_(50071))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, xbmcgui.ListItem()) #@UndefinedVariable
else:
# Add the selections as selectable files.
self.browse(self.settings.rootURL)
xbmcplugin.endOfDirectory(int(sys.argv[1])) #@UndefinedVariable
except :
self.message(_(50072))
self.pDialog.close()
xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, xbmcgui.ListItem()) #@UndefinedVariable
raise
def CATEGORIES(self):
# Disc
if self.settings.enableDisc:
disclist = self.makemkv.discList()
for disc in disclist:
self.addDir(_(50061) %(disc[0], disc[1]),1, True, disc[0])
for disc in disclist:
self.addDir(_(50062) %(disc[0], disc[1]),1, False, disc[0])
# Filelocation
if self.settings.enableFile:
self.addDir(_(50063),2, True)
self.addDir(_(50064),2, False)
# Remote
# if self.settings.enableRemote:
# self.addDir(_(50065),3, True)
# self.addDir(_(50066),3, False)
self.addDir(_(50060),20, True, '0', False)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def addDir(self, name,mode, autoplay, disc = '0', isPlayable = True):
u=sys.argv[0]+"?mode="+str(mode)+"&autoplay="+urllib.quote_plus(str(autoplay)) + "&disc=" + disc
_log.info(u)
icon = "DefaultVideoPlaylists.png"
if autoplay:
icon= "DefaultVideo.png"
liz=xbmcgui.ListItem(name, iconImage=icon, thumbnailImage='')
if autoplay and isPlayable:
liz.setProperty("IsPlayable", "true")
liz.setInfo( type="Video", infoLabels={ "Title": name } )
_log.info(name)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz, isFolder= not autoplay)
def addLink(self, name,url):
liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage='') #@UndefinedVariable
liz.setInfo( type="Video", infoLabels={ "Title": name } )
liz.setProperty("IsPlayable" , "true")
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) #@UndefinedVariable
def message(self, messageText):
dialog = xbmcgui.Dialog() #@UndefinedVariable
dialog.ok("Info", messageText)
_log.info("args")
for arg in sys.argv:
_log.info(arg)
_log.info("done args")
mydisplay = BluRayStarter()
mydisplay.handleListing()

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1,41 @@
<strings>
<string id="50001">MakeMKV location</string>
<string id="50002">Autoplay main feature</string>
<string id="51000">Remote Setup</string>
<string id="51001">Remote IP address</string>
<string id="51002">Local Port number</string>
<string id="51003">Seconds to wait for stream</string>
<string id="51004">General Settings</string>
<string id="51005">Browseable Options</string>
<string id="51006">Enable Disc support</string>
<string id="51007">Enable File location support</string>
<string id="51008">Enable Remote location support</string>
<string id="51009">Remote Port number</string>
<!-- Chapter browse -->
<string id="50005">duration</string>
<string id="50006">chapters</string>
<!-- Progress Dialog -->
<string id="50050">Starting BluRay script</string>
<string id="50051">Initializing</string>
<string id="50052">Waiting for BluRay to be prepared</string>
<string id="50053">Starting Disc</string>
<string id="50054">Starting Image</string>
<string id="50055">Starting Directory</string>
<string id="50056">Waiting for stream</string>
<!-- Plugin strings -->
<string id="50060">Settings</string>
<string id="50061">Play Disc %s: %s</string>
<string id="50062">Browse Disc %s: %s</string>
<string id="50063">Play Filelocation</string>
<string id="50064">Browse Filelocation</string>
<string id="50065">Play Remote location</string>
<string id="50066">Browse Remote location</string>
<!-- Error messages -->
<string id="50070">Running MakeMKV ended abnormally. Is it installed?</string>
<string id="50071">unable to find autoplay stream</string>
<string id="50072">Error trying to open makemkv stream</string>
<string id="50073">The file you've selected cannot be accessed by the filesystem</string>
</strings>

32
resources/lib/brlog.py Normal file
View file

@ -0,0 +1,32 @@
class BrLog:
__DEBUG = 0
__INFO = 1
__WARN = 2
__ERROR = 3
def __init__(self, prefix = ''):
self.logLevel = self.__INFO
if prefix <> '':
prefix = '-' + prefix
self.prefix = prefix
def setLevel(self, level):
if level >= 0 and level <= 3:
self.logLevel = level
def info(self, message):
self.log(message, self.__INFO)
def debug(self, message):
self.log(message, self.__DEBUG)
def error(self, message):
self.log(message, self.__ERROR)
def warn(self, message):
self.log(message, self.__WARN)
def log(self, message, level):
if self.logLevel <= level:
print '[BR%s %d] %s' %(self.prefix, level, message)

View file

@ -0,0 +1,196 @@
#
# ElementTree
# $Id: ElementPath.py 1858 2004-06-17 21:31:41Z Fredrik $
#
# limited xpath support for element trees
#
# history:
# 2003-05-23 fl created
# 2003-05-28 fl added support for // etc
# 2003-08-27 fl fixed parsing of periods in element names
#
# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The ElementTree toolkit is
#
# Copyright (c) 1999-2004 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
##
# Implementation module for XPath support. There's usually no reason
# to import this module directly; the <b>ElementTree</b> does this for
# you, if needed.
##
import re
xpath_tokenizer = re.compile(
"(::|\.\.|\(\)|[/.*:\[\]\(\)@=])|((?:\{[^}]+\})?[^/:\[\]\(\)@=\s]+)|\s+"
).findall
class xpath_descendant_or_self:
pass
##
# Wrapper for a compiled XPath.
class Path:
##
# Create an Path instance from an XPath expression.
def __init__(self, path):
tokens = xpath_tokenizer(path)
# the current version supports 'path/path'-style expressions only
self.path = []
self.tag = None
if tokens and tokens[0][0] == "/":
raise SyntaxError("cannot use absolute path on element")
while tokens:
op, tag = tokens.pop(0)
if tag or op == "*":
self.path.append(tag or op)
elif op == ".":
pass
elif op == "/":
self.path.append(xpath_descendant_or_self())
continue
else:
raise SyntaxError("unsupported path syntax (%s)" % op)
if tokens:
op, tag = tokens.pop(0)
if op != "/":
raise SyntaxError(
"expected path separator (%s)" % (op or tag)
)
if self.path and isinstance(self.path[-1], xpath_descendant_or_self):
raise SyntaxError("path cannot end with //")
if len(self.path) == 1 and isinstance(self.path[0], type("")):
self.tag = self.path[0]
##
# Find first matching object.
def find(self, element):
tag = self.tag
if tag is None:
nodeset = self.findall(element)
if not nodeset:
return None
return nodeset[0]
for elem in element:
if elem.tag == tag:
return elem
return None
##
# Find text for first matching object.
def findtext(self, element, default=None):
tag = self.tag
if tag is None:
nodeset = self.findall(element)
if not nodeset:
return default
return nodeset[0].text or ""
for elem in element:
if elem.tag == tag:
return elem.text or ""
return default
##
# Find all matching objects.
def findall(self, element):
nodeset = [element]
index = 0
while 1:
try:
path = self.path[index]
index = index + 1
except IndexError:
return nodeset
set = []
if isinstance(path, xpath_descendant_or_self):
try:
tag = self.path[index]
if not isinstance(tag, type("")):
tag = None
else:
index = index + 1
except IndexError:
tag = None # invalid path
for node in nodeset:
new = list(node.getiterator(tag))
if new and new[0] is node:
set.extend(new[1:])
else:
set.extend(new)
else:
for node in nodeset:
for node in node:
if path == "*" or node.tag == path:
set.append(node)
if not set:
return []
nodeset = set
_cache = {}
##
# (Internal) Compile path.
def _compile(path):
p = _cache.get(path)
if p is not None:
return p
p = Path(path)
if len(_cache) >= 100:
_cache.clear()
_cache[path] = p
return p
##
# Find first matching object.
def find(element, path):
return _compile(path).find(element)
##
# Find text for first matching object.
def findtext(element, path, default=None):
return _compile(path).findtext(element, default)
##
# Find all matching objects.
def findall(element, path):
return _compile(path).findall(element)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,30 @@
# $Id: __init__.py 1821 2004-06-03 16:57:49Z fredrik $
# elementtree package
# --------------------------------------------------------------------
# The ElementTree toolkit is
#
# Copyright (c) 1999-2004 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------

6
resources/lib/file.py Normal file
View file

@ -0,0 +1,6 @@
class FakeFile:
def poll(self):
return False
def communicate(self):
return '', ''

148
resources/lib/makemkv.py Normal file
View file

@ -0,0 +1,148 @@
import subprocess, settings, brlog, tempfile, os, threading, xbmcgui, urllib, re, xbmc
from functools import partial
def killMkvOnPlaybackEnd(pid):
dialog = xbmcgui.Dialog() #@UndefinedVariable
dialog.ok("playback ended, about to kill %d"%(pid))
class MakeMkvInteraction:
def __init__(self):
self.settings = settings.BluRaySettings()
self.progress = ProgressInfo()
self.progress.start()
self.log = brlog.BrLog('makemkvinteraction')
def discList(self):
# First stop any old one
self.killMkv()
tmpf = tempfile.NamedTemporaryFile(delete=True)
progressFile = self.progress.startProgress()
sp = os.system(r'%s -r --cache=1 --progress=%s --messages=%s info disc:10' %(self.settings.mkvLocation, progressFile, tmpf.name))
tmpf = open(tmpf.name)
content = tmpf.read()
tmpf.close()
disclist = [x for x in content.splitlines() if x.startswith('DRV:')]
readableDiscs = list()
for item in disclist:
info = [x.replace('"','') for x in item[4:].split(',')]
if len(info[5]) > 0:
readableDiscs.append( (info[0],info[5]))
return readableDiscs
def startStream(self, disc):
self.log.info("Starting stream on disc %s with local url %s" %(disc, self.settings.rootURL))
# Then fork the makemkv process
# progressFile = self.progress.startProgress(times = 2)
return self.__runandregistershutdown('%s -r --cache=128 stream disc:%s' %(self.settings.mkvLocation, disc))
def startFileStream(self, choice):
type = ''
if re.search("BDMV.index.bdmv", choice) :
# Treat as file
type = 'file'
choice = choice[:-15]
elif re.search("BDMV.MovieObject.bdmv", choice) :
# Treat as file
type = 'file'
choice = choice[:-21]
else:
# Treat as iso
type = 'iso'
# Check if the file is reachable through the filesystem, to prevent errors with smb:// shares etc.
if not os.path.exists(choice) :
dialog = xbmcgui.Dialog() #@UndefinedVariable
dialog.ok("Info", _(50073))
return False
return self.__runandregistershutdown('"%s" -r --cache=128 stream \'%s:%s\'' %(self.settings.mkvLocation, type, choice))
def __runandregistershutdown(self, mkvStart):
result = self.__runmkvstream(mkvStart)
if result >= 0:
xbmc.Player().onPlayBackStopped(partial(killMkvOnPlaybackEnd, result))
return True
else:
return False
def __runmkvstream(self, mkvStart):
self.log.info('Starting %s' %(mkvStart))
# First stop any old one
self.killMkv()
timeSlept = 0
proc = subprocess.Popen(mkvStart, shell=True)
# Then wait for the stream to come up
while True:
try:
urllib.urlretrieve(self.settings.rootURL)
return proc.pid
except IOError:
pass
if proc.poll() :
if proc.proc != 0 :
self.message(_(50070))
return -1
xbmc.sleep(1000)
timeSlept = timeSlept + 1
if timeSlept > self.settings.waitTimeOut :
return -1
def killMkv(self):
# Linux
try :
self.log.info('attempting linux kill of makemkvcon') #@UndefinedVariable
subprocess.call('killall -9 makemkvcon', shell=True)
self.log.info('Linux call successful') #@UndefinedVariable
except:
pass
#Windows.
try :
self.log.info('attempting windows kill of makemkvcon') #@UndefinedVariable
subprocess.call('taskkill /F /IM makemkvcon.exe', shell=True)
self.log.info('Windows call successful') #@UndefinedVariable
except:
pass
class ProgressInfo(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.progressFile = None
self.showing = False
self.dialog = None
def run(self):
while True:
if self.showing:
busy = True
maxprg = 1000
current = 0
while self.showing:
line = self.progressFile.readline()
if line.startswith('PRGV:'):
progress = line[4:].split(',')
maxprg = int(progress[2])
current= int(progress[1])
self.dialog.update(int(float(current) / float(maxprg) * 1000.0) )
if current >= maxprg:
self.times = self.times - 1
if self.times == 0:
self.dialog.close()
self.showing = False
def startProgress(self, times = 1):
self.dialog = xbmcgui.DialogProgress()
self.dialog.create('XBMC', '', '')
self.progressFile = tempfile.NamedTemporaryFile()
self.times = times
self.showing = True
return self.progressFile.name

View file

@ -0,0 +1,56 @@
import urllib, re, elementtree.ElementTree as ET
class BrowseHandler:
def __init__(self) :
self.catchCharData = False
self.keyColumn = False
self.map = {}
self.lastKey = ''
self.lastVal = ''
self.titleMap = {}
def start(self, url, title = 'none'):
# Initialize all locals
self.catchCharData = False
self.keyColumn = False
self.map[url] = {}
self.currMap = self.map[url]
self.lastKey = ''
self.lastVal = ''
filename, headers = urllib.urlretrieve(url)
del headers
XML = ET.parse(filename)
elems = XML.getiterator(tag='{http://www.w3.org/1999/xhtml}td')
for each in elems:
self.keyColumn = not self.keyColumn
if self.keyColumn:
self.lastKey = each.text
else:
txt = ''
# Check for href:
refs = each.getiterator(tag='{http://www.w3.org/1999/xhtml}a')
for ref in refs:
txt = ref.get('href')
if txt == '' :
txt = each.text
self.currMap[self.lastKey] = txt
# Now do some processing:
for k, v in self.map[url].iteritems() :
if k == 'titles':
# go straight ahead and parse some more:
self.start(v)
if re.search('title\d+', k) :
self.titleMap[k] = {}
self.start(v, k)
if title != 'none':
if k == 'duration':
self.titleMap[title]['duration'] = v
elif k == 'file0':
self.titleMap[title]['file'] = v
elif k == 'chaptercount':
self.titleMap[title]['chaptercount'] = v

86
resources/lib/settings.py Normal file
View file

@ -0,0 +1,86 @@
import xbmcplugin, xbmcaddon
import sys
import urllib
import brlog
__scriptID__ = sys.modules[ "__main__" ].__scriptID__
class BluRaySettings:
def __init__(self):
addon = xbmcaddon.Addon(__scriptID__)
self.log = brlog.BrLog('settings')
self.log.info('reading settings') #@UndefinedVariable
params = self.getParams()
self.paramUrl = self.getParam(params, 'url')
self.paramName = self.getParam(params, "name")
self.paramMode = self.getIntParam(params, "mode")
self.autoPlay = self.getBoolParam(params, "autoplay")
self.disc = self.getParam(params, "disc")
self.local = self.paramMode <> 3
self.ipAddress = addon.getSetting('ip_address') #@UndefinedVariable
self.portNumber = addon.getSetting('port_number') #@UndefinedVariable
if (self.local):
#Make sure local means 127.0.0.1 ...
self.ipAddress = '127.0.0.1'
else :
#Remote so use that portnumber
self.portNumber = addon.getSetting('remote_port_number') #@UndefinedVariable
self.mkvLocation = addon.getSetting('mkvlocation') #@UndefinedVariable
self.rootURL = 'http://%s:%s/' % (self.ipAddress, self.portNumber)
self.waitTimeOut = int(addon.getSetting('wait_timeout')) #@UndefinedVariable
# Sections:
self.enableDisc = addon.getSetting('support_disc') == "true" #@UndefinedVariable
self.enableFile = addon.getSetting('support_fileselect') == "true" #@UndefinedVariable
self.enableRemote = addon.getSetting('support_remote') == "true" #@UndefinedVariable
def getParam(self, params, name):
try:
result = params[name]
result = urllib.unquote_plus(result)
return result
except:
return None
def getIntParam (self, params, name):
try:
param = self.getParam(params,name)
self.log.debug(name + ' = ' + param)
return int(param)
except:
return None
def getBoolParam (self, params, name):
try:
param = self.getParam(params,name)
self.log.debug(name + ' = ' + param)
return 'True' == param
except:
return None
def getParams(self):
try:
param=[]
paramstring=sys.argv[2]
self.log.info('raw param string: ' + paramstring)
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
except:
return []
def showSettings(self):
xbmcaddon.Addon(__scriptID__).openSettings(sys.argv[ 0 ]) #@UndefinedVariable

17
resources/settings.xml Normal file
View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<settings>
<setting type="lsep" label="51004"/>
<setting id="mkvlocation" type="file" label="50001" default="makemkvcon"/>
<setting id="wait_timeout" type="number" label="51003" default="120" />
<setting id="port_number" type="number" label="51002" default="51000" />
<setting type="lsep" label="51005"/>
<setting id="support_disc" type="bool" label="51006" default="true" />
<setting id="support_fileselect" type="bool" label="51007" default="true"/>
<setting id="support_remote" type="bool" label="51008" default="true"/>
<setting type="lsep" label="51000" visible="eq(-1,true)"/>
<setting id="ip_address" type="ipaddress" label="51001" default="127.0.0.1" visible="eq(-2,true)" />
<setting id="remote_port_number" type="number" label="51009" default="51000" visible="eq(-3,true)" />
</settings>

41
service.py Normal file
View file

@ -0,0 +1,41 @@
import xbmc, xbmcgui, subprocess, os, sys, urllib, re
import xbmcplugin, xbmcaddon
__scriptID__ = "plugin.makemkvbluray"
__addon__ = xbmcaddon.Addon(__scriptID__)
# Shared resources
BASE_RESOURCE_PATH = os.path.join( __addon__.getAddonInfo('path'), "resources" )
sys.path.append( os.path.join( BASE_RESOURCE_PATH, "lib" ) )
import makemkv
__language__ = __addon__.getLocalizedString
_ = sys.modules[ "__main__" ].__language__
import settings, file, mkvparser, brlog, makemkv
_log = brlog.BrLog('tracker service')
_log.info('Starting the BluRay tracker service') #@UndefinedVariable
class MyPlayer(xbmc.Player):
def __init__(self):
xbmc.Player.__init__(self)
self.makemkv = makemkv.MakeMkvInteraction()
def onPlayBackStopped(self):
_log.info('Playback stopped, trying to kill makemkv')
xbmc.executebuiltin('Notification("MakeMkv", "Playback ended, stopping makemkv")')
self.makemkv.killMkv()
def onPlayBackStarted(self):
_log.info('Playback started')
myPlayer = MyPlayer()
while (not xbmc.abortRequested):
xbmc.sleep(4)