2012-11-15, 21:12
I have never tried it with profiles or with suspend so im not sure.. Best just to try it.
xbmc.VideoLibrary.Scan()
(2013-02-11, 21:40)Burke Wrote: @ pushnoi
you have the script here, if you want to update library you would need to
Code:xbmc.VideoLibrary.Scan()
but if you are not at home ground with scripts, there are easier ways to "auto update" library.
Both Sickbeard and Couchpoto can send update command.
Also there are XBMC addons that can do the trick.
Library watchdog
or
XBMC Library Updater Addon
They all work so just chose one that suits your needs the most.
#!/usr/bin/python
#!/bin/bash
##
############################################################################################################################
# This script is stiched from two diferent scripts...
# First part (sabnzb)is moded script taken from bobbintb @sabnzbdforums
# Second part (xbmc) is modede script taken from N3MIS15 @xbmc forums
# If you want to thank anyone thank them !!!
# Stiched by burke @xbmc forum :)
#############################################################################################################################
# IMPORTANT: For this to work you need to have SABnzbd+ 0.7.10 (changes in API needed for script)
# The works:
# Scrip will loop in part one utill download is complete then until sab is finshed with download files...
# It will send update command to xbmc
# It will check are any player active: video, music foto...
# IF video or music player are active it will exit. đ
# !!! Foto player is treated as screen saver so if it is active it will suspend (this can be changed easilly if needed
#
# !!!!!!!!! HOW TO
# all parts marked with '### EDIT' need to be configured to your system needs!!
# part of scrip marked with '### SUSPEND' will do just that - suspend your system so remove if not needded
################################################################################################################################
# setings for xbmc part of script
### EDIT
settings = {
'hostname': '127.0.0.1',
'port': '8088',
'username': 'xbmc',
'password': ''
}
# import stuff we need
import logging
logger = logging.getLogger('myapp')
### EDIT path to log file same as below!!
hdlr = logging.FileHandler('/home/xbmc/skripte/deamon_complete.txt')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
import subprocess
import urllib2
import os
import datetime
import time
from xml.dom.minidom import parseString
## clean log before starting actual job
### EDIT path to log file
f = open("/home/xbmc/skripte/deamon_complete.txt", 'w')
f.close()
## SABnzbd download state ##
now = datetime.datetime.now()
### EDIT time range in which script is allowed to start
if now.hour>=8 and now.hour<=16:
logger.info("- Starting the script...")
#load the queue:
### EDIT IP adress and insert your SAB API replace ???API???
queue = urllib2.urlopen('http://192.168.5.11:8083/sabnzbd/api?mode=qstatus&output=xml&apikey=???API???')
queuedata = queue.read()
queue.close()
## ACTIVE DOWNLOAD ?##
# Script checks for active download it will loop here until download is complete
while True:
complete = queuedata.count("<noofslots>0</noofslots>")
if complete != 1:
logtime = datetime.datetime.now()
print logtime,'- SABnzbd: Downloading...'
logger.info('- SABnzbd: Downloading...')
time.sleep(300)
# reload queue or loop will be stuck with old data from first read
### EDIT IP adress and insert your SAB API replace ???API???
queue = urllib2.urlopen('http://192.168.5.11:8083/sabnzbd/api?mode=qstatus&output=xml&apikey=???API???')
queuedata = queue.read()
queue.close()
# triger to continue
if complete == 1:
logtime1 = datetime.datetime.now()
print logtime1, '- SABnzbd: No active downloads. '
logger.info('- SABnzbd: No active downloads. ')
break
time.sleep(300)
## HISTORY - POSTPROCESSING ACTIVE ?##
# this is fale switch not to kill system while there is some postprocessing dun by sab
# load history data - check if Sabnzbd is doing something else (like unpacking files)
### EDIT IP adress and insert your SAB API replace ???API???
while True:
history = urllib2.Request('http://192.168.5.11:8083/sabnzbd/api?mode=history&start=0&limit=4&apikey=???API???&output=json')
response = urllib2.urlopen(history)
historydata = response.read()
##looking for stuff we need in history
postprocesing = historydata.count('Repairing') or historydata.count('Unpacking') or historydata.count('Verifying')
Repairing = historydata.count('Repairing')
Unpacking = historydata.count('Unpacking')
Verifying = historydata.count('Verifying')
##loging
if Repairing >= 1:
print 'Repairing'
logger.info('- SABnzbd: Repairing files...')
elif Unpacking >= 1:
print 'Unpacking'
logger.info('- SABnzbd: Unpacking files...')
elif Verifying >= 1:
print 'Verifying'
logger.info('- SABnzbd: Verifying files...')
if postprocesing >= 1:
print 'bussy.....'
## loop script while sab is doing something with files
time.sleep(120)
else:
logtime3 = datetime.datetime.now()
print logtime3, '- SABnzbd: Finished all jobs. '
logger.info('- SABnzbd: Finished all jobs.')
break
## XBMC update
## LIBRARY UPDATE ##
### SABntbd is not active script is going to update video library
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)
## Command to update Video library
xbmc.VideoLibrary.Scan()
logtime0 = datetime.datetime.now()
print logtime0, '- XBMC: Updating Video Library.'
logger.info('- XBMC: Updating Video Library.' )
## Giving time to XBMC tu update library before going forward
time.sleep(1)
### SUSPEND
## ARE PLAYERS ACTIVE? ##
# This will suspend system if used
# Check are there any active players (video or adudio), photo is used for screensaver!
active_player = xbmc.Player.GetActivePlayers()
#print logtime, active_player
try:
playerid = active_player[0]['playerid']
if (playerid)==0: # Video player
logtime4 = datetime.datetime.now()
print logtime4, '- XBMC: Audio player active'
logger.info('- XBMC: Audio player active' )
print logtime4, '- Script: Exiting...'
logger.info('- Script: Exiting...')
exit()
elif (playerid)==1: # Audio player
logtime4 = datetime.datetime.now()
print logtime4, '- XBMC: Video player active'
logger.info('- XBMC: Video player active' )
print logtime4, '- Script: Exiting...'
logger.info('- Script: Exiting...')
# If active exit script
exit()
elif (playerid)==2: # Photo player
## Presume it is screen saver so suspend system
logtime5 = datetime.datetime.now()
print logtime5, '- XBMC: Screensaver active'
logger.info("- XBMC: Screensaver active" )
print logtime4, '- XBMC: Screen saver active'
logger.info('- XBMC: Screen saver active' )
print logtime5, '- System: Going to sleep.'
logger.info( '- System: Going to sleep. \n\n>>> end ')
xbmc.System.Suspend()
exit()
except LookupError: # If no players are active supending system
logtime6 = datetime.datetime.now()
print logtime6, '- XBMC: Nothing active'
logger.info("- XBMC: Nothing active" )
print logtime6, '- System: Going to sleep'
logger.info('- System: Going to sleep \n \n>>> end ' )
xbmc.System.Suspend()
exit()
else:
print "Not in time range. Exiting script."
logger.info('- Script: Not in time range. Exiting script.')
#### END ###
REM Simple script to have XBMC update the library (Windows) after downloading with SABNZBd. Make sure you have wget for Windows installed.
REM Only tested on Win8 (64-bits) + XBMC 12.0 Frodo and SABnzbd 0.7.11.
"c:\Program Files (x86)\GnuWin32\bin\wget" -q -O NUL --header="Content-Type: application/json" --post-data="{\"id\":1,\"jsonrpc\":\"2.0\",\"method\":\"VideoLibrary.Scan\"}" http://username:[email protected]:9999/jsonrpc
(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?
#!/bin/sh
pidof xbmc.bin > /dev/null
if [ $? -eq 0 ] ; then
wget -q -O- --header='Content-Type: application/json' --post-data='{"jsonrpc": "2.0", "method": "VideoLibrary.Scan", "id": "sabnzbd"}' http://localhost:8000/jsonrpc
else
echo XBMC not running
fi
exit 0