mythtvrecordedshows.py :  » Game-2D-3D » XBMC-MythTV » xbmcmythtv » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Game 2D 3D » XBMC MythTV 
XBMC MythTV » xbmcmythtv » mythtvrecordedshows.py
"""
$Id: mythtvrecordedshows.py,v 1.29 2007/04/12 08:14:30 frooby Exp $

Copyright (C) 2005 Tom Warkentin <tom@ixionstudios.com>

"""
import mythtvgui
from mythtvgui import Dialog
from singleton import getInstance
from time import strftime,strptime
import mythtv, mythtvrecordedshowdetails, mythtvutil
import os, sre, time, string, traceback
import xbmcgui

def debug( str ):
    mythtvutil.debug( mythtvutil.DEBUG_GUI, str )

def compareDateAsc( x, y ):
    if x.starttime() == y.starttime():
        return cmp( x.endtime(), y.endtime() )
    else:
        return cmp( x.starttime(), y.starttime() )

def compareDateDesc( y, x ):
    if x.starttime() == y.starttime():
        return cmp( x.endtime(), y.endtime() )
    else:
        return cmp( x.starttime(), y.starttime() )

def compareTitleAsc( x, y ):
    if x.title() == y.title():
        return cmp( x.starttime(), y.starttime() )
    else:
        return cmp( x.title(), y.title() )

def compareTitleDesc( y, x ):
    if x.title() == y.title():
        return cmp( x.starttime(), y.starttime() )
    else:
        return cmp( x.title(), y.title() )

def showWindow(winDialog):
    """
    Function to create the recorded show window.
    """
    debug( "> mythtvrecordedshows.showWindow()" )

    win = Window()
    win.loadskin( "recordedshows.xml" )
    win.checkConnections()
    win.loadRecGroupList()
    winDialog.close()
    win.doModal()
    del win

    debug( "< mythtvrecordedshows.showWindow()" )

class Window( mythtvgui.BaseWindow ):
    
    VIEW_BY_MIN         = 0     # must be smallest sequential value
    VIEW_BY_DATE_ASC    = 1
    VIEW_BY_DATE_DESC   = 2
    VIEW_BY_TITLE_ASC   = 3
    VIEW_BY_TITLE_DESC  = 4
    VIEW_BY_MAX         = 5     # must be largest sequential value

    def __init__( self ):
        mythtvgui.BaseWindow.__init__( self )
        self.recordings = []
        self.focusControl = None
        self.showRecGroup = True
        self.updateEpisodesOnScroll = True
        try:
            self.recGroup = getInstance( mythtv.Settings ).getSetting( "recorded_default_group" )
        except:
            self.recGroup = "default"
        
        self.curTitle = "All Shows (x shows)"
        self.recGroups = []
        self.showTitles = []

        self.db = None
        self.conn = None

        self.viewByLabel = { \
            self.VIEW_BY_DATE_ASC: 38, \
            self.VIEW_BY_TITLE_ASC: 39, \
            self.VIEW_BY_DATE_DESC: 69, \
            self.VIEW_BY_TITLE_DESC: 70 \
        }

        try:
            self.viewBy = \
                int(getInstance( mythtv.Settings ).getSetting( \
                    "recorded_view_by" ))
        except IndexError, ie:
            self.viewBy = self.VIEW_BY_DATE_DESC
            getInstance( mythtv.Settings ).setSetting( \
                "recorded_view_by", \
                "%d"%self.viewBy, \
                shouldCreate=1 )
            pass

    def checkConnections( self ):
        if not self.db:
            self.db = getInstance( mythtv.Database )
            
        if self.db.isConnected == 0:
            Dialog().ok( mythtvutil.getLocalizedString( 27 ), "Database Connection Failed.","Recorded Shows is Unable to Continue","Please Check Settings and Try Again" )
            self.close()

        if not self.conn:
            self.conn = getInstance( mythtv.Connection )

        if self.conn.isConnected == 0:
            Dialog().ok( mythtvutil.getLocalizedString( 27 ), "MythTV Server Connection Failed.","Recorded Shows is Unable to Continue","Please Check Settings and Try Again" )
            self.close()


    def loadingRemove(self):
        self.isLoading = False
        self.hidegroup("popup")
            
    def showIconImg( self, img, path="" ):
        c = self.controls['popup_icon'].control
        self.removeControl( c )
        del c

        x = int(self.getvalue( self.getoption( "popup_channel_x" ) ) )
        y = int(self.getvalue( self.getoption( "popup_channel_y" ) ) )
        w = int(self.getvalue( self.getoption( "popup_channel_w" ) ) )
        h = int(self.getvalue( self.getoption( "popup_channel_h" ) ) )

        texture = img
        tx = mythtvutil.findMediaFile( texture )
        if tx == None:
            tx = path + texture

        c = xbmcgui.ControlImage( x, y, w, h, tx )
        self.addControl( c )
        self.controls['popup_icon'].control = c

    def loadingShow(self, show):
        # self.loadingRemove()
        self.group = "main"
        self.showgroup("popup", False)

        # populate title
        self.isLoading = True
        theShowDesc = show.formattedDescription()
        theChanID = show.chanstr()
        theChanName = show.formattedChannel()
        theShowName = show.fullTitle()
        
        chanTxt = "Loading " + str(theShowName) + " Please Wait..."
        debug("*** %s: %s - %s" % ( chanTxt, theShowName, theShowDesc) )
        self.controls['popup_title'].control.setLabel( chanTxt )
        self.controls['popup_line_a'].control.reset()
        self.controls['popup_line_a'].control.addLabel( chanTxt )
        self.controls['popup_line_b'].control.reset()
        self.controls['popup_line_b'].control.addLabel( theShowDesc )

        self.showIconImg( 'channels\\' + str(theChanID) + mythtvgui.picType, mythtvgui.picBase )

    def buildListEntry( self, row ):
        debug( '> mythtvrecordedshows.Window.buildListEntry( row=[%s])'%row )
        
        start = strptime( row.starttime(), "%Y%m%d%H%M%S" )
        entry = strftime( "%m/%d %I:%M %p", start ) + "   "
        if row.title():
            entry += row.title()
        if row.subtitle() and not sre.match( '^\s+$', row.subtitle() ):
            entry += " - " + row.subtitle()

        debug( '< mythtvrecordedshows.Window.buildListEntry()' )
        return entry

    def loadRecGroupList( self ):
        debug( '> mythtvrecordedshows.Window.loadRecGroupList()' )
        if self.showRecGroup:        
            self.recGroups = self.db.getRecordingGroups( )
            debug ( "%s Recording Groups Found" % str(len(self.recGroups) ) )
            ctl = self.controls["recgroup_list"].control

            cnt = 0
            curIdx = 0
            recg = self.recGroup

            debug ( recg )
            xbmcgui.lock()
            try:
                ctl.reset()
                try:
                    ctl.setPageControlVisible(False)
                except:
                    pass
                
                for r in self.recGroups:
                    if string.upper(r[0]) == string.upper(recg):
                        curIdx = cnt
                    cnt += 1
                    ctl.addItem( "%s" % (r[0]) )
                    ctl.selectItem( curIdx )
                xbmcgui.unlock()
            except:
                traceback.print_exc()
                xbmcgui.unlock()
        else:
            try:
                ctl = self.controls["recgroup_list"].control
                ctl.setVisible(False)
            except:
                debug("Unable to remove recgroup control. Maybe it's been removed from the skin?")

        self.loadTitleList()
        debug( '< mythtvrecordedshows.Window.loadRecGroupList()' )

    def loadTitleList( self ):
        debug( '> mythtvrecordedshows.Window.loadTitleList()' )

        recg = self.recGroup # self.recGroup[:str(self.recGroup).rfind("(")-1]

        debug ( recg )
        self.showTitles = self.db.getRecordingTitles( recg )
        debug ( "%s Recording Titles Found for Rec Group %s" % ( str(len(self.showTitles) ), recg ) )
        ctl = self.controls["show_list"].control

        ## if rec group has no shows swap back to first group and reload
        if len(self.showTitles) == 1:
            self.recGroup = self.recGroups[1][0]
            self.loadRecGroupList()
            return

        cnt = 0
        curIdx = 0
        curt = string.upper(self.curTitle[:str(self.curTitle).rfind("(")-1])

        debug ( curt )        
        xbmcgui.lock()
        try:
            ctl.reset()
            try:
                ctl.setPageControlVisible(False)
            except:
                pass
      
            for r in self.showTitles:
                if string.upper(r[0]) == curt:
                    curIdx = cnt
                cnt += 1
                title = mythtv.convToGUIEncoding( r[0] )
                ctl.addItem( "%s (%s shows)" % (title, str(r[1])) )
            ctl.selectItem( curIdx )
            xbmcgui.unlock()
        except:
            traceback.print_exc()
            xbmcgui.unlock()
        self.loadEpisodeList()
        debug( '< mythtvrecordedshows.Window.loadTitleList()' )
    
    def loadEpisodeList( self ):
        debug( '> mythtvrecordedshows.Window.loadShowList()' )
        curt = self.curTitle[:str(self.curTitle).rfind("(")-1]
        recg = self.recGroup # self.recGroup[:str(self.recGroup).rfind("(")-1]
        debug ( "%s - %s" % (recg, curt ) )
        self.recordings = self.conn.getRecordings( recg, curt )
        debug ( "%s Recordings Found for Title %s" % ( str(len(self.recordings) ), str(curt) ) )

        ## If current title has no recordings then swap back to all shows (current title has been deleted)
        if len(self.recordings) == 0 and string.upper(curt) != "ALL SHOWS":
            self.curTitle = "All Shows (x shows)"
            self.loadTitleList()
            return

        try:   
            if self.viewBy == self.VIEW_BY_DATE_ASC:
                self.recordings.sort( compareDateAsc )
            elif self.viewBy == self.VIEW_BY_DATE_DESC:
                self.recordings.sort( compareDateDesc )
            elif self.viewBy == self.VIEW_BY_TITLE_ASC:
                self.recordings.sort( compareTitleAsc )
            elif self.viewBy == self.VIEW_BY_TITLE_DESC:
                self.recordings.sort( compareTitleDesc )
    
            ctl = self.controls["episode_list"].control
        except:
            traceback.print_exc()
            raise
        
        xbmcgui.lock()
        try:
            self.controls["view_by"].control.setLabel( \
                mythtvutil.getLocalizedString( self.viewByLabel[self.viewBy] ) )

            ctl.reset()
            for r in self.recordings:
                ctl.addItem( self.buildListEntry( r ) )
            if len( self.recordings ) > 0:
                self.populateShowDetails( 0 )

            xbmcgui.unlock()
        except:
            traceback.print_exc()
            xbmcgui.unlock()
            raise

        try:
            freeSpace = getInstance( "mythtv.Connection" ).getFreeSpace()
            self.controls['free_space'].control.setLabel( freeSpace[0] )
        except Exception, ex:
            self.controls['free_space'].control.setLabel( \
                mythtvutil.getLocalizedString( 45 ) )
            traceback.print_exc()

        debug( '< mythtvrecordedshows.Window.loadShowList()' )

    def onActionHook( self, action ):
        debug("> mythtvrecordedshows.Window.onActionHook( action=[%s] )"%action)

        self.focusControl = self.getFocus()

        if action == mythtvgui.ACTION_PREVIOUS_MENU:
            getInstance( mythtv.Settings ).saveSettings()

        debug( "< mythtvrecordedshows.Window.onActionHook()" )
        return 0

    def onActionPostHook( self, action ):
        debug( "> mythtvrecordedshows.Window.onActionPostHook( action=[%s] )"%action )

        # check if the action was to move up or down
        if action == mythtvgui.ACTION_MOVE_UP or \
            action == mythtvgui.ACTION_MOVE_DOWN or \
            action == mythtvgui.ACTION_SCROLL_UP or \
            action == mythtvgui.ACTION_SCROLL_DOWN:

            # check if the control in focus is the show list
            id = self.getcontrolid( self.focusControl )
            if id == "recgroup_list":
                if self.updateEpisodesOnScroll:
                    # give gui time to update
                    time.sleep( 0.10 )
                    # Update episode list with new shows
                    rg = self.recGroups[self.focusControl.getSelectedPosition()]
                    self.recGroup = "%s" % ( rg[0])
                    getInstance( mythtv.Settings ).setSetting( \
                        "recorded_default_group", \
                        "%s"%self.recGroup, shouldCreate=1 )
                    self.curTitle = "All Shows (0 shows)"
                    self.loadTitleList()
            elif id == "episode_list":
                # give gui time to update
                time.sleep( 0.10 )
                # get selected show and populate details
                self.populateShowDetails(
                    self.focusControl.getSelectedPosition() )
            elif id == "show_list":
                if self.updateEpisodesOnScroll:
                    # give gui time to update
                    time.sleep( 0.10 )
                    # Update episode list with new shows
                    ct = self.showTitles[self.focusControl.getSelectedPosition()]
                    self.curTitle = "%s (%s shows)" % ( ct[0], str(ct[1]) )
                    self.loadEpisodeList()

        debug( "< mythtvrecordedshows.Window.onActionPostHook()" )

    def onControlHook( self, control ):
        debug( "> mythtvrecordedshows.Window.onControlHook()" )

        id = self.getcontrolid( control )
        if id == "view_by":
            self.viewBySelected()
        elif id == "episode_list":
            self.showSelected( control )
        elif id == "recgroup_list":
            if not self.updateEpisodesOnScroll:            
                rg = self.recGroups[self.focusControl.getSelectedPosition()]
                self.recGroup = "%s" % ( rg[0])
                self.curTitle = "All Shows (0 shows)"
                self.loadTitleList()
        elif id == "show_list":
            if not self.updateEpisodesOnScroll:
                ct = self.showTitles[self.focusControl.getSelectedPosition()]
                self.curTitle = "%s (%s shows)" % ( ct[0], str(ct[1]) )
                self.loadEpisodeList()
        elif id == "refresh":
            self.loadRecGroupList()

        debug( "< mythtvrecordedshows.Window.onControlHook()" )
        return 1

    def populateShowDetails( self, pos ):
        debug( "> mythtvrecordedshows.Window.populateShowDetails( pos=%d)"%pos )

        if pos < len( self.recordings ):
            row = self.recordings[pos]

            # populate title
            self.controls['show_title'].control.reset()
            self.controls['show_title'].control.addLabel( row.fullTitle() )
            debug( "show_title=[%s]"%row.fullTitle() )

            # populate air date
            self.controls['show_air_date'].control.setLabel( \
                row.formattedAirDate() )
            debug( "show_air_date=[%s]"%row.formattedAirDate() )

            # populate channel
            self.controls['show_channel'].control.setLabel( \
                row.formattedChannel() )
            debug( "show_channel=[%s]"%row.formattedChannel() )

            # populate orig air
            self.controls['show_orig_air'].control.setLabel( \
                row.formattedOrigAirDate() )
            debug( "show_orig_air=[%s]"%row.formattedOrigAirDate() )

            # populate description
            self.controls['show_descr'].control.reset()
            self.controls['show_descr'].control.addLabel( \
                row.formattedDescription() )
            debug( "show_descr=[%s]"%row.formattedDescription() )

        debug( "< mythtvrecordedshows.Window.populateShowDetails( pos=%d)"%pos )

    def showSelected( self, control ):
        debug( "> mythtvrecordedshows.Window.showSelected()" )

        pos = control.getSelectedPosition()
        if pos < len( self.recordings ):
            self.loadingShow(self.recordings[pos])
            rc = mythtvrecordedshowdetails.showWindow(self.recordings[pos])
            self.loadingRemove()
            # refresh list if show was deleted
            if rc == 1:
                self.loadRecGroupList()

        debug( "< mythtvrecordedshows.Window.showSelected()" )

    def viewBySelected( self ):
        debug( "> mythtvrecordedshows.Window.viewBySelected()" )

        # switch to next view by
        self.viewBy += 1
        if self.viewBy >= self.VIEW_BY_MAX:
            self.viewBy = self.VIEW_BY_MIN+1

        # store the setting change
        getInstance( mythtv.Settings ).setSetting( \
            "recorded_view_by", \
            "%d"%self.viewBy, \
            shouldCreate=1 )

        # refresh the listing
        self.loadEpisodeList()

        debug( "< mythtvrecordedshows.Window.viewBySelected()" )

if __name__ == "__main__":
    try:
#        mythtvutil.debugOff()
        loadingWin = xbmcgui.DialogProgress()
        loadingWin.create("Recorded Shows","Loading Recorded Shows","Please Wait...")    
        mythtvutil.debugSetLevel( mythtvutil.DEBUG_NONE )
        mythtvutil.initialize()
        showWindow(loadingWin)

    except Exception, ex:
        traceback.print_exc()
        Dialog().ok( mythtvutil.getLocalizedString( 27 ), str( ex ) )

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.