Advertisement
Guest User

Untitled

a guest
Mar 9th, 2011
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.14 KB | None | 0 0
  1. import sys
  2. import os
  3. import signal
  4. import subprocess
  5. import re
  6. import xbmc
  7. import xbmcaddon
  8. import xbmcgui
  9. import threading
  10. import time, datetime
  11. import commands
  12. import urllib2
  13. from xml.dom import minidom
  14.  
  15. #get actioncodes from keymap.xml
  16. ACTION_PREVIOUS_MENU = 10
  17. TVHEADEND_URL = 'http://localhost:9981/status.xml'
  18. LOG_FILE = '/home/xbmc/.xbmc/temp/pvruptime.log'
  19. WAITBEFORESHUTDOWN = 120
  20. WAKEBEFORERECORDING = 0 #300
  21.  
  22. class MyClass(xbmcgui.Window):
  23.   def __init__(self):
  24.     self.strActionInfo = xbmcgui.ControlLabel(100, 120, 1600, 400, '')
  25.     self.addControl(self.strActionInfo)
  26.     self.strActionInfo.setLabel('Determining TV recording status before shutting down...')
  27.     self.button0 = xbmcgui.ControlButton(350, 500, 300, 50, "Return to XBMC")
  28.     self.addControl(self.button0)
  29.     self.button1 = xbmcgui.ControlButton(750, 500, 300, 50, "Shutdown XBMC")
  30.     self.addControl(self.button1)
  31.     self.setFocus(self.button0)
  32.     self.button0.controlRight(self.button1)
  33.     self.button0.controlLeft(self.button1)
  34.     self.button1.controlRight(self.button0)
  35.     self.button1.controlLeft(self.button0)
  36.     self.timerMsg = threading.Timer(2, self.checkRecording)
  37.     self.timerMsg.start()
  38.  
  39.   def onAction(self, action):
  40.     if action == ACTION_PREVIOUS_MENU:
  41.       self.timerMsg.cancel()
  42.       self.close()
  43.  
  44.   def onControl(self, control):
  45.     if control == self.button0:
  46.       self.timerMsg.cancel()
  47.       self.close()
  48.     if control == self.button1:
  49.       self.message('Are you sure you want to force a shutdown?  You may have active recordings.')
  50.       self.timerMsg.cancel()
  51.  
  52.   def message(self, message):
  53.     dialog = xbmcgui.Dialog()
  54.     if dialog.yesno("PVRUptime", message):
  55.       self.close()
  56.  
  57.   def findThisProcess(self, process_name ):
  58.     ps = subprocess.Popen("ps -eaf | grep "+process_name, shell=True, stdout=subprocess.PIPE)
  59.     output = ps.stdout.read()
  60.     ps.stdout.close()
  61.     ps.wait()
  62.     return output
  63.  
  64.   def writeToLogFile(self, message):
  65.     if os.path.isfile(LOG_FILE) == False:
  66.       logFile = open(LOG_FILE, 'w')
  67.     else:
  68.       logFile = open(LOG_FILE, 'r+')
  69.       logFile.seek(0,2)
  70.     logFile.write(message +'\n\n')
  71.     logFile.close()
  72.  
  73.   def checkProcess(self, processname):
  74.     processExists = "False"
  75.     processList = os.popen("ps xa")
  76.     if processList:
  77.       for line in processList:
  78.         fields = line.split()
  79.         pid = fields[0]
  80.         process = fields[4]
  81.         if process.find(processname) > 0:
  82.           processExists = "True"
  83.           break
  84.     return processExists
  85.  
  86.   def checkRecording(self):
  87.     closestRecordingDateTimeStart = None
  88.     closestRecordingDateTimeEnd = None
  89.     closestRecordingTitle = None
  90.     currentlyRecording = "False"
  91.     difference = None
  92.     UTCTimeDelta = datetime.timedelta(hours=8)
  93.     currentTime = datetime.datetime.now()
  94.     dialog = xbmcgui.Dialog()
  95.  
  96.     password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
  97.     password_mgr.add_password(None, TVHEADEND_URL, 'xbmc', 'xxxxx')
  98.     handler = urllib2.HTTPBasicAuthHandler(password_mgr)
  99.     opener = urllib2.build_opener(handler)
  100.     opener.open(TVHEADEND_URL)
  101.     urllib2.install_opener(opener)
  102.     f = urllib2.urlopen(TVHEADEND_URL)
  103.     link = f.read()
  104.     xmldoc = minidom.parseString(link)
  105.     f.close()
  106.  
  107.     self.writeToLogFile('starting the process')
  108.  
  109.     subscriptionnode = xmldoc.getElementsByTagName('subscriptions')[0]
  110.     numsubscriptions = subscriptionnode.childNodes[0].data
  111.  
  112.     # DEBUGGING OUTPUT
  113.     self.writeToLogFile('we have determined num subscriptions = ' + numsubscriptions)
  114.  
  115.     if numsubscriptions == "0":
  116.  
  117.       # DEBUGGING OUTPUT
  118.       self.writeToLogFile('num subscriptions = 0 and we made it into the if statement')
  119.  
  120.       # New code -------------------------------------------------
  121.       nextRecord = xmldoc.getElementsByTagName('next')
  122.       if nextRecord:
  123.         minutesUntilNextRecording = int(nextRecord[0].childNodes[0].data)
  124.     closestRecordingDateTimeStart = currentTime + datetime.timedelta(minutes=minutesUntilNextRecording)
  125.       else:
  126.         closestRecordingDateTimeStart = None
  127.       # End new code ---------------------------------------------
  128.      
  129.       # DEBUGGING OUTPUT
  130.       #self.writeToLogFile('minutesUntilNextRecording = ' + str(minutesUntilNextRecording))
  131.      
  132.       #minutesUntilNextRecording = int(xmldoc.getElementsByTagName('next')[0].childNodes[0].data)
  133.       #closestRecordingDateTimeStart = currentTime + datetime.timedelta(minutes=minutesUntilNextRecording)
  134.  
  135.       # DEBUGGING OUTPUT
  136.       self.writeToLogFile('closestRecordingDateTimeStart = ' + str(closestRecordingDateTimeStart))
  137.  
  138.     elif numsubscriptions != "0":
  139.       for recordingnode in xmldoc.getElementsByTagName('recording'):
  140.         nextRecordingDateTimeStart = datetime.datetime.fromtimestamp(float(recordingnode.getElementsByTagName('start')[0].getElementsByTagName('unixtime')[0].childNodes[0].data)) - datetime.timedelta(minutes=5)
  141.         nextRecordingDateTimeStartUTC = nextRecordingDateTimeStart
  142.         nextRecordingDateTimeEnd = datetime.datetime.fromtimestamp(float(recordingnode.getElementsByTagName('stop')[0].getElementsByTagName('unixtime')[0].childNodes[0].data)) + datetime.timedelta(minutes=15)
  143.         nextRecordingDateTimeEndUTC = nextRecordingDateTimeEnd
  144.         nextRecordingTitle = recordingnode.getElementsByTagName('title')[0].childNodes[0].data
  145.  
  146.         #self.strActionInfo.setLabel(nextRecordingTitle)
  147.         self.strActionInfo.setLabel(str(nextRecordingDateTimeStartUTC) + ", " + str(nextRecordingDateTimeEndUTC) +", " + str(currentTime))
  148.  
  149.         if nextRecordingDateTimeStartUTC < nextRecordingDateTimeEndUTC:
  150.           if nextRecordingDateTimeStartUTC > currentTime:
  151.             if currentlyRecording == "False":
  152.               if closestRecordingDateTimeStart is None:
  153.                 closestRecordingDateTimeStart = nextRecordingDateTimeStartUTC
  154.                 closestRecordingDateTimeEnd = nextRecordingDateTimeEndUTC
  155.                 closestRecordingTitle = nextRecordingTitle
  156.               else:
  157.                 if closestRecordingDateTimeStart > nextRecordingDateTimeStartUTC:
  158.                   closestRecordingDateTimeStart = nextRecordingDateTimeStartUTC
  159.                   closestRecordingDateTimeEnd = nextRecordingDateTimeEndUTC
  160.                   closestRecordingTitle = nextRecordingTitle
  161.                 #else:
  162.                   #print "Ignoring ", nextRecordingTitle, " as there is a current recording ", closestRecordingTitle
  163.           else:
  164.             if nextRecordingDateTimeEndUTC > currentTime:
  165.               if currentlyRecording == "False":
  166.                 closestRecordingDateTimeStart = nextRecordingDateTimeStartUTC
  167.                 closestRecordingDateTimeEnd = nextRecordingDateTimeEndUTC
  168.                 closestRecordingTitle = nextRecordingTitle
  169.                 currentlyRecording = "True"
  170.               else:
  171.                 closestRecordingTitle = closestRecordingTitle + "\n" + nextRecordingTitle
  172.                 if nextRecordingDateTimeEndUTC > closestRecordingDateTimeEnd:
  173.                   closestRecordingDateTimeStart = nextRecordingDateTimeStartUTC
  174.                   closestRecordingDateTimeEnd = nextRecordingDateTimeEndUTC
  175.             #else:
  176.               #print "completed recording", nextRecordingTitle
  177.  
  178.     if currentlyRecording == "True":
  179.       difference = closestRecordingDateTimeEnd - currentTime
  180.       outputMessage = "Currently recording \n" + closestRecordingTitle + "\nfor another " + str(difference.seconds/60) + " minutes \nuntil " + str(closestRecordingDateTimeEnd)
  181.       self.writeToLogFile(outputMessage)
  182.       self.strActionInfo.setLabel(outputMessage)
  183.       self.timerMsg = threading.Timer(5, self.checkRecording)
  184.       self.timerMsg.start()
  185.    
  186.     else:
  187.       if closestRecordingDateTimeStart is None:
  188.         # by default, set wake up for 4 hours time if no new recordings are scheduled and we're not recording now
  189.         closestRecordingDateTimeStart = currentTime + datetime.timedelta(hours=4)
  190.  
  191.     # DEBUGGING OUTPUT
  192.         self.writeToLogFile('closestRecordingDateTimeStart now reset from None = ' + str(closestRecordingDateTimeStart))
  193.  
  194.       difference = closestRecordingDateTimeStart - currentTime
  195.       # DEBUGGING OUTPUT
  196.       self.writeToLogFile('difference = ' + str(difference))
  197.       self.writeToLogFile('difference.seconds = ' + str(difference.seconds))
  198.  
  199.       # determine if the next recording is > 2 minutes away
  200.       if difference.seconds > WAITBEFORESHUTDOWN:
  201.  
  202.         wakeupDateTimeUTC = closestRecordingDateTimeStart - datetime.timedelta(seconds=WAKEBEFORERECORDING)
  203.  
  204.         outputMessage = "Next recording more than " + str(WAITBEFORESHUTDOWN/60) + " minutes away \nshutting down with restart in " + str(difference.seconds/60) + " minutes, at " + str(wakeupDateTimeUTC + UTCTimeDelta)
  205.         self.writeToLogFile(outputMessage)
  206.     self.writeToLogFile('Wakeup time is: ' + str(time.mktime(wakeupDateTimeUTC.timetuple())))
  207.         self.strActionInfo.setLabel(outputMessage)
  208.  
  209.         wakeupCommand = "sudo /usr/share/xbmc/addons/script.pvruptime/shutdown.sh " + str(time.mktime(wakeupDateTimeUTC.timetuple()))
  210.         self.strActionInfo.setLabel(wakeupCommand)
  211.         os.system(wakeupCommand)
  212.  
  213.     self.writeToLogFile('Wakeup command is: ' + wakeupCommand)
  214.  
  215.         self.strActionInfo.setLabel("Determining TV recording status...")
  216.         currentTime = datetime.datetime.now()
  217.         self.writeToLogFile("Current Time: " + str(currentTime) + ", Wake-Up Time: " + str(wakeupDateTimeUTC))
  218.         difference = time.mktime(wakeupDateTimeUTC.timetuple()) - time.mktime(currentTime.timetuple())
  219.         outputMessage = "Difference = " + str(difference)
  220.         self.writeToLogFile(outputMessage)
  221.         if difference > 30:
  222.           self.timerMsg.cancel()
  223.           self.close()
  224.         else:
  225.           self.timerMsg = threading.Timer(5, self.checkRecording)
  226.           self.timerMsg.start()
  227.       else:
  228.         self.strActionInfo.setLabel("Next recording less than " + str(WAITBEFORESHUTDOWN/60) + " minutes away, staying awake")
  229.         self.timerMsg = threading.Timer(5, self.checkRecording)
  230.         self.timerMsg.start()
  231.  
  232.  
  233. mydisplay = MyClass()
  234. mydisplay .doModal()
  235. del mydisplay
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement