Example #1
0
def login():
    
    username = __addon__.getSetting('username')
    xbmc.log('Logging in with username "%s"' %username)
    password = __addon__.getSetting('password')
    
    if(username == '' or password == ''):
        xbmcgui.Dialog().ok(PLUGINNAME, __language__(30102), __language__(30103))
        return False
        
    loginparams = {'username_field' : username, 'password_field' : password}
    loginurl = 'https://ssl.s04.tv/get_content.php?lang=TV&form=login&%s' %urllib.urlencode(loginparams)
    
    
    browser.open(loginurl)
    loginresponse = browser.response().read()
    xbmc.log('login response: ' +loginresponse)
    
    #loginresponse should look like this: ({"StatusCode":"1","stat":"OK","UserData":{"SessionID":"...","Firstname":"...","Lastname":"...","Username":"******","hasAbo":1,"AboExpiry":"31.07.14"},"out":"<form>...</form>"});
    #remove (); from response
    jsonstring = loginresponse[1:len(loginresponse) -2]
    jsonResult = json.loads(jsonstring)
    if(jsonResult['stat'] == "OK"):
        userdata = jsonResult['UserData']
        if(userdata['hasAbo'] == 1):
            xbmc.log('login successful')
            return True
        else:
            xbmc.log('no valid abo')
            xbmcgui.Dialog().ok(PLUGINNAME, __language__(30100) %username.decode('utf-8'), __language__(30101))
            return False
    else:
        xbmc.log('login failed')
        xbmcgui.Dialog().ok(PLUGINNAME, __language__(30100) %username.decode('utf-8'), __language__(30101))
        return False
Example #2
0
 def log(self, msg, level=xbmc.LOGNOTICE):
     '''
     Writes a string to the XBMC log file. The addon name is inserted into 
     the beginning of the message automatically to help you find relevent 
     messages in the log file.
     
     The available log levels are defined in the :mod:`xbmc` module and are
     currently as follows::
     
         xbmc.LOGDEBUG = 0
         xbmc.LOGERROR = 4
         xbmc.LOGFATAL = 6
         xbmc.LOGINFO = 1
         xbmc.LOGNONE = 7
         xbmc.LOGNOTICE = 2
         xbmc.LOGSEVERE = 5
         xbmc.LOGWARNING = 3
     
     Args:
         msg (str or unicode): The message to be written to the log file.
     
     Kwargs:
         level (int): The XBMC log level to write at.
     '''
     msg = unicodedata.normalize('NFKD', unicode(msg)).encode('ascii',
                                                              'ignore')
     xbmc.log('%s: %s' % (self.get_name(), msg), level)
Example #3
0
def getData(url, period = __cachePeriod__):
        if __DEBUG__:
            print 'url --> ' + url
        if float(period) > 0:
            cachePath = xbmc.translatePath(os.path.join(__PLUGIN_PATH__, 'cache', 'pages', urllib.quote(url,"")))
            if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= float(period)):
                f = open(cachePath, 'r')
                ret = f.read()
                f.close()
                return 'UTF-8',ret
        try:
            req = urllib2.Request(url)
            req.add_header('User-Agent', __USERAGENT__)
            response = urllib2.urlopen(req)
            contentType = response.headers['content-type']
            data = response.read().replace("\n","").replace("\t","").replace("\r","")
            response.close()            
            
        except:
            if __DEBUG__:
                errno, errstr = sys.exc_info()[:2]
                print 'Error in getData: ' + str(errno) + ': ' + str(errstr)
            xbmc.log('Error in getData: Unable to save cache', xbmc.LOGERROR)
            return 'UTF-8','unavailable'
        return contentType, data
Example #4
0
def buildSubDir(url, doc):
    xbmc.log('buildSubDir')
    soup = BeautifulSoup(''.join(doc))
    
    nav = soup.find('ul', attrs={'class': 'contentnav'})
    if(not nav):
        #no subdir (home page or flat category)
        buildVideoDir(url, doc)
        return
    
    div =  nav.find('div')
    if(not div):
        #no subdir (home page or flat category)
        buildVideoDir(url, doc)
        return
    
    ul = div.find('ul')
    for ulitem in ul.contents:
        if(type(ulitem) == Tag):
            if(ulitem.name == 'li'):
                a = ulitem.find('a')
                if(not a):
                    xbmc.log(missingelementtext%'a')
                    continue
                url = BASE_URL + a['href']
                addDir(a.text, url, 3, '')
Example #5
0
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' + '")')
Example #6
0
def resolve_novamov(url, guid):
	xbmc.log("Starting resolve_novamov with url: " + str(url) + " and guid: " + str(guid))
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()

	match1=re.compile('flashvars.file="(.+?)"').findall(link)
	for file in match1:
		file = file

	match2=re.compile('flashvars.filekey="(.+?)"').findall(link)
	for filekey in match2:
		filekey = filekey

	if not match1 or not match2:
		return 'CONTENTREMOVED'

	novaurl = 'http://www.novamov.com/api/player.api.php?user=undefined&key=' + filekey + '&codes=undefined&pass=undefined&file=' + file 

	req = urllib2.Request(novaurl)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()

	match3=re.compile('url=(.+?\.flv)').findall(link)
	for link in match3:
		link = link


	print ('auth url is ' + str(link))
	return link
Example #7
0
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)" )
Example #8
0
def play_fourshared(url, name):
	global media_id
	xbmc.log("starting 4shared method with: %s and %s" % (name, url))
	username = '******'
	password = '******'
	cookie_file = os.path.join(__profilepath__, 'pktemp.cookies')
	media_file = os.path.join(__profilepath__, ("pktemp%d.mp3" % (media_id)))
	cj = cookielib.LWPCookieJar()
	media_id = media_id + 1

	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
	loginurl = 'https://www.4shared.com/login?login=%s&password=%s' % (username, password)
	xbmc.log("logging in to 4shared: " + loginurl)
	resp = opener.open(loginurl)

	cj.save(cookie_file, ignore_discard=True)
	cj.load(cookie_file, ignore_discard=True)

	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
	urllib2.install_opener(opener)

	usock = opener.open(url)
	data = usock.read()
	#media_file = usock.geturl()
	usock.close()

	fp = open(media_file, 'wb')
	fp.write(data)
	fp.close()

	#play_stream(media_file, name)
	print "playing stream name: " + str(name) + " url: " + str(media_file)
	listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=media_file )
	listitem.setInfo( type="Music", infoLabels={ "Title": name } )
	xbmc.Player( xbmc.PLAYER_CORE_DVDPLAYER ).play( str(media_file), listitem)
Example #9
0
def find_stream(url, name):
	xbmc.log("Starting find_stream with url: " + str(url))
	try:
		pageUrl = url.split("&streamer=")[0]
		streamer = url.split("&streamer=")[1]
		print ('Opening ' + pageUrl)
		res = open_url(pageUrl)
		#print (res)
		playpath = ''
		swfUrl = ''
	
		for line in res.split("\n"):
			#print ("line:" + line)
			matches = re.search(r'file.*\'(.+)\'', line)
			if matches:
				playpath = matches.group(1)
				print ("Found playpath:" + playpath)
	
			matches = re.search(r'(http.+\.swf)', line)
			if matches:
				swfUrl = matches.group(1)
				print ("Found swfUrl:" + swfUrl)

		streamurl = "%s playpath=%s swfUrl=%s pageurl=%s swfVfy=true live=true" % (streamer, playpath, swfUrl, pageUrl)
		xbmc.log ("streamurl: " + streamurl)
		return (streamurl)
	except:
		return (" ")
Example #10
0
def log(msg, err=False):
    if err:
        xbmc.log(addon.getAddonInfo('name') + ': ' + msg.encode('utf-8'), 
                 xbmc.LOGERROR)    
    else:
        xbmc.log(addon.getAddonInfo('name') + ': ' + msg.encode('utf-8'), 
                    xbmc.LOGDEBUG)    
Example #11
0
def get_media_url(media_args):
    log('getting media url')
    querytype = media_args[0]
    title = re.sub(" \(?(.*.)\)", "", media_args[1])
    year = media_args[2]
    if year == "":
        yr = re.search(r"\((\d{4})\)", media_args[1])
        if yr is not None:
            year = yr.group(1)

    year_suffix = "" if querytype == "dizi" else " (%s)" % year

    page = load_url('/index.php?page=arama&arama=%s' % title + year_suffix)

    redirect_url = [sc.getText() for sc in page.findAll('script') if 'location.href' in sc.getText()]
    if len(redirect_url) > 0:
        a = redirect_url[0]
        episode_uri = a[a.find('"')+1:a.rfind('"')]
        log('Found uri via redirect')
        return episode_uri

    for result in page.findAll('td', attrs={'width': '60%'}):
        link = result.find('a')
        link_title = link.find('b').getText().strip()
        if querytype == "film":
            if str(year) == "" or str(year) in result.getText():
                return link["href"]
        elif querytype == "dizi" and link_title.startswith('"'):
            if str(year) == "" or str(year) in result.getText():
                return link["href"]
    raise ValueError('No valid results')
Example #12
0
def remove_strm_file(name, dir_path):
    try:
        filename = "%s.strm" % (clean_file_name(name, use_blanks=False))
        path = os.path.join(dir_path, filename)
        os.remove(path)
    except:
        xbmc.log("[What the Furk] Was unable to remove movie: %s" % (name)) 
Example #13
0
def setup_sources():
    xbmc.log("[What the Furk] Trying to add source paths...")
    source_path = os.path.join(xbmc.translatePath('special://profile/'), 'sources.xml')
    
    try:
        f = open(source_path, 'r')
        content = f.read()
        f.close()
        r = re.search("(?i)(<sources>[\S\s]+?<video>[\S\s]+?>)\s+?(</video>[\S\s]+?</sources>)", content)
        new_content = r.group(1)
        if not check_sources_xml(MOVIES_PATH):
            new_content += '<source><name>Movies (What the Furk)</name><path pathversion="1">'
            new_content += MOVIES_PATH
            new_content += '</path></source>'
        if not check_sources_xml(TV_SHOWS_PATH):
            new_content += '<source><name>TV Shows (What the Furk)</name><path pathversion="1">'
            new_content += TV_SHOWS_PATH
            new_content += '</path></source>'
        new_content += r.group(2)
        
        f = open(source_path, 'w')
        f.write(new_content)
        f.close()

        dialog = xbmcgui.Dialog()
        dialog.ok("Source folders added", "To complete the setup:", " 1) Restart XBMC.", " 2) Set the content type of added sources.")
        #if dialog.yesno("Restart now?", "Do you want to restart XBMC now?"):
            #xbmc.restart()
    except:
        xbmc.log("[What the Furk] Could not edit sources.xml")
Example #14
0
    def __init__(self):
        try:
            fetcher = FileFetcher('guides.ini', ADDON)
            if fetcher.fetchFile() < 0:
                xbmcgui.Dialog().ok(strings(FETCH_ERROR_TITLE), strings(FETCH_ERROR_LINE1), strings(FETCH_ERROR_LINE2))

            self.guideParser.read(self.filePath)
            guideTypes = []
            defaultGuideId = 0  # fallback to the first guide in case no default is actually set in the ini file
            for section in self.guideParser.sections():
                sectMap = self.SectionMap(section)
                id = int(sectMap['id'])
                fName = sectMap['file']
                sortOrder = int(sectMap['sort_order'])
                default = False
                if 'default' in sectMap and sectMap['default'] == 'true':
                    default = True
                    defaultGuideId = id
                guideTypes.append((id, sortOrder, section, fName, default))
            self.guideTypes = sorted(guideTypes, key=itemgetter(self.GUIDE_SORT))
            xbmc.log('[script.clarkeyepg] GuideTypes collected: %s' % str(self.guideTypes), xbmc.LOGDEBUG)

            if str(ADDON.getSetting('xmltv.type')) == '':
                ADDON.setSetting('xmltv.type', str(defaultGuideId))
        except:
            print 'unable to parse guides.ini'
Example #15
0
def get_subscriptions():
    try:
        content = read_from_file(SUBSCRIPTION_FILE)
        lines = content.split('\n')
        
        for line in lines:
            data = line.split('\t')
            if len(data) == 2:
                if data[1].startswith('tt'):
                    tv_show_name = data[0]
                    tv_show_imdb = data[1]
                    tv_show_mode = "strm tv show dialog"
                    create_tv_show_strm_files(tv_show_name, tv_show_imdb, tv_show_mode, TV_SHOWS_PATH)
                else:
                    mode = data[1]
                    items = get_menu_items(name, mode, "", "")
                    
                    for (url, li, isFolder) in items:
                        paramstring = url.replace(sys.argv[0], '')
                        params = get_params(paramstring)
                        movie_name = urllib.unquote_plus(params["name"])
                        movie_data = urllib.unquote_plus(params["name"])
                        movie_imdb = urllib.unquote_plus(params["imdb_id"])
                        movie_mode = "strm movie dialog"
                        create_strm_file(movie_name, movie_data, movie_imdb, movie_mode, MOVIES_PATH)
                    
    except:
        xbmc.log("[What the Furk] Failed to fetch subscription")
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 panDir():
    while not panAuth():
        if xbmcgui.Dialog().yesno(_name, '          Login Failed', 'Bad User / Pass / Proxy', '       Check Settings?'):
            _settings.openSettings()
        else: exit()

    sort = _settings.getSetting('sort')
    stations = _pandora.stations
    quickmix = stations.pop(0)							# Quickmix
    if   sort == '0':	stations = stations					# Normal
    elif sort == '2':	stations = stations[::-1]				# Reverse
    else:		stations = sorted(stations, key=lambda s: s.name)	# A-Z
    stations.insert(0, quickmix)						# Quickmix back on top

    for station in stations:
        li = xbmcgui.ListItem(station.name, station.id)
        li.setProperty('IsPlayable', 'true')

        img = _settings.getSetting("img-%s" % station.id)
        li.setIconImage(img)
        li.setThumbnailImage(img)
        li.addContextMenuItems([('Select Thumb', "RunPlugin(plugin://%s/?thumb=%s)" % (_plugin, station.id))])

        xbmcplugin.addDirectoryItem(_handle, "%s?station=%s" % (_base, station.id), li)

    xbmcplugin.endOfDirectory(_handle, cacheToDisc = False)
    xbmc.log("%s.Dir   OK" % _plugin, xbmc.LOGDEBUG)
Example #18
0
	def scrapLive(self, url):
		global login_true
		xbmc.log( logmsg + url )
		req = urllib2.Request(url)
		req.add_header('User-Agent', USER_AGENT)
		response = opener.open(req)
		
		channels = common.parseDOM(response.read(), "div", {'class': 'channel'})
		l = []
		for r in channels:
			link = 'http://m.mtvkatsomo.fi' + common.parseDOM(r, "a", ret = "href")[0]
			title = common.parseDOM(r, "h1")[0]
			
			title += ' - ' + common.parseDOM(r, "h2")[0]
			imgClass = common.parseDOM(r, "div", ret = "class")[0].split(' ')[1]
			img = ''
			if imgClass == 'channel-logo-1':
				title = '[MTV3] ' + title
				img = 'http://m.mtvkatsomo.fi/images/channel-logos/[email protected]'
			elif imgClass == 'channel-logo-3':
				title = '[SUB] ' + title
				img = 'http://m.mtvkatsomo.fi/images/channel-logos/[email protected]'
			elif imgClass == 'channel-logo-6':
				title = '[AVA] ' + title
				img = 'http://m.mtvkatsomo.fi/images/channel-logos/[email protected]'
			
			
			l.append( {'link':link, 'title':common.replaceHTMLCodes(title), 'img':img} )
			
		return l		
def panFetch(song, path):
    global _high

    isad = int(_settings.getSetting('isad')) * 1024
    wait = int(_settings.getSetting('delay'))
    qual = _settings.getSetting('quality')
    skip = _settings.getSetting('skip')

    url  = urlparse.urlsplit(song.audioUrl[qual])
    conn = httplib.HTTPConnection(url.netloc, timeout = 9)
    conn.request('GET', "%s?%s" % (url.path, url.query))
    strm = conn.getresponse()
    size = int(strm.getheader('content-length'))

    if size in (341980, 173310): # empty song cause requesting to fast
        xbmc.log("%s.Fetch MT (%13s,%8d)  '%s - %s - %s'" % (_plugin, _stamp, size, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG)
        panMsg(song, 'To Many Songs Requested')
        return

    xbmc.log("%s.Fetch %s (%13s,%8d)  '%s - %s - %s'" % (_plugin, strm.reason, _stamp, size, song.songId[:4], song.artist, song.title))

    totl = 0
    qued = False
    last = time.time()
    file = open(path, 'wb', 0)

    while (totl < size) and (not xbmc.abortRequested):
        try: data = strm.read(min(4096, size - totl))
        except socket.timeout:
            xbmc.log("%s.Fetch TO (%13s,%8d)  '%s - %s - %s'" % (_plugin, _stamp, totl, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG)
            break

        if _high < (time.time() - last): _high = time.time() - last
        last = time.time()

        file.write(data)
        totl += len(data)

        if (not qued) and (size > isad):
            threading.Timer(wait, panQueue, (song, path)).start()
            qued = True

    file.close()
    conn.close()
    
    if totl < size:		# incomplete file
        xbmc.log("%s.Fetch RM (%13s)           '%s - %s - %s'" % (_plugin, _stamp, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG)
        xbmcvfs.delete(path)
    elif size <= isad:		# looks like an ad
        if skip == 'true':
            xbmc.log("%s.Fetch AD (%13s)           '%s - %s - %s'" % (_plugin, _stamp, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG)
            xbmcvfs.delete(path)

        elif qued == False:	# play it anyway
            song.artist = song.album = song.title = 'Advertisement'        
            dest = path + '.ad.m4a'
            xbmcvfs.rename(path, dest)
            panQueue(song, dest)

    else: panSave(song, path)
Example #20
0
def parse_data(reply):
	try:
		data = json.loads(reply)
	except:
		xbmc.log('Failed to Parse Weather Data',level=log_level)
		data = ''
	return data
Example #21
0
	def scrapSerie(self, url):
		global login_true
		xbmc.log( logmsg + url )
		req = urllib2.Request(url)
		req.add_header('User-Agent', USER_AGENT)
		response = opener.open(req)
		
		programs = common.parseDOM(response.read(), "div", {'class': 'programs'})[0]
		ret = common.parseDOM(programs, "div", {'class': 'program program-toggle'})
		l = []
		for r in ret:
			link = 'http://m.mtvkatsomo.fi' + common.parseDOM(r, "a", ret = "href")[0]
			title = common.parseDOM(r, "p", {'class': 'program-name'})[0]
			if 'class="star"' in title and not login_true: continue
			elif 'class="star"' in title and login_true and self.scrapVideoLink(link) == None: continue	
			
			img = common.parseDOM(r, "img", ret = "src")[0]
			tsList = common.parseDOM(r, "p", {'class': 'timestamp'})
			if len(tsList) > 0:
				timestamp = tsList[0]
				ts = None
				if 'TULOSSA' in timestamp:
					continue;
			
				try:
					ts = datetime.strptime(timestamp.replace('- ', ''), '%d.%m.%Y %H.%M')
				except TypeError:
					try:
						tsts = datetime(*(time.strptime(timestamp.replace('- ', ''), '%d.%m.%Y %H.%M')[0:6]))				
					except:
						xbmc.log('Could not parse timestamp: ' + timestamp, xbmc.LOGDEBUG)
			
			l.append( {'link':link, 'title':title, 'img':img, 'published': timestamp, 'publ-ts': ts} )
			
		return l
Example #22
0
def GetHttpData(url):
    print "getHttpData: " + url
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)')
    try:
        response = urllib2.urlopen(req)
        httpdata = response.read()
        if response.headers.get('content-encoding', None) == 'gzip':
            httpdata = gzip.GzipFile(fileobj=StringIO.StringIO(httpdata)).read()
        charset = response.headers.getparam('charset')
        response.close()
    except:
        xbmc.log( "%s: %s (%d) [%s]" % (
            __addonname__,
            sys.exc_info()[ 2 ].tb_frame.f_code.co_name,
            sys.exc_info()[ 2 ].tb_lineno,
            sys.exc_info()[ 1 ]
            ), level=xbmc.LOGERROR)
        return ''
    match = re.compile('<meta http-equiv=["]?[Cc]ontent-[Tt]ype["]? content="text/html;[\s]?charset=(.+?)"').findall(httpdata)
    if len(match)>0:
        charset = match[0]
    if charset:
        charset = charset.lower()
        if (charset != 'utf-8') and (charset != 'utf8'):
            httpdata = httpdata.decode(charset, 'ignore').encode('utf8', 'ignore')
    return httpdata
def authorize(resource):
    if is_authorized(resource):
        xbmc.log(TAG + 'already authorized', xbmc.LOGDEBUG)
        return
    params = urllib.urlencode({'requestor': 'ESPN',
                               'deviceId': get_device_id(),
                               'resource': resource})

    path = '/authorize'
    url = urlparse.urlunsplit(['https', 'api.auth.adobe.com',
                                   'api/v1' + path,
                                   params, ''])

    message = generate_message('GET', path)

    resp = get_url_response(url, message)

    settings = load_settings()
    if 'authorize' not in settings:
        settings['authorize'] = dict()
    xbmc.log(TAG + 'resource %s' % resource, xbmc.LOGDEBUG)
    if 'status' in resp and resp['status'] == 403:
        raise AuthorizationException()
    settings['authorize'][resource.decode('iso-8859-1').encode('utf-8')] = resp
    save_settings(settings)
Example #24
0
 def getEpisodeByAirdate_NEW(self, tvdbid, airdate):
     xbmc.log("getEpisodeByAirdate Creating Cache")
     try:
         response = urllib2.urlopen(self._buildUrl('GetEpisodeByAirDate.php', {'apikey' : self.apikey, 'seriesid' : tvdbid, 'airdate' : airdate})).read()
         return response
     except Exception,e:
         return ''
Example #25
0
 def getEpisodeByID_NEW(self, tvdbid):
     xbmc.log("getEpisodeByID_NEW Creating Cache")
     try:
         response = urllib2.urlopen(self._buildUrl(self.apikey + '/series/' + tvdbid + '/all/en.xml')).read()
         return response
     except Exception,e:
         return ''
Example #26
0
 def _fetch_song_list(self, artist, scraper=0, usetitle=False):
     try:
         # log message
         xbmc.log(u"  {count}. Scraper::_fetch_song_list    (scraper={scraper!r}, autoselect={auto!r})".format(count=scraper + 1, scraper=self.SCRAPERS[scraper]["title"], auto=self.SCRAPERS[scraper]["source"]["songlist"]["autoselect"]), xbmc.LOGDEBUG)
         # do we want to include title
         title = ["", self.m_song.title][usetitle]
         # format url based on scraper
         url = self._format_url(artist, title, scraper)
         # fetch source
         source = self._fetch_source(url, self.SCRAPERS[scraper]["url"]["useragent"]["string"], self.SCRAPERS[scraper]["source"]["encoding"], self.SCRAPERS[scraper]["source"]["compress"])
         # scrape song list
         songs = self.SCRAPERS[scraper]["source"]["songlist"]["regex"].findall(source)
         # raise an error if no songs found
         if (not len(songs)): raise
         # get user selection
         url = self._get_song_selection(songs, self.SCRAPERS[scraper]["title"], self.SCRAPERS[scraper]["source"]["songlist"]["format"], self.SCRAPERS[scraper]["source"]["songlist"]["autoselect"], not usetitle)
         # add scraper to our skip alias list FIXME: we need a place that doesn't affect songlist always scrapers
         if (not usetitle):
             self.skip_alias += [scraper]
         # if selection, format url
         if (url is not None):
             url = u"{address}{head}{url}".format(address=self.SCRAPERS[scraper]["url"]["address"], head=self.SCRAPERS[scraper]["url"]["song"]["title"]["head"], url=url)
     # an error occurred, should only happen if artist was not found
     except Exception as error:
         # no artist found
         return None, str(error)
     else:
         # success
         return url, ""
Example #27
0
 def _get_song_selection(self, songs, title, swap, autoselect, songlist):
     """ Returns a user selected song's url from a list of supplied songs """
     # sort songs, removing duplicates
     titles, dupes = self._sort_songs(songs, swap)
     # if autoselect, try to find a match
     if (autoselect):
         # set key
         if (len(songs[0]) == 3):
             # we use an artist alias if one was entered
             key = " - ".join([self.m_song.title, self.new_alias.get(self.m_song.artist, self.artist_aliases.get(self.m_song.artist, self.m_song.artist))]).lower()
         else:
             key = self.m_song.title.lower()
         # loop thru and find a match FIXME: titles is sorted, so may not return best result?
         choice = [count for count, k in enumerate(titles) if (k.lower() == key)]
         # if we have a match return it
         if (choice):
             return dupes[titles[choice[0]]]
     # if we are prefetching or autoselecting when not songlist skip selection, we only go this far for autoselect scrapers
     if (self.prefetch or (autoselect and not songlist)):
         return None
     # set the time to auto close in msec, 80% of time remaining is plenty of time and gives prefetch some time
     autoclose = int((xbmc.Player().getTotalTime() - xbmc.Player().getTime()) * 1000 * 0.80)
     # get user selection
     choice = xbmcgui.Dialog().select(u"{title} ({new})".format(title=self.m_song.title, new=title), titles, autoclose)
     # return selection
     if (choice >= 0):
         return dupes[titles[choice]]
     # log message only if no selection
     xbmc.log("     Scraper::_get_song_selection (message='No selection made')", xbmc.LOGDEBUG)
     # no selection return None
     return None
Example #28
0
 def write_doc(self, filepath, doc):
     with open(filepath, 'wb') as out:
         try: 
             out.write(doc)
         except:
             xbmc.log('plugin.program.pneumatic failed to create .nfo file: %s' % \
                      xbmc.translatePath(filepath))
 def _get_current_volume( self ):
     # get the current volume
     result = xbmc.executeJSONRPC( volume_query )
     match = re.search( '"volume" ?: ?([0-9]{1,3})', result )
     volume = int(match.group(1))
     xbmc.log( "[script.cinema.experience] - Current Volume: %d" % volume, level=xbmc.LOGDEBUG)
     return volume
Example #30
0
    def getPlaybackCall(self, package):

        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))
        opener.addheaders = [('User-Agent', self.user_agent)]

        WLSSC = self.authorization.getToken('WLSSC')

        if (WLSSC == ''):
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(30000), self.addon.getLocalizedString(30050))
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + self.addon.getLocalizedString(30050), xbmc.LOGERROR)
            return ('',package)


        url = 'https://onedrive.live.com/?gologin=1&mkt=en-US'

        opener.addheaders = [('User-Agent', self.user_agent),('Cookie', 'WLSSC='+WLSSC+';')]
        request = urllib2.Request(url)

        # if action fails, validate login

        try:
            response = opener.open(request)

        except urllib2.URLError, e:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return ('',package)
Example #31
0
    def onInit(self):
        try:
            SUPERFAVES = 'plugin.program.super.favourites'
            SF_ICON    = xbmcaddon.Addon(id=SUPERFAVES).getAddonInfo('icon')
            
        except:
            SF_ICON   = ''
        xbmc.log('self.addons: %s' % self.addons)
        items = list()
        for id, label, url in self.addons:
            xbmc.log('### id: %s | label: %s | url: %s' % (id, label, url))
            try:
                if '-metalliq' in id:
                    icon        = xbmcaddon.Addon(id='plugin.video.metalliq').getAddonInfo('icon')
                    name = ''
                elif id.startswith('SF_'):
                    dir  = id.split('SF_', 1)[-1]
                    cfg  = os.path.join(dir, 'folder.cfg')
                    icon = os.path.join(dixie.RESOURCES, 'social-share.png')

                    if not icon:
                        icon = SF_ICON

                    name = ''
                
                elif id == 'kodi-favourite':
                    icon = os.path.join(dixie.RESOURCES, 'kodi-favourite.png')
                    name = ''

                elif id == 'iptv-playlist':
                    icon = os.path.join(dixie.RESOURCES, 'iptv-playlist.png')
                    name = ''

                elif id == 'xbmc.pvr':
                    icon = os.path.join(dixie.RESOURCES, 'kodi-pvr.png')
                    name = 'PVR'

                else:
                    addon = xbmcaddon.Addon(id)
                    icon  = addon.getAddonInfo('icon')
                    name  = addon.getAddonInfo('name')

                if not name:
                    name = label
                if not icon:
                    icon = ''

                try:                
                    item = xbmcgui.ListItem(label, name, icon)
                    try:
                        item.setProperty('stream', url)

                        items.append(item)
                    except:
                        try:
                            item.setProperty('stream', url[0])
                            items.append(item)
                        except Exception as e:
                            xbmc.log('Failed to set stream for %s | %s' % (label, name))
                except Exception as e:
                    xbmc.log('stream: %s | Url: %s | Error: %s' % (label, url, e))

            except:
                try:
                    item = xbmcgui.ListItem(label, '', id)
                    item.setProperty('stream', url)
                    items.append(item)
                except Exception as e:
                    xbmc.log('stream: %s | Url: %s | Error: %s' % (label, url, e))

        listControl = self.getControl(StreamAddonDialog.C_SELECTION_LIST)
        listControl.addItems(items)

        self.setFocus(listControl)
Example #32
0
class Monitor():

    logLevel = 0
    settings = None

    def __init__(self, *args):

        self.settings = xbmcaddon.Addon(id='plugin.video.xbmb3c')
        try:
            self.logLevel = int(self.settings.getSetting('logLevel'))
        except:
            pass

        self.printDebug("XBMB3C Service -> starting Monitor")

        pass

    def printDebug(self, msg, level=1):
        if (self.logLevel >= level):
            if (self.logLevel == 2):
                try:
                    xbmc.log("XBMB3C " + str(level) + " -> " +
                             inspect.stack()[1][3] + " : " + str(msg))
                except UnicodeEncodeError:
                    xbmc.log("XBMB3C " + str(level) + " -> " +
                             inspect.stack()[1][3] + " : " +
                             str(msg.encode('utf-8')))
            else:
                try:
                    xbmc.log("XBMB3C " + str(level) + " -> " + str(msg))
                except UnicodeEncodeError:
                    xbmc.log("XBMB3C " + str(level) + " -> " +
                             str(msg.encode('utf-8')))

    def SkinCompatibilityMessage(self):
        return_value = xbmcgui.Dialog().yesno(
            self.settings.getLocalizedString(30229),
            self.settings.getLocalizedString(30230),
            self.settings.getLocalizedString(30231),
            self.settings.getLocalizedString(30232),
            nolabel="Ok",
            yeslabel="Dont Show Again")
        if return_value:
            xbmc.log("ignoring skin compatibility message forever")
            self.settings.setSetting("skinMessageIgnored", "true")

    def ServiceEntryPoint(self):

        xbmcgui.Window(10000).setProperty("XBMB3C_Service_Timestamp",
                                          str(int(time.time())))

        # auth the service
        try:
            downloadUtils = DownloadUtils()
            downloadUtils.authenticate()
        except Exception, e:
            pass

        # start some worker threads
        if self.settings.getSetting('useSkinHelper') == "true":
            skinHelperThread = SkinHelperThread()
            skinHelperThread.start()
        else:
            self.printDebug("XBMB3C Service SkinHelperThread Disabled")
            skinHelperThread = None

        if self.settings.getSetting('useInProgressUpdater') == "true":
            newInProgressThread = InProgressUpdaterThread()
            newInProgressThread.start()
        else:
            self.printDebug("XBMB3C Service InProgressUpdater Disabled")
            newInProgressThread = None

        if self.settings.getSetting('useRecentInfoUpdater') == "true":
            newRecentInfoThread = RecentInfoUpdaterThread()
            newRecentInfoThread.start()
        else:
            self.printDebug("XBMB3C Service RecentInfoUpdater Disabled")
            newRecentInfoThread = None

        if self.settings.getSetting('useRandomInfo') == "true":
            newRandomInfoThread = RandomInfoUpdaterThread()
            newRandomInfoThread.start()
        else:
            self.printDebug("XBMB3C Service RandomInfo Disabled")
            newRandomInfoThread = None

        if self.settings.getSetting('useNextUp') == "true":
            newNextUpThread = NextUpUpdaterThread()
            newNextUpThread.start()
        else:
            self.printDebug("XBMB3C Service NextUp Disabled")
            newNextUpThread = None

        if self.settings.getSetting('useSuggested') == "true":
            newSuggestedThread = SuggestedUpdaterThread()
            newSuggestedThread.start()
        else:
            self.printDebug("XBMB3C Service Suggested Disabled")
            newSuggestedThread = None

        if self.settings.getSetting('useWebSocketRemote') == "true":
            newWebSocketThread = WebSocketThread()
            newWebSocketThread.start()
        else:
            self.printDebug("XBMB3C Service WebSocketRemote Disabled")
            newWebSocketThread = None

        if self.settings.getSetting('useMenuLoader') == "true":
            newMenuThread = LoadMenuOptionsThread()
            newMenuThread.start()
        else:
            self.printDebug("XBMB3C Service MenuLoader Disabled")
            newMenuThread = None

        if self.settings.getSetting('useBackgroundLoader') == "true":
            artworkRotationThread = ArtworkRotationThread()
            artworkRotationThread.start()
        else:
            self.printDebug("XBMB3C Service BackgroundLoader Disabled")
            artworkRotationThread = None

        if self.settings.getSetting(
                'useThemeMovies') == "true" or self.settings.getSetting(
                    'useThemeMusic') == "true":
            newThemeMediaThread = ThemeMediaThread()
            newThemeMediaThread.start()
        else:
            self.printDebug("XBMB3C Service ThemeMedia Disabled")
            newThemeMediaThread = None

        if self.settings.getSetting('useInfoLoader') == "true":
            newInfoThread = InfoUpdaterThread()
            newInfoThread.start()
        else:
            self.printDebug("XBMB3C Service InfoLoader Disabled")
            newInfoThread = None

        if self.settings.getSetting('usePlaylistsUpdater') == "true":
            newPlaylistsThread = PlaylistItemUpdaterThread()
            newPlaylistsThread.start()
        else:
            self.printDebug("XBMB3C Service PlaylistsUpdater Disabled")
            newPlaylistsThread = None

        if self.settings.getSetting('useBackgroundData') == "true":
            newBackgroundDataThread = BackgroundDataUpdaterThread()
            newBackgroundDataThread.start()
        else:
            self.printDebug("XBMB3C BackgroundDataUpdater Disabled")
            newBackgroundDataThread = None

        # start the service
        service = Service()
        lastProgressUpdate = datetime.today()

        addonSettings = xbmcaddon.Addon(id='plugin.video.xbmb3c')
        if socket.gethostname() != None and socket.gethostname(
        ) != '' and addonSettings.getSetting("deviceName") == 'XBMB3C':
            addonSettings.setSetting("deviceName", socket.gethostname())

        xbmc.log("XBMB3C Service -> Starting Service")

        whenStarted = datetime.today()
        skinMessageShown = False

        while not xbmc.abortRequested:
            if xbmc.Player().isPlaying():
                try:
                    playTime = xbmc.Player().getTime()
                    currentFile = xbmc.Player().getPlayingFile()

                    if (service.played_information.get(currentFile) != None):
                        service.played_information[currentFile][
                            "currentPossition"] = playTime

                    # send update
                    td = datetime.today() - lastProgressUpdate
                    secDiff = td.seconds
                    if (secDiff > 10):
                        try:
                            service.reportPlayback(currentFile)
                            #if(service.played_information.get(currentFile) != None and service.played_information.get(currentFile).get("item_id") != None):
                            #item_id =  service.played_information.get(currentFile).get("item_id")
                            #if(newWebSocketThread != None):
                            #newWebSocketThread.sendProgressUpdate(item_id, str(int(playTime * 10000000)))
                        except Exception, msg:
                            try:
                                xbmc.log(
                                    "XBMB3C Service -> Exception reporting progress : "
                                    + str(msg))
                            except:
                                pass
                            pass
                        lastProgressUpdate = datetime.today()

                except Exception, e:
                    xbmc.log(
                        "XBMB3C Service -> Exception in Playback Monitor Service : "
                        + str(e))
                    pass
            else:
                if (skinMessageShown == False):
                    timeSinceStart = (datetime.today() - whenStarted).seconds
                    if (timeSinceStart > 10):
                        skinMessageShown = True
                        skinIsCompatible = xbmcgui.Window(10000).getProperty(
                            "SkinIsCompatible")
                        skinMessageIgnored = self.settings.getSetting(
                            "skinMessageIgnored")
                        if (skinIsCompatible != "true"
                                and skinMessageIgnored != "true"):
                            self.SkinCompatibilityMessage()

            xbmc.sleep(1000)
            xbmcgui.Window(10000).setProperty("XBMB3C_Service_Timestamp",
                                              str(int(time.time())))
Example #33
0
                    timeSinceStart = (datetime.today() - whenStarted).seconds
                    if (timeSinceStart > 10):
                        skinMessageShown = True
                        skinIsCompatible = xbmcgui.Window(10000).getProperty(
                            "SkinIsCompatible")
                        skinMessageIgnored = self.settings.getSetting(
                            "skinMessageIgnored")
                        if (skinIsCompatible != "true"
                                and skinMessageIgnored != "true"):
                            self.SkinCompatibilityMessage()

            xbmc.sleep(1000)
            xbmcgui.Window(10000).setProperty("XBMB3C_Service_Timestamp",
                                              str(int(time.time())))

        xbmc.log("XBMB3C Service -> Stopping Service")

        # stop all worker threads
        if (newWebSocketThread != None):
            newWebSocketThread.stopClient()

        if (skinHelperThread != None):
            skinHelperThread.stop()
        if (newInProgressThread != None):
            newInProgressThread.stop()
        if (newRecentInfoThread != None):
            newRecentInfoThread.stop()
        if (newRandomInfoThread != None):
            newRandomInfoThread.stop()
        if (newNextUpThread != None):
            newNextUpThread.stop()
def log(v):
    xbmc.log(repr(v))
Example #35
0
    def run(self):
        threads = []

        # check if cache has expired
        if not ADDON.getSetting("forceupdate") == "true"\
            and not int(ADDON.getSetting("cacheexpire_days")) == 0\
            and self.checkFileTime(pluginConfig.get('cache', 'cacheChannels'),
                                   ADDON.getSetting("cacheexpire_days")):
            ADDON.setSetting(id="forceupdate", value="true")

        if ADDON.getSetting("forceupdate") == "true":
            channels = []
            html = ""

            # if username is set, try to login and go for premium channels
            if ADDON.getSetting('username') != "":
                loginData = urllib.urlencode({
                    'member_session[username]':
                    ADDON.getSetting('username'),
                    'member_session[password]':
                    ADDON.getSetting('password')
                })

                # post login info and get frontpage html
                html = self.curler.request(pluginConfig.get('urls', 'login'),
                                           'post', loginData)

                # if we could not reach radiotunes.com at all
                if not bool(html):
                    xbmc.log(u'RadioTunes.com could not be reached',
                             xbmc.LOGWARNING)
                    xbmcgui.Dialog().ok(ADDON.getLocalizedString(30100),
                                        ADDON.getLocalizedString(30101),
                                        ADDON.getLocalizedString(30102),
                                        ADDON.getLocalizedString(30103))
                    xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
                    return True

                channels = json.loads(
                    self.curler.request(
                        pluginConfig.get(
                            'streams', 'premium%sk' % self.dictBitrate[int(
                                ADDON.getSetting('bitrate'))]), 'get'))

                premiumConfig = self.getPremiumConfig()

                # if premiumConfig['listenKey'] is blank, we did not log in correctly
                if premiumConfig is False or premiumConfig['listenKey'] == '':
                    xbmc.log('Login did not succeed', xbmc.LOGWARNING)
                    xbmcgui.Dialog().ok(ADDON.getLocalizedString(30170),
                                        ADDON.getLocalizedString(30171),
                                        ADDON.getLocalizedString(30172))
                    xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
                    return True

                self.listenKey = premiumConfig['listenKey']

                # if we should get the favorites or all channels
                if ADDON.getSetting("usefavorites") == 'true':
                    channels = self.getFavoriteChannels(html, channels)
                    if len(channels) == 0:
                        xbmcgui.Dialog().ok(ADDON.getLocalizedString(30180),
                                            ADDON.getLocalizedString(30181),
                                            ADDON.getLocalizedString(30182))
                        xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
                        return True

                # add listenkey to playlist urls
                for channel in channels:
                    channel['playlist'] = '%s?%s' % (
                        channel['playlist'], premiumConfig['listenKey'])

            # go for free/public channels
            else:
                html = self.curler.request(
                    pluginConfig.get('urls', 'frontpage'), 'get')

                # if we could not reach radiotunes.com at all
                if not html:
                    xbmc.log('RadioTunes.com could not be reached',
                             xbmc.LOGWARNING)
                    xbmcgui.Dialog().ok(ADDON.getLocalizedString(30100),
                                        ADDON.getLocalizedString(30101),
                                        ADDON.getLocalizedString(30102),
                                        ADDON.getLocalizedString(30103))
                    xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
                    return True

                channels = json.loads(
                    self.curler.request(pluginConfig.get('streams', 'public'),
                                        'get'))

            re_channelData = re.compile(
                "NS\('AudioAddict.API.Config'\).channels\s*=\s*([^\n]+);",
                re.M | re.I)
            channelMeta = json.loads(re_channelData.findall(html)[0])

            # put each playlist in a worker queue for threading
            for channel in channels:
                self.workQueue.put(channel)

            # starts 8 threads to download streams for each channel
            while not self.workQueue.empty():
                xbmc.log(
                    'Worker queue size is %s' % (str(self.workQueue.qsize())),
                    xbmc.LOGNOTICE)

                if threading.activeCount(
                ) < self.threadMax and not self.workQueue.empty():
                    threads.append(
                        scraperThread(self, self.workQueue.get(), channelMeta,
                                      len(channels)))
                    threads[-1].start()
                else:
                    time.sleep(0.1)

            # wait for all threads to finish before continuing
            for t in threads:
                t.join()

            # Saves channels to cache and reset the "force update" flag
            if len(channels) > 0:
                pickle.dump(self.channelsList,
                            open(
                                os.path.join(
                                    self.addonProfilePath,
                                    pluginConfig.get('cache',
                                                     'cacheChannels')), "w"),
                            protocol=0)
                ADDON.setSetting(id="forceupdate", value="false")

        # else load channels from cache file
        else:
            self.channelsList = pickle.load(
                open(
                    os.path.join(self.addonProfilePath,
                                 pluginConfig.get('cache', 'cacheChannels')),
                    "r"))

            for channel in self.channelsList:
                self.addItem(channel['name'], channel['streamUrl'],
                             channel['name'], channel['bitrate'],
                             channel['asset'], channel['isNew'],
                             len(self.channelsList))

        # Should channels be sorted A-Z?
        if ADDON.getSetting('sortaz') == "true":
            xbmcplugin.addSortMethod(HANDLE,
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)

        # tell XMBC there are no more items to list
        xbmcplugin.endOfDirectory(HANDLE, succeeded=True)

        if self.newChannels > 0:
            xbmcgui.Dialog().ok(
                ADDON.getLocalizedString(30130),
                ADDON.getLocalizedString(30131) +
                str(self.newChannels) + ADDON.getLocalizedString(30132),
                ADDON.getLocalizedString(30133),
                ADDON.getLocalizedString(30134))

        return True
Example #36
0
def log(msg, level=xbmc.LOGDEBUG):
    if DEBUG == False and level != xbmc.LOGERROR: return
    if level == xbmc.LOGERROR: msg += ' ,' + traceback.format_exc()
    xbmc.log(ADDON_ID + '-' + ADDON_VERSION + '-' + (msg.encode("utf-8")),
             level)
Example #37
0
 def Log(self, *args, **kwargs):
     return xbmc.log(*args, **kwargs)
Example #38
0
def log(msg, level=xbmc.LOGDEBUG):
    if type(msg).__name__=='unicode':
        msg = msg.encode('utf-8')
    xbmc.log("[%s] %s"%(_scriptname_,msg.__str__()), level)
Example #39
0
    xbmc.executebuiltin(
        'XBMC.RunPlugin(plugin://plugin.video.dr.strms/service)')
    time.sleep(2)
    servicing = False


if __name__ == '__main__':
    ADDON = xbmcaddon.Addon('plugin.video.dr.strms')

    xbmcvfs.delete(
        'special://profile/addon_data/plugin.video.dr.strms/servicing')

    try:
        if ADDON.getSetting('service') == 'true':
            monitor = xbmc.Monitor()
            xbmc.log("[plugin.video.dr.strms] service started...",
                     xbmc.LOGERROR)
            if ADDON.getSetting('service.startup') == 'true':
                Service()
                ADDON.setSetting('last.update', str(time.time()))
            while not monitor.abortRequested():
                if ADDON.getSetting('service.type') == '1':
                    interval = int(ADDON.getSetting('service.interval'))
                    waitTime = 3600 * interval
                    ts = ADDON.getSetting('last.update') or "0.0"
                    lastTime = datetime.datetime.fromtimestamp(float(ts))
                    now = datetime.datetime.now()
                    nextTime = lastTime + datetime.timedelta(seconds=waitTime)
                    td = nextTime - now
                    timeLeft = td.seconds + (td.days * 24 * 3600)
                    xbmc.log(
                        "[plugin.video.dr.strms] Service waiting for interval %s"
def log(description, level=0):
    if dbg and dbglevel > level:
        try:
            xbmc.log(("[%s] %s : '%s'" % (plugin, inspect.stack()[1][3], description)).decode("utf-8"), xbmc.LOGDEBUG)
        except:
            xbmc.log("FALLBACK [%s] %s : '%s'" % (plugin, inspect.stack()[1][3], repr(description)), xbmc.LOGDEBUG)
Example #41
0
def log(msg):
    if enable_debug:
        try:
            xbmc.log(msg)
        except:
            xbmc.log(msg.encode('utf-8'))
Example #42
0
def myfreecam_start(url):
    global CAMGIRL
    global CAMGIRLSERVER
    global CAMGIRLUID
    global CAMGIRLCHANID
    CAMGIRL= url
    CAMGIRLSERVER = 0

    try:
        xchat=[ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 
            20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 
            33, 34, 35, 36, 39, 40, 41, 42, 43, 44, 45, 46, 
            47, 48, 49, 56, 57, 58, 59, 60, 61
              ]
        host = "ws://xchat"+str(random.choice(xchat))+".myfreecams.com:8080/fcsl"
        ws = websocket.WebSocket()
        ws = websocket.create_connection(host)
        ws.send("hello fcserver\n\0")
        ws.send("1 0 0 20071025 0 guest:guest\n\0")
    except:
        xbmc.log('f****d')
        return ''
    rembuf=""
    quitting = 0
    while quitting == 0:
        sock_buf =  ws.recv()
        sock_buf=rembuf+sock_buf
        rembuf=""
        while True:
            hdr=re.search (r"(\w+) (\w+) (\w+) (\w+) (\w+)", sock_buf)
            if bool(hdr) == 0:
                break

            fc = hdr.group(1)

            mlen   = int(fc[0:4])
            fc_type = int(fc[4:])

            msg=sock_buf[4:4+mlen]

            if len(msg) < mlen:
                rembuf=''.join(sock_buf)
                break

            msg=urllib.unquote(msg)

            if fc_type == 1:
                ws.send("10 0 0 20 0 %s\n\0" % CAMGIRL)
            elif fc_type == 10:
                read_model_data(msg)
                quitting=1

            sock_buf=sock_buf[4+mlen:]

            if len(sock_buf) == 0:
                break
    ws.close()
    if CAMGIRLSERVER != 0:
        Url="http://video"+str(CAMGIRLSERVER)+".myfreecams.com:1935/NxServer/ngrp:mfc_"+\
            str(CAMGIRLCHANID)+".f4v_mobile/playlist.m3u8" #better resolution
        return Url
    else:
        pass
Example #43
0
def log(message):
    xbmc.log(message)  # Write something on XBMC log
Example #44
0
def getInfoLabel(asset_type, item_data):
    data = item_data
    if 'mediainfo' in data:
        data = data['mediainfo']
    elif extMediaInfos and extMediaInfos == 'true':
        try:
            data = getAssetDetailsFromCache(data['id'])
        except:
            pass
    info = {}
    info['title'] = data.get('title', '')
    info['originaltitle'] = data.get('original_title', '')
    if not data.get('year_of_production', '') == '':
        info['year'] = data.get('year_of_production', '')
    info['plot'] = data.get('synopsis', '').replace('\n', '').strip()
    if info['plot'] == '':
        info['plot'] = data.get('description', '').replace('\n', '').strip()
    info['duration'] = data.get('lenght', 0) * 60
    if data.get('main_trailer', {}).get('trailer', {}).get('url', '') != '':
        info['trailer'] = data.get('main_trailer', {}).get('trailer',
                                                           {}).get('url', '')
    if data.get('cast_list', {}).get('cast', {}) != '':
        cast_list = []
        castandrole_list = []
        for cast in data.get('cast_list', {}).get('cast', {}):
            if cast['type'] == 'Darsteller':
                if cast['character'] != '':
                    char = re.search(
                        '(.*)\(',
                        cast['content']).group(1).strip() if re.search(
                            '(.*)\(', cast['content']) else ''
                    castandrole_list.append((char, cast['character']))
                else:
                    cast_list.append(cast['content'])
            elif cast['type'] == 'Regie':
                info['director'] = cast['content']
        if len(castandrole_list) > 0:
            info['castandrole'] = castandrole_list
        else:
            info['cast'] = cast_list
    if data.get('genre', {}) != '':
        category_list = []
        for category in data.get('genre', {}):
            if 'content' in data.get('genre', {}).get(
                    category, {}) and not data.get('genre', {}).get(
                        category, {}).get('content', {}) in category_list:
                category_list.append(
                    data.get('genre', {}).get(category, {}).get('content', {}))
        info['genre'] = ", ".join(category_list)

    if asset_type == 'Sport':
        if data.get('current_type', '') == 'Live':
            #LivePlanner listing
            info['title'] = buildLiveEventTag(
                data['technical_event']['on_air']) + ' ' + info['title']
    if asset_type == 'Clip':
        info['title'] = data['item_title']
        info['plot'] = data.get('teaser_long', '')
        info['genre'] = data.get('item_category_name', '')
    if asset_type == 'live':
        item_data['event']['subtitle'] = htmlparser.unescape(
            item_data['event'].get('subtitle', ''))
        if item_data['channel']['name'].find("Bundesliga") != -1 or item_data[
                'channel']['name'].find("Sport") != -1:
            info['title'] = item_data['event'].get('subtitle', '')
        if info['title'] == '':
            info['title'] = item_data['event'].get('title', '')
        info['plot'] = data.get(
            'synopsis', '').replace('\n', '').strip() if data.get(
                'synopsis', '') != '' else item_data['event'].get(
                    'subtitle', '')
        if 'assetid' in item_data['event']:
            if 'mediainfo' in item_data:
                info['title'] = data.get('title', '')
                info['plot'] = data.get('synopsis', '').replace('\n',
                                                                '').strip()
            else:
                info['plot'] = 'Folge: ' + item_data.get('event', '').get(
                    'subtitle', '')
                info['title'] = item_data.get('event', '').get('title', '')
                info['duration'] = item_data.get('event', '').get('length',
                                                                  0) * 60
            if data.get('type', {}) == 'Film':
                asset_type = 'Film'
            elif data.get('type', {}) == 'Episode':
                asset_type = 'Episode'
                info['plot'] = 'Folge: ' + data.get(
                    'title', '') + '\n\n' + data.get('synopsis', '').replace(
                        '\n', '').strip()
                info['title'] = '%1dx%02d. %s' % (data.get(
                    'season_nr', ''), data.get(
                        'episode_nr', ''), data.get('serie_title', ''))
        if xbmcaddon.Addon().getSetting('channel_name_first') == 'true':
            channel = '[COLOR blue]' + item_data['channel'][
                'name'] + ' | [/COLOR]'
            info['title'] = channel + info['title']
        else:
            channel = '[COLOR blue] | ' + item_data['channel'][
                'name'] + '[/COLOR]'
            info['title'] += channel
    if asset_type == 'searchresult':
        if extMediaInfos and extMediaInfos == 'false':
            info['plot'] = data.get('description', '')
            info['year'] = data.get('year', '')
            info['genre'] = data.get('category', '')
        if data.get('type', {}) == 'Film':
            asset_type = 'Film'
        elif data.get('type', {}) == 'Episode':
            asset_type = 'Episode'
            info['plot'] = 'Folge: ' + data.get(
                'title', '') + '\n\n' + data.get('synopsis', '').replace(
                    '\n', '').strip()
            info['title'] = '%1dx%02d. %s' % (data.get(
                'season_nr', ''), data.get('episode_nr',
                                           ''), data.get('serie_title', ''))
    if asset_type == 'Film':
        info['mediatype'] = 'movie'
        if xbmcaddon.Addon().getSetting(
                'lookup_tmdb_data') == 'true' and not data.get('title',
                                                               '') == '':
            title = data.get('title', '').encode("utf-8")
            xbmc.log('Searching Rating and better Poster for %s at tmdb.com' %
                     title.upper())
            if not data.get('year_of_production', '') == '':
                TMDb_Data = getTMDBDataFromCache(title, info['year'])
            else:
                TMDb_Data = getTMDBDataFromCache(title)

            if TMDb_Data['rating'] is not None:
                info['rating'] = str(TMDb_Data['rating'])
                info['plot'] = 'User-Rating: ' + info[
                    'rating'] + ' / 10 (from TMDb) \n\n' + info['plot']
                xbmc.log("Result of get Rating: %s" % (TMDb_Data['rating']))
            if TMDb_Data['poster_path'] is not None:
                item_data['TMDb_poster_path'] = TMDb_Data['poster_path']
                xbmc.log("Path to TMDb Picture: %s" %
                         (TMDb_Data['poster_path']))
    if asset_type == 'Series':
        info['year'] = data.get('year_of_production_start', '')
    if asset_type == 'Episode':
        info['mediatype'] = 'episode'
        info['episode'] = data.get('episode_nr', '')
        info['season'] = data.get('season_nr', '')
        info['tvshowtitle'] = data.get('serie_title', '')
        if info['title'] == '':
            info['title'] = '%s - S%02dE%02d' % (data.get(
                'serie_title', ''), data.get('season_nr',
                                             0), data.get('episode_nr', 0))

    return info, item_data
Example #45
0
def main():
    if not hasattr(sys, 'listitem'):
        xbmc.log(
            'context.cinemavision: Not launched as a context menu - aborting')
        return
    xbmc.executebuiltin('RunScript(script.cinemavision,experience)')
Example #46
0
def _log(message):  # Write this module messages on XBMC log
    if module_log_enabled: xbmc.log("plugintools." + message)
Example #47
0
def log(msg, level=xbmc.LOGNOTICE):
    addon = xbmcaddon.Addon()
    addonID = addon.getAddonInfo('id')
    xbmc.log('%s: %s' % (addonID, msg), level) 
Example #48
0
 def scheduleNotifications(self):
     xbmc.log("[script.tvportal] Scheduling notifications")
     for channelTitle, programTitle, startTime in self.database.getNotifications():
         self._scheduleNotification(channelTitle, programTitle, startTime)
Example #49
0
            if not value:
                continue
            if key.lower() in ["label"]:
                listitem.setLabel(value)
            elif key.lower() in ["search_string"]:
                path = "plugin://plugin.program.autocompletion/?info=selectautocomplete&&id=%s" % value
                listitem.setPath(path=path)
                listitem.setProperty('path', path)
        listitem.setProperty("index", str(count))
        listitem.setProperty("isPlayable", "false")
        itemlist.append(listitem)
    return itemlist


if (__name__ == "__main__"):
    xbmc.log("version %s started" % ADDON_VERSION)
    args = sys.argv[2][1:]
    handle = int(sys.argv[1])
    infos = []
    params = {"handle": handle}
    delimiter = "&&"
    for arg in args.split(delimiter):
        param = arg.replace('"', '').replace("'", " ")
        if param.startswith('info='):
            infos.append(param[5:])
        else:
            try:
                params[param.split("=")[0].lower()] = "=".join(
                    param.split("=")[1:]).strip()
            except Exception:
                pass
Example #50
0
def Initialize():
    #-- remote PhantomJS service
    if Addon.getSetting('External_PhantomJS') == 'true':
        url = 'http://' + Addon.getSetting(
            'PhantomJS_IP') + ':' + Addon.getSetting('PhantomJS_Port')
        try:
            str = get_HTML(url)
        except:
            str = get_HTML(url)
        f = open(os.path.join(Addon.getAddonInfo('path'), 'ext_cookie.txt'),
                 'w')
        f.write(str)
        f.close()

        #-- load cookies
        cj.load(os.path.join(Addon.getAddonInfo('path'), 'ext_cookie.txt'),
                True, True)
        return

    #-- local PhantomJS service
    startupinfo = None
    if os.name == 'nt':
        prog = '"' + os.path.join(
            Addon.getAddonInfo('path'),
            'phantomjs.exe" --cookies-file="') + os.path.join(
                Addon.getAddonInfo('path'),
                'cookie.txt') + '" "' + os.path.join(
                    Addon.getAddonInfo('path'), 'seasonvar.js"')
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= 1
    else:
        prog = [
            os.path.join(Addon.getSetting('PhantomJS_Path'),
                         'phantomjs'), '--cookies-file=' +
            os.path.join(Addon.getAddonInfo('path'), 'cookie.txt'),
            os.path.join(Addon.getAddonInfo('path'), 'seasonvar.js')
        ]

    try:
        process = subprocess.Popen(prog,
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   shell=False,
                                   startupinfo=startupinfo)
        process.wait()
    except:
        xbmc.log('*** PhantomJS is not found or failed.')

    #-- load cookies
    f = open(os.path.join(Addon.getAddonInfo('path'), 'cookie.txt'), 'r')
    fcookie = f.read()
    f.close()

    group = ''
    for r in fcookie.split('\n'):
        r = r.strip()
        if group == '' and r != '':
            group = r
        elif r != '':
            ck = cookielib.Cookie(version=0,
                                  name=r.split('=', 1)[0],
                                  value=r.split('=', 1)[1],
                                  port=None,
                                  port_specified=False,
                                  domain=group.replace('[',
                                                       '').replace(']', ''),
                                  domain_specified=False,
                                  domain_initial_dot=False,
                                  path='/',
                                  path_specified=True,
                                  secure=False,
                                  expires=None,
                                  discard=True,
                                  comment=None,
                                  comment_url=None,
                                  rest={'HttpOnly': None},
                                  rfc2109=False)
            cj.set_cookie(ck)
        else:
            group = ''
Example #51
0
 def log(txt):
     if ADDON.getSetting("logEnabled") == "true":
         if isinstance(txt, str):
             txt = txt
         message = u'%s: %s' % (ADDON_ID, txt)
         xbmc.log(msg=message, level=xbmc.LOGDEBUG)
def writeLog(message, level=xbmc.LOGDEBUG):
    xbmc.log('[%s] %s' % (ADDONNAME, message.encode('utf-8')), level)
Example #53
0
def errorTrace(module, data):
    log = "PureVPN : (" + module + ") " + data
    xbmc.log(msg=log, level=xbmc.LOGERROR)
Example #54
0
# -*- coding: utf-8 -*
#/*
import string, xbmc, xbmcgui, xbmcplugin, os, xbmcaddon

addon = xbmcaddon.Addon(id='plugin.video.shura.tv')
step = addon.getSetting('SmallStepForward')

myPlayer = xbmc.PLAYER_CORE_AUTO
try:
    item = xbmcgui.ListItem('', '', '', '')
    archiveName = str(xbmc.Player(myPlayer).getVideoInfoTag().getTitle())
    #xbmc.log('Name0='+archiveName)
    archiveurl = xbmc.Player(myPlayer).getPlayingFile().split('=')[0]
    #xbmc.log('url='+archiveurl)
    archivetime = xbmc.Player(myPlayer).getPlayingFile().split('=')[1]
    #xbmc.log('time1='+str(archivetime))
    playedtime = xbmc.Player(myPlayer).getTime()
    #xbmc.log('played time='+str(playedtime)+',step='+str(step*60))
    archivetime = int(archivetime) + int(playedtime) + int(step) * 60
    #xbmc.log('time2='+str(archivetime))
    item.setInfo(type="Video", infoLabels={"Title": archiveName})
    url = archiveurl + '=' + str(archivetime)
    #xbmc.log('url2='+url)
    xbmc.Player(myPlayer).play(url, listitem=item)
except:
    xbmc.log(
        '[SHURA.TV] exception in OneMinForward.py use default function for this key'
    )
    xbmc.executebuiltin('PlayerControl(SmallSkipForward)')
#xbmc.log('[PageDownFixExceputed]')
Example #55
0
def make_notice(object):
    xbmc.log(str(object), xbmc.LOGDEBUG)
Example #56
0
def infoTrace(module, data):
    log = "PureVPN : (" + module + ") " + data
    xbmc.log(msg=log, level=xbmc.LOGNOTICE)
Example #57
0
def log(message):
    xbmc.log('OSMC APFStore store : ' + str(message), level=xbmc.LOGDEBUG)
Example #58
0
def debugTrace(data):    
    log = "PureVPN : " + data
    if addon.getSetting("vpn_enable_debug") == "true":
        print log        
    else:
        xbmc.log(msg=log, level=xbmc.LOGDEBUG)
Example #59
0
def error(s):
    xbmc.log(str(s), xbmc.LOGERROR)
		filename = oneFileOrFolderItem["name"]
		if oneFileOrFolderItem["isfolder"]:
			li = xbmcgui.ListItem(filename)
			li.setIconImage("DefaultFolder.png")
			# Add context menu item for "delete folder"
			deleteActionMenuText = myAddon.getLocalizedString(30114) # "Delete from PCloud..."
			deleteActionUrl = base_url + "?mode=delete&folderID=" + str(oneFileOrFolderItem["folderid"]) + "&filename=" + quote(oneFileOrFolderItem["name"].encode("utf-8"))
			li.addContextMenuItems(
				[(deleteActionMenuText, "RunPlugin(" + deleteActionUrl + ")")])
			# Finally add the list item to the directory
			url = base_url + "?mode=folder&folderID=" + str(oneFileOrFolderItem["folderid"])
			xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
									listitem=li, isFolder=True)
		else:
			contentType = oneFileOrFolderItem["contenttype"]
			xbmc.log ("contentType is: ")
			xbmc.log (contentType)
			if not contentType.startswith("video/"
				) and not contentType.startswith("audio/"
				) and not contentType.startswith("application/x-iso9660-image"
				) and not contentType.startswith("image/"):
				continue
			fileUrl = base_url + "?mode=file&fileID=" + str(oneFileOrFolderItem["fileid"])
			thumbnailUrl = thumbs.get(oneFileOrFolderItem["fileid"], None)
			if thumbnailUrl is None:
				if contentType[:6] == "video/":
					thumbnailUrl = "DefaultVideo.png"
				elif contentType[:6] == "audio/":
					thumbnailUrl = "DefaultAlbumCover.png"
			li = xbmcgui.ListItem(filename)
			li.setIconImage(thumbnailUrl)