Video library update python script for SABnzbd
#1
Until recently I was using the following script to update XBMC whenever SABnzbd finished downloading a movie -

PHP Code:
#!/bin/sh

wget --O/dev/null --header='Content-Type: application/json' --post-data='{"jsonrpc": "2.0", "method": "VideoLibrary.Scan"}' http://localhost:8080/jsonrpc 

but since switching to nightly OpenELEC builds this has stopped working.

Now I know the XBMC.py script for SickBeard updates my library just fine so I thought I could modify to make a simple 'Library Updater' script that SABnzbd could after downloading a movie, only trouble is it's way too complicated for me to work out which bits I need and don't.

So if anyone could help out I'd really appreciate it.

Here's the full python script - http://pastebin.com/Wu4jw5Qu
PHP Code:
# Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sick Beard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Sick Beard.  If not, see <http://www.gnu.org/licenses/>.


import urlliburllib2
import socket
import base64
import time
struct

import sickbeard

from sickbeard import logger
from sickbeard import common
from sickbeard
.exceptions import ex
from sickbeard
.encodingKludge import fixStupidEncodings

try:
    
import xml.etree.cElementTree as etree
except ImportError
:
    
import xml.etree.ElementTree as etree

class XBMCNotifier:

    
def notify_snatch(selfep_name):
        if 
sickbeard.XBMC_NOTIFY_ONSNATCH:
            
self._notifyXBMC(ep_namecommon.notifyStrings[common.NOTIFY_SNATCH])

    
def notify_download(selfep_name):
        if 
sickbeard.XBMC_NOTIFY_ONDOWNLOAD:
            
self._notifyXBMC(ep_namecommon.notifyStrings[common.NOTIFY_DOWNLOAD])

    
def test_notify(selfhostusernamepassword):
        return 
self._notifyXBMC("Testing XBMC notifications from Sick Beard""Test Notification"hostusernamepasswordforce=True)

    
def update_library(selfshow_name):
        if 
sickbeard.XBMC_UPDATE_LIBRARY:
            for 
curHost in [x.strip() for x in sickbeard.XBMC_HOST.split(",")]:
                
# do a per-show update first, if possible
                
if not self._update_library(curHostshowName=show_name) and sickbeard.XBMC_UPDATE_FULL:
                    
# do a full update if requested
                    
logger.log(u"Update of show directory failed on " curHost ", trying full update as requested"logger.ERROR)
                    
self._update_library(curHost)

    
def _username(self):
        return 
sickbeard.XBMC_USERNAME

    def _password
(self):
        return 
sickbeard.XBMC_PASSWORD

    def _use_me
(self):
        return 
sickbeard.USE_XBMC

    def _hostname
(self):
        return 
sickbeard.XBMC_HOST

    def _sendToXBMC
(selfcommandhostusername=Nonepassword=None):
        
'''
        Handles communication with XBMC servers
    
        command - Dictionary of field/data pairs, encoded via urllib.urlencode and
        passed to /xbmcCmds/xbmcHttp
    
        host - host/ip + port (foo:8080)
        '''
    
        
if not username:
            
username self._username()
        if 
not password:
            
password self._password()
    
        for 
key in command:
            if 
type(command[key]) == unicode:
                
command[key] = command[key].encode('utf-8')
    
        
enc_command urllib.urlencode(command)
        
logger.log(u"Encoded command is " enc_commandlogger.DEBUG)
        
# Web server doesn't like POST, GET is the way to go
        
url 'http://%s/xbmcCmds/xbmcHttp/?%s' % (hostenc_command)
    
        try:
            
# If we have a password, use authentication
            
req urllib2.Request(url)
            if 
password:
                
logger.log(u"Adding Password to XBMC url"logger.DEBUG)
                
base64string base64.encodestring('%s:%s' % (usernamepassword))[:-1]
                
authheader =  "Basic %s" base64string
                req
.add_header("Authorization"authheader)
    
            
logger.log(u"Contacting XBMC via url: " urllogger.DEBUG)
            
handle urllib2.urlopen(req)
            
response handle.read().decode(sickbeard.SYS_ENCODING)
            
logger.log(u"response: " responselogger.DEBUG)
        
except IOErrore:
            
logger.log(u"Warning: Couldn't contact XBMC HTTP server at " fixStupidEncodings(host) + ": " ex(e))
            
response ''
    
        
return response

    def _notifyXBMC
(selfinputtitle="Sick Beard"host=Noneusername=Nonepassword=Noneforce=False):
    
        if 
not self._use_me() and not force:
            
logger.log("Notification for XBMC not enabled, skipping this notification"logger.DEBUG)
            return 
False
    
        
if not host:
            
host self._hostname()
        if 
not username:
            
username self._username()
        if 
not password:
            
password self._password()
    
        
logger.log(u"Sending notification for " inputlogger.DEBUG)
    
        
fileString title "," input
    
        result 
''
    
        
for curHost in [x.strip() for x in host.split(",")]:
            
command = {'command''ExecBuiltIn''parameter''Notification(' +fileString ')' }
            
logger.log(u"Sending notification to XBMC via host: "curHost +"username: "username " password: " passwordlogger.DEBUG)
            if 
result:
                
result += ', '
            
result += curHost ':' self._sendToXBMC(commandcurHostusernamepassword)

        return 
result

    def _update_library
(selfhostshowName=None):
    
        if 
not self._use_me():
            
logger.log("Notifications for XBMC not enabled, skipping library update"logger.DEBUG)
            return 
False
    
        logger
.log(u"Updating library in XBMC"logger.DEBUG)
    
        if 
not host:
            
logger.log('No host specified, no updates done'logger.DEBUG)
            return 
False
    
        
# if we're doing per-show
        
if showName:
            
pathSql 'select path.strPath from path, tvshow, tvshowlinkpath where ' \
                
'tvshow.c00 = "%s" and tvshowlinkpath.idShow = tvshow.idShow ' \
                
'and tvshowlinkpath.idPath = path.idPath' % (showName)
    
            
# Use this to get xml back for the path lookups
            
xmlCommand = {'command''SetResponseFormat(webheader;false;webfooter;false;header;<xml>;footer;</xml>;opentag;<tag>;closetag;</tag>;closefinaltag;false)'}
            
# Sql used to grab path(s)
            
sqlCommand = {'command''QueryVideoDatabase(%s)' % (pathSql)}
            
# Set output back to default
            
resetCommand = {'command''SetResponseFormat()'}
    
            
# Set xml response format, if this fails then don't bother with the rest
            
request self._sendToXBMC(xmlCommandhost)
            if 
not request:
                return 
False
    
            sqlXML 
self._sendToXBMC(sqlCommandhost)
            
request self._sendToXBMC(resetCommandhost)
    
            if 
not sqlXML:
                
logger.log(u"Invalid response for " showName " on " hostlogger.DEBUG)
                return 
False
    
            encSqlXML 
urllib.quote(sqlXML,':\\/<>')
            try:
                
et etree.fromstring(encSqlXML)
            
except SyntaxErrore:
                
logger.log("Unable to parse XML returned from XBMC: "+ex(e), logger.ERROR)
                return 
False
    
            paths 
et.findall('.//field')
    
            if 
not paths:
                
logger.log(u"No valid paths found for " showName " on " hostlogger.DEBUG)
                return 
False
    
            
for path in paths:
                
# Don't need it double-encoded, gawd this is dumb
                
unEncPath urllib.unquote(path.text).decode(sickbeard.SYS_ENCODING)
                
logger.log(u"XBMC Updating " showName " on " host " at " unEncPathlogger.DEBUG)
                
updateCommand = {'command''ExecBuiltIn''parameter''XBMC.updatelibrary(video, %s)' % (unEncPath)}
                
request self._sendToXBMC(updateCommandhost)
                if 
not request:
                    return 
False
                
# Sleep for a few seconds just to be sure xbmc has a chance to finish
                # each directory
                
if len(paths) > 1:
                    
time.sleep(5)
        else:
            
logger.log(u"XBMC Updating " hostlogger.DEBUG)
            
updateCommand = {'command''ExecBuiltIn''parameter''XBMC.updatelibrary(video)'}
            
request self._sendToXBMC(updateCommandhost)
    
            if 
not request:
                return 
False
    
        
return True

# Wake function
def wakeOnLan(ethernet_address):
    
addr_byte ethernet_address.split(':')
    
hw_addr struct.pack('BBBBBB'int(addr_byte[0], 16),
    
int(addr_byte[1], 16),
    
int(addr_byte[2], 16),
    
int(addr_byte[3], 16),
    
int(addr_byte[4], 16),
    
int(addr_byte[5], 16))

    
# Build the Wake-On-LAN "Magic Packet"...
    
msg '\xff' hw_addr 16

    
# ...and send it to the broadcast address using UDP
    
ss socket.socket(socket.AF_INETsocket.SOCK_DGRAM)
    
ss.setsockopt(socket.SOL_SOCKETsocket.SO_BROADCAST1)
    
ss.sendto(msg, ('<broadcast>'9))
    
ss.close()

# Test Connection function
def isHostUp(host,port):

    (
familysocktypeprotogarbageaddress) = socket.getaddrinfo(hostport)[0#@UnusedVariable
    
socket.socket(familysocktypeproto)

    try:
        
s.connect(address)
        return 
"Up"
    
except:
        return 
"Down"


def checkHost(hostport):

    
# we should try to get this programmatically from the IP
    
mac ""

    
i=1
    
while isHostUp(host,port)=="Down" and i<4:
        
wakeOnLan(mac)
        
time.sleep(20)
        
i=i+1

notifier 
XBMCNotifier 
Reply
#2
Here is a little script i put together for myself. Should do what you want, just edit the settings at the top.

Code:
settings = {
    'hostname': '127.0.0.1',
    'port': '1234',
    'username': '',
    'password': ''
}



http_address = 'http://%s:%s/jsonrpc' % (settings['hostname'], settings['port'])
username = settings['username']
password = settings['password']

try:
    import json
except ImportError:
    import simplejson as json
import urllib2, base64

class XBMCJSON:

    def __init__(self, server):
        self.server = server
        self.version = '2.0'

    def __call__(self, **kwargs):
        method = '.'.join(map(str, self.n))
        self.n = []
        return XBMCJSON.__dict__['Request'](self, method, kwargs)

    def __getattr__(self,name):
        if not self.__dict__.has_key('n'):
            self.n=[]
        self.n.append(name)
        return self

    def Request(self, method, kwargs):
        data = [{}]
        data[0]['method'] = method
        data[0]['params'] = kwargs
        data[0]['jsonrpc'] = self.version
        data[0]['id'] = 1

        data = json.JSONEncoder().encode(data)
        content_length = len(data)

        content = {
            'Content-Type': 'application/json',
            'Content-Length': content_length,
        }
  
        request = urllib2.Request(self.server, data, content)
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

        f = urllib2.urlopen(request)
        response = f.read()
        f.close()
        response = json.JSONDecoder().decode(response)

        try:
            return response[0]['result']
        except:
            return response[0]['error']


xbmc = XBMCJSON(http_address)
xbmc.VideoLibrary.Scan()
Image
Reply
#3
Thanks but I can't get it working for me. Confused

Here's the error -

Code:
Command '"./xbmc.py"'
failed with return code 2 and error message
./xbmc.py: line 1: settings: not found
./xbmc.py: line 2: hostname:: not found
./xbmc.py: line 3: port:: not found
./xbmc.py: line 4: username:: not found
./xbmc.py: line 5: password:: not found
./xbmc.py: line 6: }
: not found
./xbmc.py: line 7:
: not found
./xbmc.py: line 8:
: not found
./xbmc.py: line 9:
: not found
./xbmc.py: line 10: syntax error: unexpected "(".
Reply
#4
might need this as the first line:
Code:
#!/usr/bin/env python

it should run as is with
Code:
python xbmc.py
Image
Reply
#5
Nice one.

I had a permission problem but sorted that out and now runs perfectly.

PHP Code:
#!/usr/bin/env python

settings = {
    
'hostname''127.0.0.1',
    
'port''8080',
    
'username''',
    
'password'''
}

http_address 'http://%s:%s/jsonrpc' % (settings['hostname'], settings['port'])
username settings['username']
password settings['password']

try:
    
import json
except ImportError
:
    
import simplejson as json
import urllib2
base64

class XBMCJSON:

    
def __init__(selfserver):
        
self.server server
        self
.version '2.0'

    
def __call__(self, **kwargs):
        
method '.'.join(map(strself.n))
        
self.= []
        return 
XBMCJSON.__dict__['Request'](selfmethodkwargs)
 
    
def __getattr__(self,name):
        if 
not self.__dict__.has_key('n'):
            
self.n=[]
        
self.n.append(name)
        return 
self

    def Request
(selfmethodkwargs):
        
data = [{}]
        
data[0]['method'] = method
        data
[0]['params'] = kwargs
        data
[0]['jsonrpc'] = self.version
        data
[0]['id'] = 1

        data 
json.JSONEncoder().encode(data)
        
content_length len(data)

        
content = {
            
'Content-Type''application/json',
            
'Content-Length'content_length,
        }
   
        
request urllib2.Request(self.serverdatacontent)
        
base64string base64.encodestring('%s:%s' % (usernamepassword)).replace('\n''')
        
request.add_header("Authorization""Basic %s" base64string)

        
urllib2.urlopen(request)
        
response f.read()
        
f.close()
        
response json.JSONDecoder().decode(response)

        try:
            return 
response[0]['result']
        
except:
            return 
response[0]['error']


xbmc XBMCJSON(http_address)
xbmc.VideoLibrary.Scan() 
Reply
#6
HI

Was looking for a way to have sabnzbd upate my xbmc every time a download finishes. Looks like that is exactly what this script is supposed to do.

I am however a complete noob - I have no idea at all to use what is in the posts above - how do I get this to work?

My setup is SAbnzbd running on my Synology, and my xbmc running on the atv 2 - how do I configure this correctly and get it to work?

/ULrik
Reply
#7
I just use the updater from couchpotato. Don't even have to think about it. Works even if you haven't added the movie to couchpotato's list.
Reply
#8
Hi N3MIS15,

Would you mind if I borrowed your script,

I am putting together a script to suspend my system (during night) if sab has finished with downloads.

I would like to update video library before that, so your script is perfect for me.

Thanks, Sinisa
Reply
#9
No need to ask.
Also, its worth noting that any http json request can be sent with this script, not just updating video library Smile.
Image
Reply
#10
Could this be modified to wake up my HTPC at say 6:00am, wait 1 min, then issue the update command, then put the computer back to sleep? Any ideas?
TV: VIZIO E-Series 43”
HTPC: Raspberry Pi 3
STORAGE: Windows 8 Server with DrivePool (Currently with 24TB)
Reply
#11
(2012-10-24, 12:14)N3MIS15 Wrote: No need to ask.
Also, its worth noting that any http json request can be sent with this script, not just updating video library Smile.

that is good to know for some future plans, but for now I will be happy to wake up in the morning to find
my downloads completed, library updated an my xbmc box in susspend.

Thank you Smile
Reply
#12
(2012-10-24, 14:03)mprassel Wrote: Could this be modified to wake up my HTPC at say 6:00am, wait 1 min, then issue the update command, then put the computer back to sleep? Any ideas?

Im not sure about waking from sleep, but if it is shut down you could run the script from another computer on a cron job or something.

This example will turn on computer with WOL then wait 2 minutes scan the videolibrary, wait another 5 minutes (while scan is happening) then shut it down again.

Code:
#!/usr/bin/env python

settings = {
    'hostname': '192.168.1.111',
    'port': '8080',
    'username': '',
    'password': '',
    'mac_address': '00:00:00:00:00:00'
}

http_address = 'http://%s:%s/jsonrpc' % (settings['hostname'], settings['port'])
username = settings['username']
password = settings['password']

try:
    import json
except ImportError:
    import simplejson as json
import urllib2, base64, time, socket, struct

class XBMCJSON:

    def __init__(self, server):
        self.server = server
        self.version = '2.0'

    def __call__(self, **kwargs):
        method = '.'.join(map(str, self.n))
        self.n = []
        return XBMCJSON.__dict__['Request'](self, method, kwargs)

    def __getattr__(self,name):
        if not self.__dict__.has_key('n'):
            self.n=[]
        self.n.append(name)
        return self

    def Request(self, method, kwargs):
        data = [{}]
        data[0]['method'] = method
        data[0]['params'] = kwargs
        data[0]['jsonrpc'] = self.version
        data[0]['id'] = 1

        data = json.JSONEncoder().encode(data)
        content_length = len(data)

        content = {
            'Content-Type': 'application/json',
            'Content-Length': content_length,
        }
  
        request = urllib2.Request(self.server, data, content)
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

        f = urllib2.urlopen(request)
        response = f.read()
        f.close()
        response = json.JSONDecoder().decode(response)

        try:
            return response[0]['result']
        except:
            return response[0]['error']


xbmc = XBMCJSON(http_address)

mac_address = settings['mac_address']
addr_byte = mac_address.split(':')
hw_addr = struct.pack('BBBBBB',
    int(addr_byte[0], 16),
    int(addr_byte[1], 16),
    int(addr_byte[2], 16),
    int(addr_byte[3], 16),
    int(addr_byte[4], 16),
    int(addr_byte[5], 16)
)


#Send wakeup packet
msg = '\xff' * 6 + hw_addr * 16
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, ("255.255.255.255", 9))

#Sleep for 2 minutes
time.sleep(120)

#Send scan request
xbmc.VideoLibrary.Scan()

#Sleep for 5 minutes
time.sleep(300)

#Shutdown
xbmc.System.Shutdown()
Image
Reply
#13
(2012-10-25, 07:23)N3MIS15 Wrote:
(2012-10-24, 14:03)mprassel Wrote: Could this be modified to wake up my HTPC at say 6:00am, wait 1 min, then issue the update command, then put the computer back to sleep? Any ideas?

Im not sure about waking from sleep, but if it is shut down you could run the script from another computer on a cron job or something.

This example will turn on computer with WOL then wait 2 minutes scan the videolibrary, wait another 5 minutes (while scan is happening) then shut it down again.

Code:
#!/usr/bin/env python

settings = {
    'hostname': '192.168.1.111',
    'port': '8080',
    'username': '',
    'password': '',
    'mac_address': '00:00:00:00:00:00'
}

http_address = 'http://%s:%s/jsonrpc' % (settings['hostname'], settings['port'])
username = settings['username']
password = settings['password']

try:
    import json
except ImportError:
    import simplejson as json
import urllib2, base64, time, socket, struct

class XBMCJSON:

    def __init__(self, server):
        self.server = server
        self.version = '2.0'

    def __call__(self, **kwargs):
        method = '.'.join(map(str, self.n))
        self.n = []
        return XBMCJSON.__dict__['Request'](self, method, kwargs)

    def __getattr__(self,name):
        if not self.__dict__.has_key('n'):
            self.n=[]
        self.n.append(name)
        return self

    def Request(self, method, kwargs):
        data = [{}]
        data[0]['method'] = method
        data[0]['params'] = kwargs
        data[0]['jsonrpc'] = self.version
        data[0]['id'] = 1

        data = json.JSONEncoder().encode(data)
        content_length = len(data)

        content = {
            'Content-Type': 'application/json',
            'Content-Length': content_length,
        }
  
        request = urllib2.Request(self.server, data, content)
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

        f = urllib2.urlopen(request)
        response = f.read()
        f.close()
        response = json.JSONDecoder().decode(response)

        try:
            return response[0]['result']
        except:
            return response[0]['error']


xbmc = XBMCJSON(http_address)

mac_address = settings['mac_address']
addr_byte = mac_address.split(':')
hw_addr = struct.pack('BBBBBB',
    int(addr_byte[0], 16),
    int(addr_byte[1], 16),
    int(addr_byte[2], 16),
    int(addr_byte[3], 16),
    int(addr_byte[4], 16),
    int(addr_byte[5], 16)
)


#Send wakeup packet
msg = '\xff' * 6 + hw_addr * 16
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, ("255.255.255.255", 9))

#Sleep for 2 minutes
time.sleep(120)

#Send scan request
xbmc.VideoLibrary.Scan()

#Sleep for 5 minutes
time.sleep(300)

#Shutdown
xbmc.System.Shutdown()

Wow this is completely over my head but I understand enough coding to know how to comment out lines. I was just looking for a simple way to replace my simple batch script that updates my library on my W7 machine which runs the MySQL server for my two ATV2 boxes (C:\cURL\curl.exe --get "http://xbmc:[email protected]:8082/xbmcCmds/xbmcHttp?command=ExecBuiltIn&parameter=XBMC.updatelibrary(video)") which was deprecated with Frodo. I tried doing some JSON curl commands but nothing worked. Anyways I just commented out the parts of your script that calls for the sleep and shutdown functions leaving only the xbmc.VideoLibrary.Scan() call. So whether this is overkill or not it works and thank you Smile

Quick question: Is the VideoLibrary.Scan supposed to rescan everything everytime? Whenever I run it it says "Downloading movie information" and lists the same general files, but definitely not every single file I have.

Edit: I figured out how to do what I wanted with curl for Windows: http://forum.xbmc.org/showthread.php?tid...pid1222124
ATV2 running XBMC Eden (Skin: Quartz3)
Windows 7 running XBMC Eden (custom setup as I'm basically running it as a service)
MySQL installed on Windows 7 for sharing libraries
iOS Specific FAQ | Alternative ATV2 keymap | Default ATV2 keymap
Post log files to Pastebin

Image
Reply
#14
(2012-10-24, 14:03)mprassel Wrote: Could this be modified to wake up my HTPC at say 6:00am, wait 1 min, then issue the update command, then put the computer back to sleep? Any ideas?


Lots of boards have "wake on RPC alarm" function in BIOS. This function will wake computer from sleep in predefined time.

I use it to download stuff over night it is simple and clean solution. Smile

@ N3MIS15

have to say thank you again - realised last night that with your script I have perfect solution for last problem in my script,
suspend that will wait for services to stop.

Thank you Smile
Reply
#15
(2012-10-25, 07:23)N3MIS15 Wrote:
(2012-10-24, 14:03)mprassel Wrote: Could this be modified to wake up my HTPC at say 6:00am, wait 1 min, then issue the update command, then put the computer back to sleep? Any ideas?

Im not sure about waking from sleep, but if it is shut down you could run the script from another computer on a cron job or something.

This example will turn on computer with WOL then wait 2 minutes scan the videolibrary, wait another 5 minutes (while scan is happening) then shut it down again.

Code:
#!/usr/bin/env python

settings = {
    'hostname': '192.168.1.111',
    'port': '8080',
    'username': '',
    'password': '',
    'mac_address': '00:00:00:00:00:00'
}

http_address = 'http://%s:%s/jsonrpc' % (settings['hostname'], settings['port'])
username = settings['username']
password = settings['password']

try:
    import json
except ImportError:
    import simplejson as json
import urllib2, base64, time, socket, struct

class XBMCJSON:

    def __init__(self, server):
        self.server = server
        self.version = '2.0'

    def __call__(self, **kwargs):
        method = '.'.join(map(str, self.n))
        self.n = []
        return XBMCJSON.__dict__['Request'](self, method, kwargs)

    def __getattr__(self,name):
        if not self.__dict__.has_key('n'):
            self.n=[]
        self.n.append(name)
        return self

    def Request(self, method, kwargs):
        data = [{}]
        data[0]['method'] = method
        data[0]['params'] = kwargs
        data[0]['jsonrpc'] = self.version
        data[0]['id'] = 1

        data = json.JSONEncoder().encode(data)
        content_length = len(data)

        content = {
            'Content-Type': 'application/json',
            'Content-Length': content_length,
        }
  
        request = urllib2.Request(self.server, data, content)
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

        f = urllib2.urlopen(request)
        response = f.read()
        f.close()
        response = json.JSONDecoder().decode(response)

        try:
            return response[0]['result']
        except:
            return response[0]['error']


xbmc = XBMCJSON(http_address)

mac_address = settings['mac_address']
addr_byte = mac_address.split(':')
hw_addr = struct.pack('BBBBBB',
    int(addr_byte[0], 16),
    int(addr_byte[1], 16),
    int(addr_byte[2], 16),
    int(addr_byte[3], 16),
    int(addr_byte[4], 16),
    int(addr_byte[5], 16)
)


#Send wakeup packet
msg = '\xff' * 6 + hw_addr * 16
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, ("255.255.255.255", 9))

#Sleep for 2 minutes
time.sleep(120)

#Send scan request
xbmc.VideoLibrary.Scan()

#Sleep for 5 minutes
time.sleep(300)

#Shutdown
xbmc.System.Shutdown()

Will this also work with password protected profiles?
I have 2 profiles, 1 master (password protected) and 1 kids profile which can't do anything except view watch movies.
And my box doesn't go completely off so i need to put it in hibernation/sleep by replacing xbmc.System.Shutdown() with xbmc.System.Suspend()?
Reply

Logout Mark Read Team Forum Stats Members Help
Video library update python script for SABnzbd0