def __init__(self): try: fetcher = FileFetcher('guides.ini', ADDON) if fetcher.fetchFile() < 0: xbmcgui.Dialog().ok(strings(FETCH_ERROR_TITLE), strings(FETCH_ERROR_LINE1), strings(FETCH_ERROR_LINE2)) self.guideParser.read(self.filePath) guideTypes = [] defaultGuideId = 0 # fallback to the first guide in case no default is actually set in the ini file for section in self.guideParser.sections(): sectMap = self.SectionMap(section) id = int(sectMap['id']) fName = sectMap['file'] sortOrder = int(sectMap['sort_order']) default = False if 'default' in sectMap and sectMap['default'] == 'true': default = True defaultGuideId = id guideTypes.append((id, sortOrder, section, fName, default)) self.guideTypes = sorted(guideTypes, key=itemgetter(self.GUIDE_SORT)) xbmc.log('[script.clarkeyepg] GuideTypes collected: %s' % str(self.guideTypes), xbmc.LOGDEBUG) if str(ADDON.getSetting('xmltv.type')) == '': ADDON.setSetting('xmltv.type', str(defaultGuideId)) except: print 'unable to parse guides.ini'
def playScheduledProgram(self, startTime): debug('Notification playScheduledProgram') programToPlay = None element = self.getScheduledNotificationForThisTime(startTime) if element is None: return programList = element[2] self.timers.remove(element) if len(programList) == 1: program = programList[0] if self.epg.currentChannel is not None and program.channel.id == self.epg.currentChannel.id and xbmc.Player().isPlaying(): return ret = xbmcgui.Dialog().yesno(heading=strings(NOTIFICATION_POPUP_NAME).encode('utf-8', 'replace'), line1='%s %s?' % (strings(NOTIFICATION_POPUP_QUESTION).encode('utf-8', 'replace'), program.title.encode('utf-8', 'replace')), autoclose=60000) if ret == True: programToPlay = program else: programs = list() programs.append(strings(NOTIFICATION_CANCEL).encode('utf-8', 'replace')) for prog in programList: programs.append(prog.title.encode('utf-8', 'replace')) ret = xbmcgui.Dialog().select(strings(NOTIFICATION_POPUP_NAME).encode('utf-8', 'replace'), programs, autoclose=60000) if ret > 0: programToPlay = programList[ret-1] if programToPlay is not None: #xbmc.Player().stop() if ADDON.getSetting('info.osd') == "true": self.epg.playChannel2(programToPlay) else: self.epg.playChannel(programToPlay.channel, programToPlay)
def onInit(self): playControl = self.getControl(self.C_POPUP_PLAY) remindControl = self.getControl(self.C_POPUP_REMIND) channelLogoControl = self.getControl(self.C_POPUP_CHANNEL_LOGO) channelTitleControl = self.getControl(self.C_POPUP_CHANNEL_TITLE) programTitleControl = self.getControl(self.C_POPUP_PROGRAM_TITLE) playControl.setLabel(strings(WATCH_CHANNEL, self.program.channel.title)) if not self.program.channel.isPlayable(): playControl.setEnabled(False) self.setFocusId(self.C_POPUP_CHOOSE_STREAM) if self.database.getCustomStreamUrl(self.program.channel): chooseStrmControl = self.getControl(self.C_POPUP_CHOOSE_STREAM) chooseStrmControl.setLabel(strings(REMOVE_STRM_FILE)) if self.program.channel.logo is not None: channelLogoControl.setImage(self.program.channel.logo) channelTitleControl.setVisible(False) else: channelTitleControl.setLabel(self.program.channel.title) channelLogoControl.setVisible(False) programTitleControl.setLabel(self.program.title) if self.showRemind: remindControl.setLabel(strings(REMIND_PROGRAM)) else: remindControl.setLabel(strings(DONT_REMIND_PROGRAM))
def _scheduleNotification(self, channelTitle, programTitle, startTime): debug('Notification _scheduleNotification program: %s, startTime %s' % (programTitle.encode('utf-8'), startTime)) t = startTime - datetime.datetime.now() secToNotification = (t.days * 86400) + t.seconds timeToNotification = secToNotification / 60 if timeToNotification < 0: return name = self.createAlarmClockName(programTitle, startTime) description = strings(NOTIFICATION_5_MINS, channelTitle) xbmc.executebuiltin('CancelAlarm(%s-5mins,True)' % name.encode('utf-8', 'replace')) xbmc.executebuiltin('AlarmClock(%s-5mins,Notification(%s,%s,10000,%s),%d,True)' % (name.encode('utf-8', 'replace'), programTitle.encode('utf-8', 'replace'), description.encode('utf-8', 'replace'), self.icon, timeToNotification - 5)) description = strings(NOTIFICATION_NOW, channelTitle) xbmc.executebuiltin('CancelAlarm(%s-now,True)' % name.encode('utf-8', 'replace')) xbmc.executebuiltin('AlarmClock(%s-now,Notification(%s,%s,10000,%s),%d,True)' % (name.encode('utf-8', 'replace'), programTitle.encode('utf-8', 'replace'), description.encode('utf-8', 'replace'), self.icon, timeToNotification)) if ADDON.getSetting('notifications.enabled') == 'true' and timeToNotification > 0: for chann in self.channels: if chann.title == channelTitle: program = self.database.getProgramStartingAt(chann, startTime) element = self.getScheduledNotificationForThisTime(program.startDate) if element is not None: programList = element[2] #Fetch already scheduled list of programs programList.append(program) #And add one more else: programList = list() programList.append(program) timer = threading.Timer(secToNotification, self.playScheduledProgram, [startTime]) self.timers.append([program.startDate, timer, programList]) timer.start()
def LoadVideoLink(self, channel, service): deb('LoadVideoLink %s service' % service) res = False channels = None startWindowed = False if ADDON.getSetting('start_video_minimalized') == 'true': startWindowed = True channelInfo = self.getChannel(channel, service, self.currentlyPlayedService) if channelInfo is not None: if self.currentlyPlayedService != service: self.unlockService(self.currentlyPlayedService) self.currentlyPlayedService = service liz = xbmcgui.ListItem(channelInfo.title, iconImage = channelInfo.img, thumbnailImage = channelInfo.img) liz.setInfo( type="Video", infoLabels={ "Title": channelInfo.title, } ) try: if channelInfo.premium == 0: xbmcgui.Dialog().ok(strings(57034).encode('utf-8'), strings(57036).encode('utf-8') + '\n' + strings(57037).encode('utf-8') + '\n' + 'service: %s' % service.encode('utf-8')) self.player.play(channelInfo.strm, liz, windowed=startWindowed) res = True except Exception, ex: self.unlockService(self.currentlyPlayedService) self.currentlyPlayedService = None xbmcgui.Dialog().ok(strings(57018).encode('utf-8'), strings(57021).encode('utf-8') + '\n' + strings(57028).encode('utf-8') + '\n' + str(ex))
def _scheduleNotification(self, channelTitle, programTitle, startTime): t = startTime - datetime.datetime.now() timeToNotification = ((t.days * 86400) + t.seconds) / 60 if timeToNotification < 0: return name = self.createAlarmClockName(programTitle, startTime) description = strings(NOTIFICATION_5_MINS, channelTitle) xbmc.executebuiltin( "AlarmClock(%s-5mins,Notification(%s,%s,10000,%s),%d,True)" % ( name.encode("utf-8", "replace"), programTitle.encode("utf-8", "replace"), description.encode("utf-8", "replace"), self.icon, timeToNotification - 5, ) ) description = strings(NOTIFICATION_NOW, channelTitle) xbmc.executebuiltin( "AlarmClock(%s-now,Notification(%s,%s,10000,%s),%d,True)" % ( name.encode("utf-8", "replace"), programTitle.encode("utf-8", "replace"), description.encode("utf-8", "replace"), self.icon, timeToNotification, ) )
def __init__(self, defaultFilters): """ WhoPlayedRoleInTVShowQuestion """ super(WhoPlayedRoleInTVShowQuestion, self).__init__() show = library.getTVShows(['title', 'genre', 'cast', 'art']).withFilters(defaultFilters).limitTo(1).asItem() if not show or len(show['cast']) < 4: raise QuestionException('No tvshows found') otherActors = show['cast'] actor = otherActors.pop(random.randint(0, len(otherActors) - 1)) role = actor['role'] if re.search('[|/,]', role): roles = re.split('[|/,]', role) # find random role role = roles[random.randint(0, len(roles) - 1)] self.addCorrectAnswer(id=actor['name'], text=actor['name'], image=actor.get('thumbnail')) for otherActor in otherActors: self.addAnswer(id=otherActor['name'].encode('utf-8', 'ignore'), text=otherActor['name'], image=otherActor.get('thumbnail')) if len(self.answers) == 4: break random.shuffle(self.answers) if self._isAnimationGenre(show['genre']): self.text = strings(Q_WHO_VOICES_ROLE_IN_TVSHOW) % (role, show['title']) else: self.text = strings(Q_WHO_PLAYS_ROLE_IN_TVSHOW) % (role, show['title']) self.setFanartFile(show['art']['fanart'])
def __init__(self, database): """ WhoPlayedRoleInTVShowQuestion @type database: quizlib.db.Database @param database: Database connection instance to use """ photoDisplayType = PhotoDisplayType() super(WhoPlayedRoleInTVShowQuestion, self).__init__(photoDisplayType) rows = database.getTVShowActors(maxResults = 1, mustHaveRole = True) if not rows: raise QuestionException('No tvshow actors found') row = rows[0] role = row['strRole'] if re.search('[|/]', role): roles = re.split('[|/]', role) # find random role role = roles[random.randint(0, len(roles)-1)] self.addCorrectAnswer(row['idActor'], row['strActor'], path = thumb.getCachedActorThumb(row['strActor'])) actors = database.getTVShowActors(maxResults = 3, onlySelectActor = True, showId = row['idShow'], excludeActorId = row['idActor']) for actor in actors: self.addAnswer(actor['idActor'], actor['strActor'], path = thumb.getCachedActorThumb(actor['strActor'])) random.shuffle(self.answers) if self._isAnimationGenre(row['genre']): self.text = strings(Q_WHO_VOICES_ROLE_IN_TVSHOW) % (role, row['title']) else: self.text = strings(Q_WHO_PLAYS_ROLE_IN_TVSHOW) % (role, row['title']) photoDisplayType.setPhotoFile(thumb.getCachedTVShowThumb(row['strPath']))
def updateLocalFile(self, name, addon): path = os.path.join(XMLTVSource.PLUGIN_DATA, name) fetcher = FileFetcher(name, addon) retVal = fetcher.fetchFile() if retVal == fetcher.FETCH_OK and name <> XMLTVSource.INI_FILE: self.needReset = True elif retVal == fetcher.FETCH_ERROR: xbmcgui.Dialog().ok(strings(FETCH_ERROR_TITLE), strings(FETCH_ERROR_LINE1), strings(FETCH_ERROR_LINE2)) return path
def getControl(self, controlId): try: return super(EPG, self).getControl(controlId) except: if controlId in self.ignoreMissingControlIds: return None if not self.isClosing: xbmcgui.Dialog().ok("Control not found", strings(SKIN_ERROR_LINE1), strings(SKIN_ERROR_LINE2), strings(SKIN_ERROR_LINE3)) self.close() return None
def _initialize(self, cancel_requested_callback): sqlite3.register_adapter(datetime.datetime, self.adapt_datetime) sqlite3.register_converter('timestamp', self.convert_datetime) self.alreadyTriedUnlinking = False while True: if cancel_requested_callback is not None and cancel_requested_callback(): break try: self.conn = sqlite3.connect(self.databasePath, detect_types=sqlite3.PARSE_DECLTYPES) self.conn.execute('PRAGMA foreign_keys = ON') #self.conn.execute('PRAGMA synchronous = OFF') #self.conn.execute('PRAGMA journal_mode = OFF') #self.conn.execute("PRAGMA page_size = 16384"); #self.conn.execute("PRAGMA cache_size = 64000"); #self.conn.execute("PRAGMA temp_store = MEMORY"); #self.conn.execute("PRAGMA locking_mode = NORMAL"); #self.conn.execute("PRAGMA count_changes = OFF"); self.conn.row_factory = sqlite3.Row # create and drop dummy table to check if database is locked c = self.conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS database_lock_check(id TEXT PRIMARY KEY)') c.execute('DROP TABLE database_lock_check') c.close() self._createTables() self.settingsChanged = self._wasSettingsChanged(ADDON) break except sqlite3.OperationalError: if cancel_requested_callback is None: xbmc.log('[script.bmtvguide] Database is locked, bailing out...', xbmc.LOGDEBUG) break else: # ignore 'database is locked' xbmc.log('[script.bmtvguide] Database is locked, retrying...', xbmc.LOGDEBUG) except sqlite3.DatabaseError: self.conn = None if self.alreadyTriedUnlinking: xbmc.log('[script.bmtvguide] Database is broken and unlink() failed', xbmc.LOGDEBUG) break else: try: os.unlink(self.databasePath) except OSError: pass self.alreadyTriedUnlinking = True xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), strings(DATABASE_SCHEMA_ERROR_1), strings(DATABASE_SCHEMA_ERROR_2), strings(DATABASE_SCHEMA_ERROR_3)) return self.conn is not None
def onClick(self, controlId): if controlId == 9001 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_info = 1 self.getControl(7001).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8001).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9001).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9002 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_stop = 1 self.getControl(7002).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8002).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9002).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9003 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_pp = 1 self.getControl(7003).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8003).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9003).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9004 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_pm = 1 self.getControl(7004).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8004).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9004).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9005 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_home = 1 self.getControl(7005).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8005).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9005).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9006 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_ctxt = 1 self.getControl(7006).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8006).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9006).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9007 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.a_rec = 1 self.getControl(7007).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(8007).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) self.getControl(9007).setAnimations([('Conditional', 'effect=fade start=0 end=100 time=1000 condition=True pulse=True')]) if controlId == 9008 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: deb('Key settings reset!') ADDON.setSetting(id="info_key", value=str('')) ADDON.setSetting(id="stop_key", value=str('')) ADDON.setSetting(id="pp_key", value=str('')) ADDON.setSetting(id="pm_key", value=str('')) ADDON.setSetting(id="home_key", value=str('')) ADDON.setSetting(id="context_key", value=str('')) ADDON.setSetting(id="record_key", value=str('')) self.close() xbmcgui.Dialog().ok(strings(31013).encode('utf-8'),"\n" + strings(310014).encode('utf-8')) if controlId == 9099 and self.a_info == 0 and self.a_stop == 0 and self.a_pp == 0 and self.a_pm == 0 and self.a_home == 0 and self.a_ctxt == 0 and self.a_rec == 0: self.close()
def _setupHighscores(self): # Local highscore localHighscore = highscore.LocalHighscoreDatabase(xbmc.translatePath(ADDON.getAddonInfo('profile'))) newHighscoreId = localHighscore.addHighscore(self.game) name = localHighscore.getNickname(self.game.getUserId()) if newHighscoreId != -1: entries = localHighscore.getHighscoresNear(self.game, newHighscoreId) else: entries = localHighscore.getHighscores(self.game) localHighscore.close() subTypeText = None if isinstance(self.game, game.UnlimitedGame): subTypeText = strings(M_UNLIMITED) elif isinstance(self.game, game.QuestionLimitedGame): subTypeText = strings(M_X_QUESTIONS_LIMIT, self.game.getGameSubType()) elif isinstance(self.game, game.TimeLimitedGame): if int(self.game.getGameSubType()) == 1: subTypeText = strings(M_ONE_MINUT_LIMIT) else: subTypeText = strings(M_X_MINUTS_LIMIT, self.game.getGameSubType()) self.getControl(self.C_GAMEOVER_LOCAL_HIGHSCORE_TYPE).setLabel(subTypeText) listControl = self.getControl(self.C_GAMEOVER_LOCAL_HIGHSCORE_LIST) for entry in entries: item = xbmcgui.ListItem("%d. %s" % (entry['position'], entry['nickname'])) item.setProperty('score', str(entry['score'])) if int(entry['id']) == int(newHighscoreId): item.setProperty('highlight', 'true') listControl.addItem(item) # Global highscore globalHighscore = highscore.GlobalHighscoreDatabase(ADDON.getAddonInfo('version')) if ADDON.getSetting('submit.highscores') == 'true': newHighscoreId = globalHighscore.addHighscore(name, self.game) else: newHighscoreId = -1 if newHighscoreId != -1: entries = globalHighscore.getHighscoresNear(self.game, newHighscoreId) else: entries = globalHighscore.getHighscores(self.game) self.getControl(self.C_GAMEOVER_GLOBAL_HIGHSCORE_TYPE).setLabel(subTypeText) listControl = self.getControl(self.C_GAMEOVER_GLOBAL_HIGHSCORE_LIST) for entry in entries: item = xbmcgui.ListItem("%s. %s" % (entry['position'], entry['nickname'])) item.setProperty('score', str(entry['score'])) if int(entry['id']) == int(newHighscoreId): item.setProperty('highlight', 'true') listControl.addItem(item)
def _initialize(self, cancel_requested_callback): sqlite3.register_adapter(datetime.datetime, self.adapt_datetime) sqlite3.register_converter("timestamp", self.convert_datetime) self.alreadyTriedUnlinking = False while True: if cancel_requested_callback is not None and cancel_requested_callback(): break try: self.conn = sqlite3.connect(self.databasePath, detect_types=sqlite3.PARSE_DECLTYPES) self.conn.execute("PRAGMA foreign_keys = ON") self.conn.row_factory = sqlite3.Row # create and drop dummy table to check if database is locked c = self.conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS database_lock_check(id TEXT PRIMARY KEY)") c.execute("DROP TABLE database_lock_check") c.close() self._createTables() self.settingsChanged = self._wasSettingsChanged(ADDON) break except sqlite3.OperationalError: if cancel_requested_callback is None: xbmc.log("[script.pragma] Database is locked, bailing out...", xbmc.LOGDEBUG) break else: # ignore 'database is locked' xbmc.log("[script.pragma] Database is locked, retrying...", xbmc.LOGDEBUG) except sqlite3.DatabaseError: self.conn = None if self.alreadyTriedUnlinking: xbmc.log("[script.pragma] Database is broken and unlink() failed", xbmc.LOGDEBUG) break else: try: os.unlink(self.databasePath) except OSError: pass self.alreadyTriedUnlinking = True xbmcgui.Dialog().ok( ADDON.getAddonInfo("name"), strings(DATABASE_SCHEMA_ERROR_1), strings(DATABASE_SCHEMA_ERROR_2), strings(DATABASE_SCHEMA_ERROR_3), ) return self.conn is not None
def __init__(self, addon, cachePath): super(YouSeeTvSource, self).__init__(addon, cachePath) self.date = datetime.datetime.today() self.channelCategory = addon.getSetting('youseetv.category') self.ysApi = ysapi.YouSeeTVGuideApi() self.playbackUsingYouSeeWebTv = False try: if addon.getSetting('youseewebtv.playback') == 'true': xbmcaddon.Addon(id = 'plugin.video.yousee.tv') # raises Exception if addon is not installed self.playbackUsingYouSeeWebTv = True except Exception: ADDON.setSetting('youseewebtv.playback', 'false') xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), strings(YOUSEE_WEBTV_MISSING_1), strings(YOUSEE_WEBTV_MISSING_2), strings(YOUSEE_WEBTV_MISSING_3))
def __init__(self, database): """ WhatTVShowIsThisQuoteFrom @type database: quizlib.db.Database @param database: Database connection instance to use """ quoteDisplayType = QuoteDisplayType() super(WhatTVShowIsThisQuoteFrom, self).__init__(quoteDisplayType) rows = database.getTVShows(maxResults = 1) if not rows: raise QuestionException('No tvshows found') row = rows[0] quoteText = IMDB.getRandomQuote(row['title'], season = row['season'], episode = row['episode'], maxLength = 128) if quoteText is None: raise QuestionException('Did not find any quotes') self.addCorrectAnswer(row['idShow'], row['title'], row['idFile'], path = thumb.getCachedTVShowThumb(row['tvShowPath'])) # Fill with random episodes from other shows shows = database.getTVShows(maxResults = 3, excludeTVShowId = row['idShow'], onlySelectTVShow = True) for show in shows: self.addAnswer(show['idShow'], show['title'], path = thumb.getCachedTVShowThumb(show['tvShowPath'])) random.shuffle(self.answers) quoteDisplayType.setQuoteText(quoteText) self.text = strings(Q_WHAT_TVSHOW_IS_THIS_QUOTE_FROM)
def onFocus(self, controlId): try: controlInFocus = self.getControl(controlId) except Exception: return program = self._getProgramFromControl(controlInFocus) if program is None: return if program['description'] == None: self.setControlLabel(self.C_MAIN_TITLE, '[B]%s[/B]' % program['title']) else: self.setControlLabel(self.C_MAIN_TITLE, '[B]%s[/B] - [B]%s[/B]' % (program['title'], program['description'])) if program['start_date'] or program['end_date']: self.setControlLabel(self.C_MAIN_TIME,'[B]%s - %s[/B]' % (self.formatTime(program['start_date']), self.formatTime(program['end_date']))) else: self.setControlLabel(self.C_MAIN_TIME, '') description = self.db.getShowLongDescription(program['showID']) if description == '': description = strings(NO_DESCRIPTION) self.setControlText(self.C_MAIN_DESCRIPTION, description) self.setControlImage(self.C_MAIN_LOGO, program['channel_logo']) if program['image_small'] is not None: self.setControlImage(self.C_MAIN_IMAGE, program['image_small']) self.setControlImage(self.C_MAIN_BACKGROUND, program['image_small'])
def getDataFromExternal(self, date, progress_callback=None): channels = self.ysApi.channelsInCategory(self.channelCategory) for idx, channel in enumerate(channels): c = Channel(id=channel['id'], title=channel['name'], logo=channel['logo']) yield c for program in self.ysApi.programs(c.id, tvdate=date): description = program['description'] if description is None: description = strings(NO_DESCRIPTION) imagePrefix = program['imageprefix'] p = Program( c, program['title'], datetime.datetime.fromtimestamp(program['begin']), datetime.datetime.fromtimestamp(program['end']), description, imagePrefix + program['images_sixteenbynine']['large'], imagePrefix + program['images_sixteenbynine']['small'], ) yield p if progress_callback: if not progress_callback(100.0 / len(channels) * idx): raise SourceUpdateCanceledException()
def __init__(self, defaultFilters): """ WhatYearWasMovieReleasedQuestion """ super(WhatYearWasMovieReleasedQuestion, self).__init__() movie = library.getMovies(['title', 'year', 'art']).withFilters(defaultFilters).fromYear(1900).limitTo( 1).asItem() if not movie: raise QuestionException('No movies found') skew = random.randint(0, 10) minYear = int(movie['year']) - skew maxYear = int(movie['year']) + (10 - skew) thisYear = datetime.datetime.today().year if maxYear > thisYear: maxYear = thisYear minYear = thisYear - 10 years = list() years.append(int(movie['year'])) while len(years) < 4: year = random.randint(minYear, maxYear) if not year in years: years.append(year) list.sort(years) for year in years: self.addAnswer(id=movie['movieid'], text=str(year), correct=(year == int(movie['year']))) self.text = strings(Q_WHAT_YEAR_WAS_MOVIE_RELEASED, movie['title']) self.setFanartFile(movie['art']['fanart'])
def __init__(self, defaultFilters): """ WhatMovieHasTheLongestRuntimeQuestion """ super(WhatMovieHasTheLongestRuntimeQuestion, self).__init__() # Find a bunch of movies items = library.getMovies(['title', 'runtime', 'art']).withFilters(defaultFilters).limitTo(10).asList() movie = None otherMovies = list() for item in items: if movie is None or movie['runtime'] < item['runtime']: movie = item else: otherMovies.append(item) if not movie or len(otherMovies) < 3: raise QuestionException('Not enough movies found') self.addCorrectAnswer(id=movie['movieid'], text=movie['title'], image=movie['art']['poster']) for otherMovie in otherMovies: self.addAnswer(id=otherMovie['movieid'], text=otherMovie['title'], image=otherMovie['art']['poster']) if len(self.answers) == 4: break random.shuffle(self.answers) self.text = strings(Q_WHAT_MOVIE_HAS_THE_LONGEST_RUNTIME)
def __init__(self, defaultFilters): """ WhatTagLineBelongsToMovieQuestion """ super(WhatTagLineBelongsToMovieQuestion, self).__init__() movie = None items = library.getMovies(['title', 'tagline', 'art']).withFilters(defaultFilters).limitTo(10).asList() for item in items: if not item['tagline']: continue movie = item break if not movie: raise QuestionException('No movies found') self.addCorrectAnswer(id=movie['movieid'], text=movie['tagline']) otherMovies = library.getMovies(['tagline']).withFilters(defaultFilters).excludeTitles(movie['title']).limitTo( 10).asList() for otherMovie in otherMovies: if not otherMovie['tagline']: continue self.addAnswer(id=otherMovie['movieid'], text=otherMovie['tagline']) if len(self.answers) == 4: break random.shuffle(self.answers) self.text = strings(Q_WHAT_TAGLINE_BELONGS_TO_MOVIE, movie['title']) self.setFanartFile(movie['art']['fanart'])
def __init__(self, database): """ WhatEpisodeIsThisQuestion @type database: quizlib.db.Database @param database: Database connection instance to use """ videoDisplayType = VideoDisplayType() super(WhatEpisodeIsThisQuestion, self).__init__(videoDisplayType) rows = database.getTVShowEpisodes(maxResults = 1, minEpisodeCount = 3) if not rows: raise QuestionException('No tvshow episodes found') row = rows[0] answerText = self._get_episode_title(row['season'], row['episode'], row['episodeTitle']) id = "%s-%s-%s" % (row['idShow'], row['season'], row['episode']) cover = thumb.getCachedTVShowThumb(row['strPath']) self.addCorrectAnswer(id, answerText, row['idFile'], path = cover, sortWeight = row['episode']) # Fill with random episodes from this show episodes = database.getTVShowEpisodes(maxResults = 3, idShow = row['idShow'], season = row['season'], excludeEpisode = row['episode']) for episode in episodes: answerText = self._get_episode_title(episode['season'], episode['episode'], episode['episodeTitle']) id = "%s-%s-%s" % (row['idShow'], row['season'], episode['episode']) cover = thumb.getCachedTVShowThumb(row['strPath']) self.addAnswer(id, answerText, path = cover, sortWeight = episode['episode']) self.answers = sorted(self.answers, key=lambda answer: int(answer.sortWeight)) self.text = strings(Q_WHAT_EPISODE_IS_THIS) % row['title'] videoDisplayType.setVideoFile(row['strPath'], row['strFileName'])
def onInit(self): if self.initialized: # onInit(..) is invoked again by XBMC after a video addon exits after being invoked by XBMC.RunPlugin(..) xbmc.log("[script.tvguide.hellenic] TVGuide.onInit(..) invoked, but we're already initialized!") return self.initialized = True self._hideControl(self.C_MAIN_MOUSE_CONTROLS, self.C_MAIN_OSD) self._showControl(self.C_MAIN_EPG, self.C_MAIN_LOADING) self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(BACKGROUND_UPDATE_IN_PROGRESS)) self.setFocusId(self.C_MAIN_LOADING_CANCEL) control = self.getControl(self.C_MAIN_EPG_VIEW_MARKER) if control: left, top = control.getPosition() self.focusPoint.x = left self.focusPoint.y = top self.epgView.left = left self.epgView.top = top self.epgView.right = left + control.getWidth() self.epgView.bottom = top + control.getHeight() self.epgView.width = control.getWidth() self.epgView.cellHeight = control.getHeight() / CHANNELS_PER_PAGE try: self.database = src.Database() except src.SourceNotConfiguredException: self.onSourceNotConfigured() self.close() return self.database.initialize(self.onSourceInitialized, self.isSourceInitializationCancelled) self.updateTimebar()
def __init__(self, defaultFilters): """ WhatQuoteIsThisFrom """ quoteDisplayType = QuoteDisplayType() super(WhatMovieIsThisQuoteFrom, self).__init__(quoteDisplayType) quoteText = None row = None for item in library.getMovies(['title', 'art']).withFilters(defaultFilters).limitTo(10).asList(): quoteText = IMDB.getRandomQuote(item['title'], maxLength=128) if quoteText is not None: row = item break if quoteText is None: raise QuestionException('Did not find any quotes') self.addCorrectAnswer(row['movieid'], row['title'], image=row['art']['poster']) theRest = library.getMovies(['title', 'art']).withFilters(defaultFilters).excludeTitles( self.getAnswerTexts()).limitTo(3).asList() for movie in theRest: self.addAnswer(movie['movieid'], movie['title'], image=movie['art']['poster']) random.shuffle(self.answers) quoteDisplayType.setQuoteText(quoteText) self.text = strings(Q_WHAT_MOVIE_IS_THIS_QUOTE_FROM)
def onFocus(self, controlId): try: controlInFocus = self.getControl(controlId) except Exception: return program = self._getProgramFromControl(controlInFocus) if program is None: return self.setControlLabel(self.C_MAIN_TITLE, '[B]%s[/B]' % program.title) self.setControlLabel(self.C_MAIN_TIME, '[B]%s - %s[/B]' % (self.formatTime(program.startDate), self.formatTime(program.endDate))) if program.description: description = program.description else: description = strings(NO_DESCRIPTION) self.setControlText(self.C_MAIN_DESCRIPTION, description) if program.channel.logo is not None: self.setControlImage(self.C_MAIN_LOGO, program.channel.logo) if program.imageSmall is not None: self.setControlImage(self.C_MAIN_IMAGE, program.imageSmall) if ADDON.getSetting('program.background.enabled') == 'true' and program.imageLarge is not None: self.setControlImage(self.C_MAIN_BACKGROUND, program.imageLarge) if not self.osdEnabled and self.player.isPlaying(): self.player.stop()
def __init__(self, defaultFilters): """ WhatTVShowIsThisQuoteFrom """ quoteDisplayType = QuoteDisplayType() super(WhatTVShowIsThisQuoteFrom, self).__init__(quoteDisplayType) episode = library.getEpisodes(['showtitle', 'season', 'episode', 'art']).withFilters(defaultFilters).limitTo( 1).asItem() if not episode: raise QuestionException('No episodes found') quoteText = IMDB.getRandomQuote(episode['showtitle'], season=episode['season'], episode=episode['episode'], maxLength=128) if quoteText is None: raise QuestionException('Did not find any quotes') self.addCorrectAnswer(id=episode['showtitle'], text=episode['showtitle'], image=episode['art']['tvshow.poster']) otherShows = library.getTVShows(['title', 'art']).withFilters(defaultFilters).excludeTitles( [episode['showtitle']]).limitTo(3).asList() for otherShow in otherShows: self.addAnswer(id=otherShow['title'].encode('utf-8', 'ignore'), text=otherShow['title'], image=otherShow['art']['poster']) random.shuffle(self.answers) quoteDisplayType.setQuoteText(quoteText) self.text = strings(Q_WHAT_TVSHOW_IS_THIS_QUOTE_FROM)
def __init__(self, addon, cachePath): super(JSONSource, self).__init__(addon, cachePath) self.playbackUsingWeebTv = False self.JSONURL = addon.getSetting('json.url') if not addon.getSetting('json.url'): raise SourceNotConfiguredException() try: if addon.getSetting('weebtv.playback') == 'true': xbmcaddon.Addon(id = 'plugin.video.weeb.tv') # raises Exception if addon is not installed self.playbackUsingWeebTv = True except Exception: ADDON.setSetting('weebtv.playback', 'false') xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), strings(WEEBTV_WEBTV_MISSING_1), strings(WEEBTV_WEBTV_MISSING_2), strings(WEEBTV_WEBTV_MISSING_3))
def __init__(self, defaultFilters): audioDisplayType = AudioDisplayType() super(WhatTVShowIsThisThemeFromQuestion, self).__init__(audioDisplayType) items = library.getTVShows(['title', 'file', 'art']).withFilters(defaultFilters).limitTo(4).asList() show = None otherShows = list() for item in items: themeSong = os.path.join(item['file'], 'theme.mp3') if show is None and xbmcvfs.exists(themeSong): show = item else: otherShows.append(item) if show is None: raise QuestionException('Unable to find any tv shows with a theme.mp3 file') self.addCorrectAnswer(id=show['tvshowid'], text=show['title'], image=show['art']['poster']) # Fill with random episodes from other shows for otherShow in otherShows: self.addAnswer(id=otherShow['tvshowid'], text=otherShow['title'], image=otherShow['art']['poster']) random.shuffle(self.answers) audioDisplayType.setAudioFile(os.path.join(show['file'], 'theme.mp3')) self.text = strings(Q_WHAT_TVSHOW_IS_THIS_THEME_FROM)
def __init__(self, defaultFilters): """ WhatEpisodeIsThisQuestion """ videoDisplayType = VideoDisplayType() super(WhatEpisodeIsThisQuestion, self).__init__(videoDisplayType) show = library.getTVShows(['title', 'art']).withFilters(defaultFilters).limitTo(1).asItem() if not show: raise QuestionException('No tvshows found') season = library.getSeasons(show['tvshowid'], ['season', 'art']).limitTo(14).asItem() if not season: raise QuestionException('No seasons found') episodes = library.getEpisodes(['episode', 'title', 'file']).fromShow(show['title']).fromSeason( season['season']).limitTo(4).asList() correctIdx = random.randint(0, len(episodes) - 1) for idx, episode in enumerate(episodes): id = "%s-%s-%s" % (show['tvshowid'], season['season'], episode['episode']) self.addAnswer(id=id, text=episode['label'], image=season['art']['poster'], sortWeight=episode['episode'], correct=(idx == correctIdx)) self.answers = sorted(self.answers, key=lambda answer: int(answer.sortWeight)) self.text = strings(Q_WHAT_EPISODE_IS_THIS) % show['title'] videoDisplayType.setVideoFile(episodes[correctIdx]['file'])
def __init__(self, defaultFilters): """ WhatTVShowIsThisQuestion """ videoDisplayType = VideoDisplayType() super(WhatTVShowIsThisQuestion, self).__init__(videoDisplayType) show = library.getTVShows(['title', 'art']).withFilters(defaultFilters).limitTo(1).asItem() if not show: raise QuestionException('No tvshows found') self.addCorrectAnswer(id=show['tvshowid'], text=show['title'], image=show['art']['poster']) episode = library.getEpisodes(['file']).withFilters(defaultFilters).fromShow(show['title']).limitTo( 1).asItem() if not episode: raise QuestionException('TVshow has no episodes') otherShows = library.getTVShows(['title', 'art']).withFilters(defaultFilters).excludeTitles( [show['title']]).limitTo(3).asList() for otherShow in otherShows: self.addAnswer(id=otherShow['tvshowid'], text=otherShow['title'], image=otherShow['art']['poster']) random.shuffle(self.answers) self.text = strings(Q_WHAT_TVSHOW_IS_THIS) videoDisplayType.setVideoFile(episode['file'])
def __init__(self, defaultFilters): """ WhoPlayedRoleInMovieQuestion """ super(WhoPlayedRoleInMovieQuestion, self).__init__() movie = None items = library.getMovies(['title', 'cast', 'genre', 'art']).withFilters(defaultFilters).limitTo(10).asList() for item in items: if len(item['cast']) < 4: continue movie = item break if not movie: raise QuestionException('No applicable movie found') actor = random.choice(movie['cast']) role = actor['role'] if re.search('[|/,]', role): roles = re.split('[|/,]', role) # find random role role = roles[random.randint(0, len(roles) - 1)] self.addCorrectAnswer(actor['name'], actor['name'], image=actor['thumbnail']) for otherActor in movie['cast']: if otherActor['name'] == actor['name']: continue self.addAnswer(otherActor['name'].encode('utf-8', 'ignore'), otherActor['name'], image=otherActor['thumbnail']) if len(self.answers) == 4: break random.shuffle(self.answers) if self._isAnimationGenre(movie['genre']): self.text = strings(Q_WHO_VOICES_ROLE_IN_MOVIE) % (role, movie['title']) else: self.text = strings(Q_WHO_PLAYS_ROLE_IN_MOVIE) % (role, movie['title']) self.setFanartFile(movie['art']['fanart'])
def getControl(self, controlId): try: return super(EPG, self).getControl(controlId) except: if controlId in self.ignoreMissingControlIds: return None if not self.isClosing: xbmcgui.Dialog().ok("Control not found "+str(controlId), strings(SKIN_ERROR_LINE1), strings(SKIN_ERROR_LINE2), strings(SKIN_ERROR_LINE3)) self.close() return None
def __init__(self, addon, cachePath): super(JSONSource, self).__init__(addon, cachePath) self.playbackUsingWeebTv = False self.JSONURL = addon.getSetting('json.url') if not addon.getSetting('json.url'): raise SourceNotConfiguredException() try: if addon.getSetting('weebtv.playback') == 'true': xbmcaddon.Addon(id='plugin.video.weeb.tv' ) # raises Exception if addon is not installed self.playbackUsingWeebTv = True except Exception: ADDON.setSetting('weebtv.playback', 'false') xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), strings(WEEBTV_WEBTV_MISSING_1), strings(WEEBTV_WEBTV_MISSING_2), strings(WEEBTV_WEBTV_MISSING_3))
def __init__(self): self.database = src.Database() self.command = sys.argv[1] deb('ClearDB onInitialized param %s' % self.command) if self.command == 'deleteDbFile': self.database.deleteDbFile() self.database.close() xbmcgui.Dialog().ok(strings(DB_DELETED), 'OK') else: self.database.initialize(self.onInitialized)
def __init__(self, defaultFilters): """ What movie is this? """ videoDisplayType = VideoDisplayType() super(WhatMovieIsThisQuestion, self).__init__(videoDisplayType) correctAnswer = library.getMovies( ['title', 'set', 'genre', 'file', 'art']).withFilters(defaultFilters).limitTo(1).asItem() if not correctAnswer: raise QuestionException('No movies found') self.addCorrectAnswer(id=correctAnswer['movieid'], text=correctAnswer['title'], image=correctAnswer['art']['poster']) # Find other movies in set if correctAnswer['set'] is not None: otherMoviesInSet = library.getMovies( ['title', 'art']).withFilters(defaultFilters).inSet( correctAnswer['set']).excludeTitles( self.getAnswerTexts()).limitTo(3).asList() for movie in otherMoviesInSet: self.addAnswer(id=movie['movieid'], text=movie['title'], image=movie['art']['poster']) # Find other movies in genre if len(self.answers) < 4: otherMoviesInGenre = library.getMovies([ 'title', 'art' ]).withFilters(defaultFilters).inGenre( correctAnswer['genre']).excludeTitles( self.getAnswerTexts()).limitTo(4 - len(self.answers)).asList() for movie in otherMoviesInGenre: self.addAnswer(id=movie['movieid'], text=movie['title'], image=movie['art']['poster']) # Fill with random movies if len(self.answers) < 4: theRest = library.getMovies([ 'title', 'art' ]).withFilters(defaultFilters).excludeTitles( self.getAnswerTexts()).limitTo(4 - len(self.answers)).asList() for movie in theRest: self.addAnswer(id=movie['movieid'], text=movie['title'], image=movie['art']['poster']) random.shuffle(self.answers) self.text = strings(Q_WHAT_MOVIE_IS_THIS) videoDisplayType.setVideoFile(correctAnswer['file'])
def parseXMLTV(self, context, f, size, logoFolder, progress_callback): event, root = context.next() elements_parsed = 0 for event, elem in context: if event == "end": result = None if elem.tag == "programme": channel = elem.get("channel") description = elem.findtext("desc") iconElement = elem.find("icon") icon = None if iconElement is not None: icon = iconElement.get("src") if not description: description = strings(NO_DESCRIPTION) result = Program(channel, elem.findtext('title'), self.parseXMLTVDate(elem.get('start')), self.parseXMLTVDate(elem.get('stop')), description, imageSmall=icon) elif elem.tag == "channel": id = elem.get("id") title = elem.findtext("display-name") logo = None if logoFolder: logoFile = os.path.join(logoFolder, title + '.png') if (self.logoSource == XMLTVSource.LOGO_SOURCE_FTV): logo = logoFile.replace( ' ', '%20') # needed due to fetching from a server! elif xbmcvfs.exists(logoFile): logo = logoFile # local file instead of remote! streamElement = elem.find("stream") streamUrl = None if streamElement is not None: streamUrl = streamElement.text visible = elem.get("visible") if visible == "0": visible = False else: visible = True result = Channel(id, title, logo, streamUrl, visible) if result: elements_parsed += 1 if progress_callback and elements_parsed % 500 == 0: if not progress_callback(100.0 / size * f.tell()): raise SourceUpdateCanceledException() yield result root.clear() f.close()
def playScheduledProgram(self, startTime): debug('Notification playScheduledProgram') programToPlay = None element = self.getScheduledNotificationForThisTime(startTime) if element is None: return programList = element[2] self.timers.remove(element) if len(programList) == 1: program = programList[0] if self.epg.currentChannel is not None and program.channel.id == self.epg.currentChannel.id and xbmc.Player( ).isPlaying(): return ret = xbmcgui.Dialog().yesno( heading=strings(NOTIFICATION_POPUP_NAME).encode( 'utf-8', 'replace'), line1='%s %s?' % (strings(NOTIFICATION_POPUP_QUESTION).encode( 'utf-8', 'replace'), program.title.encode('utf-8', 'replace')), autoclose=60000) if ret == True: programToPlay = program else: programs = list() programs.append( strings(NOTIFICATION_CANCEL).encode('utf-8', 'replace')) for prog in programList: programs.append(prog.title.encode('utf-8', 'replace')) ret = xbmcgui.Dialog().select( strings(NOTIFICATION_POPUP_NAME).encode('utf-8', 'replace'), programs, autoclose=60000) if ret > 0: programToPlay = programList[ret - 1] if programToPlay is not None: #xbmc.Player().stop() if ADDON.getSetting('info.osd') == "true": self.epg.playChannel2(programToPlay) else: self.epg.playChannel(programToPlay.channel, programToPlay)
def __init__(self, defaultFilters): """ WhoPlayedRoleInTVShowQuestion """ super(WhoPlayedRoleInTVShowQuestion, self).__init__() show = library.getTVShows( ['title', 'genre', 'cast', 'art']).withFilters(defaultFilters).limitTo(1).asItem() if not show or len(show['cast']) < 4: raise QuestionException('No tvshows found') otherActors = show['cast'] actor = otherActors.pop(random.randint(0, len(otherActors) - 1)) role = actor['role'] if re.search('[|/,]', role): roles = re.split('[|/,]', role) # find random role role = roles[random.randint(0, len(roles) - 1)] self.addCorrectAnswer(id=actor['name'], text=actor['name'], image=actor.get('thumbnail')) for otherActor in otherActors: self.addAnswer(id=otherActor['name'].encode('utf-8', 'ignore'), text=otherActor['name'], image=otherActor.get('thumbnail')) if len(self.answers) == 4: break random.shuffle(self.answers) if self._isAnimationGenre(show['genre']): self.text = strings(Q_WHO_VOICES_ROLE_IN_TVSHOW) % (role, show['title']) else: self.text = strings(Q_WHO_PLAYS_ROLE_IN_TVSHOW) % (role, show['title']) self.setFanartFile(show['art']['fanart'])
def fixSkinIfNeeded(): Skin.removeSkinsIfKodiVersionChanged() Skin.removeSkinsIfAddonVersionChanged() Skin.createCustomDirIfNeeded() if Skin.getSkinPath() is None: deb('Skins fixing skin!') success = False deb('Missing skin: %s' % Skin.getSkinName()) skins = Skin.getSkinList() for skin in skins: #deb('Checking skin: %s, guideVersion: %s' % (skin.name, skin.minGuideVersion)) if skin.name == Skin.getSkinName(): deb('Skin found online skin which is missing: %s, starting download!' % skin.name) success = Skin.downloadSkin(skin) xbmcgui.Dialog().notification(strings(30710), strings(30709) + ": " + skin.name, time=7000, sound=False) if success == False: ADDON.setSetting(id="Skin", value=str('skin.default')) xbmcgui.Dialog().ok(strings(LOAD_ERROR_TITLE), strings(SKIN_ERROR_LINE1), strings(SKIN_ERROR_LINE4)) quit()
def onInit(self): self._hideControl(self.C_MAIN_MOUSE_CONTROLS, self.C_MAIN_OSD) self._showControl(self.C_MAIN_OSD, self.C_MAIN_LOADING) self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(BACKGROUND_UPDATE_IN_PROGRESS)) self.setFocusId(self.C_MAIN_LOADING_CANCEL) self.serial = SerialInitializer(self) self.serial.start() THREADS.append(self.serial) self._showControl(self.C_MAIN_MOUSE_CONTROLS)
def refreshControls(self): if not self.initialized: return if self.ctrlServiceName is not None: self.ctrlServiceName.setLabel( '%s' % self.playService.getCurrentServiceString()) if self.ctrlChanName is not None: self.ctrlChanName.setLabel('%s' % (self.program.channel.title)) if self.ctrlMainTitle is not None: self.ctrlMainTitle.setLabel('%s' % (self.program.title)) if self.ctrlProgramTime is not None: self.ctrlProgramTime.setLabel( '%s - %s' % (self.formatTime(self.program.startDate), self.formatTime(self.program.endDate))) if self.ctrlProgramDesc is not None: if self.program.description and self.ctrlProgramDesc: self.ctrlProgramDesc.setText(self.program.description) else: self.ctrlProgramDesc.setText(strings(NO_DESCRIPTION)) if self.program.channel.logo and self.ctrlProgramLogo: self.ctrlProgramLogo.setImage( self.program.channel.logo.encode('utf-8')) if self.program.imageSmall is not None and self.ctrlProgramImg: self.ctrlProgramImg.setImage( self.program.imageSmall.encode('utf-8')) else: if self.ctrlProgramImg is not None: self.ctrlProgramImg.setImage('tvguide-logo-epg.png') if self.program.imageLarge == 'live' and self.ctrlMainLive: self.ctrlMainLive.setImage('live.png') else: if self.ctrlMainLive is not None: self.ctrlMainLive.setImage('') if self.ctrlProgramProgress: self.stdat = time.mktime(self.program.startDate.timetuple()) self.endat = time.mktime(self.program.endDate.timetuple()) self.nodat = time.mktime(datetime.datetime.now().timetuple()) try: self.per = 100 - ((self.endat - self.nodat) / ((self.endat - self.stdat) / 100)) except: self.per = 0 if self.per > 0 and self.per < 100: self.ctrlProgramProgress.setVisible(True) self.ctrlProgramProgress.setPercent(self.per) else: self.ctrlProgramProgress.setVisible(False) self.setControlVisibility()
def importSettings(self): success = False filename = xbmcgui.Dialog().browseSingle( type=1, heading=strings(58007).encode('utf-8'), shares='files', mask='.zip') if filename is not None and filename != '': deb('SettingsImp importSettings file %s' % filename) if os.path.isdir(self.profilePath) == False: os.makedirs(self.profilePath) zf = zipfile.ZipFile(filename) for fileN in [dbFileName, settingsFileName]: try: zf.extract(fileN, self.profilePath) success = True except Exception, ex: deb('SettingsImp importSettings: Error got exception %s while reading archive %s' % (str(ex), filename)) if success == True: xbmcgui.Dialog().ok( strings(58003).encode('utf-8'), "\n" + strings(58008).encode('utf-8')) xbmc.executebuiltin('Addon.OpenSettings(%s)' % ADDON_ID) else: xbmcgui.Dialog().ok( strings(58003).encode('utf-8'), "\n" + strings(58009).encode('utf-8') + "\n" + strings(58010).encode('utf-8'))
def __init__(self): if os.path.isfile(LOGFILE): logContent = self.getLog(LOGFILE) elif os.path.isfile(LOGFILE2): logContent = self.getLog(LOGFILE2) elif os.path.isfile(LOGFILE3): logContent = self.getLog(LOGFILE3) else: xbmcgui.Dialog().ok(strings(30150), "\n" + "Unable to find kodi log file") return logUrl = self.upload(logContent) try: self.copy2clip(logUrl) except: deb('LogUploader ERROR not supported OS') if logUrl: xbmcgui.Dialog().ok( strings(69020), "\n" + strings(69033) + logUrl + strings(69055)) else: xbmcgui.Dialog().ok(strings(30150), "\n" + strings(69034))
def loginService(self): try: if self.dashjs == '': try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup html = sess.get( 'https://www.telia.se/privat/support/info/registrerade-enheter-telia-play', verify=False).text soup = BeautifulSoup(html, "html.parser") msg = soup.body.find('div', attrs={ 'class': 'stepbystep__wrapper' }).text msg = re.sub(' ', '[CR]', msg) msg = msg[75:] if sys.version_info[0] > 2: xbmcgui.Dialog().ok(strings(30904), str(msg)) else: xbmcgui.Dialog().ok(strings(30904), str(msg.encode('utf-8'))) self.createData() login = self.loginData() run = Threading() return login except: self.log('getChannelList exception: {}'.format( getExceptionString())) self.connErrorMessage() return False
def __init__(self): self.database = src.Database() self.command = sys.argv[1] deb('ClearDB onInitialized param {}'.format(self.command)) if self.command == 'deleteDbFile' or self.command == 'deleteAll' or self.command == 'deleteDb59908': self.database.deleteDbFile() self.database.close() #Delete skinsFix check if sys.version_info[0] > 2: try: self.profilePath = xbmcvfs.translatePath( ADDON.getAddonInfo('profile')) except: self.profilePath = xbmcvfs.translatePath( ADDON.getAddonInfo('profile')).decode('utf-8') else: try: self.profilePath = xbmc.translatePath( ADDON.getAddonInfo('profile')) except: self.profilePath = xbmc.translatePath( ADDON.getAddonInfo('profile')).decode('utf-8') if xbmcvfs.exists(os.path.join(self.profilePath, 'skin_fonts.ini')) == True: os.remove(os.path.join(self.profilePath, 'skin_fonts.ini')) with open(os.path.join(self.profilePath, 'skin_fonts.ini'), 'w+') as fp: fp.write('') fp.close() if self.command == 'deleteAll' or self.command == 'deleteDb59908': settingsFile = os.path.join(self.profilePath, 'settings.xml') os.remove(settingsFile) try: shutil.rmtree(self.profilePath) except: pass xbmcgui.Dialog().ok(strings(DB_DELETED), strings(30969)) else: self.database.initialize(self.onInitialized)
def __init__(self, defaultFilters): """ Actor not in movie? """ photoDisplayType = PhotoDisplayType() super(ActorNotInMovieQuestion, self).__init__(photoDisplayType) actors = list() for movie in library.getMovies( ['cast']).withFilters(defaultFilters).limitTo(10).asList(): for actor in movie['cast']: if 'thubmnail' in actor: actors.append(actor) if not actors: raise QuestionException("Didn't find any actors with thumbnail") random.shuffle(actors) actor = None for actor in actors: # Movie actor is in movies = library.getMovies( ['title', 'art']).withFilters(defaultFilters).withActor( actor['name']).limitTo(3).asList() if len(movies) < 3: continue for movie in movies: self.addAnswer(-1, movie['title'], image=movie['art']['poster']) # Movies actor is not in correctAnswer = library.getMovies( ['title', 'art']).withFilters(defaultFilters).withoutActor( actor['name']).limitTo(1).asItem() if not correctAnswer: raise QuestionException('No movies found') self.addCorrectAnswer(actor['name'], correctAnswer['title'], image=correctAnswer['art']['poster']) break if not self.answers: raise QuestionException( "Didn't find any actors with at least three movies") random.shuffle(self.answers) self.text = strings(Q_WHAT_MOVIE_IS_ACTOR_NOT_IN, actor['name']) photoDisplayType.setPhotoFile(actor['thumbnail'])
def _scheduleNotification(self, channelId, channelTitle, programTitle, startTime): t = startTime - datetime.datetime.now() timeToNotification = ((t.days * 86400) + t.seconds) / 60 if timeToNotification < 0: return name = self.createAlarmClockName(programTitle, startTime) description = strings(NOTIFICATION_5_MINS, channelTitle) xbmc.executebuiltin('AlarmClock(%s-5mins,Notification(%s,%s,10000,%s),%d,True)' % (name.encode('utf-8', 'replace'), programTitle.encode('utf-8', 'replace'), description.encode('utf-8', 'replace'), self.icon, timeToNotification - 5)) path = os.path.join(HOME, 'playPlanner.py') description = strings(NOTIFICATION_NOW, channelTitle) value = programTitle value += ',' + str(channelTitle) value += ',' + str(channelId) value += ',' + description.encode('utf-8', 'replace') xbmc.executebuiltin('AlarmClock(%s-now,RunScript(%s,%s),%d,True)' % (name.encode('utf-8', 'replace'), path.encode('utf-8', 'replace'), value.encode('utf-8', 'replace'), timeToNotification))
def __init__(self, defaultFilters): """ WhenWasTVShowFirstAiredQuestion """ super(WhenWasTVShowFirstAiredQuestion, self).__init__() show = library.getTVShows( ['title', 'art']).withFilters(defaultFilters).limitTo(1).asItem() if not show: raise QuestionException('No shows found') season = library.getSeasons(show['tvshowid'], ['season']).limitTo(1).asItem() if not season: raise QuestionException('No seasons found') episode = library.getEpisodes([ 'firstaired' ]).withFilters(defaultFilters).episode(1).fromShow( show['title']).fromSeason(season['season']).limitTo(1).asItem() if not episode: raise QuestionException('No episodes found') episodeYear = int(episode['firstaired'][0:4]) skew = random.randint(0, 10) minYear = episodeYear - skew maxYear = episodeYear + (10 - skew) thisYear = datetime.datetime.today().year if maxYear > thisYear: maxYear = thisYear minYear = thisYear - 10 years = list() years.append(episodeYear) while len(years) < 4: year = random.randint(minYear, maxYear) if not year in years: years.append(year) list.sort(years) for year in years: self.addAnswer(id="%s-%s" % (show['tvshowid'], season['season']), text=str(year), correct=(year == episodeYear)) self.text = strings(Q_WHEN_WAS_TVSHOW_FIRST_AIRED) % ( show['title'] + ' - ' + season['label']) self.setFanartFile(show['art']['fanart'])
def _scheduleNotification(self, channelTitle, programTitle, startTime): t = startTime - datetime.datetime.now() timeToNotification = ((t.days * 86400) + t.seconds) / 60 if timeToNotification < 0: return name = self.createAlarmClockName(programTitle, startTime) description = strings(NOTIFICATION_5_MINS, channelTitle) xbmc.executebuiltin( 'AlarmClock(%s-5mins,Notification(%s,%s,10000,%s),%d,True)' % (name.encode('utf-8', 'replace'), programTitle.encode('utf-8', 'replace'), description.encode('utf-8', 'replace'), self.icon, timeToNotification - 5)) description = strings(NOTIFICATION_NOW, channelTitle) xbmc.executebuiltin( 'AlarmClock(%s-now,Notification(%s,%s,10000,%s),%d,True)' % (name.encode( 'utf-8', 'replace'), programTitle.encode( 'utf-8', 'replace'), description.encode( 'utf-8', 'replace'), self.icon, timeToNotification))
def __init__(self, defaultFilters): """ WhatActorIsInMovieBesidesOtherActorQuestion """ super(WhatActorIsInMovieBesidesOtherActorQuestion, self).__init__() # Find a bunch of movies items = library.getMovies( ['title', 'cast', 'art']).withFilters(defaultFilters).limitTo(10).asList() movie = None for item in items: if len(item['cast']) >= 2: movie = item break if not movie: raise QuestionException('No movies with two actors found') actors = movie['cast'] random.shuffle(actors) actorOne = actors[0] actorTwo = actors[1] self.addCorrectAnswer(actorOne['name'], actorOne['name'], image=actorOne['thumbnail']) # Find another bunch of actors otherActors = list() items = library.getMovies( ['title', 'cast']).withFilters(defaultFilters).withoutActor( actorOne['name']).withoutActor( actorTwo['name']).limitTo(10).asList() for item in items: otherActors.extend(iter(item['cast'])) random.shuffle(otherActors) for otherActor in otherActors: if not 'thumbnail' in otherActor: continue self.addAnswer(otherActor['name'].encode('utf-8', 'ignore'), otherActor['name'], image=otherActor['thumbnail']) if len(self.answers) == 4: break random.shuffle(self.answers) self.text = strings(Q_WHAT_ACTOR_IS_IN_MOVIE_BESIDES_OTHER_ACTOR, (movie['title'], actorTwo['name'])) self.setFanartFile(movie['art']['fanart'])
def set_tv_provider_credentials(self): operator = ADDON.getSetting('cmore_operator') operators = self.get_operators() for i in operators: if operator == i['name']: username_type = i['username'] password_type = i['password'] info_message = re.sub('<[^<]+?>', '', i['login']) # strip html tags break self.dialog('ok', ADDON.getSetting('cmore_operator_title'), message=info_message) username = self.get_user_input(strings(59952) + ' (C More)') password = self.get_user_input(strings(59953) + ' (C More)', hidden=True) if username and password: self.set_setting('cmore_username', username) self.set_setting('cmore_password', password) return True else: return False
def LoadVideoLink(self, channel, service): #deb('LoadVideoLink %s service' % service) res = False channels = None startWindowed = False if ADDON.getSetting('start_video_minimalized') == 'true': startWindowed = True channelInfo = self.getChannel(channel, service, self.currentlyPlayedService) if channelInfo is not None: if self.currentlyPlayedService['service'] != service: self.unlockService(self.currentlyPlayedService['service']) self.currentlyPlayedService['service'] = service liz = xbmcgui.ListItem(channelInfo.title, iconImage=channelInfo.img, thumbnailImage=channelInfo.img) liz.setInfo(type="Video", infoLabels={ "Title": channelInfo.title, }) try: self.playbackStopped = False xbmc.Player().play(channelInfo.strm, liz, windowed=startWindowed) res = True except Exception, ex: deb('Exception while trying to play video: %s' % str(ex)) self.unlockService(self.currentlyPlayedService['service']) self.currentlyPlayedService['service'] = None xbmcgui.Dialog().ok( strings(57018).encode('utf-8'), strings(57021).encode('utf-8') + '\n' + strings(57028).encode('utf-8') + '\n' + str(ex))
def set_locale(self, locale=None): countries = ['sv_SE', 'da_DK', 'nb_NO'] if not locale: options = ['cmore.se', 'cmore.dk', 'cmore.no'] selected_locale = self.dialog('select', strings(30368), options=options) if selected_locale is None: selected_locale = 0 # default to .se self.set_setting('cmore_locale_title', options[selected_locale]) self.set_setting('cmore_locale', countries[selected_locale]) self.set_setting('cmore_login_token', '') # reset token when locale is changed return True
def parseXMLTV(context, f, size, logoFolder, progress_callback): event, root = context.next() elements_parsed = 0 for event, elem in context: if event == "end": result = None if elem.tag == "programme": channel = elem.get("channel") description = elem.findtext("desc") iconElement = elem.find("icon") icon = None if iconElement is not None: icon = iconElement.get("src") if not description: description = strings(NO_DESCRIPTION) result = Program(channel, elem.findtext('title'), parseXMLTVDate(elem.get('start')), parseXMLTVDate(elem.get('stop')), description, imageSmall=icon) elif elem.tag == "channel": id = elem.get("id") title = elem.findtext("display-name") logo = None if logoFolder: logoFile = os.path.join( logoFolder.encode('utf-8', 'ignore'), title.encode('utf-8', 'ignore') + '.png') if xbmcvfs.exists(logoFile): logo = logoFile if not logo: iconElement = elem.find("icon") if iconElement is not None: logo = iconElement.get("src") result = Channel(id, title, logo) if result: elements_parsed += 1 if progress_callback and elements_parsed % 500 == 0: if not progress_callback(100.0 / size * f.tell()): raise SourceUpdateCanceledException() yield result root.clear() f.close()
def get_operator(self, operator=None): if not operator: self.set_setting('cmore_tv_provider_login', 'true') operators = self.get_operators() options = [x['title'] for x in operators] selected_operator = self.dialog('select', strings(30370), options=options) if selected_operator is not None: operator = operators[selected_operator]['name'] operator_title = operators[selected_operator]['title'] self.set_setting('cmore_operator', operator) self.set_setting('cmore_operator_title', operator_title) return ADDON.getSetting('cmore_operator')
def __init__(self, defaultFilters): """ WhoDirectedThisMovieQuestion """ super(WhoDirectedThisMovieQuestion, self).__init__() movie = None items = library.getMovies( ['title', 'director', 'art']).withFilters(defaultFilters).limitTo(10).asList() for item in items: if not item['director']: continue movie = item break if not movie: raise QuestionException('No movies found') director = random.choice(movie['director']) self.addCorrectAnswer(id=movie['movieid'], text=director) otherMovies = library.getMovies( ['director']).withFilters(defaultFilters).excludeTitles( movie['title']).limitTo(10).asList() for otherMovie in otherMovies: if not otherMovie['director']: continue directorFound = False for otherDirector in otherMovie['director']: if otherDirector in self.getAnswerTexts(): directorFound = True break if directorFound: continue self.addAnswer(id=otherMovie['movieid'], text=random.choice(otherMovie['director'])) if len(self.answers) == 4: break random.shuffle(self.answers) self.text = strings(Q_WHO_DIRECTED_THIS_MOVIE, movie['title']) self.setFanartFile(movie['art']['fanart'])
def __init__(self, defaultFilters): """ WhatStudioReleasedMovieQuestion """ super(WhatStudioReleasedMovieQuestion, self).__init__() movie = None items = library.getMovies( ['title', 'studio', 'art']).withFilters(defaultFilters).limitTo(10).asList() for item in items: if not item['studio']: continue movie = item break if not movie: raise QuestionException('No movies found') studio = random.choice(movie['studio']) self.addCorrectAnswer(id=movie['movieid'], text=studio) otherMovies = library.getMovies( ['studio']).withFilters(defaultFilters).excludeTitles( movie['title']).limitTo(10).asList() for otherMovie in otherMovies: if not otherMovie['studio']: continue studioFound = False for otherStudio in otherMovie['studio']: if otherStudio in self.getAnswerTexts(): studioFound = True break if studioFound: continue self.addAnswer(id=otherMovie['movieid'], text=random.choice(otherMovie['studio'])) if len(self.answers) == 4: break random.shuffle(self.answers) self.text = strings(Q_WHAT_STUDIO_RELEASED_MOVIE, movie['title']) self.setFanartFile(movie['art']['fanart'])
def getDataFromExternal(self, date, progress_callback=None): channels = self.sapoMeoApi.getChannelList() entries = dict() streamsService = streaming.StreamsService() for channel in channels: if not channel['Sigla'].startswith( 'M ' ): entries[channel['Sigla']]=channel for idx, channelKey in enumerate(sorted(entries.keys())): channel = entries[channelKey] c = Channel(id=channel['Sigla'], title=channel['Name'], logo=None) if self.filterTVportuguesa: matches = streamsService.detectStream(c) if matches == None or len(matches)==0: c.visible=False print c.title.encode('utf-8') yield c if c.visible: try: for program in self.sapoMeoApi.getChannelByDateInterval(c.id, date): description = program['Description'] if description is None: description = strings(NO_DESCRIPTION) p = Program( c, program['Title'], self.convertDate(program['StartTime']), self.convertDate(program['EndTime']), description ) print " "+p.title.encode('utf-8') yield p except Exception, ex: xbmc.log('[script.tvguide] Uncaugt exception in source.py: %s' % str(ex) , xbmc.LOGDEBUG) if progress_callback: if not progress_callback(100.0 / len(channels) * idx): raise SourceUpdateCanceledException()
def __init__(self, defaultFilters): """ WhatMovieIsNotDirectedByQuestion """ super(WhatMovieIsNotDirectedByQuestion, self).__init__() # Find a bunch of directors directors = list() items = library.getMovies( ['title', 'director']).withFilters(defaultFilters).limitTo(10).asList() for item in items: directors.extend(iter(item['director'])) # Find one that has at least three movies movies = None director = None for director in directors: # if not director['thumbnail']: # continue movies = library.getMovies(['title', 'art']).withFilters( defaultFilters).directedBy(director).limitTo(3).asList() if len(movies) >= 3: break if len(movies) < 3: raise QuestionException( "Didn't find a director with at least three movies") # Find movie not directed by director otherMovie = library.getMovies(['title', 'art']).withFilters( defaultFilters).notDirectedBy(director).limitTo(1).asItem() if not otherMovie: raise QuestionException('No movie found') self.addCorrectAnswer(director, otherMovie['title'], image=otherMovie['art']['poster']) for movie in movies: self.addAnswer(-1, movie['title'], image=movie['art']['poster']) random.shuffle(self.answers) self.text = strings(Q_WHAT_MOVIE_IS_NOT_DIRECTED_BY, director)
def refreshControls(self): if self.ctrlMainTitle is not None: self.ctrlMainTitle.setLabel('[B]%s[/B]' % (self.gu.program.title)) if self.ctrlProgramTime is not None: self.ctrlProgramTime.setLabel( '[B]%s - %s[/B]' % (self.formatTime(self.gu.program.startDate), self.formatTime(self.gu.program.endDate))) if self.ctrlProgramDesc is not None: if self.gu.program.description and self.ctrlProgramDesc: self.ctrlProgramDesc.setText(self.gu.program.description) else: self.ctrlProgramDesc.setText(strings(NO_DESCRIPTION)) if self.gu.program.channel.logo and self.ctrlProgramLogo: self.ctrlProgramLogo.setImage( self.gu.program.channel.logo.encode('utf-8')) if self.gu.program.imageSmall is not None and self.ctrlProgramImg: self.ctrlProgramImg.setImage( self.gu.program.imageSmall.encode('utf-8')) else: if self.ctrlProgramImg is not None: self.ctrlProgramImg.setImage('tvguide-logo-epg.png') if self.gu.program.imageLarge == 'live' and self.ctrlMainLive: self.ctrlMainLive.setImage('live.png') else: if self.ctrlMainLive is not None: self.ctrlMainLive.setImage('') if self.ctrlProgramProgress: self.stdat = time.mktime(self.gu.program.startDate.timetuple()) self.endat = time.mktime(self.gu.program.endDate.timetuple()) self.nodat = time.mktime(datetime.datetime.now().timetuple()) self.per = 100 - ((self.endat - self.nodat) / ((self.endat - self.stdat) / 100)) if self.per > 0 and self.per < 100: self.ctrlProgramProgress.setVisible(True) self.ctrlProgramProgress.setPercent(self.per) else: self.ctrlProgramProgress.setVisible(False)