def play(url, xlistitem, is_view=None, subtitle=""): # -- Necesario para algunas webs ---------------------------- if not url.endswith(".torrent") and not url.startswith("magnet"): t_file = scrapertools.get_header_from_response( url, header_to_get="location") if len(t_file) > 0: url = t_file t_file = scrapertools.get_header_from_response( url, header_to_get="location") if len(t_file) > 0: url = t_file # -- Crear dos carpetas en descargas para los archivos ------ save_path_videos = os.path.join(config.get_setting("downloadpath"), "torrent-videos") save_path_torrents = os.path.join(config.get_setting("downloadpath"), "torrent-torrents") if not os.path.exists(save_path_torrents): os.mkdir(save_path_torrents) # -- Usar - archivo torrent desde web, meagnet o HD --------- if not os.path.isfile(url) and not url.startswith("magnet"): # -- http - crear archivo torrent ----------------------- data = url_get(url) # -- El nombre del torrent será el que contiene en los -- # -- datos. - re_name = urllib.unquote( scrapertools.get_match(data, ':name\d+:(.*?)\d+:')) torrent_file = filetools.join(save_path_torrents, filetools.encode(re_name + '.torrent')) f = open(torrent_file, 'wb') f.write(data) f.close() elif os.path.isfile(url): # -- file - para usar torrens desde el HD --------------- torrent_file = url else: # -- magnet --------------------------------------------- torrent_file = url # ----------------------------------------------------------- # -- MCT - MiniClienteTorrent ------------------------------- ses = lt.session() print "### Init session ########" print lt.version print "#########################" ses.add_dht_router("router.bittorrent.com", 6881) ses.add_dht_router("router.utorrent.com", 6881) ses.add_dht_router("router.bitcomet.com", 554) ses.add_dht_router("dht.transmissionbt.com", 6881) trackers = [ "http://exodus.desync.com:6969/announce", "udp://tracker.publicbt.com:80/announce", "udp://tracker.openbittorrent.com:80/announce", "http://tracker.torrentbay.to:6969/announce", "http://fr33dom.h33t.com:3310/announce", "http://tracker.pow7.com/announce", "udp://tracker.ccc.de:80/announce", "http://tracker.bittorrent.am:80/announce", "http://denis.stalker.h3q.com:6969/announce", "udp://tracker.prq.to:80/announce", "udp://tracker.istole.it:80/announce", "udp://open.demonii.com:1337", "http://9.rarbg.com:2710/announce", "http://announce.torrentsmd.com:6969/announce", "http://bt.careland.com.cn:6969/announce", "http://explodie.org:6969/announce", "http://mgtracker.org:2710/announce", "http://tracker.best-torrents.net:6969/announce", "http://tracker.tfile.me/announce", "http://tracker.torrenty.org:6969/announce", "http://tracker1.wasabii.com.tw:6969/announce", "udp://9.rarbg.com:2710/announce", "udp://9.rarbg.me:2710/announce", "udp://coppersurfer.tk:6969/announce", "udp://tracker.btzoo.eu:80/announce", "http://www.spanishtracker.com:2710/announce", "http://www.todotorrents.com:2710/announce", ] video_file = "" # -- magnet2torrent ----------------------------------------- if torrent_file.startswith("magnet"): try: tempdir = tempfile.mkdtemp() except IOError: tempdir = os.path.join(save_path_torrents, "temp") if not os.path.exists(tempdir): os.mkdir(tempdir) params = { 'save_path': tempdir, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_allocate, 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } h = lt.add_magnet_uri(ses, torrent_file, params) dp = xbmcgui.DialogProgress() dp.create('pelisalacarta-MCT') while not h.has_metadata(): message, porcent, msg_file, s, download = getProgress( h, "Creando torrent desde magnet") dp.update(porcent, message, msg_file) if s.state == 1: download = 1 if dp.iscanceled(): dp.close() remove_files(download, torrent_file, video_file, ses, h) return dp.close() info = h.get_torrent_info() data = lt.bencode(lt.create_torrent(info).generate()) #torrent_file = os.path.join(save_path_torrents, info.name() + ".torrent") torrent_file = os.path.join( save_path_torrents, unicode(info.name(), "'utf-8'", errors="replace") + ".torrent") f = open(torrent_file, 'wb') f.write(data) f.close() ses.remove_torrent(h) shutil.rmtree(tempdir) # ----------------------------------------------------------- # -- Archivos torrent --------------------------------------- e = lt.bdecode(open(torrent_file, 'rb').read()) info = lt.torrent_info(e) # -- El más gordo o uno de los más gordo se entiende que es - # -- el vídeo o es el vídeo que se usará como referencia - # -- para el tipo de archivo - print "##### Archivos ## %s ##" % len(info.files()) _index_file, _video_file, _size_file = get_video_file(info) _video_file_ext = os.path.splitext(_video_file)[1] if _video_file_ext == ".avi" or _video_file_ext == ".mp4": print "##### storage_mode_t.storage_mode_allocate (" + _video_file_ext + ") #####" h = ses.add_torrent({ 'ti': info, 'save_path': save_path_videos, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_allocate }) else: print "##### storage_mode: none (" + _video_file_ext + ") #####" h = ses.add_torrent({ 'ti': info, 'save_path': save_path_videos, 'trackers': trackers, 'storage_mode': lt.storage_mode_t.storage_mode_sparse }) # ----------------------------------------------------------- # -- Descarga secuencial - trozo 1, trozo 2, ... ------------ h.set_sequential_download(True) h.force_reannounce() h.force_dht_announce() # -- Prioritarizar/Seleccionar archivo----------------------- _index, video_file, video_size = get_video_files_sizes(info) if _index == -1: _index = _index_file video_file = _video_file video_size = _size_file # -- Inicio de variables para 'pause' automático cuando el - # -- el vídeo se acerca a una pieza sin completar - is_greater_num_pieces = False is_greater_num_pieces_plus = False is_greater_num_pieces_pause = False #porcent4first_pieces = int( video_size / 1073741824 ) porcent4first_pieces = int(video_size * 0.000000005) if porcent4first_pieces < 10: porcent4first_pieces = 10 if porcent4first_pieces > 100: porcent4first_pieces = 100 #num_pieces_to_resume = int( video_size / 1610612736 ) num_pieces_to_resume = int(video_size * 0.0000000025) if num_pieces_to_resume < 5: num_pieces_to_resume = 5 if num_pieces_to_resume > 25: num_pieces_to_resume = 25 print "##### porcent4first_pieces ## %s ##" % porcent4first_pieces print "##### num_pieces_to_resume ## %s ##" % num_pieces_to_resume # -- Prioritarizar o seleccionar las piezas del archivo que - # -- se desea reproducir con 'file_priorities' - piece_set = set_priority_pieces(h, _index, video_file, video_size) # -- Crear diálogo de progreso para el primer bucle --------- dp = xbmcgui.DialogProgress() dp.create('pelisalacarta-MCT') _pieces_info = {} # -- Doble bucle anidado ------------------------------------ # -- Descarga - Primer bucle - while not h.is_seed(): s = h.status() xbmc.sleep(100) # -- Recuperar los datos del progreso ------------------- message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info) # -- Si hace 'checking' existe descarga ----------------- # -- 'download' Se usará para saber si hay datos - # -- descargados para el diálogo de 'remove_files' - if s.state == 1: download = 1 # -- Player - play -------------------------------------- # -- Comprobar si se han completado las piezas para el - # -- inicio del vídeo ............... - first_pieces = True _p = "" _c = 0 for i in range(piece_set[0], piece_set[porcent4first_pieces]): _p += "[%s:%s]" % (i, h.have_piece(i)) first_pieces &= h.have_piece(i) if h.have_piece(i): _c += 1 _pieces_info = { 'current': 0, 'continuous': "%s/%s" % (_c, porcent4first_pieces), 'have': h.status().num_pieces, 'len': len(piece_set) } _p = "##### first_pieces [%s/%s][%s]: " % (_c, porcent4first_pieces, len(piece_set)) + _p print _p # -- -------------------------------------------------- - if is_view != "Ok" and first_pieces: print "##### porcent [%.2f%%]" % (s.progress * 100) is_view = "Ok" dp.close() # -- Player - Ver el vídeo -------------------------- playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() #ren_video_file = os.path.join( save_path_videos, video_file ).replace('\\','\\\\') ren_video_file = os.path.join(save_path_videos, video_file) playlist.add(ren_video_file, xlistitem) #playlist.add( os.path.join( save_path_videos, video_file ), xlistitem ) #playlist.add( "http://192.168.0.200/mctplay/" + video_file.replace(' ','%20'), xlistitem ) player = play_video(xbmc.PLAYER_CORE_AUTO) player.play(playlist) ''' # -- Player - Ver el vídeo -------------------------- player = play_video() #player.play( os.path.join( save_path_videos, video_file ) ) player.play( "http://192.168.0.200/mctplay/" + video_file.replace(' ','%20') ) ''' #player.play( os.path.join( save_path_videos, video_file ) ) # -- Contador de cancelaciones para la ventana de - # -- 'pause' automático - is_greater_num_pieces_canceled = 0 continuous_pieces = 0 porcent_time = 0.00 current_piece = 0 # -- Impedir que kodi haga 'resume' a un archivo ---- # -- que se reprodució con anterioridad y que se - # -- eliminó para impedir que intente la reprucción - # -- en una pieza que aún no se ha completado y se - # -- active 'pause' automático - not_resume = True # -- Bandera subTítulos _sub = False # -- Segundo bucle - Player - Control de eventos ---- while player.isPlaying(): xbmc.sleep(100) # -- Añadir subTítulos if subtitle != "" and not _sub: _sub = True player.setSubtitles(subtitle) # -- Impedir que kodi haga 'resume' al inicio --- # -- de la descarga de un archivo conocido - if not_resume: player.seekTime(0) not_resume = False #xbmc.sleep(1000) # -- Control 'pause' automático - continuous_pieces = count_completed_continuous_pieces( h, piece_set) if xbmc.Player().isPlaying(): # -- Porcentage del progreso del vídeo ------ porcent_time = player.getTime() / player.getTotalTime( ) * 100 # -- Pieza que se está reproduciendo -------- current_piece = int(porcent_time / 100 * len(piece_set)) # -- Banderas de control -------------------- is_greater_num_pieces = ( current_piece > continuous_pieces - num_pieces_to_resume) is_greater_num_pieces_plus = ( current_piece + porcent4first_pieces > continuous_pieces) is_greater_num_pieces_finished = ( current_piece + porcent4first_pieces >= len(piece_set)) # -- Activa 'pause' automático -------------- if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished: is_greater_num_pieces_pause = True player.pause() # -- Log ------------------------------------ _TotalTime = player.getTotalTime() _Time = player.getTime() _print_log = "\n##### Player ##################################" _print_log += "\nTamaño del vídeo: %s" % video_size _print_log += "\nTotal piezas: %s" % len(piece_set) _print_log += "\nPiezas contiguas: %s" % continuous_pieces _print_log += "\n-----------------------------------------------" _print_log += "\nVídeo-Total segundos: %s" % _TotalTime _print_log += "\nVídeo-Progreso segundos: %s" % _Time _print_log += "\nVídeo-Progreso porcentaje: %.2f%%" % porcent_time _print_log += "\n-----------------------------------------------" _print_log += "\ncurrent_piece: %s" % current_piece _print_log += "\nis_greater_num_pieces: %s" % is_greater_num_pieces _print_log += "\nis_greater_num_pieces_plus: %s" % is_greater_num_pieces_plus _print_log += "\nis_greater_num_pieces_pause: %s" % is_greater_num_pieces_pause _print_log += "\nis_greater_num_pieces_finished: %s" % is_greater_num_pieces_finished _print_log += "\nPieza que se está visionando: %.2f" % ( porcent_time / 100 * len(piece_set)) _print_log += "\nOffset que se está visionando: %.2f" % ( porcent_time / 100 * video_size) if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished: _print_log += "\n+++++++++++++++++++++++++++++++++++++++++++++++" _print_log += "\nPausa con:" _print_log += "\n current_piece = %s" % current_piece _print_log += "\n continuous_pieces = %s" % continuous_pieces _print_log += "\n###############################################" print _print_log # ------------------------------------------- _pieces_info = { 'current': current_piece, 'continuous': continuous_pieces, 'have': h.status().num_pieces, 'len': len(piece_set) } # -- Cerrar el diálogo de progreso -------------- if player.resumed: dp.close() # -- Mostrar el diálogo de progreso ------------- if player.paused: # -- Crear diálogo si no existe ------------- if not player.statusDialogoProgress: dp = xbmcgui.DialogProgress() dp.create('pelisalacarta-MCT') player.setDialogoProgress() # -- Diálogos de estado en el visionado ----- if not h.is_seed(): # -- Recuperar los datos del progreso --- message, porcent, msg_file, s, download = getProgress( h, video_file, _pf=_pieces_info) dp.update(porcent, message, msg_file) else: dp.update(100, "Descarga completa: " + video_file) # -- Se canceló el progreso en el visionado - # -- Continuar - if dp.iscanceled(): dp.close() player.pause() # -- Se canceló el progreso en el visionado - # -- en la ventana de 'pause' automático. - # -- Parar si el contador llega a 3 - if dp.iscanceled() and is_greater_num_pieces_pause: is_greater_num_pieces_canceled += 1 if is_greater_num_pieces_canceled == 3: player.stop() # -- Desactiva 'pause' automático y --------- # -- reinicia el contador de cancelaciones - if not dp.iscanceled( ) and not is_greater_num_pieces_plus and is_greater_num_pieces_pause: dp.close() player.pause() is_greater_num_pieces_pause = False is_greater_num_pieces_canceled = 0 # -- El usuario cancelo el visionado -------- # -- Terminar - if player.ended: # -- Diálogo eliminar archivos ---------- remove_files(download, torrent_file, video_file, ses, h) return # -- Kodi - Se cerró el visionado ----------------------- # -- Continuar | Terminar - if is_view == "Ok" and not xbmc.Player().isPlaying(): if info.num_files() == 1: # -- Diálogo continuar o terminar --------------- d = xbmcgui.Dialog() ok = d.yesno('pelisalacarta-MCT', 'XBMC-Kodi Cerró el vídeo.', '¿Continuar con la sesión?') else: ok = False # -- SI --------------------------------------------- if ok: # -- Continuar: --------------------------------- is_view = None else: # -- Terminar: ---------------------------------- # -- Comprobar si el vídeo pertenece a una ------ # -- lista de archivos - _index, video_file, video_size = get_video_files_sizes(info) if _index == -1 or info.num_files() == 1: # -- Diálogo eliminar archivos -------------- remove_files(download, torrent_file, video_file, ses, h) return else: # -- Lista de archivos. Diálogo de opciones - piece_set = set_priority_pieces(h, _index, video_file, video_size) is_view = None dp = xbmcgui.DialogProgress() dp.create('pelisalacarta-MCT') # -- Mostar progeso antes del visionado ----------------- if is_view != "Ok": dp.update(porcent, message, msg_file) # -- Se canceló el progreso antes del visionado --------- # -- Terminar - if dp.iscanceled(): dp.close() # -- Comprobar si el vídeo pertenece a una lista de - # -- archivos - _index, video_file, video_size = get_video_files_sizes(info) if _index == -1 or info.num_files() == 1: # -- Diálogo eliminar archivos ------------------ remove_files(download, torrent_file, video_file, ses, h) return else: # -- Lista de archivos. Diálogo de opciones ----- piece_set = set_priority_pieces(h, _index, video_file, video_size) is_view = None dp = xbmcgui.DialogProgress() dp.create('pelisalacarta-MCT') # -- Kodi - Error? - No debería llegar aquí ----------------- if is_view == "Ok" and not xbmc.Player().isPlaying(): dp.close() # -- Diálogo eliminar archivos -------------------------- remove_files(download, torrent_file, video_file, ses, h) return
def run_internal(self): dialog = xbmcgui.Dialog() startupComplete = False log.warn("---===### Starting LibrarySync ###===---") # Verify database structure, otherwise create it. self._verify_emby_database() while not self.monitor.abortRequested(): # In the event the server goes offline while self.suspend_thread: # Set in service.py if self.monitor.waitForAbort(5): # Abort was requested while waiting. We should exit break if (window('emby_dbCheck') != "true" and settings('SyncInstallRunDone') == "true"): # Verify the validity of the database embyconn = utils.kodiSQL('emby') embycursor = embyconn.cursor() emby_db = embydb.Embydb_Functions(embycursor) currentVersion = emby_db.get_version() ###$ Begin migration $### if not currentVersion: currentVersion = emby_db.get_version( settings('dbCreatedWithVersion') or self.clientInfo.get_version()) embyconn.commit() log.info("Migration of database version completed") ###$ End migration $### embycursor.close() window('emby_version', value=currentVersion) minVersion = window('emby_minDBVersion') uptoDate = self.compareDBVersion(currentVersion, minVersion) if not uptoDate: log.warn( "Database version out of date: %s minimum version required: %s" % (currentVersion, minVersion)) resp = dialog.yesno(lang(29999), lang(33022)) if not resp: log.warn( "Database version is out of date! USER IGNORED!") dialog.ok(lang(29999), lang(33023)) else: utils.reset() break window('emby_dbCheck', value="true") if not startupComplete: # Verify the video database can be found videoDb = utils.getKodiVideoDBPath() if not xbmcvfs.exists(videoDb): # Database does not exists log.error("The current Kodi version is incompatible " "with the Emby for Kodi add-on. Please visit " "https://github.com/MediaBrowser/Emby.Kodi/wiki " "to know which Kodi versions are supported.") dialog.ok(heading=lang(29999), line1=lang(33024)) break # Run start up sync log.warn("Database version: %s", window('emby_version')) log.info("SyncDatabase (started)") startTime = datetime.now() librarySync = self.startSync() elapsedTime = datetime.now() - startTime log.info("SyncDatabase (finished in: %s) %s" % (str(elapsedTime).split('.')[0], librarySync)) # Add other servers at this point # TODO: re-add once plugin listing is created # self.user.load_connect_servers() # Only try the initial sync once per kodi session regardless # This will prevent an infinite loop in case something goes wrong. startupComplete = True # Process updates if window('emby_dbScan') != "true" and window( 'emby_shouldStop') != "true": self.incrementalSync() if window('emby_onWake') == "true" and window( 'emby_online') == "true": # Kodi is waking up # Set in kodimonitor.py window('emby_onWake', clear=True) if window('emby_syncRunning') != "true": log.info("SyncDatabase onWake (started)") librarySync = self.startSync() log.info("SyncDatabase onWake (finished) %s" % librarySync) if self.stop_thread: # Set in service.py log.debug("Service terminated thread.") break if self.monitor.waitForAbort(1): # Abort was requested while waiting. We should exit break log.warn("###===--- LibrarySync Stopped ---===###")
def widget_selectdialog(filter=None, string_prefix="widget"): """ show dialog including all video media lists (for widget selection) and set strings PREFIX.path and PREFIX.label with chosen values """ movie = { "intheaters": "%s [I](RottenTomatoes)[/I]" % LANG(32042), "boxoffice": "%s [I](RottenTomatoes)[/I]" % LANG(32055), "opening": "%s [I](RottenTomatoes)[/I]" % LANG(32048), "comingsoon": "%s [I](RottenTomatoes)[/I]" % LANG(32043), "toprentals": "%s [I](RottenTomatoes)[/I]" % LANG(32056), "currentdvdreleases": "%s [I](RottenTomatoes)[/I]" % LANG(32049), "newdvdreleases": "%s [I](RottenTomatoes)[/I]" % LANG(32053), "upcomingdvds": "%s [I](RottenTomatoes)[/I]" % LANG(32054), # tmdb "incinemas": "%s [I](TheMovieDB)[/I]" % LANG(32042), "upcoming": "%s [I](TheMovieDB)[/I]" % LANG(32043), "topratedmovies": "%s [I](TheMovieDB)[/I]" % LANG(32046), "popularmovies": "%s [I](TheMovieDB)[/I]" % LANG(32044), "accountlists": "%s [I](TheMovieDB)[/I]" % LANG(32045), # trakt "trendingmovies": "%s [I](Trakt.tv)[/I]" % LANG(32047), # tmdb "starredmovies": "%s [I](TheMovieDB)[/I]" % LANG(32134), "ratedmovies": "%s [I](TheMovieDB)[/I]" % LANG(32135), } tvshow = { "airingshows": "%s [I](Trakt.tv)[/I]" % LANG(32028), "premiereshows": "%s [I](Trakt.tv)[/I]" % LANG(32029), "trendingshows": "%s [I](Trakt.tv)[/I]" % LANG(32032), "airingtodaytvshows": "%s [I](TheMovieDB)[/I]" % LANG(32038), "onairtvshows": "%s [I](TheMovieDB)[/I]" % LANG(32039), "topratedtvshows": "%s [I](TheMovieDB)[/I]" % LANG(32040), "populartvshows": "%s [I](TheMovieDB)[/I]" % LANG(32041), "starredtvshows": "%s [I](TheMovieDB)[/I]" % LANG(32144), "ratedtvshows": "%s [I](TheMovieDB)[/I]" % LANG(32145), } image = { "xkcd": "XKCD webcomics", "cyanide": "Cyanide & Happiness webcomics", "dailybabe": "%s" % LANG(32057), "dailybabes": "%s" % LANG(32058), } # popularpeople artist = { "topartists": "LastFM: Top artists", "hypedartists": "LastFM: Hyped artists" } event = {} if True: listitems = merge_dicts(movie, tvshow, image, artist, event) keywords = [key for key in listitems.keys()] labels = [label for label in listitems.values()] ret = xbmcgui.Dialog().select(LANG(32151), labels) if ret > -1: notify(keywords[ret]) xbmc.executebuiltin( "Skin.SetString(%s.path,plugin://script.extendedinfo?info=%s)" % (string_prefix, keywords[ret])) xbmc.executebuiltin("Skin.SetString(%s.label,%s)" % (string_prefix, labels[ret]))
def show_info_notification(message, duration=3000): xbmcgui.Dialog().notification(ADDON_NAME, message, xbmcgui.NOTIFICATION_INFO, duration, False)
def checkPreviousEpisode(): global player_monitor ignoredShows = getIgnoredShowsFromConfig() log('Playback started!') command = '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}' jsonobject = json.loads(xbmc.executeJSONRPC(command)) log(str(jsonobject)) # Only do something is we get a result for our query back from Kodi if (len(jsonobject['result']) == 1): resultitem = jsonobject['result'][0] log("Player running with ID: %d" % resultitem['playerid']) command = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": { "playerid": %d }, "id": 1}' % resultitem[ 'playerid'] jsonobject = json.loads(xbmc.executeJSONRPC(command)) log(str(jsonobject)) # Only do something is this is an episode of a TV show if jsonobject['result']['item']['type'] == 'episode': log("An Episode is playing!") command = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": { "episodeid": %d, "properties": ["tvshowid", "showtitle", "season", "episode"] }, "id": 1}' % ( jsonobject['result']['item']['id']) jsonobject = json.loads(xbmc.executeJSONRPC(command)) log(str(jsonobject)) # Only do something if we can get the episode details from Kodi if (len(jsonobject['result']) == 1): playingTvshowid = jsonobject['result']['episodedetails'][ 'tvshowid'] playingTvshowTitle = jsonobject['result']['episodedetails'][ 'showtitle'] playingSeason = jsonobject['result']['episodedetails'][ 'season'] playingEpisode = jsonobject['result']['episodedetails'][ 'episode'] log("Playing Info: SHOWTITLE '%s', TVSHOWID '%d', SEASON: '%d', EPISODE: '%d'" % (playingTvshowTitle, playingTvshowid, playingSeason, playingEpisode)) # Ignore first episodes... if (jsonobject['result']['episodedetails']['episode'] > 1): command = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "tvshowid": %d, "season": %d, "properties": ["episode", "playcount"] }, "id": 1}' % ( jsonobject['result']['episodedetails']['tvshowid'], jsonobject['result']['episodedetails']['season']) jsonobject = json.loads(xbmc.executeJSONRPC(command)) log(str(jsonobject)) # We found some episodes for this show... if (len(jsonobject['result']) > 0): found = False playcount = 0 for episode in jsonobject['result']['episodes']: if (episode['episode'] == (playingEpisode - 1)): playcount += episode['playcount'] found = True log("Found: " + str(found) + " playcount: " + str(playcount) + " setting IgnoreIfEpisodeAbsentFromLibrary " + str(getSetting("IgnoreIfEpisodeAbsentFromLibrary")) ) if (not found and getSettingAsBoolean( "IgnoreIfEpisodeAbsentFromLibrary") != True ) or (found and playcount == 0): if playingTvshowid in ignoredShows: log("Unplayed previous episode detected, but show set to ignore: " + playingTvshowTitle) else: # Only trigger the pause if the player is actually playing as other addons may also have paused the player if not isPlaybackPaused(): log("Pausing playback") player_monitor.pause() result = xbmcgui.Dialog().select( __language__(32020), [ __language__(32021), __language__(32022), __language__(32023) ], preselect=0) # User has requested we ignore this particular show from now on... if result == 2: writeIgnoredShowsToConfig( ignoredShows, playingTvshowTitle, playingTvshowid) if (result == 1 or result == 2): if isPlaybackPaused(): log("Unpausing playback") player_monitor.pause() else: player_monitor.stop() if (getSettingAsBoolean( "ForceBrowseForShow") == True): # Jump to this shows Episode in the Kodi library command = '{"jsonrpc": "2.0", "method": "GUI.ActivateWindow", "params": { "window": "videos", "parameters": [ "videodb://2/2/%d/%d" ] }, "id": 1}' % ( playingTvshowid, playingSeason) xbmc.executeJSONRPC(command)
def on_arm_unsync(self, myo, timestamp): """ Called when a Myo armband and an arm is unsynced. """ dialog = xbmcgui.Dialog() dialog.notification("Attention", "Myo unsynced")
def print_notification(json_data): event_string = docker_events[json_data['Type']]['event'][ json_data['Action']]['string'] if __addon__.getSetting('notifications') is '0': # default if docker_events[json_data['Type']]['event'][ json_data['Action']]['enabled']: try: message = unicode(' '.join([ __addon__.getLocalizedString(30010), json_data['Actor']['Attributes']['name'], '|', __addon__.getLocalizedString(30012), __addon__.getLocalizedString(event_string) ])) except KeyError as e: message = unicode(' '.join([ __addon__.getLocalizedString(30011), json_data['Type'], '|', __addon__.getLocalizedString(30012), __addon__.getLocalizedString(event_string) ])) elif __addon__.getSetting('notifications') is '1': # all try: message = unicode(' '.join([ __addon__.getLocalizedString(30010), json_data['Actor']['Attributes']['name'], '|', __addon__.getLocalizedString(30012), __addon__.getLocalizedString(event_string) ])) except KeyError as e: message = unicode(' '.join([ __addon__.getLocalizedString(30011), json_data['Type'], '|', __addon__.getLocalizedString(30012), __addon__.getLocalizedString(event_string) ])) elif __addon__.getSetting('notifications') is '2': # none pass elif __addon__.getSetting('notifications') is '3': # custom if __addon__.getSetting(json_data['Action']) == 'true': try: message = unicode(' '.join([ __addon__.getLocalizedString(30010), json_data['Actor']['Attributes']['name'], '|', __addon__.getLocalizedString(30012), __addon__.getLocalizedString(event_string) ])) except KeyError as e: message = unicode(' '.join([ __addon__.getLocalizedString(30011), json_data['Type'], '|', __addon__.getLocalizedString(30012), __addon__.getLocalizedString(event_string) ])) dialog = xbmcgui.Dialog() try: if message is not '': length = int(__addon__.getSetting('notification_length')) * 1000 dialog.notification( 'Docker', message, '/storage/.kodi/addons/service.system.docker/icon.png', length) xbmc.log('## service.system.docker ## ' + unicode(message)) except NameError as e: pass
def display_message(message, type='INFO'): # Possible types: INFO, WARNING, ERROR dialog = xbmcgui.Dialog() dialog.notification('Handover', message, getattr(xbmcgui, 'NOTIFICATION_' + type), 5000)
def GetSourceLocation(title, list): dialog = xbmcgui.Dialog() answer = dialog.select(title, list) return answer
def PlayVideo(url, title, thumb, Plot, sub_path=None, Merk='false'): PLog('PlayVideo:') PLog(url) PLog(title) PLog(Plot) PLog(sub_path) Plot = transl_doubleUTF8(Plot) li = xbmcgui.ListItem(path=url) li.setArt({'thumb': thumb, 'icon': thumb}) Plot = Plot.replace('||', '\n') # || Code für LF (\n scheitert in router) # li.setProperty('IsPlayable', 'true') # hier unwirksam li.setInfo(type="video", infoLabels={ "Title": title, "Plot": Plot, "mediatype": "video" }) # Info aus GetZDFVideoSources hierher verlagert - wurde von Kodi nach Videostart # erneut gezeigt - dto. für ARD (parseLinks_Mp4_Rtmp, ARDStartSingle) if sub_path: # Vorbehandlung ARD-Untertitel if 'ardmediathek.de' in sub_path: # ARD-Untertitel speichern + Endung -> .sub local_path = "%s/%s" % (SUBTITLESTORE, sub_path.split('/')[-1]) local_path = os.path.abspath(local_path) try: urllib.urlretrieve(sub_path, local_path) except Exception as exception: PLog(str(exception)) local_path = '' if local_path: sub_path = xml2srt(local_path) # leer bei Fehlschlag PLog('sub_path: ' + str(sub_path)) if sub_path: # Untertitel aktivieren, falls vorh. if SETTINGS.getSetting('pref_UT_Info') == 'true': msg1 = 'Info: für dieses Video stehen Untertitel zur Verfügung.' xbmcgui.Dialog().ok(ADDON_NAME, msg1, '', '') if SETTINGS.getSetting('pref_UT_ON') == 'true': sub_path = sub_path.split('|') li.setSubtitles(sub_path) xbmc.Player().showSubtitles(True) # Abfrage: ist gewählter Eintrag als Video deklariert? - Falls ja, # IsPlayable-Test # erfolgt der Aufruf indirekt (setResolvedUrl). Falls nein, # wird der Player direkt aufgerufen. Direkter Aufruf ohne IsPlayable-Eigenschaft # verhindert Resume-Funktion. # Mit xbmc.Player() ist die Unterscheidung Kodi V18/V17 nicht mehr erforderlich, # xbmc.Player().updateInfoTag bei Kodi V18 entfällt. # Die Player-Varianten PlayMedia + XBMC.PlayMedia scheitern bei Kommas in Url. # IsPlayable = xbmc.getInfoLabel( 'ListItem.Property(IsPlayable)') # 'true' / 'false' PLog("IsPlayable: %s, Merk: %s" % (IsPlayable, Merk)) PLog("kodi_version: " + KODI_VERSION) # Debug # kodi_version = re.search('(\d+)', KODI_VERSION).group(0) # Major-Version reicht hier - entfällt #if Merk == 'true': # entfällt bisher - erfordert # xbmc.Player().play(url, li, windowed=False) # eigene Resumeverwaltung # return if IsPlayable == 'true': # true xbmcplugin.setResolvedUrl(HANDLE, True, li) # indirekt else: # false, None od. Blank xbmc.Player().play(url, li, windowed=False) # direkter Start return
def check_for_updates(self, skin_name=None, silent=False): """ Performs update check for requested theme/s :param skin_name: Optional name of skin to update :type skin_name: str :param silent: Optional argument to disable user feedback :type silent: bool :return: None :rtype: None """ skins = [] if skin_name is None: skins = self.installed_skins else: try: skins.append( [i for i in self.installed_skins if i["skin_name"] == skin_name][0] ) except IndexError: raise SkinNotFoundException(skin_name) if not silent: self._progress_dialog.create(g.ADDON_NAME, g.get_language_string(30085)) self._progress_dialog.update(-1) skins = [i for i in skins if self._skin_can_update(i)] skins = [i for i in skins if self._check_skin_for_update(i)] if len(skins) == 0: if not silent: self._progress_dialog.close() xbmcgui.Dialog().ok(g.ADDON_NAME, g.get_language_string(30084)) return if not silent: self._progress_dialog.close() while skins and len(skins) > 0: self._progress_dialog.create(g.ADDON_NAME, g.get_language_string(30336)) self._progress_dialog.update(-1) selection = xbmcgui.Dialog().select( g.ADDON_NAME, ["{} - {}".format(i["skin_name"], i["version"]) for i in skins], ) if selection == -1: return skin_info = skins[selection] try: self.install_skin(skin_info["update_directory"], True) skins.remove(skin_info) self._progress_dialog.close() xbmcgui.Dialog().ok(g.ADDON_NAME, g.get_language_string(30078)) except Exception as e: g.log_stacktrace() g.log("Failed to update skin: {}".format(selection)) g.notification(g.ADDON_NAME, g.get_language_string(30080)) raise e xbmcgui.Dialog().ok(g.ADDON_NAME, g.get_language_string(30084)) return else: for skin in skins: try: self.install_skin(skin["update_directory"], True) except Exception as e: g.log("Failed to update theme: {}".format(skin["skin_name"])) raise e g.log("Skin updates completed")
def Default_Mode(): """ internal command ~""" dialog = xbmcgui.Dialog() dialog.ok('MODE ERROR','You\'ve tried to call Add_Dir() without a valid mode, check you\'ve added the mode into the master_modes dictionary') #----------------------------------------------------------------
def parental_control(name, year, mpaa, type): mpaa = PC_DEFAULT if type == 'movies': if mpaa in mrating: mpaa = mpaa else: infoLabels = infoLabels = get_meta(name, 'movie', year=year) if infoLabels['mpaa'] == '' or infoLabels['mpaa'] == 'N/A': mpaa = 'Unrated' else: mpaa = infoLabels['mpaa'] else: if mpaa in tvrating: mpaa = mpaa else: infoLabels = get_meta(name, 'tvshow', year=None, season=None, episode=None, imdb=None) if infoLabels['mpaa'] == '' or infoLabels['mpaa'] == 'N/A': mpaa = 'Unrated' else: mpaa = infoLabels['mpaa'] dialog = xbmcgui.Dialog() if type == 'movies': rating_list = [ "No thanks, I'll choose later", "G", "PG", "PG-13", "R", "NC-17" ] rating_list_return = [ "No thanks, I'll choose later", "G", "PG", "PG-13", "R", "NC-17" ] else: rating_list = [ "No thanks, I'll choose later", "TV-Y", "TV-Y7-FG", "TV-PG", "TV-14", "TV-MA" ] rating_list_return = [ "No thanks, I'll choose later", "TV-Y", "TV-Y7-FG", "TV-PG", "TV-14", "TV-MA" ] if mpaa == "Unrated" or mpaa == "": mpaa = PC_DEFAULT if os.path.isfile(CUSTOM_PC): s = read_from_file(CUSTOM_PC) if name in s: search_list = s.split('\n') for list in search_list: if list != '': list1 = list.split('<>') title = list1[0] cmpaa = list1[1] vtype = list1[2] if title == name and vtype == type: mpaa = cmpaa else: rating_id = dialog.select( "No rating found....set/save your own?", rating_list) if (rating_id <= 0): mpaa = PC_DEFAULT else: pw = '' keyboard = xbmc.Keyboard( pw, 'Enter your PIN/Password to save the rating', True) keyboard.doModal() if keyboard.isConfirmed(): pw = keyboard.getText() else: pw = '' if pw == PC_PASS: mpaa = rating_list_return[rating_id] content = '%s<>%s<>%s' % (name, mpaa, type) add_to_list(content, CUSTOM_PC) else: mpaa = PC_DEFAULT if mpaa == "PLAY": mpaa_n = 0 elif mpaa == "G" or mpaa == "TV-Y" or mpaa == "TV-Y7-FG": mpaa_n = 1 elif mpaa == "PG" or mpaa == "TV-PG": mpaa_n = 2 elif mpaa == "PG-13" or mpaa == "TV-14": mpaa_n = 3 elif mpaa == "R" or mpaa == "NC-17" or mpaa == "TV-MA" or mpaa == "REQUIRE PIN": mpaa_n = 4 return mpaa_n, mpaa
def onNotificationsCleared(): xbmcgui.Dialog().ok(strings(CLEAR_NOTIFICATIONS), strings(DONE))
def setting_channel_new(item): import xbmcgui # Load list of options (active user channels that allow global search) lista = [] ids = [] lista_lang = [] lista_ctgs = [] channels_list = channelselector.filterchannels('all') for channel in channels_list: if channel.action == '': continue channel_parameters = channeltools.get_channel_parameters(channel.channel) # Do not include if "include_in_global_search" does not exist in the channel configuration if not channel_parameters['include_in_global_search']: continue lbl = '%s' % channel_parameters['language'] lbl += ' %s' % ', '.join(config.get_localized_category(categ) for categ in channel_parameters['categories']) it = xbmcgui.ListItem(channel.title, lbl) it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) lista.append(it) ids.append(channel.channel) lista_lang.append(channel_parameters['language']) lista_ctgs.append(channel_parameters['categories']) # Pre-select dialog preselecciones = [ config.get_localized_string(70570), config.get_localized_string(70571), 'Modificar partiendo de Recomendados', 'Modificar partiendo de Frecuentes', config.get_localized_string(70572), config.get_localized_string(70573), config.get_localized_string(70574), config.get_localized_string(70575) ] presel_values = ['skip', 'actual', 'recom', 'freq', 'all', 'none', 'cast', 'lat'] categs = ['movie', 'tvshow', 'documentary', 'anime', 'vos', 'direct', 'torrent'] if config.get_setting('adult_mode') > 0: categs.append('adult') for c in categs: preselecciones.append(config.get_localized_string(70577) + config.get_localized_category(c)) presel_values.append(c) if item.action == 'setting_channel': # Configuración de los canales incluídos en la búsqueda del preselecciones[0] del presel_values[0] # else: # Call from "search on other channels" (you can skip the selection and go directly to the search) ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones) if ret == -1: return False # order cancel if presel_values[ret] == 'skip': return True # continue unmodified elif presel_values[ret] == 'none': preselect = [] elif presel_values[ret] == 'all': preselect = list(range(len(ids))) elif presel_values[ret] in ['cast', 'lat']: preselect = [] for i, lg in enumerate(lista_lang): if presel_values[ret] in lg or '*' in lg: preselect.append(i) elif presel_values[ret] == 'actual': preselect = [] for i, canal in enumerate(ids): channel_status = config.get_setting('include_in_global_search', canal) if channel_status: preselect.append(i) elif presel_values[ret] == 'recom': preselect = [] for i, canal in enumerate(ids): _not, set_canal_list = channeltools.get_channel_controls_settings(canal) if set_canal_list.get('include_in_global_search', False): preselect.append(i) elif presel_values[ret] == 'freq': preselect = [] for i, canal in enumerate(ids): frequency = channeltools.get_channel_setting('frequency', canal, 0) if frequency > 0: preselect.append(i) else: preselect = [] for i, ctgs in enumerate(lista_ctgs): if presel_values[ret] in ctgs: preselect.append(i) # Dialog to select ret = xbmcgui.Dialog().multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True) if not ret: return False # order cancel seleccionados = [ids[i] for i in ret] # Save changes to search channels for canal in ids: channel_status = config.get_setting('include_in_global_search', canal) if channel_status and canal not in seleccionados: config.set_setting('include_in_global_search', False, canal) elif not channel_status and canal in seleccionados: config.set_setting('include_in_global_search', True, canal) return True
def GetNumFromUser(title, defaultt=''): dialog = xbmcgui.Dialog() choice = dialog.input(title, defaultt=defaultt, type=xbmcgui.INPUT_NUMERIC) return 0 if choice == '' else int(choice)
def on_disconnect(self, myo, timestamp): """ Called when a Myo is disconnected. """ dialog = xbmcgui.Dialog() dialog.notification("Attention", "Myo disconnected")
def GetIndexFromUser(listLen, index): dialog = xbmcgui.Dialog() location = GetNumFromUser('{0} (1-{1})'.format(getLocaleString(10033), listLen)) return 0 if location > listLen or location <= 0 else location - 1 - index
def killxbmc(): choice = xbmcgui.Dialog().yesno('Force Close Kodi', 'You are about to close Kodi', 'Would you like to continue?', nolabel='No, Cancel', yeslabel='Yes, Close') if choice == 0: return elif choice == 1: pass myplatform = platform() print "Platform: " + str(myplatform) if myplatform == 'osx': # OSX print "############ try osx force close #################" try: os.system('killall -9 XBMC') except: pass try: os.system('killall -9 Kodi') except: pass dialog.ok( "[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", '') elif myplatform == 'linux': #Linux print "############ try linux force close #################" try: os.system('killall XBMC') except: pass try: os.system('killall Kodi') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass dialog.ok( "[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", '') elif myplatform == 'android': # Android print "############ try android force close #################" try: os.system('adb shell am force-stop org.xbmc.kodi') except: pass try: os.system('adb shell am force-stop org.kodi') except: pass try: os.system('adb shell am force-stop org.xbmc.xbmc') except: pass try: os.system('adb shell am force-stop org.xbmc') except: pass dialog.ok( "[COLOR=red][B]WARNING !!![/COLOR][/B]", "Your system has been detected as Android, you ", "[COLOR=yellow][B]MUST[/COLOR][/B] force close XBMC/Kodi. [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", "Either close using Task Manager (If unsure pull the plug).") elif myplatform == 'windows': # Windows print "############ try windows force close #################" try: os.system('@ECHO off') os.system('tskill XBMC.exe') except: pass try: os.system('@ECHO off') os.system('tskill Kodi.exe') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im Kodi.exe /f') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im XBMC.exe /f') except: pass dialog.ok( "[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", "Use task manager and NOT ALT F4") else: #ATV print "############ try atv force close #################" try: os.system('killall AppleTV') except: pass print "############ try raspbmc force close #################" #OSMC / Raspbmc try: os.system('sudo initctl stop kodi') except: pass try: os.system('sudo initctl stop xbmc') except: pass dialog.ok( "[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.", "Your platform could not be detected so just pull the power cable." )
def play(ch_id, link=None): # 178.132.5.135 193.70.111.192 137.74.200.60 149.202.197.108 key = b"10912895" r = s.post(list_url, headers={'app-token': '9120163167c05aed85f30bf88495bd89'}, data={'username': '******'}, timeout=15) ch = r.json() for c in ch['msg']['channels']: if c['pk_id'] == ch_id: selected_channel = c break title = selected_channel.get('channel_name') icon = selected_channel.get('img') image = "http://uktvnow.net/uktvnow8/{0}|User-Agent={1}".format( urllib.quote(icon.encode('utf-8')), quote(user_agent)) with s.cache_disabled(): r = s.post(token_url, headers={'app-token': '9120163167c05aed85f30bf88495bd89'}, data={ 'channel_id': ch_id, 'username': '******' }, timeout=15) links = [] for stream in r.json()['msg']['channel'][0].keys(): if 'stream' in stream or 'chrome_cast' in stream: d = des(key) link = d.decrypt( r.json()['msg']['channel'][0][stream].decode('base64'), padmode=PAD_PKCS5) if link: if not link == 'dummytext': links.append(link) if addon.getSetting('autoplay') == 'true': link = links[0] else: dialog = xbmcgui.Dialog() ret = dialog.select('Choose Stream', links) link = links[ret] if 'uktvnow.net' and 'playlist.m3u8' in link: media_url = '{0}|User-Agent={1}'.format(link, quote(user_agent)) if addon.getSetting('inputstream') == 'true': li = ListItem(title, path=media_url) li.setArt({'thumb': image, 'icon': image}) li.setMimeType('application/vnd.apple.mpegurl') li.setProperty('inputstreamaddon', 'inputstream.adaptive') li.setProperty('inputstream.adaptive.manifest_type', 'hls') li.setProperty('inputstream.adaptive.stream_headers', media_url.split('|')[-1]) elif addon.getSetting('livestreamer') == 'true': serverPath = os.path.join( xbmc.translatePath(addon.getAddonInfo('path')), 'livestreamerXBMCLocalProxy.py') runs = 0 while not runs > 10: try: requests.get('http://127.0.0.1:19001/version') break except: xbmc.executebuiltin('RunScript(' + serverPath + ')') runs += 1 xbmc.sleep(600) livestreamer_url = 'http://127.0.0.1:19001/livestreamer/' + b64encode( 'hlsvariant://' + media_url) li = ListItem(title, path=livestreamer_url) li.setArt({'thumb': image, 'icon': image}) li.setMimeType('video/x-mpegts') else: li = ListItem(title, path=media_url) li.setArt({'thumb': image, 'icon': image}) li.setMimeType('application/vnd.apple.mpegurl') else: media_url = link li = ListItem(title, path=media_url) li.setArt({'thumb': image, 'icon': image}) try: li.setContentLookup(False) except: pass xbmcplugin.setResolvedUrl(plugin.handle, True, li)
def __init__(self, external=False): tools.ensure_folders() self.external = external self.dialog = xbmcgui.Dialog() self.progress_dialog = xbmcgui.DialogProgress()
from libs.utility import debugTrace, errorTrace, infoTrace from libs.platform import getLogPath, getUserDataPath from libs.common import resetVPNConnections, isVPNConnected #from libs.generation import generateAll from libs.credentials import defCred addon = xbmcaddon.Addon("service.purevpn.monitor") addon_name = addon.getAddonInfo("name") action = sys.argv[1] debugTrace("-- Entered profileupdate.py with parameter " + action + " --") # Reset the ovpn files if action == "ovpn": if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno( addon_name, "Resetting the ovpn files will reset all VPN connections. Connections must be re-validated before use.\nContinue?" ): # Only used during development to create location files #generateAll() # Reset the connection before we do anything else if isVPNConnected(): resetVPNConnections(addon) debugTrace("Deleting all generated ovpn files") # Delete the ovpn files and the generated flag file. removeGeneratedFiles() xbmcgui.Dialog().ok( addon_name, "Deleted all .ovpn files. Validate a connection to recreate them.\n" )
def show_error_notification(message): xbmcgui.Dialog().notification(ADDON_NAME, message, xbmcgui.NOTIFICATION_ERROR, 4000, False)
def get_video_url(plugin, item_id, video_url, item_dict=None, download_mode=False, video_label=None, **kwargs): """Get video URL and start video player""" url_selected = '' all_datas_videos_quality = [] all_datas_videos_path = [] videos_html = urlquick.get(video_url) root = videos_html.parse() root_videos = videos_html.parse("ul", attrs={"class": "nav nav-tabs"}) for video in root_videos.iterfind(".//a"): if '#video-' in video.get('href'): # Find a better solution to strip if video.find('.//span') is not None: all_datas_videos_quality.append(video.text.strip() + ' ' + video.find('.//span').text) else: all_datas_videos_quality.append(video.text) # Get link value_jwplayer_id = video.get('data-jwplayer-id') # Case mp4 url = '' if value_jwplayer_id != '': for stream in root.iterfind(".//div[@class='jwplayer']"): if stream.get('id') == value_jwplayer_id: url = stream.get('data-source') # Cas Yt else: video_id = re.compile('youtube.com/embed/(.*?)\?').findall( videos_html.text)[0] url = resolver_proxy.get_stream_youtube( plugin, video_id, False) all_datas_videos_path.append(url + '|referer=%s' % video_url) # Get link from FranceTV elif '#ftv-player-' in video.get('href'): # Get link value_ftvlayer_id = video.get('data-ftvplayer-id') for stream in root.iterfind( ".//iframe[@class='embed-responsive-item']"): if stream.get('id') == value_ftvlayer_id: url_id = stream.get('src') id_embeded = url_id.split('akamaihd.net/')[1] json_value = urlquick.get(SHOW_INFO_FTV % id_embeded) json_value_parser = json.loads(json_value.text) id_diffusion = json_value_parser["video_id"] return resolver_proxy.get_francetv_video_stream( plugin, id_diffusion, item_dict, download_mode=download_mode) final_url = '' if len(all_datas_videos_quality) > 1: seleted_item = xbmcgui.Dialog().select( plugin.localize(LABELS['choose_video_quality']), all_datas_videos_quality) if seleted_item == -1: return False url_selected = all_datas_videos_path[seleted_item] final_url = url_selected else: final_url = all_datas_videos_path[0] if download_mode: return download.download_video(final_url, video_label) return final_url
def fullSync(self, manualrun=False, repair=False): # Only run once when first setting up. Can be run manually. music_enabled = settings('enableMusic') == "true" xbmc.executebuiltin('InhibitIdleShutdown(true)') screensaver = utils.getScreensaver() utils.setScreensaver(value="") window('emby_dbScan', value="true") # Add sources utils.sourcesXML() embyconn = utils.kodiSQL('emby') embycursor = embyconn.cursor() # content sync: movies, tvshows, musicvideos, music kodiconn = utils.kodiSQL('video') kodicursor = kodiconn.cursor() if manualrun: message = "Manual sync" elif repair: message = "Repair sync" repair_list = [] choices = ['all', 'movies', 'musicvideos', 'tvshows'] if music_enabled: choices.append('music') if self.kodi_version > 15: # Jarvis or higher types = xbmcgui.Dialog().multiselect(lang(33094), choices) if types is None: pass elif 0 in types: # all choices.pop(0) repair_list.extend(choices) else: for index in types: repair_list.append(choices[index]) else: resp = xbmcgui.Dialog().select(lang(33094), choices) if resp == 0: # all choices.pop(resp) repair_list.extend(choices) else: repair_list.append(choices[resp]) log.info("Repair queued for: %s", repair_list) else: message = "Initial sync" window('emby_initialScan', value="true") pDialog = self.progressDialog("%s" % message) starttotal = datetime.now() # Set views self.maintainViews(embycursor, kodicursor) embyconn.commit() # Sync video library process = { 'movies': self.movies, 'musicvideos': self.musicvideos, 'tvshows': self.tvshows } for itemtype in process: if repair and itemtype not in repair_list: continue startTime = datetime.now() completed = process[itemtype](embycursor, kodicursor, pDialog) if not completed: xbmc.executebuiltin('InhibitIdleShutdown(false)') utils.setScreensaver(value=screensaver) window('emby_dbScan', clear=True) if pDialog: pDialog.close() embycursor.close() kodicursor.close() return False else: self.dbCommit(kodiconn) embyconn.commit() elapsedTime = datetime.now() - startTime log.info("SyncDatabase (finished %s in: %s)" % (itemtype, str(elapsedTime).split('.')[0])) else: # Close the Kodi cursor kodicursor.close() # sync music if music_enabled: if repair and 'music' not in repair_list: pass else: musicconn = utils.kodiSQL('music') musiccursor = musicconn.cursor() startTime = datetime.now() completed = self.music(embycursor, musiccursor, pDialog) if not completed: xbmc.executebuiltin('InhibitIdleShutdown(false)') utils.setScreensaver(value=screensaver) window('emby_dbScan', clear=True) if pDialog: pDialog.close() embycursor.close() musiccursor.close() return False else: musicconn.commit() embyconn.commit() elapsedTime = datetime.now() - startTime log.info("SyncDatabase (finished music in: %s)" % (str(elapsedTime).split('.')[0])) musiccursor.close() if pDialog: pDialog.close() emby_db = embydb.Embydb_Functions(embycursor) current_version = emby_db.get_version(self.clientInfo.get_version()) window('emby_version', current_version) embyconn.commit() embycursor.close() settings('SyncInstallRunDone', value="true") self.saveLastSync() xbmc.executebuiltin('UpdateLibrary(video)') elapsedtotal = datetime.now() - starttotal xbmc.executebuiltin('InhibitIdleShutdown(false)') utils.setScreensaver(value=screensaver) window('emby_dbScan', clear=True) window('emby_initialScan', clear=True) xbmcgui.Dialog().notification( heading=lang(29999), message="%s %s %s" % (message, lang(33025), str(elapsedtotal).split('.')[0]), icon="special://home/addons/plugin.video.emby/icon.png", sound=False) return True
def show_update_window(name='Testing Window', current='1.0', new='1.1', icon=CONFIG.ADDON_ICON, fanart=CONFIG.ADDON_FANART): class UpdateWindow(xbmcgui.WindowXMLDialog): def __init__(self, *args, **kwargs): self.name = CONFIG.THEME3.format(kwargs['name']) self.current = kwargs['current'] self.new = kwargs['new'] self.icon = kwargs['icon'] self.fanart = kwargs['fanart'] self.msgupdate = "Update avaliable for installed build:\n[COLOR {0}]{1}[/COLOR]\n\nCurrent Version: v[COLOR {2}]{3}[/COLOR]\nLatest Version: v[COLOR {4}]{5}[/COLOR]\n\n[COLOR {6}]*Recommened: Fresh install[/COLOR]".format( CONFIG.COLOR1, self.name, CONFIG.COLOR1, self.current, CONFIG.COLOR1, self.new, CONFIG.COLOR1) self.msgcurrent = "Running latest version of installed build:\n[COLOR {0}]{1}[/COLOR]\n\nCurrent Version: v[COLOR {2}]{3}[/COLOR]\nLatest Version: v[COLOR {4}]{5}[/COLOR]\n\n[COLOR {6}]*Recommended: Fresh install[/COLOR]".format( CONFIG.COLOR1, self.name, CONFIG.COLOR1, self.current, CONFIG.COLOR1, self.new, CONFIG.COLOR1) def onInit(self): self.imagefanart = 101 self.header = 102 self.textbox = 103 self.imageicon = 104 self.fresh = 201 self.normal = 202 self.ignore = 203 self.setProperty('dialog.header', self.name) self.setProperty( 'dialog.textbox', CONFIG.THEME2.format( self.msgupdate if current < new else self.msgcurrent)) self.setProperty('dialog.imagefanart', self.fanart) self.setProperty('dialog.imagediffuse', '2FFFFFFF') self.setProperty('dialog.imageicon', self.icon) def do_fresh_install(self): logging.log( "[Check Updates] [Installed Version: {0}] [Current Version: {1}] [User Selected: Fresh Install build]" .format(CONFIG.BUILDVERSION, CONFIG.BUILDLATEST)) logging.log("[Check Updates] [Next Check: {0}]".format( tools.get_date(days=CONFIG.UPDATECHECK, formatted=True))) url = 'plugin://{0}/?mode=install&name={1}&action=fresh'.format( CONFIG.ADDON_ID, quote_plus(CONFIG.BUILDNAME)) xbmc.executebuiltin('RunPlugin({0})'.format(url)) self.close() def do_normal_install(self): logging.log( "[Check Updates] [Installed Version: {0}] [Current Version: {1}] [User Selected: Normal Install build]" .format(CONFIG.BUILDVERSION, CONFIG.BUILDLATEST)) logging.log("[Check Updates] [Next Check: {0}]".format( tools.get_date(days=CONFIG.UPDATECHECK, formatted=True))) url = 'plugin://{0}/?mode=install&name={1}&action=normal'.format( CONFIG.ADDON_ID, quote_plus(CONFIG.BUILDNAME)) xbmc.executebuiltin('RunPlugin({0})'.format(url)) self.close() def do_ignore(self): logging.log( "[Check Updates] [Installed Version: {0}] [Current Version: {1}] [User Selected: Ignore {2} Days]" .format(CONFIG.BUILDVERSION, CONFIG.BUILDLATEST, CONFIG.UPDATECHECK)) logging.log("[Check Updates] [Next Check: {0}]".format( tools.get_date(days=CONFIG.UPDATECHECK, formatted=True))) self.close() def onAction(self, action): id = action.getId() if action.getId() in BACK_ACTIONS: self.do_ignore() def onClick(self, controlid): if controlid == self.fresh: self.do_fresh_install() elif controlid == self.normal: self.do_normal_install() elif controlid == self.ignore: self.do_ignore() # update = UpdateWindow("build_update_prompt.xml", CONFIG.ADDON_PATH, 'Default', name=name, current=current, new=new, icon=icon, fanart=fanart) # update.doModal() # del update msgcurrent = 'Running latest version of installed build: ' msgupdate = 'Update available for installed build: ' build_name = '[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, name) current_version = 'Current Version: v[COLOR {0}]{1}[/COLOR]'.format( CONFIG.COLOR1, current) latest_version = 'Latest Version: v[COLOR {0}]{1}[/COLOR]'.format( CONFIG.COLOR1, new) final_msg = '{0}{1}\n{2}\n{3}\n'.format( msgcurrent if current >= new else msgupdate, build_name, current_version, latest_version) install = xbmcgui.Dialog().yesno(CONFIG.ADDONTITLE, final_msg, yeslabel='Install', nolabel='Ignore') if install: from resources.libs.wizard import Wizard Wizard().build(CONFIG.BUILDNAME)
import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, xbmcaddon, os, sys, time import shutil import time ################################################# AddonID = 'plugin.program.totalinstaller' ################################################# dialog = xbmcgui.Dialog() dp = xbmcgui.DialogProgress() ADDON = xbmcaddon.Addon(id=AddonID) ADDONDATA = xbmc.translatePath(os.path.join('special://home','userdata','addon_data')) clean_cache = ADDON.getSetting('cleancache') internetcheck = ADDON.getSetting('internetcheck') cbnotifycheck = ADDON.getSetting('cbnotifycheck') mynotifycheck = ADDON.getSetting('mynotifycheck') idfile = os.path.join(ADDONDATA,AddonID,'id.xml') TBSDATA = os.path.join(ADDONDATA,AddonID,'') update_file = os.path.join(ADDONDATA,AddonID,'updating') print'###### Community Portal Update Service ######' if not os.path.exists(TBSDATA): os.makedirs(TBSDATA) if not os.path.exists(idfile): localfile = open(idfile, mode='w+') localfile.write('id="None"\nname="None"') localfile.close() if os.path.exists(os.path.join(TBSDATA,'scripts')): shutil.rmtree(os.path.join(TBSDATA,'scripts'))
def notify_timezone_not_detected(): confirm = xbmcgui.Dialog().yesno(g.get_language_string(30591), g.get_language_string(30592)) if confirm: choose_timezone()
def notify(header="", message="", icon=ADDON_ICON, time=5000, sound=True): xbmcgui.Dialog().notification(heading=header, message=message, icon=icon, time=time, sound=sound)
def doDownload(self, url, dest, title, image, headers): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } url = urllib.unquote_plus(url) title = urllib.unquote_plus(title) image = urllib.unquote_plus(image) dest = urllib.unquote_plus(dest) file = dest.rsplit(os.sep, 1)[-1] resp = self.getResponse(url, headers, 0) if not resp: xbmcgui.Dialog().ok(title, dest, 'Download failed', 'No response from server') return try: content = int(resp.headers['Content-Length']) except: content = 0 try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False print "Download Header" print resp.headers if resumable: print "Download is resumable" if content < 1: xbmcgui.Dialog().ok(title, file, 'Unknown filesize', 'Unable to download') return size = 1024 * 1024 mb = content / (1024 * 1024) if content < size: size = content total = 0 notify = 0 errors = 0 count = 0 resume = 0 sleep = 0 stopped = True if xbmcgui.Dialog().yesno(title + ' - Confirm Download', file, 'Complete file is %dMB' % mb, 'Continue with download?', 'Confirm', 'Cancel') == 1: return print 'Download File Size : %dMB %s ' % (mb, dest) #f = open(dest, mode='wb') f = xbmcvfs.File(dest, 'w') chunk = None chunks = [] self.logDownload(title, '0', dest, mode='add') xbmc.executebuiltin("XBMC.Notification(%s,%s,%i,%s)" % (title, 'DOWNLOAD STARTED', 10000, image)) while True: self.stopped = False downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / content, 100) if percent >= notify: # label = '[%s] %s MB of %s MB' % (str(percent)+ '%', downloaded / 1000000, content / 1000000) # xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( title + ' - In Progress - ' + str(percent)+ '%', label, 10000, image)) print 'Download percent : %s %s %dMB downloaded : %sMB File Size : %sMB' % ( str(percent) + '%', dest, mb, downloaded / 1000000, content / 1000000) notify += 1 self.logDownload(title, percent, dest, mode='update') status = self.logDownload(title, '0', dest, mode='status') if status == 'stopped': self.stopped = True break chunk = None error = False try: chunk = resp.read(size) if not chunk: if percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c # DOWNLOAD COMPLETED self.logDownload(title, '100', dest, mode='completed') f.close() print '%s download complete' % (dest) return self.done(title, dest, True) except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) xbmc.sleep(sleep * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % ( dest) return self.done(title, dest, False) resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) resp = self.getResponse(url, headers, total) else: #use existing response pass