def _kaid_conf_upload( self ): """ uploads the kai configuration file to the router """ if ( self.settings[ "upload_method" ] == 1 ): command = self.router_settings[ "wget_ftp_kaid_conf" ] % ( self.settings[ "xbox_user" ], self.settings[ "xbox_pwd" ], xbmc.getIPAddress(), self.settings[ "path_to_kaid_conf" ].replace( ":" , "" ).replace( "\\", "/" ), self.router_settings[ "conf_filename" ], ) else: command = self.router_settings[ "wget_http_kaid_conf" ] % ( xbmc.getIPAddress(), self.settings[ "path_to_kaid_conf" ].replace( ":" , "" ).replace( "\\", "/" ), self.router_settings[ "conf_filename" ], ) ok, result = self._do_command( command ) return ok
def _kaid_upload( self ): """ uploads the kai daemon to the router """ ok = self._kaid_kill() if ( self.settings[ "upload_method" ] == 1 ): command = self.router_settings[ "wget_ftp_kaid" ] % ( self.settings[ "xbox_user" ], self.settings[ "xbox_pwd" ], xbmc.getIPAddress(), self.settings[ "path_to_kaid" ].replace( ":" , "" ).replace( "\\", "/" ), self.router_settings[ "bin_filename" ], ) else: command = self.router_settings[ "wget_http_kaid" ] % ( xbmc.getIPAddress(), self.settings[ "path_to_kaid" ].replace( ":" , "" ).replace( "\\", "/" ), self.router_settings[ "bin_filename" ], ) ok, result = self._do_command( command ) if ( ok ): ok = self._kaid_conf_upload() return ok
def get_sources(self, url): logger.debug('%s SOURCES URL %s' % (self.__class__, url)) try: sources = [] if url == None: return sources try: import xbmc ip = xbmc.getIPAddress() except: ip = 'London' url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url) sources.append({ 'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url, 'direct': True }) logger.debug('%s SOURCES [%s]' % (__name__, sources)) return sources except: return sources
def discover(self): ssdpDiscover = ('M-SEARCH * HTTP/1.1\r\n' + 'HOST: 239.255.255.250:1900\r\n' + 'MAN: "ssdp:discover"\r\n' + 'MX: 1\r\n' + 'ST: ssdp:all\r\n' + '\r\n') try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(ssdpDiscover.encode('ASCII'), ('239.255.255.250', 1900)) sock.settimeout(self.timeout) except socket.error as e: display_message( '%s: %s' % (self.addon.getLocalizedString(32023), str(e)), 'ERROR') log_error(str(e), True) service_re = re.compile('location:[ ]*(.+)\r\n', re.IGNORECASE) try: while True: data, addr = sock.recvfrom(1024) result = service_re.search(data.decode('ASCII')) url = result.group(1) if result and (url not in self.services) and ( urlparse(url).hostname != xbmc.getIPAddress()): self.services.add(url) except socket.timeout: sock.close()
def phoneHome(): #gather information such as Pi IP Address and settings information from addon piip = xbmc.getIPAddress() location = __addon__.getSetting("Location") org = __addon__.getSetting("Org") piDee = __addon__.getSetting("PiDee") serverIP = __addon__.getSetting("ServerIP") pidentity = { 'location': location, 'org': org, 'piip': piip, 'piDee': piDee } data = location, piip, org print data try: req = urllib2.Request('http://' + serverIP + ':' + PORT) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, simplejson.dumps(pidentity)) print response except: #Go ahead and play whatever media we knew about if urllib timeouts if (piDee != -1): overrides.digitalSignagePlayer.playSignage()
def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: import xbmc ; ip = xbmc.getIPAddress() except: ip = 'London' referer = 'http://www.einthusan.com/movies/watch.php?id=%s' % url agent = client.randomagent() headers = {'User-Agent': agent, 'Referer': referer} url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url, headers=headers) url +='|%s' % urllib.urlencode({'User-agent': agent}) sources.append({'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url, 'direct': True, 'debridonly': False}) return sources except: return sources
def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: import xbmc ip = xbmc.getIPAddress() except: ip = 'London' referer = 'http://www.einthusan.com/movies/watch.php?id=%s' % url url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url, referer=referer) sources.append({ 'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url, 'direct': True, 'debridonly': False }) return sources except: return sources
def checkDns(): ip = xbmc.getIPAddress() dns1 = xbmc.getInfoLabel('Network.DNS1Address') dns2 = xbmc.getInfoLabel('Network.DNS2Address') gate = xbmc.getInfoLabel('Network.GatewayAddress') logging.warning("MANDRA_DNS") logga("############ START NETWORK INFO ############") logga("## IP: %s" % (ip)) logga("## GATE: %s" % (gate)) logga("## DNS1: %s" % (dns1)) logga("## DNS2: %s" % (dns2)) logga("############# END NETWORK INFO #############") okDns = False if dns1 == "1.1.1.1" or dns1 == "8.8.8.8" or dns1 == gate: okDns = True elif dns1 == "1.0.0.1" or dns1 == "8.8.4.4" or dns1 == gate: okDns = True elif dns2 == "1.1.1.1" or dns2 == "8.8.8.8" or dns2 == gate: okDns = True elif dns2 == "1.1.1.1" or dns2 == "8.8.4.4" or dns2 == gate: okDns = True if okDns == False: dialog = xbmcgui.Dialog() mess = "Con i DNS attualmente impostati, " + dns1 + " - " + dns2 + ",\npotresti avere problemi a recuperare i link da alcuni siti.\nSe puoi, utilizza quelli di CloudFlare [1.1.1.1 - 1.0.0.1]" return dialog.ok("Mandrakodi", mess)
def get_this_system(): """Get this system's local IP address, along with port, username, and password """ port = eval(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.GetSettingValue","params":{"setting":"services.webserverport"}}'))['result']['value'] username = eval(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.GetSettingValue","params":{"setting":"services.webserverusername"}}'))['result']['value'] password = eval(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.GetSettingValue","params":{"setting":"services.webserverpassword"}}'))['result']['value'] # get the IP address from the Remote Downloader "local_ip_address" setting ip = xbmcaddon.Addon('script.remote_downloader').getSetting('local_ip_address') if ip not in ['', '0.0.0.0']: if test_ip_address(ip, port, username, password): return ip, port, username, password # https://stackoverflow.com/a/25850698 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets ip = s.getsockname()[0] if test_ip_address(ip, port, username, password): return ip, port, username, password # get the IP address from the Kodi function ip = xbmc.getIPAddress() timeout = int(xbmcaddon.Addon('script.remote_downloader').getSetting('max_wait_time')) if test_ip_address(ip, port, username, password, timeout=timeout): return ip, port, username, password # failed to get IP address xbmcgui.Dialog().ok('Remote Downloader', "Error: please specify the correct IP address for this system") sys.exit()
def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: import xbmc ip = xbmc.getIPAddress() except: ip = 'London' referer = 'http://www.einthusan.com/movies/watch.php?id=%s' % url agent = client.randomagent() headers = {'User-Agent': agent, 'Referer': referer} url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url, headers=headers) url += '|%s' % urllib.urlencode({'User-agent': agent}) sources.append({ 'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url, 'direct': True, 'debridonly': False }) return sources except: return sources
def __getServerList(self): """ Returns a list of servers from GDM and possibly plex.tv """ self.plx.discoverPMS(xbmc.getIPAddress(), plexToken=self.plexToken) serverlist = self.plx.returnServerList(self.plx.g_PMS) self.logMsg('PMS serverlist: %s' % serverlist, 2) return serverlist
def run(self): self._server = ThreadedHTTPServer(("", self._port), ServerHandler) self._server.daemon_threads = True logging.debug("Server started at port {}".format(self._port)) logging.debug("Local IP: {}".format(xbmc.getIPAddress())) self._server.serve_until_shutdown(self._monitor.abortRequested) self._server.server_close()
def __init__(self, is_exit = True, check_dns = True, view_msg = True, lst_urls = [], lst_site_check_dns = [], in_addon = False): self.ip_addr = xbmc.getIPAddress() self.dns = [xbmc.getInfoLabel('Network.DNS1Address'), xbmc.getInfoLabel('Network.DNS2Address')] self.check_dns = check_dns self.is_exit = is_exit self.lst_urls = lst_urls self.view_msg = view_msg self.lst_site_check_dns = lst_site_check_dns self.urls = []
def getXbmcHttpBaseUrl(): data = open( xbmc.translatePath( "special://userdata/guisettings.xml" ) ).read() webserver = search( '<webserver>(.*?)</webserver>', data ).group( 1 ) password = search( '<webserverpassword>(.*?)</webserverpassword>', data ).group( 1 ) port = search( '<webserverport>(.*?)</webserverport>', data ).group( 1 ) username = search( '<webserverusername>(.*?)</webserverusername>', data ).group( 1 ) xbmcHttp = "http://" if password and username: xbmcHttp += "%s:%s@" % ( username, password ) xbmcHttp += xbmc.getIPAddress() #"localhost" #"107.0.0.1" if port and port != "80": xbmcHttp += ":%s" % port xbmcHttp += "/xbmcCmds/xbmcHttp" return xbmcHttp
def __init__(self, client_id, callback=None): try: self._own_address = xbmc.getIPAddress() except: self._own_address = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] # open discovery udp socket self._s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self._s.bind(('', 27036)) # apperently not necessary self._client_id = client_id self._callback = callback super(DiscoveryClient, self).__init__()
def getXbmcHttpBaseUrl(): data = open( xbmc.translatePath("special://userdata/guisettings.xml")).read() webserver = search('<webserver>(.*?)</webserver>', data).group(1) password = search('<webserverpassword>(.*?)</webserverpassword>', data).group(1) port = search('<webserverport>(.*?)</webserverport>', data).group(1) username = search('<webserverusername>(.*?)</webserverusername>', data).group(1) xbmcHttp = "http://" if password and username: xbmcHttp += "%s:%s@" % (username, password) xbmcHttp += xbmc.getIPAddress() #"localhost" #"107.0.0.1" if port and port != "80": xbmcHttp += ":%s" % port xbmcHttp += "/xbmcCmds/xbmcHttp" return xbmcHttp
def get_sources(self, url, hosthdDict, hostDict, locDict): try: sources = [] if url == None: return sources try: import xbmc ; ip = xbmc.getIPAddress() except: ip = 'London' url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url) sources.append({'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url, 'direct': True}) return sources except: return sources
def get_sources(self, url): logger.debug('%s SOURCES URL %s' % (self.__class__, url)) try: sources = [] if url == None: return sources try: import xbmc ; ip = xbmc.getIPAddress() except: ip = 'London' url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url) sources.append({'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url,'direct':True}) logger.debug('%s SOURCES [%s]' % (__name__,sources)) return sources except: return sources
def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources try: import xbmc ; ip = xbmc.getIPAddress() except: ip = 'London' referer = 'http://www.einthusan.com/movies/watch.php?id=%s' % url url = 'http://cdn.einthusan.com/geturl/%s/hd/%s/' % (url, ip) url = client.request(url, referer=referer) sources.append({'source': 'einthusan', 'quality': 'HD', 'provider': 'Einthusan', 'url': url, 'direct': True, 'debridonly': False}) return sources except: return sources
def phoneHome(): #gather information such as Pi IP Address and settings information from addon piip = xbmc.getIPAddress() location = __addon__.getSetting("Location") org = __addon__.getSetting("Org") piDee = __addon__.getSetting("PiDee") serverIP = __addon__.getSetting("ServerIP") pidentity = {'location' : location, 'org' : org, 'piip' : piip, 'piDee' : piDee} data = location, piip, org print data try: req = urllib2.Request('http://' + serverIP + ':'+PORT) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, simplejson.dumps(pidentity)) print response except: #Go ahead and play whatever media we knew about if urllib timeouts if (piDee != -1): overrides.digitalSignagePlayer.playSignage()
def get_local_ip(): return xbmc.getIPAddress()
if (parameters['action'] == "none"): # No action paramter, so must be run from programs thingy. # Lets show settings for now #__addon__.openSettings() parameters['action'] = "showpresets" if (parameters['action'] == "connect_to_bridge"): progress = xbmcgui.DialogProgress() progress.create(__language__(30007), __language__(30008)) progress.update(0) bridges = hue.BridgeLocator(iprange=xbmc.getIPAddress()).FindBridges(progress=progress.update) bridgeidx = -1; progress.close(); if (len(bridges) == 0): xbmcgui.Dialog().ok(__language__(30009), __language__(30010)) elif (len(bridges) == 1): # Only one bridge, done bridgeidx = 0 bridge = bridges[bridgeidx] xbmccommon.notify(__language__(30011).format(bridge.name)) # Keep output on one line. Name is name + IP e.g. Philips hue (111.112.113.114) else: dialog = xbmcgui.Dialog() bridgenames = ["{0}, {1} ({2})".format(bridge.name, bridge.id, bridge.ip) for bridge in bridges]
def information(self, obfuscate = False): result = {} # Local localIpAddress = xbmc.getIPAddress() localHostName = None if localHostName == None or localHostName == '': try: import platform localHostName = platform.node() except: pass if localHostName == None or localHostName == '': try: import platform localHostName = platform.uname()[1] except: pass if localHostName == None or localHostName == '': try: localHostName = os.uname()[1] except: pass if localHostName == None or localHostName == '': try: import socket localHostName = socket.gethostname() except: pass # Global globalIpAddress = None globalIpName = None globalIpType = None globalProvider = None globalOrganisation = None globalSystem = None globalContinentCode = None globalContinentName = None globalCountryCode = None globalCountryName = None globalRegionCode = None globalRegionName = None globalCityCode = None # Zip code globalCityName = None globalLatitude = None globalLongitude = None if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('https://tools.keycdn.com/geo.json'))['data']['geo'] if 'ip' in result and globalIpAddress in [None, '']: globalIpAddress = result['ip'] if 'rdns' in result and globalIpName in [None, '']: globalIpName = result['rdns'] if 'continent_code' in result and globalContinentCode in [None, '']: globalContinentCode = result['continent_code'] if 'country_name' in result and globalCountryName in [None, '']: globalCountryName = result['country_name'] if 'country_code' in result and globalCountryCode in [None, '']: globalCountryCode = result['country_code'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'postal_code' in result and globalCityCode in [None, '']: globalCityCode = str(result['postal_code']) if 'latitude' in result and globalLatitude in [None, '']: globalLatitude = str(result['latitude']) if 'longitude' in result and globalLongitude in [None, '']: globalLongitude = str(result['longitude']) except: pass if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('http://extreme-ip-lookup.com/json/')) if 'query' in result and globalIpAddress in [None, '']: globalIpAddress = result['query'] if 'ipName' in result and globalIpName in [None, '']: globalIpName = result['ipName'] if 'ipType' in result and globalIpType in [None, '']: globalIpType = result['ipType'] if 'isp' in result and globalProvider in [None, '']: globalProvider = result['isp'] if 'org' in result and globalOrganisation in [None, '']: globalOrganisation = result['org'] if 'continent' in result and globalContinentName in [None, '']: globalContinentName = result['continent'] if 'country' in result and globalCountryName in [None, '']: globalCountryName = result['country'] if 'countryCode' in result and globalCountryCode in [None, '']: globalCountryCode = result['countryCode'] if 'region' in result and globalRegionName in [None, '']: globalRegionName = result['region'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'lat' in result and globalLatitude in [None, '']: globalLatitude = str(result['lat']) if 'lon' in result and globalLongitude in [None, '']: globalLongitude = str(result['lon']) except: pass if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('http://ip-api.com/json')) if 'query' in result and globalIpAddress in [None, '']: globalIpAddress = result['query'] if 'isp' in result and globalProvider in [None, '']: globalProvider = result['isp'] if 'org' in result and globalOrganisation in [None, '']: globalOrganisation = result['org'] if 'as' in result and globalSystem in [None, '']: globalSystem = result['as'] if 'country' in result and globalCountryName in [None, '']: globalCountryName = result['country'] if 'countryCode' in result and globalCountryCode in [None, '']: globalCountryCode = result['countryCode'] if 'regionName' in result and globalRegionName in [None, '']: globalRegionName = result['regionName'] if 'region' in result and globalRegionCode in [None, '']: globalRegionCode = result['region'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'zip' in result and globalCityCode in [None, '']: globalCityCode = str(result['zip']) if 'lat' in result and globalLatitude in [None, '']: globalLatitude = str(result['lat']) if 'lon' in result and globalLongitude in [None, '']: globalLongitude = str(result['lon']) except: pass if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('http://freegeoip.net/json/')) if 'ip' in result and globalIpAddress in [None, '']: globalIpAddress = result['ip'] if 'country_name' in result and globalCountryName in [None, '']: globalCountryName = result['country_name'] if 'country_code' in result and globalCountryCode in [None, '']: globalCountryCode = result['country_name'] if 'region_name' in result and globalRegionName in [None, '']: globalRegionName = result['region_name'] if 'region_code' in result and globalRegionCode in [None, '']: globalRegionCode = result['region_code'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'zip' in result and globalCityCode in [None, '']: globalCityCode = str(result['zip']) if 'latitude' in result and globalLatitude in [None, '']: globalLatitude = str(result['latitude']) if 'longitude' in result and globalLongitude in [None, '']: globalLongitude = str(result['longitude']) except: pass if obfuscate and not globalIpAddress == None: index = globalIpAddress.rfind('.') if index > 0: globalIpAddress = globalIpAddress[:index] globalIpAddress += '.0' globalIpName = None globalIpAddress = None if globalIpAddress == '' else globalIpAddress globalIpName = None if globalIpName == '' else globalIpName globalIpType = None if globalIpType == '' else globalIpType globalProvider = None if globalProvider == '' else globalProvider globalOrganisation = None if globalOrganisation == '' else globalOrganisation globalSystem = None if globalSystem == '' else globalSystem globalContinentCode = None if globalContinentCode == '' else globalContinentCode globalContinentName = None if globalContinentName == '' else globalContinentName globalCountryCode = None if globalCountryCode == '' else globalCountryCode globalCountryName = None if globalCountryName == '' else globalCountryName globalRegionCode = None if globalRegionCode == '' else globalRegionCode globalRegionName = None if globalRegionName == '' else globalRegionName globalCityCode = None if globalCityCode == '' else globalCityCode globalCityName = None if globalCityName == '' else globalCityName globalLatitude = None if globalLatitude == '' else globalLatitude globalLongitude = None if globalLongitude == '' else globalLongitude return { 'local' : { 'connection' : { 'address' : localIpAddress, 'name' : localHostName, }, }, 'global' : { 'connection' : { 'address' : globalIpAddress, 'name' : tools.Converter.unicode(globalIpName), 'type' : globalIpType, 'provider' : tools.Converter.unicode(globalProvider), 'organisation' : tools.Converter.unicode(globalOrganisation), 'system' : tools.Converter.unicode(globalSystem), }, 'location' : { 'continent' : { 'code' : tools.Converter.unicode(globalContinentCode), 'name' : tools.Converter.unicode(globalContinentName), }, 'country' : { 'code' : tools.Converter.unicode(globalCountryCode), 'name' : tools.Converter.unicode(globalCountryName), }, 'region' : { 'code' : tools.Converter.unicode(globalRegionCode), 'name' : tools.Converter.unicode(globalRegionName), }, 'city' : { 'code' : globalCityCode, 'name' : tools.Converter.unicode(globalCityName), }, 'coordinates' : { 'latitude' : tools.Converter.unicode(globalLatitude), 'longitude' : tools.Converter.unicode(globalLongitude), }, }, } }
__settings__ = xbmcaddon.Addon("plugin.program.multiroomaudio") DEFAULT_IMG = xbmc.translatePath(os.path.join( "special://home/", "addons", "plugin.program.multiroomaudio", "icon.png" ) ) ############################################################################################################# def log(msg): try: xbmc.output("[%s]: %s\n" % ("MAV",msg)) except: pass ################################################################################################################# # Starts here ################################################################################################################# ## def _bcasttoggle(self): localhost = xbmc.getIPAddress() port_xbmc = "8080" udp_xbmc = "8278" xbmc_level = "129" url = "http://" + str(localhost) + ":" + str(port_xbmc) + "/xbmcCmds/xbmcHttp?command=SetBroadcast(" + str(xbmc_level) + ";" + str(udp_xbmc) + ")" usock = urllib2.urlopen(url) data = usock.read() usock.close() print data ## xbmc.executebuiltin("Notification(Multiroom Audio,MAV Broadcast Started,10000,"+DEFAULT_IMG+")") log("MAV UDP Sender Started and Running in background...") outsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) bcast = "255.255.255.255" poll = 60 ## Poll time in seconds name = __settings__.getSetting( "sap_name" )
def setup(self, forcePlexTV=False, chooseServer=False): """ Initial setup. Run once upon startup. Check server, user, direct paths, music, direct stream if not direct path. """ string = xbmcaddon.Addon().getLocalizedString # SERVER INFO ##### self.logMsg("Initial setup called.", 0) server = self.userClient.getServer() serverid = utils.settings('plex_machineIdentifier') # Get Plex credentials from settings file, if they exist plexdict = self.plx.GetPlexLoginFromSettings() myplexlogin = plexdict['myplexlogin'] plexLogin = plexdict['plexLogin'] plexToken = plexdict['plexToken'] plexid = plexdict['plexid'] if plexToken: self.logMsg('Found plex.tv token in settings', 0) dialog = xbmcgui.Dialog() # Optionally sign into plex.tv. Will not be called on very first run # as plexToken will be '' if (plexToken and myplexlogin == 'true' and forcePlexTV is False and chooseServer is False): chk = self.plx.CheckConnection('plex.tv', plexToken) try: chk.attrib except: pass else: # Success - we downloaded an xml! chk = 200 # HTTP Error: unauthorized. Token is no longer valid if chk in (401, 403): self.logMsg('plex.tv connection returned HTTP %s' % chk, 0) # Delete token in the settings utils.settings('plexToken', value='') # Could not login, please try again dialog.ok(self.addonName, string(39009)) result = self.plx.PlexTvSignInWithPin() if result: plexLogin = result['username'] plexToken = result['token'] plexid = result['plexid'] elif chk is False or chk >= 400: # Problems connecting to plex.tv. Network or internet issue? self.logMsg('plex.tv connection returned HTTP %s' % str(chk), 0) dialog.ok(self.addonName, string(39010)) else: self.logMsg('plex.tv connection with token successful', 0) # Refresh the info from Plex.tv xml = self.doUtils('https://plex.tv/users/account', authenticate=False, headerOptions={'X-Plex-Token': plexToken}) try: xml.attrib except: self.logMsg('Failed to update Plex info from plex.tv', -1) else: plexLogin = xml.attrib.get('title') utils.settings('plexLogin', value=plexLogin) home = 'true' if xml.attrib.get('home') == '1' else 'false' utils.settings('plexhome', value=home) utils.settings('plexAvatar', value=xml.attrib.get('thumb')) utils.settings( 'plexHomeSize', value=xml.attrib.get('homeSize', '1')) self.logMsg('Updated Plex info from plex.tv', 0) # If a Plex server IP has already been set, return. if server and forcePlexTV is False and chooseServer is False: self.logMsg("Server is already set.", 0) self.logMsg("url: %s, Plex machineIdentifier: %s" % (server, serverid), 0) return # If not already retrieved myplex info, optionally let user sign in # to plex.tv. This DOES get called on very first install run if ((not plexToken and myplexlogin == 'true' and chooseServer is False) or forcePlexTV): result = self.plx.PlexTvSignInWithPin() if result: plexLogin = result['username'] plexToken = result['token'] plexid = result['plexid'] # Get g_PMS list of servers (saved to plx.g_PMS) httpsUpdated = False while True: if httpsUpdated is False: # Populate g_PMS variable with the found Plex servers self.plx.discoverPMS(xbmc.getIPAddress(), plexToken=plexToken) isconnected = False self.logMsg('g_PMS: %s' % self.plx.g_PMS, 1) serverlist = self.plx.returnServerList(self.plx.g_PMS) self.logMsg('PMS serverlist: %s' % serverlist, 2) # Let user pick server from a list # Get a nicer list dialoglist = [] # Exit if no servers found if len(serverlist) == 0: dialog.ok( self.addonName, string(39011) ) break for server in serverlist: if server['local'] == '1': # server is in the same network as client. Add "local" msg = string(39022) else: # Add 'remote' msg = string(39054) if server.get('ownername'): # Display username if its not our PMS dialoglist.append('%s (%s, %s)' % (server['name'], server['ownername'], msg)) else: dialoglist.append('%s (%s)' % (server['name'], msg)) resp = dialog.select(string(39012), dialoglist) server = serverlist[resp] activeServer = server['machineIdentifier'] # Re-direct via plex if remote - will lead to the correct SSL # certificate if server['local'] == '1': url = server['scheme'] + '://' + server['ip'] + ':' \ + server['port'] else: url = server['baseURL'] # Deactive SSL verification if the server is local! # Watch out - settings is cached by Kodi - use dedicated var! if server['local'] == '1': utils.settings('sslverify', 'false') self.logMsg("Setting SSL verify to false, because server is " "local", 1) verifySSL = False else: utils.settings('sslverify', 'true') self.logMsg("Setting SSL verify to true, because server is " "not local", 1) verifySSL = None chk = self.plx.CheckConnection(url, server['accesstoken'], verifySSL=verifySSL) if chk == 504 and httpsUpdated is False: # Not able to use HTTP, try HTTPs for now serverlist[resp]['scheme'] = 'https' httpsUpdated = True continue httpsUpdated = False if chk == 401: # Not yet authorized for Plex server # Please sign in to plex.tv dialog.ok(self.addonName, string(39013) + server['name'], string(39014)) result = self.plx.PlexTvSignInWithPin() if result: plexLogin = result['username'] plexToken = result['token'] plexid = result['plexid'] else: # Exit while loop if user cancels break # Problems connecting elif chk >= 400 or chk is False: # Problems connecting to server. Pick another server? resp = dialog.yesno(self.addonName, string(39015)) # Exit while loop if user chooses No if not resp: break # Otherwise: connection worked! else: isconnected = True break if not isconnected: # Enter Kodi settings instead xbmc.executebuiltin('Addon.OpenSettings(%s)' % self.addonId) return # Write to Kodi settings file utils.settings('plex_machineIdentifier', activeServer) utils.settings('plex_servername', server['name']) utils.settings('plex_serverowned', server['owned']) if server['local'] == '1': scheme = server['scheme'] utils.settings('ipaddress', server['ip']) utils.settings('port', server['port']) else: baseURL = server['baseURL'].split(':') scheme = baseURL[0] utils.settings('ipaddress', baseURL[1].replace('//', '')) utils.settings('port', baseURL[2]) if scheme == 'https': utils.settings('https', 'true') else: utils.settings('https', 'false') self.logMsg("Writing to Kodi user settings file", 0) self.logMsg("PMS machineIdentifier: %s, ip: %s, port: %s, https: %s " % (activeServer, server['ip'], server['port'], server['scheme']), 0) if forcePlexTV is True or chooseServer is True: return goToSettings = False # Direct paths (\\NAS\mymovie.mkv) or addon (http)? if dialog.yesno(heading=self.addonName, line1=string(39027), line2=string(39028), nolabel="Addon (Default)", yeslabel="Native (Direct Paths)"): self.logMsg("User opted to use direct paths.", 1) utils.settings('useDirectPaths', value="1") # Are you on a system where you would like to replace paths # \\NAS\mymovie.mkv with smb://NAS/mymovie.mkv? (e.g. Windows) if dialog.yesno(heading=self.addonName, line1=string(39033)): self.logMsg("User chose to replace paths with smb", 1) else: utils.settings('replaceSMB', value="false") # complete replace all original Plex library paths with custom SMB if dialog.yesno(heading=self.addonName, line1=string(39043)): self.logMsg("User chose custom smb paths", 1) utils.settings('remapSMB', value="true") # Please enter your custom smb paths in the settings under # "Sync Options" and then restart Kodi dialog.ok(heading=self.addonName, line1=string(39044)) goToSettings = True # Go to network credentials? if dialog.yesno(heading=self.addonName, line1=string(39029), line2=string(39030)): self.logMsg("Presenting network credentials dialog.", 1) utils.passwordsXML() # Disable Plex music? if dialog.yesno(heading=self.addonName, line1=string(39016)): self.logMsg("User opted to disable Plex music library.", 1) utils.settings('enableMusic', value="false") if goToSettings: xbmc.executebuiltin( 'Addon.OpenSettings(plugin.video.plexkodiconnect)') else: # Open Settings page now? You will need to restart! if dialog.yesno(heading=self.addonName, line1=string(39017)): utils.window('emby_serverStatus', value="Stop") xbmc.executebuiltin( 'Addon.OpenSettings(plugin.video.plexkodiconnect)')
try: send_json_command_http(kodiip, 80, "Player.Stop", params=[1], id=1) except: pass ### Stop All other Kodis elif methode == 'stopallother': writeLog('STOPALLOTHER Kodis', level=xbmc.LOGNOTICE) notifyheader = "Remote Kodi PVR Info" notifymsg = "Stopping all other Remote Kodis" xbmc.executebuiltin('XBMC.Notification(' + notifyheader + ', ' + notifymsg + ' ,4000,' + __icon__ + ')') localip = xbmc.getIPAddress() for x in range(1, 5): kodiisenabled = __settings__.getSetting("kodienable.%s" % (str(x))) if kodiisenabled == "true": kodiip = __settings__.getSetting("kodiip.%s" % (str(x))) if localip != kodiip: try: send_json_command_http(kodiip, 80, "Player.Stop", params=[1], id=1) except: pass ### Play local stream on all Kodis
import xbmc xml = xbmc.translatePath("special://userdata/guisettings.xml") data = open(xml).read() webserver = re.search('<webserver>(.*?)</webserver>', data).group(1) webserverpassword = re.search('<webserverpassword>(.*?)</webserverpassword>', data).group(1) webserverport = re.search('<webserverport>(.*?)</webserverport>', data).group(1) webserverusername = re.search('<webserverusername>(.*?)</webserverusername>', data).group(1) xbmcHttp = "http://" if webserverpassword and webserverusername: xbmcHttp += "%s:%s@" % (webserverusername, webserverpassword) xbmcHttp += xbmc.getIPAddress() #"localhost" #"107.0.0.1" if webserverport and webserverport != "80": xbmcHttp += ":%s" % webserverport xbmcHttp += "/xbmcCmds/xbmcHttp" #print webserver #print webserverpassword #print webserverport #print webserverusername #print xbmcHttp
def get_platform_ip(): return xbmc.getIPAddress()
class XplPlayer(xbmc.Player): # xPL source name source = "parasit-xbmc." + gethostname().replace("-", "").split(".")[0][:16] xpl = Xpl(source, xbmc.getIPAddress()) lastState = "" lastKind = "" lastAudioTag = None lastVideoTag = None def __init__(self): xbmc.Player.__init__(self) self.xpl.parse = self.parseBroadcast xbmc.log("FA: init completed") def onPlayBackStarted(self): xbmc.log("FA: play") self.monitorXbmc("play") def onPlayBackEnded(self): xbmc.log("FA: stop") self.monitorXbmc("stop") def onPlayBackStopped(self): xbmc.log("FA: stop") self.monitorXbmc("stop") def onPlayBackPaused(self): xbmc.log("FA: pause") self.monitorXbmc("pause") def onPlayBackResumed(self): xbmc.log("FA: play") self.monitorXbmc("play") def parseBroadcast(self, data): xbmc.log("FA, data:" + data) parts = data.split("\n") msgtype = parts[0].lower() offset = 2 values = dict() if parts[offset - 1] == "{": while parts[offset] != "}": part = parts[offset] if part != "}": value = part.split("=") if len(value) == 2: values[value[0].lower()] = value[1] offset = offset + 1 else: break offset = offset + 1 schema = parts[offset].lower() offset = offset + 2 if parts[offset - 1] == "{": while parts[offset] != "}": part = parts[offset] if part != "}": value = part.split("=") if len(value) == 2: values[value[0].lower()] = value[1] offset = offset + 1 else: break if (values['target'] != "*" and values['target'] != "parasit-xbmc.*" and values['target'] != self.source ) or values['source'] == self.source: return if msgtype == "xpl-cmnd": if schema == "osd.basic": if (values['command'].lower() == "write" or values['command'].lower() == "clear"): if (values['text']): displayTime = values.get('delay', "20") self.osdMessage("xPL Message", values['text'].replace("\\n", "\n"), displayTime, "") if schema == "cid.basic" or schema == "cid.netcall" or schema == "cid.meteor": if (values['calltype'].lower() == "inbound"): cln = values['cln'] if (len(cln) == 0): cln = "Incoming\x201A call" self.osdMessage(cln, values['phone'], 20, "phone") if schema == "media.basic": print "Got media command:" + values['command'] if values['command'].lower() == "stop": xbmc.executebuiltin('PlayerControl(Stop)') if values['command'].lower() == "play": xbmc.executebuiltin('PlayerControl(Play)') if values['command'].lower() == "pause": if xbmc.Player().isPlaying(): xbmc.executebuiltin('PlayerControl(Play)') if values['command'].lower() == "skip": xbmc.executebuiltin('PlayerControl(Next)') if schema == "media.request": if values['request'].lower() == "devinfo": self.xpl.sendBroadcast( "xpl-stat", values['source'], "media.devinfo", "name=Boxee xPL Interface\nversion=1.0\nauthor=Sam Steele\ninfo-url=http://www.c99.org/\nmp-list=boxee\n" ) if values['request'].lower() == "devstate": self.xpl.sendBroadcast("xpl-stat", values['source'], "media.devstate", "power=on\nconnected=true\n") if values['request'].lower() == "mpinfo": self.xpl.sendBroadcast( "xpl-stat", values['source'], "media.mpinfo", "mp=xbmc\nname=Boxee\ncommand-list=play,stop,pause,skip\naudio=true\nvideo=true\n" ) if values['request'].lower() == "mptrnspt": self.xpl.sendBroadcast( "xpl-stat", values['source'], "media.mptrnspt", "mp=xbmc\ncommand=" + self.lastState + "\n") if values['request'].lower() == "mpmedia": media = "mp=xbmc\n" if xbmc.Player().isPlaying(): if xbmc.Player().isPlayingAudio(): tag = xbmc.Player().getMusicInfoTag() media = "mp=xbmc\n" media = media + "kind=audio\n" media = media + "title=" + tag.getTitle() + "\n" media = media + "album=" + tag.getAlbum() + "\n" media = media + "artist=" + tag.getArtist() + "\n" media = media + "duration=" + str( xbmc.Player().getTotalTime()) + "\n" media = media + "format=" + os.path.splitext( xbmc.Player().getPlayingFile())[1][1:] + "\n" else: tag = xbmc.Player().getVideoInfoTag() media = "mp=xbmc\n" media = media + "kind=video\n" media = media + "title=" + tag.getTitle() + "\n" media = media + "album=" + "\n" media = media + "artist=" + "\n" media = media + "duration=" + str( xbmc.Player().getTotalTime()) + "\n" media = media + "format=" + os.path.splitext( xbmc.Player().getPlayingFile())[1][1:] + "\n" self.xpl.sendBroadcast("xpl-stat", values['source'], "media.mpmedia", media) def monitorXbmc(self, status): kind = self.lastKind if xbmc.Player().isPlaying(): try: if xbmc.Player().isPlayingAudio(): xbmc.log("Is playing audio") kind = "audio" if kind != self.lastKind: self.lastState = "stop" self.xpl.sendBroadcast( "xpl-trig", "*", "media.mptrnspt", "mp=xbmc\ncommand=stop\nkind=" + self.lastKind) tag = xbmc.Player().getMusicInfoTag() if self.lastAudioTag is None or self.lastAudioTag.getTitle( ) != tag.getTitle() or self.lastAudioTag.getArtist( ) != tag.getArtist() or self.lastAudioTag.getAlbum( ) != tag.getAlbum(): xbmc.log("Try to send broadcast") media = "mp=xbmc\n" media = media + "kind=audio\n" media = media + "title=" + tag.getTitle() + "\n" media = media + "album=" + tag.getAlbum() + "\n" media = media + "artist=" + tag.getArtist() + "\n" media = media + "duration=" + str( xbmc.Player().getTotalTime()) + "\n" media = media + "format=" + os.path.splitext( xbmc.Player().getPlayingFile())[1][1:] + "\n" media = media + "state=" + status + "\n" self.xpl.sendBroadcast("xpl-trig", "*", "media.mpmedia", media) self.lastAudioTag = tag if xbmc.Player().isPlayingVideo(): kind = "video" if kind != self.lastKind: self.lastState = "stop" self.xpl.sendBroadcast( "xpl-trig", "*", "media.mptrnspt", "mp=xbmc\ncommand=stop\nkind=" + self.lastKind) tag = xbmc.Player().getVideoInfoTag() if self.lastVideoTag is None or self.lastVideoTag.getTitle( ) != tag.getTitle(): #media = media + "state=" + status + "\n" media = "mp=xbmc\n" media = media + "kind=video\n" media = media + "title=" + tag.getTitle() + "\n" media = media + "album=" + "\n" media = media + "artist=" + "\n" media = media + "duration=" + str( xbmc.Player().getTotalTime()) + "\n" media = media + "format=" + os.path.splitext( xbmc.Player().getPlayingFile())[1][1:] + "\n" media = media + "state=" + status + "\n" self.xpl.sendBroadcast("xpl-trig", "*", "media.mpmedia", media) self.lastVideoTag = tag except: media = "mp=xbmc\n" media = media + "kind=unknown\n" media = media + "title=Exception, should be playing video but none gotten\n" media = media + "album=\n" media = media + "artist=\n" media = media + "duration=00:00\n" media = media + "format=" + os.path.splitext( xbmc.Player().getPlayingFile())[1][1:] + "\n" media = media + "state=" + status + "\n" self.xpl.sendBroadcast("xpl-trig", "*", "media.mpmedia", media) else: lastAudioTag = None lastVideoTag = None if status != self.lastState: self.xpl.sendBroadcast( "xpl-trig", "*", "media.mptrnspt", "mp=xbmc\ncommand=" + status + "\nkind=" + kind) self.lastState = status self.lastKind = kind # dialog = xbmcgui.Dialog() # dialog.ok('Status', 'Status: %s' % (state)) def osdMessage(self, title, message, displayTimeSeconds, icon): #todo: messages containing , or . will screw stuff up. Must find a way to fix executeString = "Notification(%s,%s,%s,%s)" % ( title, message, str(displayTimeSeconds) + "000", icon) xbmc.log("FA:executeString=" + executeString) xbmc.executebuiltin(executeString) def destroy(self): self.xpl.stop()
def get_intern_ip(): return xbmc.getIPAddress()
sudo = __addon__.getSetting('sudo') housecode = __addon__.getSetting('house') lightadr = __addon__.getSetting('lightadr') lightport = __addon__.getSetting('lightport') lightnum = 0 names = [] types = [] kinds = [] dimms = [] if sudo != '': lightman = 'echo "' + sudo + '" | sudo -S ' + lightman if remote != "0": import urllib2 if remote == "2": log('Check!') lightadr = xbmc.getIPAddress() cmd = ' -d -s -h ' + housecode + ' -p ' + lightport log('Starting Server: ' + lightman + cmd + '\n') try: p = subprocess.Popen(lightman + cmd, stdout=subprocess.PIPE, shell=True) except OSError: msg = 'FAILED: ' + cmd log(msg + '\n', xbmc.LOGDEBUG) out, err = p.communicate() if len(out.splitlines()) > 0: outmsg = str(out.splitlines()[0]) log('Returned: ' + outmsg + '\n', xbmc.LOGDEBUG) lightman = 'http://' + lightadr + ':' + lightport + '/cmd=' # Get Device Settings while True:
def _get(self, key): if key == 'lang': return xbmc.getLanguage() elif key == 'langname': langname = xbmc.getLanguage() if langname.find('Oromo') != -1: langname = 'Oromo' else: for tag in (' (', ';', ','): i = langname.find(tag) if i != -1: langname = langname[0:i] break try: LANGCODE[langname] except KeyError: return 'English' else: return langname elif key == 'langcode': return LANGCODE[self._get('langname')] elif key == 'dvd': state = { 0: 'open', 1: 'notready', 2: 'ready', 3: 'empty', 4: 'present', 5: None } return state[xbmc.getDVDState()] elif key == 'mem': return xbmc.getFreeMem() # MB elif key == 'time': return xbmc.getGlobalIdleTime() elif key == 'skin': return xbmc.getSkinDir() elif key == 'ip': return xbmc.getIPAddress() elif key == 'platform': if self._platform == -1: for platform in ('linux', 'windows', 'android', 'atv2', 'ios', 'osx'): if xbmc.getCondVisibility('system.platform.' + platform): self._platform = platform break else: self._platform = None return self._platform elif key == 'is_64bits': return sys.maxsize > 2**32 elif key == 'support': if not self._support['all']: for src, dst in (('video', 'video'), ('music', 'audio'), ('picture', 'picture')): self._support[dst] = [ x[1:] for x in xbmc.getSupportedMedia(src).split('|') ] self._support['all'].extend(self._support[dst]) return self._support elif key == 'region': if not self._region: for tag in ('dateshort', 'datelong', 'time', 'meridiem', 'tempunit', 'speedunit'): self._region[tag] = xbmc.getRegion(tag) return self._region else: raise AttributeError, key
def information(self, obfuscate = False): result = {} # Local localIpAddress = xbmc.getIPAddress() localHostName = None if localHostName == None or localHostName == '': try: import platform localHostName = platform.node() except: pass if localHostName == None or localHostName == '': try: import platform localHostName = platform.uname()[1] except: pass if localHostName == None or localHostName == '': try: localHostName = os.uname()[1] except: pass if localHostName == None or localHostName == '': try: import socket localHostName = socket.gethostname() except: pass # Global globalIpAddress = None globalIpName = None globalIpType = None globalProvider = None globalOrganisation = None globalSystem = None globalContinentCode = None globalContinentName = None globalCountryCode = None globalCountryName = None globalRegionCode = None globalRegionName = None globalCityCode = None # Zip code globalCityName = None globalLatitude = None globalLongitude = None if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('https://tools.keycdn.com/geo.json'))['data']['geo'] if 'ip' in result and globalIpAddress in [None, '']: globalIpAddress = result['ip'] if 'rdns' in result and globalIpName in [None, '']: globalIpName = result['rdns'] if 'continent_code' in result and globalContinentCode in [None, '']: globalContinentCode = result['continent_code'] if 'country_name' in result and globalCountryName in [None, '']: globalCountryName = result['country_name'] if 'country_code' in result and globalCountryCode in [None, '']: globalCountryCode = result['country_code'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'postal_code' in result and globalCityCode in [None, '']: globalCityCode = str(result['postal_code']) if 'latitude' in result and globalLatitude in [None, '']: globalLatitude = str(result['latitude']) if 'longitude' in result and globalLongitude in [None, '']: globalLongitude = str(result['longitude']) except: pass if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('http://extreme-ip-lookup.com/json/')) if 'query' in result and globalIpAddress in [None, '']: globalIpAddress = result['query'] if 'ipName' in result and globalIpName in [None, '']: globalIpName = result['ipName'] if 'ipType' in result and globalIpType in [None, '']: globalIpType = result['ipType'] if 'isp' in result and globalProvider in [None, '']: globalProvider = result['isp'] if 'org' in result and globalOrganisation in [None, '']: globalOrganisation = result['org'] if 'continent' in result and globalContinentName in [None, '']: globalContinentName = result['continent'] if 'country' in result and globalCountryName in [None, '']: globalCountryName = result['country'] if 'countryCode' in result and globalCountryCode in [None, '']: globalCountryCode = result['countryCode'] if 'region' in result and globalRegionName in [None, '']: globalRegionName = result['region'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'lat' in result and globalLatitude in [None, '']: globalLatitude = str(result['lat']) if 'lon' in result and globalLongitude in [None, '']: globalLongitude = str(result['lon']) except: pass if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('http://ip-api.com/json')) if 'query' in result and globalIpAddress in [None, '']: globalIpAddress = result['query'] if 'isp' in result and globalProvider in [None, '']: globalProvider = result['isp'] if 'org' in result and globalOrganisation in [None, '']: globalOrganisation = result['org'] if 'as' in result and globalSystem in [None, '']: globalSystem = result['as'] if 'country' in result and globalCountryName in [None, '']: globalCountryName = result['country'] if 'countryCode' in result and globalCountryCode in [None, '']: globalCountryCode = result['countryCode'] if 'regionName' in result and globalRegionName in [None, '']: globalRegionName = result['regionName'] if 'region' in result and globalRegionCode in [None, '']: globalRegionCode = result['region'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'zip' in result and globalCityCode in [None, '']: globalCityCode = str(result['zip']) if 'lat' in result and globalLatitude in [None, '']: globalLatitude = str(result['lat']) if 'lon' in result and globalLongitude in [None, '']: globalLongitude = str(result['lon']) except: pass if None in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude] or '' in [globalIpAddress, globalIpName, globalIpType, globalProvider, globalOrganisation, globalSystem, globalContinentName, globalContinentCode, globalCountryName, globalCountryCode, globalRegionName, globalRegionCode, globalCityName, globalCityCode, globalLatitude, globalLongitude]: try: result = json.load(urllib2.urlopen('http://freegeoip.net/json/')) if 'ip' in result and globalIpAddress in [None, '']: globalIpAddress = result['ip'] if 'country_name' in result and globalCountryName in [None, '']: globalCountryName = result['country_name'] if 'country_code' in result and globalCountryCode in [None, '']: globalCountryCode = result['country_name'] if 'region_name' in result and globalRegionName in [None, '']: globalRegionName = result['region_name'] if 'region_code' in result and globalRegionCode in [None, '']: globalRegionCode = result['region_code'] if 'city' in result and globalCityName in [None, '']: globalCityName = result['city'] if 'zip' in result and globalCityCode in [None, '']: globalCityCode = str(result['zip']) if 'latitude' in result and globalLatitude in [None, '']: globalLatitude = str(result['latitude']) if 'longitude' in result and globalLongitude in [None, '']: globalLongitude = str(result['longitude']) except: pass if obfuscate: index = globalIpAddress.rfind('.') if index > 0: globalIpAddress = globalIpAddress[:index] globalIpAddress += '.0' globalIpName = None globalIpAddress = None if globalIpAddress == '' else globalIpAddress globalIpName = None if globalIpName == '' else globalIpName globalIpType = None if globalIpType == '' else globalIpType globalProvider = None if globalProvider == '' else globalProvider globalOrganisation = None if globalOrganisation == '' else globalOrganisation globalSystem = None if globalSystem == '' else globalSystem globalContinentCode = None if globalContinentCode == '' else globalContinentCode globalContinentName = None if globalContinentName == '' else globalContinentName globalCountryCode = None if globalCountryCode == '' else globalCountryCode globalCountryName = None if globalCountryName == '' else globalCountryName globalRegionCode = None if globalRegionCode == '' else globalRegionCode globalRegionName = None if globalRegionName == '' else globalRegionName globalCityCode = None if globalCityCode == '' else globalCityCode globalCityName = None if globalCityName == '' else globalCityName globalLatitude = None if globalLatitude == '' else globalLatitude globalLongitude = None if globalLongitude == '' else globalLongitude return { 'local' : { 'connection' : { 'address' : localIpAddress, 'name' : localHostName, }, }, 'global' : { 'connection' : { 'address' : globalIpAddress, 'name' : tools.Converter.unicode(globalIpName), 'type' : globalIpType, 'provider' : tools.Converter.unicode(globalProvider), 'organisation' : tools.Converter.unicode(globalOrganisation), 'system' : tools.Converter.unicode(globalSystem), }, 'location' : { 'continent' : { 'code' : tools.Converter.unicode(globalContinentCode), 'name' : tools.Converter.unicode(globalContinentName), }, 'country' : { 'code' : tools.Converter.unicode(globalCountryCode), 'name' : tools.Converter.unicode(globalCountryName), }, 'region' : { 'code' : tools.Converter.unicode(globalRegionCode), 'name' : tools.Converter.unicode(globalRegionName), }, 'city' : { 'code' : globalCityCode, 'name' : tools.Converter.unicode(globalCityName), }, 'coordinates' : { 'latitude' : tools.Converter.unicode(globalLatitude), 'longitude' : tools.Converter.unicode(globalLongitude), }, }, } }
import xbmcgui import xbmcaddon import subprocess # plugin constants __plugin__ = "vnc-launcher" __author__ = "jcnventura" __url__ = "http://blog.petrockblock.com/retropie/" __git_url__ = "https://github.com/mcobit/retrosmc/" __credits__ = "mcobit" __version__ = "0.0.2" kdialog = xbmcgui.Dialog() addon = xbmcaddon.Addon(id='plugin.program.vnc-launcher') #keyboard = xbmc.Keyboard("", "Enter server IP", False) #keyboard.doModal() myip = xbmc.getIPAddress() newserverip = kdialog.numeric(3, "Enter server IP", myip) keypass = xbmc.Keyboard("", "Enter password", True) keypass.doModal() if newserverip != "": servip = newserverip if keypass.isConfirmed() and keypass.getText() != "": servpass = keypass.getText() subprocess.Popen('/home/osmc/vnc-client/vncstart2.sh %s %s' % (str(servip), str(servpass)), shell=True)
idx += 1 if (parameters['action'] == "none"): # No action parameter, so must be run from programs thingy. # Lets show presets parameters['action'] = "showpresets" if (parameters['action'] == "connect_to_bridge"): progress = xbmcgui.DialogProgress() progress.create(__language__(30007), __language__(30008)) progress.update(0) bridges = hue.BridgeLocator(iprange=xbmc.getIPAddress(), logfunc=logDebug).FindBridges(progress=progress.update) bridgeidx = -1; progress.close(); if (len(bridges) == 0): xbmcgui.Dialog().ok(__language__(30009), __language__(30010)) elif (len(bridges) == 1): # Only one bridge, done bridgeidx = 0 bridge = bridges[bridgeidx] xbmccommon.notify(__language__(30011).format(bridge.name)) # Keep output on one line. Name is name + IP e.g. Philips hue (111.112.113.114) else: dialog = xbmcgui.Dialog() bridgenames = ["{0} - {1} ({2})".format(bridge.name, bridge.id[-6:].upper(), bridge.ip) for bridge in bridges]
except: ADDON2 = xbmcaddon.Addon(ADDONID) HOME = xbmc.translatePath('special://home') NATIVE = xbmc.translatePath('special://xbmc') ADDONS = os.path.join(HOME, 'addons') PACKAGES = os.path.join(ADDONS, 'packages') ADDON_DATA = xbmc.translatePath('special://profile/addon_data') ADDON_PATH = xbmcaddon.Addon(ADDONID).getAddonInfo("path") OPENWINDOW_DATA = os.path.join(ADDON_DATA, ADDONID) INSTALL_COMPLETE = os.path.join(OPENWINDOW_DATA, 'INSTALL_COMPLETE') RUN_SPEEDTEST = os.path.join(OPENWINDOW_DATA, 'RUN_SPEEDTEST') NON_REGISTERED = os.path.join(OPENWINDOW_DATA, 'unregistered') TARGET_ZIP = os.path.join(PACKAGES, 'target.zip') TEMP_DL_TIME = os.path.join(PACKAGES, 'dltime') XBMC_VERSION = xbmc.getInfoLabel("System.BuildVersion")[:2] IP_ADDRESS = xbmc.getIPAddress() CURRENT_SKIN = xbmc.getSkinDir() KEYWORD_FILE = os.path.join(OPENWINDOW_DATA, 'keyword') INTERNET_ICON = os.path.join(ADDON_PATH, 'resources', 'images', 'internet.png') BRANDING_VID = xbmc.translatePath('special://home/media/branding/intro.mp4') LANGUAGE_ART = os.path.join(ADDON_PATH, 'resources', 'images', 'language.jpg') DEBUG = Addon_Setting(setting='debug') OFFLINE_MODE = Addon_Setting(setting='offline') BASE = Addon_Setting(setting='base') BASE2 = '687474703a2f2f6e6f6f6273616e646e657264732e636f6d2f' adult_store = xbmc.translatePath( 'special://profile/addon_data/script.module.python.koding.aio/adult_store') zip_path = xbmc.translatePath('special://home/addons/packages/~~ZIPS~~') OWSETTINGS = xbmc.translatePath( 'special://profile/addon_data/script.openwindow/settings.xml') branding = xbmc.translatePath('special://home/media/branding/branding.png')
def setup(self, forcePlexTV=False, chooseServer=False): """ Initial setup. Run once upon startup. Check server, user, direct paths, music, direct stream if not direct path. """ string = xbmcaddon.Addon().getLocalizedString # SERVER INFO ##### self.logMsg("Initial setup called.", 0) server = self.userClient.getServer() serverid = utils.settings('plex_machineIdentifier') # Get Plex credentials from settings file, if they exist plexdict = self.plx.GetPlexLoginFromSettings() myplexlogin = plexdict['myplexlogin'] plexLogin = plexdict['plexLogin'] plexToken = plexdict['plexToken'] plexid = plexdict['plexid'] if plexToken: self.logMsg('Found plex.tv token in settings', 0) dialog = xbmcgui.Dialog() # Optionally sign into plex.tv. Will not be called on very first run # as plexToken will be '' if (plexToken and myplexlogin == 'true' and forcePlexTV is False and chooseServer is False): chk = self.plx.CheckConnection('plex.tv', plexToken) try: chk.attrib except: pass else: # Success - we downloaded an xml! chk = 200 # HTTP Error: unauthorized. Token is no longer valid if chk in (401, 403): self.logMsg('plex.tv connection returned HTTP %s' % chk, 0) # Delete token in the settings utils.settings('plexToken', value='') # Could not login, please try again dialog.ok(self.addonName, string(39009)) result = self.plx.PlexTvSignInWithPin() if result: plexLogin = result['username'] plexToken = result['token'] plexid = result['plexid'] elif chk is False or chk >= 400: # Problems connecting to plex.tv. Network or internet issue? self.logMsg('plex.tv connection returned HTTP %s' % str(chk), 0) dialog.ok(self.addonName, string(39010)) else: self.logMsg('plex.tv connection with token successful', 0) # Refresh the info from Plex.tv xml = self.doUtils('https://plex.tv/users/account', authenticate=False, headerOptions={'X-Plex-Token': plexToken}) try: xml.attrib except: self.logMsg('Failed to update Plex info from plex.tv', -1) else: plexLogin = xml.attrib.get('title') utils.settings('plexLogin', value=plexLogin) home = 'true' if xml.attrib.get('home') == '1' else 'false' utils.settings('plexhome', value=home) utils.settings('plexAvatar', value=xml.attrib.get('thumb')) utils.settings( 'plexHomeSize', value=xml.attrib.get('homeSize', '1')) self.logMsg('Updated Plex info from plex.tv', 0) # If a Plex server IP has already been set, return. if server and forcePlexTV is False and chooseServer is False: self.logMsg("Server is already set.", 0) self.logMsg("url: %s, Plex machineIdentifier: %s" % (server, serverid), 0) return # If not already retrieved myplex info, optionally let user sign in # to plex.tv. This DOES get called on very first install run if ((not plexToken and myplexlogin == 'true' and chooseServer is False) or forcePlexTV): result = self.plx.PlexTvSignInWithPin() if result: plexLogin = result['username'] plexToken = result['token'] plexid = result['plexid'] # Get g_PMS list of servers (saved to plx.g_PMS) httpsUpdated = False while True: if httpsUpdated is False: # Populate g_PMS variable with the found Plex servers self.plx.discoverPMS(xbmc.getIPAddress(), plexToken=plexToken) isconnected = False self.logMsg('g_PMS: %s' % self.plx.g_PMS, 1) serverlist = self.plx.returnServerList(self.plx.g_PMS) self.logMsg('PMS serverlist: %s' % serverlist, 2) # Let user pick server from a list # Get a nicer list dialoglist = [] # Exit if no servers found if len(serverlist) == 0: dialog.ok( self.addonName, string(39011) ) break for server in serverlist: if server['local'] == '1': # server is in the same network as client. Add "local" msg = string(39022) else: # Add 'remote' msg = string(39054) if server.get('ownername'): # Display username if its not our PMS dialoglist.append('%s (%s, %s)' % (server['name'], server['ownername'], msg)) else: dialoglist.append('%s (%s)' % (server['name'], msg)) resp = dialog.select(string(39012), dialoglist) server = serverlist[resp] activeServer = server['machineIdentifier'] # Re-direct via plex if remote - will lead to the correct SSL # certificate if server['local'] == '1': url = server['scheme'] + '://' + server['ip'] + ':' \ + server['port'] else: url = server['baseURL'] # Deactive SSL verification if the server is local! # Watch out - settings is cached by Kodi - use dedicated var! if server['local'] == '1': utils.settings('sslverify', 'false') self.logMsg("Setting SSL verify to false, because server is " "local", 1) verifySSL = False else: utils.settings('sslverify', 'true') self.logMsg("Setting SSL verify to true, because server is " "not local", 1) verifySSL = None chk = self.plx.CheckConnection(url, server['accesstoken'], verifySSL=verifySSL) if chk == 504 and httpsUpdated is False: # Not able to use HTTP, try HTTPs for now serverlist[resp]['scheme'] = 'https' httpsUpdated = True continue httpsUpdated = False if chk == 401: # Not yet authorized for Plex server # Please sign in to plex.tv dialog.ok(self.addonName, string(39013) + server['name'], string(39014)) result = self.plx.PlexTvSignInWithPin() if result: plexLogin = result['username'] plexToken = result['token'] plexid = result['plexid'] else: # Exit while loop if user cancels break # Problems connecting elif chk >= 400 or chk is False: # Problems connecting to server. Pick another server? resp = dialog.yesno(self.addonName, string(39015)) # Exit while loop if user chooses No if not resp: break # Otherwise: connection worked! else: isconnected = True break if not isconnected: # Enter Kodi settings instead xbmc.executebuiltin('Addon.OpenSettings(%s)' % self.addonId) return # Write to Kodi settings file utils.settings('plex_machineIdentifier', activeServer) utils.settings('plex_servername', server['name']) utils.settings('plex_serverowned', 'true' if server['owned'] == '1' else 'false') if server['local'] == '1': scheme = server['scheme'] utils.settings('ipaddress', server['ip']) utils.settings('port', server['port']) else: baseURL = server['baseURL'].split(':') scheme = baseURL[0] utils.settings('ipaddress', baseURL[1].replace('//', '')) utils.settings('port', baseURL[2]) if scheme == 'https': utils.settings('https', 'true') else: utils.settings('https', 'false') self.logMsg("Writing to Kodi user settings file", 0) self.logMsg("PMS machineIdentifier: %s, ip: %s, port: %s, https: %s " % (activeServer, server['ip'], server['port'], server['scheme']), 0) if forcePlexTV is True or chooseServer is True: return goToSettings = False # Direct paths (\\NAS\mymovie.mkv) or addon (http)? if dialog.yesno(heading=self.addonName, line1=string(39027), line2=string(39028), nolabel="Addon (Default)", yeslabel="Native (Direct Paths)"): self.logMsg("User opted to use direct paths.", 1) utils.settings('useDirectPaths', value="1") # Are you on a system where you would like to replace paths # \\NAS\mymovie.mkv with smb://NAS/mymovie.mkv? (e.g. Windows) if dialog.yesno(heading=self.addonName, line1=string(39033)): self.logMsg("User chose to replace paths with smb", 1) else: utils.settings('replaceSMB', value="false") # complete replace all original Plex library paths with custom SMB if dialog.yesno(heading=self.addonName, line1=string(39043)): self.logMsg("User chose custom smb paths", 1) utils.settings('remapSMB', value="true") # Please enter your custom smb paths in the settings under # "Sync Options" and then restart Kodi dialog.ok(heading=self.addonName, line1=string(39044)) goToSettings = True # Go to network credentials? if dialog.yesno(heading=self.addonName, line1=string(39029), line2=string(39030)): self.logMsg("Presenting network credentials dialog.", 1) utils.passwordsXML() # Disable Plex music? if dialog.yesno(heading=self.addonName, line1=string(39016)): self.logMsg("User opted to disable Plex music library.", 1) utils.settings('enableMusic', value="false") else: utils.advancedSettingsXML() if goToSettings is False: # Open Settings page now? You will need to restart! goToSettings = dialog.yesno(heading=self.addonName, line1=string(39017)) if goToSettings: utils.window('emby_serverStatus', value="Stop") xbmc.executebuiltin( 'Addon.OpenSettings(plugin.video.plexkodiconnect)') else: xbmc.executebuiltin('RestartApp')
import os import re import xbmc xml = xbmc.translatePath( "special://userdata/guisettings.xml" ) data = open( xml ).read() webserver = re.search( '<webserver>(.*?)</webserver>', data ).group( 1 ) webserverpassword = re.search( '<webserverpassword>(.*?)</webserverpassword>', data ).group( 1 ) webserverport = re.search( '<webserverport>(.*?)</webserverport>', data ).group( 1 ) webserverusername = re.search( '<webserverusername>(.*?)</webserverusername>', data ).group( 1 ) xbmcHttp = "http://" if webserverpassword and webserverusername: xbmcHttp += "%s:%s@" % ( webserverusername, webserverpassword ) xbmcHttp += xbmc.getIPAddress() #"localhost" #"107.0.0.1" if webserverport and webserverport != "80": xbmcHttp += ":%s" % webserverport xbmcHttp += "/xbmcCmds/xbmcHttp" #print webserver #print webserverpassword #print webserverport #print webserverusername #print xbmcHttp
self._setScene("scenePlaying") # Check if the bridge still exists where we expect it __addon__ = xbmcaddon.Addon(id=xbmccommon.ADDON_ID) __language__ = __addon__.getLocalizedString hueAddonSettings = xbmccommon.HueControlSettings() hueBridgeOk = False # Make sure the important settings exist if ("bridgeip" in hueAddonSettings.data and "bridgeid" in hueAddonSettings.data): bridge = hue.BridgeLocator(iprange=xbmc.getIPAddress()).FindBridgeById(hueAddonSettings.data["bridgeid"], hueAddonSettings.data["bridgeip"]) if bridge == None: xbmccommon.notify(__language__(30019), duration=10000) else: bridge.username = hueAddonSettings.data.get("bridgeusername", None) bridge.devicetype = huecontrol.DEVICETYPE.format(xbmc.getInfoLabel('System.FriendlyName')) if not bridge.isAuthorized(): xbmccommon.notify(__language__(30019), duration=10000) else: hueAddonSettings.data["bridgeip"] = bridge.ip hueAddonSettings.data["bridgeid"] = bridge.id if hueAddonSettings.store(): xbmccommon.notify(__language__(30018))
def _get(self, key): if key == 'lang': return xbmc.getLanguage() elif key == 'langname': langname = xbmc.getLanguage() if langname.find('Oromo') != -1: langname = 'Oromo' else: for tag in (' (', ';', ','): i = langname.find(tag) if i != -1: langname = langname[0:i] break try: LANGCODE[langname] except KeyError: return 'English' else: return langname elif key == 'langcode': return LANGCODE[self._get('langname')] elif key == 'dvd': state = {0: 'open', 1: 'notready', 2: 'ready', 3: 'empty', 4: 'present', 5: None} return state[xbmc.getDVDState()] elif key == 'mem': return xbmc.getFreeMem() # MB elif key == 'time': return xbmc.getGlobalIdleTime() elif key == 'skin': return xbmc.getSkinDir() elif key == 'ip': return xbmc.getIPAddress() elif key == 'platform': if self._platform == -1: for platform in ('linux', 'windows', 'android', 'atv2', 'ios', 'osx'): if xbmc.getCondVisibility('system.platform.' + platform): self._platform = platform break else: self._platform = None return self._platform elif key == 'is_64bits': return sys.maxsize > 2**32 elif key == 'support': if not self._support['all']: for src, dst in (('video', 'video'), ('music', 'audio'), ('picture', 'picture')): self._support[dst] = [x[1:] for x in xbmc.getSupportedMedia(src).split('|')] self._support['all'].extend(self._support[dst]) return self._support elif key == 'region': if not self._region: for tag in ('dateshort', 'datelong', 'time', 'meridiem', 'tempunit', 'speedunit'): self._region[tag] = xbmc.getRegion(tag) return self._region else: raise AttributeError, key
def cache_loader(m3u8_url, m3u8_headers={}, segment_headers={}): ip = __addon__.getSetting('ip') if not ip: ip = xbmc.getIPAddress() __addon__.setSetting('ip', ip) port = __addon__.getSetting('port') cache_forward = int(__addon__.getSetting('cache_forward')) download_delay = int(__addon__.getSetting('download_delay')) cache_multiplier = int(__addon__.getSetting('cache_multiplier')) count = int(0) duration = int(0) m3u8_timeout = int(10) m3u8_segment_timeout = int(5) chunk_size = int(1024 * cache_multiplier) segment_error = int(0) max_segment_error = int(0) sess = requests.Session() content_type = 'application/octet-stream' cache_path = os.path.abspath(os.path.join(__addon_path__, 'cache')) new_m3u8_path = os.path.abspath(os.path.join(cache_path, 'hls.m3u8')) try: req = sess.get(url=m3u8_url, stream=False, allow_redirects=True, verify=False, timeout=m3u8_timeout, headers=m3u8_headers) if req.status_code == 200: xbmc.startServer(iTyp=xbmc.SERVER_WEBSERVER, bStart=True, bWait=False) with open(new_m3u8_path, 'wb', buffering=chunk_size) as m3u8: for line in req.iter_lines(): line = line.strip() if line: if line.startswith('http'): m3u8.write( '{0}\n'.format('http://' + ip + ':' + port + '/cache/' + str(count))) count += 1 else: m3u8.write('{0}\n'.format(line)) count = 0 for line in req.iter_lines(): line = line.strip() if line: if line.startswith('#EXTINF:'): match = re.compile(r'#EXTINF:(\d+)', re.DOTALL).search(line) if match: duration = int(match.group(1)) if line.startswith('http'): try: req = sess.get(url=line, stream=True, allow_redirects=True, verify=False, timeout=m3u8_segment_timeout, headers=segment_headers) content_type_header = req.headers.get( 'Content-Type') if content_type_header: match = re.compile( r'(.+?);', re.DOTALL).search(content_type_header) if match: content_type = match.group(1) with open(os.path.abspath( os.path.join(cache_path, str(count))), 'wb', buffering=chunk_size) as fi: while True: chunk = req.raw.read(chunk_size) if not chunk: break else: fi.write(chunk) except: segment_error += 1 if segment_error <= 2: continue elif segment_error > 2: segment_error = 0 max_segment_error += 1 if max_segment_error >= 10: if bool(xbmcgui.Dialog().yesno( heading= '[COLOR red]CACHE LOARDER SEGMENT ERROR[/COLOR]', line1='Maximum segment error X10 reached', line2='', line3='', nolabel='EXIT', yeslabel='CONTINUE', autoclose=0)): max_segment_error = 0 else: break if count == cache_forward: listitem = xbmcgui.ListItem(path='http://' + ip + ':' + port + '/cache/hls.m3u8') listitem.setMimeType(content_type) listitem.setContentLookup(False) xbmcplugin.setResolvedUrl(handle=__addon_handle__, succeeded=True, listitem=listitem) elif count > cache_forward: if not xbmc.getCondVisibility('Player.HasMedia'): break if download_delay > 0: xbmc.sleep(duration * download_delay) count += 1 req.close() while True: if not xbmc.getCondVisibility('Player.HasMedia'): xbmc.startServer(iTyp=xbmc.SERVER_WEBSERVER, bStart=False, bWait=False) clear_dir(cache_path) break else: xbmc.sleep(1500) else: xbmcgui.Dialog().ok('REQUESTS INFO', 'Status code : ' + str(req.status_code)) except Exception as e: xbmcgui.Dialog().ok('[COLOR red]CACHE LOARDER ERROR[/COLOR]', str(e))
""" import xbmc,xbmcgui,xbmcplugin,urllib2,os,sys,subprocess,xbmcvfs,socket,re from utils.pluginxbmc import * from utils.utilities import handle_wait """ Sopcast Dependent variables are listed below""" LISTA_SOP='http://www.sopcast.com/chlist.xml' SPSC_BINARY = "sp-sc-auth" LOCAL_PORT = settings.getSetting('local_port') VIDEO_PORT = settings.getSetting('video_port') BUFER_SIZE = int(settings.getSetting('buffer_size')) if(settings.getSetting('auto_ip')): LOCAL_IP=xbmc.getIPAddress() else: LOCAL_IP=settings.getSetting('localhost') """ Addon functions related to sopcast Main functions: sopstreams(name,iconimage,sop) -> This function processes the id/sop url received as argument and does the magic for windows. If the OS is not windows, it sends the processed url to sopstreams_function sopstreams_builtin(name,iconimage,sop) -> This function processes the url received from sopstreams and does the magic for all *nix based OS's. Classes: SopWindowsPlayer -> Inheritance of XBMC Player class used only for Windows streamplayer -> Inheritance of XBMC Player class used for Linux/osx/Android Sopcast Utils: sop_sleep(time , spsc_pid) -> sopcast_binary pid sleep function. For all supported OS's except Windows.
def handle_request(server, req_method, req_path, origin_header, host_header): if req_path.endswith(RUN_URI): # URL ends with run # Maximum app name length of 255 characters. app_name = req_path.split('/')[-2][:255] # Check authorized origins. if origin_header and not is_allowed_origin(origin_header, app_name): server.call_error(403, 'Forbidden') return # Return OPTIONS. if req_method == 'OPTIONS': server.call_response( OPTIONS_RESPONSE.format(origin=origin_header, methods='DELETE, OPTIONS')) return # DELETE non-empty app name if app_name and req_method == 'DELETE': handle_app_stop(server, app_name, origin_header) else: server.call_error(501, 'Not Implemented') elif req_path.startswith(APPS_URI): # URI starts with "/apps/" and is followed by an app name app_name = req_path.replace(APPS_URI, '') # Check authorized origins. if origin_header and not is_allowed_origin(origin_header, app_name): server.call_error(403, 'Forbidden') return # Return OPTIONS. if req_method == 'OPTIONS': server.call_response( OPTIONS_RESPONSE.format(origin=origin_header, methods='GET, POST, OPTIONS')) return # Start app if req_method == 'POST': handle_app_start(server, app_name, origin_header) # Get app status elif req_method == 'GET': handle_app_status(server, app_name, origin_header) else: server.call_error(501, 'Not Implemented') elif req_path.endswith(HIDE_URI): # URI that ends with HIDE_URI # Maximum app name length of 255 characters. app_name = req_path.split('/')[-2][:255] # Check authorized origins. if origin_header and not is_allowed_origin(origin_header, app_name): server.call_error(403, 'Forbidden') return if req_method == 'OPTIONS': server.call_response( OPTIONS_RESPONSE.format(origin=origin_header, methods='POST, OPTIONS')) return # Hide app if app_name and req_method == 'POST': handle_app_hide(server, app_name, origin_header) else: server.call_error(501, 'Not Implemented') elif req_path.endswith(DIAL_DATA_URI): # URI is of the form */app_name/dial_data # Check if the call come from localhost if server.client_address[0] in ['127.0.0.1', xbmc.getIPAddress()]: app_name = req_path.split('/')[-2] if not app_name: server.call_error(500, '500 Internal Server Error') else: # Check authorized origins. if origin_header and not is_allowed_origin( origin_header, app_name): server.call_error(403, 'Forbidden') return if req_method == 'OPTIONS': server.call_response( OPTIONS_RESPONSE.format(origin=origin_header, methods='POST, OPTIONS')) return # Deliver data payload handle_dial_data(server, app_name, origin_header, req_method == 'POST') else: server.call_error(404, 'Not found')
def getHostname(self): try: return socket.gethostname() except: return xbmc.getIPAddress()
def HeartBeat(): global port SendBroadcast("xpl-stat", "*","hbeat.app", "interval=1\nport=" + str(port) + "\nremote-ip=" + xbmc.getIPAddress()) heartbeat_timer = threading.Timer(60, HeartBeat) heartbeat_timer.start()
os.path.join('special://home', 'userdata', 'Thumbnails')) PACKAGES = xbmc.translatePath( os.path.join('special://home', 'addons', 'packages', '')) HOME = xbmc.translatePath('special://home/') RestoreGUI = os.path.join(HOME, 'userdata', 'addon_data', 'service.openelec.settings', 'restoregui') RunWizard = os.path.join(HOME, 'userdata', 'addon_data', 'service.openelec.settings', 'runwizard') timepath = os.path.join(HOME, 'userdata', 'addon_data', 'service.openelec.settings', 'dltime') addondata = os.path.join(HOME, 'userdata', 'addon_data', 'service.openelec.settings') SYSTEM = xbmc.translatePath('special://xbmc/') branding_update = xbmc.translatePath( 'special://home/media/branding/branding_update.png') ipaddress = xbmc.getIPAddress() log_path = xbmc.translatePath('special://logpath/') m3u_file = xbmc.translatePath(os.path.join(HOME, 'debug.txt')) addonfolder = xbmc.translatePath('special://home/addons/script.openwindow/') xbmc_version = xbmc.getInfoLabel("System.BuildVersion") testdebug = ADDON.getSetting('testdebug') email = '' download_thread = '' if not os.path.exists(addonfolder): addonfolder = xbmc.translatePath( 'special://xbmc/addons/script.openwindow/') def OpenELEC_Check(): xbmc_version = xbmc.getInfoLabel("System.BuildVersion")
import os import pyqrcode import xbmc import xbmcaddon from addon import CACHE_DIR, utils if __name__ == '__main__': addon = xbmcaddon.Addon() host = xbmc.getIPAddress() port = addon.getSetting('server.port') is_auth_enabled = addon.getSetting('server.auth_enabled') username = addon.getSetting('server.username') password = addon.getSetting('server.password') tmp_file = os.path.join(CACHE_DIR, 'qr-code.png') qr_string = host + ':' + port if is_auth_enabled and username and password: qr_string = username + ':' + password + '@' + qr_string qr = pyqrcode.create(qr_string) qr.png(tmp_file, scale=30) utils.execute_jsonrpc('Player.Open', {'item': {'file': tmp_file}})