Video library update python script for SABnzbd
#16
I have never tried it with profiles or with suspend so im not sure.. Best just to try it.
Image
Reply
#17
(2012-11-15, 21:12)N3MIS15 Wrote: I have never tried it with profiles or with suspend so im not sure.. Best just to try it.

Ok will try otherwise it should be possible to let the script login with specific user and Suspend i guess, also using it now in kids profile so they can't poweroff box.
Reply
#18
Hi guys,

anybody tried this with frodo?
Reply
#19
yep, works same as eden.
Image
Reply
#20
N3MIS15 thenks for ultra quick respond,

I must have done something with code - will recheck it.

Combined your script with another script that watches my sabnzbd queue,

over night, when queue is empty it suspends my system.

You really made my life simpler Smile

Thank you
Reply
#21
Hi guys, just moved on from a Popcorn Hour to an HTPC. It's running Windows 8 (64 bits) and XBMC 12. I've managed to get most of my stuff up & running. Just need a simple script to make SABNZBd update the XBMC library. Any idea what this should be for Windows? I installed the latest Python (3.3.0).. but kind on stuck of what to do now.

The HTPC is always on, so no need for fancy wake-up stuff.
Reply
#22
@ 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. Smile
Reply
#23
(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. Smile

Thanks for your reply Burke, but the two alternatives suggested would mean that my hardrive would either be spinning constantly or taking out of standby every hour or so. The good thing about a postscript in sab would be that it would only update my Library when it's needed: after there has been a download (which are being pushed via DOGnzb).

I'm guessing though that the code you posted is something I would use to make the script? No idea where to start though..
Reply
#24
I have something for you. :-)
I will post it tomorrow morning when I get back home.
Script watches sab queue and when it is empty updates xbmc
[/align]
Reply
#25
Cool, TIA!
Reply
#26
Here it is.

Disclaimer: I am not a coder, so if any one needs help abut this do not know will I be able to help,
It is not tidy as I had no time to clan it properly ... but it works 10+ on my system

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

If you want to thank anyone thank them !!!

Thank you guys for letting me use your code Smile

I use this script over night, system is woken up by RTC alarm in BIOS.

1. Script checks SAB queue, when it is empty it moves on.
2. When SAB has finished processing files it moves on
3. Sends update command to XBMC
4. Checks if audio or video player is active
4.a. if yes exits
4.b. if no suspend system

notice: I use photo screen saver so script assumes that if screensaver is active system is idle and suspends system,
that can be changed easily.



PHP Code:
#!/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 
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>=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__(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)

    
## 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 ### 
Reply
#27
Tnx for your work Burke, but I could not get this to work on my machine. Also - this seems way too elaborate for my needs. I'm guessing you do not want to update when video playing because you do not want any interruptions in your videostream? I don't think I'll notice this on my machine (i3 3225, 8gb, ssd + hdd), so a simple complete update would be enough.
Reply
#28
Ok, so I couldn't get it to work, decided to do something simpeler. I just want a simple library update to run after downloading something with sab defined as either the 'TV' category or the 'Movies' category. Figured basically the only thing that had to happen was that a basic http command had to be given. So I came up with the following and thought I'd share it with you all:

Code:
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

Save as something like updatevideolibrary.cmd in your sab script folder and assign it to the categories. Seems to work like a charm. So you need wget for Windows, and make sure the path to wget is set correctly and you fill in the username and password + port you defined in XBMC under the webserver service.
Reply
#29
(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?

Why not use, WOL (Wake On Lan)? Smile
Kodi 21.0α | Ubuntu 22.04.3 | Kernel 6.4.x | intel i5-12600K | Gigabyte Z690 Gaming X DDR4 | Corsair 2x8192MB (DDR4-3200) | HDPlex H5v2 | HDPlex 400W HiFi DC-ATX | Pioneer VSX-934 | LG 65B7D
Reply
#30
I'd like to point out that the only reason the script in the OP doesn't work is because it doesn't have the "id" field, which is required. If one just adds , "id": 1 after VideoLibrary.Scan, it works no problem. I'm not sure what I was googing when I ended up here but I'll throw my SAbnzbd post-processing script into the pile:
Code:
#!/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
For troubleshooting and bug reporting please make sure you read this first.
Reply

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