Beispiel #1
0
    def __init__(self, parent):
        logger.log( 9, 'manual_record.ManualRecordItem.__init__(parent)')
        Item.__init__(self, parent, skin_type='video')

        self.name = _("Manual Record")

        self.recordclient = RecordClient()

        # maxinum number of days we can record
        self.MAXDAYS = 7

        # minimum amount of time it would take record_server.py
        # to pick us up in seconds by default it is one minute plus
        # a few seconds just in case
        self.MINPICKUP = 70

        self.months = [
            _('Jan'), _('Feb'), _('Mar'), _('Apr'), _('May'), _('Jun'),
            _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec')
        ]

        now = time.time()
        now += 300
        self.startnow = now
        self.starttime = time.localtime(now)
        now += 1900
        self.stopnow = now
        self.stoptime = time.localtime(now)
Beispiel #2
0
    def __init__(self, standalone=False):
        """
        init the upsoon plugin
        """
        logger.log( 9, 'upsoon.PluginInterface.__init__()')
        plugin.DaemonPlugin.__init__(self)
        plugin.register(self, 'upsoon')
        self.standalone = standalone
        self.lock = thread.allocate_lock()
        self.running = True
        self.timer = Timer(self.timer_handler).start(15)
        self.event = EventHandler(self.event_handler)
        #self.event.register(('VIDEO_START', 'VIDEO_END'))
        self.event.register()

        self.recordclient = RecordClient()

        self.fc = FreevoChannels()
        self.rdev = config.RADIO_DEVICE

        self.next_program = None
        self.announced = False
        self.seconds_before_announce = config.TV_UPSOON_ANNOUNCE
        self.seconds_before_start = config.TV_UPSOON_BEFORE_START
        self.pending_lockfile = config.FREEVO_CACHEDIR + '/record.soon'
        self.tv_lockfile = None # lockfile of recordserver
        self.stopped = None     # flag that tells upsoon what stopped
        if os.path.exists(self.pending_lockfile):
            os.remove(self.pending_lockfile)
            logger.debug('%r lockfile removed', self.pending_lockfile)
Beispiel #3
0
    def __init__(self, standalone=False):
        """
        init the upsoon plugin
        """
        _debug_('upsoon.PluginInterface.__init__()', 2)
        plugin.DaemonPlugin.__init__(self)
        plugin.register(self, 'upsoon')
        self.standalone = standalone
        self.lock = thread.allocate_lock()
        self.running = True
        self.timer = Timer(self.timer_handler).start(15)
        self.event = EventHandler(self.event_handler)
        #self.event.register(('VIDEO_START', 'VIDEO_END'))
        self.event.register()

        self.recordclient = RecordClient()

        self.fc = FreevoChannels()
        self.rdev = config.RADIO_DEVICE

        self.next_program = None
        self.seconds_before_announce = 120
        self.seconds_before_start = 60
        self.pending_lockfile = config.FREEVO_CACHEDIR + '/record.soon'
        self.tv_lockfile = None  # lockfile of recordserver
        self.stopped = None  # flag that tells upsoon what stopped
Beispiel #4
0
    def __init__(self, parent, prog, context='menu'):
        Item.__init__(self, parent, skin_type='video')
        logger.log( 9, '__init__(parent=%r, prog=%r, context=%r)', parent, prog, context)
        # prog is a TvProgram object as we get it from the recordserver
        self.prog = prog
        self.context= context

        if hasattr(prog, 'name'): self.name = self.title = prog.name
        if hasattr(prog, 'title'): self.title = self.name = Unicode(prog.title)
        if hasattr(prog, 'sub_title'): self.sub_title = prog.sub_title
        if hasattr(prog, 'desc'): self.description = prog.desc
        if hasattr(prog, 'categories'):self.categories = prog.categories
        if hasattr(prog, 'ratings'): self.ratings = prog.ratings
        if hasattr(prog, 'advisories'): self.advisories = prog.advisories

        self.channel = tv_util.get_chan_displayname(prog.channel_id)
        if hasattr(prog, 'scheduled'):
            self.scheduled = prog.scheduled
        else:
            self.scheduled = False

        self.favorite = False
        self.allowDuplicates = prog.allowDuplicates
        self.onlyNew = prog.onlyNew
        self.overlap = prog.overlap

        self.start = time.strftime(config.TV_DATETIME_FORMAT, time.localtime(prog.start))
        self.stop = time.strftime(config.TV_DATETIME_FORMAT, time.localtime(prog.stop))
        self.recordclient = RecordClient()
Beispiel #5
0
def search_for_more(arg=None, menuw=None):
    parent, title = arg
    # this might take some time, thus we open a popup messages
    logger.log( 9, String('searching for: %s', title))
    pop = dialog.show_working_indicator(_('Searching, please wait...'))

    # do the search
    (status, matches) = RecordClient().findMatchesNow(title)
    pop.hide()
    if status:
        items = []
        logger.log( 9, 'search found %s matches', len(matches))
        # sort by start times
        f = lambda a, b: cmp(a.start, b.start)
        matches.sort(f)
        for prog in matches:
            items.append(ProgramItem(parent, prog, context='search'))
    elif matches == 'no matches':
        # there have been no matches
        msgtext = _('No matches found for %s') % self.title
        dialog.show_alert(msgtext)
        return
    else:
        # something else went wrong
        msgtext = _('Search failed') +(':\n%s' % matches)
        dialog.show_alert(msgtext)
        return

    # create a menu from the search result
    search_menu = Menu(_('Search Results'), items, item_types='tv program menu')
    # do not return from the search list to the submenu
    # where the search was initiated
    menuw.delete_submenu(refresh = False)
    menuw.pushmenu(search_menu)
    menuw.refresh()
Beispiel #6
0
    def __init__(self, start_time, player, menuw):
        _debug_(
            'TVGuide.__init__(start_time=%r, player=%r, menuw=%r)' %
            (start_time, player, menuw), 2)
        Item.__init__(self)

        # get skin definitions of the TVGuide
        self.n_items, self.hours_per_page = skin.items_per_page(('tv', self))
        # end of visible guide
        stop_time = start_time + self.hours_per_page * 60 * 60

        # constructing the guide takes some time
        msgtext = _('Preparing the program guide')
        guide = tv.epg_xmltv.get_guide(PopupBox(text=msgtext))
        # getting channels
        channels = guide.get_programs(start_time + 1, stop_time - 1)
        if not channels:
            AlertBox(text=_('TV Guide is corrupt!')).show()
            return

        # select the first available program
        selected = None
        for chan in channels:
            if chan.programs:
                self.selected = chan.programs[0]
                break

        self.recordclient = RecordClient()
        self.col_time = 30  # each col represents 30 minutes
        self.n_cols = (stop_time - start_time) / 60 / self.col_time
        self.player = player

        self.type = 'tv'
        self.menuw = menuw
        self.visible = True
        self.select_time = start_time
        self.last_update = 0

        self.lastinput_value = None
        self.lastinput_time = None

        self.update_schedules(force=True)

        self.event_context = 'tvmenu'
        self.rebuild(start_time, stop_time, guide.chan_list[0].id, selected)
        menuw.pushmenu(self)
    def __init__(self, parent, fav, fav_action='edit'):
        """ """
        Item.__init__(self, parent, skin_type='video')
        _debug_('FavoriteItem.__init__(parent=%r, fav=%r, fav_action=%r)' % (parent, fav, fav_action), 2)
        self.recordclient = RecordClient()
        self.fav   = fav
        self.name  = self.origname = fav.name
        self.title = fav.title
        self.fav_action = fav_action
        # twisted needs FALSE and TRUE, it does not know False and True
        if hasattr(fav,'allowDuplicates') and not fav.allowDuplicates:
            self.allowDuplicates = fav.allowDuplicates = FALSE
        else:
            self.allowDuplicates = fav.allowDuplicates = TRUE
        # twisted needs FALSE and TRUE, it does not know False and True
        if hasattr(fav,'onlyNew') and fav.onlyNew:
            self.onlyNew = fav.onlyNew = TRUE
        else:
            self.onlyNew = fav.onlyNew = FALSE

        self.week_days = (_('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun'))

        if fav.channel == 'ANY':
            self.channel = _('ANY CHANNEL')
        else:
            self.channel = fav.channel
        if fav.dow == 'ANY':
            self.dow = _('ANY DAY')
        else:
            self.dow = self.week_days[int(fav.dow)]
        if fav.mod == 'ANY':
            self.mod = _('ANY TIME')
        else:
            try:
                self.mod = time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(int(fav.mod) * 60)))
            except:
                print 'Cannot add "%s" to favorites' % fav.name

        # needed by the inputbox handler
        self.menuw = None

        self.red_action = (self.display_submenu,_('Edit favorite'))
        self.green_action = (self.rem_favorite, _('Remove favorite'))
Beispiel #8
0
    def __init__(self, parent, fav, fav_action='edit'):
        """ """
        Item.__init__(self, parent, skin_type='video')
        logger.log(9,
                   'FavoriteItem.__init__(parent=%r, fav=%r, fav_action=%r)',
                   parent, fav, fav_action)
        self.recordclient = RecordClient()
        self.fav = fav
        self.name = self.origname = fav.name
        self.title = fav.title
        self.fav_action = fav_action
        if hasattr(fav, 'allowDuplicates'):
            self.allowDuplicates = int(fav.allowDuplicates)

        if hasattr(self.fav, 'onlyNew'):
            self.onlyNew = int(fav.onlyNew)

        self.week_days = (_('Monday'), _('Tuesday'), _('Wednesday'),
                          _('Thursday'), _('Friday'), _('Saturday'),
                          _('Sunday'))

        if fav.channel == 'ANY':
            self.channel = _('ANY CHANNEL')
        else:
            self.channel = fav.channel
        if fav.dow == 'ANY':
            self.dow = _('ANY DAY')
        else:
            self.dow = self.week_days[int(fav.dow)]
        if fav.mod == 'ANY':
            self.mod = _('ANY TIME')
        else:
            try:
                self.mod = time.strftime(config.TV_TIME_FORMAT,
                                         time.gmtime(float(int(fav.mod) * 60)))
            except:
                print 'Cannot add "%s" to favorites' % fav.name

        # needed by the inputbox handler
        self.menuw = None
Beispiel #9
0
    def __init__(self, parent, prog, context='menu'):
        Item.__init__(self, parent, skin_type='video')
        logger.log(9, '__init__(parent=%r, prog=%r, context=%r)', parent, prog,
                   context)
        # prog is a TvProgram object as we get it from the recordserver
        self.prog = prog
        self.context = context

        if hasattr(prog, 'name'): self.name = self.title = prog.name
        if hasattr(prog, 'title'): self.title = self.name = Unicode(prog.title)
        if hasattr(prog, 'sub_title'): self.sub_title = prog.sub_title
        if hasattr(prog, 'desc'): self.description = prog.desc
        if hasattr(prog, 'categories'): self.categories = prog.categories
        if hasattr(prog, 'ratings'): self.ratings = prog.ratings
        if hasattr(prog, 'advisories'): self.advisories = prog.advisories

        self.channel = tv_util.get_chan_displayname(prog.channel_id)
        if hasattr(prog, 'scheduled'):
            self.scheduled = prog.scheduled
        else:
            self.scheduled = False

        self.favorite = False
        if hasattr(prog, 'allowDuplicates'):
            self.allowDuplicates = prog.allowDuplicates
        else:
            self.allowDuplicates = 1

        if hasattr(prog, 'onlyNew'):
            self.onlyNew = prog.onlyNew
        else:
            self.onlyNew = 0

        self.overlap = prog.overlap

        self.start = time.strftime(config.TV_DATETIME_FORMAT,
                                   time.localtime(prog.start))
        self.stop = time.strftime(config.TV_DATETIME_FORMAT,
                                  time.localtime(prog.stop))
        self.recordclient = RecordClient()
Beispiel #10
0
    def __init__(self, parent):
        _debug_('manual_record.ManualRecordItem.__init__(parent)', 2)
        Item.__init__(self, parent, skin_type='video')

        self.name = _("Manual Record")

        self.recordclient = RecordClient()

        # maxinum number of days we can record
        self.MAXDAYS = 7

        # minimum amount of time it would take record_server.py
        # to pick us up in seconds by default it is one minute plus
        # a few seconds just in case
        self.MINPICKUP = 70

        self.months = [
            _('Jan'),
            _('Feb'),
            _('Mar'),
            _('Apr'),
            _('May'),
            _('Jun'),
            _('Jul'),
            _('Aug'),
            _('Sep'),
            _('Oct'),
            _('Nov'),
            _('Dec')
        ]

        now = time.time()
        now += 300
        self.startnow = now
        self.starttime = time.localtime(now)
        now += 1900
        self.stopnow = now
        self.stoptime = time.localtime(now)
Beispiel #11
0
    def __init__(self, parent, fav, fav_action='edit'):
        """ """
        Item.__init__(self, parent, skin_type='video')
        logger.log( 9, 'FavoriteItem.__init__(parent=%r, fav=%r, fav_action=%r)', parent, fav, fav_action)
        self.recordclient = RecordClient()
        self.fav   = fav
        self.name  = self.origname = fav.name
        self.title = fav.title
        self.fav_action = fav_action
        if hasattr(fav, 'allowDuplicates'):
            self.allowDuplicates = int(fav.allowDuplicates)

        if hasattr(self.fav, 'onlyNew'):
            self.onlyNew = int(fav.onlyNew)

        self.week_days = (_('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'))


        if fav.channel == 'ANY':
            self.channel = _('ANY CHANNEL')
        else:
            self.channel = fav.channel
        if fav.dow == 'ANY':
            self.dow = _('ANY DAY')
        else:
            self.dow = self.week_days[int(fav.dow)]
        if fav.mod == 'ANY':
            self.mod = _('ANY TIME')
        else:
            try:
                self.mod = time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(int(fav.mod) * 60)))
            except:
                print 'Cannot add "%s" to favorites' % fav.name

        # needed by the inputbox handler
        self.menuw = None
Beispiel #12
0
    if opts.update:
        tv.epg.update(config.XMLTV_FILE)
    else:
        grab()

    import kaa
    from tv.record_client import RecordClient

    def handler(result):
        if result:
            print _('Updated recording schedule')
        else:
            print _('Not updated recording schedule')
        raise SystemExit


    rc = RecordClient()
    try:
        kaa.inprogress(rc.channel).wait()
    except Exception, why:
        print 'Cannot connect to record server'
        raise SystemExit

    print 'Scheduling favorites for recording:  '
    if not rc.updateFavoritesSchedule(handler):
        print rc.recordserverdown
        raise SystemExit

    kaa.main.run()
Beispiel #13
0
class FavoriteItem(Item):
    """
    Item class for favorite items
    """
    def __init__(self, parent, fav, fav_action='edit'):
        """ """
        Item.__init__(self, parent, skin_type='video')
        logger.log(9,
                   'FavoriteItem.__init__(parent=%r, fav=%r, fav_action=%r)',
                   parent, fav, fav_action)
        self.recordclient = RecordClient()
        self.fav = fav
        self.name = self.origname = fav.name
        self.title = fav.title
        self.fav_action = fav_action
        if hasattr(fav, 'allowDuplicates'):
            self.allowDuplicates = int(fav.allowDuplicates)

        if hasattr(self.fav, 'onlyNew'):
            self.onlyNew = int(fav.onlyNew)

        self.week_days = (_('Monday'), _('Tuesday'), _('Wednesday'),
                          _('Thursday'), _('Friday'), _('Saturday'),
                          _('Sunday'))

        if fav.channel == 'ANY':
            self.channel = _('ANY CHANNEL')
        else:
            self.channel = fav.channel
        if fav.dow == 'ANY':
            self.dow = _('ANY DAY')
        else:
            self.dow = self.week_days[int(fav.dow)]
        if fav.mod == 'ANY':
            self.mod = _('ANY TIME')
        else:
            try:
                self.mod = time.strftime(config.TV_TIME_FORMAT,
                                         time.gmtime(float(int(fav.mod) * 60)))
            except:
                print 'Cannot add "%s" to favorites' % fav.name

        # needed by the inputbox handler
        self.menuw = None

    def actions(self):
        logger.log(9, 'actions()')
        return [(self.display_submenu, _('Edit favorite')),
                (self.priority_up, _('Increase priority')),
                (self.priority_down, _('Decrease priority')),
                (self.rem_favorite, _('Remove favorite'))]

    def display_submenu(self, arg=None, menuw=None):
        """ Display menu for a favorite

        With this menu the user can made a program a favorite.
        All attributes of a favorite can be edited here and in the end
        the user must select 'save changes' to finally create the favorite.
        """
        logger.log(9, 'display_submenu(arg=%r, menuw=%r)', arg, menuw)
        ### create menu items for editing the favorites attributes
        items = []

        items.append(
            menu.MenuItem(_('Name') + u'\t' + _(self.name),
                          action=self.mod_name))
        items.append(
            menu.MenuItem(_('Channel') + u'\t' + _(self.channel),
                          action=self.mod_channel))
        items.append(
            menu.MenuItem(_('Day of the Week') + u'\t' + _(self.dow),
                          action=self.mod_day))
        items.append(
            menu.MenuItem(_('Time of Day') + u'\t' + _(self.mod),
                          action=self.mod_time))

        if config.TV_RECORD_DUPLICATE_DETECTION:
            if self.allowDuplicates:
                value = _('Allow duplicates')
            else:
                value = _('Prevent duplicates')
            items.append(
                menu.MenuItem(_('Duplicate Recordings') + u'\t' + _(value),
                              action=self.alter_prop,
                              arg=('dup', not self.allowDuplicates)))

        if config.TV_RECORD_ONLY_NEW_DETECTION:
            if self.onlyNew:
                value = _('Only new episodes')
            else:
                value = _('All episodes')
            items.append(
                menu.MenuItem(_('Episode Filter') + u'\t' + _(value),
                              action=self.alter_prop,
                              arg=('new', not self.onlyNew)))

        # XXX: priorities aren't quite supported yet
        if 0:
            (status, favorites) = self.recordclient.getFavoritesNow()
            if status and len(favorites) > 1:
                items.append(
                    menu.MenuItem(_('Modify priority'),
                                  action=self.mod_priority))

        ### save favorite
        items.append(
            menu.MenuItem(_('Save changes') + u'\t', action=self.save_changes))

        ### remove this program from favorites
        if not self.fav_action == 'add':
            items.append(
                menu.MenuItem(_('Remove favorite') + u'\t',
                              action=self.rem_favorite))

        ### put the whole menu together
        favorite_menu = menu.Menu(_('Favorite Menu'),
                                  items,
                                  item_types='tv favorite menu')
        favorite_menu.infoitem = self
        favorite_menu.is_submenu = True
        favorite_menu.table = (50, 50)
        menuw.pushmenu(favorite_menu)
        menuw.refresh()

    ### Actions:

    def mod_name(self, arg=None, menuw=None):
        """ Modify name

        This opens a input box to ask the user for a new name for this favorite.
        The default name of a favorite is the name of the program.
        """
        logger.log(9, 'mod_name(arg=%r, menuw=%r)', arg, menuw)
        self.menuw = menuw
        InputBox(text=_('Alter Name'), handler=self.alter_name, \
            width=osd.get_singleton().width - config.OSD_OVERSCAN_LEFT - 20, input_text=self.name).show()

    def alter_name(self, name):
        """ set the new name"""
        logger.log(9, 'alter_name(name=%r)', name)
        if name:
            self.name = self.fav.name = name.strip()
        menustack = self.menuw.menustack[-1]
        menustack.selected.dirty = True
        self.menuw.refresh()

    def mod_channel(self, arg=None, menuw=None):
        """Modify channel"""
        logger.log(9, 'mod_channel(arg=%r, menuw=%r)', arg, menuw)
        items = []

        items.append(
            menu.MenuItem('ANY CHANNEL',
                          action=self.alter_prop,
                          arg=('channel', 'ANY')))

        for chanline in config.TV_CHANNELS:
            items.append(
                menu.MenuItem(chanline[1],
                              action=self.alter_prop,
                              arg=('channel', chanline[1])))

        favorite_menu = menu.Menu(_('Modify Channel'),
                                  items,
                                  item_types='tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()

    def mod_day(self, arg=None, menuw=None):
        """ Modify day

        Opens a submenu where the day of the week of a favorite can be configured.
        """
        logger.log(9, 'mod_day(arg=%r, menuw=%r)', arg, menuw)
        items = []

        items.append(
            menu.MenuItem(_('ANY DAY'),
                          action=self.alter_prop,
                          arg=('dow', 'ANY')))

        for i in range(len(self.week_days)):
            items.append(
                menu.MenuItem(self.week_days[i],
                              action=self.alter_prop,
                              arg=('dow', i)))

        favorite_menu = menu.Menu(_('Modify Day'),
                                  items,
                                  item_types='tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()

    def mod_time(self, arg=None, menuw=None):
        """ Modify time

        Opens a submenu where the time of a favorite can be configured.
        """
        logger.log(9, 'mod_time(arg=%r, menuw=%r)', arg, menuw)
        items = []

        items.append(
            menu.MenuItem(_('ANY TIME'),
                          action=self.alter_prop,
                          arg=('mod', 'ANY')))

        for i in range(48):
            mod = i * 30
            items.append(menu.MenuItem(time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(mod * 60))), \
                action=self.alter_prop, arg=('mod', mod)))

        favorite_menu = menu.Menu(_('Modify Time'),
                                  items,
                                  item_types='tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()

    def alter_prop(self, arg=(None, None), menuw=None):
        """ Alter a favorites property

        This function is where the properties of a favorite really are changed.
        """
        logger.log(9, 'alter_prop(arg=%r, menuw=%r)', arg, menuw)
        (prop, val) = arg
        new_text = None
        new_arg = None
        back = True

        if prop == 'channel':
            if val == 'ANY':
                self.channel = 'ANY CHANNEL'
                self.fav.channel = 'ANY'
            else:
                self.channel = val
                self.fav.channel = val
            new_text = _('Channel') + u'\t' + _(self.channel)

        elif prop == 'dow':
            if val == 'ANY':
                self.dow = 'ANY DAY'
                self.fav.dow = 'ANY'
            else:
                self.dow = self.week_days[val]
                self.fav.dow = val
            new_text = _('Day of the Week') + u'\t' + _(self.dow)

        elif prop == 'mod':
            if val == 'ANY':
                self.mod = 'ANY TIME'
                self.fav.mod = 'ANY'
            else:
                # self.mod = tv_util.minToTOD(val)
                self.mod = time.strftime(config.TV_TIME_FORMAT,
                                         time.gmtime(float(val * 60)))
                self.fav.mod = val
            new_text = _('Time of Day') + u'\t' + _(self.mod)

        elif prop == 'dup':
            self.allowDuplicates = self.fav.allowDuplicates = val
            if val:
                value = _('Allow Duplicates')
            else:
                value = _('Prevent Duplicates')

            new_text = _('Duplicate Recordings') + u'\t' + value
            new_arg = ('dup', not val)
            back = False

        elif prop == 'new':
            self.onlyNew = self.fav.onlyNew = val
            if val:
                value = _('Only New Episodes')
            else:
                value = _('All New Episodes')
            new_text = _('Episode Filter') + u'\t' + value
            new_arg = ('new', not val)
            back = False

        if menuw and new_text:
            menu = menuw.menustack[back and -2 or -1]
            menu.selected.name = new_text
            if new_arg:
                menu.selected.arg = new_arg
            menu.selected.dirty = True
            if back:
                menuw.back_one_menu(arg='reload')
            else:
                menuw.refresh()

    def save_changes(self, arg=None, menuw=None):
        """
        Save favorite
        """
        logger.log(9, 'save_changes(arg=%r, menuw=%r)', arg, menuw)
        # this can take some time, as it means although to update the schedule
        msgtext = _('Saving the changes to this favorite.') + '\n' + _(
            'This may take some time.')
        pop = dialog.show_working_indicator(msgtext)

        if self.fav_action == 'edit':
            # first we remove the old favorite
            (result, msg) = self.recordclient.removeFavoriteNow(self.origname)
        elif self.fav_action == 'add':
            result = True

        if result:
            # create a new edited favorite
            (result, msg) = self.recordclient.addEditedFavoriteNow(
                self.fav.name, self.fav.title, self.fav.channel, self.fav.dow,
                self.fav.mod, self.fav.priority, self.fav.allowDuplicates,
                self.fav.onlyNew)
            if result:
                if menuw:
                    menuw.delete_submenu()
                    if self.fav_action == 'add':
                        menuw.refresh(reload=1)
                self.fav_action = 'edit'
                pop.hide()
            else:
                pop.hide()
                # it is important to show the user this error,
                # because that means the favorite is removed,
                # and must be created again
                msgtext = _('Save failed, favorite was lost') + (':\n%s' % msg)
                dialog.show_alert(msgtext)

    def rem_favorite(self, arg=None, menuw=None):
        """
        Remove favorite
        """
        logger.log(9, 'rem_favorite(arg=%r, menuw=%r)', arg, menuw)
        name = self.origname
        (result, msg) = self.recordclient.removeFavoriteNow(name)
        if result:
            # if this is successfull
            if menuw:
                menuw.delete_submenu()
                menuw.refresh(reload=1)
            # and show a short message of success
            msgtext = text = _('"%s" has been removed from favorites') % name
            dialog.show_alert(msgtext)
        else:
            # if all fails then we should show an error
            msgtext = _('Remove failed') + (':\n%s' % msg)
            dialog.show_alert(msgtext)

    def priority_mod(self, adjust, menuw=None):
        """
        Move current item in the priority list and refresh menu to
        show new position
        """
        name = self.origname
        result = self.recordclient.adjustPriorityNow(name, adjust)
        if result:
            # if this is successfull
            if menuw:
                menuw.delete_submenu()
                menuw.refresh(reload=1)
            else:
                event.Event('MENU_RELOAD').post()
        else:
            # if all fails then we should show an error
            msgtext = _('Priority adjustment failed') + (':\n%s' % msg)
            dialog.show_message(msgtext)

    def priority_up(self, arg=None, menuw=None):
        self.priority_mod(-1, menuw)

    def priority_down(self, arg=None, menuw=None):
        self.priority_mod(1, menuw)
Beispiel #14
0
import os
import time
import sys
import glob
import commands
import config
import plugin
import menu
import event as em
from item import Item
from gui import ConfirmBox
from gui.AlertBox import AlertBox
from tv.record_client import RecordClient
from plugins.shutdown import ShutdownModes, shutdown

recordclient = RecordClient()


class ExInternalError:
    pass


class ExNoRecordServer(Exception):
    pass


class ExRecordServerRemote(Exception):
    pass


class ExNoDefaultWakeup(Exception):
Beispiel #15
0
class TVGuide(Item):
    """
    Class for TVGuide
    """
    def __init__(self, start_time, player, menuw):
        _debug_(
            'TVGuide.__init__(start_time=%r, player=%r, menuw=%r)' %
            (start_time, player, menuw), 2)
        Item.__init__(self)

        # get skin definitions of the TVGuide
        self.n_items, self.hours_per_page = skin.items_per_page(('tv', self))
        # end of visible guide
        stop_time = start_time + self.hours_per_page * 60 * 60

        # constructing the guide takes some time
        msgtext = _('Preparing the program guide')
        guide = tv.epg_xmltv.get_guide(PopupBox(text=msgtext))
        # getting channels
        channels = guide.get_programs(start_time + 1, stop_time - 1)
        if not channels:
            AlertBox(text=_('TV Guide is corrupt!')).show()
            return

        # select the first available program
        selected = None
        for chan in channels:
            if chan.programs:
                self.selected = chan.programs[0]
                break

        self.recordclient = RecordClient()
        self.col_time = 30  # each col represents 30 minutes
        self.n_cols = (stop_time - start_time) / 60 / self.col_time
        self.player = player

        self.type = 'tv'
        self.menuw = menuw
        self.visible = True
        self.select_time = start_time
        self.last_update = 0

        self.lastinput_value = None
        self.lastinput_time = None

        self.update_schedules(force=True)

        self.event_context = 'tvmenu'
        self.rebuild(start_time, stop_time, guide.chan_list[0].id, selected)
        menuw.pushmenu(self)

    def update_schedules_cb(self, scheduledRecordings):
        """ """
        _debug_(
            'update_schedules_cb(scheduledRecordings=%r)' %
            (scheduledRecordings, ), 2)
        #upsoon = '%s/upsoon' % (config.FREEVO_CACHEDIR)
        #if os.path.isfile(upsoon):
        #    os.unlink(upsoon)

        util.misc.comingup(None, (True, scheduledRecordings))
        progs = scheduledRecordings.getProgramList()

        for k in progs:
            prog = progs[k]
            self.scheduled_programs.append(prog.str2utf())
            if prog.overlap:
                self.overlap_programs.append(prog.str2utf())
            if hasattr(prog, 'isFavorite') and prog.isFavorite:
                self.favorite_programs.append(prog.str2utf())

    @benchmark(benchmarking)
    def update_schedules(self, force=False):
        """
        update schedule

        reload the list of scheduled programs and check for overlapping
        """
        _debug_('update_schedules(force=%r)' % (force, ), 2)
        if not force and self.last_update + 60 > time.time():
            return

        _debug_('update schedule', 2)
        self.last_update = time.time()
        self.scheduled_programs = []
        self.overlap_programs = []
        self.favorite_programs = []
        self.recordclient.getScheduledRecordings(self.update_schedules_cb)

    @benchmark(benchmarking)
    def eventhandler(self, event, menuw=None):
        """
        Handles events in the tv guide
        """
        _debug_('eventhandler(event=%r, menuw=%r)' % (event.name, menuw), 2)

        ## MENU_CHANGE_STYLE
        if event == MENU_CHANGE_STYLE:
            if skin.toggle_display_style('tv'):
                start_time = self.start_time
                stop_time = self.stop_time
                start_channel = self.start_channel
                selected = self.selected

                self.n_items, hours_per_page = skin.items_per_page(
                    ('tv', self))

                before = -1
                after = -1
                for c in self.guide.chan_list:
                    if before >= 0 and after == -1:
                        before += 1
                    if after >= 0:
                        after += 1
                    if c.id == start_channel:
                        before = 0
                    if c.id == selected.channel_id:
                        after = 0

                if self.n_items <= before:
                    start_channel = selected.channel_id

                if after < self.n_items:
                    up = min(self.n_items - after, len(
                        self.guide.chan_list)) - 1
                    for i in range(len(self.guide.chan_list) - up):
                        if self.guide.chan_list[i + up].id == start_channel:
                            start_channel = self.guide.chan_list[i].id
                            break

                stop_time = start_time + hours_per_page * 60 * 60

                self.n_cols = (stop_time - start_time) / 60 / self.col_time
                self.rebuild(start_time, stop_time, start_channel, selected)
            return True

        ## MENU_UP: Move one channel up in the guide
        elif event == MENU_UP:
            self.change_channel(-1)
            return True

        ## MENU_DOWN: Move one channel down in the guide
        elif event == MENU_DOWN:
            self.change_channel(1)
            return True

        ## MENU_LEFT: Move to the next program on this channel
        elif event == MENU_LEFT:
            self.change_program(-1)
            return True

        ## MENU_RIGHT: Move to previous programm on this channel
        elif event == MENU_RIGHT:
            self.change_program(1)
            return True

        ## MENU_PAGEUP: Moves to the first of the currently displayed channels
        elif event == MENU_PAGEUP:
            self.change_channel(-self.n_items)
            return True

        ## MENU_PAGEDOWN: Move to the last of the currently displayed channels
        elif event == MENU_PAGEDOWN:
            self.change_channel(self.n_items)
            return True

        ## MENU_SUBMENU: Open a submenu for the selected program
        elif event == MENU_SUBMENU:
            # create a ProgramItem for the selected program
            pi = ProgramItem(self, prog=self.selected, context='guide')
            #and show its submenu
            pi.display_submenu(menuw=self.menuw)
            return True

        ## MENU_SELECT: Show the description
        elif event == MENU_SELECT:
            # create a ProgramItem for the selected program
            pi = ProgramItem(self, prog=self.selected, context='guide')
            #and show selecte the first action in the actions list
            pi.actions()[0][0](menuw=self.menuw)
            return True

        ## TV_START_RECORDING: add or remove this program from schedule
        elif event == TV_START_RECORDING:
            pi = ProgramItem(self, prog=self.selected, context='guide')
            pi.toggle_rec(menuw=self.menuw)
            return True

        ## PLAY: Start to watch the selected channel (if it is possible)
        elif event == PLAY:
            # create a ProgramItem for the selected program
            pi = ProgramItem(self, prog=self.selected, context='guide')
            #and show its submenu
            pi.play(menuw=self.menuw)
            return True

        ## PLAY_END: Show the guide again
        elif event == PLAY_END:
            self.show()
            return True

        # FIX or REMOVE:
        # the numerical INPUT events are not available in the tvmenu context
        ## numerical INPUT: Jump to a specific channel number
        elif event in INPUT_ALL_NUMBERS:
            newinput_time = time.time()
            if self.lastinput_value is not None:
                # allow 1.2 seconds delay for multiple digit channels
                if newinput_time - self.lastinput_time < 1.2:
                    # this enables multiple (max 3) digit channel selection
                    if self.lastinput_value >= 100:
                        self.lastinput_value = (self.lastinput_value % 100)
                    newinput_value = self.lastinput_value * 10 + int(event)
            self.lastinput_value = newinput_value
            self.lastinput_time = newinput_time

            channel_no = int(newinput_value) - 1
            if channel_no < len(self.guide.chan_list):
                self.start_channel = self.guide.chan_list[channel_no].id
            else:
                self.lastinput_value = None

            self.rebuild(self.start_time, self.stop_time, self.start_channel,
                         self.selected)
            return True

        return False

    ### gui functions

    def show(self):
        """ show the guide"""
        _debug_('show', 2)
        if not self.visible:
            self.visible = 1
            self.refresh()

    def hide(self):
        """ hide the guide"""
        _debug_('hide', 2)
        if self.visible:
            self.visible = 0
            skin.clear()

    @benchmark(benchmarking)
    def refresh(self, force_update=True):
        """refresh the guide

        This function is called automatically by freevo whenever this menu is
        opened or reopened.
        """
        _debug_('refresh(force_update=True)', 2)
        if self.menuw.children:
            return
        _debug_('tvguide: setting context to %s' % self.event_context, 2)
        rc.set_context(self.event_context)
        self.update(force_update)
        skin.draw(self.type, self)

    @benchmark(benchmarking)
    def update(self, force=False):
        """ update the guide

        This function updates the scheduled and overlap flags for
        all currently displayed programs.
        """
        _debug_('update(force=False)', 2)
        self.update_schedules(force)
        if self.table:
            for t in self.table:
                try:
                    for p in t.programs:
                        if p in self.scheduled_programs:
                            p.scheduled = True
                            # DO NOT change this to 'True' Twisted
                            # does not support boolean objects and
                            # it will break under Python 2.3
                        else:
                            p.scheduled = False
                            # Same as above; leave as 'False' until
                            # Twisted includes Boolean
                        if p in self.overlap_programs:
                            p.overlap = True
                        else:
                            p.overlap = False

                        if p in self.favorite_programs:
                            p.favorite = True
                        else:
                            p.favorite = False
                except:
                    pass

        #self.refresh()

    def jump_to_now(self, old_selected):
        """
        jump to now in the tv guide.
        """
        _debug_('jump_to_now(old_selected=%r)' % (old_selected, ), 2)
        start_time = time.time()
        stop_time = start_time + self.hours_per_page * 60 * 60
        start_channel = self.start_channel

        # we need to determine the program,
        # that is running now at the selected channel
        programs = self.guide.get_programs(start_time + 1, stop_time - 1,
                                           old_selected.channel_id)

        if len(programs) > 0 and len(programs[0].programs) > 0:
            selected = programs[0].programs[0]
        else:
            selected = None

        self.rebuild(start_time, stop_time, start_channel, selected)

    def advance_tv_guide(self, hours=0):
        """
        advance the tv guide by the number of hours that is passed in arg.
        """
        _debug_('advance_tv_guide(hours=%r)' % (hours, ), 2)
        new_start_time = self.start_time + (hours * 60 * 60)
        new_end_time = self.stop_time + (hours * 60 * 60)
        start_channel = self.start_channel

        # we need to determine the new selected program
        programs = self.guide.get_programs(new_start_time + 1,
                                           new_end_time - 1,
                                           self.start_channel)

        if len(programs) > 0 and len(programs[0].programs) > 0:
            selected = programs[0].programs[0]
        else:
            selected = None

        self.rebuild(new_start_time, new_end_time, start_channel, selected)

    @benchmark(benchmarking)
    def rebuild(self, start_time, stop_time, start_channel, selected):
        """ rebuild the guide

        This is neccessary we change the set of programs that have to be
        displayed, this is the case when the user moves around in the menu.
        """
        _debug_(
            'rebuild(start_time=%r, stop_time=%r, start_channel=%r, selected=%r)'
            % (start_time, stop_time, start_channel, selected), 2)
        self.guide = tv.epg_xmltv.get_guide()
        channels = self.guide.get_programs(start_time + 1, stop_time - 1)

        table = []

        self.start_time = start_time
        self.stop_time = stop_time
        self.start_channel = start_channel
        self.selected = selected

        self.display_up_arrow = False
        self.display_down_arrow = False

        # table header
        table += [['Chan']]
        for i in range(int(self.n_cols)):
            table[0] += [start_time + self.col_time * i * 60]

        table += [self.selected]  # the selected program

        found_1stchannel = 0
        if stop_time == None:
            found_1stchannel = 1

        flag_selected = 0

        n = 0
        for chan in channels:
            if n >= self.n_items:
                self.display_down_arrow = True
                break

            if start_channel != None and chan.id == start_channel:
                found_1stchannel = 1

            if not found_1stchannel:
                self.display_up_arrow = True

            if found_1stchannel:
                if not chan.programs:
                    prg = TvProgram(chan.id,
                                    0,
                                    0,
                                    2147483647,
                                    CHAN_NO_DATA,
                                    desc='')
                    chan.programs = [prg]

                for i in range(len(chan.programs)):
                    if selected:
                        if chan.programs[i] == selected:
                            flag_selected = 1

                table += [chan]
                n += 1

        if flag_selected == 0:
            for i in range(2, len(table)):
                if flag_selected == 1:
                    break
                else:
                    if table[i].programs:
                        for j in range(len(table[i].programs)):
                            if table[i].programs[j].stop > start_time:
                                self.selected = table[i].programs[j]
                                table[1] = table[i].programs[j]
                                flag_selected = 1
                                break

        self.table = table
        # then we can refresh the display with this programs
        #self.update()
        self.refresh(force_update=False)

    @benchmark(benchmarking)
    def change_program(self, value, full_scan=False):
        """
        Move to the next program
        """
        _debug_('change_program(value=%r, full_scan=%r)' % (value, full_scan),
                2)
        start_time = self.start_time
        stop_time = self.stop_time
        start_channel = self.start_channel
        last_prg = self.selected

        channel = self.guide.chan_dict[last_prg.channel_id]
        if full_scan:
            all_programs = self.guide.get_programs(start_time - 24 * 60 * 60,
                                                   stop_time + 24 * 60 * 60,
                                                   channel.id)
        else:
            all_programs = self.guide.get_programs(start_time + 1,
                                                   stop_time - 1, channel.id)

        # Current channel programs
        programs = all_programs[0].programs
        if programs:
            for i in range(len(programs)):
                if programs[i].title == last_prg.title and \
                   programs[i].start == last_prg.start and \
                   programs[i].stop == last_prg.stop and \
                   programs[i].channel_id == last_prg.channel_id:
                    break

            prg = None

            if value > 0:
                if i + value < len(programs):
                    prg = programs[i + value]
                elif full_scan:
                    prg = programs[-1]
                else:
                    return self.change_program(value, True)
            else:
                if i + value >= 0:
                    prg = programs[i + value]
                elif full_scan:
                    prg = programs[0]
                else:
                    return self.change_program(value, True)

            if prg.sub_title:
                procdesc = '"' + prg.sub_title + '"\n' + prg.desc
            else:
                procdesc = prg.desc
            to_info = (prg.title, procdesc)
            self.select_time = prg.start

            # set new (better) start / stop times
            extra_space = 0
            if prg.stop - prg.start > self.col_time * 60:
                extra_space = self.col_time * 60

            while prg.start + extra_space >= stop_time:
                start_time += (self.col_time * 60)
                stop_time += (self.col_time * 60)

            while prg.start + extra_space <= start_time:
                start_time -= (self.col_time * 60)
                stop_time -= (self.col_time * 60)
        else:
            prg = TvProgram(channel.id,
                            0,
                            0,
                            2147483647,
                            CHAN_NO_DATA,
                            desc='')
            to_info = CHAN_NO_DATA

        self.rebuild(start_time, stop_time, start_channel, prg)

    @benchmark(benchmarking)
    def change_channel(self, value):
        """
        Move to the next channel
        """
        _debug_('change_channel(value=%r)' % (value, ), 2)
        start_time = self.start_time
        stop_time = self.stop_time
        start_channel = self.start_channel
        last_prg = self.selected

        for i in range(len(self.guide.chan_list)):
            if self.guide.chan_list[i].id == start_channel:
                start_pos = i
                end_pos = i + self.n_items
            if self.guide.chan_list[i].id == last_prg.channel_id:
                break

        channel_pos = min(len(self.guide.chan_list) - 1, max(0, i + value))

        if value < 0 and channel_pos >= 0 and channel_pos < start_pos:
            start_channel = self.guide.chan_list[start_pos + value].id

        if value > 0 and channel_pos < len(
                self.guide.chan_list) - 1 and channel_pos + 1 >= end_pos:
            start_channel = self.guide.chan_list[start_pos + value].id

        channel = self.guide.chan_list[channel_pos]

        programs = self.guide.get_programs(start_time + 1, stop_time - 1,
                                           channel.id)
        programs = programs[0].programs

        prg = None
        if programs and len(programs) > 0:
            for i in range(len(programs)):
                if programs[i].stop > self.select_time and programs[
                        i].stop > start_time:
                    break

            prg = programs[i]
            if prg.sub_title:
                procdesc = '"' + prg.sub_title + '"\n' + prg.desc
            else:
                procdesc = prg.desc

            to_info = (prg.title, procdesc)
        else:
            prg = TvProgram(channel.id,
                            0,
                            0,
                            2147483647,
                            CHAN_NO_DATA,
                            desc='')
            to_info = CHAN_NO_DATA

        self.rebuild(start_time, stop_time, start_channel, prg)
    def __init__(self, parent=None, subject=None, left=None, top=None, width=500, height=350, context=None):
        """ """
        _debug_('EditFavorite.__init__(parent=%r, subject=%r, left=%r, top=%r, width=%r, height=%r, context=%r)' % \
            (parent, subject, left, top, width, height, context), 1)

        self.oldname = None
        if context:
            self.context = context
        else:
            context = 'guide'

        self.recordclient = RecordClient()
        if isinstance(subject, TvProgram):
            (result, favs) = self.recordclient.getFavorites()
            if result:
                num_favorites = len(favs)
                self.priority = num_favorites + 1
            else:
                self.priority = 1
            self.fav = Favorite(subject.title, subject, TRUE, TRUE, TRUE, self.priority, TRUE, FALSE)

        else:
            self.fav = subject
            self.oldname = self.fav.name

        PopupBox.__init__(self, text=_('Edit Favorite'), x=left, y=top, width=width, height=height)

        self.v_spacing = 15
        self.h_margin = 20
        self.v_margin = 20

        self.internal_h_align = Align.LEFT

        if not self.left:     self.left   = self.osd.width/2 - self.width/2
        if not self.top:      self.top    = self.osd.height/2 - self.height/2

        guide = epg_xmltv.get_guide()

        name = Label(_('Name')+':', self, Align.LEFT)
        self.name_input = LetterBoxGroup(text=self.fav.name)
        self.name_input.h_align = Align.NONE
        self.add_child(self.name_input)


        title = Label(_('Title')+': %s' % self.fav.title, self, Align.LEFT)

        chan = Label(_('Channel')+':', self, Align.LEFT)

        self.chan_box = OptionBox('ANY')
        self.chan_box.h_align = Align.NONE
        self.chan_box.add_item(text=_('ANY'), value='ANY')

        i = 1
        chan_index = 0
        for ch in guide.chan_list:
            #if ch.id == self.fav.channel_id:
            if ch.displayname == self.fav.channel:
                chan_index = i
            i += 1
            self.chan_box.add_item(text=ch.displayname, value=ch.displayname)


        self.chan_box.toggle_selected_index(chan_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.chan_box.change_item(None)
        self.add_child(self.chan_box)

        dow = Label(_('Day of Week') +':', self, Align.LEFT)
        self.dow_box = OptionBox('ANY DAY')
        self.dow_box.h_align = Align.NONE

        self.dow_box.add_item(text=_('ANY DAY'), value='ANY')

        i=1
        dow_index = 0
        for dow in (_('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun')):
            val = "%d" % (i-1)
            self.dow_box.add_item(text=_(dow), value=val )
            if val == self.fav.dow:
                dow_index = i
            i += 1
        self.dow_box.toggle_selected_index(dow_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.dow_box.change_item(None)
        self.add_child(self.dow_box)

        tod = Label(_('Time of Day')+':', self, Align.LEFT)
        self.tod_box = OptionBox('ANY')
        self.tod_box.h_align = Align.NONE
        self.tod_box.add_item(text=_('ANY TIME'), value='ANY')

        i = 0
        tod_index = 0

        for h in range(0, 24):
            for m in (00, 30):
                val = i*30
                # Little hack: we calculate the hours from Jan 1st, 1970 GMT,
                # and then use strftime to get the string representation
                text = strftime(config.TV_TIME_FORMAT, gmtime(h * 3600 + 60 * m))
                self.tod_box.add_item(text=text, value=val)
                if val == self.fav.mod:
                    tod_index = i+1
                i += 1
        self.tod_box.toggle_selected_index(tod_index)
        # This is a hack for setting the OptionBox's label to the current
        # value. It should be done by OptionBox when drawing, but it doesn't
        # work :(
        self.tod_box.change_item(None)
        self.add_child(self.tod_box)

        self.save = Button(_('Save'))
        self.add_child(self.save)
        if self.oldname:
            self.remove = Button(_('Remove'))
            self.add_child(self.remove)
        else:
            self.remove = None
        self.cancel = Button(_('CANCEL'))
        self.add_child(self.cancel)
Beispiel #17
0
def comingup():
    """
    What's coming up in the TV recording schedule
    """
    import time
    import codecs
    from tv.record_client import RecordClient

    result = u''

    (status, progs) = RecordClient().getScheduledRecordingsNow()
    if status is None:
        result = RecordClient().recordserverdown
        return result
    elif status is False:
        result = _('No recordings are scheduled')
        return result


    progs.sort(lambda a, b: cmp(a.start, b.start))

    today = []
    tomorrow = []
    later = []

    for what in progs:
        if time.localtime(what.start)[2] == time.localtime()[2]:
            today.append(what)
        if time.localtime(what.start)[2] == (time.localtime()[2] + 1):
            tomorrow.append(what)
        if time.localtime(what.start)[2] > (time.localtime()[2] + 1):
            later.append(what)

    if len(today) > 0:
        result = result + _('Today') + u':\n'
        for m in today:
            sub_title = ''
            if hasattr(m, 'sub_title') and m.sub_title:
                sub_title = u' "' + Unicode(m.sub_title) + u'" '
            result = result + u"- %s%s " % \
                     ( Unicode(m.title), Unicode(sub_title) ) \
                     + _('at') + u" %s\n" % \
                     Unicode(time.strftime(config.TV_TIME_FORMAT, time.localtime(m.start)))

    if len(tomorrow) > 0:
        result = result + _('Tomorrow') + u':\n'
        for m in tomorrow:
            sub_title = ''
            if hasattr(m, 'sub_title') and m.sub_title:
                sub_title = ' "' + m.sub_title + '" '
            result = result + u"- %s%s " % \
                     ( Unicode(m.title), Unicode(sub_title) ) \
                     + _('at') + u" %s\n" % \
                     Unicode(time.strftime(config.TV_TIME_FORMAT, time.localtime(m.start)))

    if len(later) > 0:
        result = result + _('This Week') + u':\n'
        for m in later:
            sub_title = ''
            if hasattr(m, 'sub_title') and m.sub_title:
                sub_title = ' "' + m.sub_title + '" '
            result = result + u"- %s%s " % ( Unicode(m.title), Unicode(sub_title) ) \
                    + _('at') + u" %s\n" % Unicode(time.strftime(config.TV_DATE_FORMAT, time.localtime(m.start)))

    if not result:
        result = _('No recordings are scheduled')

    return result
Beispiel #18
0
class ViewFavoritesItem(Item):
    def __init__(self, parent):
        logger.log(9, 'ViewFavoritesItem.__init__(parent=%r)', parent)
        Item.__init__(self, parent, skin_type='tv')
        self.name = _('View Favorites')
        self.menuw = None
        self.recordclient = RecordClient()

    def actions(self):
        logger.log(9, 'actions()')
        return [(self.view_favorites, _('View Favorites')),
                (self.reschedule_favorites, _('Reschedule Favorites'))]

    def view_favorites(self, arg=None, menuw=None):
        logger.log(9, 'view_favorites(arg=%r, menuw=%r)', arg, menuw)
        if not self.recordclient.pingNow():
            dialog.show_alert(self.recordclient.recordserverdown)
            return

        items = self.get_items()
        if not len(items):
            dialog.show_alert(_('No favorites.'))
            return

        favorite_menu = menu.Menu(_('View Favorites'),
                                  items,
                                  reload_func=self.reload,
                                  item_types='tv favorite menu')
        self.menuw = menuw
        menuw.pushmenu(favorite_menu)
        menuw.refresh()

    def reschedule_favorites(self, arg=None, menuw=None):
        """
        Force rescheduling of favorites
        """
        logger.log(9, 'resched_favs(arg=%r, menuw=%r)', arg, menuw)
        dialog.show_message(_('Rescheduling Favorites...'))
        self.recordclient.updateFavoritesScheduleCo().connect(
            self.reschedule_favorites_complete)
        if menuw:
            menuw.delete_submenu()

    def reschedule_favorites_complete(self, result):
        if result:
            dialog.show_message(_('Favorites rescheduled'))
        else:
            dialog.show_alert(_('Reschedule failed'))

    def reload(self):
        logger.log(9, 'reload()')
        menuw = self.menuw

        menu = menuw.menustack[-1]

        new_choices = self.get_items()
        if not menu.selected in new_choices and len(new_choices):
            sel = menu.choices.index(menu.selected)
            if len(new_choices) <= sel:
                menu.selected = new_choices[-1]
            else:
                menu.selected = new_choices[sel]

        menu.choices = new_choices

        return menu

    def get_items(self):
        logger.log(9, 'get_items()')
        items = []

        (status, favorites) = self.recordclient.getFavoritesNow()
        if status:
            f = lambda a, b: cmp(a.priority, b.priority)
            favs = favorites.values()
            favs.sort(f)
            for fav in favs:
                items.append(FavoriteItem(self, fav))

        return items
Beispiel #19
0
        if (event.name == 'VIDEO_END'):
            if self.stopped:
                # upsoon stopped the tv, now display a msgbox
                if not self.standalone:
                    AlertBox(text=_('%s stopped, a recording is about to start!') % self.stopped, height=200).show()
                self.stopped = None
        return 0


if __name__ == '__main__':
    # test code, run with freevo execute /path/to/upsoon.py
    config.DEBUG = 2
    function = None
    if len(sys.argv) > 1:
        function = sys.argv[1].lower()
        server = RecordClient()

    if function == 'run':
        #import rc as rctrl
        #rc = rctrl.get_singleton(False)
        pi = PluginInterface()
        kaa.main.run()

    elif function == 'findnextprogram':
        def handler(result):
            print 'findnextprogram=%r' % (result,)
            print result.__dict__
            raise SystemExit
        server.findNextProgram(handler)
        kaa.main.run()
Beispiel #20
0
class ManualRecordItem(Item):

    def __init__(self, parent):
        logger.log( 9, 'manual_record.ManualRecordItem.__init__(parent)')
        Item.__init__(self, parent, skin_type='video')

        self.name = _("Manual Record")

        self.recordclient = RecordClient()

        # maxinum number of days we can record
        self.MAXDAYS = 7

        # minimum amount of time it would take record_server.py
        # to pick us up in seconds by default it is one minute plus
        # a few seconds just in case
        self.MINPICKUP = 70

        self.months = [
            _('Jan'), _('Feb'), _('Mar'), _('Apr'), _('May'), _('Jun'),
            _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec')
        ]

        now = time.time()
        now += 300
        self.startnow = now
        self.starttime = time.localtime(now)
        now += 1900
        self.stopnow = now
        self.stoptime = time.localtime(now)


    def make_newprog(self):
        logger.log( 9, 'make_newprog(self)')
        self.prog = TvProgram()

        self.disp_title = self.prog.title = self.name

        self.description = ''
        self.prog.desc = ''

        self.prog.channel_id = config.TV_CHANNELS[0][0]
        self.disp_channel = config.TV_CHANNELS[0][1]

        #self.start_year = self.starttime[0]
        self.start_month = self.starttime[1]
        self.disp_start_month = self.months[self.start_month - 1]
        self.start_day   = self.starttime[2]
        self.start_time  = time.strftime(config.TV_TIME_FORMAT, self.starttime)
        self.prog.start  = self.startnow
        self.disp_starttime = '%s %s %s' % (self.disp_start_month, self.start_day, self.start_time)

        #self.stop_year = self.stoptime[0]
        self.stop_month = self.stoptime[1]
        self.disp_stop_month = self.months[self.stop_month - 1]
        self.stop_day   = self.stoptime[2]
        self.stop_time  = time.strftime(config.TV_TIME_FORMAT, self.stoptime)
        self.prog.stop  = self.stopnow
        self.disp_stoptime = '%s %s %s' % (self.disp_stop_month, self.stop_day, self.stop_time)


    def actions(self):
        logger.log( 9, 'actions(self)')
        return [( self.display_recitem , _('Display record item') )]


    def display_recitem(self, arg=None, menuw=None):
        logger.log( 9, 'display_recitem(self, arg=None, menuw=None)')
        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return

        self.make_newprog()

        items = []

        items.append(menu.MenuItem(_('Modify name'), action=self.mod_name))
        items.append(menu.MenuItem(_('Modify channel'), action=self.mod_channel))
        items.append(menu.MenuItem(_('Modify start month'), action=self.mod_start_month))
        items.append(menu.MenuItem(_('Modify start day'), action=self.mod_start_day))
        items.append(menu.MenuItem(_('Modify start time'), action=self.mod_start_time))
        items.append(menu.MenuItem(_('Modify stop month'), action=self.mod_stop_month))
        items.append(menu.MenuItem(_('Modify stop day'), action=self.mod_stop_day))
        items.append(menu.MenuItem(_('Modify stop time'), action=self.mod_stop_time))
        items.append(menu.MenuItem(_('Save'), action=self.save_changes))

        manualrecord_menu = menu.Menu(_('Record Item Menu'), items, item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_name(self, arg=None, menuw=None):
        logger.log( 9, 'mod_name(self, arg=None, menuw=None)')
        self.menuw = menuw
        InputBox(text=_('Alter Name'), handler=self.alter_name).show()


    def mod_channel(self, arg=None, menuw=None):
        logger.log( 9, 'mod_channel(self, arg=None, menuw=None)')
        items = []

        for chanline in config.TV_CHANNELS:
            items.append(menu.MenuItem(chanline[1], action=self.alter_prop,
                         arg=('channel', (chanline[1],chanline[0]))))

        manualrecord_menu = menu.Menu(_('Modify Channel'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_start_month(self, arg=None, menuw=None):
        logger.log( 9, 'mod_start_month(self, arg=None, menuw=None)')
        items = []

        iter=0
        while iter < 12:
            month_name = self.months[(iter + self.starttime[1] - 1) % 12];
            month_num  = self.months.index(month_name) + 1;
            items.append(menu.MenuItem(month_name, action=self.alter_prop, arg=('startmonth', (month_name, month_num))))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_start_day(self, arg=None, menuw=None):
        logger.log( 9, 'mod_start_day(self, arg=None, menuw=None)')
        items = []

        numdays = calendar.monthrange(self.starttime[0], self.start_month)[1]
        daylimit = numdays + 1
        iter=1
        while iter < daylimit:
            newday = (iter + self.starttime[2] - 1)
            currday = newday % daylimit
            if newday >= daylimit:
                currday += 1
            items.append(menu.MenuItem(str(currday), action=self.alter_prop,
                         arg=('startday', currday)))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_start_time(self, arg=None, menuw=None):
        logger.log( 9, 'mod_start_time(self, arg=None, menuw=None)')
        items = []

        currminutes = self.starttime[3]*60 + self.starttime[4]
        minpadding = 5 - (currminutes % 5)
        if minpadding == 5:
            minpadding = 0
        for i in range(288):
            mod = (i * 5 + currminutes + minpadding) % 1440
            showtime = strftime(config.TV_TIME_FORMAT, gmtime(float(mod * 60)))
            items.append(menu.MenuItem(showtime,
                                       action=self.alter_prop,
                                       arg=('starttime', showtime)))

        manualrecord_menu = menu.Menu(_('Modify Time'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_stop_month(self, arg=None, menuw=None):
        logger.log( 9, 'mod_stop_month(self, arg=None, menuw=None)')
        items = []

        iter=0
        while iter < 12:
            month_name = self.months[(iter + self.stoptime[1] - 1) % 12];
            month_num  = self.months.index(month_name) + 1;
            items.append(menu.MenuItem(month_name, action=self.alter_prop, arg=('stopmonth', (month_name, month_num))))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_stop_day(self, arg=None, menuw=None):
        logger.log( 9, 'mod_stop_day(self, arg=None, menuw=None)')
        items = []

        numdays = calendar.monthrange(self.stoptime[0], self.stop_month)[1]
        daylimit = numdays + 1
        iter=1
        while iter < daylimit:
            newday = (iter + self.starttime[2] - 1)
            currday = newday % daylimit
            if newday >= daylimit:
                currday += 1
            items.append(menu.MenuItem(str(currday), action=self.alter_prop,
                         arg=('stopday', currday)))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def mod_stop_time(self, arg=None, menuw=None):
        logger.log( 9, 'mod_stop_time(self, arg=None, menuw=None)')
        items = []

        currminutes = self.starttime[3]*60 + self.starttime[4]
        minpadding = 5 - (currminutes % 5)
        if minpadding == 5:
            minpadding = 0
        for i in range(288):
            mod = (i * 5 + currminutes + minpadding) % 1440
            showtime = strftime(config.TV_TIME_FORMAT, gmtime(float(mod * 60)))
            items.append(menu.MenuItem(showtime,
                                       action=self.alter_prop,
                                       arg=('stoptime', showtime)))

        manualrecord_menu = menu.Menu(_('Modify Time'), items,
                                  item_types = 'tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()


    def alter_name(self, name):
        logger.log( 9, 'alter_name(self, name)')
        if name:
            self.disp_title = self.prog.title = name

        self.menuw.refresh()


    def alter_prop(self, arg=(None,None), menuw=None):
        logger.log( 9, 'alter_prop(self, arg=(None,None), menuw=None)')
        (prop, val) = arg

        if prop == 'channel':
            self.prog.channel_id = val[1]
            self.disp_channel = val[0]

        if prop == 'startday':
            self.start_day = val
            self.disp_starttime = '%s %s %s' % (self.disp_start_month, self.start_day, self.start_time)

        if prop == 'startmonth':
            self.start_month = val[1]
            self.disp_start_month = val[0]
            self.disp_starttime = '%s %s %s' % (self.disp_start_month, self.start_day, self.start_time)

        if prop == 'starttime':
            self.start_time = val
            self.disp_starttime = '%s %s %s' % (self.disp_start_month, self.start_day, self.start_time)

        if prop == 'stopday':
            self.stop_day = val
            self.disp_stoptime = '%s %s %s' % (self.disp_stop_month, self.stop_day, self.stop_time)

        if prop == 'stopmonth':
            self.stop_month = val[1]
            self.disp_stop_month = val[0]
            self.disp_stoptime = '%s %s %s' % (self.disp_stop_month, self.stop_day, self.stop_time)

        if prop == 'stoptime':
            self.stop_time = val
            self.disp_stoptime = '%s %s %s' % (self.disp_stop_month, self.stop_day, self.stop_time)

        if menuw:
            menuw.back_one_menu(arg='reload')


    def save_changes(self, arg=None, menuw=None):
        logger.log( 9, 'save_changes(self, arg=None, menuw=None)')
        result = self.check_prog()
        if result:
            (result, reason) = self.recordclient.scheduleRecordingNow(self.prog)

            if not result:
                AlertBox(text=_('Save Failed, recording was lost')+(':\n%s' % reason)).show()
            else:
                if menuw:
                    menuw.back_one_menu(arg='reload')


    def check_prog(self):
        logger.log( 9, 'check_prog(self)')
        isgood = True
        curtime_epoch = time.time()
        curtime = time.localtime(curtime_epoch)
        startyear = curtime[0]
        stopyear = curtime[0]
        currentmonth = curtime[1]

        # handle the year wraparound
        if int(self.stop_month) < currentmonth:
            stopyear = int(stopyear) + 1
        if int(self.start_month) < currentmonth:
            startyear = int(startyear) + 1
        # create utc second start time
        starttime_str = '%s %s %s %s:00' % (self.start_month, self.start_day, startyear, self.start_time)
        starttime = time.mktime(strptime(starttime_str, '%m %d %Y '+config.TV_TIME_FORMAT+':%S'))
        # create utc stop time
        stoptime_str = '%s %s %s %s:00' % (self.stop_month, self.stop_day, stopyear, self.stop_time)
        stoptime = time.mktime(strptime(stoptime_str, '%m %d %Y '+config.TV_TIME_FORMAT+':%S'))

        # so we don't record for more then maxdays (maxdays day * 24hr/day * 60 min/hr * 60 sec/min)
        if not abs(stoptime - starttime) < (self.MAXDAYS * 86400):
            if self.MAXDAYS > 1:
                isgood = False
                msg = _("Program would record for more than %d days!") % self.MAXDAYS
                AlertBox(text=_('Save Failed, recording was lost')+(':\n%s' % msg)).show()
            else:
                isgood = False
                msg = _("Program would record for more than 1 day!") % self.MAXDAYS
                AlertBox(text=_('Save Failed, recording was lost')+(':\n%s' % msg)).show()

        elif not starttime < stoptime:
            isgood = False
            msg = _("start time is not before stop time." )
            AlertBox(text=_('Save Failed, recording was lost')+(':\n%s' % msg)).show()
        elif stoptime < curtime_epoch + self.MINPICKUP:
            isgood = False
            msg = _("Sorry, the stop time does not give enough time for scheduler to pickup the change.  Please set it to record for a few minutes longer.")
            AlertBox(text=_('Save Failed, recording was lost')+(':\n%s' % msg)).show()
        else:
            self.prog.start = starttime
            self.prog.stop = stoptime

        return isgood
Beispiel #21
0
class ViewFavoritesItem(Item):
    def __init__(self, parent):
        logger.log( 9, 'ViewFavoritesItem.__init__(parent=%r)', parent)
        Item.__init__(self, parent, skin_type='tv')
        self.name = _('View Favorites')
        self.menuw = None
        self.recordclient = RecordClient()


    def actions(self):
        logger.log( 9, 'actions()')
        return [ ( self.view_favorites , _('View Favorites') ),
                 ( self.reschedule_favorites, _('Reschedule Favorites'))]


    def view_favorites(self, arg=None, menuw=None):
        logger.log( 9, 'view_favorites(arg=%r, menuw=%r)', arg, menuw)
        if not self.recordclient.pingNow():
            dialog.show_alert(self.recordclient.recordserverdown)
            return

        items = self.get_items()
        if not len(items):
            dialog.show_alert(_('No favorites.'))
            return

        favorite_menu = menu.Menu(_( 'View Favorites'), items, reload_func=self.reload, item_types='tv favorite menu')
        self.menuw = menuw
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def reschedule_favorites(self, arg=None, menuw=None):
        """
        Force rescheduling of favorites
        """
        logger.log( 9, 'resched_favs(arg=%r, menuw=%r)', arg, menuw)
        dialog.show_message(_('Rescheduling Favorites...'))
        self.recordclient.updateFavoritesScheduleCo().connect(self.reschedule_favorites_complete)
        if menuw:
            menuw.delete_submenu()

    def reschedule_favorites_complete(self, result):
        if result:
            dialog.show_message(_('Favorites rescheduled'))
        else:
            dialog.show_alert(_('Reschedule failed'))


    def reload(self):
        logger.log( 9, 'reload()')
        menuw = self.menuw

        menu = menuw.menustack[-1]

        new_choices = self.get_items()
        if not menu.selected in new_choices and len(new_choices):
            sel = menu.choices.index(menu.selected)
            if len(new_choices) <= sel:
                menu.selected = new_choices[-1]
            else:
                menu.selected = new_choices[sel]

        menu.choices = new_choices

        return menu


    def get_items(self):
        logger.log( 9, 'get_items()')
        items = []

        (status, favorites) = self.recordclient.getFavoritesNow()
        if status:
            f = lambda a, b: cmp(a.priority, b.priority)
            favs = favorites.values()
            favs.sort(f)
            for fav in favs:
                items.append(FavoriteItem(self, fav))

        return items
Beispiel #22
0
class ProgramItem(Item):
    """
    Item class for program items

    This is used in the tv guide
    and in the list of schedules recordings.
    """
    def __init__(self, parent, prog, context='menu'):
        Item.__init__(self, parent, skin_type='video')
        logger.log( 9, '__init__(parent=%r, prog=%r, context=%r)', parent, prog, context)
        # prog is a TvProgram object as we get it from the recordserver
        self.prog = prog
        self.context= context

        if hasattr(prog, 'name'): self.name = self.title = prog.name
        if hasattr(prog, 'title'): self.title = self.name = Unicode(prog.title)
        if hasattr(prog, 'sub_title'): self.sub_title = prog.sub_title
        if hasattr(prog, 'desc'): self.description = prog.desc
        if hasattr(prog, 'categories'):self.categories = prog.categories
        if hasattr(prog, 'ratings'): self.ratings = prog.ratings
        if hasattr(prog, 'advisories'): self.advisories = prog.advisories

        self.channel = tv_util.get_chan_displayname(prog.channel_id)
        if hasattr(prog, 'scheduled'):
            self.scheduled = prog.scheduled
        else:
            self.scheduled = False

        self.favorite = False
        self.allowDuplicates = prog.allowDuplicates
        self.onlyNew = prog.onlyNew
        self.overlap = prog.overlap

        self.start = time.strftime(config.TV_DATETIME_FORMAT, time.localtime(prog.start))
        self.stop = time.strftime(config.TV_DATETIME_FORMAT, time.localtime(prog.stop))
        self.recordclient = RecordClient()


    def actions(self):
        """ List of actions """
        logger.log( 9, 'actions()')
        #list of entries for the menu
        items = []

        #'Play', if this programm is currently running or starts soon
        if self.context == 'guide':
            items.append((self.play, _('Play')))
            #now = time.time()
            #if self.prog.start <= now+(7*60) and self.prog.stop > now:
            #    items.append((self.play, _('Play')))

        # 'Show full description'
        items.append((self.show_description, _('Full Description')))

        if self.recordclient.pingNow():

            # 'Schedule for recording' OR 'Remove from schedule'
            (status, reason) = self.recordclient.isProgScheduledNow(self.prog)
            self.scheduled = status
            if self.scheduled:
                items.append((self.remove_program, _('Remove from schedule')))
            else:
                items.append((self.schedule_program, _('Schedule for recording')))

            # 'Add to favorites' OR 'Remove from favorites'
            (status, reason) = self.recordclient.isProgAFavoriteNow(self.prog)
            self.favorite = status
            if self.favorite:
                items.append((self.edit_favorite, _('Edit favorite')))
            else:
                items.append((self.add_favorite, _('Add to favorites')))

        plugins_list = plugin.get('tv_program')
        for p in plugins_list:
            items += p.items(self)

        return items


    ### Actions:

    def play(self, arg=None, menuw=None):
        """ Start watching TV """
        logger.log( 9, 'play(arg=%r, menuw=%r)', arg, menuw)
        # watching TV should only be possible from the guide
        if not self.context == 'guide':
            rc.post_event(MENU_SELECT)
            return
        now = time.time()
        if menuw: menuw.delete_submenu()
        # Check if the selected program is >7 min in the future
        if self.prog.start > now + (7*60):
            if menuw: menuw.show()
            # this program is in the future
            if self.scheduled:
                msgtext= _('Do you want to remove the Program from the record schedule?')
                confirmbtn = _('Remove')
            else:
                msgtext = _('This Program is in the future. Do you want to record it?')
                confirmbtn = _('Record')
            dialog.show_confirmation(msgtext, lambda: self.toggle_rec(menuw=menuw), proceed_text=confirmbtn)
            return
        else:
            # check if the device is free
            fc = FreevoChannels()
            # for that we need the name of the lock file
            suffix = fc.getVideoGroup(self.prog.channel_id, True, CHANNEL_ID).vdev
            suffix = suffix.split('/')[-1]
            tvlockfile = config.FREEVO_CACHEDIR + '/record.'+suffix
            if os.path.exists(tvlockfile):
                if menuw: menuw.show()
                # XXX: In the future add the options to watch what we are
                #      recording or cancel it and watch TV.
                msgtext = _('Sorry, you cannot watch TV while recording. ')
                msgtext += _('If this is not true then remove ')
                msgtext += tvlockfile + '.'
                dialog.show_alert(msgtext)
            else:
                # everything is ok, we can start watching!
                self.parent.hide()
                self.parent.player('tv', self.prog.channel_id)


    def show_description(self, arg=None, menuw=None):
        """ View a full scrollable description of the program.  """
        logger.log( 9, 'show_description(arg=%r, menuw=%r)', arg, menuw)
        ShowProgramDetails(menuw, self)


    def toggle_rec(self, arg=None, menuw=None):
        """ Schedule or unschedule this program, depending on its current status """
        logger.log( 9, 'toggle_rec(arg=%r, menuw=%r)', arg, menuw)
        if self.scheduled:
            # remove this program from schedule it it is already scheduled
            self.remove_program(menuw=menuw)
        else:
            # otherwise add it to schedule without more questions
            self.schedule_program(menuw=menuw)


    def schedule_program(self, arg=None, menuw=None):
        """ Add a program to schedule """
        logger.log( 9, 'schedule_program(arg=%r, menuw=%r)', arg, menuw)
        # schedule the program
        (status, reason) = self.recordclient.scheduleRecordingNow(self.prog)
        if status == 'ok':
            self.scheduled = True
            menuw.delete_submenu(refresh=False)
            if hasattr(self.parent, 'update'):
                self.parent.update(force=True)
            else:
                menuw.refresh(reload=True)
            msgtext= _('"%s" has been scheduled for recording') % self.name
        elif status == 'conflict':
            msgtext=_('Conflict detected!')
            self.resolve_conflict(menuw, reason)
            return
        else:
            # something went wrong
            msgtext = _('Scheduling failed: ')+ _(reason)

        dialog.show_message(msgtext)


    def remove_program(self, arg=None, menuw=None):
        """ Remove a program from schedule """
        logger.log( 9, 'remove_program(arg=%r, menuw=%r)', arg, menuw)
        # remove the program
        (status, reason) = self.recordclient.removeScheduledRecordingNow(self.prog)
        if status:
            self.scheduled = False
            menuw.delete_submenu(refresh=False)
            if hasattr(self.parent, 'update'):
                self.parent.update(force=True)
            else:
                menuw.refresh(reload=True)
            msgtext = _('"%s" has been removed from schedule') % self.name
        else:
            # something went wrong
            msgtext = _('Remove failed')+(':\n%s' % reason)
        dialog.show_message(msgtext)


    def add_favorite(self, arg=None, menuw=None):
        """ Add a program to favorites """
        logger.log( 9, 'add_favorite(arg=%r, menuw=%r)', arg, menuw)
        if menuw:
            menuw.delete_submenu(refresh=False)
        # create a favorite
        fav = Favorite(self.title, self.prog, True, True, True, -1, True, False)
        logger.log( 9, 'self.title=%r, self.prog=%r, fav.__dict__=%r)', self.title, self.prog, fav.__dict__)
        # and a favorite item which represents the submen
        fav_item = FavoriteItem(self, fav, fav_action='add')
        # and open that submenu
        fav_item.display_submenu(menuw=menuw)


    def edit_favorite(self, arg=None, menuw=None):
        """
        Edit the settings of a favorite
        """
        logger.log( 9, 'edit_favorite(arg=%r, menuw=%r)', arg, menuw)
        if menuw:
            menuw.delete_submenu(refresh=False)

        # get the favorite from the record client
        (got_fav, fav) = self.recordclient.getFavoriteObjectNow(self.prog)
        if got_fav:
            # create a favorite item for the submenu
            fav_item = FavoriteItem(self, fav, fav_action='edit')
            # and open the submenu
            fav_item.display_submenu(menuw=menuw)
        else:
            dialog.show_alert(_('Cannot edit favorite %s') % self.name)


    def display_submenu(self, arg=None, menuw=None):
        """
        Open the submenu for this item
        """
        logger.log( 9, 'display_submenu(arg=%r, menuw=%r)', arg, menuw)
        if not menuw:
            return
        # this tries to imitated freevo's internal way of creating submenus
        menuw.make_submenu(_('Program Menu'), self.actions(), self)
        menuw.show()

    def resolve_conflict(self, menuw, conflictingProgs):
        prog_text = self.prog.getattr('time') + u' ' + self.prog.title
        other_prog_text = u''
        menu_items = []
        for progs in conflictingProgs:
            remove_text = ''
            for cprog in progs:
                if other_prog_text:
                    other_prog_text += u'\n'
                other_prog_text += cprog.getattr('time') + u' ' + cprog.title
                if not remove_text:
                    remove_text = cprog.title
                else:
                    remove_text += u', ' + cprog.title
            other_prog_text += u'\n\n'
            menu_items.append(menu.MenuItem(_('Remove ') + remove_text, self.remove_and_schedule, progs))
        self.conflict_info = _('How do you want to resolve the conflict?\n%s\nconflicts with\n%s') % (prog_text, other_prog_text)
        menu_items.append(menu.MenuItem(_('Cancel scheduling ') + self.prog.title, menuw.back_one_menu))

        conflict_menu = menu.Menu(_('Resovle Conflict'), menu_items, item_types='tv conflict menu')
        conflict_menu.infoitem = self
        menuw.delete_submenu(refresh = False)
        menuw.pushmenu(conflict_menu)
        menuw.refresh()


    def remove_and_schedule(self, arg=None, menuw=None):
        for prog in arg:
            self.recordclient.removeScheduledRecordingNow(prog)
        menuw.back_one_menu()
        self.schedule_program(menuw=menuw)
Beispiel #23
0
 def __init__(self, parent):
     Item.__init__(self, parent, skin_type='tv')
     self.name = _('Scheduled Recordings')
     self.menuw = None
     self.recordclient = RecordClient()
Beispiel #24
0
class ScheduledRecordingsItem(Item):
    def __init__(self, parent):
        Item.__init__(self, parent, skin_type='tv')
        self.name = _('Scheduled Recordings')
        self.menuw = None
        self.recordclient = RecordClient()


    def actions(self):
        return [ ( self.display_schedule , _('Display Scheduled Recordings') ) ]


    def display_schedule(self, arg=None, menuw=None):
        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return

        items = self.get_items()
        if not len(items):
            AlertBox(_('Nothing scheduled.')).show()
            return

        schedule_menu = menu.Menu(_('Scheduled Recordings'), items,
            reload_func=self.reload, item_types='tv program menu')
        self.menuw = menuw
        rc.app(None)
        menuw.pushmenu(schedule_menu)
        menuw.refresh()


    def reload(self):
        menuw = self.menuw

        menu = menuw.menustack[-1]

        new_choices = self.get_items()
        if not menu.selected in new_choices and len(new_choices):
            sel = menu.choices.index(menu.selected)
            if len(new_choices) <= sel:
                menu.selected = new_choices[-1]
            else:
                menu.selected = new_choices[sel]

        menu.choices = new_choices

        return menu


    def get_items(self):
        items = []

        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return []

        (status, schedule) = self.recordclient.getScheduledRecordingsNow()
        if status:
            progs = schedule.getProgramList()

            f = lambda a, b: cmp(a.start, b.start)
            progs = progs.values()
            progs.sort(f)
            for prog in progs:
                items.append(ProgramItem(self, prog, context='schedule'))
        else:
            AlertBox(_('Get scheduled recordings failed')+(':\n%s' % schedule)).show()
            return []

        return items
Beispiel #25
0
class ProgramItem(Item):
    """
    Item class for program items

    This is used in the tv guide
    and in the list of schedules recordings.
    """
    def __init__(self, parent, prog, context='menu'):
        Item.__init__(self, parent, skin_type='video')
        logger.log(9, '__init__(parent=%r, prog=%r, context=%r)', parent, prog,
                   context)
        # prog is a TvProgram object as we get it from the recordserver
        self.prog = prog
        self.context = context

        if hasattr(prog, 'name'): self.name = self.title = prog.name
        if hasattr(prog, 'title'): self.title = self.name = Unicode(prog.title)
        if hasattr(prog, 'sub_title'): self.sub_title = prog.sub_title
        if hasattr(prog, 'desc'): self.description = prog.desc
        if hasattr(prog, 'categories'): self.categories = prog.categories
        if hasattr(prog, 'ratings'): self.ratings = prog.ratings
        if hasattr(prog, 'advisories'): self.advisories = prog.advisories

        self.channel = tv_util.get_chan_displayname(prog.channel_id)
        if hasattr(prog, 'scheduled'):
            self.scheduled = prog.scheduled
        else:
            self.scheduled = False

        self.favorite = False
        if hasattr(prog, 'allowDuplicates'):
            self.allowDuplicates = prog.allowDuplicates
        else:
            self.allowDuplicates = 1

        if hasattr(prog, 'onlyNew'):
            self.onlyNew = prog.onlyNew
        else:
            self.onlyNew = 0

        self.overlap = prog.overlap

        self.start = time.strftime(config.TV_DATETIME_FORMAT,
                                   time.localtime(prog.start))
        self.stop = time.strftime(config.TV_DATETIME_FORMAT,
                                  time.localtime(prog.stop))
        self.recordclient = RecordClient()

    def actions(self):
        """ List of actions """
        logger.log(9, 'actions()')
        #list of entries for the menu
        items = []

        #'Play', if this programm is currently running or starts soon
        if self.context == 'guide':
            items.append((self.play, _('Play')))
            #now = time.time()
            #if self.prog.start <= now+(7*60) and self.prog.stop > now:
            #    items.append((self.play, _('Play')))

        # 'Show full description'
        items.append((self.show_description, _('Full Description')))

        if self.recordclient.pingNow():

            # 'Schedule for recording' OR 'Remove from schedule'
            (status, reason) = self.recordclient.isProgScheduledNow(self.prog)
            self.scheduled = status
            if self.scheduled:
                items.append((self.remove_program, _('Remove from schedule')))
            else:
                items.append(
                    (self.schedule_program, _('Schedule for recording')))

            # 'Add to favorites' OR 'Remove from favorites'
            (status, reason) = self.recordclient.isProgAFavoriteNow(self.prog)
            self.favorite = status
            if self.favorite:
                items.append((self.edit_favorite, _('Edit favorite')))
            else:
                items.append((self.add_favorite, _('Add to favorites')))

        plugins_list = plugin.get('tv_program')
        for p in plugins_list:
            items += p.items(self)

        return items

    ### Actions:

    def play(self, arg=None, menuw=None):
        """ Start watching TV """
        logger.log(9, 'play(arg=%r, menuw=%r)', arg, menuw)
        # watching TV should only be possible from the guide
        if not self.context == 'guide':
            rc.post_event(MENU_SELECT)
            return
        now = time.time()
        if menuw: menuw.delete_submenu()
        # Check if the selected program is >7 min in the future
        if self.prog.start > now + (7 * 60):
            if menuw: menuw.show()
            # this program is in the future
            if self.scheduled:
                msgtext = _(
                    'Do you want to remove the Program from the record schedule?'
                )
                confirmbtn = _('Remove')
            else:
                msgtext = _(
                    'This Program is in the future. Do you want to record it?')
                confirmbtn = _('Record')
            dialog.show_confirmation(msgtext,
                                     lambda: self.toggle_rec(menuw=menuw),
                                     proceed_text=confirmbtn)
            return
        else:
            # check if the device is free
            fc = FreevoChannels()
            # for that we need the name of the lock file
            suffix = fc.getVideoGroup(self.prog.channel_id, True,
                                      CHANNEL_ID).vdev
            suffix = suffix.split('/')[-1]
            tvlockfile = config.FREEVO_CACHEDIR + '/record.' + suffix
            if os.path.exists(tvlockfile):
                if menuw: menuw.show()
                # XXX: In the future add the options to watch what we are
                #      recording or cancel it and watch TV.
                msgtext = _('Sorry, you cannot watch TV while recording. ')
                msgtext += _('If this is not true then remove ')
                msgtext += tvlockfile + '.'
                dialog.show_alert(msgtext)
            else:
                # everything is ok, we can start watching!
                self.parent.hide()
                self.parent.player('tv', self.prog.channel_id)

    def show_description(self, arg=None, menuw=None):
        """ View a full scrollable description of the program.  """
        logger.log(9, 'show_description(arg=%r, menuw=%r)', arg, menuw)
        ShowProgramDetails(menuw, self)

    def toggle_rec(self, arg=None, menuw=None):
        """ Schedule or unschedule this program, depending on its current status """
        logger.log(9, 'toggle_rec(arg=%r, menuw=%r)', arg, menuw)
        if self.scheduled:
            # remove this program from schedule it it is already scheduled
            self.remove_program(menuw=menuw)
        else:
            # otherwise add it to schedule without more questions
            self.schedule_program(menuw=menuw)

    def schedule_program(self, arg=None, menuw=None):
        """ Add a program to schedule """
        logger.log(9, 'schedule_program(arg=%r, menuw=%r)', arg, menuw)
        # schedule the program
        (status, reason) = self.recordclient.scheduleRecordingNow(self.prog)
        if status == 'ok':
            self.scheduled = True
            menuw.delete_submenu(refresh=False)
            if hasattr(self.parent, 'update'):
                self.parent.update(force=True)
            else:
                menuw.refresh(reload=True)
            msgtext = _('"%s" has been scheduled for recording') % self.name
        elif status == 'conflict':
            msgtext = _('Conflict detected!')
            self.resolve_conflict(menuw, reason)
            return
        else:
            # something went wrong
            msgtext = _('Scheduling failed: ') + _(reason)

        dialog.show_message(msgtext)

    def remove_program(self, arg=None, menuw=None):
        """ Remove a program from schedule """
        logger.log(9, 'remove_program(arg=%r, menuw=%r)', arg, menuw)
        # remove the program
        (status,
         reason) = self.recordclient.removeScheduledRecordingNow(self.prog)
        if status:
            self.scheduled = False
            menuw.delete_submenu(refresh=False)
            if hasattr(self.parent, 'update'):
                self.parent.update(force=True)
            else:
                menuw.refresh(reload=True)
            msgtext = _('"%s" has been removed from schedule') % self.name
        else:
            # something went wrong
            msgtext = _('Remove failed') + (':\n%s' % reason)
        dialog.show_message(msgtext)

    def add_favorite(self, arg=None, menuw=None):
        """ Add a program to favorites """
        logger.log(9, 'add_favorite(arg=%r, menuw=%r)', arg, menuw)
        if menuw:
            menuw.delete_submenu(refresh=False)
        # create a favorite
        fav = Favorite(self.title, self.prog, True, True, True, -1, True,
                       False)
        logger.log(9, 'self.title=%r, self.prog=%r, fav.__dict__=%r)',
                   self.title, self.prog, fav.__dict__)
        # and a favorite item which represents the submen
        fav_item = FavoriteItem(self, fav, fav_action='add')
        # and open that submenu
        fav_item.display_submenu(menuw=menuw)

    def edit_favorite(self, arg=None, menuw=None):
        """
        Edit the settings of a favorite
        """
        logger.log(9, 'edit_favorite(arg=%r, menuw=%r)', arg, menuw)
        if menuw:
            menuw.delete_submenu(refresh=False)

        # get the favorite from the record client
        (got_fav, fav) = self.recordclient.getFavoriteObjectNow(self.prog)
        if got_fav:
            # create a favorite item for the submenu
            fav_item = FavoriteItem(self, fav, fav_action='edit')
            # and open the submenu
            fav_item.display_submenu(menuw=menuw)
        else:
            dialog.show_alert(_('Cannot edit favorite %s') % self.name)

    def display_submenu(self, arg=None, menuw=None):
        """
        Open the submenu for this item
        """
        logger.log(9, 'display_submenu(arg=%r, menuw=%r)', arg, menuw)
        if not menuw:
            return
        # this tries to imitated freevo's internal way of creating submenus
        menuw.make_submenu(_('Program Menu'), self.actions(), self)
        menuw.show()

    def resolve_conflict(self, menuw, conflictingProgs):
        prog_text = self.prog.getattr('time') + u' ' + self.prog.title
        other_prog_text = u''
        menu_items = []
        for progs in conflictingProgs:
            remove_text = ''
            for cprog in progs:
                if other_prog_text:
                    other_prog_text += u'\n'
                other_prog_text += cprog.getattr('time') + u' ' + cprog.title
                if not remove_text:
                    remove_text = cprog.title
                else:
                    remove_text += u', ' + cprog.title
            other_prog_text += u'\n\n'
            menu_items.append(
                menu.MenuItem(
                    _('Remove ') + remove_text, self.remove_and_schedule,
                    progs))
        self.conflict_info = _(
            'How do you want to resolve the conflict?\n%s\nconflicts with\n%s'
        ) % (prog_text, other_prog_text)
        menu_items.append(
            menu.MenuItem(
                _('Cancel scheduling ') + self.prog.title,
                menuw.back_one_menu))

        conflict_menu = menu.Menu(_('Resovle Conflict'),
                                  menu_items,
                                  item_types='tv conflict menu')
        conflict_menu.infoitem = self
        menuw.delete_submenu(refresh=False)
        menuw.pushmenu(conflict_menu)
        menuw.refresh()

    def remove_and_schedule(self, arg=None, menuw=None):
        for prog in arg:
            self.recordclient.removeScheduledRecordingNow(prog)
        menuw.back_one_menu()
        self.schedule_program(menuw=menuw)
Beispiel #26
0
class FavoriteItem(Item):
    """
    Item class for favorite items
    """
    def __init__(self, parent, fav, fav_action='edit'):
        """ """
        Item.__init__(self, parent, skin_type='video')
        _debug_('FavoriteItem.__init__(parent=%r, fav=%r, fav_action=%r)' % (parent, fav, fav_action), 2)
        self.recordclient = RecordClient()
        self.fav   = fav
        self.name  = self.origname = fav.name
        self.title = fav.title
        self.fav_action = fav_action
        # twisted needs FALSE and TRUE, it does not know False and True
        if hasattr(fav,'allowDuplicates') and not fav.allowDuplicates:
            self.allowDuplicates = fav.allowDuplicates = FALSE
        else:
            self.allowDuplicates = fav.allowDuplicates = TRUE
        # twisted needs FALSE and TRUE, it does not know False and True
        if hasattr(fav,'onlyNew') and fav.onlyNew:
            self.onlyNew = fav.onlyNew = TRUE
        else:
            self.onlyNew = fav.onlyNew = FALSE

        self.week_days = (_('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun'))

        if fav.channel == 'ANY':
            self.channel = _('ANY CHANNEL')
        else:
            self.channel = fav.channel
        if fav.dow == 'ANY':
            self.dow = _('ANY DAY')
        else:
            self.dow = self.week_days[int(fav.dow)]
        if fav.mod == 'ANY':
            self.mod = _('ANY TIME')
        else:
            try:
                self.mod = time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(int(fav.mod) * 60)))
            except:
                print 'Cannot add "%s" to favorites' % fav.name

        # needed by the inputbox handler
        self.menuw = None

        self.red_action = (self.display_submenu,_('Edit favorite'))
        self.green_action = (self.rem_favorite, _('Remove favorite'))


    def actions(self):
        _debug_('actions()', 2)
        return [( self.display_submenu , _('Edit favorite'))]


    def display_submenu(self, arg=None, menuw=None):
        """ Display menu for a favorite

        With this menu the user can made a program a favorite.
        All attributes of a favorite can be edited here and in the end
        the user must select 'save changes' to finally create the favorite.
        """
        _debug_('display_submenu(arg=%r, menuw=%r)' % (arg, menuw), 2)
        ### create menu items for editing the favorites attributes
        items = []

        items.append(menu.MenuItem(_('Modify name'), action=self.mod_name))
        items.append(menu.MenuItem(_('Modify channel'), action=self.mod_channel))
        items.append(menu.MenuItem(_('Modify day of week'), action=self.mod_day))
        items.append(menu.MenuItem(_('Modify time of day'), action=self.mod_time))

        if config.TV_RECORD_DUPLICATE_DETECTION:
            if self.allowDuplicates:
                items.append(menu.MenuItem(_('Prevent Recording of Duplicates'), \
                    action=self.alter_prop, arg=('dup', 'False')))
            else:
                items.append(menu.MenuItem(_('Allow Recording of Duplicates'),
                    action=self.alter_prop, arg=('dup', 'True')))


        if config.TV_RECORD_ONLY_NEW_DETECTION:
            if self.onlyNew:
                items.append(menu.MenuItem(_('Record All Episodes'), action=self.alter_prop, arg=('new', 'False')))
            else:
                items.append(menu.MenuItem(_('Record Only New Episodes'), action=self.alter_prop, arg=('new', 'True')))

        # XXX: priorities aren't quite supported yet
        if 0:
            (status, favorites) = self.recordclient.getFavoritesNow()
            if status and len(favorites) > 1:
                items.append(menu.MenuItem(_('Modify priority'), action=self.mod_priority))


        ### save favorite
        items.append(menu.MenuItem(_('Save changes'), action=self.save_changes))

        ### remove this program from favorites
        if not self.fav_action == 'add':
            items.append(menu.MenuItem(_('Remove favorite'), action=self.rem_favorite))

        ### put the whole menu together
        favorite_menu = menu.Menu(_('Favorite Menu'), items, item_types='tv favorite menu')
        favorite_menu.infoitem = self
        favorite_menu.is_submenu = True
        menuw.pushmenu(favorite_menu)
        menuw.refresh()



    ### Actions:

    def mod_name(self, arg=None, menuw=None):
        """ Modify name

        This opens a input box to ask the user for a new name for this favorite.
        The default name of a favorite is the name of the program.
        """
        _debug_('mod_name(arg=%r, menuw=%r)' % (arg, menuw), 2)
        self.menuw = menuw
        InputBox(text=_('Alter Name'), handler=self.alter_name, \
            width=osd.get_singleton().width - config.OSD_OVERSCAN_LEFT - 20, input_text=self.name).show()


    def alter_name(self, name):
        """ set the new name"""
        _debug_('alter_name(name=%r)' % (name,), 2)
        if name:
            self.name = self.fav.name = name.strip()

        self.menuw.refresh()


    def mod_channel(self, arg=None, menuw=None):
        """Modify channel"""
        _debug_('mod_channel(arg=%r, menuw=%r)' % (arg, menuw), 2)
        items = []

        items.append(menu.MenuItem('ANY CHANNEL', action=self.alter_prop, arg=('channel', 'ANY')))

        for chanline in config.TV_CHANNELS:
            items.append(menu.MenuItem(chanline[1], action=self.alter_prop, arg=('channel', chanline[1])))

        favorite_menu = menu.Menu(_('Modify Channel'), items, item_types='tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def mod_day(self, arg=None, menuw=None):
        """ Modify day

        Opens a submenu where the day of the week of a favorite can be configured.
        """
        _debug_('mod_day(arg=%r, menuw=%r)' % (arg, menuw), 2)
        items = []

        items.append(menu.MenuItem(_('ANY DAY'), action=self.alter_prop, arg=('dow', 'ANY')))

        for i in range(len(self.week_days)):
            items.append(menu.MenuItem(self.week_days[i], action=self.alter_prop, arg=('dow', i)))

        favorite_menu = menu.Menu(_('Modify Day'), items, item_types = 'tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def mod_time(self, arg=None, menuw=None):
        """ Modify time

        Opens a submenu where the time of a favorite can be configured.
        """
        _debug_('mod_time(arg=%r, menuw=%r)' % (arg, menuw), 2)
        items = []

        items.append(menu.MenuItem(_('ANY TIME'), action=self.alter_prop, arg=('mod', 'ANY')))

        for i in range(48):
            mod = i * 30
            items.append(menu.MenuItem(time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(mod * 60))), \
                action=self.alter_prop, arg=('mod', mod)))

        favorite_menu = menu.Menu(_('Modify Time'), items, item_types = 'tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def alter_prop(self, arg=(None,None), menuw=None):
        """ Alter a favorites property

        This function is where the properties of a favorite really are changed.
        """
        _debug_('alter_prop(arg=%r, menuw=%r)' % (arg, menuw), 2)
        (prop, val) = arg

        if prop == 'channel':
            if val == 'ANY':
                self.channel = 'ANY CHANNEL'
                self.fav.channel = 'ANY'
            else:
                self.channel = val
                self.fav.channel = val
            if menuw:
                menuw.back_one_menu(arg='reload')

        elif prop == 'dow':
            if val == 'ANY':
                self.dow = 'ANY DAY'
                self.fav.dow = 'ANY'
            else:
                self.dow = self.week_days[val]
                self.fav.dow = val
            if menuw:
                menuw.back_one_menu(arg='reload')

        elif prop == 'mod':
            if val == 'ANY':
                self.mod = 'ANY TIME'
                self.fav.mod = 'ANY'
            else:
                # self.mod = tv_util.minToTOD(val)
                self.mod = time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(val * 60)))
                self.fav.mod = val
            if menuw:
                menuw.back_one_menu(arg='reload')

        elif prop == 'dup':
            if val == 'True':
                # twisted needs FALSE and TRUE, it does not know False and True
                self.allowDuplicates=TRUE
                self.fav.allowDuplicates=TRUE
                newname = _('Prevent Recording of Duplicates')
                val = 'False'
            else:
                # twisted needs FALSE and TRUE, it does not know False and True
                self.allowDuplicates=FALSE
                self.fav.allowDuplicates=FALSE
                newname = _('Allow Recordings of Duplicates')
                val = 'True'
            if menuw:
                menustack = menuw.menustack[-1]
                pos = menustack.choices.index(menustack.selected)
                new = menu.MenuItem(newname, action=self.alter_prop, arg=('dup', val))
                menustack.choices[pos] = new
                menustack.selected = menustack.choices[pos]
                menuw.init_page()
                menuw.refresh()

        elif prop == 'new':
            # twisted needs FALSE and TRUE, it does not know False and True
            if val == 'True':
                self.onlyNew=TRUE
                self.fav.onlyNew=TRUE
                newname = _('Record All Episodes')
                val = 'False'
            else:
                self.onlyNew=FALSE
                self.fav.onlyNew=FALSE
                newname = _('Record Only New Episodes')
                val = 'True'
            if menuw:
                menustack = menuw.menustack[-1]
                pos = menustack.choices.index(menustack.selected)
                new = menu.MenuItem(newname, action=self.alter_prop, arg=('new', val))
                menustack.choices[pos] = new
                menustack.selected = menustack.choices[pos]
                menuw.init_page()
                menuw.refresh()


    def save_changes(self, arg=None, menuw=None):
        """
        Save favorite
        """
        _debug_('save_changes(arg=%r, menuw=%r)' % (arg, menuw), 2)
        # this can take some time, as it means although to update the schedule
        msgtext = _('Saving the changes to this favorite.')+'\n'+_('This may take some time.')
        pop = PopupBox(text=msgtext)
        pop.show()

        if self.fav_action == 'edit':
            # first we remove the old favorite
            (result, msg) = self.recordclient.removeFavoriteNow(self.origname)
        elif self.fav_action =='add':
            result = True

        if result:
            # create a new edited favorite
            (result, msg) = self.recordclient.addEditedFavoriteNow(self.fav.name,
                self.fav.title, self.fav.channel, self.fav.dow, self.fav.mod,
                self.fav.priority, self.fav.allowDuplicates, self.fav.onlyNew)
            if result:
                if menuw:
                    menuw.delete_submenu()
                    if self.fav_action == 'add':
                        menuw.refresh(reload=1)
                self.fav_action = 'edit'
                pop.destroy()
            else:
                pop.destroy()
                # it is important to show the user this error,
                # because that means the favorite is removed,
                # and must be created again
                msgtext=_('Save failed, favorite was lost')+(':\n%s' % msg)
                AlertBox(text=msgtext).show()


    def rem_favorite(self, arg=None, menuw=None):
        """
        Remove favorite
        """
        _debug_('rem_favorite(arg=%r, menuw=%r)' % (arg, menuw), 2)
        name = self.origname
        (result, msg) = self.recordclient.removeFavoriteNow(name)
        if result:
            # if this is successfull
            if menuw:
                menuw.delete_submenu()
                menuw.refresh(reload=1)
            # and show a short message of success
            msgtext = text=_('"%s" has been removed from favorites') % name
            AlertBox(text=msgtext).show()
        else:
            # if all fails then we should show an error
            msgtext = _('Remove failed')+(':\n%s' % msg)
            AlertBox(text=msgtext).show()
 def __init__(self, parent):
     Item.__init__(self, parent, skin_type='tv')
     self.name = _('Scheduled Recordings')
     self.menuw = None
     self.recordclient = RecordClient()
Beispiel #28
0
        usage()

    if len(sys.argv) > 1 and sys.argv[1] == '--query':
        print
        print 'searching for station information'

        chanlist = config.detect_channels()

        print
        print 'Possible list of tv channels. If you want to change the station'
        print 'id, copy the next statement into your local_conf.py and edit it.'
        print 'You can also remove lines or resort them'
        print
        print 'TV_CHANNELS = ['
        for c in chanlist[:-1]:
            print '    ( \'%s\', \'%s\', \'%s\' ), ' % c
        print '    ( \'%s\', \'%s\', \'%s\' ) ] ' % chanlist[-1]
        sys.exit(0)

    grab()

    import kaa
    from tv.record_client import RecordClient

    print 'Scheduling favorites for recording:  '
    if not RecordClient().updateFavoritesSchedule(handler):
        print RecordClient().recordserverdown
        raise SystemExit

    kaa.main.run()
Beispiel #29
0
    def __init__(self, parent=None, subject=None, left=None, top=None, width=500, height=350, context=None):
        """
        Initialise an instance of EditFavorite

        @ivar parent:  parent of the class
        @ivar subject: the title of the program
        @ivar left:    x coordinate, Integer
        @ivar top:     y coordinate, Integer
        @ivar width:   width in pixels, Integer
        @ivar height:  height in pixels, Integer
        @ivar context: context in which the object is instantiated
        """
        logger.debug(
            "EditFavorite.__init__(parent=%r, subject=%r, left=%r, top=%r, width=%r, height=%r, context=%r)",
            parent,
            subject,
            left,
            top,
            width,
            height,
            context,
        )

        self.oldname = None
        if context:
            self.context = context
        else:
            context = "guide"

        self.recordclient = RecordClient()
        if isinstance(subject, TvProgram):
            (result, favs) = self.recordclient.getFavorites()
            if result:
                num_favorites = len(favs)
                self.priority = num_favorites + 1
            else:
                self.priority = 1
            self.fav = Favorite(subject.title, subject, TRUE, TRUE, TRUE, self.priority, TRUE, FALSE)

        else:
            self.fav = subject
            self.oldname = self.fav.name

        PopupBox.__init__(self, text=_("Edit Favorite"), x=left, y=top, width=width, height=height)

        self.v_spacing = 15
        self.h_margin = 20
        self.v_margin = 20

        self.internal_h_align = Align.LEFT

        if not self.left:
            self.left = self.osd.width / 2 - self.width / 2
        if not self.top:
            self.top = self.osd.height / 2 - self.height / 2

        name = Label(_("Name") + ":", self, Align.LEFT)
        self.name_input = LetterBoxGroup(text=self.fav.name)
        self.name_input.h_align = Align.NONE
        self.add_child(self.name_input)

        title = Label(_("Title") + ": %s" % self.fav.title, self, Align.LEFT)

        chan = Label(_("Channel") + ":", self, Align.LEFT)

        self.chan_box = OptionBox("ANY")
        self.chan_box.h_align = Align.NONE
        self.chan_box.add_item(text=_("ANY"), value="ANY")

        i = 1
        chan_index = 0
        for ch in tv.epg.channels:
            # if ch.id == self.fav.channel_id:
            if ch.displayname == self.fav.channel:
                chan_index = i
            i += 1
            self.chan_box.add_item(text=ch.displayname, value=ch.displayname)

        self.chan_box.toggle_selected_index(chan_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.chan_box.change_item(None)
        self.add_child(self.chan_box)

        dow = Label(_("Day of Week") + ":", self, Align.LEFT)
        self.dow_box = OptionBox("ANY DAY")
        self.dow_box.h_align = Align.NONE

        self.dow_box.add_item(text=_("ANY DAY"), value="ANY")

        i = 1
        dow_index = 0
        for dow in (_("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun")):
            val = "%d" % (i - 1)
            self.dow_box.add_item(text=_(dow), value=val)
            if val == self.fav.dow:
                dow_index = i
            i += 1
        self.dow_box.toggle_selected_index(dow_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.dow_box.change_item(None)
        self.add_child(self.dow_box)

        tod = Label(_("Time of Day") + ":", self, Align.LEFT)
        self.tod_box = OptionBox("ANY")
        self.tod_box.h_align = Align.NONE
        self.tod_box.add_item(text=_("ANY TIME"), value="ANY")

        i = 0
        tod_index = 0

        for h in range(0, 24):
            for m in (00, 30):
                val = i * 30
                # Little hack: we calculate the hours from Jan 1st, 1970 GMT,
                # and then use strftime to get the string representation
                text = strftime(config.TV_TIME_FORMAT, gmtime(h * 3600 + 60 * m))
                self.tod_box.add_item(text=text, value=val)
                if val == self.fav.mod:
                    tod_index = i + 1
                i += 1
        self.tod_box.toggle_selected_index(tod_index)
        # This is a hack for setting the OptionBox's label to the current
        # value. It should be done by OptionBox when drawing, but it doesn't
        # work :(
        self.tod_box.change_item(None)
        self.add_child(self.tod_box)

        self.save = Button(_("Save"))
        self.add_child(self.save)
        if self.oldname:
            self.remove = Button(_("Remove"))
            self.add_child(self.remove)
        else:
            self.remove = None
        self.cancel = Button(_("CANCEL"))
        self.add_child(self.cancel)
class ScheduledRecordingsItem(Item):
    def __init__(self, parent):
        Item.__init__(self, parent, skin_type='tv')
        self.name = _('Scheduled Recordings')
        self.menuw = None
        self.recordclient = RecordClient()


    def actions(self):
        return [ ( self.display_schedule , _('Display Scheduled Recordings') ) ]


    def display_schedule(self, arg=None, menuw=None):
        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return

        items = self.get_items()
        if not len(items):
            AlertBox(_('Nothing scheduled.')).show()
            return

        schedule_menu = menu.Menu(_('Scheduled Recordings'), items,
            reload_func=self.reload, item_types='tv program menu')
        self.menuw = menuw
        menuw.pushmenu(schedule_menu)
        menuw.refresh()


    def reload(self):
        menuw = self.menuw

        menu = menuw.menustack[-1]

        new_choices = self.get_items()
        if not menu.selected in new_choices and len(new_choices):
            sel = menu.choices.index(menu.selected)
            if len(new_choices) <= sel:
                menu.selected = new_choices[-1]
            else:
                menu.selected = new_choices[sel]

        menu.choices = new_choices

        return menu


    def get_items(self):
        items = []

        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return []

        (status, progs) = self.recordclient.getScheduledRecordingsNow()
        if status:
            f = lambda a, b: cmp(a.start, b.start)
            progs.sort(f)
            for prog in progs:
                items.append(ProgramItem(self, prog, context='schedule'))
        else:
            AlertBox(_('Get scheduled recordings failed')+(':\n%s' % schedule)).show()
            return []

        return items
class EditFavorite(PopupBox):
    """
    @param prog:    the program to record
    @param left:    x coordinate, Integer
    @param top:     y coordinate, Integer
    @param width:   width in pixels, Integer
    @param height:  height in pixels, Integer
    @param context: context in which the object is instantiated
    """
    def __init__(self, parent=None, subject=None, left=None, top=None, width=500, height=350, context=None):
        """ """
        _debug_('EditFavorite.__init__(parent=%r, subject=%r, left=%r, top=%r, width=%r, height=%r, context=%r)' % \
            (parent, subject, left, top, width, height, context), 1)

        self.oldname = None
        if context:
            self.context = context
        else:
            context = 'guide'

        self.recordclient = RecordClient()
        if isinstance(subject, TvProgram):
            (result, favs) = self.recordclient.getFavorites()
            if result:
                num_favorites = len(favs)
                self.priority = num_favorites + 1
            else:
                self.priority = 1
            self.fav = Favorite(subject.title, subject, TRUE, TRUE, TRUE, self.priority, TRUE, FALSE)

        else:
            self.fav = subject
            self.oldname = self.fav.name

        PopupBox.__init__(self, text=_('Edit Favorite'), x=left, y=top, width=width, height=height)

        self.v_spacing = 15
        self.h_margin = 20
        self.v_margin = 20

        self.internal_h_align = Align.LEFT

        if not self.left:     self.left   = self.osd.width/2 - self.width/2
        if not self.top:      self.top    = self.osd.height/2 - self.height/2

        guide = epg_xmltv.get_guide()

        name = Label(_('Name')+':', self, Align.LEFT)
        self.name_input = LetterBoxGroup(text=self.fav.name)
        self.name_input.h_align = Align.NONE
        self.add_child(self.name_input)


        title = Label(_('Title')+': %s' % self.fav.title, self, Align.LEFT)

        chan = Label(_('Channel')+':', self, Align.LEFT)

        self.chan_box = OptionBox('ANY')
        self.chan_box.h_align = Align.NONE
        self.chan_box.add_item(text=_('ANY'), value='ANY')

        i = 1
        chan_index = 0
        for ch in guide.chan_list:
            #if ch.id == self.fav.channel_id:
            if ch.displayname == self.fav.channel:
                chan_index = i
            i += 1
            self.chan_box.add_item(text=ch.displayname, value=ch.displayname)


        self.chan_box.toggle_selected_index(chan_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.chan_box.change_item(None)
        self.add_child(self.chan_box)

        dow = Label(_('Day of Week') +':', self, Align.LEFT)
        self.dow_box = OptionBox('ANY DAY')
        self.dow_box.h_align = Align.NONE

        self.dow_box.add_item(text=_('ANY DAY'), value='ANY')

        i=1
        dow_index = 0
        for dow in (_('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun')):
            val = "%d" % (i-1)
            self.dow_box.add_item(text=_(dow), value=val )
            if val == self.fav.dow:
                dow_index = i
            i += 1
        self.dow_box.toggle_selected_index(dow_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.dow_box.change_item(None)
        self.add_child(self.dow_box)

        tod = Label(_('Time of Day')+':', self, Align.LEFT)
        self.tod_box = OptionBox('ANY')
        self.tod_box.h_align = Align.NONE
        self.tod_box.add_item(text=_('ANY TIME'), value='ANY')

        i = 0
        tod_index = 0

        for h in range(0, 24):
            for m in (00, 30):
                val = i*30
                # Little hack: we calculate the hours from Jan 1st, 1970 GMT,
                # and then use strftime to get the string representation
                text = strftime(config.TV_TIME_FORMAT, gmtime(h * 3600 + 60 * m))
                self.tod_box.add_item(text=text, value=val)
                if val == self.fav.mod:
                    tod_index = i+1
                i += 1
        self.tod_box.toggle_selected_index(tod_index)
        # This is a hack for setting the OptionBox's label to the current
        # value. It should be done by OptionBox when drawing, but it doesn't
        # work :(
        self.tod_box.change_item(None)
        self.add_child(self.tod_box)

        self.save = Button(_('Save'))
        self.add_child(self.save)
        if self.oldname:
            self.remove = Button(_('Remove'))
            self.add_child(self.remove)
        else:
            self.remove = None
        self.cancel = Button(_('CANCEL'))
        self.add_child(self.cancel)


    def removeFavorite(self):
        _debug_('removeFavorite()', 2)
        (result, reason) = self.recordclient.removeFavoriteNow(self.oldname)
        if result:
            searcher = None
            if self.parent and self.context == 'favorites':
                for child in self.parent.children:
                    if isinstance(child, ViewFavorites):
                        searcher = child
                        break
                if searcher:
                    searcher.refreshList()
                self.destroy()
                if searcher:
                    searcher.draw()
                    self.osd.update()
        else:
            AlertBox(parent=self, text=_('Remove favorite failed')+(':\n%s' % reason)).show()


    def eventhandler(self, event, menuw=None):
        _debug_('eventhandler(event=%r, menuw=%r)' % (event, menuw), 2)

        if self.get_selected_child() == self.name_input:
            if event == em.INPUT_LEFT:
                self.name_input.change_selected_box('left')
                self.draw()
                return True
            elif event == em.INPUT_RIGHT:
                self.name_input.change_selected_box('right')
                self.draw()
                return True
            elif event == em.INPUT_ENTER:
                self.name_input.get_selected_box().toggle_selected()
                self.chan_box.toggle_selected()
                self.draw()
                return True
            elif event == em.INPUT_UP:
                self.name_input.get_selected_box().charUp()
                self.draw()
                return True
            elif event == em.INPUT_DOWN:
                self.name_input.get_selected_box().charDown()
                self.draw()
                return True
            elif event in em.INPUT_ALL_NUMBERS:
                self.name_input.get_selected_box().cycle_phone_char(event)
                self.draw()
                return True
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True

        elif self.get_selected_child() == self.chan_box:
            if event in (em.INPUT_UP, em.INPUT_DOWN):
                self.chan_box.change_item(event)
                self.draw()
            elif event == em.INPUT_ENTER:
                if self.chan_box.selected or self.chan_box.list.is_visible():
                    self.chan_box.toggle_box()
                    self.draw()
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.chan_box.toggle_selected()
                self.name_input.boxes[0].toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.chan_box.toggle_selected()
                self.dow_box.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
            return True

        elif self.get_selected_child() == self.dow_box:
            if event in (em.INPUT_UP, em.INPUT_DOWN):
                self.dow_box.change_item(event)
                self.draw()
            elif event == em.INPUT_ENTER:
                if self.dow_box.selected or self.dow_box.list.is_visible():
                    self.dow_box.toggle_box()
                    self.draw()
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.dow_box.toggle_selected()
                self.chan_box.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.dow_box.toggle_selected()
                self.tod_box.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.tod_box:
            if event in (em.INPUT_UP, em.INPUT_DOWN):
                self.tod_box.change_item(event)
                self.draw()
            elif event == em.INPUT_ENTER:
                if self.tod_box.selected or self.tod_box.list.is_visible():
                    self.tod_box.toggle_box()
                    self.draw()
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.tod_box.toggle_selected()
                self.dow_box.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.tod_box.toggle_selected()
                self.save.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.save:
            if event == em.INPUT_ENTER:
                # remove the old favourite
                if self.oldname:
                    (result, reason) = self.recordclient.removeFavoriteNow(self.oldname)
                    if not result:
                        AlertBox(parent=self, text=_('Add favorite failed')+(':\n%s' % reason)).show()
                # add the new favourite
                (result, reason) = self.recordclient.addEditedFavoriteNow(self.name_input.get_word(), self.fav.title,
                    self.chan_box.list.get_selected_item().value, self.dow_box.list.get_selected_item().value,
                    self.tod_box.list.get_selected_item().value, self.fav.priority, self.fav.allowDuplicates,
                    self.fav.onlyNew)
                if result:
                    #tv.view_favorites.ViewFavorites(parent=self.parent, text='Favorites').show()
                    self.destroy()
                    AlertBox(parent='osd', text=_('Favorite %s has been saved') % self.name_input.get_word()).show()
                else:
                    AlertBox(parent=self, text=_('Add favorite failed')+(':\n%s' % reason)).show()
                return True
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.save.toggle_selected()
                self.tod_box.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.save.toggle_selected()
                if self.remove:
                    self.remove.toggle_selected()
                else:
                    self.cancel.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.remove:
            if event == em.INPUT_ENTER:
                ConfirmBox(text=_('Do you want to remove %s?') % self.name_input.get_word(),
                           handler=self.removeFavorite).show()
                return True
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.save.toggle_selected()
                self.remove.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.remove.toggle_selected()
                self.cancel.toggle_selected()
                self.draw()
            elif event in (em.INPUT_ENTER, em.INPUT_EXIT):
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.cancel:
            if event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                if self.remove:
                    self.remove.toggle_selected()
                else:
                    self.save.toggle_selected()
                self.cancel.toggle_selected()
                self.draw()
            elif event in (em.INPUT_ENTER, em.INPUT_EXIT):
                self.destroy()
                return True
            return True
        if event == em.INPUT_EXIT:
            self.destroy()
            return True
        elif event in (em.MENU_PAGEDOWN, em.MENU_PAGEUP):
            return True
        else:
            return self.parent.eventhandler(event)
Beispiel #32
0
class EditFavorite(PopupBox):
    """ """

    def __init__(self, parent=None, subject=None, left=None, top=None, width=500, height=350, context=None):
        """
        Initialise an instance of EditFavorite

        @ivar parent:  parent of the class
        @ivar subject: the title of the program
        @ivar left:    x coordinate, Integer
        @ivar top:     y coordinate, Integer
        @ivar width:   width in pixels, Integer
        @ivar height:  height in pixels, Integer
        @ivar context: context in which the object is instantiated
        """
        logger.debug(
            "EditFavorite.__init__(parent=%r, subject=%r, left=%r, top=%r, width=%r, height=%r, context=%r)",
            parent,
            subject,
            left,
            top,
            width,
            height,
            context,
        )

        self.oldname = None
        if context:
            self.context = context
        else:
            context = "guide"

        self.recordclient = RecordClient()
        if isinstance(subject, TvProgram):
            (result, favs) = self.recordclient.getFavorites()
            if result:
                num_favorites = len(favs)
                self.priority = num_favorites + 1
            else:
                self.priority = 1
            self.fav = Favorite(subject.title, subject, TRUE, TRUE, TRUE, self.priority, TRUE, FALSE)

        else:
            self.fav = subject
            self.oldname = self.fav.name

        PopupBox.__init__(self, text=_("Edit Favorite"), x=left, y=top, width=width, height=height)

        self.v_spacing = 15
        self.h_margin = 20
        self.v_margin = 20

        self.internal_h_align = Align.LEFT

        if not self.left:
            self.left = self.osd.width / 2 - self.width / 2
        if not self.top:
            self.top = self.osd.height / 2 - self.height / 2

        name = Label(_("Name") + ":", self, Align.LEFT)
        self.name_input = LetterBoxGroup(text=self.fav.name)
        self.name_input.h_align = Align.NONE
        self.add_child(self.name_input)

        title = Label(_("Title") + ": %s" % self.fav.title, self, Align.LEFT)

        chan = Label(_("Channel") + ":", self, Align.LEFT)

        self.chan_box = OptionBox("ANY")
        self.chan_box.h_align = Align.NONE
        self.chan_box.add_item(text=_("ANY"), value="ANY")

        i = 1
        chan_index = 0
        for ch in tv.epg.channels:
            # if ch.id == self.fav.channel_id:
            if ch.displayname == self.fav.channel:
                chan_index = i
            i += 1
            self.chan_box.add_item(text=ch.displayname, value=ch.displayname)

        self.chan_box.toggle_selected_index(chan_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.chan_box.change_item(None)
        self.add_child(self.chan_box)

        dow = Label(_("Day of Week") + ":", self, Align.LEFT)
        self.dow_box = OptionBox("ANY DAY")
        self.dow_box.h_align = Align.NONE

        self.dow_box.add_item(text=_("ANY DAY"), value="ANY")

        i = 1
        dow_index = 0
        for dow in (_("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun")):
            val = "%d" % (i - 1)
            self.dow_box.add_item(text=_(dow), value=val)
            if val == self.fav.dow:
                dow_index = i
            i += 1
        self.dow_box.toggle_selected_index(dow_index)
        # This is a hack for setting the OptionBox's label to the current value.
        # It should be done by OptionBox when drawing, but it doesn't work :(
        self.dow_box.change_item(None)
        self.add_child(self.dow_box)

        tod = Label(_("Time of Day") + ":", self, Align.LEFT)
        self.tod_box = OptionBox("ANY")
        self.tod_box.h_align = Align.NONE
        self.tod_box.add_item(text=_("ANY TIME"), value="ANY")

        i = 0
        tod_index = 0

        for h in range(0, 24):
            for m in (00, 30):
                val = i * 30
                # Little hack: we calculate the hours from Jan 1st, 1970 GMT,
                # and then use strftime to get the string representation
                text = strftime(config.TV_TIME_FORMAT, gmtime(h * 3600 + 60 * m))
                self.tod_box.add_item(text=text, value=val)
                if val == self.fav.mod:
                    tod_index = i + 1
                i += 1
        self.tod_box.toggle_selected_index(tod_index)
        # This is a hack for setting the OptionBox's label to the current
        # value. It should be done by OptionBox when drawing, but it doesn't
        # work :(
        self.tod_box.change_item(None)
        self.add_child(self.tod_box)

        self.save = Button(_("Save"))
        self.add_child(self.save)
        if self.oldname:
            self.remove = Button(_("Remove"))
            self.add_child(self.remove)
        else:
            self.remove = None
        self.cancel = Button(_("CANCEL"))
        self.add_child(self.cancel)

    def removeFavorite(self):
        logger.log(9, "removeFavorite()")
        (result, reason) = self.recordclient.removeFavoriteNow(self.oldname)
        if result:
            searcher = None
            if self.parent and self.context == "favorites":
                for child in self.parent.children:
                    if isinstance(child, ViewFavorites):
                        searcher = child
                        break
                if searcher:
                    searcher.refreshList()
                self.destroy()
                if searcher:
                    searcher.draw()
                    self.osd.update()
        else:
            AlertBox(parent=self, text=_("Remove favorite failed") + (":\n%s" % reason)).show()

    def eventhandler(self, event, menuw=None):
        logger.log(9, "eventhandler(event=%r, menuw=%r)", event, menuw)

        if self.get_selected_child() == self.name_input:
            if event == em.INPUT_LEFT:
                self.name_input.change_selected_box("left")
                self.draw()
                return True
            elif event == em.INPUT_RIGHT:
                self.name_input.change_selected_box("right")
                self.draw()
                return True
            elif event == em.INPUT_ENTER:
                self.name_input.get_selected_box().toggle_selected()
                self.chan_box.toggle_selected()
                self.draw()
                return True
            elif event == em.INPUT_UP:
                self.name_input.get_selected_box().charUp()
                self.draw()
                return True
            elif event == em.INPUT_DOWN:
                self.name_input.get_selected_box().charDown()
                self.draw()
                return True
            elif event in em.INPUT_ALL_NUMBERS:
                self.name_input.get_selected_box().cycle_phone_char(event)
                self.draw()
                return True
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True

        elif self.get_selected_child() == self.chan_box:
            if event in (em.INPUT_UP, em.INPUT_DOWN):
                self.chan_box.change_item(event)
                self.draw()
            elif event == em.INPUT_ENTER:
                if self.chan_box.selected or self.chan_box.list.is_visible():
                    self.chan_box.toggle_box()
                    self.draw()
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.chan_box.toggle_selected()
                self.name_input.boxes[0].toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.chan_box.toggle_selected()
                self.dow_box.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
            return True

        elif self.get_selected_child() == self.dow_box:
            if event in (em.INPUT_UP, em.INPUT_DOWN):
                self.dow_box.change_item(event)
                self.draw()
            elif event == em.INPUT_ENTER:
                if self.dow_box.selected or self.dow_box.list.is_visible():
                    self.dow_box.toggle_box()
                    self.draw()
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.dow_box.toggle_selected()
                self.chan_box.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.dow_box.toggle_selected()
                self.tod_box.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.tod_box:
            if event in (em.INPUT_UP, em.INPUT_DOWN):
                self.tod_box.change_item(event)
                self.draw()
            elif event == em.INPUT_ENTER:
                if self.tod_box.selected or self.tod_box.list.is_visible():
                    self.tod_box.toggle_box()
                    self.draw()
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.tod_box.toggle_selected()
                self.dow_box.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.tod_box.toggle_selected()
                self.save.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.save:
            if event == em.INPUT_ENTER:
                # remove the old favourite
                if self.oldname:
                    (result, reason) = self.recordclient.removeFavoriteNow(self.oldname)
                    if not result:
                        AlertBox(parent=self, text=_("Add favorite failed") + (":\n%s" % reason)).show()
                # add the new favourite
                (result, reason) = self.recordclient.addEditedFavoriteNow(
                    self.name_input.get_word(),
                    self.fav.title,
                    self.chan_box.list.get_selected_item().value,
                    self.dow_box.list.get_selected_item().value,
                    self.tod_box.list.get_selected_item().value,
                    self.fav.priority,
                    self.fav.allowDuplicates,
                    self.fav.onlyNew,
                )
                if result:
                    # tv.view_favorites.ViewFavorites(parent=self.parent, text='Favorites').show()
                    self.destroy()
                    AlertBox(parent="osd", text=_("Favorite %s has been saved") % self.name_input.get_word()).show()
                else:
                    AlertBox(parent=self, text=_("Add favorite failed") + (":\n%s" % reason)).show()
                return True
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.save.toggle_selected()
                self.tod_box.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.save.toggle_selected()
                if self.remove:
                    self.remove.toggle_selected()
                else:
                    self.cancel.toggle_selected()
                self.draw()
            elif event == em.INPUT_EXIT:
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.remove:
            if event == em.INPUT_ENTER:
                ConfirmBox(
                    text=_("Do you want to remove %s?") % self.name_input.get_word(), handler=self.removeFavorite
                ).show()
                return True
            elif event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                self.save.toggle_selected()
                self.remove.toggle_selected()
                self.draw()
            elif event in (em.INPUT_RIGHT, em.MENU_PAGEDOWN):
                self.remove.toggle_selected()
                self.cancel.toggle_selected()
                self.draw()
            elif event in (em.INPUT_ENTER, em.INPUT_EXIT):
                self.destroy()
                return True
            return True

        elif self.get_selected_child() == self.cancel:
            if event in (em.INPUT_LEFT, em.MENU_PAGEUP):
                if self.remove:
                    self.remove.toggle_selected()
                else:
                    self.save.toggle_selected()
                self.cancel.toggle_selected()
                self.draw()
            elif event in (em.INPUT_ENTER, em.INPUT_EXIT):
                self.destroy()
                return True
            return True
        if event == em.INPUT_EXIT:
            self.destroy()
            return True
        elif event in (em.MENU_PAGEDOWN, em.MENU_PAGEUP):
            return True
        else:
            return self.parent.eventhandler(event)
Beispiel #33
0
class ManualRecordItem(Item):
    def __init__(self, parent):
        _debug_('manual_record.ManualRecordItem.__init__(parent)', 2)
        Item.__init__(self, parent, skin_type='video')

        self.name = _("Manual Record")

        self.recordclient = RecordClient()

        # maxinum number of days we can record
        self.MAXDAYS = 7

        # minimum amount of time it would take record_server.py
        # to pick us up in seconds by default it is one minute plus
        # a few seconds just in case
        self.MINPICKUP = 70

        self.months = [
            _('Jan'),
            _('Feb'),
            _('Mar'),
            _('Apr'),
            _('May'),
            _('Jun'),
            _('Jul'),
            _('Aug'),
            _('Sep'),
            _('Oct'),
            _('Nov'),
            _('Dec')
        ]

        now = time.time()
        now += 300
        self.startnow = now
        self.starttime = time.localtime(now)
        now += 1900
        self.stopnow = now
        self.stoptime = time.localtime(now)

    def make_newprog(self):
        _debug_('make_newprog(self)', 2)
        self.prog = TvProgram()

        self.disp_title = self.prog.title = self.name

        self.description = ''
        self.prog.desc = ''

        self.prog.channel_id = config.TV_CHANNELS[0][0]
        self.disp_channel = config.TV_CHANNELS[0][1]

        #self.start_year = self.starttime[0]
        self.start_month = self.starttime[1]
        self.disp_start_month = self.months[self.start_month - 1]
        self.start_day = self.starttime[2]
        self.start_time = time.strftime(config.TV_TIME_FORMAT, self.starttime)
        self.prog.start = self.startnow
        self.disp_starttime = '%s %s %s' % (self.disp_start_month,
                                            self.start_day, self.start_time)

        #self.stop_year = self.stoptime[0]
        self.stop_month = self.stoptime[1]
        self.disp_stop_month = self.months[self.stop_month - 1]
        self.stop_day = self.stoptime[2]
        self.stop_time = time.strftime(config.TV_TIME_FORMAT, self.stoptime)
        self.prog.stop = self.stopnow
        self.disp_stoptime = '%s %s %s' % (self.disp_stop_month, self.stop_day,
                                           self.stop_time)

    def actions(self):
        _debug_('actions(self)', 2)
        return [(self.display_recitem, _('Display record item'))]

    def display_recitem(self, arg=None, menuw=None):
        _debug_('display_recitem(self, arg=None, menuw=None)', 2)
        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return

        self.make_newprog()

        items = []

        items.append(menu.MenuItem(_('Modify name'), action=self.mod_name))
        items.append(
            menu.MenuItem(_('Modify channel'), action=self.mod_channel))
        items.append(
            menu.MenuItem(_('Modify start month'),
                          action=self.mod_start_month))
        items.append(
            menu.MenuItem(_('Modify start day'), action=self.mod_start_day))
        items.append(
            menu.MenuItem(_('Modify start time'), action=self.mod_start_time))
        items.append(
            menu.MenuItem(_('Modify stop month'), action=self.mod_stop_month))
        items.append(
            menu.MenuItem(_('Modify stop day'), action=self.mod_stop_day))
        items.append(
            menu.MenuItem(_('Modify stop time'), action=self.mod_stop_time))
        items.append(menu.MenuItem(_('Save'), action=self.save_changes))

        manualrecord_menu = menu.Menu(_('Record Item Menu'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_name(self, arg=None, menuw=None):
        _debug_('mod_name(self, arg=None, menuw=None)', 2)
        self.menuw = menuw
        InputBox(text=_('Alter Name'), handler=self.alter_name).show()

    def mod_channel(self, arg=None, menuw=None):
        _debug_('mod_channel(self, arg=None, menuw=None)', 2)
        items = []

        for chanline in config.TV_CHANNELS:
            items.append(
                menu.MenuItem(chanline[1],
                              action=self.alter_prop,
                              arg=('channel', (chanline[1], chanline[0]))))

        manualrecord_menu = menu.Menu(_('Modify Channel'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_start_month(self, arg=None, menuw=None):
        _debug_('mod_start_month(self, arg=None, menuw=None)', 2)
        items = []

        iter = 0
        while iter < 12:
            month_name = self.months[(iter + self.starttime[1] - 1) % 12]
            month_num = self.months.index(month_name) + 1
            items.append(
                menu.MenuItem(month_name,
                              action=self.alter_prop,
                              arg=('startmonth', (month_name, month_num))))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_start_day(self, arg=None, menuw=None):
        _debug_('mod_start_day(self, arg=None, menuw=None)', 2)
        items = []

        numdays = calendar.monthrange(self.starttime[0], self.start_month)[1]
        daylimit = numdays + 1
        iter = 1
        while iter < daylimit:
            newday = (iter + self.starttime[2] - 1)
            currday = newday % daylimit
            if newday >= daylimit:
                currday += 1
            items.append(
                menu.MenuItem(str(currday),
                              action=self.alter_prop,
                              arg=('startday', currday)))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_start_time(self, arg=None, menuw=None):
        _debug_('mod_start_time(self, arg=None, menuw=None)', 2)
        items = []

        currminutes = self.starttime[3] * 60 + self.starttime[4]
        minpadding = 5 - (currminutes % 5)
        if minpadding == 5:
            minpadding = 0
        for i in range(288):
            mod = (i * 5 + currminutes + minpadding) % 1440
            showtime = strftime(config.TV_TIME_FORMAT, gmtime(float(mod * 60)))
            items.append(
                menu.MenuItem(showtime,
                              action=self.alter_prop,
                              arg=('starttime', showtime)))

        manualrecord_menu = menu.Menu(_('Modify Time'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_stop_month(self, arg=None, menuw=None):
        _debug_('mod_stop_month(self, arg=None, menuw=None)', 2)
        items = []

        iter = 0
        while iter < 12:
            month_name = self.months[(iter + self.stoptime[1] - 1) % 12]
            month_num = self.months.index(month_name) + 1
            items.append(
                menu.MenuItem(month_name,
                              action=self.alter_prop,
                              arg=('stopmonth', (month_name, month_num))))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_stop_day(self, arg=None, menuw=None):
        _debug_('mod_stop_day(self, arg=None, menuw=None)', 2)
        items = []

        numdays = calendar.monthrange(self.stoptime[0], self.stop_month)[1]
        daylimit = numdays + 1
        iter = 1
        while iter < daylimit:
            newday = (iter + self.starttime[2] - 1)
            currday = newday % daylimit
            if newday >= daylimit:
                currday += 1
            items.append(
                menu.MenuItem(str(currday),
                              action=self.alter_prop,
                              arg=('stopday', currday)))
            iter = iter + 1

        manualrecord_menu = menu.Menu(_('Modify Day'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def mod_stop_time(self, arg=None, menuw=None):
        _debug_('mod_stop_time(self, arg=None, menuw=None)', 2)
        items = []

        currminutes = self.starttime[3] * 60 + self.starttime[4]
        minpadding = 5 - (currminutes % 5)
        if minpadding == 5:
            minpadding = 0
        for i in range(288):
            mod = (i * 5 + currminutes + minpadding) % 1440
            showtime = strftime(config.TV_TIME_FORMAT, gmtime(float(mod * 60)))
            items.append(
                menu.MenuItem(showtime,
                              action=self.alter_prop,
                              arg=('stoptime', showtime)))

        manualrecord_menu = menu.Menu(_('Modify Time'),
                                      items,
                                      item_types='tv manual record menu')
        manualrecord_menu.infoitem = self
        menuw.pushmenu(manualrecord_menu)
        menuw.refresh()

    def alter_name(self, name):
        _debug_('alter_name(self, name)', 2)
        if name:
            self.disp_title = self.prog.title = name

        self.menuw.refresh()

    def alter_prop(self, arg=(None, None), menuw=None):
        _debug_('alter_prop(self, arg=(None,None), menuw=None)', 2)
        (prop, val) = arg

        if prop == 'channel':
            self.prog.channel_id = val[1]
            self.disp_channel = val[0]

        if prop == 'startday':
            self.start_day = val
            self.disp_starttime = '%s %s %s' % (
                self.disp_start_month, self.start_day, self.start_time)

        if prop == 'startmonth':
            self.start_month = val[1]
            self.disp_start_month = val[0]
            self.disp_starttime = '%s %s %s' % (
                self.disp_start_month, self.start_day, self.start_time)

        if prop == 'starttime':
            self.start_time = val
            self.disp_starttime = '%s %s %s' % (
                self.disp_start_month, self.start_day, self.start_time)

        if prop == 'stopday':
            self.stop_day = val
            self.disp_stoptime = '%s %s %s' % (self.disp_stop_month,
                                               self.stop_day, self.stop_time)

        if prop == 'stopmonth':
            self.stop_month = val[1]
            self.disp_stop_month = val[0]
            self.disp_stoptime = '%s %s %s' % (self.disp_stop_month,
                                               self.stop_day, self.stop_time)

        if prop == 'stoptime':
            self.stop_time = val
            self.disp_stoptime = '%s %s %s' % (self.disp_stop_month,
                                               self.stop_day, self.stop_time)

        if menuw:
            menuw.back_one_menu(arg='reload')

    def save_changes(self, arg=None, menuw=None):
        _debug_('save_changes(self, arg=None, menuw=None)', 2)
        result = self.check_prog()
        if result:
            (result,
             reason) = self.recordclient.scheduleRecordingNow(self.prog)

            if not result:
                AlertBox(text=_('Save Failed, recording was lost') +
                         (':\n%s' % reason)).show()
            else:
                if menuw:
                    menuw.back_one_menu(arg='reload')

    def check_prog(self):
        _debug_('check_prog(self)', 2)
        isgood = True
        curtime_epoch = time.time()
        curtime = time.localtime(curtime_epoch)
        startyear = curtime[0]
        stopyear = curtime[0]
        currentmonth = curtime[1]

        # handle the year wraparound
        if int(self.stop_month) < currentmonth:
            stopyear = str(int(stopyear) + 1)
        if int(self.start_month) < currentmonth:
            startyear = str(int(startyear) + 1)
        # create utc second start time
        starttime = time.mktime(
            strptime.strptime(
                str(self.start_month) + " " + str(self.start_day) + " " +
                str(startyear) + " " + str(self.start_time) + ":00",
                '%m %d %Y ' + config.TV_TIME_FORMAT + ':%S'))
        # create utc stop time
        stoptime = time.mktime(
            strptime.strptime(
                str(self.stop_month) + " " + str(self.stop_day) + " " +
                str(stopyear) + " " + str(self.stop_time) + ":00",
                '%m %d %Y ' + config.TV_TIME_FORMAT + ':%S'))

        # so we don't record for more then maxdays (maxdays day * 24hr/day * 60 min/hr * 60 sec/min)
        if not abs(stoptime - starttime) < (self.MAXDAYS * 86400):
            if self.MAXDAYS > 1:
                isgood = False
                msg = _("Program would record for more than %d days!"
                        ) % self.MAXDAYS
                AlertBox(text=_('Save Failed, recording was lost') +
                         (':\n%s' % msg)).show()
            else:
                isgood = False
                msg = _(
                    "Program would record for more than 1 day!") % self.MAXDAYS
                AlertBox(text=_('Save Failed, recording was lost') +
                         (':\n%s' % msg)).show()

        elif not starttime < stoptime:
            isgood = False
            msg = _("start time is not before stop time.")
            AlertBox(text=_('Save Failed, recording was lost') +
                     (':\n%s' % msg)).show()
        elif stoptime < curtime_epoch + self.MINPICKUP:
            isgood = False
            msg = _(
                "Sorry, the stop time does not give enough time for scheduler to pickup the change.  Please set it to record for a few minutes longer."
            )
            AlertBox(text=_('Save Failed, recording was lost') +
                     (':\n%s' % msg)).show()
        else:
            self.prog.start = starttime
            self.prog.stop = stoptime

        return isgood
Beispiel #34
0
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# -----------------------------------------------------------------------

import config
import kaa
from tv.record_client import RecordClient


def handler(result):
    if result:
        print _('Updated recording schedule')
    else:
        print _('Not updated recording schedule')
    raise SystemExit


rc = RecordClient()
try:
    kaa.inprogress(rc.channel).wait()
except Exception, why:
    print 'Cannot connect to record server'
    raise SystemExit

print _('Updating recording schedule')
if not rc.updateFavoritesSchedule(handler):
    print rc.recordserverdown
    raise SystemExit

kaa.main.run()
Beispiel #35
0
 def __init__(self, parent):
     logger.log(9, 'ViewFavoritesItem.__init__(parent=%r)', parent)
     Item.__init__(self, parent, skin_type='tv')
     self.name = _('View Favorites')
     self.menuw = None
     self.recordclient = RecordClient()
Beispiel #36
0
class ViewFavoritesItem(Item):
    def __init__(self, parent):
        _debug_('ViewFavoritesItem.__init__(parent=%r)' % (parent,), 2)
        Item.__init__(self, parent, skin_type='tv')
        self.name = _('View Favorites')
        self.menuw = None
        self.recordclient = RecordClient()


    def actions(self):
        _debug_('actions()', 2)
        return [ ( self.view_favorites , _('View Favorites') ) ]


    def view_favorites(self, arg=None, menuw=None):
        _debug_('view_favorites(arg=%r, menuw=%r)' % (arg, menuw), 2)
        if not self.recordclient.pingNow():
            AlertBox(self.recordclient.recordserverdown).show()
            return

        items = self.get_items()
        if not len(items):
            AlertBox(_('No favorites.')).show()
            return

        favorite_menu = menu.Menu(_( 'View Favorites'), items, reload_func=self.reload, item_types='tv favorite menu')
        self.menuw = menuw
        rc.app(None)
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def reload(self):
        _debug_('reload()', 2)
        menuw = self.menuw

        menu = menuw.menustack[-1]

        new_choices = self.get_items()
        if not menu.selected in new_choices and len(new_choices):
            sel = menu.choices.index(menu.selected)
            if len(new_choices) <= sel:
                menu.selected = new_choices[-1]
            else:
                menu.selected = new_choices[sel]

        menu.choices = new_choices

        return menu


    def get_items(self):
        _debug_('get_items()', 2)
        items = []

        (status, favorites) = self.recordclient.getFavoritesNow()
        if status:
            f = lambda a, b: cmp(a.priority, b.priority)
            favs = favorites.values()
            favs.sort(f)
            for fav in favs:
                items.append(FavoriteItem(self, fav))

        return items
Beispiel #37
0
 def __init__(self, parent):
     _debug_('ViewFavoritesItem.__init__(parent=%r)' % (parent,), 2)
     Item.__init__(self, parent, skin_type='tv')
     self.name = _('View Favorites')
     self.menuw = None
     self.recordclient = RecordClient()
Beispiel #38
0
def comingup(items=None, scheduledRecordings=None):
    """ Coming Up for TV schedule """
    from tv.record_client import RecordClient
    import time
    import codecs

    result = u''

    cachefile = '%s/upsoon' % (config.FREEVO_CACHEDIR)
    if not scheduledRecordings:
        if os.path.exists(cachefile) and abs(
                time.time() - os.path.getmtime(cachefile)) < 600:
            cache = codecs.open(cachefile, 'r', config.encoding)
            for a in cache.readlines():
                result = result + a
            cache.close()
            return result

        (status, schedule) = RecordClient().getScheduledRecordingsNow()
        if not status:
            return schedule
    else:
        (status, schedule) = scheduledRecordings

    if not status:
        return schedule  # in this case the schedule is the reason

    progs = schedule.getProgramList()

    f = lambda a, b: cmp(a.start, b.start)
    progl = progs.values()
    progl.sort(f)

    today = []
    tomorrow = []
    later = []

    for what in progl:
        if time.localtime(what.start)[2] == time.localtime()[2]:
            today.append(what)
        if time.localtime(what.start)[2] == (time.localtime()[2] + 1):
            tomorrow.append(what)
        if time.localtime(what.start)[2] > (time.localtime()[2] + 1):
            later.append(what)

    if len(today) > 0:
        result = result + _('Today') + u':\n'
        for m in today:
            sub_title = ''
            if hasattr(m, 'sub_title') and m.sub_title:
                sub_title = u' "' + Unicode(m.sub_title) + u'" '
            result = result + u"- %s%s " % \
                     ( Unicode(m.title), Unicode(sub_title) ) \
                     + _('at') + u" %s\n" % \
                     Unicode(time.strftime(config.TV_TIME_FORMAT, time.localtime(m.start)))

    if len(tomorrow) > 0:
        result = result + _('Tomorrow') + u':\n'
        for m in tomorrow:
            sub_title = ''
            if hasattr(m, 'sub_title') and m.sub_title:
                sub_title = ' "' + m.sub_title + '" '
            result = result + u"- %s%s " % \
                     ( Unicode(m.title), Unicode(sub_title) ) \
                     + _('at') + u" %s\n" % \
                     Unicode(time.strftime(config.TV_TIME_FORMAT, time.localtime(m.start)))

    if len(later) > 0:
        result = result + _('This Week') + u':\n'
        for m in later:
            sub_title = ''
            if hasattr(m, 'sub_title') and m.sub_title:
                sub_title = ' "' + m.sub_title + '" '
            result = result + u"- %s%s " % ( Unicode(m.title), Unicode(sub_title) ) \
                    + _('at') + u" %s\n" % Unicode(time.strftime(config.TV_DATE_FORMAT, time.localtime(m.start)))

    if not result:
        result = _('No recordings are scheduled')

    if os.path.isfile(cachefile):
        os.unlink(cachefile)
    cache = codecs.open(cachefile, 'w', config.encoding)
    cache.write(result)
    cache.close()

    return result
Beispiel #39
0
class FavoriteItem(Item):
    """
    Item class for favorite items
    """
    def __init__(self, parent, fav, fav_action='edit'):
        """ """
        Item.__init__(self, parent, skin_type='video')
        logger.log( 9, 'FavoriteItem.__init__(parent=%r, fav=%r, fav_action=%r)', parent, fav, fav_action)
        self.recordclient = RecordClient()
        self.fav   = fav
        self.name  = self.origname = fav.name
        self.title = fav.title
        self.fav_action = fav_action
        if hasattr(fav, 'allowDuplicates'):
            self.allowDuplicates = int(fav.allowDuplicates)

        if hasattr(self.fav, 'onlyNew'):
            self.onlyNew = int(fav.onlyNew)

        self.week_days = (_('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'))


        if fav.channel == 'ANY':
            self.channel = _('ANY CHANNEL')
        else:
            self.channel = fav.channel
        if fav.dow == 'ANY':
            self.dow = _('ANY DAY')
        else:
            self.dow = self.week_days[int(fav.dow)]
        if fav.mod == 'ANY':
            self.mod = _('ANY TIME')
        else:
            try:
                self.mod = time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(int(fav.mod) * 60)))
            except:
                print 'Cannot add "%s" to favorites' % fav.name

        # needed by the inputbox handler
        self.menuw = None


    def actions(self):
        logger.log( 9, 'actions()')
        return [( self.display_submenu, _('Edit favorite')), 
                ( self.priority_up, _('Increase priority')), 
                ( self.priority_down, _('Decrease priority')),
                ( self.rem_favorite, _('Remove favorite'))]


    def display_submenu(self, arg=None, menuw=None):
        """ Display menu for a favorite

        With this menu the user can made a program a favorite.
        All attributes of a favorite can be edited here and in the end
        the user must select 'save changes' to finally create the favorite.
        """
        logger.log( 9, 'display_submenu(arg=%r, menuw=%r)', arg, menuw)
        ### create menu items for editing the favorites attributes
        items = []

        items.append(menu.MenuItem(_('Name') + u'\t' + _(self.name), action=self.mod_name))
        items.append(menu.MenuItem(_('Channel') + u'\t' + _(self.channel), action=self.mod_channel))
        items.append(menu.MenuItem(_('Day of the Week') + u'\t' + _(self.dow), action=self.mod_day))
        items.append(menu.MenuItem(_('Time of Day') + u'\t' + _(self.mod), action=self.mod_time))

        if config.TV_RECORD_DUPLICATE_DETECTION:
            if self.allowDuplicates:
                value = _('Allow duplicates')
            else:
                value = _('Prevent duplicates')
            items.append(menu.MenuItem(_('Duplicate Recordings') + u'\t' + _(value),
                                        action=self.alter_prop,
                                        arg=('dup', not self.allowDuplicates)))


        if config.TV_RECORD_ONLY_NEW_DETECTION:
            if self.onlyNew:
                value = _('Only new episodes')
            else:
                value = _('All episodes')
            items.append(menu.MenuItem(_('Episode Filter') + u'\t' + _(value),
                                        action=self.alter_prop,
                                        arg=('new', not self.onlyNew)))

        # XXX: priorities aren't quite supported yet
        if 0:
            (status, favorites) = self.recordclient.getFavoritesNow()
            if status and len(favorites) > 1:
                items.append(menu.MenuItem(_('Modify priority'), action=self.mod_priority))


        ### save favorite
        items.append(menu.MenuItem(_('Save changes') + u'\t', action=self.save_changes))

        ### remove this program from favorites
        if not self.fav_action == 'add':
            items.append(menu.MenuItem(_('Remove favorite') + u'\t', action=self.rem_favorite))

        ### put the whole menu together
        favorite_menu = menu.Menu(_('Favorite Menu'), items, item_types='tv favorite menu')
        favorite_menu.infoitem = self
        favorite_menu.is_submenu = True
        favorite_menu.table = (50, 50)
        menuw.pushmenu(favorite_menu)
        menuw.refresh()



    ### Actions:

    def mod_name(self, arg=None, menuw=None):
        """ Modify name

        This opens a input box to ask the user for a new name for this favorite.
        The default name of a favorite is the name of the program.
        """
        logger.log( 9, 'mod_name(arg=%r, menuw=%r)', arg, menuw)
        self.menuw = menuw
        InputBox(text=_('Alter Name'), handler=self.alter_name, \
            width=osd.get_singleton().width - config.OSD_OVERSCAN_LEFT - 20, input_text=self.name).show()


    def alter_name(self, name):
        """ set the new name"""
        logger.log( 9, 'alter_name(name=%r)', name)
        if name:
            self.name = self.fav.name = name.strip()
        menustack = self.menuw.menustack[-1]
        menustack.selected.dirty = True
        self.menuw.refresh()


    def mod_channel(self, arg=None, menuw=None):
        """Modify channel"""
        logger.log( 9, 'mod_channel(arg=%r, menuw=%r)', arg, menuw)
        items = []

        items.append(menu.MenuItem('ANY CHANNEL', action=self.alter_prop, arg=('channel', 'ANY')))

        for chanline in config.TV_CHANNELS:
            items.append(menu.MenuItem(chanline[1], action=self.alter_prop, arg=('channel', chanline[1])))

        favorite_menu = menu.Menu(_('Modify Channel'), items, item_types='tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def mod_day(self, arg=None, menuw=None):
        """ Modify day

        Opens a submenu where the day of the week of a favorite can be configured.
        """
        logger.log( 9, 'mod_day(arg=%r, menuw=%r)', arg, menuw)
        items = []

        items.append(menu.MenuItem(_('ANY DAY'), action=self.alter_prop, arg=('dow', 'ANY')))

        for i in range(len(self.week_days)):
            items.append(menu.MenuItem(self.week_days[i], action=self.alter_prop, arg=('dow', i)))

        favorite_menu = menu.Menu(_('Modify Day'), items, item_types = 'tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def mod_time(self, arg=None, menuw=None):
        """ Modify time

        Opens a submenu where the time of a favorite can be configured.
        """
        logger.log( 9, 'mod_time(arg=%r, menuw=%r)', arg, menuw)
        items = []

        items.append(menu.MenuItem(_('ANY TIME'), action=self.alter_prop, arg=('mod', 'ANY')))

        for i in range(48):
            mod = i * 30
            items.append(menu.MenuItem(time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(mod * 60))), \
                action=self.alter_prop, arg=('mod', mod)))

        favorite_menu = menu.Menu(_('Modify Time'), items, item_types = 'tv favorite menu')
        favorite_menu.infoitem = self
        menuw.pushmenu(favorite_menu)
        menuw.refresh()


    def alter_prop(self, arg=(None, None), menuw=None):
        """ Alter a favorites property

        This function is where the properties of a favorite really are changed.
        """
        logger.log( 9, 'alter_prop(arg=%r, menuw=%r)', arg, menuw)
        (prop, val) = arg
        new_text = None
        new_arg = None
        back = True

        if prop == 'channel':
            if val == 'ANY':
                self.channel = 'ANY CHANNEL'
                self.fav.channel = 'ANY'
            else:
                self.channel = val
                self.fav.channel = val
            new_text = _('Channel') + u'\t' + _(self.channel)

        elif prop == 'dow':
            if val == 'ANY':
                self.dow = 'ANY DAY'
                self.fav.dow = 'ANY'
            else:
                self.dow = self.week_days[val]
                self.fav.dow = val
            new_text = _('Day of the Week') + u'\t' + _(self.dow)

        elif prop == 'mod':
            if val == 'ANY':
                self.mod = 'ANY TIME'
                self.fav.mod = 'ANY'
            else:
                # self.mod = tv_util.minToTOD(val)
                self.mod = time.strftime(config.TV_TIME_FORMAT, time.gmtime(float(val * 60)))
                self.fav.mod = val
            new_text = _('Time of Day') + u'\t' + _(self.mod)

        elif prop == 'dup':
            self.allowDuplicates= self.fav.allowDuplicates= val
            if val:
                value = _('Allow Duplicates')
            else:
                value = _('Prevent Duplicates')

            new_text =  _('Duplicate Recordings') + u'\t' + value
            new_arg = ('dup', not val)
            back = False

        elif prop == 'new':
            self.onlyNew= self.fav.onlyNew = val
            if val:
                value = _('Only New Episodes')
            else:
                value = _('All New Episodes')
            new_text = _('Episode Filter') + u'\t' + value
            new_arg = ('new', not val)
            back = False

        if menuw and new_text:
            menu = menuw.menustack[back and -2 or -1]
            menu.selected.name = new_text
            if new_arg:
                menu.selected.arg = new_arg
            menu.selected.dirty = True
            if back:
                menuw.back_one_menu(arg='reload')
            else:
                menuw.refresh()

    def save_changes(self, arg=None, menuw=None):
        """
        Save favorite
        """
        logger.log( 9, 'save_changes(arg=%r, menuw=%r)', arg, menuw)
        # this can take some time, as it means although to update the schedule
        msgtext = _('Saving the changes to this favorite.')+'\n'+_('This may take some time.')
        pop = dialog.show_working_indicator(msgtext)

        if self.fav_action == 'edit':
            # first we remove the old favorite
            (result, msg) = self.recordclient.removeFavoriteNow(self.origname)
        elif self.fav_action =='add':
            result = True

        if result:
            # create a new edited favorite
            (result, msg) = self.recordclient.addEditedFavoriteNow(self.fav.name,
                self.fav.title, self.fav.channel, self.fav.dow, self.fav.mod,
                self.fav.priority, self.fav.allowDuplicates, self.fav.onlyNew)
            if result:
                if menuw:
                    menuw.delete_submenu()
                    if self.fav_action == 'add':
                        menuw.refresh(reload=1)
                self.fav_action = 'edit'
                pop.hide()
            else:
                pop.hide()
                # it is important to show the user this error,
                # because that means the favorite is removed,
                # and must be created again
                msgtext=_('Save failed, favorite was lost')+(':\n%s' % msg)
                dialog.show_alert(msgtext)


    def rem_favorite(self, arg=None, menuw=None):
        """
        Remove favorite
        """
        logger.log( 9, 'rem_favorite(arg=%r, menuw=%r)', arg, menuw)
        name = self.origname
        (result, msg) = self.recordclient.removeFavoriteNow(name)
        if result:
            # if this is successfull
            if menuw:
                menuw.delete_submenu()
                menuw.refresh(reload=1)
            # and show a short message of success
            msgtext = text=_('"%s" has been removed from favorites') % name
            dialog.show_alert(msgtext)
        else:
            # if all fails then we should show an error
            msgtext = _('Remove failed')+(':\n%s' % msg)
            dialog.show_alert(msgtext)


    def priority_mod(self, adjust, menuw=None):
        """
        Move current item in the priority list and refresh menu to
        show new position
        """
        name = self.origname
        result = self.recordclient.adjustPriorityNow(name, adjust)
        if result:
            # if this is successfull
            if menuw:
                menuw.delete_submenu()
                menuw.refresh(reload=1)
            else:
                event.Event('MENU_RELOAD').post()
        else:
            # if all fails then we should show an error
            msgtext = _('Priority adjustment failed')+(':\n%s' % msg)
            dialog.show_message(msgtext)


    def priority_up(self, arg=None, menuw=None):
        self.priority_mod(-1, menuw)


    def priority_down(self, arg=None, menuw=None):
        self.priority_mod(1, menuw)
Beispiel #40
0
                if not self.standalone:
                    AlertBox(
                        text=_('%s stopped, a recording is about to start!') %
                        self.stopped,
                        height=200).show()
                self.stopped = None
        return 0


if __name__ == '__main__':
    # test code, run with freevo execute /path/to/upsoon.py
    config.DEBUG = 2
    function = None
    if len(sys.argv) > 1:
        function = sys.argv[1].lower()
        server = RecordClient()

    if function == 'run':
        #import rc as rctrl
        #rc = rctrl.get_singleton(False)
        pi = PluginInterface()
        kaa.main.run()

    elif function == 'findnextprogram':

        def handler(result):
            print 'findnextprogram=%r' % (result, )
            print result.__dict__
            raise SystemExit

        server.findNextProgram(handler)
Beispiel #41
0
 def __init__(self, parent):
     logger.log( 9, 'ViewFavoritesItem.__init__(parent=%r)', parent)
     Item.__init__(self, parent, skin_type='tv')
     self.name = _('View Favorites')
     self.menuw = None
     self.recordclient = RecordClient()