Example #1
0
def ShowDirectDownloadTVItems(html, cached=False, cached_path=False):
    html=main.unescapes(html)
    if cached: 
        match = eval(cached)
    else:
        match=re.compile('{"release":"([^"]+?)","when":.+?,"size":".+?","links":(.+?),"idtvs".+?"quality":"([^"]+?)".+?}').findall(html)
        if cached_path and match:
            main.setFile(cached_path,str(match))
    totalLinks = len(match)
    if totalLinks:
        dialogWait = xbmcgui.DialogProgress()
        ret = dialogWait.create('Please wait until Show list is cached.')
        loadedLinks = 0
        remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].'
        dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display)
        xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)")
        for title,url,quality in match:
            title = processTitle(title,quality)
            url=url.replace('\/','/')
            if isArchive(url): title = '[B][Archived][/B] ' + title
            main.addDirTE(title,url,62,'','','','','','')
            loadedLinks += 1
            percent = (loadedLinks * 100)/totalLinks
            remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].'
            dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display)
            if dialogWait.iscanceled(): return loadedLinks
        dialogWait.close()
        del dialogWait
    return totalLinks
Example #2
0
def MAINSIDE(cacheOnly = False):
    import time
    import datetime
    cached_path = os.path.join(os.path.join(main.datapath,'Cache'), 'Sidereel')
    cached = main.getFile(cached_path)
    if (not cached or (cached and time.mktime(datetime.date.today().timetuple()) > os.stat(cached_path).st_mtime)
         or xbmcgui.Window(10000).getProperty('Refresh_Sidreel')):
        from t0mm0.common.net import Net as net
        setCookie(MAINURL)
        response = net().http_GET(MAINURL)
        link = response.content
        link = cleanHex(link)
        link=link.replace('\r','').replace('\n','').replace('\t','').replace(' ','').replace('  ','')
        today=re.compile("<li class='current'>[^/]+?<h2 class='[^']*?'><span>(.+?)</span></h2><div(.+?)/div></div></li>",re.DOTALL).findall(link)
        match=re.compile("<li class=''>[^/]+?<h2 class='[^']+?'><span>(.+?)</span></h2><div(.+?)/div></div></li>",re.DOTALL).findall(link)
        match = today + match
        if match:
            main.setFile(cached_path,str(match),True)
        if '''<h3 class='sr-header sr-blue font-16'>Login to your account</h3>''' in link:
            main.addLink('[COLOR red]Login Error Clear Cache & Cookies Below[/COLOR]','TV','')
            main.addDir('[COLOR blue]Clear Cache & Cookies[/COLOR]','MashCache',416,art+'/maintenance.png')
        xbmcgui.Window(10000).clearProperty('Refresh_Sidreel')
    else: match = eval(cached)
    if cacheOnly: return False
    main.GA("None","SideReel")
    main.addDir('Search for Shows','TV',398,art+'/search.png')
    main.addDir('All Tracked Shows','TV',402,art+'/sidereel.png')
    
    import calendar
    todaytimestamp = calendar.timegm(time.strptime(time.strftime("%b") + " " + time.strftime("%d"), "%b %d"))
    showsdisplayed = 0
    for date,shows in match:
        print shows
        if 'data-track-label="Profile"' in shows:
            s = re.sub('(?i)^.*?,(.*)$','\\1',date).strip()
            timestamp =  calendar.timegm(time.strptime(s, "%b %d"))
            days = (timestamp - todaytimestamp) / 86400
            relative = getRelativeDate(days)
            main.addLink('[COLOR yellow]'+date+'[/COLOR]  [COLOR orange]('+relative+')[/COLOR]','',art+'/link.png')
            
            match2=re.compile("""data-track-label="Profile" href=".+?">([^<]+?)</a><div><a class=".+?data-track-label="Profile" href="([^"]+?)">([^<]+?)</a></div>""",re.DOTALL).findall(shows)
            for showname,seaepi, epiname in match2:
                se=re.search('season-(\d+)/episode-(\d+)',seaepi)
                if se:
                    if len(se.group(1))==1:
                        sea='0'+str(se.group(1))
                    else:
                        sea=str(se.group(1))
                    if len(se.group(2))==1:
                        epi='0'+str(se.group(2))
                    else:
                        epi=str(se.group(2))
                    final= 'S'+sea+'E'+epi
                else:
                    final=''

                main.addDir(showname+' '+final+' [COLOR red] "'+epiname+'"[/COLOR]','TV',20,art+'/sidereel.png')
                showsdisplayed += 1
    if not showsdisplayed: main.removeFile(cached_path)
Example #3
0
def showList(cacheOnly = False):
    if not user:
        xbmc.executebuiltin("XBMC.Notification(Sorry,Set Trakt user in settings,3000)")
        xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False, False)
        return False
    import time,datetime,calendar
    todaytimestamp = calendar.timegm(time.strptime(time.strftime("%Y") + "-" + time.strftime("%m") + "-" + time.strftime("%d"), "%Y-%m-%d"))
    cached_path = os.path.join(os.path.join(main.datapath,'Cache'), 'Trakt')
    cached = main.getFile(cached_path)
    if (not cached or (cached and time.mktime(datetime.date.today().timetuple()) > os.stat(cached_path).st_mtime)
         or xbmcgui.Window(10000).getProperty('Refresh_Trakt')):
        setCookie()
        import hashlib,json
        data = {'username':user,'password':hashlib.sha1(passw).hexdigest()}
        link = main.OPENURL("http://api.trakt.tv/user/calendar/shows.json/"+TRAKT_API+"/"+user+'/6daysago/14',data=data)
        fields=json.loads(link)
        tofront = []
        daysinfuture = 2
        daysinpast = 1
        for item in fields:
            timestamp =  calendar.timegm(time.strptime(item['date'], "%Y-%m-%d"))
            if timestamp <= todaytimestamp + daysinfuture * 86400 and timestamp >= todaytimestamp - daysinpast * 86400:
                tofront.append(item)
        for item in tofront:fields.remove(item)
        fields = tofront + fields
        if fields:
            main.setFile(cached_path,str(fields),True)
        xbmcgui.Window(10000).clearProperty('Refresh_Trakt')
    else: fields = eval(cached)
    if cacheOnly: return False
    main.GA("None","Trakt")
    main.addDir('Search for Shows','TV',430,art+'/search.png')
    main.addDir('All Tracked Shows','TV',431,art+'/sidereel.png')
    showsdisplayed = 0
    for data in fields:
        timestamp =  calendar.timegm(time.strptime(data['date'], "%Y-%m-%d"))
        datestring = datetime.datetime.fromtimestamp(timestamp).strftime('%A, %b %d')
        days = (timestamp - todaytimestamp) / 86400
        relative = getRelativeDate(days)
        main.addLink('[COLOR yellow]'+datestring+'[/COLOR]  [COLOR orange]('+relative+')[/COLOR]','',art+'/link.png')
        for showdata in data['episodes']:
            if showdata['episode']['season'] < 10: sea='0'+str(showdata['episode']['season'])
            else: sea=str(showdata['episode']['season'])
            if showdata['episode']['number'] < 10: epi='0'+str(showdata['episode']['number'])
            else: epi=str(showdata['episode']['number'])
            episodenumber= 'S'+sea+'E'+epi
            airtime = showdata['show']['air_time_localized'].upper().replace("AM"," AM").replace("PM"," PM")+' on ' + showdata['show']['network']
            main.addDir(showdata['show']['title'].encode('utf-8')+' '+episodenumber+' [COLOR red]"'+showdata['episode']['title'].encode('utf-8')+
                        '"[/COLOR] [COLOR blue]'+ airtime.encode('utf-8') +'[/COLOR]','TV',20,showdata['show']['images']['poster'].encode('utf-8'),
                        showdata['episode']['overview'].encode('utf-8'),showdata['episode']['images']['screen'].encode('utf-8'))
            showsdisplayed += 1
    if not showsdisplayed: main.removeFile(cached_path)
Example #4
0
File: trakt.py Project: noba3/KoTos
def showList(cacheOnly = False):
    if not user:
        xbmc.executebuiltin("XBMC.Notification(Sorry,Set Trakt user in settings,3000)")
        xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False, False)
        return False
    import time,datetime,calendar
    todaytimestamp = time.mktime(time.strptime(time.strftime("%Y") + "-" + time.strftime("%m") + "-" + time.strftime("%d"), "%Y-%m-%d"))
    cached_path = os.path.join(os.path.join(main.datapath,'Cache'), 'Trakt')
    cached = main.getFile(cached_path)
    if (not cached or (cached and time.mktime(datetime.date.today().timetuple()) > os.stat(cached_path).st_mtime)
         or xbmcgui.Window(10000).getProperty('Refresh_Trakt')):
        setCookie()
        import hashlib,json
        data = {'username':user,'password':hashlib.sha1(passw).hexdigest()}
        link = main.OPENURL("http://api.trakt.tv/user/calendar/shows.json/"+TRAKT_API+"/"+user+'/6daysago/14',data=data)
        fields=json.loads(link)
        tofront = []
        daysinfuture = 2
        daysinpast = 1
        for item in fields:
            timestamp =  time.mktime(time.strptime(item['date'], "%Y-%m-%d"))
            if timestamp <= todaytimestamp + daysinfuture * 86400 and timestamp >= todaytimestamp - daysinpast * 86400:
                tofront.append(item)
        for item in tofront:fields.remove(item)
        fields = tofront + fields
        if fields:
            main.setFile(cached_path,str(fields),True)
        xbmcgui.Window(10000).clearProperty('Refresh_Trakt')
    else: fields = eval(cached)
    if cacheOnly: return False
    main.GA("None","Trakt")
    main.addDir('Search for Shows','TV',430,art+'/search.png')
    main.addDir('All Tracked Shows','TV',431,art+'/sidereel.png')
    showsdisplayed = 0
    for data in fields:
        timestamp =  time.mktime(time.strptime(data['date'], "%Y-%m-%d"))
        datestring = (datetime.datetime.fromtimestamp(timestamp)).strftime('%A, %b %d')
        days = (timestamp - todaytimestamp) / 86400
        relative = getRelativeDate(days)
        main.addLink('[COLOR yellow]'+str(datestring)+'[/COLOR]  [COLOR orange]('+relative+')[/COLOR]','',art+'/link.png')
        for showdata in data['episodes']:
            if showdata['episode']['season'] < 10: sea='0'+str(showdata['episode']['season'])
            else: sea=str(showdata['episode']['season'])
            if showdata['episode']['number'] < 10: epi='0'+str(showdata['episode']['number'])
            else: epi=str(showdata['episode']['number'])
            episodenumber= 'S'+sea+'E'+epi
            airtime = showdata['show']['air_time_localized'].upper().replace("AM"," AM").replace("PM"," PM")+' on ' + showdata['show']['network']
            main.addDir(showdata['show']['title'].encode('utf-8')+' '+episodenumber+' [COLOR red]"'+showdata['episode']['title'].encode('utf-8')+
                        '"[/COLOR] [COLOR blue]'+ airtime.encode('utf-8') +'[/COLOR]','TV',20,showdata['show']['images']['poster'].encode('utf-8'))
            #            showdata['episode']['overview'].encode('utf-8'),showdata['episode']['images']['screen'].encode('utf-8'))
            showsdisplayed += 1
    if not showsdisplayed: main.removeFile(cached_path)
Example #5
0
def MAIN():
    lock_file_path = os.path.join(os.path.join(main.datapath,'Temp'), 'mbox.lock')
    lock_file = main.getFile(lock_file_path)
    if not lock_file:
        try: 
            lib=os.path.join(datapath, 'MBox.zip')
            if main.downloadFile(dataurl,lib,False): xbmc.executebuiltin("XBMC.Extract(%s,%s)"%(lib,profile))
        except: pass
        main.setFile(lock_file_path,'lock')
    main.addDir('First 25 Movies','25movies',278,art+'/mbox.png')
    main.addDir('Movies','movies',278,art+'/mbox.png')
    main.addDir('TV','tv',278,art+'/mbox.png')
    main.addDir('Music','music',278,art+'/mbox.png')
Example #6
0
def ListSceneLogItems(murl, quality='all'):
    if murl.startswith('Movies'):
        main.addDir('Search SceneLog', 'Movies', 659, art + '/search.png')
        subpages = 5
        category = "movies"
    elif murl.startswith('TV'):
        main.addDir('Search SceneLog', 'TV', 659, art + '/search.png')
        subpages = 5
        category = "tv-shows"
    parts = murl.split('-', 1)
    max = subpages
    try:
        pages = parts[1].split(',', 1)
        page = int(pages[0])
        max = int(pages[1])
        murl = parts[0]
    except:
        page = 0
    page = page * subpages
    html = ''
    urls = []
    for n in range(subpages):
        if page + n + 1 > max: break
        urls.append('http://scnlog.eu/' + category + '/page/' +
                    str(page + n + 1) + '/')
    cached_path = os.path.join(
        os.path.join(main.datapath, 'Temp'),
        filename + '_' + murl + "-" + str(page) + '.cache')
    cached = main.getFile(cached_path)
    if cached:
        xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)")
        html = cached
    else:
        html = main.batchOPENURL(urls)
        main.setFile(cached_path, html)
    hasNextPage = re.compile('<strong>&raquo;</strong>').findall(html)
    if len(hasNextPage) < subpages:
        page = None
    hasMax = re.compile('page/(\d+)/">Last &raquo;').findall(html)
    if hasMax:
        max = hasMax[0]
    if html:
        ShowSceneLogItems(html, murl, quality)
        if not page is None:
            main.addDir('Page ' + str(page / subpages + 1) + ', Next Page >>>',
                        murl + "-" + str(page / subpages + 1) + "," + max, 657,
                        art + '/next2.png')
    main.GA("Movies-TV", "SceneLog")
    main.VIEWS()
Example #7
0
File: mbox.py Project: noba3/KoTos
def MAIN():
    lock_file_path = os.path.join(os.path.join(main.datapath, "Temp"), "mbox.lock")
    lock_file = main.getFile(lock_file_path)
    if not lock_file:
        try:
            lib = os.path.join(datapath, "MBox.zip")
            if main.downloadFile(dataurl, lib, False):
                xbmc.executebuiltin("XBMC.Extract(%s,%s)" % (lib, profile))
        except:
            pass
        main.setFile(lock_file_path, "lock")
    main.addDir("First 25 Movies", "25movies", 278, art + "/mbox.png")
    main.addDir("Movies", "movies", 278, art + "/mbox.png")
    main.addDir("TV", "tv", 278, art + "/mbox.png")
    main.addDir("Music", "music", 278, art + "/mbox.png")
    main.GA("Plugin", "MBox")
Example #8
0
def MAIN():
    lock_file_path = os.path.join(os.path.join(main.datapath, 'Temp'),
                                  'mbox.lock')
    lock_file = main.getFile(lock_file_path)
    if not lock_file:
        try:
            lib = os.path.join(datapath, 'MBox.zip')
            if main.downloadFile(dataurl, lib, False):
                xbmc.executebuiltin("XBMC.Extract(%s,%s)" % (lib, profile))
        except:
            pass
        main.setFile(lock_file_path, 'lock')
    main.addDir('First 25 Movies', '25movies', 278, art + '/mbox.png')
    main.addDir('Movies', 'movies', 278, art + '/mbox.png')
    main.addDir('TV', 'tv', 278, art + '/mbox.png')
    main.addDir('Music', 'music', 278, art + '/mbox.png')
    main.GA("Plugin", "MBox")
Example #9
0
def ListSceneLogItems(murl,quality='all'):
    if murl.startswith('Movies'):
        main.addDir('Search SceneLog','Movies',659,art+'/search.png')
        subpages = 5
        category = "movies"
    elif murl.startswith('TV'):
        main.addDir('Search SceneLog','TV',659,art+'/search.png')
        subpages = 5
        category = "tv-shows"
    parts = murl.split('-', 1 );
    max = subpages
    try:
        pages = parts[1].split(',', 1 );
        page = int(pages[0])
        max = int(pages[1])
        murl = parts[0]
    except:
        page = 0
    page = page * subpages;
    html = ''
    urls = []
    for n in range(subpages):
        if page + n + 1 > max: break
        urls.append('http://scnlog.eu/'+category+'/page/'+str(page+n+1)+'/')
    cached_path = os.path.join(os.path.join(main.datapath,'Temp'), filename + '_' + murl+"-"+str(page)+'.cache')
    cached = main.getFile(cached_path)
    if cached:
        xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)")          
        html = cached
    else:
        html = main.batchOPENURL(urls)
        main.setFile(cached_path,html)
    hasNextPage = re.compile('<strong>&raquo;</strong>').findall(html)
    if len(hasNextPage) < subpages:
        page = None
    hasMax = re.compile('page/(\d+)/">Last &raquo;').findall(html)
    if hasMax:
        max = hasMax[0]
    if html:
        ShowSceneLogItems(html,murl,quality)
        if not page is None:
            main.addDir('Page ' + str(page/subpages+1) + ', Next Page >>>',murl + "-" + str(page/subpages+1) + "," + max,657,art+'/next2.png')
    main.GA("Movies-TV","SceneLog")
    main.VIEWS()
Example #10
0
def setCookie():
    cookieExpired = False
    if os.path.exists(cookie_file):
        try:
            cookie = open(cookie_file).read()
            expire = re.search('expires="(.*?)"',cookie, re.I)
            if expire:
                expire = str(expire.group(1))
                import time
                if time.time() > time.mktime(time.strptime(expire, '%Y-%m-%d %H:%M:%SZ')):
                   cookieExpired = True
        except: cookieExpired = True 
        loggedin = re.search('morbo',cookie, re.I)
    if not os.path.exists(cookie_file) or cookieExpired or (not loggedin and user != '' and passw != '') or not apifile:
        main.OPENURL('http://trakt.tv/auth/signin',data={'username':user,'password':passw,'remember_me':1},cookie='trakt')
    if not apifile:
        apihtml = main.OPENURL('http://trakt.tv/settings/api',cookie='trakt')
        api = re.search('(?i)name="email" value="([^"]+?)"',apihtml)
        if api: main.setFile(api_file,api.group(1),True)
Example #11
0
File: trakt.py Project: noba3/KoTos
def setCookie():
    cookieExpired = False
    if os.path.exists(cookie_file):
        try:
            cookie = open(cookie_file).read()
            expire = re.search('expires="(.*?)"',cookie, re.I)
            if expire:
                expire = str(expire.group(1))
                import time
                if time.time() > time.mktime(time.strptime(expire, '%Y-%m-%d %H:%M:%SZ')):
                   cookieExpired = True
        except: cookieExpired = True 
        loggedin = re.search('morbo',cookie, re.I)
    if not os.path.exists(cookie_file) or cookieExpired or (not loggedin and user != '' and passw != '') or not apifile:
        main.OPENURL('http://trakt.tv/auth/signin',data={'username':user,'password':passw,'remember_me':1},cookie='trakt')
    if not apifile:
        apihtml = main.OPENURL('http://trakt.tv/settings/api',cookie='trakt')
        api = re.search('(?i)name="email" value="([^"]+?)"',apihtml)
        if api: main.setFile(api_file,api.group(1),True)
Example #12
0
def ShowDirectDownloadTVItems(html, cached=False, cached_path=False):
    html = main.unescapes(html)
    if cached:
        match = eval(cached)
    else:
        match = re.compile(
            '{"release":"([^"]+?)","when":.+?,"size":".+?","links":(.+?),"idtvs".+?"quality":"([^"]+?)".+?}'
        ).findall(html)
        if cached_path and match:
            main.setFile(cached_path, str(match))
    totalLinks = len(match)
    if totalLinks:
        dialogWait = xbmcgui.DialogProgress()
        ret = dialogWait.create('Please wait until Show list is cached.')
        loadedLinks = 0
        remaining_display = 'Episodes loaded :: [B]' + str(
            loadedLinks) + ' / ' + str(totalLinks) + '[/B].'
        dialogWait.update(0, '[B]Will load instantly from now on[/B]',
                          remaining_display)
        xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)")
        for title, url, quality in match:
            title = processTitle(title, quality)
            url = url.replace('\/', '/')
            if isArchive(url): title = '[B][Archived][/B] ' + title
            main.addDirTE(title, url, 62, '', '', '', '', '', '')
            loadedLinks += 1
            percent = (loadedLinks * 100) / totalLinks
            remaining_display = 'Episodes loaded :: [B]' + str(
                loadedLinks) + ' / ' + str(totalLinks) + '[/B].'
            dialogWait.update(percent,
                              '[B]Will load instantly from now on[/B]',
                              remaining_display)
            if dialogWait.iscanceled(): return loadedLinks
        dialogWait.close()
        del dialogWait
    return totalLinks
Example #13
0
def CheckForAutoUpdate(force = False):
	if selfAddon.getSetting("autosource") == "false":
                if selfAddon.getSetting("updateoption") == "gitupdate1":
                    GitHubRepo    = 'gitupdate1'
                    UpdateVerFile = 'gitupdate1'
                    GitHubUser    = '******'
                elif selfAddon.getSetting("updateoption") == "gitupdate2":
                    GitHubRepo    = 'gitupdate2'
                    UpdateVerFile = 'gitupdate2'
                    GitHubUser    = '******'
                else:
                    GitHubRepo    = 'AutoUpdate'
                    UpdateVerFile = 'update'
                    GitHubUser    = '******'
		GitHubBranch  = 'master'
		RunningFile   = 'running'
		verCheck=True #main.CheckVersion()#Checks If Plugin Version is up to date
		if verCheck == True:
			from resources.libs import autoupdate
			try:
				print "Mashup auto update - started"
				html=main.OPENURL('https://github.com/'+GitHubUser+'/'+GitHubRepo+'?files=1', mobile=True, verbose=False)
			except: html=''
			m = re.search("View (\d+) commit",html,re.I)
			if m: gitver = int(m.group(1))
			else: gitver = 0
			UpdateVerPath = os.path.join(UpdatePath,UpdateVerFile)
			try: locver = int(autoupdate.getUpdateFile(UpdateVerPath))
			except: locver = 0
			RunningFilePath = os.path.join(UpdatePath, RunningFile)
			if locver < gitver and (not os.path.exists(RunningFilePath) or os.stat(RunningFilePath).st_mtime + 120 < time.time()) or force:
				UpdateUrl = 'https://github.com/'+GitHubUser+'/'+GitHubRepo+'/archive/'+GitHubBranch+'.zip'
				UpdateLocalName = GitHubRepo+'.zip'
				UpdateDirName   = GitHubRepo+'-'+GitHubBranch
				UpdateLocalFile = xbmc.translatePath(os.path.join(UpdatePath, UpdateLocalName))
				main.setFile(RunningFilePath,'')
				print "auto update - new update available ("+str(gitver)+")"
				xbmc.executebuiltin("XBMC.Notification(MashUp Update,New Update detected,3000,"+main.slogo+")")
				xbmc.executebuiltin("XBMC.Notification(MashUp Update,Updating...,3000,"+main.slogo+")")
				try:os.remove(UpdateLocalFile)
				except:pass
				try: urllib.urlretrieve(UpdateUrl,UpdateLocalFile)
				except:pass
				if os.path.isfile(UpdateLocalFile):
					extractFolder = xbmc.translatePath('special://home/addons')
					pluginsrc =  xbmc.translatePath(os.path.join(extractFolder,UpdateDirName))
					if autoupdate.unzipAndMove(UpdateLocalFile,extractFolder,pluginsrc):
						autoupdate.saveUpdateFile(UpdateVerPath,str(gitver))
						main.GA("Autoupdate",str(gitver)+" Successful")
						print "Mashup auto update - update install successful ("+str(gitver)+")"
						xbmc.executebuiltin("XBMC.Notification(MashUp Update,Successful,5000,"+main.slogo+")")
						xbmc.executebuiltin("XBMC.Container.Refresh")
						if selfAddon.getSetting('autochan')=='true':
							xbmc.executebuiltin('XBMC.RunScript('+xbmc.translatePath(main.mashpath + '/resources/libs/changelog.py')+',Env)')
					else:
						print "Mashup auto update - update install failed ("+str(gitver)+")"
						xbmc.executebuiltin("XBMC.Notification(MashUp Update,Failed,3000,"+main.elogo+")")
						main.GA("Autoupdate",str(gitver)+" Failed")
				else:
					print "Mashup auto update - cannot find downloaded update ("+str(gitver)+")"
					xbmc.executebuiltin("XBMC.Notification(MashUp Update,Failed,3000,"+main.elogo+")")
					main.GA("Autoupdate",str(gitver)+" Repo problem")
				try:os.remove(RunningFilePath)
				except:pass
			else:
				if force: xbmc.executebuiltin("XBMC.Notification(MashUp Update,MashUp is up-to-date,3000,"+main.slogo+")")
				print "Mashup auto update - Mashup is up-to-date ("+str(locver)+")"
			return
	else:
		GitHubRepo    = 'bitautoupdate1'
		GitHubUser    = '******'
		GitHubBranch  = 'master'
		UpdateVerFile = 'bitupdate1'
		RunningFile   = 'running'
		verCheck=True #main.CheckVersion()#Checks If Plugin Version is up to date
		if verCheck == True:
			from resources.libs import autoupdate
			try:
                                import time
				print "Mashup auto update - started"
				html=main.OPENURL('https://bitbucket.org/api/1.0/repositories/'+GitHubUser+'/'+GitHubRepo+'/branches-tags?'+ str(time.time()), mobile=True, verbose=False)
			except: html=''
			m = re.search('"changeset": "([^"]+?)"',html,re.I)
			if m: 
				gitver = m.group(1)[0:7]
				CommitNumber=m.group(1)[0:12]
			else: gitver = 0
			UpdateVerPath = os.path.join(UpdatePath,UpdateVerFile)
			try: locver = autoupdate.getUpdateFile(UpdateVerPath)
			except: locver = 0
			RunningFilePath = os.path.join(UpdatePath, RunningFile)
			if locver != gitver and (not os.path.exists(RunningFilePath) or os.stat(RunningFilePath).st_mtime + 120 < time.time()) or force:
				UpdateUrl = 'https://bitbucket.org/'+GitHubUser+'/'+GitHubRepo+'/get/'+GitHubBranch+'.zip'
				UpdateLocalName = GitHubRepo+'.zip'
				UpdateDirName   = GitHubUser+'-'+GitHubRepo+'-'+CommitNumber
				print UpdateDirName
				UpdateLocalFile = xbmc.translatePath(os.path.join(UpdatePath, UpdateLocalName))
				main.setFile(RunningFilePath,'')
				print "auto update - new update available ("+str(gitver)+")"
				xbmc.executebuiltin("XBMC.Notification(MashUp Update,New Update detected,3000,"+main.slogo+")")
				xbmc.executebuiltin("XBMC.Notification(MashUp Update,Updating...,3000,"+main.slogo+")")
				try:os.remove(UpdateLocalFile)
				except:pass
				try: urllib.urlretrieve(UpdateUrl,UpdateLocalFile)
				except:pass
				if os.path.isfile(UpdateLocalFile):
                                        extractFolder = xbmc.translatePath('special://home/addons')
                                        pluginsrc =  xbmc.translatePath(os.path.join(extractFolder,UpdateDirName))
                                        if autoupdate.unzipAndMove(UpdateLocalFile,extractFolder,pluginsrc):
						autoupdate.saveUpdateFile(UpdateVerPath,str(gitver))
						main.GA("Autoupdate",str(gitver)+" Successful")
						print "Mashup auto update - update install successful ("+str(gitver)+")"
						xbmc.executebuiltin("XBMC.Notification(MashUp Update,Successful,5000,"+main.slogo+")")
						xbmc.executebuiltin("XBMC.Container.Refresh")
						if selfAddon.getSetting('autochan')=='true':
							xbmc.executebuiltin('XBMC.RunScript('+xbmc.translatePath(main.mashpath + '/resources/libs/changelog.py')+',Env)')
					else:
						print "Mashup auto update - update install failed ("+str(gitver)+")"
						xbmc.executebuiltin("XBMC.Notification(MashUp Update,Failed,3000,"+main.elogo+")")
						main.GA("Autoupdate",str(gitver)+" Failed")
				else:
					print "Mashup auto update - cannot find downloaded update ("+str(gitver)+")"
					xbmc.executebuiltin("XBMC.Notification(MashUp Update,Failed,3000,"+main.elogo+")")
					main.GA("Autoupdate",str(gitver)+" Repo problem")
				try:os.remove(RunningFilePath)
				except:pass
			else:
				if force: xbmc.executebuiltin("XBMC.Notification(MashUp Update,MashUp is up-to-date,3000,"+main.slogo+")")
				print "Mashup auto update - Mashup is up-to-date ("+str(locver)+")"
			return
Example #14
0
def MAINSIDE(cacheOnly=False):
    import time
    import datetime
    cached_path = os.path.join(os.path.join(main.datapath, 'Cache'),
                               'Sidereel')
    cached = main.getFile(cached_path)
    if (not cached or (cached and time.mktime(
            datetime.date.today().timetuple()) > os.stat(cached_path).st_mtime)
            or xbmcgui.Window(10000).getProperty('Refresh_Sidreel')):
        from t0mm0.common.net import Net as net
        setCookie(MAINURL)
        response = net().http_GET(MAINURL)
        link = response.content
        link = cleanHex(link)
        link = link.replace('\r',
                            '').replace('\n', '').replace('\t', '').replace(
                                '&nbsp;', '').replace('  ', '')
        today = re.compile(
            "<li class='current'>[^/]+?<h2 class='[^']*?'><span>(.+?)</span></h2><div(.+?)/div></div></li>",
            re.DOTALL).findall(link)
        match = re.compile(
            "<li class=''>[^/]+?<h2 class='[^']+?'><span>(.+?)</span></h2><div(.+?)/div></div></li>",
            re.DOTALL).findall(link)
        match = today + match
        if match:
            main.setFile(cached_path, str(match), True)
        else:
            main.addLink(
                '[COLOR red]Something is wrong, Check if you credentials are correct[/COLOR]',
                'TV', '')
            main.addSpecial(
                '[COLOR yellow]User: [/COLOR][COLOR white]' + user +
                '[/COLOR] --- Click to EDIT', 'USER', 456, '')
            main.addSpecial(
                '[COLOR yellow]Pass: [/COLOR][COLOR white]' + passw +
                '[/COLOR] --- Click to EDIT', 'PASS', 456, '')
            main.addLink(
                '[COLOR orange]If they are correct Clear Cache & Cookies Below[/COLOR]',
                'TV', '')
            main.addDir('[COLOR blue]Clear Cache & Cookies[/COLOR]',
                        'MashCache', 416, art + '/maintenance.png')
            main.addLink(
                '[COLOR red]If that does not solve the issue post log on forums[/COLOR]',
                'TV', '')
        xbmcgui.Window(10000).clearProperty('Refresh_Sidreel')
    else:
        match = eval(cached)
    if cacheOnly: return False
    main.GA("None", "SideReel")
    main.addDir('Search for Shows', 'TV', 398, art + '/search.png')
    main.addDir('All Tracked Shows', 'TV', 402, art + '/sidereel.png')

    import calendar
    todaytimestamp = calendar.timegm(
        time.strptime(
            time.strftime("%b") + " " + time.strftime("%d"), "%b %d"))
    showsdisplayed = 0
    for date, shows in match:
        print shows
        if 'data-track-label="TrackerPage"' in shows:
            s = re.sub('(?i)^.*?,(.*)$', '\\1', date).strip()
            timestamp = calendar.timegm(time.strptime(s, "%b %d"))
            days = (timestamp - todaytimestamp) / 86400
            relative = getRelativeDate(days)
            main.addLink(
                '[COLOR yellow]' + date + '[/COLOR]  [COLOR orange](' +
                relative + ')[/COLOR]', '', art + '/link.png')

            match2 = re.compile(
                """data-track-label="TrackerPage" href=".+?">([^<]+?)</a><div><a class=".+?data-track-label="TrackerPage" href="([^"]+?)">([^<]+?)</a></div>""",
                re.DOTALL).findall(shows)
            for showname, seaepi, epiname in match2:
                se = re.search('season-(\d+)/episode-(\d+)', seaepi)
                if se:
                    if len(se.group(1)) == 1:
                        sea = '0' + str(se.group(1))
                    else:
                        sea = str(se.group(1))
                    if len(se.group(2)) == 1:
                        epi = '0' + str(se.group(2))
                    else:
                        epi = str(se.group(2))
                    final = 'S' + sea + 'E' + epi
                else:
                    final = ''

                main.addDir(
                    showname + ' ' + final + ' [COLOR red] "' + epiname +
                    '"[/COLOR]', 'TV', 20, art + '/sidereel.png')
                showsdisplayed += 1
    if not showsdisplayed: main.removeFile(cached_path)
Example #15
0
def showList(cacheOnly=False):
    if not user:
        xbmc.executebuiltin("XBMC.Notification(Sorry,Set Trakt user in settings,3000)")
        xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False, False)
        return False
    import time, datetime, calendar

    todaytimestamp = calendar.timegm(
        time.strptime(time.strftime("%Y") + "-" + time.strftime("%m") + "-" + time.strftime("%d"), "%Y-%m-%d")
    )
    cached_path = os.path.join(os.path.join(main.datapath, "Cache"), "Trakt")
    cached = main.getFile(cached_path)
    if (
        not cached
        or (cached and time.mktime(datetime.date.today().timetuple()) > os.stat(cached_path).st_mtime)
        or xbmcgui.Window(10000).getProperty("Refresh_Trakt")
    ):
        setCookie()
        import hashlib, json

        data = {"username": user, "password": hashlib.sha1(passw).hexdigest()}
        link = main.OPENURL(
            "http://api.trakt.tv/user/calendar/shows.json/" + TRAKT_API + "/" + user + "/6daysago/14", data=data
        )
        fields = json.loads(link)
        tofront = []
        daysinfuture = 2
        daysinpast = 1
        for item in fields:
            timestamp = calendar.timegm(time.strptime(item["date"], "%Y-%m-%d"))
            if timestamp <= todaytimestamp + daysinfuture * 86400 and timestamp >= todaytimestamp - daysinpast * 86400:
                tofront.append(item)
        for item in tofront:
            fields.remove(item)
        fields = tofront + fields
        if fields:
            main.setFile(cached_path, str(fields), True)
        xbmcgui.Window(10000).clearProperty("Refresh_Trakt")
    else:
        fields = eval(cached)
    if cacheOnly:
        return False
    main.GA("None", "Trakt")
    main.addDir("Search for Shows", "TV", 430, art + "/search.png")
    main.addDir("All Tracked Shows", "TV", 431, art + "/sidereel.png")
    showsdisplayed = 0
    for data in fields:
        timestamp = calendar.timegm(time.strptime(data["date"], "%Y-%m-%d"))
        datestring = (datetime.datetime.fromtimestamp(timestamp) + datetime.timedelta(1)).strftime("%A, %b %d")
        days = (timestamp - todaytimestamp) / 86400
        relative = getRelativeDate(days)
        main.addLink(
            "[COLOR yellow]" + str(datestring) + "[/COLOR]  [COLOR orange](" + relative + ")[/COLOR]",
            "",
            art + "/link.png",
        )
        for showdata in data["episodes"]:
            if showdata["episode"]["season"] < 10:
                sea = "0" + str(showdata["episode"]["season"])
            else:
                sea = str(showdata["episode"]["season"])
            if showdata["episode"]["number"] < 10:
                epi = "0" + str(showdata["episode"]["number"])
            else:
                epi = str(showdata["episode"]["number"])
            episodenumber = "S" + sea + "E" + epi
            airtime = (
                showdata["show"]["air_time_localized"].upper().replace("AM", " AM").replace("PM", " PM")
                + " on "
                + showdata["show"]["network"]
            )
            main.addDir(
                showdata["show"]["title"].encode("utf-8")
                + " "
                + episodenumber
                + ' [COLOR red]"'
                + showdata["episode"]["title"].encode("utf-8")
                + '"[/COLOR] [COLOR blue]'
                + airtime.encode("utf-8")
                + "[/COLOR]",
                "TV",
                20,
                showdata["show"]["images"]["poster"].encode("utf-8"),
            )
            #            showdata['episode']['overview'].encode('utf-8'),showdata['episode']['images']['screen'].encode('utf-8'))
            showsdisplayed += 1
    if not showsdisplayed:
        main.removeFile(cached_path)