def check4update(): import re,time,xbmc,xbmcgui from resources.lib.modules import client addonxml = xbmc.translatePath('special://home/addons/script.module.streamhub/addon.xml') file = open(addonxml) data = file.read() file.close() c_version = re.compile('" version="(.+?)"').findall(data)[0] c_version2= (c_version).replace('.','') log(c_version2) html = client.request('https://raw.githubusercontent.com/sClarkeIsBack/StreamHub/master/Repo_Files/addons.xml') o_version = re.compile('script.module.streamhub.+?version="(.+?)"').findall(html)[0] o_version2= (o_version).replace('.','') log(o_version2) if c_version2 < o_version2: update = 'https://github.com/sClarkeIsBack/StreamHub/raw/master/Repo_Files/Zips/script.module.streamhub/script.module.streamhub-%s.zip'%o_version install(o_version,update) xbmc.executebuiltin("UpdateAddonRepos") xbmc.executebuiltin("UpdateLocalAddons") time.sleep(5) xbmcgui.Dialog().notification('[COLOR red]StreamHub[/COLOR]','Updated Successfully')
def LINKTV4(mname,url): xbmc.executebuiltin("XBMC.Notification(Please Wait!,Collecting Hosts,3000)") link=main.OPENURL(url) link= link.replace('TV Rage','').replace('Homepage','').replace('href="http://www.tvrage.com','').replace('href="http://www.cbs.com','').replace('Torrent Search','').replace('Season Download','').replace('href="http://uppix.net','').replace('href="http://www.torrentz.com','').replace('href="http://directdownload.tv','') ok=True main.addLink("[COLOR red]For Download Options, Bring up Context Menu Over Selected Link.[/COLOR]",'','') match=re.compile('<a href="(.+?)" target="_blank">(.+?)</a>').findall(link) print len(match) for url, host in match: thumb=host.lower() match5=re.compile('Part').findall(host) if len(match5)>0: match6=re.compile('http://(.+?)/.+?').findall(url) for url2 in match6: host2 = url2.replace('www.','').replace('.in','').replace('.net','').replace('.com','').replace('.to','').replace('.org','').replace('.ch','') thumb=host2.lower() match3=re.compile('720p').findall(url) match4=re.compile('mp4').findall(url) if len(match3)>0: host =host+' [COLOR red]HD[/COLOR]' elif len(match4)>0: host =host+' [COLOR green]SD MP4[/COLOR]' else: host =host+' [COLOR blue]SD[/COLOR]' match2=re.compile('rar').findall(url) if len(match2)==0: hosted_media = urlresolver.HostedMediaFile(url=url, title=host) match2=re.compile("{'url': '(.+?)', 'host': '(.+?)', 'media_id': '.+?'}").findall(str(hosted_media)) for murl,name in match2: main.addDown2(mname+' [COLOR blue]'+host+'[/COLOR]',murl,210,art+thumb+".png",art+thumb+".png")
def autostart(): xbmc.log('script.pseudotv.live-Service: autostart') xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ("AutoStart PseudoTV Live","Service Starting...", 4000, THUMB) ) AUTOSTART_TIMER = [0,5,10,15,20]#in seconds IDLE_TIME = AUTOSTART_TIMER[int(REAL_SETTINGS.getSetting('timer_amount'))] sleep(IDLE_TIME) xbmc.executebuiltin('RunScript("' + ADDON_PATH + '/default.py' + '")')
def apagarinterrompido(tipo): try: os.remove(os.path.join(pastaperfil, tipo)) except: pass try: os.remove(os.path.join(pastaperfil, tipo + '_info')) except: pass xbmc.executebuiltin("XBMC.Notification(wareztuga.tv," + traducao(40201) + ",'10000',"+iconpequeno.encode('utf-8')+")") xbmc.executebuiltin("XBMC.Container.Refresh")
def getEpisodeList(self, url): contentType,main_page = common.getData(url) episodeList = re.compile('<ol class="episode-list".*?</ol>').findall(main_page) episodes = re.compile('data-json.*?tooltipTitle":"(.*?)&.*?:"(.*?)".*?:"(.*?)&.*?href="(.*?)"').findall(episodeList[0]) for title, summary, img, url in episodes: episodeNum = re.compile('(\d.*?)/').findall(url)[0] contentType, page = common.getData('http://video2.walla.co.il/?w=null/null/' + episodeNum + '/@@/video/flv_pl') titleMatches = re.compile('<title>(.*?)</title>(.*)<subtitle>(.*?)<').findall(page) if (len(titleMatches)) == 1: title = titleMatches[0][0] images = re.compile('<preview_pic>(.*?)</preview_pic>').findall(page) if (len(images)) >= 1: iconImage = images[0] details = re.compile('<synopsis>(.*?)</synopsis>').findall(page) if (len(details)) > 0: epiDetails = details[0] timeInSeconds = re.compile('<duration>(.*?)</duration>').findall(page) if not timeInSeconds == None and not len(timeInSeconds[0]) <= 0: time = int(timeInSeconds[0]) / 60 else: time = '00:00' url = 'rtmp://waflaWBE.walla.co.il/ app=vod/ swfvfy=true swfUrl=http://i.walla.co.il/w9/swf/video_swf/vod/walla_vod_player_adt.swf?95 tcurl=rtmp://waflaWBE.walla.co.il/vod/ pageurl=http://walla.co.il/ playpath=' + re.compile('<src>(.*?)</src>').findall(page)[0] common.addLink(contentType,title, url, iconImage, str(time), epiDetails) nextPage = re.compile('<a class="in_blk p_r" href="(.*?)" style=""></a>').findall(main_page) if (len(nextPage)) > 0: addDir('UTF-8',__language__(30001), __BASE_URL__ + nextPage[0], self.MODES.GET_EPISODES_LIST, 'DefaultFolder.png', __NAME__) xbmcplugin.setContent(int(sys.argv[1]), 'episodes') xbmc.executebuiltin("Container.SetViewMode(500)")
def colours(): ##### Read colour XML & set if os.path.isfile ( Colour_xml ): log('| Parsing colours.xml') xbmc.executebuiltin('Skin.Reset(nodefaultxml)') Colour_XML = open( Colour_xml, 'r' ).read() Output = BeautifulSoup( Colour_XML ) try: # Colour 1 Current_Window.setProperty( 'Synopsis_colour_1', Output.colour_1.string ) except(TypeError, KeyError, AttributeError): pass try: # Colour 2 Current_Window.setProperty( 'Synopsis_colour_2', Output.colour_2.string ) except(TypeError, KeyError, AttributeError): pass try: # Colour 3 Current_Window.setProperty( 'Synopsis_colour_3', Output.colour_3.string ) except(TypeError, KeyError, AttributeError): pass try: # Colour 4 Current_Window.setProperty( 'Synopsis_colour_4', Output.colour_4.string ) except(TypeError, KeyError, AttributeError): pass try: # Colour 5 Current_Window.setProperty( 'Synopsis_colour_5', Output.colour_5.string ) except(TypeError, KeyError, AttributeError): pass else: log('| No colour.xml found')
def synopsis_mode_video(): ##### Check for Preview files. PreviewFile = "0" for root, dirs, files in os.walk( _Resources_Preview ): for filename in files: PreviewFile = root + '\\' + filename Current_Window.setProperty( 'Synopsis_Video_Preview_Path', PreviewFile ) Current_Window.setProperty( 'Synopsis_Video_Preview_Name', "Found "+filename ) if PreviewFile == "0": log('| No preview video found') xbmc.executebuiltin('Skin.Reset(SynopsisPreviewThere)') else: if PreviewFile.endswith('.xmv'): Current_Window.setProperty( 'Player_Type','DVDPlayer' ) xbmc.executebuiltin('Skin.SetBool(SynopsisPreviewThere)') elif PreviewFile.endswith('.strm'): try: urllib2.urlopen('http://www.google.com', timeout=1) Current_Window.setProperty( 'Player_Type','MPlayer' ) xbmc.executebuiltin('Skin.SetBool(SynopsisPreviewThere)') except urllib2.URLError as err: xbmc.executebuiltin('Skin.Reset(SynopsisPreviewThere)') else: Current_Window.setProperty( 'Player_Type','MPlayer' ) xbmc.executebuiltin('Skin.SetBool(SynopsisPreviewThere)') log('| Found ' + PreviewFile)
def do_disable_check(): scrapers=relevant_scrapers() auto_disable=ADDON.get_setting('auto-disable') check_freq=int(ADDON.get_setting('disable-freq')) disable_thresh=int(ADDON.get_setting('disable-thresh')) for cls in scrapers: last_check = db_connection.get_setting('%s_check' % (cls.get_name())) last_check = int(last_check) if last_check else 0 tries=ADDON.get_setting('%s_try' % (cls.get_name())) tries = int(tries) if tries else 0 if tries>0 and tries/check_freq>last_check/check_freq: ADDON.set_setting('%s_check' % (cls.get_name()), str(tries)) success_rate=calculate_success(cls.get_name()) if success_rate<disable_thresh: if auto_disable == DISABLE_SETTINGS.ON: ADDON.set_setting('%s-enable' % (cls.get_name()), 'false') builtin = "XBMC.Notification(%s,[COLOR blue]%s[/COLOR] Scraper Automatically Disabled, 5000, %s)" % (ADDON.get_name(), cls.get_name(), ICON_PATH) xbmc.executebuiltin(builtin) elif auto_disable == DISABLE_SETTINGS.PROMPT: dialog=xbmcgui.Dialog() line1='The [COLOR blue]%s[/COLOR] scraper timed out on [COLOR red]%s%%[/COLOR] of %s requests' % (cls.get_name(), 100-success_rate, tries) line2= 'Each timeout wastes system resources and time.' line3='([I]If you keep it enabled, consider increasing the scraper timeout.[/I])' ret = dialog.yesno('SALTS', line1, line2, line3, 'Keep Enabled', 'Disable It') if ret: ADDON.set_setting('%s-enable' % (cls.get_name()), 'false')
def MAIN(murl): if 'TV' in murl: main.addDir('Movies','MOVIES',451,art+'/shush.png') link=main.OPENURL('http://www.shush.se/index.php?shows') link=link.replace('\r','').replace('\n','').replace('\t','').replace(' ','').replace('»','') match=re.compile('(?sim)class="shows"><a href="([^"]+)"><img src="([^"]+)" alt="Watch (.+?) online').findall(link) for url,thumb,name in match: main.addDirT(name.title(),'http://www.shush.se/'+url,452,thumb,'','','','','') else: main.addDir('TV','TV',451,art+'/shush.png') link=main.OPENURL('http://www.shush.se/index.php?movies') link=link.replace('\r','').replace('\n','').replace('\t','').replace(' ','').replace('»','') match=re.compile('(?sim)class="shows"><a href="([^"]+)"><img src="([^"]+)" alt="([^"]+)" title=').findall(link) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until Movie list is cached.') totalLinks = len(match) loadedLinks = 0 remaining_display = 'Movies loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display) xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)") for url,thumb,name in match: main.addPlayM(name.title(),'http://www.shush.se/'+url,453,thumb,'','','','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Movies loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if (dialogWait.iscanceled()): return False dialogWait.close() del dialogWait
def PlayB(name,url): ok=True hname=name name = name.split('[COLOR blue]')[0] name = name.split('[COLOR red]')[0] infoLabels = main.GETMETAT(name,'','','') video_type='movie' season='' episode='' img=infoLabels['cover_url'] fanart =infoLabels['backdrop_url'] imdb_id=infoLabels['imdb_id'] infolabels = { 'supports_meta' : 'true', 'video_type':video_type, 'name':str(infoLabels['title']), 'imdb_id':str(infoLabels['imdb_id']), 'season':str(season), 'episode':str(episode), 'year':str(infoLabels['year']) } try: xbmc.executebuiltin("XBMC.Notification(Please Wait!,Resolving Link,3000)") stream_url = main.resolve_url(url) infoL={'Title': infoLabels['metaName'], 'Plot': infoLabels['plot'], 'Genre': infoLabels['genre']} # play with bookmark player = playbackengine.PlayWithoutQueueSupport(resolved_url=stream_url, addon_id=addon_id, video_type=video_type, title=str(infoLabels['title']),season=str(season), episode=str(episode), year=str(infoLabels['year']),img=img,infolabels=infoL, watchedCallbackwithParams=main.WatchedCallbackwithParams,imdb_id=imdb_id) #WatchHistory if selfAddon.getSetting("whistory") == "true": wh.add_item(hname+' '+'[COLOR green]Movie25[/COLOR]', sys.argv[0]+sys.argv[2], infolabels=infolabels, img=img, fanart=fanart, is_folder=False) player.KeepAlive() return ok except Exception, e: if stream_url != False: main.ErrorReport(e) return ok
def do_startup_task(task): run_on_startup=ADDON.get_setting('auto-%s' % task)=='true' and ADDON.get_setting('%s-during-startup' % task) == 'true' if run_on_startup and not xbmc.abortRequested: log_utils.log('Service: Running startup task [%s]' % (task)) now = datetime.datetime.now() xbmc.executebuiltin('RunPlugin(plugin://%s/?mode=%s)' % (ADDON.get_id(), task)) db_connection.set_setting('%s-last_run' % (task), now.strftime("%Y-%m-%d %H:%M:%S.%f"))
def LISTEPISODES(tvshowname,url): link=main.OPENURL(url) link=link.replace('\r','').replace('\n','').replace('\t','').replace(' ','') match = re.findall('<a class=".+?" href="(.+?)" id=".+?">(.+?)</a>',link) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until ['+tvshowname+'] Episodes are cached.') totalLinks = len(match) loadedLinks = 0 remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0, '[B]Will load instantly from now on[/B]',remaining_display) xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)") for url,name in match: if "Online" not in name: continue name=name.replace(tvshowname,'').replace('Watch Online','') name=main.removeNonASCII(name) main.addTVInfo(name,MainUrl+url,39,'','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if dialogWait.iscanceled(): return False match=re.findall('<div id="above_threadlist" class="above_threadlist">(.+?)</div>',link) for string in match: match1=re.findall('<a href="(.+?)" title="(.+?)">[0-9]+</a>', string) for url, page in match1: main.addTVInfo(page,MainUrl+url,38,'','','') dialogWait.close() del dialogWait xbmcplugin.setContent(int(sys.argv[1]), 'TV Shows') main.VIEWS()
def apt_commit_complete(self): # on commit complete, remove the notification from the Home window self.window.setProperty('OSMC_notification', 'false') # remove the file that blocks further update checks try: os.remove(self.block_update_file) except: pass if self.check_if_reboot_required(): # the files flagging that an installed package needs a reboot are present # 0 "Prompt for all actions" -- PROMPT # 1 "Display icon on home screen only" -- PROMPT # 2 "Download updates, then prompt" -- PROMPT # 3 "Download and display icon" -- PROMPT # 4 "Download, install, prompt if restart needed" -- PROMPT # display dialogue saying that osmc needs to reboot reboot = DIALOG.yesno(lang(32077), lang(32079), lang(32080), yeslabel=lang(32081), nolabel=lang(32082)) if reboot: exit_osmc_settings_addon() xbmc.sleep(1000) xbmc.executebuiltin('Reboot') else: # skip further update checks until osmc has rebooted self.skip_update_check = True
def getCategoryItems(self, url, page): print "*** Get category items %s" % url page_url = "%s/page/%s/" % (url, str(int(page))) response = common.fetchPage({"link": page_url}) items = 0 if response["status"] == 200: content = common.parseDOM(response["content"], "div", attrs={"id": "page_content"}) movie = common.parseDOM(content, "div", attrs={"class": "movie_teaser clearfix"}) header = common.parseDOM(movie, "h2") links = common.parseDOM(header, "a", ret="href") titles = common.parseDOM(header, "a") poster = common.parseDOM(movie, "li", attrs={"class": "movie_teaser_poster"}) images = common.parseDOM(poster, "img", ret="src") teaser = common.parseDOM(movie, "div", attrs={"class": "teaser_info"}) descs = common.parseDOM(teaser, "div", attrs={"class": "teaser_desc"}) infos = common.parseDOM(teaser, "ul", attrs={"class": "teaser_ads"}) ratings = common.parseDOM(movie, "li", attrs={"class": "current-rating"}) pagenav = common.parseDOM(response["content"], "div", attrs={"id": "pagenav"}) for i, title in enumerate(titles): items += 1 info = common.parseDOM(infos[i], "li") image = images[i] genre = self.encode(', '.join(common.parseDOM(info[2], "a"))) year = info[1].split('</span>')[-1] desc = common.stripTags(self.encode(descs[i])) rating = int(ratings[i])/10 if ratings[i] > 0 else None try: tmp = year.split(' ') year = tmp[0] season = tmp[1]+tmp[2] title = "%s %s %s" % (self.encode(title), self.encode(season), year) except IndexError: title = "%s (%s)" % (self.encode(title), year) uri = sys.argv[0] + '?mode=show&url=%s' % (links[i]) item = xbmcgui.ListItem(title, iconImage=self.icon, thumbnailImage=self.url+image) item.setInfo(type='Video', infoLabels={'title': title, 'genre': genre, 'plot': desc, 'rating': rating}) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) else: self.showErrorMessage("getCategoryItems(): Bad response status%s" % response["status"]) if pagenav and not items < 10: uri = sys.argv[0] + '?mode=%s&url=%s&page=%s' % ("category", url, str(int(page) + 1)) item = xbmcgui.ListItem("Next page >>", thumbnailImage=self.inext) xbmcplugin.addDirectoryItem(self.handle, uri, item, True) xbmc.executebuiltin('Container.SetViewMode(52)') xbmcplugin.endOfDirectory(self.handle, True)
def LISTSHOWS(murl,channel,index=False): link=main.OPENURL(murl) link=link.replace('\r','').replace('\n','').replace('\t','').replace(' ','') match = re.findall('<div class="titleline"><h2 class="forumtitle"><a href="(.+?)">(.+?)</a></h2></div>',link) label='TV Shows' if not len(match) > 0: match = re.findall('<h3 class="threadtitle">.+?<a class=".+?" href="(.+?)" id=".+?">(.+?)</a></h3>', link) label = 'Movies' dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until ' + label + ' Show list is cached.') totalLinks = len(match) loadedLinks = 0 remaining_display = label + ' loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0, '[B]Will load instantly from now on[/B]',remaining_display) xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)") for url,name in match: if "color" in name: name=name.replace('<b><font color=red>','[COLOR red]').replace('</font></b>','[/COLOR]') name=name.replace('<b><font color="red">','[COLOR red]').replace('</font></b>','[/COLOR]') if label == 'Movies': main.addDirX(name, MainUrl+url,39,'',searchMeta=True, metaType='Movies') else: main.addTVInfo(name,MainUrl+url,38,getShowImage(channel,name),'','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = label + ' loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if dialogWait.iscanceled(): return False dialogWait.close() del dialogWait xbmcplugin.setContent(int(sys.argv[1]), label) main.VIEWS()
def play_picture_slideshow(origurl, name): print "Starting play_picture_slideshow(): " + str(origurl) #user clicked on a picture if origurl[-4:].lower()=='.jpg' or origurl[-4:].lower()=='.gif' or origurl[-4:].lower()=='.png': print "Single picture mode" origurl = origurl.replace( ' ', '%20' ) xbmc.log("adding to picture slideshow: " + str(origurl)) xbmc.executehttpapi("ClearSlideshow") xbmc.executehttpapi("AddToSlideshow(%s)" % origurl) xbmc.executebuiltin( "SlideShow(,,notrandom)" ) return #user clicked on <start slideshow> items = getItemsFromUrl(origurl) xbmc.executehttpapi("ClearSlideshow") itemCount=0 for item in items: itemCount=itemCount+1 label, url, description, pubDate, guid, thumb, duration, rating, viewcount = getItemFields(item) if url is not None and url != '': xbmc.executehttpapi("AddToSlideshow(%s)" % url) print "# of pictures added to sideshow " + str(itemCount) xbmc.executebuiltin( "SlideShow(,,notrandom)" )
def downloader_is(url, name, showProgress=True): import downloader, extract addonsDir = xbmc.translatePath(os.path.join('special://home', 'addons')).decode("utf-8") packageFile = os.path.join(addonsDir, 'packages', 'isr.zip') ''' try: os.remove(packageFile) except: pass ''' if showProgress: dp = xbmcgui.DialogProgress() dp.create(AddonName, "Downloading", name, "Please Wait") downloader.download(url, packageFile, dp) dp.update(0, "", "Extracting Zip Please Wait") extract.all(packageFile, addonsDir, dp) else: urllib.urlretrieve(url, packageFile) extract.all(packageFile, addonsDir) try: os.remove(packageFile) except: pass xbmc.executebuiltin("UpdateLocalAddons") xbmc.executebuiltin("UpdateAddonRepos")
def mudar_nome_pasta(name): keyb = xbmc.Keyboard('', 'Nome da Pasta') #Chama o keyboard do XBMC com a frase indicada keyb.doModal() #Espera ate que seja confirmada uma determinada string if (keyb.isConfirmed()): #Se a entrada estiver confirmada (isto e, se carregar no OK) nome_pasta = keyb.getText() #Variavel search fica definida com o conteudo do formulario if nome_pasta == '': return nome_pasta = nome_pasta.replace('"','\'') else: return lines = [] try: f = open(db,"r") lines = f.readlines() f.close() except: return for line in lines: if re.search('pasta="'+nome_pasta+'"',line): dialog = xbmcgui.Dialog() dialog.ok('Erro!','Já existe uma pasta com o mesmo nome!') return f = open(db,"w") for line in lines: line = line.replace('pasta="'+name+'"','pasta="'+nome_pasta+'"') f.write(line) f.close() xbmc.executebuiltin("Container.Refresh")
def add_to_folder(name,url): if db == 'db_addonmanager.txt': dialog = xbmcgui.Dialog() dialog.ok('Erro!','Defina onde deseja guardar os dados.') selfAddon.openSettings() return keyb = xbmc.Keyboard('', 'Nome da Pasta') #Chama o keyboard do XBMC com a frase indicada keyb.doModal() #Espera ate que seja confirmada uma determinada string if (keyb.isConfirmed()): #Se a entrada estiver confirmada (isto e, se carregar no OK) nome_pasta = keyb.getText() #Variavel search fica definida com o conteudo do formulario if nome_pasta == '': return nome_pasta = nome_pasta.replace('"','\'') else: return lines = [] try: f = open(db,"r") lines = f.readlines() f.close() except: pass flag = True f = open(db,"w") for line in lines: if re.search('pasta="' + nome_pasta + '"',line): flag = False f.write(line) if flag: f.write('pasta="' + nome_pasta + '" name="' + name + '" id="' + url + '" icon=""\n') else: dialog = xbmcgui.Dialog() dialog.ok('Erro!','Já existe uma pasta com esse nome.') f.close() xbmc.executebuiltin("Container.Refresh")
def PLAY(name,url): ok=True hname=name name = name.split('[COLOR blue]')[0] name = name.split('[COLOR red]')[0] infoLabels = main.GETMETAT(name,'','','') video_type='movie' season='' episode='' img=infoLabels['cover_url'] fanart =infoLabels['backdrop_url'] imdb_id=infoLabels['imdb_id'] infolabels = { 'supports_meta' : 'true', 'video_type':video_type, 'name':str(infoLabels['title']), 'imdb_id':str(infoLabels['imdb_id']), 'season':str(season), 'episode':str(episode), 'year':str(infoLabels['year']) } try: xbmc.executebuiltin("XBMC.Notification(Please Wait!,Resolving Link,3000)") stream_url = urlresolver.resolve(url) infoL={'Title': infoLabels['metaName'], 'Plot': infoLabels['plot'], 'Genre': infoLabels['genre']} from resources.universal import playbackengine player = playbackengine.PlayWithoutQueueSupport(resolved_url=stream_url, addon_id=addon_id, video_type=video_type, title=str(infoLabels['title']),season=str(season), episode=str(episode), year=str(infoLabels['year']),img=img,infolabels=infoL, watchedCallbackwithParams=main.WatchedCallbackwithParams,imdb_id=imdb_id) player.KeepAlive() return ok except Exception, e: if stream_url != False: main.ErrorReport(e) return ok
def add_item(self, params): error = False arg = {"play": params['url'], 'cp': 'sosac.ph', "title": params['name']} item_url = util._create_plugin_url(arg, 'plugin://' + self.addon_id + '/') print("item: ", item_url, params) new_items = False # self.showNotification('Linking', params['name']) if "movie" in params['url']: item_dir = self.getSetting('library-movies') (error, new_items) = self.add_item_to_library( os.path.join(item_dir, self.normalize_filename(params['name']), self.normalize_filename(params['name'])) + '.strm', item_url) else: if not ('notify' in params): self.showNotification(params['name'], 'Checking new content') subs = self.get_subs() item_dir = self.getSetting('library-tvshows') if not params['url'] in subs.keys(): subs.update({params['url']: params['name']}) self.set_subs(subs) # self.addon.setSetting('tvshows-subs', json.dumps(subs)) if not xbmcvfs.exists(os.path.join(item_dir, self.normalize_filename(params['name']), 'tvshow.nfo')): tvid = self.getTVDB(params['name']) if tvid: self.add_item_to_library(os.path.join(item_dir, self.normalize_filename( params['name']), 'tvshow.nfo'), 'http://thetvdb.com/index.php?tab=series&id=' + tvid) list = self.provider.list_tv_show(params['url']) for itm in list: nfo = re.search('[^\d+](?P<season>\d+)[^\d]+(?P<episode>\d+)', itm['title'], re.IGNORECASE | re.DOTALL) arg = {"play": itm['url'], 'cp': 'sosac.ph', "title": self.normalize_filename(itm['epname'])} """ info = ''.join(('<episodedetails><season>', nfo.group('season'), '</season><episode>', nfo.group('episode'), '</episode></episodedetails>')) """ item_url = util._create_plugin_url(arg, 'plugin://' + self.addon_id + '/') (err, new) = self.add_item_to_library(os.path.join( item_dir, self.normalize_filename(params['name']), 'Season ' + nfo.group('season'), "S" + nfo.group('season') + "E" + nfo.group('episode') + '.strm'), item_url) error |= err if new is True and not err: new_items = True if not error and new_items and not ('update' in params) and not ('notify' in params): self.showNotification(params['name'], 'New content') xbmc.executebuiltin('UpdateLibrary(video)') elif not error and not ('notify' in params): self.showNotification(params['name'], 'No new contents') if error and not ('notify' in params): self.showNotification('Failed, Please check kodi.util.info', 'Linking') return new_items
def panPlay(): li = xbmcgui.ListItem(_station[0]) li.setPath("special://home/addons/%s/silent.m4a" % _plugin) li.setProperty(_plugin, _stamp) li.setProperty('mimetype', 'audio/aac') _lock.acquire() start = time.time() panFill() while not _play: time.sleep(0.01) xbmc.sleep(1000) if xbmc.abortRequested: _lock.release() exit() if (threading.active_count() == 1) or ((time.time() - start) >= 60): if _play: break # check one last time before we bail xbmc.log("%s.Play BAD (%13s, %ds)" % (_plugin, _stamp, time.time() - start)) xbmcgui.Dialog().ok(_name, 'No Tracks Received', '', 'Try again later') exit() _playlist.clear() _lock.release() time.sleep(0.01) # yield to the song threads xbmc.sleep(1000) # might return control to xbmc and skip the other threads ? xbmcplugin.setResolvedUrl(_handle, True, li) _player.play(_playlist) xbmc.executebuiltin('ActivateWindow(10500)') xbmc.log("%s.Play OK (%13s) '%s - %s'" % (_plugin, _stamp, _station.id[-4:], _station.name))
def set_view(view_mode, view_code=0): _log("set_view view_mode='"+view_mode+"', view_code="+str(view_code)) # Set the content for extended library views if needed if view_mode==MOVIES: _log("set_view content is movies") xbmcplugin.setContent( int(sys.argv[1]) ,"movies" ) elif view_mode==TV_SHOWS: _log("set_view content is tvshows") xbmcplugin.setContent( int(sys.argv[1]) ,"tvshows" ) elif view_mode==SEASONS: _log("set_view content is seasons") xbmcplugin.setContent( int(sys.argv[1]) ,"seasons" ) elif view_mode==EPISODES: _log("set_view content is episodes") xbmcplugin.setContent( int(sys.argv[1]) ,"episodes" ) # Reads skin name skin_name = xbmc.getSkinDir() _log("set_view skin_name='"+skin_name+"'") try: if view_code==0: _log("set_view view mode is "+view_mode) view_codes = ALL_VIEW_CODES.get(view_mode) view_code = view_codes.get(skin_name) _log("set_view view code for "+view_mode+" in "+skin_name+" is "+str(view_code)) xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")") else: _log("set_view view code forced to "+str(view_code)) xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")") except: _log("Unable to find view code for view mode "+str(view_mode)+" and skin "+skin_name)
def __init__( self, *args, **kwargs ): if sys.argv[1] == "changelog": changelog = self.openfile('changelog.txt') self.text(changelog,'Changelog') elif sys.argv[1] == "license": texto = self.openfile('LICENSE.txt') self.text(texto,traducao(1004)) elif sys.argv[1] == "version": try: codigo_fonte=self.abrir_url('http://anonymous-repo.googlecode.com/svn/trunk/anonymous-repo-adults/plugin.video.adultstv/addon.xml') match=re.compile('version="(.+?)"').findall(codigo_fonte)[1] except: match='error' if match=='error': xbmcgui.Dialog().ok(traducao(2010),traducao(2059),traducao(2060)) elif match!=selfAddon.getAddonInfo('version'):xbmcgui.Dialog().ok(traducao(2061)+' ('+match+')',traducao(2062)) else: xbmcgui.Dialog().ok('Adults TV', traducao(2063)) elif sys.argv[1] == "xbmctools": xbmcgui.Dialog().ok('XBMC Tools',traducao(2065),traducao(2064)) elif sys.argv[1] == "disclaimer": self.text(traducao(1003),'Disclaimer') elif sys.argv[1] == "help": self.text(traducao(2066)+'\n\ni96751414\nAnonymous',traducao(2067)) elif sys.argv[1] == "import": dir = xbmcgui.Dialog().browse(1,traducao(2072),"myprograms").replace('\\','/') if dir == '': return if self.file_name(dir) != 'bla.zip': xbmcgui.Dialog().ok(traducao(2010),traducao(2073)) return dest = os.path.join(addonfolder,'resources','lib') xbmc.executebuiltin('XBMC.Extract('+dir+','+dest+')') xbmcgui.Dialog().ok(traducao(2070),traducao(2075))
def download(url, dest, title=None, referer=None, agent=None, cookie=None, silent=False): if not title: title = 'Kodi Download' if not referer: referer = '' if not agent: agent = '' if not cookie: cookie = '' #quote parameters url = urllib.quote_plus(url) dest = urllib.quote_plus(dest) title = urllib.quote_plus(title) referer = urllib.quote_plus(referer) agent = urllib.quote_plus(agent) cookie = urllib.quote_plus(cookie) script = inspect.getfile(inspect.currentframe()) cmd = 'RunScript(%s, %s, %s, %s, %s, %s, %s, %s)' % (script, url, dest, title, referer, agent, cookie, silent) xbmc.executebuiltin(cmd)
def PASTEBIN(url): try: if url == 'ADD': dialog = xbmcgui.Dialog() dialog.ok("TIP!", 'Read The Readme For Help On Channel Names & CTRL V To Paste') searchStr = '' keyboard = xbmc.Keyboard(searchStr, 'Pastebin Url') keyboard.doModal() if (keyboard.isConfirmed()==False): return searchStr=keyboard.getText() if len(searchStr) == 0: return else: url = searchStr ret = dialog.select('Select A Slot To Save To', ['Slot 1', 'Slot 2']) if ret == 0: save = ADDON.setSetting('PASTE1',url) xbmc.executebuiltin('Container.Refresh') dialog.ok("SAVED", "SAVED") if ret == '1': save = ADDON.setSetting('PASTE2',url) xbmc.executebuiltin('Container.Refresh') dialog.ok("SAVED", "SAVED") except: pass
def ATLES(): r = requests.get('https://voila.metabroadcast.com/1.0/schedules/?annotations=broadcasts,images,description&apiKey=public:64a03c33f9a64c2b80b6f58cd218e5c8&from=now&count=1&id=hmfk,hmfj,hmfh,hmfg,hmff,hmfd,hmfc,hmfb,hm7x,hmb5,hmb4,hkzf,hn46,hn45,hm7h,hn4f,hn4d,hn4b,hmd6,hn4m,hn4k,hn4h,hn4v,hn4w,hn4r,hn4z,hn4x,hn4y,hmv9,hkzr,hk78,hk79,hk76,hkqs,hk72,hmbs,hmbr,hmbq,hmbv,hmbt,hm74,hmbx,hmbc,hmbg,hmbf,hkz5,hkz4,hkz7,hkz6,hmbn,hkz2,hk7n,hk7m,hk7j,hk7k,hk7h,hk7f,hk7g,hk7d,hk7b,hk7c,hk7z,hk7x,hk7y,hk7v,hk7w,hk7t,hk7r,hk7s,hk7p,hk7q,hkzm,hmb2,hkzn,hmb7,hkzh,hkzk,hkzj,hkzd,hkzg,hmb8,hn88,hkzc,hkzb,hkzy,hkzx,hkzz,hkzt,hkzw,hkzv,hkzq,hkzp,hkzs,hm7c,hkwn,hkwm,hkwj,hkwk,hkwh,hkwb,hpb8,hkwz,hkwx,hkwy,hpb2,hn86,hn87,hkwp,hn85,hmwz,hpb6,hkws,hk94,hk95,hk96,hn84,hk92,hpb5,hk99,hpbj,hn8n,hn8b,hpbc,hn8g,hpbz,hpby,hkw9,hkw6,hkw7,hn8p,hkw5,hn8t,hk9d,hk9f,hk9g,hk9b,hk9c,hk9m,hk9n,hk9h,hk9k,hk9t,hk9v,hk9w,hk9p,hk9r,hk9s,hk9x,hk9y,hk9z,hk2d,hk2g,hk2f,hnxn,hk2c,hk2b,hk2m,hnxc,hk2n,hk2h,hk2k,hk2j,hk2t,hk2w,hk2v,hk2q,hk2p,hk2s,hk2r,hnxp,hnxq,hk2y,hk2x,hnxt,hk2z,hkyd,hkyf,hkyg,hkyb,hkyc,hkym,hkyn,hkyh,hkyj,hkyk,hkyt,hkyv,hkyw,hkyp,hkyq,hkyr,hkys,hkyx,hkyy,hkyz,hk25,hk24,hk27,hk26,hk22,hk29,hnx7,hnx4,hmvz,hky4,hky5,hky6,hky7,hky2,hky8,hky9,hkq7,hn5h,hmsm,hn5q,hkq2,hmsy,hn8c,hpbg,hn8z,hn8y,hk6h,hk6k,hk6j,hk6m,hk6n,hk6c,hk6b,hk6d,hk6g,hk6f,hk6y,hk6x,hk6z,hk6q,hk6p,hk6s,hk6r,hk6t,hk6w,hk6v,hn24,hm6z,hm6y,hm6w,hm6t,hn28,hn29,hpbt,hm6h,hm6d,hkrd,hkrg,hkrf,hkrc,hkrb,hkrm,hkrn,hkrh,hkrj,hk69,hk68,hkrv,hkrq,hkrs,hkrr,hk62,hk65,hk64,hk67,hk66,hn2v,hn2q,hn2r,hn2s,hn2x,hm62,hn2d,hn2c,hmzv,hn9t,hn9w,hn9p,hn9y,hn9z,hn9g,hpcf,hn9c,hn9b,hpcm,hn9n,hn9h,hpck,hpcj,hmhb,hk8m,hk8k,hk8j,hk8h,hk8w,hk8v,hk8t,hk8s,hk8r,hk8q,hk8p,hk8z,hk8y,hk8x,hn95,hn94,hn97,hn96,hn92,hk28,hn98,hkrt,hk87,hk86,hk85,hk84,hk82,hk89,hk88,hm2p,hm2w,hm2y,hkv7,hn68,hkqx,hkqy,hkqz,hkqt,hkry,hn64,hkrx,hnxb,hkqk,hkrz,hkvh,hkvk,hkvj,hkvm,hkvn,hkvc,hkvb,hkvd,hkvg,hkvf,hm22,hmcs,hm27,hkvp,hn6x,hn6y,hkq8,hkq9,hmvy,hkq4,hn6r,hn6s,hn6t,hn6v,hn6h,hnws,hn6k,hn6b,hmvc,hn6g,hny5,hny4,hny7,hny2,hmd8,hny9,hn2y,hk52,hk54,hk55,hk56,hk57,hk58,hk59,hmdt,hmdw,hmdv,hmdy,hmdx,hmdz,hkx7,hkx6,hkx5,hkx4,hkx2,hkx9,hkx8,hnyt,hk5b,hk5c,hk5d,hk5f,hk5g,hk5h,hk5j,hk5k,hk5m,hk5n,hnyz,hk5p,hk5q,hk5r,hnyf,hk5t,hk5v,hk5w,hk5x,hk5y,hk5z,hnyj,hmd5,hkxf,hmd7,hkxd,hkxc,hkxb,hmd2,hkxk,hkxj,hkxh,hkxw,hkxv,hk5s,hkxs,hkxr,hkxq,hkxp,hkxz,hkxy,hkxx,hmyz,hmyn,hmyj,hmyk,hmd4,hpcy,hmrp,hkw4,hn9f,hnzm,hnzn,hnzd,hmd9,hnzf,hkt4,hnzc,hn9m,hnzx,hnzz,hm56,hm54,hm55,hkxt,hn9k,hnz8,hkq6,hnz5,hnz6,hnz7,hnz2,hnx9,hm5c,hn7y,hn7q,hn7t,hn7k,hn7c,hn7d,hpdp,hpdr,hpdw,hpdb,hpdc,hpdd,hpdf,hpdm,hk4c,hk4b,hk4g,hk4f,hk4d,hk4k,hk4j,hk4h,hk4n,hk4m,hk4s,hk4r,hk4q,hk4p,hk4w,hk4v,hk4t,hk4z,hk4y,hk4x,hpc8,hk42,hk47,hk46,hk45,hk44,hk49,hk48,hm77,hmqf,hmqt,hnxg,hnw9,hmc5,hmc6,hnw7,hnw6,hnw5,hnw4,hkz9,hkz8,hnwz,hnwy,hnwx,hmcv,hmcx,hmcy,hmcz,hmpy,hmcb,hmcf,hmcg,hmcj,hmck,hmcm,hmcn,hm4h,hkt7,hm4r,hkt9,hkt8,hm4z,hnbd,hktk,hktj,hkth,hnbh,hktn,hktm,hnxy,hktr,hktq,hktp,hktw,hktv,hktz,hkty,hmxb') match=re.compile('image":"(.+?)".+?parent":{"title":"(.+?)","id":".+?"},"start_date":".+?","id":"(.+?)".+?content":\[{"id":".+?","type":"(.+?)","title":"(.+?)","description":"(.+?)","image":"(.+?)"').findall(r.content) for channel,name,ids,types,title,description,image in match: addDir3('%s - [COLOR yellow] Now: - %s[/COLOR]'%(name,title),ids,15,channel,image,'[COLOR yellow]%s[/COLOR] - %s'%(types,description)) xbmcplugin.setContent(int(sys.argv[1]), 'movies') xbmc.executebuiltin("Container.SetViewMode(515)")
def show_Msg(heading, message, times = 3000, pics = addon_icon): try: xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (heading.encode('utf-8'), message.encode('utf-8'), times, pics.encode('utf-8'))) except Exception, e: print( '[%s]: ShowMessage: Transcoding UTF-8 failed [%s]' % (addon_id, e), 2 ) try: xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (heading, message, times, pics)) except Exception, e: print( '[%s]: ShowMessage: exec failed [%s]' % (addon_id, e), 3 )
def IPTV3(): try: r = requests.get(ADDON.getSetting('PASTE1')) match=re.compile('#EXTINF:.+?,(.+?)[\n<"].+?http(.+?)[\n#>" ]', re.DOTALL).findall(r.text.replace('\n\n','\n')) for name,url in match: GRAB(name,url) except: pass try: r = requests.get(ADDON.getSetting('PASTE2')) match=re.compile('#EXTINF:.+?,(.+?)[\n<"].+?http(.+?)[\n#>" ]', re.DOTALL).findall(r.text.replace('\n\n','\n')) for name,url in match: GRAB(name,url) except: pass try: r = open(ADDON.getSetting('PASTE1'),'r') match=re.compile('#EXTINF:.+?,(.+?)[\n<"].+?http(.+?)[\n#>" ]', re.DOTALL).findall(r.read()) for name,url in match: GRAB(name,url) except: pass try: r = open(ADDON.getSetting('PASTE2'),'r') match=re.compile('#EXTINF:.+?,(.+?)[\n<"].+?http(.+?)[\n#>" ]', re.DOTALL).findall(r.read()) for name,url in match: GRAB(name,url) except: pass xbmcplugin.setContent(int(sys.argv[1]), 'movies') xbmc.executebuiltin("Container.SetViewMode(515)")
def do_scheduled_task(task, isPlaying): global last_check now = datetime.datetime.now() if kodi.get_setting("auto-%s" % task) == "true": if last_check < now - datetime.timedelta(minutes=1): # log_utils.log('Check Triggered: Last: %s Now: %s' % (last_check, now), log_utils.LOGDEBUG) next_run = get_next_run(task) last_check = now else: # hack next_run to be in the future next_run = now + datetime.timedelta(seconds=1) # log_utils.log("Update Status on [%s]: Currently: %s Will Run: %s Last Check: %s" % (task, now, next_run, last_check), xbmc.LOGDEBUG) if now >= next_run: is_scanning = xbmc.getCondVisibility("Library.IsScanningVideo") if not is_scanning: during_playback = kodi.get_setting("%s-during-playback" % (task)) == "true" if during_playback or not isPlaying: log_utils.log("Service: Running Scheduled Task: [%s]" % (task)) builtin = "RunPlugin(plugin://%s/?mode=%s)" % (kodi.get_id(), task) xbmc.executebuiltin(builtin) db_connection.set_setting("%s-last_run" % task, now.strftime("%Y-%m-%d %H:%M:%S.%f")) else: log_utils.log("Service: Playing... Busy... Postponing [%s]" % (task), log_utils.LOGDEBUG) else: log_utils.log("Service: Scanning... Busy... Postponing [%s]" % (task), log_utils.LOGDEBUG)
def oldmeth(): dialog = xbmcgui.Dialog() choice = 1 choice = DIALOG.yesno( 'Close System', '[COLOR %s]You are about to close The Entertainment Center' % COLOR2, 'Would you like to continue?[/COLOR]', nolabel='[B][COLOR red] No Cancel[/COLOR][/B]', yeslabel='[B][COLOR green]Yes Close[/COLOR][/B]') if choice == 0: xbmc.executebuiltin("Action(Close)") return elif choice == 1: pass log_path = xbmc.translatePath('special://logpath') if xbmc.getCondVisibility('system.platform.android'): try: os.system( 'kill $(ps | busybox grep org.xbmc.kodi | busybox awk "{ print $2 }")' ) except: pass try: os.system( 'kill $(ps | busybox grep com.sempermax.spmc16 | busybox awk "{ print $2 }")' ) except: pass try: os.system( 'kill $(ps | busybox grep com.sempermax.spmc | busybox awk "{ print $2 }")' ) except: pass try: os.system( 'kill $(ps | busybox grep org.xbmc.kodi | busybox awk "{ print $2 }")' ) except: pass # if xbmc.getCondVisibility('system.platform.linux'): try: os.system('killall Kodi') except: pass try: os.system('killall SMC') except: pass try: os.system('killall XBMC') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 SMC.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass # if xbmc.getCondVisibility('system.platform.osx'): try: os.system('killall -9 Kodi') except: pass try: os.system('killall -9 SMC') except: pass try: os.system('killall -9 XBMC') except: pass # if xbmc.getCondVisibility('system.platform.ios'): print 'ios' # if xbmc.getCondVisibility('system.platform.atv2'): 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 try: os.system('sudo initctl stop tvmc') except: pass try: os.system('sudo initctl stop smc') except: pass # else: 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 try: os.system('sudo initctl stop tvmc') except: pass try: os.system('sudo initctl stop smc') except: pass # #dialog.ok("WARNING", "Force Close was unsuccessful.","Closing Kodi normally...",'') #xbmc.executebuiltin('Quit') xbmc.executebuiltin('ActivateWindow(ShutdownMenu)')
def __exit__(self, type, value, traceback): xbmc.executebuiltin('Dialog.Close(busydialog)')
def __init__(self): xbmc.executebuiltin('ActivateWindow(busydialog)')
def close_all(): xbmc.executebuiltin('Dialog.Close(all)')
if dp.iscanceled(): raise Exception("Cancelled") dp.close() def ExtractorClass(_in, _out): dp = xbmcgui.DialogProgress() zin = zipfile.ZipFile(_in, 'r') nFiles = float(len(zin.infolist())) count = 0 for item in zin.infolist(): count += 1 update = count / nFiles * 100 zin.extract(item, _out) if __name__ == '__main__': dialog = xbmcgui.Dialog() try: DownloaderClass(url,lib) except: xbmc.executebuiltin('Notification(Download Failed,Please Try Again Later,50000,special://skin/icon.png)') time.sleep(1) try: ExtractorClass(lib,home) except: xbmc.executebuiltin('Notification(Install Failed, Is Super Favourites installed?,special://home/addons/script.jedi.guide/icon.png)') time.sleep(1) os.remove(path + "/PSF.zip") xbmc.executebuiltin('Notification(Personal Super Favs, Updated,special://home/addons/script.jedi.guide/icon.png)') time.sleep(1)
import sys import xbmc if __name__ == '__main__': item = sys.listitem message = item.getLabel() path = item.getPath() if 'action=showSeasons' in path: path = path.replace('action=showSeasons', 'action=shufflePlay') if 'action=smartPlay' in path: path = path.replace('action=smartPlay', 'action=shufflePlay') if 'action=getSources' in path: path = path.replace('action=getSources', 'action=shufflePlay') if 'action=playbackResume' in path: path = path.replace('action=playbackResume', 'action=shufflePlay') xbmc.executebuiltin('RunPlugin(%s)' % path)
def SHOW_PICTURE(url): SHOW = "ShowPicture(" + url + ')' xbmc.executebuiltin(SHOW) sys.exit(1)
def back_dir(): # back one directory xbmc.executebuiltin('Action(ParentDir)')
def run_plugin(url): xbmc.executebuiltin(run_plugin_builtin_url(url))
def omfci(): if xbmc.getCondVisibility('system.platform.android'): try: os.system( 'kill $(ps | busybox grep org.xbmc.kodi | busybox awk "{ print $2 }")' ) except: pass try: os.system( 'kill $(ps | busybox grep com.sempermax.spmc16 | busybox awk "{ print $2 }")' ) except: pass try: os.system( 'kill $(ps | busybox grep com.sempermax.spmc | busybox awk "{ print $2 }")' ) except: pass try: os.system( 'kill $(ps | busybox grep org.xbmc.kodi | busybox awk "{ print $2 }")' ) except: pass # if xbmc.getCondVisibility('system.platform.linux'): try: os.system('killall Kodi') except: pass try: os.system('killall SMC') except: pass try: os.system('killall XBMC') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 SMC.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass # if xbmc.getCondVisibility('system.platform.osx'): try: os.system('killall -9 Kodi') except: pass try: os.system('killall -9 SMC') except: pass try: os.system('killall -9 XBMC') except: pass # if xbmc.getCondVisibility('system.platform.ios'): print 'ios' # if xbmc.getCondVisibility('system.platform.atv2'): 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 try: os.system('sudo initctl stop tvmc') except: pass try: os.system('sudo initctl stop smc') except: pass # else: 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 try: os.system('sudo initctl stop tvmc') except: pass try: os.system('sudo initctl stop smc') except: pass # #dialog.ok("WARNING", "Force Close was unsuccessful.","Closing Kodi normally...",'') #xbmc.executebuiltin('Quit') xbmc.executebuiltin('ActivateWindow(ShutdownMenu)')
def HomePage(item): xbmc.executebuiltin( "ReplaceWindow(10024,plugin://plugin.video.streamondemand)")
def busy_indicator(): xbmc.executebuiltin('ActivateWindow(busydialog)') try: yield finally: xbmc.executebuiltin('Dialog.Close(busydialog)')
def notification(header="", message="", sleep=5000): xbmc.executebuiltin("XBMC.Notification(%s,%s,%i)" % (header, message, sleep))
def refresh(): # refresh directory xbmc.executebuiltin('Container.Refresh')
def UpdateAddonRepos(self): return xbmc.executebuiltin("UpdateAddonRepos")
def SetView(name): if name == 'Wall': try: xbmc.executebuiltin('Container.SetViewMode(500)') except: pass if name == 'List': try: xbmc.executebuiltin('Container.SetViewMode(50)') except: pass if name == 'Poster': try: xbmc.executebuiltin('Container.SetViewMode(51)') except: pass if name == 'Shift': try: xbmc.executebuiltin('Container.SetViewMode(53)') except: pass if name == 'InfoWall': try: xbmc.executebuiltin('Container.SetViewMode(54)') except: pass if name == 'WideList': try: xbmc.executebuiltin('Container.SetViewMode(55)') except: pass if name == 'Fanart': try: xbmc.executebuiltin('Container.SetViewMode(502)') except: pass
def InstallAddon(self, addonId): return xbmc.executebuiltin("InstallAddon(%s)" % addonId)
def check_mode(mode=''): mode = _addon.queries.get('mode', None) section = _addon.queries.get('section', '') genre = _addon.queries.get('genre', '') letter = _addon.queries.get('letter', '') sort = _addon.queries.get('sort', '') url = _addon.queries.get('url', '') title = _addon.queries.get('title', '') img = _addon.queries.get('img', '') season = _addon.queries.get('season', '') query = _addon.queries.get('query', '') page = _addon.queries.get('page', '') imdbnum = _addon.queries.get('imdbnum', '') year = _addon.queries.get('year', '') video_type = _addon.queries.get('video_type', '') episode = _addon.queries.get('episode', '') season = _addon.queries.get('season', '') tvdbnum = _addon.queries.get('tvdbnum', '') alt_id = _addon.queries.get('alt_id', '') dialog = _addon.queries.get('dialog', '') day = _addon.queries.get('day', '') movie_num = _addon.queries.get('movie_num', '') WhereAmI('@ Checking Mode') deb('Mode', mode) if (mode == '') or (mode == 'main') or (mode == 'MainMenu'): Menu_MainMenu() ## Default Menu elif (mode == 'PlayURL'): PlayURL(_param['url']) ## Play Video elif (mode == 'play'): play(params) ## Play Video elif (mode == 'DocSubMenu'): Documentary_Sub_Menu(_param['title'], movie_num) ## Play Video elif (mode == 'ClipsSubMenu'): Clips_Sub_Menu(_param['title']) ## Play Video elif (mode == 'NightlyNewsSubMenu'): Nightly_News_Sub_Menu(_param['title'], dialog) ## Play Video elif (mode == 'HistoricShowsSubMenu'): Historic_Shows_Sub_Menu(_param['title']) ## Play Video elif (mode == 'HistoricShowsAudioSubMenu'): Historic_Shows_Audio_Sub_Menu(_param['title']) ## Play Video elif (mode == 'Settings'): _addon.addon.openSettings( ) # Another method: _plugin.openSettings() ## Settings for this addon. elif (mode == 'ResolverSettings'): urlresolver.display_settings( ) ## Settings for UrlResolver script.module. elif (mode == 'add_to_library'): add_to_library(video_type, url, title, img, year, imdbnum, movie_num) builtin = "XBMC.Notification(Add to Library,Added '%s' to library,2000, %s)" % ( title, _artIcon) xbmc.executebuiltin(builtin) # # #elif (mode=='YourMode'): YourFunction(_param['url']) # # # else: myNote(header='Mode: "' + mode + '"', msg='[ mode ] not found.') Menu_MainMenu( ) ## So that if a mode isn't found, it'll goto the Main Menu and give you a message about it.
def Dialog_CloseAll(self, *args, **kwargs): return xbmc.executebuiltin("Dialog.Close(all, true)")
def UpdateLocalAddons(self): return xbmc.executebuiltin("UpdateLocalAddons")
def PlayStream(sourceEtree, urlSoup, name, url): try: #url = urlSoup.url.text pDialog = xbmcgui.DialogProgress() pDialog.create('XBMC', 'Parsing the xml file') pDialog.update(10, 'fetching channel info') title = '' link = '' sc = '' try: link = urlSoup.item.link.text sc = sourceEtree.findtext('sname') title = urlSoup.item.title.text except: pass if link == '': timeD = 2000 #in miliseconds line1 = "couldn't read title and link" xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (__addonname__, line1, timeD, __icon__)) return False regexs = urlSoup.find('regex') pDialog.update(20, 'Parsing info') if (not regexs == None) and len(regexs) > 0: liveLink = getRegexParsed(urlSoup, link) else: liveLink = link if len(liveLink) == 0: timeD = 2000 #in miliseconds line1 = "couldn't read title and link" xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (__addonname__, line1, timeD, __icon__)) return False timeD = 2000 #in miliseconds line1 = "Resource found,playing now." pDialog.update(30, line1) liveLink = replaceSettingsVariables(liveLink) name += '-' + sc + ':' + title if (sc == 'GLArab' or sc == 'Local') and '$GL-' in liveLink: gcid = None try: gcid = urlSoup.item.glchannelid.text if gcid and len(gcid) == 0: gcid = None except: pass liveLink = replaceGLArabVariables(liveLink, pDialog, gcid, title) if liveLink == "": return False print 'liveLink', liveLink pDialog.close() listitem = xbmcgui.ListItem( label=str(name), iconImage="DefaultVideo.png", thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"), path=liveLink) if not 'plugin.video.f4mTester' in liveLink: player = CustomPlayer.MyXBMCPlayer() start = time.time() #xbmc.Player().play( liveLink,listitem) player.play(liveLink, listitem) xbmc.sleep(2000) while player.is_active: xbmc.sleep(200) #return player.urlplayed done = time.time() elapsed = done - start if player.urlplayed and elapsed >= 3: return True else: return False else: xbmc.executebuiltin('XBMC.RunPlugin(' + liveLink + ')') return True except: traceback.print_exc(file=sys.stdout) return False
def Refresh(self): return xbmc.executebuiltin("Container.Refresh")
def PlayUrl(name, url, iconimage=None): url = url.replace("\n", "").replace("\r", "") if not url.endswith(".ts") and not url.endswith(".f4m") and url.find( ".f4m?") < 0 and not url.endswith("Player=HLS"): if url.endswith("?time="): url = url + str(time.time()) print '--- Playing "{0}". {1}'.format(name, url) listitem = xbmcgui.ListItem(path=url, thumbnailImage=iconimage) listitem.setInfo(type="Video", infoLabels={"Title": name}) xbmc.Player().play(url, listitem) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem) xbmc.sleep(1000) xbmc.executebuiltin('Dialog.Close(all, true)') else: if xbmc.Player().isPlaying(): xbmc.executebuiltin("XBMC.Action(Stop)") xbmc.sleep(4000) xbmc.executebuiltin('Dialog.Close(all, true)') #xbmc.executebuiltin("XBMC.Container.Refresh()") if Addon.getSetting('use_shani') == "true": MyF4m = False else: MyF4m = True if url.endswith(".ts"): StreamType = 'TSDOWNLOADER' elif url.find("Player=HLS") > 0: StreamType = 'HLS' else: StreamType = 'HDS' if MyF4m: url = 'plugin://plugin.video.kodilivetv/?url=' + urllib.quote_plus( url) + '&streamtype=' + StreamType + '&name=' + urllib.quote( name) + '&mode=5&iconimage=' + iconimage xbmc.executebuiltin('XBMC.RunPlugin(' + url + ')') xbmc.executebuiltin('Dialog.Close(all, true)') else: f4mDir = xbmcaddon.Addon('plugin.video.f4mTester').getAddonInfo( 'path').decode("utf-8") if not os.path.exists(f4mDir): AddonID = 'plugin.video.kodilivetv' addon = xbmcaddon.Addon(AddonID) addonname = addon.getAddonInfo('name') icon = xbmcaddon.Addon(AddonID).getAddonInfo('icon') xbmc.executebuiltin( 'Notification(%s, %s, %d, %s)' % (addonname, "Plugin f4mTester required!", 3200, icon)) else: url = 'plugin://plugin.video.f4mTester/?url=' + urllib.quote_plus( url ) + '&streamtype=' + StreamType + '&name=' + urllib.quote( name) + '&iconImage=' + iconimage xbmc.executebuiltin('XBMC.RunPlugin(' + url + ')') xbmc.executebuiltin('Dialog.Close(all, true)')
def AddonSettings(self, addonId): return xbmc.executebuiltin("Addon.OpenSettings(%s)" % addonId)
def getGameUrl(video_id, video_type, video_ishomefeed): log("cookies: %s %s" % (video_type, vars.cookies), xbmc.LOGDEBUG) # video_type could be archive, live, condensed or oldseason if video_type not in ["live", "archive", "condensed"]: video_type = "archive" url = 'http://watch.nba.com/nba/servlets/publishpoint' headers = { 'Cookie': vars.cookies, 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'iPad' if video_type == "live" else "AppleCoreMedia/1.0.0.8C148a (iPad; U; CPU OS 6_2_1 like Mac OS X; en_us)", } body = { 'id': str(video_id), 'gt': video_type + ("away" if not video_ishomefeed else ""), 'type': 'game', 'plid': vars.player_id, 'nt': '1' } if video_type != "live": body['format'] = 'xml' body = urllib.urlencode(body) log("the body of publishpoint request is: %s" % body, xbmc.LOGDEBUG) try: request = urllib2.Request(url, body, headers) response = urllib2.urlopen(request) content = response.read() except urllib2.HTTPError as e: log("Failed to get video url. The url was %s, the content was %s" % (url, e.read())) xbmc.executebuiltin('Notification(NBA League Pass,Failed to get a video URL. Are you logged in?,5000,)') return '' xml = parseString(str(content)) url = xml.getElementsByTagName("path")[0].childNodes[0].nodeValue log(url, xbmc.LOGDEBUG) selected_video_url = '' if video_type == "live": # transform the url match = re.search('http://([^:]+)/([^?]+?)\?(.+)$', url) domain = match.group(1) arguments = match.group(2) querystring = match.group(3) livecookies = "nlqptid=%s" % (querystring) livecookiesencoded = urllib.quote(livecookies) log("live cookie: %s %s" % (querystring, livecookies), xbmc.LOGDEBUG) url = "http://%s/%s?%s" % (domain, arguments, querystring) url = getGameUrlWithBitrate(url, video_type) selected_video_url = "%s|Cookie=%s" % (url, livecookiesencoded) else: # Archive and condensed flow: We now work with HLS. # The cookies are already in the URL and the server will supply them to ffmpeg later. selected_video_url = getGameUrlWithBitrate(url, video_type) if selected_video_url: log("the url of video %s is %s" % (video_id, selected_video_url), xbmc.LOGDEBUG) return selected_video_url
path = xbmc.translatePath( 'special://profile/addon_data/script.jedi.guide/source.db') try: conn = sqlite3.connect(path, detect_types=sqlite3.PARSE_DECLTYPES) except Exception as detail: xbmc.log("EXCEPTION: (script.jedi.guide) %s" % detail, xbmc.LOGERROR) c = conn.cursor() c.execute('SELECT stream_url FROM custom_stream_url WHERE channel=?', [channel]) row = c.fetchone() if row: url = row[0] ADDON.setSetting('playing.channel', channel) ADDON.setSetting('playing.start', start) if xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"): try: if ADDON.getSetting('vpnmgr.connect') == "true": vpndefault = False if ADDON.getSetting('vpnmgr.default') == "true": vpndefault = True api = VPNAPI() if url[0:9] == 'plugin://': api.filterAndSwitch(url, 0, vpndefault, True) else: if vpndefault: api.defaultVPN(True) except: pass xbmc.executebuiltin('PlayMedia(%s)' % url)
def addonsettings(url,description): url = buildcleanurl(url) if url =="CC": tools.clear_cache() elif url =="AS": xbmc.executebuiltin('Addon.OpenSettings(%s)'%user.id) elif url =="ADS": dialog = xbmcgui.Dialog().select('Edit Advanced Settings', ['Enable Fire TV Stick AS','Enable Fire TV AS','Enable 1GB Ram or Lower AS','Enable 2GB Ram or Higher AS','Enable Nvidia Shield AS','Disable AS']) if dialog==0: advancedsettings('stick') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==1: advancedsettings('firetv') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==2: advancedsettings('lessthan') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==3: advancedsettings('morethan') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==4: advancedsettings('shield') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==5: advancedsettings('remove') xbmcgui.Dialog().ok(user.name, 'Advanced Settings Removed') elif url =="ADS2": dialog = xbmcgui.Dialog().select('Select Your Device Or Closest To', ['Fire TV Stick ','Fire TV','1GB Ram or Lower','2GB Ram or Higher','Nvidia Shield']) if dialog==0: advancedsettings('stick') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==1: advancedsettings('firetv') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==2: advancedsettings('lessthan') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==3: advancedsettings('morethan') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif dialog==4: advancedsettings('shield') xbmcgui.Dialog().ok(user.name, 'Set Advanced Settings') elif url =="tv": dialog = xbmcgui.Dialog().yesno(user.name,'Would You like us to Setup the TV Guide for You?') if dialog: pvrsetup() xbmcgui.Dialog().ok(user.name, 'PVR Integration Complete, Restart Kodi For Changes To Take Effect') elif url =="ST": xbmc.executebuiltin('Runscript("special://home/addons/'+user.id+'/resources/modules/speedtest.py")') elif url =="META": if 'ON' in description: xbmcaddon.Addon().setSetting('meta','false') xbmc.executebuiltin('Container.Refresh') else: xbmcaddon.Addon().setSetting('meta','true') xbmc.executebuiltin('Container.Refresh') elif url =="XXX": if 'ON' in description: xbmcaddon.Addon().setSetting('hidexxx','false') xbmc.executebuiltin('Container.Refresh') else: xbmcaddon.Addon().setSetting('hidexxx','true') xbmc.executebuiltin('Container.Refresh') elif url =="LO": xbmcaddon.Addon().setSetting('Username','') xbmcaddon.Addon().setSetting('Password','') xbmc.executebuiltin('XBMC.ActivateWindow(Videos,addons://sources/video/)') xbmc.executebuiltin('Container.Refresh') elif url =="UPDATE": if 'ON' in description: xbmcaddon.Addon().setSetting('update','false') xbmc.executebuiltin('Container.Refresh') else: xbmcaddon.Addon().setSetting('update','true') xbmc.executebuiltin('Container.Refresh')
portNum = 65007 try: portNum = int(Addon.getSetting("LiveStreamerPort")) except: pass pvrStoped = False useIPTV = False if Addon.getSetting("useIPTV") == "true": import livestreamersrv, myIPTV try: livestreamersrv.start(portNum) useIPTV = True autoIPTV = int(Addon.getSetting("autoIPTV")) if autoIPTV == 0 or autoIPTV == 2: xbmc.executebuiltin('StopPVRManager') pvrStoped = True except Exception as ex: print ex user_dataDir = xbmc.translatePath( Addon.getAddonInfo("profile")).decode("utf-8") if not os.path.exists(user_dataDir): os.makedirs(user_dataDir) remoteSettingsFile = os.path.join(user_dataDir, "remoteSettings.txt") plxFile = os.path.join(user_dataDir, "israelive.plx") globalGuideFile = os.path.join(user_dataDir, "guide.txt") filmonGuideFile = os.path.join(user_dataDir, 'filmonGuide.txt') fullGuideFile = os.path.join(user_dataDir, 'fullGuide.txt') iptvChannelsFile = os.path.join(user_dataDir, "iptv.m3u")
def tvguide(): xbmc.executebuiltin('ActivateWindow(TVGuide)')
def addGamesLinks(fromDate = '', video_type = "archive"): try: schedule = 'http://smb.cdnak.neulion.com/fs/nba/feeds_s2012/schedule/' +fromDate + '.js?t=' + "%d" %time.time() log('Requesting %s' % schedule, xbmc.LOGDEBUG) now_datetime_est = nowEST() # http://smb.cdnak.neulion.com/fs/nba/feeds_s2012/schedule/2013/10_7.js?t=1381054350000 req = urllib2.Request(schedule, None); response = str(urllib2.urlopen(req).read()) js = json.loads(response[response.find("{"):]) for game in js['games']: log(game, xbmc.LOGDEBUG) for details in game: h = details.get('h', '') v = details.get('v', '') game_id = details.get('id', '') game_start_date_est = details.get('d', '') vs = details.get('vs', '') hs = details.get('hs', '') gs = details.get('gs', '') video_has_away_feed = False video_details = details.get('video', {}) video_has_away_feed = video_details.get("af", False) # Try to convert start date to datetime try: game_start_datetime_est = datetime.datetime.strptime(game_start_date_est, "%Y-%m-%dT%H:%M:%S.%f" ) except: game_start_datetime_est = datetime.datetime.fromtimestamp(time.mktime(time.strptime(game_start_date_est, "%Y-%m-%dT%H:%M:%S.%f"))) #Set game start date in the past if python can't parse the date #so it doesn't get flagged as live or future game and you can still play it #if a video is available if type(game_start_datetime_est) is not datetime.datetime: game_start_datetime_est = now_datetime_est + timedelta(-30) #guess end date by adding 4 hours to start date game_end_datetime_est = game_start_datetime_est + timedelta(hours=4) if game_id != '': # Get pretty names for the team names if v.lower() in vars.teams: visitor_name = vars.teams[v.lower()] else: visitor_name = v if h.lower() in vars.teams: host_name = vars.teams[h.lower()] else: host_name = h has_video = "video" in details future_video = game_start_datetime_est > now_datetime_est and \ game_start_datetime_est.date() == now_datetime_est.date() live_video = game_start_datetime_est < now_datetime_est < game_end_datetime_est # Create the title name = game_start_datetime_est.strftime("%Y-%m-%d") if video_type == "live": name = toLocalTimezone(game_start_datetime_est).strftime("%Y-%m-%d (at %I:%M %p)") #Add the teams' names and the scores if needed name += ' %s vs %s' % (visitor_name, host_name) if vars.scores == '1' and not future_video: name += ' %s:%s' % (str(vs), str(hs)) thumbnail_url = ("http://e1.cdnl3.neulion.com/nba/player-v4/nba/images/teams/%s.png" % h) if video_type == "live": if future_video: name = "UPCOMING: " + name elif live_video: name = "LIVE: " + name add_link = True if video_type == "live" and not (live_video or future_video): add_link = False elif video_type != "live" and (live_video or future_video): add_link = False elif not future_video and not has_video: add_link = False if add_link == True: params = { 'video_id': game_id, 'video_type': video_type, 'video_hasawayfeed': 1 if video_has_away_feed else 0 } # Add a directory item that contains home/away/condensed items addListItem(name, url="", mode="gamechoosevideo", iconimage=thumbnail_url, isfolder=True, customparams=params) except Exception, e: xbmc.executebuiltin('Notification(NBA League Pass,'+str(e)+',5000,)') log(str(e)) pass