def playFile(play_info, monitor): id = play_info.get("item_id") # if this is a list of items them add them all to the play list if isinstance(id, list): return playListOfItems(id, monitor) auto_resume = play_info.get("auto_resume", "-1") force_transcode = play_info.get("force_transcode", False) media_source_id = play_info.get("media_source_id", "") use_default = play_info.get("use_default", False) log.debug("playFile id({0}) resume({1}) force_transcode({2})", id, auto_resume, force_transcode) settings = xbmcaddon.Addon() addon_path = settings.getAddonInfo('path') force_auto_resume = settings.getSetting('forceAutoResume') == 'true' jump_back_amount = int(settings.getSetting("jump_back_amount")) server = download_utils.getServer() url = "{server}/emby/Users/{userid}/Items/" + id + "?format=json" data_manager = DataManager() result = data_manager.GetContent(url) log.debug("Playfile item: {0}", result) if result is None: log.debug("Playfile item was None, so can not play!") return # if this is a season, tv show or album then play all items in that parent if result.get("Type") == "Season" or result.get("Type") == "MusicAlbum": log.debug("PlayAllFiles for parent item id: {0}", id) url = ('{server}/emby/Users/{userid}/items' + '?ParentId=' + id + '&Fields=MediaSources' + '&format=json') result = data_manager.GetContent(url) log.debug("PlayAllFiles items: {0}", result) # process each item items = result["Items"] if items is None: items = [] return playAllFiles(items, monitor) # select the media source to use media_sources = result.get('MediaSources') selected_media_source = None if media_sources is None or len(media_sources) == 0: log.debug("Play Failed! There is no MediaSources data!") return elif len(media_sources) == 1: selected_media_source = media_sources[0] elif media_source_id != "": for source in media_sources: if source.get("Id", "na") == media_source_id: selected_media_source = source break elif len(media_sources) > 1: sourceNames = [] for source in media_sources: sourceNames.append(source.get("Name", "na")) dialog = xbmcgui.Dialog() resp = dialog.select(i18n('select_source'), sourceNames) if resp > -1: selected_media_source = media_sources[resp] else: log.debug("Play Aborted, user did not select a MediaSource") return if selected_media_source is None: log.debug("Play Aborted, MediaSource was None") return seekTime = 0 auto_resume = int(auto_resume) # process user data for resume points if auto_resume != -1: seekTime = (auto_resume / 1000) / 10000 elif force_auto_resume: userData = result.get("UserData") reasonableTicks = int(userData.get("PlaybackPositionTicks")) / 1000 seekTime = reasonableTicks / 10000 else: userData = result.get("UserData") if userData.get("PlaybackPositionTicks") != 0: reasonableTicks = int(userData.get("PlaybackPositionTicks")) / 1000 seekTime = reasonableTicks / 10000 displayTime = str(timedelta(seconds=seekTime)) resumeDialog = ResumeDialog("ResumeDialog.xml", addon_path, "default", "720p") resumeDialog.setResumeTime("Resume from " + displayTime) resumeDialog.doModal() resume_result = resumeDialog.getResumeAction() del resumeDialog log.debug("Resume Dialog Result: {0}", resume_result) # check system settings for play action # if prompt is set ask to set it to auto resume params = {"setting": "myvideos.selectaction"} setting_result = json_rpc('Settings.getSettingValue').execute(params) log.debug("Current Setting (myvideos.selectaction): {0}", setting_result) current_value = setting_result.get("result", None) if current_value is not None: current_value = current_value.get("value", -1) if current_value not in (2,3): return_value = xbmcgui.Dialog().yesno(i18n('extra_prompt'), i18n('turn_on_auto_resume?')) if return_value: params = {"setting": "myvideos.selectaction", "value": 2} json_rpc_result = json_rpc('Settings.setSettingValue').execute(params) log.debug("Save Setting (myvideos.selectaction): {0}", json_rpc_result) if resume_result == 1: seekTime = 0 elif resume_result == -1: return listitem_props = [] playback_type = "0" playurl = None play_session_id = id_generator() log.debug("play_session_id: {0}", play_session_id) # check if strm file, path will contain contain strm contents if selected_media_source.get('Container') == 'strm': playurl, listitem_props = PlayUtils().getStrmDetails(selected_media_source) if playurl is None: return if not playurl: playurl, playback_type = PlayUtils().getPlayUrl(id, selected_media_source, force_transcode, play_session_id) log.debug("Play URL: {0} ListItem Properties: {1}", playurl, listitem_props) playback_type_string = "DirectPlay" if playback_type == "2": playback_type_string = "Transcode" elif playback_type == "1": playback_type_string = "DirectStream" # add the playback type into the overview if result.get("Overview", None) is not None: result["Overview"] = playback_type_string + "\n" + result.get("Overview") else: result["Overview"] = playback_type_string # add title decoration is needed item_title = result.get("Name", i18n('missing_title')) list_item = xbmcgui.ListItem(label=item_title) if playback_type == "2": # if transcoding then prompt for audio and subtitle playurl = audioSubsPref(playurl, list_item, selected_media_source, id, use_default) log.debug("New playurl for transcoding: {0}", playurl) elif playback_type == "1": # for direct stream add any streamable subtitles externalSubs(selected_media_source, list_item, id) # add playurl and data to the monitor data = {} data["item_id"] = id data["playback_type"] = playback_type_string data["play_session_id"] = play_session_id data["play_action_type"] = "play" monitor.played_information[playurl] = data log.debug("Add to played_information: {0}", monitor.played_information) list_item.setPath(playurl) list_item = setListItemProps(id, list_item, result, server, listitem_props, item_title) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(playurl, list_item) xbmc.Player().play(playlist) send_next_episode_details(result) if seekTime == 0: return count = 0 while not xbmc.Player().isPlaying(): log.debug("Not playing yet...sleep for 1 sec") count = count + 1 if count >= 10: return else: xbmc.Monitor().waitForAbort(1) seekTime = seekTime - jump_back_amount target_seek = (seekTime - 5) current_position = 0 while current_position < target_seek: # xbmc.Player().pause() xbmc.sleep(100) xbmc.Player().seekTime(seekTime) xbmc.sleep(100) # xbmc.Player().play() current_position = xbmc.Player().getTime() log.debug("Playback_Start_Seek target:{0} current:{1}", target_seek, current_position)
def parse_tvshows_recommended(request, list_type, full_liz, usecache, plot_enable, limit, date_liz=None, date_type=None, favourites=False): prefix = "recommended-episodes" if not favourites else "favouriteepisodes" json_query = _get_data(request, usecache) while json_query == "LOADING": xbmc.sleep(100) json_query = _get_data(request, usecache) if json_query: # First unplayed episode of recent played tvshows json_query = simplejson.loads(json_query) if "result" in json_query and 'tvshows' in json_query['result']: count = 0 for tvshow in json_query['result']['tvshows']: if xbmc.Monitor().abortRequested(): break json_query2 = xbmcgui.Window(10000).getProperty( prefix + "-data-" + str(tvshow['tvshowid'])) if json_query2: json_query2 = simplejson.loads(json_query2) if "result" in json_query2 and json_query2[ 'result'] is not None and 'episodes' in json_query2[ 'result']: for episode in json_query2['result']['episodes']: nEpisode = "%.2d" % float(episode['episode']) nSeason = "%.2d" % float(episode['season']) fEpisode = "s%se%s" % (nSeason, nEpisode) break if "cast" in episode: cast = _get_cast(episode['cast']) liz = xbmcgui.ListItem(episode['title']) liz.setInfo( type="Video", infoLabels={ "Title": episode['title'], "Episode": episode['episode'], "Season": episode['season'], "Studio": _get_first_item(tvshow.get('studio', "")), "Premiered": episode['firstaired'], "Plot": _get_plot(episode['plot'], plot_enable, episode['playcount']), "TVshowTitle": episode['showtitle'], "Rating": str(float(episode['rating'])), "MPAA": tvshow['mpaa'], "Playcount": episode['playcount'], "Director": _get_joined_items(episode.get('director', "")), "Writer": _get_joined_items(episode.get('writer', "")), "Cast": cast[0], "CastAndRole": cast[1], "mediatype": "episode" }) liz.setProperty("episodeno", fEpisode) liz.setProperty("resumetime", str(episode['resume']['position'])) liz.setProperty("totaltime", str(episode['resume']['total'])) liz.setProperty("type", ADDON_LANGUAGE(list_type)) liz.setProperty( "fanart_image", episode['art'].get('tvshow.fanart', '')) liz.setProperty("dbid", str(episode['episodeid'])) liz.setArt(episode['art']) liz.setArt({ 'icon': 'DefaultTVShows.png', 'thumb': episode['art'].get('thumb', '') }) hasVideo = False for key, value in list( episode['streamdetails'].items()): for stream in value: if 'video' in key: hasVideo = True liz.addStreamInfo(key, stream) # if duration wasnt in the streaminfo try adding the scraped one if not hasVideo: stream = {'duration': episode['runtime']} liz.addStreamInfo("video", stream) full_liz.append((episode['file'], liz, False)) if date_type is not None: date_liz.append(tvshow[date_type]) count += 1 if count == limit: break if count == limit: break del json_query
def __init__(self): xbmc.Monitor.__init__(self, xbmc.Monitor()) self.searchSub = REAL_SETTINGS.getSetting('searchSub') == "true" self.enableCC = REAL_SETTINGS.getSetting('enableCC') == "true"
def do_download(mediaurl, download_path, file_name, headers=[], silent=False, resume=True): # Crear carpeta de destino si no existe if not filetools.exists(download_path): filetools.mkdir(download_path) # Limpiar caracteres para nombre de fichero válido file_name = config.text_clean(file_name) # Lanzamos la descarga d = Downloader(mediaurl, download_path, file_name, headers=headers, resume=resume, max_connections=1 + int(config.get_setting("max_connections")), block_size=2**(17 + int(config.get_setting("block_size"))), part_size=2**(20 + int(config.get_setting("part_size"))), max_buffer=2 * int(config.get_setting("max_buffer"))) if silent: d.start() # bucle hasta terminar import xbmc while not xbmc.Monitor().abortRequested() and d.state not in [ d.states.error, d.states.stopped, d.states.completed ]: xbmc.sleep(100) else: d.start_dialog() # Descarga detenida, verificar estado: {"stopped": 0, "connecting": 1, "downloading": 2, "completed": 3, "error": 4, "saving": 5}) if d.state == d.states.error: logger.info('Error en la descarga %s' % mediaurl) status = STATUS_CODES.error elif d.state == d.states.stopped: logger.info("Descarga detenida") status = STATUS_CODES.canceled elif d.state == d.states.completed: logger.info("Descargada finalizada") status = STATUS_CODES.completed else: logger.error("Estado de descarga no previsto! %d" % d.state) status = STATUS_CODES.stopped params = { 'downloadStatus': status, # 3:error / 1:canceled / 2:completed 'downloadSize': d.size[0], # total bytes de la descarga 'downloadCompleted': d.downloaded[0], # bytes descargados 'downloadProgress': d.progress, # porcentaje descargado (float) 'downloadUrl': d.download_url, # url origen 'downloadFilename': d.filename # nombre del fichero (sin path) } return params
import xbmc, xbmcaddon, xbmcvfs, xbmcgui from bs4 import BeautifulSoup # Plugin Info ADDON_ID = 'screensaver.google.earth' REAL_SETTINGS = xbmcaddon.Addon(id=ADDON_ID) ADDON_NAME = REAL_SETTINGS.getAddonInfo('name') ADDON_PATH = (REAL_SETTINGS.getAddonInfo('path').decode('utf-8')) ADDON_VERSION = REAL_SETTINGS.getAddonInfo('version') SETTINGS_LOC = REAL_SETTINGS.getAddonInfo('profile').decode('utf-8') ICON = REAL_SETTINGS.getAddonInfo('icon').decode('utf-8') LANGUAGE = REAL_SETTINGS.getLocalizedString # Global Info KODI_MONITOR = xbmc.Monitor() JSON_FILE = xbmc.translatePath(os.path.join(SETTINGS_LOC,'earthview.json')) class Update(): def __init__(self): self.results = [] def log(self, msg, level=xbmc.LOGDEBUG): xbmc.log(ADDON_ID + '-' + ADDON_VERSION + '-' + msg, level) def notificationDialog(self, message, header=ADDON_NAME, sound=False, time=1000, icon=ICON): try: xbmcgui.Dialog().notification(header, message, icon, time, sound=False) except Exception,e:
wait = update_wait[int(config.get_setting("update_wait", "videolibrary"))] if wait > 0: xbmc.sleep(wait) # Verificar quick-fixes al abrirse Kodi, y dejarlo corriendo como Thread from platformcode import updater updater.check_addon_init() # Copia Custom code a las carpetas de Alfa desde la zona de Userdata from platformcode import custom_code custom_code.init() if not config.get_setting("update", "videolibrary") == 2: check_for_update(overwrite=False) # Se ejecuta ciclicamente if config.get_platform(True)['num_version'] >= 14: monitor = xbmc.Monitor() # For Kodi >= 14 else: monitor = None # For Kodi < 14 if monitor: while not monitor.abortRequested(): monitor_update() if monitor.waitForAbort(3600): # cada hora break else: while not xbmc.abortRequested: monitor_update() xbmc.sleep(3600)
def do_next_check(iTimeToWait): if debug == 'true': _log("DEBUG: next check in " + str(iTimeToWait) + " min") if xbmc.Monitor().waitForAbort(int(iTimeToWait) * 60): exit()
def play_from_library(item): """ Los .strm al reproducirlos desde kodi, este espera que sea un archivo "reproducible" asi que no puede contener más items, como mucho se puede colocar un dialogo de seleccion. Esto lo solucionamos "engañando a kodi" y haciendole creer que se ha reproducido algo, asi despues mediante "Container.Update()" cargamos el strm como si un item desde dentro del addon se tratara, quitando todas las limitaciones y permitiendo reproducir mediante la funcion general sin tener que crear nuevos métodos para la videoteca. @type item: item @param item: elemento con información """ logger.info() #logger.debug("item: \n" + item.tostring('\n')) import xbmcgui import xbmcplugin import xbmc from time import sleep # Intentamos reproducir una imagen (esto no hace nada y ademas no da error) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem( path=os.path.join(config.get_runtime_path(), "resources", "subtitle.mp4"))) # Por si acaso la imagen hiciera (en futuras versiones) le damos a stop para detener la reproduccion sleep(0.5) ### Si no se pone esto se bloquea Kodi xbmc.Player().stop() # modificamos el action (actualmente la videoteca necesita "findvideos" ya que es donde se buscan las fuentes item.action = "findvideos" window_type = config.get_setting("window_type", "videolibrary") # y volvemos a lanzar kodi if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1: # Ventana convencional xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")") else: # Ventana emergente from channels import videolibrary p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(70004)) p_dialog.update(0, '') itemlist = videolibrary.findvideos(item) while platformtools.is_playing(): # Ventana convencional sleep(5) p_dialog.update(50, '') '''# Se filtran los enlaces segun la lista negra if config.get_setting('filter_servers', "servers"): itemlist = servertools.filter_servers(itemlist)''' # Se limita la cantidad de enlaces a mostrar if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) # Se "limpia" ligeramente la lista de enlaces if config.get_setting("replace_VD", "videolibrary") == 1: itemlist = reorder_itemlist(itemlist) import time p_dialog.update(100, '') time.sleep(0.5) p_dialog.close() if len(itemlist) > 0: while not xbmc.Monitor().abortRequested(): # El usuario elige el mirror opciones = [] for item in itemlist: opciones.append(item.title) # Se abre la ventana de seleccion if (item.contentSerieName != "" and item.contentSeason != "" and item.contentEpisodeNumber != ""): cabecera = ("%s - %sx%s -- %s" % (item.contentSerieName, item.contentSeason, item.contentEpisodeNumber, config.get_localized_string(30163))) else: cabecera = config.get_localized_string(30163) seleccion = platformtools.dialog_select(cabecera, opciones) if seleccion == -1: return else: item = videolibrary.play(itemlist[seleccion])[0] platformtools.play_video(item) from channels import autoplay if (platformtools.is_playing() and item.action) or item.server == 'torrent' or autoplay.is_active(item.contentChannel): break
def __init__(self): utils.logMsg('started loading script entry') params = self.getParams() if params: action = params.get("ACTION", "").upper() if action == "ADDSHORTCUT": mainmodule.addShortcutWorkAround() elif action == "MUSICSEARCH": mainmodule.musicSearch() elif action == "SETVIEW": mainmodule.setView() elif action == "SEARCHYOUTUBE": title = params.get("TITLE", None) windowHeader = params.get("HEADER", "") autoplay = params.get("AUTOPLAY", "") windowed = params.get("WINDOWED", "") mainmodule.searchYouTube(title, windowHeader, autoplay, windowed) elif action == "SETFOCUS": control = params.get("CONTROL", None) fallback = params.get("FALLBACK", None) count = 0 while not xbmc.getCondVisibility( "Control.HasFocus(%s)" % control): if count == 20 or (fallback and xbmc.getCondVisibility( "Control.IsVisible(%s) + !IntegerGreaterThan(Container(%s).NumItems,0)" % (control, control))): if fallback: xbmc.executebuiltin("Control.SetFocus(%s)" % fallback) break else: xbmc.executebuiltin("Control.SetFocus(%s)" % control) xbmc.sleep(50) count += 1 elif action == "SETFORCEDVIEW": contenttype = params.get("CONTENTTYPE", None) mainmodule.setForcedView(contenttype) elif action == "SAVESKINIMAGE": skinstring = params.get("SKINSTRING", "") windowHeader = params.get("HEADER", "") multi = params.get("MULTI", "") == "true" mainmodule.saveSkinImage(skinstring, multi, windowHeader) elif action == "SETSKINSETTING": setting = params.get("SETTING", "") windowHeader = params.get("HEADER", "") originalId = params.get("ID", "") mainmodule.setSkinSetting(setting=setting, windowHeader=windowHeader, originalId=originalId) elif action == "SETSKINCONSTANT": setting = params.get("SETTING", "") windowHeader = params.get("HEADER", "") value = params.get("VALUE", "") mainmodule.setSkinConstant(setting, windowHeader, value) elif action == "SETSKINCONSTANTS": settings = params.get("SETTINGS", "").split("|") values = params.get("VALUES", "").split("|") mainmodule.setSkinConstant(settings, values) elif action == "SETSKINSHORTCUTSPROPERTY": setting = params.get("SETTING", "") windowHeader = params.get("HEADER", "") property = params.get("PROPERTY", "") mainmodule.setSkinShortCutsProperty(setting, windowHeader, property) elif action == "TOGGLEKODISETTING": kodisetting = params.get("SETTING") mainmodule.toggleKodiSetting(kodisetting) elif action == "SETKODISETTING": kodisetting = params.get("SETTING") value = params.get("VALUE") mainmodule.setKodiSetting(kodisetting, value) elif action == "ENABLEVIEWS": mainmodule.enableViews() elif action == "SPLASHSCREEN": file = params.get("FILE", "") duration = params.get("DURATION", "") if duration: mainmodule.show_splash(file, int(duration)) else: mainmodule.show_splash(file) elif action == "VIDEOSEARCH": from resources.lib.SearchDialog import SearchDialog searchDialog = SearchDialog( "script-skin_helper_service-CustomSearch.xml", utils.ADDON_PATH, "Default", "1080i") searchDialog.doModal() resultAction = searchDialog.action del searchDialog if resultAction: if "jsonrpc" in resultAction: xbmc.executeJSONRPC(resultAction) else: xbmc.executebuiltin(resultAction) elif action == "SHOWINFO": xbmc.executebuiltin("ActivateWindow(busydialog)") #try to figure out the params automatically if no ID provided... if not (params.get("MOVIEID") or params.get("EPISODEID") or params.get("TVSHOWID")): widgetContainer = utils.WINDOW.getProperty( "SkinHelper.WidgetContainer").decode('utf-8') if widgetContainer: widgetContainerPrefix = "Container(%s)." % widgetContainer else: widgetContainerPrefix = "" dbid = xbmc.getInfoLabel( "%sListItem.DBID" % widgetContainerPrefix).decode('utf-8') if not dbid or dbid == "-1": dbid = xbmc.getInfoLabel( "%sListItem.Property(DBID)" % widgetContainerPrefix).decode('utf-8') if dbid == "-1": dbid = "" dbtype = xbmc.getInfoLabel( "%sListItem.DBTYPE" % widgetContainerPrefix).decode('utf-8') utils.logMsg("dbtype: %s - dbid: %s" % (dbtype, dbid)) if not dbtype: dbtype = xbmc.getInfoLabel( "%sListItem.Property(DBTYPE)" % widgetContainerPrefix).decode('utf-8') if not dbtype: db_type = xbmc.getInfoLabel( "%sListItem.Property(type)" % widgetContainerPrefix).decode('utf-8') if "episode" in db_type.lower( ) or xbmc.getLocalizedString( 20360).lower() in db_type.lower(): dbtype = "episode" elif "movie" in db_type.lower( ) or xbmc.getLocalizedString( 342).lower() in db_type.lower(): dbtype = "movie" elif "tvshow" in db_type.lower( ) or xbmc.getLocalizedString( 36903).lower() in db_type.lower(): dbtype = "tvshow" elif "album" in db_type.lower( ) or xbmc.getLocalizedString( 558).lower() in db_type.lower(): dbtype = "album" elif "song" in db_type.lower( ) or xbmc.getLocalizedString( 36920).lower() in db_type.lower(): dbtype = "song" if dbid and dbtype: params["%sID" % dbtype.upper()] = dbid params["lastwidgetcontainer"] = widgetContainer #open info dialog... from resources.lib.InfoDialog import GUI info_dialog = GUI("script-skin_helper_service-CustomInfo.xml", utils.ADDON_PATH, "Default", "1080i", params=params) xbmc.executebuiltin("Dialog.Close(busydialog)") if info_dialog.listitem: info_dialog.doModal() resultAction = info_dialog.action if resultAction: while xbmc.getCondVisibility( "System.HasModalDialog | Window.IsActive(script-ExtendedInfo Script-DialogVideoInfo.xml) | Window.IsActive(script-ExtendedInfo Script-DialogInfo.xml) | Window.IsActive(script-skin_helper_service-CustomInfo.xml) | Window.IsActive(script-skin_helper_service-CustomSearch.xml)" ): xbmc.executebuiltin("Action(Back)") xbmc.sleep(500) if "jsonrpc" in resultAction: xbmc.executeJSONRPC(resultAction) else: xbmc.executebuiltin(resultAction) elif action == "COLORPICKER": from resources.lib.ColorPicker import ColorPicker colorPicker = ColorPicker( "script-skin_helper_service-ColorPicker.xml", utils.ADDON_PATH, "Default", "1080i") colorPicker.skinString = params.get("SKINSTRING", "") colorPicker.winProperty = params.get("WINPROPERTY", "") colorPicker.activePalette = params.get("PALETTE", "") colorPicker.headerLabel = params.get("HEADER", "") propname = params.get("SHORTCUTPROPERTY", "") colorPicker.shortcutProperty = propname colorPicker.doModal() if propname and not isinstance(colorPicker.result, int): mainmodule.waitForSkinShortcutsWindow() xbmc.sleep(400) currentWindow = xbmcgui.Window( xbmcgui.getCurrentWindowDialogId()) currentWindow.setProperty("customProperty", propname) currentWindow.setProperty("customValue", colorPicker.result[0]) xbmc.executebuiltin("SendClick(404)") xbmc.sleep(250) currentWindow.setProperty("customProperty", propname + ".name") currentWindow.setProperty("customValue", colorPicker.result[1]) xbmc.executebuiltin("SendClick(404)") del colorPicker elif action == "COLORTHEMES": from resources.lib.ColorThemes import ColorThemes colorThemes = ColorThemes("DialogSelect.xml", utils.ADDON_PATH) colorThemes.daynight = params.get("DAYNIGHT", None) colorThemes.doModal() del colorThemes elif action == "CONDITIONALBACKGROUNDS": from resources.lib.ConditionalBackgrounds import ConditionalBackgrounds conditionalBackgrounds = ConditionalBackgrounds( "DialogSelect.xml", utils.ADDON_PATH) conditionalBackgrounds.doModal() del conditionalBackgrounds elif action == "CREATECOLORTHEME": import resources.lib.ColorThemes as colorThemes colorThemes.createColorTheme() elif action == "RESTORECOLORTHEME": import resources.lib.ColorThemes as colorThemes colorThemes.restoreColorTheme() elif action == "OVERLAYTEXTURE": mainmodule.selectOverlayTexture() elif action == "BUSYTEXTURE": mainmodule.selectBusyTexture() elif action == "CACHEALLMUSICART": import resources.lib.ArtworkUtils as artworkutils artworkutils.preCacheAllMusicArt() elif action == "RESETCACHE": path = params.get("PATH") if path == "pvr": path = utils.WINDOW.getProperty( "SkinHelper.pvrthumbspath").decode("utf-8") utils.WINDOW.setProperty("resetPvrArtCache", "reset") elif path == "music": path = "special://profile/addon_data/script.skin.helper.service/musicartcache/" utils.WINDOW.setProperty("resetMusicArtCache", "reset") elif path == "wallbackgrounds": path = "special://profile/addon_data/script.skin.helper.service/wallbackgrounds/" utils.WINDOW.setProperty("resetWallArtCache", "reset") else: path = None if path: success = True ret = xbmcgui.Dialog().yesno( heading=utils.ADDON.getLocalizedString(32089), line1=utils.ADDON.getLocalizedString(32090) + path) if ret: utils.WINDOW.setProperty("SkinHelper.IgnoreCache", "ignore") success = utils.recursiveDelete(path) if success: utils.checkFolders() xbmcgui.Dialog().ok( heading=utils.ADDON.getLocalizedString(32089), line1=utils.ADDON.getLocalizedString(32091)) else: xbmcgui.Dialog().ok( heading=utils.ADDON.getLocalizedString(32089), line1=utils.ADDON.getLocalizedString(32092)) elif action == "BACKUP": import resources.lib.BackupRestore as backup filter = params.get("FILTER", "") silent = params.get("SILENT", None) promptfilename = params.get("PROMPTFILENAME", "false") backup.backup(filter, silent, promptfilename.lower()) elif action == "RESTORE": import resources.lib.BackupRestore as backup silent = params.get("SILENT", None) backup.restore(silent) elif action == "RESET": import resources.lib.BackupRestore as backup filter = params.get("FILTER", "") silent = params.get("SILENT", "") == "true" backup.reset(filter, silent) xbmc.Monitor().waitForAbort(2) mainmodule.correctSkinSettings() elif action == "DIALOGOK": headerMsg = params.get("HEADER") bodyMsg = params.get("MESSAGE") if bodyMsg.startswith(" "): bodyMsg = bodyMsg[1:] if headerMsg.startswith(" "): headerMsg = headerMsg[1:] xbmcgui.Dialog().ok(heading=headerMsg, line1=bodyMsg) elif action == "DIALOGYESNO": headerMsg = params.get("HEADER") bodyMsg = params.get("MESSAGE") yesactions = params.get("YESACTION", "").split("|") noactions = params.get("NOACTION", "").split("|") if bodyMsg.startswith(" "): bodyMsg = bodyMsg[1:] if headerMsg.startswith(" "): headerMsg = headerMsg[1:] if xbmcgui.Dialog().yesno(heading=headerMsg, line1=bodyMsg): for action in yesactions: xbmc.executebuiltin(action.encode("utf-8")) else: for action in noactions: xbmc.executebuiltin(action.encode("utf-8")) elif action == "TEXTVIEWER": headerMsg = params.get("HEADER", "") bodyMsg = params.get("MESSAGE", "") if bodyMsg.startswith(" "): bodyMsg = bodyMsg[1:] if headerMsg.startswith(" "): headerMsg = headerMsg[1:] xbmcgui.Dialog().textviewer(headerMsg, bodyMsg) elif action == "FILEEXISTS": filename = params.get("FILE") skinstring = params.get("SKINSTRING") windowprop = params.get("WINDOWPROP") if xbmcvfs.exists(filename): if windowprop: utils.WINDOW.setProperty(windowprop, "exists") if skinstring: xbmc.executebuiltin("Skin.SetString(%s,exists)" % skinstring) else: if windowprop: utils.WINDOW.clearProperty(windowprop) if skinstring: xbmc.executebuiltin("Skin.Reset(%s)" % skinstring) elif action == "STRIPSTRING": splitchar = params.get("SPLITCHAR") string = params.get("STRING") output = params.get("OUTPUT") index = params.get("INDEX", 0) string = string.split(splitchar)[int(index)] utils.WINDOW.setProperty(output, string) elif action == "GETPLAYERFILENAME": output = params.get("OUTPUT") filename = xbmc.getInfoLabel("Player.FileNameAndPath") if not filename: filename = xbmc.getInfoLabel("Player.FileName") if "filename=" in filename: url_params = dict(urlparse.parse_qsl(filename)) filename = url_params.get("filename") utils.WINDOW.setProperty(output, filename) elif action == "GETFILENAME": output = params.get("OUTPUT") filename = xbmc.getInfoLabel("ListItem.FileNameAndPath") if not filename: filename = xbmc.getInfoLabel("ListItem.FileName") if not filename: filename = xbmc.getInfoLabel( "Container(999).ListItem.FileName") if not filename: filename = xbmc.getInfoLabel( "Container(999).ListItem.FileNameAndPath") if "filename=" in filename: url_params = dict(urlparse.parse_qsl(filename)) filename = url_params.get("filename") utils.WINDOW.setProperty(output, filename) elif action == "CHECKRESOURCEADDONS": ADDONSLIST = params.get("ADDONSLIST") mainmodule.checkResourceAddons(ADDONSLIST) elif action == "GETPERCENTAGE": total = int(params.get("TOTAL")) count = int(params.get("COUNT")) roundsteps = params.get("ROUNDSTEPS") skinstring = params.get("SKINSTRING") percentage = int(round((1.0 * count / total) * 100)) if roundsteps: roundsteps = int(roundsteps) percentage = percentage + (roundsteps - percentage) % roundsteps xbmc.executebuiltin("Skin.SetString(%s,%s)" % (skinstring, percentage))
def get_system_monitor(): import xbmc return xbmc.Monitor()
def main(): try: app = Application() logout_event = Event() connstate_event = Event() monitor = xbmc.Monitor() app.set_var('logout_event', logout_event) app.set_var('login_last_error', ErrorType.Ok) app.set_var('connstate_event', connstate_event) app.set_var('exit_requested', False) app.set_var('monitor', monitor) data_dir, cache_dir, settings_dir = check_dirs() #Initialize spotify stuff ml = MainLoop() buf = BufferManager(get_audio_buffer_size()) callbacks = Callbacks(ml, buf, app) sess = Session(callbacks, app_key=appkey, user_agent="python ctypes bindings", settings_location=settings_dir, cache_location=cache_dir, initially_unload_playlists=False) set_settings(sess) ml_runner = MainLoopRunner(ml, sess) ml_runner.start() #Set the exit flag if login was cancelled if not do_login(sess, app): WINDOW.setProperty("Spotify.ServiceReady", "error") app.set_var('exit_requested', True) elif wait_for_connstate(sess, app, ConnectionState.LoggedIn): proxy_runner = ProxyRunner(sess, buf, host='127.0.0.1', allow_ranges=True) proxy_runner.start() logMsg('starting proxy at port {0}'.format( proxy_runner.get_port())) preloader_cb = get_preloader_callback(sess, buf) logMsg('Setting callback ..') proxy_runner.set_stream_end_callback(preloader_cb) user_agent = try_decode('Spotify/{0} (XBMC/{1})'.format( ADDON_VERSION, xbmc.getInfoLabel("System.BuildVersion"))).decode( 'utf-8', 'ignore') logMsg('Obtaining user token ..') playtoken = proxy_runner.get_user_token(user_agent) header_dict = {'User-Agent': user_agent, 'x-csrf-token': playtoken} logMsg('Encoding header ..') url_headers = urlencode(header_dict) WINDOW.setProperty("Spotify.PlayToken", url_headers) WINDOW.setProperty( "Spotify.PlayServer", "%s:%s" % (proxy_runner.get_host(), proxy_runner.get_port())) WINDOW.setProperty("Spotify.ServiceReady", "ready") #wait untill abortrequested while not app.get_var('exit_requested'): if monitor.abortRequested() or xbmc.abortRequested: logMsg("Shutdown requested!") app.set_var('exit_requested', True) monitor.waitForAbort(0.5) logMsg("Shutting down background processing...") #Playback and proxy deinit sequence xbmc.executebuiltin('PlayerControl(stop)') logMsg('Clearing stream / stopping ..') proxy_runner.clear_stream_end_callback() proxy_runner.stop() buf.cleanup() #Clear some vars and collect garbage proxy_runner = None preloader_cb = None #Logout logMsg('Logging out ..') if sess.user(): sess.logout() logout_event.wait(2) #Stop main loop error = login_get_last_error(app) WINDOW.setProperty("Spotify.LastError", str(login_get_last_error(app))) ml_runner.stop() except (Exception) as ex: if str(ex) != '': # trace = traceback.format_exc() logMsg("TRACE: " + (''.join(traceback.format_stack()))) logMsg("EXCEPTION in background service: " + str(ex)) # logMsg("STACK: %s" %trace, True) if "Unable to find" in str(ex): WINDOW.setProperty("Spotify.LastError", "999") else: error = str(ex) WINDOW.clearProperty("Spotify.ServiceReady") WINDOW.setProperty("Spotify.LastError", error)
def helix_abortloop(timeout, monitor_instance=None): if monitor_instance is None: monitor_instance = xbmc.Monitor() return monitor_instance.waitForAbort(timeout / 1000.0)
def play_from_library(item): """ The .strm files when played from kodi, this expects it to be a "playable" file so it cannot contain more items, at most a selection dialog can be placed. We solve this by "cheating kodi" and making him believe that something has been reproduced, so later by "Container.Update ()" we load the strm as if an item from inside the addon were treated, removing all the limitations and allowing to reproduce through the general function without having to create new methods to the video library. @type item: item @param item: item with information """ import xbmcgui, xbmcplugin, xbmc from time import sleep itemlist = [] item.fromLibrary = True logger.info() # logger.debug("item: \n" + item.tostring('\n')) # Try to reproduce an image (this does nothing and also does not give an error) xbmcplugin.setResolvedUrl( int(sys.argv[1]), True, xbmcgui.ListItem(path=os.path.join(config.get_runtime_path(), "resources", "kod.mp4"))) xbmc.Player().stop() # Modify the action (currently the video library needs "findvideos" since this is where the sources are searched item.action = "findvideos" window_type = config.get_setting("window_type", "videolibrary") # and launch kodi again if xbmc.getCondVisibility('Window.IsMedia') and not window_type == 1: # Conventional window xbmc.executebuiltin("Container.Update(" + sys.argv[0] + "?" + item.tourl() + ")") else: # Pop-up window from specials import videolibrary p_dialog = platformtools.dialog_progress_bg( config.get_localized_string(20000), config.get_localized_string(60683)) p_dialog.update(0, '') item.play_from = 'window' itemlist = videolibrary.findvideos(item) p_dialog.update(100, '') sleep(0.5) p_dialog.close() while platformtools.is_playing(): # Conventional window sleep(1) play_time = platformtools.resume_playback(item, True) if not play_time and config.get_setting('autoplay'): return # The number of links to show is limited if config.get_setting("max_links", "videolibrary") != 0: itemlist = limit_itemlist(itemlist) # The list of links is slightly "cleaned" if config.get_setting("replace_VD", "videolibrary") == 1: itemlist = reorder_itemlist(itemlist) if len(itemlist) > 0: while not xbmc.Monitor().abortRequested(): # The user chooses the mirror options = [] selection_implementation = 0 for item in itemlist: item.thumbnail = config.get_online_server_thumb( item.server) quality = '[B][' + item.quality + '][/B]' if item.quality else '' if item.server: it = xbmcgui.ListItem( '\n[B]%s[/B] %s - %s' % (item.server, quality, item.contentTitle)) it.setArt({'thumb': item.thumbnail}) options.append(it) else: selection_implementation += 1 # The selection window opens if (item.contentSerieName and item.contentSeason and item.contentEpisodeNumber): head = ("%s - %sx%s | %s" % (item.contentSerieName, item.contentSeason, item.contentEpisodeNumber, config.get_localized_string(30163))) else: head = config.get_localized_string(30163) selection = platformtools.dialog_select(head, options, preselect=-1, useDetails=True) if selection == -1: return else: item = videolibrary.play( itemlist[selection + selection_implementation])[0] platformtools.play_video(item) if (platformtools.is_playing() and item.action ) or item.server == 'torrent' or config.get_setting( 'autoplay'): break
def __init__(self): try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse # argv[0] can contain the entire path, so we limit ourselves to the base url pid = urlparse(argv[0]) self.pluginid = '{}://{}/'.format(pid.scheme, pid.netloc) self.pluginhandle = int( argv[1]) if (1 < len(argv)) and self.pluginid else -1 self._globals['monitor'] = xbmc.Monitor() self._globals['addon'] = xbmcaddon.Addon() self._globals['dialog'] = xbmcgui.Dialog() self._globals['dialogProgressBG'] = xbmcgui.DialogProgressBG() self._globals['DATA_PATH'] = py2_decode( xbmc.translatePath(self.addon.getAddonInfo('profile'))) self._globals['CONFIG_PATH'] = OSPJoin(self.DATA_PATH, 'config') self._globals['HOME_PATH'] = py2_decode( xbmc.translatePath('special://home')) self._globals['PLUGIN_ID'] = py2_decode(self.addon.getAddonInfo('id')) self._globals['PLUGIN_PATH'] = py2_decode( self.addon.getAddonInfo('path')) self._globals['PLUGIN_NAME'] = self.addon.getAddonInfo('name') self._globals['PLUGIN_VERSION'] = self.addon.getAddonInfo('version') self._globals['MEDIA_FANART'] = OSPJoin(self.PLUGIN_PATH, 'resources/media/fanart.png') self._globals['MEDIA_FOLDER'] = OSPJoin( self.PLUGIN_PATH, 'resources/media/folderIcon.png') self._globals['MEDIA_ICON'] = OSPJoin(self.PLUGIN_PATH, 'resources/media/icon.png') self._globals['MEDIA_REMOVE'] = OSPJoin( self.PLUGIN_PATH, 'resources/media/iconRemove.png') self._globals['MEDIA_UPDATE'] = OSPJoin( self.PLUGIN_PATH, 'resources/media/updateIcon.png') self._globals['DATABASES'] = [{ 'dbtype': 'movies', 'db': { 'sqliteDB': None, 'mysqlDBType': 'Movies' } }, { 'dbtype': 'tvshows', 'db': { 'sqliteDB': None, 'mysqlDBType': 'TVShows' } }, { 'dbtype': 'music', 'db': { 'sqliteDB': None, 'mysqlDBType': 'Music' } }] self._globals[ 'DATABASE_SQLLITE_OSMOSIS_SCHEMA_VERSION_FILES_PATH'] = OSPJoin( self.PLUGIN_PATH, 'resources/db/migrate') bv = xbmc.getInfoLabel('System.BuildVersion') self._globals['KODI_VERSION'] = int(bv.split('.')[0]) cdate = None if search('Git:(\d+-.*)', bv): cdate = search('Git:(\d+)', bv) cdate = date.fromtimestamp(mktime(strptime( cdate.group(1), '%Y%m%d'))) if cdate else None self._globals['KODI_COMPILE_DATE'] = cdate self._globals[ 'FEATURE_PLUGIN_RESUME_SYNC'] = self.KODI_VERSION >= 19 and self.KODI_COMPILE_DATE and self.KODI_COMPILE_DATE >= date( 2020, 1, 28) try: import StorageServer except: import storageserverdummy as StorageServer self._globals['CACHE_TVSHOWS'] = StorageServer.StorageServer( py2_encode('{0}TVShowsTVDB1').format(self.PLUGIN_NAME), 24 * 30) self._globals['CACHE_EPISODES'] = StorageServer.StorageServer( py2_encode('{0}EpisodesTVDB1').format(self.PLUGIN_NAME), 24 * 30) self._globals['CACHE_EPISODES_MANUAL'] = StorageServer.StorageServer( py2_encode('{0}EpisodesManual1').format(self.PLUGIN_NAME), 24 * 365) self._globals[ 'CACHE_TVDB_DATA'] = tvdbDataCache = StorageServer.StorageServer( py2_encode('{0}TVDBData1').format(self.PLUGIN_NAME), 1) self._globals['CACHE_ADDONNAME'] = StorageServer.StorageServer( py2_encode('{0}Addonname1').format(self.PLUGIN_NAME), 24)
def update_youtube_dl_core(url, name, action_type): #credit to ruuk for most of the download code import urllib import tarfile if action_type == 'download': newVersion = note_ytdl_versions() LATEST_URL = YTDL_LATEST_URL_TEMPLATE.format(newVersion) profile = xbmc.translatePath( profile_path ) #xbmc.translatePath(addon.getAddonInfo('profile')).decode('utf-8') archivePath = os.path.join(profile, 'youtube_dl.tar.gz') extractedPath = os.path.join(profile, 'youtube-dl') extracted_core_path = os.path.join(extractedPath, 'youtube_dl') #ytdl_core_path xbmc.translatePath( addon_path+"/resources/lib/youtube_dl/" ) try: if os.path.exists(extractedPath): shutil.rmtree(extractedPath, ignore_errors=True) update_dl_status('temp files removed') update_dl_status('Downloading {0} ...'.format(newVersion)) log(' From: {0}'.format(LATEST_URL)) log(' to: {0}'.format(archivePath)) urllib.urlretrieve(LATEST_URL, filename=archivePath) if os.path.exists(archivePath): update_dl_status('Extracting ...') with tarfile.open(archivePath, mode='r:gz') as tf: members = [ m for m in tf.getmembers() if m.name.startswith('youtube-dl/youtube_dl') ] #get just the files from the youtube_dl source directory tf.extractall(path=profile, members=members) else: update_dl_status('Download failed') except Exception as e: update_dl_status('Error:' + str(e)) update_dl_status('Updating...') if os.path.exists(extracted_core_path): log(' extracted dir exists:' + extracted_core_path) if os.path.exists(ytdl_core_path): log(' destination dir exists:' + ytdl_core_path) shutil.rmtree(ytdl_core_path, ignore_errors=True) update_dl_status(' Old ytdl core removed') xbmc.sleep(1000) try: shutil.move(extracted_core_path, ytdl_core_path) update_dl_status(' New core copied') xbmc.sleep(1000) update_dl_status('Update complete') xbmc.Monitor().waitForAbort(2.0) #ourVersion=ytdl_get_version_info('local') setSetting('ytdl_btn_check_version', "") setSetting('ytdl_btn_download', "") except Exception as e: update_dl_status('Failed...') log('move failed:' + str(e)) elif action_type == 'checkversion': note_ytdl_versions()
def run(self): monitor = xbmc.Monitor() #keep this thread alive while (True): if (time() >= self.refresh_prop): aVideo = None globalArt = None if (len(self.xbmc_movies) > 0): try: self.WINDOW.setProperty( 'script.grab.fanart.Movie.Title', self.xbmc_movies[self.movie_index].title) self.WINDOW.setProperty( 'script.grab.fanart.Movie.FanArt', self.xbmc_movies[self.movie_index].fan_art) self.WINDOW.setProperty( 'script.grab.fanart.Movie.Poster', self.xbmc_movies[self.movie_index].poster) self.WINDOW.setProperty( 'script.grab.fanart.Movie.Logo', self.xbmc_movies[self.movie_index].logo) self.WINDOW.setProperty( 'script.grab.fanart.Movie.Plot', self.xbmc_movies[self.movie_index].plot) self.WINDOW.setProperty( 'script.grab.fanart.Movie.Path', self.xbmc_movies[self.movie_index].path) aVideo = self.xbmc_movies[self.movie_index] globalArt = aVideo except IndexError: pass self.movie_index = self.movie_index + 1 if (self.movie_index >= len(self.xbmc_movies)): self.movie_index = 0 if (len(self.xbmc_tv) > 0): try: self.WINDOW.setProperty( 'script.grab.fanart.TV.Title', self.xbmc_tv[self.tv_index].title) self.WINDOW.setProperty( 'script.grab.fanart.TV.FanArt', self.xbmc_tv[self.tv_index].fan_art) self.WINDOW.setProperty( 'script.grab.fanart.TV.Poster', self.xbmc_tv[self.tv_index].poster) self.WINDOW.setProperty( 'script.grab.fanart.TV.Logo', self.xbmc_tv[self.tv_index].logo) self.WINDOW.setProperty( 'script.grab.fanart.TV.Plot', self.xbmc_tv[self.tv_index].plot) self.WINDOW.setProperty( 'script.grab.fanart.TV.Path', self.xbmc_tv[self.tv_index].path) #this will only have a value when "recent" is the type self.WINDOW.setProperty( 'script.grab.fanart.TV.Season', str(self.xbmc_tv[self.tv_index].season)) self.WINDOW.setProperty( 'script.grab.fanart.TV.Episode', str(self.xbmc_tv[self.tv_index].episode)) self.WINDOW.setProperty( 'script.grab.fanart.TV.Thumb', self.xbmc_tv[self.tv_index].thumb) #use a tv show if blank or randomly selected is = 9 (10% chance) if (aVideo == None or self.randomNum(10) == 9): aVideo = self.xbmc_tv[self.tv_index] #30% change of TV show on global if (globalArt == None or self.randomNum(3) == 2): globalArt = self.xbmc_tv[self.tv_index] except IndexError: pass self.tv_index = self.tv_index + 1 if (self.tv_index >= len(self.xbmc_tv)): self.tv_index = 0 if (aVideo != None): self.WINDOW.setProperty('script.grab.fanart.Video.Title', aVideo.title) self.WINDOW.setProperty('script.grab.fanart.Video.FanArt', aVideo.fan_art) self.WINDOW.setProperty('script.grab.fanart.Video.Poster', aVideo.poster) self.WINDOW.setProperty('script.grab.fanart.Video.Logo', aVideo.logo) self.WINDOW.setProperty('script.grab.fanart.Video.Plot', aVideo.plot) self.WINDOW.setProperty('script.grab.fanart.Video.Path', aVideo.path) if (len(self.xbmc_music) > 0): try: self.WINDOW.setProperty( 'script.grab.fanart.Music.Artist', self.xbmc_music[self.music_index].title) self.WINDOW.setProperty( 'script.grab.fanart.Music.FanArt', self.xbmc_music[self.music_index].fan_art) self.WINDOW.setProperty( 'script.grab.fanart.Music.Description', self.xbmc_music[self.music_index].plot) #30% of music fanart on global if (globalArt == None or self.randomNum(3) == 2): globalArt = self.xbmc_music[self.music_index] except IndexError: pass self.music_index = self.music_index + 1 if (self.music_index >= len(self.xbmc_music)): self.music_index = 0 if (globalArt != None): self.WINDOW.setProperty('script.grab.fanart.Global.Title', globalArt.title) self.WINDOW.setProperty('script.grab.fanart.Global.FanArt', globalArt.fan_art) self.WINDOW.setProperty('script.grab.fanart.Global.Logo', globalArt.logo) refresh_interval = 10 if (utils.getSetting('refresh') != ''): refresh_interval = float(utils.getSetting("refresh")) self.refresh_prop = time() + refresh_interval #let xbmc know the images are ready self.WINDOW.setProperty('script.grab.fanart.Ready', "true") #check if the media list should be updated if (time() >= self.refresh_media): if (utils.getSetting('mode') == '' or utils.getSetting('mode') == 'random'): thread.start_new_thread(self.grabRandom, ()) else: thread.start_new_thread(self.grabRecent, ()) self.refresh_media = time() + (60 * 60 ) #refresh again in 60 minutes if (monitor.waitForAbort(1)): break
def play_file(play_info): item_id = play_info.get("item_id") home_window = HomeWindow() last_url = home_window.get_property("last_content_url") if last_url: home_window.set_property("skip_cache_for_" + last_url, "true") action = play_info.get("action", "play") if action == "add_to_playlist": add_to_playlist(play_info) return # if this is a list of items them add them all to the play list if isinstance(item_id, list): return play_list_of_items(item_id) auto_resume = play_info.get("auto_resume", "-1") force_transcode = play_info.get("force_transcode", False) media_source_id = play_info.get("media_source_id", "") subtitle_stream_index = play_info.get("subtitle_stream_index", None) audio_stream_index = play_info.get("audio_stream_index", None) log.debug("playFile id({0}) resume({1}) force_transcode({2})".format( item_id, auto_resume, force_transcode)) settings = xbmcaddon.Addon() addon_path = settings.getAddonInfo('path') force_auto_resume = settings.getSetting('forceAutoResume') == 'true' jump_back_amount = int(settings.getSetting("jump_back_amount")) play_cinema_intros = settings.getSetting('play_cinema_intros') == 'true' server = download_utils.get_server() url = "{server}/Users/{userid}/Items/%s?format=json" % (item_id, ) data_manager = DataManager() result = data_manager.get_content(url) log.debug("Playfile item: {0}".format(result)) if result is None: log.debug("Playfile item was None, so can not play!") return # if this is a season, playlist or album then play all items in that parent if result.get("Type") in ["Season", "MusicAlbum", "Playlist"]: log.debug("PlayAllFiles for parent item id: {0}".format(item_id)) url = ('{server}/Users/{userid}/items' + '?ParentId=%s' + '&Fields=MediaSources' + '&format=json') url = url % (item_id, ) result = data_manager.get_content(url) log.debug("PlayAllFiles items: {0}".format(result)) # process each item items = result["Items"] if items is None: items = [] return play_all_files(items) # if this is a program from live tv epg then play the actual channel if result.get("Type") == "Program": channel_id = result.get("ChannelId") url = "{server}/Users/{userid}/Items/%s?format=json" % (channel_id, ) result = data_manager.get_content(url) item_id = result["Id"] if result.get("Type") == "Photo": play_url = "%s/Items/%s/Images/Primary" play_url = play_url % (server, item_id) plugin_path = xbmc.translatePath( os.path.join(xbmcaddon.Addon().getAddonInfo('path'))) action_menu = PictureViewer("PictureViewer.xml", plugin_path, "default", "720p") action_menu.setPicture(play_url) action_menu.doModal() return # get playback info from the server using the device profile playback_info = download_utils.get_item_playback_info( item_id, force_transcode) if playback_info is None: log.debug( "playback_info was None, could not get MediaSources so can not play!" ) return if playback_info.get("ErrorCode") is not None: error_string = playback_info.get("ErrorCode") xbmcgui.Dialog().notification( string_load(30316), error_string, icon="special://home/addons/plugin.video.jellycon/icon.png") return play_session_id = playback_info.get("PlaySessionId") # select the media source to use media_sources = playback_info.get('MediaSources') selected_media_source = None if media_sources is None or len(media_sources) == 0: log.debug("Play Failed! There is no MediaSources data!") return elif len(media_sources) == 1: selected_media_source = media_sources[0] elif media_source_id != "": for source in media_sources: if source.get("Id", "na") == media_source_id: selected_media_source = source break elif len(media_sources) > 1: items = [] for source in media_sources: label = source.get("Name", "na") label2 = __build_label2_from(source) items.append(xbmcgui.ListItem(label=label, label2=label2)) dialog = xbmcgui.Dialog() resp = dialog.select(string_load(30309), items, useDetails=True) if resp > -1: selected_media_source = media_sources[resp] else: log.debug("Play Aborted, user did not select a MediaSource") return if selected_media_source is None: log.debug("Play Aborted, MediaSource was None") return source_id = selected_media_source.get("Id") seek_time = 0 auto_resume = int(auto_resume) # process user data for resume points if auto_resume != -1: seek_time = (auto_resume / 1000) / 10000 elif force_auto_resume: user_data = result.get("UserData") reasonable_ticks = int(user_data.get("PlaybackPositionTicks")) / 1000 seek_time = reasonable_ticks / 10000 else: user_data = result.get("UserData") if user_data.get("PlaybackPositionTicks") != 0: reasonable_ticks = int( user_data.get("PlaybackPositionTicks")) / 1000 seek_time = reasonable_ticks / 10000 display_time = str(timedelta(seconds=seek_time)) resume_dialog = ResumeDialog("ResumeDialog.xml", addon_path, "default", "720p") resume_dialog.setResumeTime("Resume from " + display_time) resume_dialog.doModal() resume_result = resume_dialog.getResumeAction() del resume_dialog log.debug("Resume Dialog Result: {0}".format(resume_result)) if resume_result == 1: seek_time = 0 elif resume_result == -1: return log.debug("play_session_id: {0}".format(play_session_id)) playurl, playback_type, listitem_props = PlayUtils().get_play_url( selected_media_source, play_session_id) log.info( "Play URL: {0} Playback Type: {1} ListItem Properties: {2}".format( playurl, playback_type, listitem_props)) if playurl is None: return playback_type_string = "DirectPlay" if playback_type == "2": playback_type_string = "Transcode" elif playback_type == "1": playback_type_string = "DirectStream" # add the playback type into the overview if result.get("Overview", None) is not None: result["Overview"] = playback_type_string + "\n" + result.get( "Overview") else: result["Overview"] = playback_type_string # add title decoration is needed item_title = result.get("Name", string_load(30280)) # extract item info from result gui_options = {} gui_options["server"] = server gui_options["name_format"] = None gui_options["name_format_type"] = "" item_details = extract_item_info(result, gui_options) # create ListItem display_options = {} display_options["addCounts"] = False display_options["addResumePercent"] = False display_options["addSubtitleAvailable"] = False display_options["addUserRatings"] = False gui_item = add_gui_item("", item_details, display_options, False) list_item = gui_item[1] if playback_type == "2": # if transcoding then prompt for audio and subtitle playurl = audio_subs_pref(playurl, list_item, selected_media_source, item_id, audio_stream_index, subtitle_stream_index) log.debug("New playurl for transcoding: {0}".format(playurl)) elif playback_type == "1": # for direct stream add any streamable subtitles external_subs(selected_media_source, list_item, item_id) # add playurl and data to the monitor data = {} data["item_id"] = item_id data["source_id"] = source_id data["playback_type"] = playback_type_string data["play_session_id"] = play_session_id data["play_action_type"] = "play" data["item_type"] = result.get("Type", None) data["can_delete"] = result.get("CanDelete", False) home_window.set_property('now_playing', json.dumps(data)) list_item.setPath(playurl) list_item = set_list_item_props(item_id, list_item, result, server, listitem_props, item_title) player = xbmc.Player() intro_items = [] if play_cinema_intros and seek_time == 0: intro_items = get_playback_intros(item_id) if len(intro_items) > 0: playlist = play_all_files(intro_items, play_items=False) playlist.add(playurl, list_item) else: playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(playurl, list_item) player.play(playlist) if seek_time != 0: player.pause() monitor = xbmc.Monitor() count = 0 while not player.isPlaying() and not monitor.abortRequested( ) and count != 100: count = count + 1 xbmc.sleep(100) if count == 100 or not player.isPlaying() or monitor.abortRequested(): log.info( "PlaybackResumrAction : Playback item did not get to a play state in 10 seconds so exiting" ) player.stop() return log.info("PlaybackResumrAction : Playback is Running") seek_to_time = seek_time - jump_back_amount target_seek = (seek_to_time - 10) count = 0 max_loops = 2 * 120 while not monitor.abortRequested() and player.isPlaying( ) and count < max_loops: log.info( "PlaybackResumrAction : Seeking to : {0}".format(seek_to_time)) player.seekTime(seek_to_time) current_position = player.getTime() if current_position >= target_seek: break log.info("PlaybackResumrAction : target:{0} current:{1}".format( target_seek, current_position)) count = count + 1 xbmc.sleep(500) if count == max_loops: log.info( "PlaybackResumrAction : Playback could not seek to required position" ) player.stop() else: count = 0 while bool(xbmc.getCondVisibility("Player.Paused")) and count < 10: log.info("PlaybackResumrAction : Unpausing playback") player.pause() xbmc.sleep(1000) count = count + 1 if count == 10: log.info("PlaybackResumrAction : Could not unpause") else: log.info("PlaybackResumrAction : Playback resumed") next_episode = get_next_episode(result) data["next_episode"] = next_episode send_next_episode_details(result, next_episode)
def __init__(self): '''Initialize our caching class''' self._monitor = xbmc.Monitor() self.check_cleanup()
def __init__(self): FirstCycle = True next_check = False monitor = xbmc.Monitor() while not monitor.abortRequested(): kodi_time = get_kodi_time() try: supervise_start_time = int( selfAddon.getSetting('hour_start_sup').split(':')[0] + selfAddon.getSetting('hour_start_sup').split(':')[1]) except: supervise_start_time = 0 try: supervise_end_time = int( selfAddon.getSetting('hour_end_sup').split(':')[0] + selfAddon.getSetting('hour_end_sup').split(':')[1]) except: supervise_end_time = 0 proceed = should_i_supervise(kodi_time, supervise_start_time, supervise_end_time) if proceed: if FirstCycle: # Variables: enable_audio = audio_enable enable_video = video_enable maxaudio_time_in_minutes = max_time_audio maxvideo_time_in_minutes = max_time_video iCheckTime = check_time _log("started ... (" + str(__version__) + ")") if debug == 'true': _log( "DEBUG: ################################################################" ) _log("DEBUG: Settings in Kodi:") _log('DEBUG: enable_audio: ' + enable_audio) _log("DEBUG: maxaudio_time_in_minutes: " + str(maxaudio_time_in_minutes)) _log("DEBUG: enable_video: " + str(enable_video)) _log("DEBUG: maxvideo_time_in_minutes: " + str(maxvideo_time_in_minutes)) _log("DEBUG: check_time: " + str(iCheckTime)) _log("DEBUG: Supervision mode: Always") _log( "DEBUG: ################################################################" ) # Set this low values for easier debugging! _log("DEBUG: debug is enabled! Override Settings:") enable_audio = 'true' _log("DEBUG: -> enable_audio: " + str(enable_audio)) maxaudio_time_in_minutes = 1 _log("DEBUG: -> maxaudio_time_in_minutes: " + str(maxaudio_time_in_minutes)) enable_video = 'true' _log("DEBUG: -> enable_video: " + str(enable_audio)) maxvideo_time_in_minutes = 1 _log("DEBUG: -> maxvideo_time_in_minutes: " + str(maxvideo_time_in_minutes)) iCheckTime = 1 _log("DEBUG: -> check_time: " + str(iCheckTime)) _log( "DEBUG: ----------------------------------------------------------------" ) # wait 15s before start to let Kodi finish the intro-movie if monitor.waitForAbort(15): break max_time_in_minutes = -1 FirstCycle = False idle_time = xbmc.getGlobalIdleTime() idle_time_in_minutes = int(idle_time) / 60 if xbmc.Player().isPlaying(): if debug == 'true' and max_time_in_minutes == -1: _log( "DEBUG: max_time_in_minutes before calculation: " + str(max_time_in_minutes)) if next_check == 'true': # add "diff_between_idle_and_check_time" to "idle_time_in_minutes" idle_time_in_minutes += int( diff_between_idle_and_check_time) if debug == 'true' and max_time_in_minutes == -1: _log("DEBUG: max_time_in_minutes after calculation: " + str(max_time_in_minutes)) if xbmc.Player().isPlayingAudio(): if enable_audio == 'true': if debug == 'true': _log("DEBUG: enable_audio is true") print_act_playing_file() what_is_playing = "audio" max_time_in_minutes = maxaudio_time_in_minutes else: if debug == 'true': _log( "DEBUG: Player is playing Audio, but check is disabled" ) do_next_check(iCheckTime) continue elif xbmc.Player().isPlayingVideo(): if enable_video == 'true': if debug == 'true': _log("DEBUG: enable_video is true") print_act_playing_file() what_is_playing = "video" max_time_in_minutes = maxvideo_time_in_minutes else: if debug == 'true': _log( "DEBUG: Player is playing Video, but check is disabled" ) do_next_check(iCheckTime) continue ### ToDo: # expand it with RetroPlayer for playing Games!!! else: if debug == 'true': _log( "DEBUG: Player is playing, but no Audio or Video" ) print_act_playing_file() what_is_playing = "other" do_next_check(iCheckTime) continue if debug == 'true': _log("DEBUG: what_is_playing: " + str(what_is_playing)) if debug == 'true': _log("DEBUG: idle_time: '" + str(idle_time) + "s'; idle_time_in_minutes: '" + str(idle_time_in_minutes) + "'") _log("DEBUG: max_time_in_minutes: " + str(max_time_in_minutes)) # only display the Progressdialog, if audio or video is enabled AND idle limit is reached # Check if what_is_playing is not "other" and idle time exceeds limit if (what_is_playing != "other" and idle_time_in_minutes >= max_time_in_minutes): if debug == 'true': _log( "DEBUG: idle_time exceeds max allowed. Display Progressdialog" ) ret = msgdialogprogress.create(translate(30000), translate(30001)) secs = 0 percent = 0 # use the multiplier 100 to get better %/calculation increment = 100 * 100 / time_to_wait cancelled = False while secs < time_to_wait: secs = secs + 1 # divide with 100, to get the right value percent = increment * secs / 100 secs_left = str((time_to_wait - secs)) remaining_display = str( secs_left) + " seconds left." msgdialogprogress.update(int(percent), translate(30001)) xbmc.sleep(1000) if (msgdialogprogress.iscanceled()): cancelled = True if debug == 'true': _log("DEBUG: Progressdialog cancelled") break if cancelled == True: iCheckTime = check_time_next _log("Progressdialog cancelled, next check in " + str(iCheckTime) + " min") # set next_check, so that it opens the dialog after "iCheckTime" next_check = True msgdialogprogress.close() else: _log( "Progressdialog not cancelled: stopping Player" ) msgdialogprogress.close() # softmute audio before stop playing # get actual volume if audiochange == 'true': resp = xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "Application.GetProperties", "params": { "properties": [ "volume"] }, "id": 1}' ) dct = json.loads(resp) muteVol = 10 if ("result" in dct) and ("volume" in dct["result"]): curVol = dct["result"]["volume"] for i in range(curVol - 1, muteVol - 1, -1): xbmc.executebuiltin( 'SetVolume(%d,showVolumeBar)' % (i)) # move down slowly xbmc.sleep(audiochangerate) # stop player anyway monitor.waitForAbort(5) # wait 5s before stopping xbmc.executebuiltin('PlayerControl(Stop)') if audiochange == 'true': monitor.waitForAbort( 2 ) # wait 2s before changing the volume back if ("result" in dct) and ("volume" in dct["result"]): curVol = dct["result"]["volume"] # we can move upwards fast, because there is nothing playing xbmc.executebuiltin( 'SetVolume(%d,showVolumeBar)' % (curVol)) if enable_screensaver == 'true': if debug == 'true': _log("DEBUG: Activating screensaver") xbmc.executebuiltin('ActivateScreensaver') # Run a custom cmd after playback is stopped if custom_cmd == 'true': if debug == 'true': _log("DEBUG: Running custom script") os.system(cmd) else: if debug == 'true': _log( "DEBUG: Playing the stream, time does not exceed max limit" ) else: if debug == 'true': _log("DEBUG: Not playing any media file") # reset max_time_in_minutes max_time_in_minutes = -1 diff_between_idle_and_check_time = idle_time_in_minutes - int( iCheckTime) if debug == 'true' and next_check == 'true': _log("DEBUG: diff_between_idle_and_check_time: " + str(diff_between_idle_and_check_time)) do_next_check(iCheckTime) monitor.waitForAbort(1)
def serve(self): """ Starts the forever-serving loop. This function only exits when an Exception is raised inside, by unexpected error, KeyboardInterrput, etc. It is coded using *select.select* function, and it is capable to serve to an unlimited amount of connections at same time without using threading. """ self._serve = True try: sockets = [] connections = [] connidx = {} monitor_abort = xbmc.Monitor() # For Kodi >= 14 while not monitor_abort.abortRequested(): try: ready_to_read = select.select( [self._lstsck] + sockets, # read [], [], # write, errors 1 # timeout )[0] except Exception: # Probably a socket is no longer valid. a = self._lstsck.fileno( ) # if this is not valid, raise Exception, exit. newsockets = [] for sck in sockets: try: a = sck.fileno() # NOQA h = sck.getpeername() # NOQA except Exception: continue newsockets.append(sck) sockets[:] = newsockets continue if not ready_to_read: continue if self._lstsck in ready_to_read: clientsck, clientaddr = self._lstsck.accept() sockets.append(clientsck) conn = Connection(sck=clientsck, address=clientaddr, handler_factory=self._handler) connidx[clientsck.fileno()] = conn conn._debug_socket = self._debug_socket conn._debug_dispatch = self._debug_socket # conn.internal_error_callback = self. connections.append(conn) for sck in ready_to_read: fileno = sck.fileno() if fileno not in connidx: continue conn = connidx[fileno] try: conn.dispatch_until_empty() except EofError: conn.close() sockets.remove(conn.socket) connections.remove(conn) # print "Closing client conn." finally: for conn in connections: conn.close() try: self._lstsck.shutdown(socket.SHUT_RDWR) except Exception: pass try: self._lstsck.close() except Exception: pass
def abort_requested(): return xbmc.Monitor().abortRequested()
def run(self): """ Main start :return: :rtype: """ if not self.enable_kodi_allow_remote(): return self.sock_kodi = socket.socket() self.sock_kodi.setblocking(True) xbmc.sleep(self.wait_onstartup) try: self.sock_kodi.connect((self.kodi_ip, self.kodi_port)) except (BaseException, Exception) as e: return self.report_contact_fail(e) self.log('Started') self.notify('Started in background') cache_pkg = 'special://home/addons/packages/service.sickgear.watchedstate.updater-%s.zip' % ADDON_VERSION if xbmcvfs.exists(cache_pkg): try: xbmcvfs.delete(cache_pkg) except (BaseException, Exception): pass self.kodi_events = xbmc.Monitor() sock_buffer, depth, methods, method = '', 0, { 'VideoLibrary.OnUpdate': self.video_library_on_update }, None # socks listener parsing Kodi json output into action to perform while not self.kodi_events.abortRequested(): chunk = decode_str(self.sock_kodi.recv(1)) sock_buffer += chunk if chunk in '{}': if '{' == chunk: depth += 1 else: depth -= 1 if not depth: json_msg = json.loads(sock_buffer) try: method = json_msg.get('method') method_handler = methods[method] method_handler(json_msg) except KeyError: if 'System.OnQuit' == method: break if __dev__: self.log('pass on event: %s' % json_msg.get('method')) sock_buffer = '' self.sock_kodi.close() del self.kodi_events self.log('Stopped')
def search_trailers(item): logger.info() from core.tmdb import Tmdb import xbmcgui, xbmc tipo = 'movie' if item.contentType == 'movie' else 'tv' nombre = item.contentTitle if item.contentType == 'movie' else item.contentSerieName if item.infoLabels['tmdb_id']: tmdb_search = Tmdb(id_Tmdb=item.infoLabels['tmdb_id'], tipo=tipo, idioma_busqueda='es') else: anyo = item.infoLabels['year'] if item.infoLabels['year'] else '-' tmdb_search = Tmdb(texto_buscado=nombre, tipo=tipo, year=anyo, idioma_busqueda='es') opciones = [] resultados = tmdb_search.get_videos() for res in resultados: # ~ logger.debug(res) it = xbmcgui.ListItem(res['name'], '[%sp] (%s)' % (res['size'], res['language'])) if item.thumbnail: it.setArt({'thumb': item.thumbnail}) opciones.append(it) if len(resultados) == 0: platformtools.dialog_ok(nombre, 'No se encuentra ningún tráiler en TMDB') else: while not xbmc.Monitor().abortRequested(): # (while True) ret = xbmcgui.Dialog().select('Tráilers para %s' % nombre, opciones, useDetails=True) if ret == -1: break platformtools.dialog_notification(resultados[ret]['name'], 'Cargando tráiler ...', time=3000, sound=False) from core import servertools if 'youtube' in resultados[ret]['url']: video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing( 'youtube', resultados[ret]['url']) else: video_urls = [] #TODO si no es youtube ... logger.debug(resultados[ret]) if len(video_urls) > 0: # ~ logger.debug(video_urls) xbmc.Player().play( video_urls[-1][1]) # el último es el de más calidad xbmc.sleep(1000) while not xbmc.Monitor().abortRequested() and xbmc.Player( ).isPlaying(): xbmc.sleep(1000) else: platformtools.dialog_notification( resultados[ret]['name'], 'No se puede reproducir el tráiler', time=3000, sound=False) if len(resultados) == 1: break # si sólo hay un vídeo no volver al diálogo de tráilers
def startScoringUpdates(): dialog = xbmcgui.Dialog() title = "Score Notifications" dialog.notification(title, 'Starting...', nhl_logo, 5000, False) ADDON.setSetting(id='score_updates', value='true') FIRST_TIME_THRU = 1 OLD_GAME_STATS = [] todays_date = local_to_eastern() wait = 30 monitor = xbmc.Monitor() while ADDON.getSetting( id="score_updates") == 'true' and not monitor.abortRequested(): video_playing = '' if xbmc.Player().isPlayingVideo(): video_playing = xbmc.Player().getPlayingFile() video_playing = video_playing.lower() json_source = getScoreBoard(todays_date) NEW_GAME_STATS = [] #wait = json_source['wait'] for game in json_source['dates'][0]['games']: #Break out of loop if updates disabled if ADDON.getSetting(id="score_updates") == 'false': break gid = str(game['gamePk']) ateam = game['teams']['away']['team']['abbreviation'].encode( 'utf-8') hteam = game['teams']['home']['team']['abbreviation'].encode( 'utf-8') ascore = str( game['linescore']['teams']['away']['goals']).encode('utf-8') hscore = str( game['linescore']['teams']['home']['goals']).encode('utf-8') #Team names (these can be found in the live streams url) atcommon = game['teams']['away']['team']['abbreviation'].encode( 'utf-8') htcommon = game['teams']['home']['team']['abbreviation'].encode( 'utf-8') gameclock = game['status']['detailedState'].encode('utf-8') current_period = game['linescore']['currentPeriod'] try: current_period = game['linescore'][ 'currentPeriodOrdinal'].encode('utf-8') except: pass desc = '' headshot = '' try: desc = game['scoringPlays'][-1]['result']['description'] #Remove Assists if there are none if ', assists: none' in desc: desc = desc[:desc.find(', assists: none')] player_id = game['scoringPlays'][-1]['players'][0]['player'][ 'link'] #/api/v1/people/8474034 player_id = player_id[player_id.rfind('/') + 1:] headshot = 'http://nhl.bamcontent.com/images/headshots/current/60x60/' + player_id + '@2x.png' except: pass if 'In Progress' in gameclock: gameclock = game['linescore'][ 'currentPeriodTimeRemaining'].encode('utf-8') + ' ' + game[ 'linescore']['currentPeriodOrdinal'].encode('utf-8') #Disable spoiler by not showing score notifications for the game the user is currently watching if video_playing.find( atcommon.lower()) == -1 and video_playing.find( htcommon.lower()) == -1: NEW_GAME_STATS.append([ gid, ateam, hteam, ascore, hscore, gameclock, current_period, desc, headshot ]) if FIRST_TIME_THRU != 1: display_seconds = int(ADDON.getSetting(id="display_seconds")) if display_seconds > 60: #Max Seconds 60 display_seconds = 60 elif display_seconds < 1: #Min Seconds 1 display_seconds = 1 #Convert to milliseconds display_milliseconds = display_seconds * 1000 all_games_finished = 1 for new_item in NEW_GAME_STATS: if ADDON.getSetting(id="score_updates") == 'false': break #Check if all games have finished if new_item[5].upper().find('FINAL') == -1: all_games_finished = 0 for old_item in OLD_GAME_STATS: #Break out of loop if updates disabled if ADDON.getSetting(id="score_updates") == 'false': break if new_item[0] == old_item[0]: #-------------------------- # Array key #-------------------------- # 0 = game id # 1 = away team # 2 = home team # 3 = away score # 4 = home score # 5 = game clock # 6 = current period # 7 = goal description # 8 = headshot img url #-------------------------- #If the score for either team has changed and is greater than zero. #Or if the game has just ended show the final score #Or the current peroid has changed if ((new_item[3] != old_item[3] and int(new_item[3]) != 0) or (new_item[4] != old_item[4] and int(new_item[4]) != 0)) or (new_item[5].upper().find('FINAL') != -1 and old_item[5].upper().find('FINAL') == -1) or (new_item[6] != old_item[6]): #Game variables ateam = new_item[1] hteam = new_item[2] ascore = new_item[3] hscore = new_item[4] gameclock = new_item[5] current_period = new_item[6] desc = new_item[7] headshot = new_item[8] notify_mode = '' if new_item[5].upper().find('FINAL') != -1: #Highlight score of the winning team notify_mode = 'final' title = 'Final Score' if int(ascore) > int(hscore): message = '[COLOR=' + SCORE_COLOR + ']' + ateam + ' ' + ascore + '[/COLOR] ' + hteam + ' ' + hscore + ' [COLOR=' + GAMETIME_COLOR + ']' + gameclock + '[/COLOR]' else: message = ateam + ' ' + ascore + ' [COLOR=' + SCORE_COLOR + ']' + hteam + ' ' + hscore + '[/COLOR] [COLOR=' + GAMETIME_COLOR + ']' + gameclock + '[/COLOR]' elif new_item[6] != old_item[6]: #Notify user that the game has started / period has changed notify_mode = 'game' title = "Game Update" message = ateam + ' ' + ascore + ' ' + hteam + ' ' + hscore + ' [COLOR=' + GAMETIME_COLOR + ']' + current_period + ' has started[/COLOR]' else: #Highlight score for the team that just scored a goal notify_mode = 'score' if new_item[3] != old_item[3]: ascore = '[COLOR=' + SCORE_COLOR + ']' + new_item[ 3] + '[/COLOR]' if new_item[4] != old_item[4]: hscore = '[COLOR=' + SCORE_COLOR + ']' + new_item[ 4] + '[/COLOR]' if ADDON.getSetting(id="goal_desc") == 'false': title = 'Score Update' message = ateam + ' ' + ascore + ' ' + hteam + ' ' + hscore + ' [COLOR=' + GAMETIME_COLOR + ']' + gameclock + '[/COLOR]' else: title = ateam + ' ' + ascore + ' ' + hteam + ' ' + hscore + ' [COLOR=' + GAMETIME_COLOR + ']' + gameclock + '[/COLOR]' message = desc if ADDON.getSetting(id="score_updates") != 'false': dialog = xbmcgui.Dialog() img = nhl_logo #Get goal scorers head shot if notification is a score update if ADDON.getSetting( id="goal_desc" ) == 'true' and notify_mode == 'score' and headshot != '': img = headshot dialog.notification(title, message, img, display_milliseconds, False) sleep(display_seconds + 5) #if all games have finished for the night kill the thread if all_games_finished == 1 and ADDON.getSetting( id="score_updates") == 'true': ADDON.setSetting(id='score_updates', value='false') #If the user is watching a game don't display the all games finished message if 'nhl_game_video' not in video_playing: dialog = xbmcgui.Dialog() title = "Score Notifications" dialog.notification(title, 'All games have ended, good night.', nhl_logo, 5000, False) OLD_GAME_STATS = [] OLD_GAME_STATS = NEW_GAME_STATS FIRST_TIME_THRU = 0 #sleep(int(60)) #sleep(int(wait)) #If kodi exits break out of loop if monitor.waitForAbort(wait): xbmc.log("**************Abort Called**********************") break
def player_loop(player, is_transcoded, is_transcode_finished, ep_id, party_mode): try: monitor = xbmc.Monitor() # seek to beginning of stream :hack: https://github.com/peak3d/inputstream.adaptive/issues/94 if is_transcoded: while not xbmc.Player().isPlayingVideo(): monitor.waitForAbort(0.25) if not is_transcode_finished: if xbmc.Player().isPlayingVideo(): log('Seek back - so the stream is from beginning') # TODO part1: hack is temporary and not working in 100% # TODO part2: (with small segments + fast cpu, you wont start from 1st segment) #xbmc.executebuiltin('Seek(-60)') xbmc.executeJSONRPC( '{"jsonrpc":"2.0","method":"Player.Seek","params":{"playerid":1,"value":{"seconds":0}},"id":1}' ) while player.PlaybackStatus != PlaybackStatus.STOPPED and player.PlaybackStatus != PlaybackStatus.ENDED: xbmc.sleep(500) if player.PlaybackStatus == PlaybackStatus.STOPPED or player.PlaybackStatus == PlaybackStatus.ENDED: log('Playback Ended - Shutting Down: ', monitor.abortRequested()) if player.is_finished: log('post-finish: start events') if ep_id != 0: from shoko_models.v2 import Episode ep = Episode(ep_id, build_full_object=False) spam('mark as watched, episode') ep.set_watched_status(True) # wait till directory is loaded while kodi_utils.is_dialog_active(): xbmc.sleep(500) # refresh it, so it moves onto next item and the mark watched is refreshed kodi_utils.refresh() # wait till it load again while kodi_utils.is_dialog_active(): xbmc.sleep(500) if int(ep_id) != 0 and plugin_addon.getSetting( 'vote_always') == 'true' and not party_mode: spam('vote_always, voting on episode') script_utils.vote_for_episode(ep_id) if int(ep_id) != 0 and plugin_addon.getSetting( 'vote_on_series') == 'true' and not party_mode: from shoko_models.v2 import get_series_for_episode series = get_series_for_episode(ep_id) # voting should be only when you really watch full series spam('vote_on_series, mark: %s / %s' % (series.sizes.watched_episodes, series.sizes.total_episodes)) if series.sizes.watched_episodes - series.sizes.total_episodes == 0: script_utils.vote_for_series(series.id) return -1 else: log( 'Playback Ended - Playback status was not "Stopped" or "Ended". It was ', player.PlaybackStatus) return 0 except: eh.exception(ErrorPriority.HIGHEST) return -1
def sleep(sec): if xbmc.Monitor().waitForAbort(sec): Log('Abort requested - exiting addon') sys.exit()
def play_item(self, video_id, video_type): try: stream = self.d.get_stream(video_id, video_type) # DRM enabled = use Widevine (Live TV, live sport and aired sport events) if stream['drm_enabled']: is_helper = inputstreamhelper.Helper('mpd', drm='com.widevine.alpha') if is_helper.check_inputstream(): playitem = xbmcgui.ListItem(path=stream['mpd_url']) # Kodi 19 Matrix or higher if self.get_kodi_version() >= '19': playitem.setProperty('inputstream', 'inputstream.adaptive') # Kodi 18 Leia else: playitem.setProperty('inputstreamaddon', 'inputstream.adaptive') playitem.setProperty('inputstream.adaptive.manifest_type', 'mpd') playitem.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') header = 'PreAuthorization=' + stream['drm_token'] playitem.setProperty( 'inputstream.adaptive.license_key', stream['license_url'] + '|' + header + '|R{SSM}|') else: playitem = xbmcgui.ListItem(path=stream['hls_url']) # Kodi 19 Matrix or higher if self.get_kodi_version() >= '19': playitem.setProperty('inputstream', 'inputstream.adaptive') # Inputstream Adaptive 2.6.1 added support for WEBVTT subtitles over HLS (Kodi 19) # Use addons WEBVTT to SRT converter for older IA versions if self.get_ia_version() < '261': playitem.setSubtitles( self.d.get_subtitles(stream['hls_url'], video_id)) # Kodi 18 Leia else: playitem.setProperty('inputstreamaddon', 'inputstream.adaptive') # Inputstream Adaptive 2.4.6 added support for WEBVTT subtitles over HLS (Kodi 18) # Use addons WEBVTT to SRT converter for older IA versions if self.get_ia_version() < '246': playitem.setSubtitles( self.d.get_subtitles(stream['hls_url'], video_id)) # Have to use hls for shows because mpd encryption type 'clearkey' is not supported by inputstream.adaptive playitem.setProperty('inputstream.adaptive.manifest_type', 'hls') # Get metadata to use for Up next only in episodes and clips (can also be aired sport events) if video_type == 'EPISODE' or video_type == 'CLIP': # Get current episode info current_episode = self.d.get_current_episode_info( video_id=video_id) images = list( filter(lambda x: x['type'] == 'image', current_episode['included'])) shows = list( filter(lambda x: x['type'] == 'show', current_episode['included'])) for s in shows: if s['id'] == current_episode['data']['relationships'][ 'show']['data']['id']: show_title = s['attributes']['name'] if current_episode['data']['relationships'].get('images'): for i in images: if i['id'] == current_episode['data']['relationships'][ 'images']['data'][0]['id']: fanart_image = i['attributes']['src'] else: fanart_image = None duration = current_episode['data']['attributes'][ 'videoDuration'] / 1000.0 if current_episode['data'][ 'attributes'].get('videoDuration') else None info = { 'mediatype': 'episode', 'title': current_episode['data']['attributes'].get('name').lstrip(), 'tvshowtitle': show_title, 'season': current_episode['data']['attributes'].get('seasonNumber'), 'episode': current_episode['data']['attributes'].get('episodeNumber'), 'plot': current_episode['data']['attributes'].get('description'), 'duration': duration, 'aired': current_episode['data']['attributes'].get('airDate') } playitem.setInfo('video', info) art = {'fanart': fanart_image, 'thumb': fanart_image} playitem.setArt(art) player = DplayPlayer() player.resolve(playitem) player.video_id = video_id player.current_episode_info = info player.current_episode_art = art monitor = xbmc.Monitor() while not monitor.abortRequested() and player.running: if player.isPlayingVideo(): player.video_totaltime = player.getTotalTime() player.video_lastpos = player.getTime() xbmc.sleep(1000) # Live TV else: xbmcplugin.setResolvedUrl(self.handle, True, listitem=playitem) except self.d.DplayError as error: self.dialog('ok', self.language(30006), error.value)
def get_sensor_data(self, cookie): CS_KEY = "0a46G5m17Vrp4o4c" API_KEY = "afSbep8yjnZUjq3aL010jO15Sawj2VZfdYK8uY90uxq" VERSION = "1.41" USER_AGENT = self.ua_browser REQUEST_INFO = "12147" PRODUCT_SUB = "20030107" LANGUAGE = "en-US" ENGINE = "Gecko" PLUGIN_COUNT = "3" HEADLESS = "0" NEW_WINDOW = "0" SPAM_BOT = "0" AVAIL_WIDTH = "1920" AVAIL_HEIGHT = "1040" SCREEN_WIDTH = "1920" SCREEN_HEIGHT = "1080" WINDOW_WIDTH = "1920" WINDOW_HEIGHT = "937" WINDOW_OWIDTH = "1920" IS_IE = "0" DOC_MODE = "1" CHROME_WEB_STORE = "0" ON_LINE = "1" OPERA = "0" FIREFOX = "0" SAFARI = "0" RTC_SUPPORT = "1" WINDOW_TOP = "0" VIBRATION = "1" BATTERY = "1" FOR_EACH = "0" FILE_READER = "1" ORIENTATION = "do_en" MOTION = "dm_en" TOUCH = "t_en" INFORM_INFO = "" FORM_INFO = "" K_ACT = "" M_ACT = "" T_ACT = "" DO_ACT = "" DM_ACT = "" P_ACT = "" VC_ACT = "" AJ_TYPE = "0" AJ_INDEX = "0" MN_R = "" FP_VALUE = "-1" url = "https://id.sonyentertainmentnetwork.com/signin/#/signin?entry=%2Fsignin" signature = self.sign(CS_KEY, API_KEY) date_floor = int(math.floor(int(time.time() * 1000) / 36e5)) signature += self.sign(str(date_floor), signature) timestamp = int(time.time() * 1000) time_calc = int(timestamp / (2016 * 2016)) time_calc2 = int(timestamp % 1e7) time_calc3 = int(time_calc / 23) time_calc4 = int(time_calc3 / 6) xbmc.Monitor().waitForAbort(.25) time_calc5 = int(time.time() * 1000) - timestamp #xbmc.log("Dated Signature: %s" % signature) sensor_string = \ VERSION + "-1,2,-94,-100," + USER_AGENT + ",uaend," + REQUEST_INFO + "," + PRODUCT_SUB + "," + \ LANGUAGE + "," + ENGINE + "," + PLUGIN_COUNT + "," + HEADLESS + "," + NEW_WINDOW + "," + \ SPAM_BOT + "," + str(time_calc) + "," + str(time_calc2) + "," + AVAIL_WIDTH + "," + AVAIL_HEIGHT + \ "," + SCREEN_WIDTH + "," + SCREEN_HEIGHT + "," + WINDOW_WIDTH + "," + WINDOW_HEIGHT + "," + \ WINDOW_OWIDTH + ",,cpen:" + HEADLESS + ",i1:" + IS_IE + ",dm:" + DOC_MODE + ",cwen:" + \ CHROME_WEB_STORE + ",non:" + ON_LINE + ",opc:" + OPERA + ",fc:" + FIREFOX + ",sc:" + SAFARI + \ ",wrc:" + RTC_SUPPORT + ",isc:" + WINDOW_TOP + ",vib:" + VIBRATION + ",bat:" + BATTERY + ",x11:" + \ FOR_EACH + ",x12:" + FILE_READER + "," + str(self.txt_func(USER_AGENT)) + "," + str(random.random())[0:13] + \ "," + str(timestamp / 2) + ",loc:" + "-1,2,-94,-101" + "," + ORIENTATION + "," + MOTION + "," + \ TOUCH + "-1,2,-94,-105," + INFORM_INFO + "-1,2,-94,-102," + FORM_INFO + "-1,2,-94,-108," + \ K_ACT + "-1,2,-94,-110," + M_ACT + "-1,2,-94,-117," + T_ACT + "-1,2,-94,-111," + DO_ACT + \ "-1,2,-94,-109," + DM_ACT + "-1,2,-94,-114," + P_ACT + "-1,2,-94,-103," + VC_ACT + \ "-1,2,-94,-112," + url + "-1,2,-94,-115," + "1,1,0,0,0,0,0,1,0," + str(timestamp) + ",-999999," + \ str(time_calc3) + "," + "0," + "0," + str(time_calc4) + ",0" + ",0" + "," + str(time_calc5) + \ ",0" + ",0" + "," + cookie + "," + str(self.txt_func(cookie)) + ",-1" + ",-1" + ",30261693" + \ "-1,2,-94,-106," + AJ_TYPE + "," + AJ_INDEX + "-1,2,-94,-119," + "-1" + \ "-1,2,-94,-122," + "0,0,0,0,1,0,0" + "-1,2,-94,-123," + MN_R txt_val = self.txt_func(sensor_string) sensor_string += "-1,2,-94,-70," + FP_VALUE + "-1,2,-94,-80," + \ str(self.txt_func(FP_VALUE)) + "-1,2,-94,-116," + str(self.time_func(time_calc2)) + \ "-1,2,-94,-118," + str(txt_val) + "-1,2,-94,-121," sensor_string = signature + sensor_string + ";" + str( int(time.time() * 1000) - timestamp) + ";-1;0" sensor_string = '{"sensor_data":"' + sensor_string + '"}' #xbmc.log("Sensor String:\n%s" % sensor_string) return sensor_string
from datetime import datetime, timedelta update = getConfig('update_running', 'false') if update != 'false': starttime = strp(update, '%Y-%m-%d %H:%M') if (starttime + timedelta(hours=6)) <= datetime.today(): writeConfig('update_running', 'false') Log('DB Cancel update - duration > 6 hours') else: Log('DB Update already running', xbmc.LOGDEBUG) return True return False if __name__ == '__main__': addon = xbmcaddon.Addon() monitor = xbmc.Monitor() Log('AmazonDB: Service Start') writeConfig('update_running', 'false') freq = int('0' + var.addon.getSetting('auto_update')) checkfreq = 60 idleupdate = 300 startidle = 0 if freq: while not monitor.abortRequested(): from datetime import datetime, timedelta today = datetime.today() freq = var.addon.getSetting('auto_update') time = var.addon.getSetting('update_time') time = '00:00' if time == '' else time last = getConfig('last_update', '1970-01-01')
import hashlib, binascii from xml.dom import minidom import imp from xbmc import LOGDEBUG, LOGINFO, LOGWARNING, LOGERROR __author__ = 'LibreELEC' __scriptid__ = 'service.libreelec.settings' __addon__ = xbmcaddon.Addon(id=__scriptid__) __cwd__ = __addon__.getAddonInfo('path') __oe__ = sys.modules[globals()['__name__']] __media__ = f'{__cwd__}/resources/skins/Default/media' xbmcDialog = xbmcgui.Dialog() xbmcm = xbmc.Monitor() is_service = False conf_lock = False xbmcIsPlaying = 0 input_request = False dictModules = {} listObject = { 'list': 1100, 'netlist': 1200, 'btlist': 1300, 'other': 1900, 'test': 900, } CANCEL = ( 9,