def get_tv_link(url,movie_title,thumb,media):
    hmf = urlresolver.HostedMediaFile(url)
    ##########################################
    if hmf:
        url = urlresolver.resolve(url)
    if not hmf:
        url = url
    try:
        params = {'url':url, 'name':media, 'thumb':thumb}
        addon.add_video_item(params, {'title':media}, img=thumb)
        liz=xbmcgui.ListItem(media, iconImage="DefaultFolder.png", thumbnailImage=thumb)
        xbmc.sleep(1000)
        liz.setPath(str(url))
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
        #xbmc.Player ().play(url, liz, False)
        movie_name = movie_title[:-6]
        movie_name = '"'+movie_name+'"'
        movie_year_full = movie_title[-6:]
        movie_year = movie_year_full.replace('(','').replace(')','')
        if kodi.get_setting('trakt_oauth_token'):
            xbmc.sleep(30000)
            log_utils.log("Velocity: TV Show Scrobble  Start")
            try:
                trakt_auth.start_tv_watch(movie_name,media)
            except Exception as e:
                    log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
                    if kodi.get_setting('error_notify') == "true":
                        kodi.notify(header='Scrobble not loggged', msg='%s  %s' % (str(e), ''), duration=5000, sound=None)
        xbmc.sleep(30000)
        if kodi.get_setting('trakt_oauth_token'):
            check_tv_player(movie_name,media)

    except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            kodi.notify(header='Try Another Source', msg='Link Removed or Failed', duration=4000, sound=None)
Beispiel #2
0
def auto_weekly_clean_on_off():
    if kodi.get_setting("clearday") == '7':
        if xbmcgui.Dialog().yesno(AddonName, 'Please confirm that you wish to enable weekly automated maintenance.'):
            kodi.set_setting("clearday", datetime.datetime.today().weekday())
            kodi.openSettings(addon_id, id1=5, id2=3)
            available_space, total_space = get_free_space_mb(xbmc.translatePath('special://home'))
            if str(available_space) == '0 B Free' and str(total_space) == '0 B Total':
                xbmcgui.Dialog().ok('Auto Maintenance Error',
                                    'Auto Maintenance encountered a problem and can not be run',
                                    'Maintenace can still be done individually')
                return
            mb_settings = (0, 25, 50, 75, 100)
            while True:
                allotted_space = 0
                for value in ('cachemb', 'thumbsmb', 'packagesmb'):
                    allotted_space += mb_settings[int(kodi.get_setting(value))] * 10**6
                if (allotted_space >= available_space) and not kodi.get_setting("automb"):
                    xbmcgui.Dialog().ok("Your settings sizes for Kodi to use are larger than the available drive space",
                                        'Please try lower settings, uninstall uneeded apps and addons,',
                                        'or set kodi size to "Auto" to use the automated settings based on free space')
                    kodi.openSettings(addon_id, id1=5, id2=3)
                else:
                    break
    else:
        if xbmcgui.Dialog().yesno(AddonName, 'Please confirm that you wish to disable weekly automated maintenance.'):
            kodi.set_setting("clearday", '7')
    xbmc.executebuiltin("Container.Refresh")
Beispiel #3
0
def menu():
	autoupdates.STARTUP()
	if  kodi.get_setting('trakt_authorized') =='true':
		kodi.addDir("Parent Approved Movies",'','custom_movie_lists',artwork+'movies.png','',1,'','',fanart=fanart)
		kodi.addDir("Parent Approved TV Shows",'','custom_tv_lists',artwork+'tvshows.png','',1,'','',fanart=fanart)
	if  kodi.get_setting('trakt_authorized') =='false':
		kodi.addDir("[COLOR gold]Requires Trakt Integration[/COLOR]",messages+'trakt_auth.txt','get_pin',artwork+'trakt.png','',1,'','',fanart=fanart,is_playable=False,is_folder=True)
	kodi.auto_view('menu')
def service_checks():
    import maintool
    maintool.source_change()
    date = datetime.datetime.today().weekday()
    if (kodi.get_setting("clearday") == date) or kodi.get_setting("acstartup") == "true":
        maintool.auto_clean(True)
    elif (kodi.get_setting("clearday") == 0) and kodi.get_setting("acstartup") != "true":
        kodi.log('Auto Main Turned off')
Beispiel #5
0
def auto_clean(auto_clear=False):
    if not auto_clear:
        if not xbmcgui.Dialog().yesno(AddonName, 'Selecting Yes runs maintenance based on your settings.',
                                      'Do you wish to continue?', yeslabel='Yes', nolabel='No'):
            return
    available_space, total_space = get_free_space_mb(xbmc.translatePath('special://home'))
    err_default = (0, '0 B', '0M', '0 MB', '0 MB Free', '0 MB Total', '0M Free', '0M Total')
    if str(available_space) in err_default or str(total_space) in err_default:
        if not auto_clear:
            if xbmcgui.Dialog().yesno('Auto Maintenance Error',
                                      'Auto Maintenance encountered a problem and was not ran',
                                      'Maintenace can still be done now or individually',
                                      'Would you like to just clear the cache, packages, and thumbnails',
                                      yeslabel='Yes', nolabel='No'):
                delete_cache(auto_clear=True)
                delete_packages(auto_clear=True)
                delete_thumbnails(auto_clear=True)
                delete_crash_logs(auto_clear=True)
                xbmc.executebuiltin("Container.Refresh")
                xbmcgui.Dialog().ok(AddonName, 'Auto Maintenance has been run successfully')
        return
    mb_settings = (0, 25, 50, 75, 100)
    for value in ('cachemb', 'thumbsmb', 'packagesmb'):
        available_space += mb_settings[int(kodi.get_setting(value))] * 10**6
    automb = kodi.get_setting("automb")
    cachemb = float((mb_settings[int(kodi.get_setting("cachemb"))]) * 10**6)  # 35%
    for path in (cache_path, temp_path):
        if os.path.exists(path):
            try:
                if (automb and (cachemb >= float(available_space) * .35)) or \
                        ((cachemb == 0 and kodi.get_setting("accache") == 'true')
                         or (cachemb != 0 and (get_size(cache_path) >= int(cachemb)))):
                    delete_cache(auto_clear=True)
            except Exception as e:
                kodi.log(str(e))
    thumbsmb = float((mb_settings[int(kodi.get_setting("thumbsmb"))]) * 10**6)  # 35%
    try:
        if (automb and (thumbsmb >= int(available_space) * .35)) or \
                ((thumbsmb == 0 and kodi.get_setting("acthumbs") == 'true')
                 or (thumbsmb != 0 and (get_size(thumbnail_path) >= int(thumbsmb)))):
            delete_thumbnails(auto_clear=True)
    except Exception as e:
        kodi.log(str(e))
    packagesmb = float((mb_settings[int(kodi.get_setting("packagesmb"))]) * 10**6)  # 10%
    try:
        if (automb and (packagesmb >= int(available_space) * .10)) or \
                ((packagesmb == 0 and kodi.get_setting("acpackages") == 'true')
                 or (packagesmb != 0 and (get_size(packages_path) >= int(packagesmb)))):
            delete_packages(auto_clear=True)
    except Exception as e:
        kodi.log(str(e))
    if kodi.get_setting("accrash") == 'true':
        delete_crash_logs(auto_clear=True)

    if not auto_clear:
        xbmc.executebuiltin("Container.Refresh")
        xbmcgui.Dialog().ok(AddonName, 'Auto Maintenance has been run successfully')
Beispiel #6
0
def _set_cookies(base_url, cookies):
        cj = cookielib.LWPCookieJar(cookie_file)
        try: cj.load(ignore_discard=True)
        except: pass
        if kodi.get_setting('debug') == 'true':
            log_utils.log('Before Cookies: %s' % (cookies_as_str(cj)), log_utils.LOGDEBUG)
        domain = urlparse.urlsplit(base_url).hostname
        for key in cookies:
            c = cookielib.Cookie(0, key, str(cookies[key]), port=None, port_specified=False, domain=domain, domain_specified=True,domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=False, comment=None,comment_url=None, rest={})
            cj.set_cookie(c)
        cj.save(ignore_discard=True)
        if kodi.get_setting('debug') == 'true':
            log_utils.log('After Cookies: %s' % (cookies_as_str(cj)), log_utils.LOGDEBUG)
        return cj
Beispiel #7
0
def tmlinkpage(url,movie_title,thumb,media):

    try:
        if  "full" in url:
                link = OPEN_URL(url)
                if 'Before you start watching' in link:
                                                #print 'Confirmation Button '
                                                url = url
                                                header_dict = {}
                                                header_dict['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
                                                header_dict['Connection'] = 'keep-alive'
                                                header_dict['Content-Type'] = 'application/x-www-form-urlencoded'
                                                header_dict['Origin'] = host_url
                                                header_dict['Referer'] = url
                                                header_dict['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'
                                                form_data = {'confirm':'I understand, Let me watch the movie now!'}
                                                net.set_cookies(cookiejar)
                                                conbutton = net.http_POST(url, form_data=form_data,headers=header_dict)

                link=OPEN_URL(url)
                link=link.replace('\r','').replace('\n','').replace('\t','').replace(' ','')
                matchurl=re.compile('Sourcelink:<arel="nofollow"onlicktarget="_blank">(.+?)</').findall(link)
                for urls in matchurl:
                    urls = str(urls)
                    urls = urls.replace('&rel=nofollow','')
                    if media =='movies':
                        main_scrape.get_link(urls,movie_title,thumb,media)
                    else:
                        main_scrape.get_tv_link(urls,movie_title,thumb,media)
    except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            if kodi.get_setting('error_notify') == "true":
                kodi.notify(header='TwoMovies',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
Beispiel #8
0
def tmovies_tv(name,movie_title):

    try:
        sources = []
        searchUrl = base_url+'watch_episode/'
        # if 'House' in movie_title:
        #     movie_title = movie_title.replace('House','DR House')
        movie_name = movie_title[:-6]
        movie_name_short = movie_title[:-7]
        movie_year = movie_title[-6:]
        movie_year = movie_year.replace('(','').replace(')','')
        movie_match =movie_name.replace(" ","_").replace(":","").replace("-","")
        year_movie_match = movie_match+movie_year
        direct_movie_match = movie_match[:-1]
        seasons=re.compile('S(.+?)E(.+?) ').findall(name)
        for sea,epi in seasons:
            tmurl = searchUrl+direct_movie_match+'/'+sea+'/'+epi+'/'
            link = OPEN_URLTM(tmurl)
            names = dom_parser.parse_dom(link, 'a',{'class':"norm vlink"})
            urls = dom_parser.parse_dom(link, 'a',{'class':"norm vlink"}, ret='href')
            for host, url in zip(names, urls):
                host = host.replace('www.','')
                #host = tools.get_hostname(host)
                source = {'url': url, 'host':host,'direct':False}
                sources.append(source)
            sources = main_scrape.apply_urlresolver(sources)
            return sources
    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='TwoMovies',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
def scriptblock_checks():
    if kodi.get_setting('scriptblock') == 'true':
        kodi.log('SCRIPT BLOCKER ON')
        try:
            req = urllib2.Request(BlocksUrl)
            req.add_header('User-Agent', 'Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30')
            response = urllib2.urlopen(req)
        except:
            kodi.log('Could not perform blocked script check. invalid URL')
            return
        link = response.read()
        response.close()
        link = link.replace('\n', '').replace('\r', '').replace('\a', '')

        match = re.compile('block="(.+?)"').findall(link)
        for blocked in match:
            kodi.log('Checking for Malicious scripts')

            addonPath = xbmcaddon.Addon(id=addon_id).getAddonInfo('path')
            addonPath = xbmc.translatePath(addonPath)
            xbmcPath = os.path.join(addonPath, "..", "..")
            xbmcPath = os.path.abspath(xbmcPath);

            addonpath = xbmcPath + '/addons/'
            try:
                for root, dirs, files in os.walk(addonpath, topdown=False):
                    if root != addonpath:
                        if blocked in root:
                            shutil.rmtree(root)
            except:
                kodi.log('Could not find blocked script')
Beispiel #10
0
def add_to_queue(name,url,thumb,ext,media):
    try:
        try:
            conn.execute('''CREATE TABLE downloads(name text unique, url text, thumb text, ext text, media text)''')
        except:
            print "Velocity says: Downloads DB Table Already exists"

        # Insert a row of data or return already there
        try:
            #Quote Replacement
            name = name.replace("'", "''")
            media = media.replace("'", "''")
            #END Quote Replacement

            conn.execute("INSERT INTO downloads VALUES ('"+name+"','"+url+"','"+thumb+"','"+ext+"','"+media+"')")
            addon.show_small_popup(title='[COLOR gold]Item Added To Your Queue [/COLOR]', msg=name + ' Was Added To Your Download Queue', delay=int(5000), image=thumb)
        except Exception as e:
            addon.show_small_popup(title='[COLOR red]Item Already In Your Queue[/COLOR]', msg=name + ' Is Already In Your Download Queue', delay=int(5000), image=thumb)
            print 'Error [%s]  %s' % (str(e), '')
        # Save (commit) the changes
        conn.commit()
        # We can also close the connection if we are done with it.
        # Just be sure any changes have been committed or they will be lost.
        conn.close()
    except Exception as e:
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='Downloads',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
Beispiel #11
0
def afdah(name):
    try:
        title = name[:-7]
        movie_year = name[-6:]
        year = movie_year.replace('(','').replace(')','')
        video_type = 'movies'
        search_url = urlparse.urljoin(base_url, '/wp-content/themes/afdah/ajax-search.php')
        data = {'search': title, 'type': 'title'}
        html = OPEN_URL(search_url, data=data, cache_limit=1)
        pattern = '<li>.*?href="([^"]+)">([^<]+)\s+\((\d{4})\)'
        results = []
        for match in re.finditer(pattern, html, re.DOTALL | re.I):
            url, title, match_year = match.groups('')
            if not year or not match_year or year == match_year:
                result = {'url': _pathify_url(url), 'title': title, 'year': year}
                results.append(result)
        for e in results:

            url = e['url']
            year = e['year']
            name = e['title']
            # print year
            # print name
            # print url
            # srcurl = base_url+url
            # link = OPEN_URL_REG(srcurl)
            hosters=get_sources(url)
            # print hosters
            return hosters
    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='Afdah',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
Beispiel #12
0
def custom_list_view_tv(trakt_id,media):
	try:
		lists = trakt_api.get_special_list('kids',media)#is actually SLUG ID
		for e in lists:
			infoLabels = trakt_api.process_movie(e)
			infoLabels.update(make_infoLabels(e))
			menu_items=[]
			trakt_id = str(infoLabels['trakt_id'])
			trailer = infoLabels['trailer_url']
			year = str(infoLabels['year'])
			name = infoLabels['title'].encode('utf-8')
			thumb=infoLabels['cover_url']
			if thumb is None:
				thumb = ''
			menu_items.append(('[COLOR gold]Show Information[/COLOR]', 'XBMC.Action(Info)'))
			if trailer:
				utube = tools.make_trailer(trailer)
				menu_items.append(('[COLOR gold]Play Trailer[/COLOR]', 'PlayMedia('+utube+',xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image))'))


			kodi.addDir(name+' ('+year+')','','find_season',thumb,name,5,trakt_id,'shows',meta_data=infoLabels,menu_items=menu_items,replace_menu=False)
			kodi.auto_view('tvshows')
	except Exception as e:
		log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
		if kodi.get_setting('error_notify') == "true":
			kodi.notify(header='Custom List Error',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
Beispiel #13
0
def ice_films_tv(name,movie_title):
    try:
        title = movie_title[:-7]
        movie_year = movie_title[-6:]
        year = movie_year.replace('(','').replace(')','')
        video_type = 'shows'
        # print title
        # print year

        show_url = search(video_type,title,year)
        for e in show_url:
                url = e['url']
                #TV MAIN URL RETURNED HERE
                newseas=re.compile('S(.+?)E(.+?)  (?P<name>[A-Za-z\t .]+)').findall(name)
                for sea,epi,epi_title in newseas:
                    # print sea,epi
                    # print url
                    video = make_vid_params('Episode',title,year,sea,epi,epi_title,'')
                    #print video
                    ep_url = _get_episode_url(url, video,sea,epi)
                    #print "HERE IS END" +ep_url
                    hosters=get_sources(ep_url)

                    hosters = main_scrape.apply_urlresolver(hosters)
                    return hosters

    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='Ice Films',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
Beispiel #14
0
def primewire(name):
    try:
            sources = []
            searchUrl = base_url+'index.php?search_keywords='
            movie_name = name[:-6]
            movie_name_short = name[:-7]
            movie_year_full = name[-6:]
            movie_year = movie_year_full.replace('(','').replace(')','')
            sname = movie_name.replace(" ","+")
            primename = sname[:-1]
            movie_match =movie_name.replace(" ","_")+movie_year
            surl = searchUrl + primename
            link = OPEN_URL(surl)
            full_match  = movie_name+movie_year_full
            match=re.compile('<a href="/(.+?)" title="Watch (.+?)">').findall(link)
            for url, name in match:
                if full_match == name:
                    link = OPEN_URL(base_url+url)
                    container_pattern = r'<table[^>]+class="movie_version[ "][^>]*>(.*?)</table>'
                    item_pattern = (
                        r'quality_(?!sponsored|unknown)([^>]*)></span>.*?'
                        r'url=([^&]+)&(?:amp;)?domain=([^&]+)&(?:amp;)?(.*?)'
                        r'"version_veiws"> ([\d]+) views</')
                    max_index = 0
                    max_views = -1
                    for container in re.finditer(container_pattern, link, re.DOTALL | re.IGNORECASE):
                        for i, source in enumerate(re.finditer(item_pattern, container.group(1), re.DOTALL)):
                            qual, url, host, parts, views = source.groups()
                            if kodi.get_setting('debug') == "true":
                                print"PrimeWire Debug:"
                                print "Quality is " + qual
                                print "URL IS " + url.decode('base-64')
                                print "HOST IS  "+host.decode('base-64')
                                print "VIEWS ARE " +views
                            if host == 'ZnJhbWVndGZv': continue  # filter out promo hosts
                            #host = tools.get_hostname(host.decode('base-64'))
                            source = {'hostname':'PrimeWire','url': url.decode('base-64'), 'host': host.decode('base-64'),'views':views,'quality':qual,'direct':False}
                            sources.append(source)
            #print "MOVIE SOURCES ARE = "+str(sources)
            sources = main_scrape.apply_urlresolver(sources)
            return sources
    except Exception as e:
        sources =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='PrimeWire',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return sources
Beispiel #15
0
def __fix_bad_cookies():
    c = cj._cookies
    for domain in c:
        for path in c[domain]:
            for key in c[domain][path]:
                cookie = c[domain][path][key]
                if cookie.expires > sys.maxint:
                    if kodi.get_setting('debug') == "true":
                        kodi.notify(header='Cookie Fix', msg='Fixing cookie expiration for %s: was: %s now: %s' % (key, cookie.expires, sys.maxint), duration=5000, sound=None)
                        log_utils.log('Fixing cookie expiration for %s: was: %s now: %s' % (key, cookie.expires, sys.maxint), xbmc.LOGERROR)
                    cookie.expires = sys.maxint
Beispiel #16
0
def download_now(name, url, thumb, ext, media):
    print name
    print url
    print thumb
    print ext
    print media
    download_path = kodi.get_setting('download_folder')
    if download_path == '':
      addon.show_small_popup(title='File Not Downloadable', msg='You need to set your download folder in addon settings first', delay=int(5000), image='')
    else:
        dlThread = downloadThread(name, url, thumb, media, ext)
        dlThread.start()
Beispiel #17
0
def make_infoLabels(item, show=None, people=None):
	try:
			item = item['movie']
	except:
		try:
			item = item['show']
		except:
			item = item
	if kodi.get_setting('debug') == "true":
		print "ITEM IS : = "+str(item)
	if people is None: people = {}
	if show is None: show = {}
	infoLabels = {}
	if 'title' in item: infoLabels['title'] = item['title']
	if 'overview' in item: infoLabels['plot'] = infoLabels['plotoutline'] = item['overview']
	if 'runtime' in item and item['runtime'] is not None: infoLabels['duration'] = item['runtime'] * 60
	if 'certification' in item: infoLabels['mpaa'] = item['certification']
	if 'year' in item: infoLabels['year'] = item['year']
	if 'season' in item: infoLabels['season'] = item['season']  # needs check
	if 'episode' in item: infoLabels['episode'] = item['episode']  # needs check
	if 'number' in item: infoLabels['episode'] = item['number']  # needs check
	if 'network' in item: infoLabels['studio'] = item['network']
	if 'status' in item: infoLabels['status'] = item['status']
	if 'tagline' in item: infoLabels['tagline'] = item['tagline']
	if 'watched' in item and item['watched']: infoLabels['playcount'] = 1
	if 'plays' in item and item['plays']: infoLabels['playcount'] = item['plays']
	if 'rating' in item: infoLabels['rating'] = item['rating']
	if 'votes' in item: infoLabels['votes'] = item['votes']
	if 'released' in item: infoLabels['premiered'] = item['released']
	if 'trailer' in item and item['trailer']: infoLabels['trailer'] = tools.make_trailer(item['trailer'])
	if 'trailer' in item and item['trailer']:
		infoLabels['trailer_url'] = item['trailer']
	else: infoLabels['trailer_url'] = False
	if 'first_aired' in item: infoLabels['aired'] = infoLabels['premiered'] = make_air_date(item['first_aired'])
	infoLabels.update(make_ids(item))
	infoLabels.update(make_art(item))
	if 'genres' in item:
		infoLabels.update(make_genre(item))
	if 'aired_episodes' in item:
		infoLabels['episode'] = infoLabels['TotalEpisodes'] = item['aired_episodes']
		infoLabels['WatchedEpisodes'] = item['watched_count'] if 'watched_count' in item else 0
		infoLabels['UnWatchedEpisodes'] = infoLabels['TotalEpisodes'] - infoLabels['WatchedEpisodes']
	# override item params with show infoLabels if it exists
	if 'certification' in show: infoLabels['mpaa'] = show['certification']
	if 'year' in show: infoLabels['year'] = show['year']
	if 'runtime' in show and show['runtime'] is not None: infoLabels['duration'] = show['runtime'] * 60
	if 'title' in show: infoLabels['tvshowtitle'] = show['title']
	if 'network' in show: infoLabels['studio'] = show['network']
	if 'status' in show: infoLabels['status'] = show['status']
	if 'trailer' in show and show['trailer']: infoLabels['trailer'] = tools.make_trailer(show['trailer'])
	infoLabels.update(make_ids(show))
	# infoLabels.update(make_people(people))
	return infoLabels
Beispiel #18
0
def toggle_setting(setting_title, setting, restart=False, silent=False):
    # kodi.log('TOGGLE SETTING')
    if not silent:
        if kodi.get_setting(setting) == "true":
            status_on_off = 'OFF'
        else:
            status_on_off = 'ON'
        if not xbmcgui.Dialog().yesno(setting_title,
                                      'Please confirm that you wish to TURN %s %s' % (status_on_off, setting_title),
                                      '', '', 'Cancel', 'Confirm'):
                return
    if kodi.get_setting(setting) == 'true':
        kodi.set_setting(setting, 'false')
    else:
        kodi.set_setting(setting, 'true')
    kodi.log('Toggled setting for ' + setting_title)
    if not silent and not restart:
        xbmcgui.Dialog().notification('', 'Setting Changed!', sound=False)
        xbmc.executebuiltin("Container.Refresh")
    if restart:
        xbmcgui.Dialog().notification('', 'Kodi is shutting down for changes to take effect', sound=False)
        xbmc.executebuiltin('ShutDown')
Beispiel #19
0
def __get_links_from_xml(xml, video):
    sources = {}
    try:
        root = ET.fromstring(xml)
        for item in root.findall('.//item'):
            title = item.find('title').text
            for source in item.findall('{http://rss.jwpcdn.com/}source'):
                stream_url = source.get('file')
                label = source.get('label')
                if _get_direct_hostname(stream_url) == 'gvideo':
                    quality = _gv_get_quality(stream_url)
                elif label:
                    quality = _height_get_quality(label)
                else:
                    quality = _blog_get_quality(video, title, '')
                sources[stream_url] = {'quality': quality, 'direct': True}
                if kodi.get_setting('debug') == "true":
                        kodi.notify(header='ERROR', msg='Adding stream: %s Quality: %s' % (stream_url, quality), duration=5000, sound=None)
    except Exception as e:
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='ERROR', msg='%s  %s' % (str(e), ''), duration=5000, sound=None)

    return sources
Beispiel #20
0
def OPEN_URL(url):

  try:
      req=urllib2.Request(url)
      req.add_header('User-Agent', 'Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30')
      response=urllib2.urlopen(req)
      link=response.read()
      cj.save(cookie_file, ignore_discard=True)
      response.close()
      return link
  except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            if kodi.get_setting('error_notify') == "true":
                kodi.notify(header='TwoMovies',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
Beispiel #21
0
def auto_clean(auto_clear=False):
    if not auto_clear:
        if not xbmcgui.Dialog().yesno(AddonName, 'Selecting Yes runs maintenance based on your settings.',
                                      'Do you wish to continue?', yeslabel='Yes', nolabel='No'):
            return
    available_space, total_space = get_free_space_mb(xbmc.translatePath('special://home'))
    mb_settings = (0, 25, 50, 75, 100)
    for value in ('cachemb', 'thumbsmb', 'packagesmb'):
        available_space += mb_settings[int(kodi.get_setting(value))] * 10 ** 6
    automb = kodi.get_setting("automb")
    cachemb = float((mb_settings[int(kodi.get_setting("cachemb"))]) * 10 ** 6)  # 35%
    for path in (cache_path, temp_path):
        if os.path.exists(path):
            try:
                if (automb and (cachemb >= float(available_space) * .35)) or \
                        ((cachemb == 0 and kodi.get_setting("accache") == 'true')
                         or (cachemb != 0 and (get_size(cache_path) >= int(cachemb)))):
                    delete_cache(auto_clear=True)
            except:
                pass
    thumbsmb = float((mb_settings[int(kodi.get_setting("thumbsmb"))]) * 10 ** 6)  # 35%
    try:
        if (automb and (thumbsmb >= int(available_space) * .35)) or \
                ((thumbsmb == 0 and kodi.get_setting("acthumbs") == 'true')
                 or (thumbsmb != 0 and (get_size(thumbnail_path) >= int(thumbsmb)))):
            delete_thumbnails(auto_clear=True)
    except:
        pass
    packagesmb = float((mb_settings[int(kodi.get_setting("packagesmb"))]) * 10 ** 6)  # 10%
    try:
        if (automb and (packagesmb >= int(available_space) * .10)) or \
                ((packagesmb == 0 and kodi.get_setting("acpackages") == 'true')
                 or (packagesmb != 0 and (get_size(packages_path) >= int(packagesmb)))):
            delete_packages(auto_clear=True)
    except:
        pass
    if kodi.get_setting("accrash") == 'true':
        delete_crash_logs(auto_clear=True)
    if not auto_clear:
        xbmc.executebuiltin("Container.Refresh")
        xbmcgui.Dialog().ok(AddonName, 'Auto Maintenance has been run successfully')
def show_about():
	interval = int(kodi.get_setting('last_about'))
	if interval == 0:
		interval = 5
		try:
			import xbmc
			KODI_LANGUAGE = xbmc.getLanguage()
		except:
			KODI_LANGUAGE = 'English'
		path = kodi.vfs.join(kodi.get_path(), 'resources/language/%s/github_help.txt', KODI_LANGUAGE)
		if not kodi.vfs.exists(path):
			path = kodi.vfs.join(kodi.get_path(), 'resources/language/English/github_help.txt')
		text = kodi.vfs.read_file(path)
		kodi.dialog_textbox('GitHub Browser Instructions', text)
	else:
		interval -= 1	
	kodi.set_setting('last_about', interval)
Beispiel #23
0
def zmovies(name):
    try:
        sources = []
        movie_name = name[:-6]
        movie_name_short = name[:-7]
        movie_year = name[-6:]
        movie_year = movie_year.replace('(','').replace(')','')
        sname = movie_name.replace(" ","+")
        movie_match =movie_name.replace(" ","-").replace(":","")
        year_movie_match = movie_match+movie_year
        direct_movie_match = movie_match[:-1]
        tmurl = base_url+'movies/view/'+direct_movie_match
        ytmurl = base_url+'movies/view/'+year_movie_match
        #dp.update(25)
        #For links that are direct
        link = OPEN_URL(tmurl)
        match=re.compile('target="_blank"   href="(.+?)"> <b> Watch Full </b></a> </td>').findall(link)
        for url in match:
            hmf = urlresolver.HostedMediaFile(url)
            if hmf:

            #linkname= hmf.get_host()
                linkname = tools.get_hostname(url)
                host = linkname
                #source = {'hostname':'IceFilms','multi-part': False, 'quality': quality, 'label': label, 'rating': None, 'views': None, 'direct': False}
                source = {'hostname':'ZMovies','views':None, 'quality': None, 'rating': None,'url': url, 'host': host, 'direct':False}
                sources.append(source)
        #Fro Links that need year added
        link = OPEN_URL(ytmurl)
        #dp.update(80)
        match=re.compile('target="_blank"   href="(.+?)"> <b> Watch Full </b></a> </td>').findall(link)
        for url in match:
            linkname = tools.get_hostname(url)
            host = linkname
            source = {'hostname':'ZMovies','views':None, 'quality': None, 'rating': None,'url': url, 'host': host, 'direct':False}
            sources.append(source)
        #dp.close()
        sources = main_scrape.apply_urlresolver(sources)
        print sources
        return sources
    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='Zee Moviess',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
Beispiel #24
0
def find_episode(name,trakt_id,movie_title):

	try:
		media ='episode'
		season = name.replace('Season ','')
		#print "SHOW TRAKT IS : "+trakt_id
		link = trakt_api.get_show_episodes(trakt_id,season)
		for e in link:
			ep_trakt_id= e['ids']['trakt']
			#print "Episode TRAKT ID IS  : "+str(ep_trakt_id)
			infoLabels={}
			infoLabels.update(make_infoLabels(e))
			episode = infoLabels['episode']
			infoLabels = trakt_api.get_episode_details(trakt_id,season,episode)
			menu_items=[]
			trailer = infoLabels['trailer_url']
			year = str(infoLabels['year'])
			name = infoLabels['title'].encode('utf-8')
			thumb=infoLabels['cover_url']
			# ################
			was_watched=watched_cache.get_watched_cache(ep_trakt_id)
			if was_watched is not None:
				infoLabels['playcount'] = 1
			# ################
			if thumb is None:
				thumb = ''
			#print infoLabels['premiered'][:10]
			#if (episode['first_aired'] != None and utils2.iso_2_utc(episode['first_aired']) <= time.time()) or (include_unknown and episode['first_aired'] == None):
			d1 = str(infoLabels['premiered'])
			d2 = str(datetime.date.today())
			#print today - was_aired
			#if infoLabels['premiered'] =='':
			if d1 >= d2 or infoLabels['premiered'] == '':
				if name is not '':
					menu_items.append(('[COLOR gold]Show Information[/COLOR]', 'XBMC.Action(Info)'))
					kodi.addDir('[COLOR maroon]S'+str(season)+'E'+str(episode)+'  '+name+'[/COLOR]','','findsource',thumb,movie_title,5,'','shows',meta_data=infoLabels,menu_items=menu_items,replace_menu=True)
					#name = name+" [COLOR red]Coming Soon[/COLOR]"
			else:
				menu_items.append(('[COLOR gold]Show Information[/COLOR]', 'XBMC.Action(Info)'))
				kodi.addDir('S'+str(season)+'E'+str(episode)+'  '+name,'','findsource',thumb,movie_title,5,'','shows',meta_data=infoLabels,menu_items=menu_items,replace_menu=True)
			kodi.auto_view('episode')
	except Exception as e:
		log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
		if kodi.get_setting('error_notify') == "true":
			kodi.notify(header='Trakt Episodes',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
def putlocker_movies(movie_title):
    try:
        title = movie_title[:-7]
        movie_year = movie_title[-6:]
        year = movie_year.replace('(','').replace(')','')
        video_type = 'movies'
        show_url = search(video_type,title,year)
        for e in show_url:
                url = e['url']
                hosters=get_sources(url)
                print "HOSTERS ARE " + str(hosters)
                hosters = main_scrape.apply_urlresolver(hosters)
                return hosters
    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='Putlocker Movies',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
Beispiel #26
0
def OPEN_URLTM(url):

        try:
            req=urllib2.Request(url)
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36')
            req.add_header('Content-Type','application/x-www-form-urlencoded')
            req.add_header('Host',host_url)
            req.add_header('Referer','')
            req.add_header('Connection','keep-alive')
            req.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
            response=urllib2.urlopen(req)
            link=response.read()
            cj.save(cookie_file, ignore_discard=True)
            response.close()
            return link
        except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            if kodi.get_setting('error_notify') == "true":
                kodi.notify(header='TwoMovies',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
Beispiel #27
0
def primewire_tv(name,movie_title):
    #print "SEARCHING TITLE IS =" +movie_title
    #print "EPISODE REAL NAME IS = "+name
    tvso = []
    seasons=re.compile('S(.+?)E(.+?) ').findall(name)
    for sea,epi in seasons:


        movie_name = movie_title[:-7]
        tv_title=movie_name.replace(' ','+')
        #print "TV REAL TITLE IS = "+tv_title
        searchUrl = 'http://www.primewire.ag/index.php?search_keywords='
        surl = searchUrl + tv_title            ###########CHANGE THIS
        #print "SEARCH URL PRIME IS + " +surl
        link = OPEN_URL(surl+'&search_section=2')
        match=re.compile('<a href="/(.+?)" title="Watch (.+?)">').findall(link)
        for url, name in match:
            if movie_title == name:
                url = url.replace('watch','tv').replace('-online-free','')
                link = OPEN_URL(base_url+url+'/season-'+sea+'-episode-'+epi)
                container_pattern = r'<table[^>]+class="movie_version[ "][^>]*>(.*?)</table>'
                item_pattern = (
                    r'quality_(?!sponsored|unknown)([^>]*)></span>.*?'
                    r'url=([^&]+)&(?:amp;)?domain=([^&]+)&(?:amp;)?(.*?)'
                    r'"version_veiws"> ([\d]+) views</')
                max_index = 0
                max_views = -1
                for container in re.finditer(container_pattern, link, re.DOTALL | re.IGNORECASE):
                    for i, source in enumerate(re.finditer(item_pattern, container.group(1), re.DOTALL)):
                        qual, url, host, parts, views = source.groups()
                        if kodi.get_setting('debug') == "true":
                            print"PrimeWire Debug:"
                            print "Quality is " + qual
                            print "URL IS " + url.decode('base-64')
                            print "HOST IS  "+host.decode('base-64')
                            print "VIEWS ARE " +views
                        if host == 'ZnJhbWVndGZv': continue  # filter out promo hosts
                        #host = tools.get_hostname(host.decode('base-64'))
                        source = {'url': url.decode('base-64'), 'host':host.decode('base-64'),'view':views,'quality':qual,'direct':False}
                        tvso.append(source)
        tvso = main_scrape.apply_urlresolver(tvso)
        return tvso
Beispiel #28
0
def ot3_movies(name):
    try:
        title = name[:-7]
        movie_year = name[-6:]
        year = movie_year.replace('(','').replace(')','')
        video_type = 'movies'
        source = search(video_type,title,year)
        for e in source:
                url = e['url']
                year = e['year']
                name = e['title']
                srcurl =base_url+url
                hosters=get_sources(srcurl,url)
                hosters = main_scrape.apply_urlresolver(hosters)
                return hosters
    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='123Movies',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
Beispiel #29
0
def toggle_notify():
    if kodi.get_setting('notifications-on-startup') == "false":
        option = 'OPT-out'
        sub = 'Un'
        status = 'Disabled'
    else:
        option = 'OPT-in'
        sub = ''
        status = 'Enabled'
    confirm = xbmcgui.Dialog()
    if confirm.yesno('Community Notifications',  "Please confirm that you wish to " + option + " of community notifications! ", " "):
        if status == 'Enabled':
            kodi.set_setting('notifications-on-startup', "false")
        else:
            kodi.set_setting('notifications-on-startup', "true")
        kodi.logInfo(status + "notifications")
        dialog = xbmcgui.Dialog()
        dialog.ok("Notifications " + status, "                     You have " + sub + "subscribed to notifications!")
        xbmc.executebuiltin("Container.Refresh()")
    else:
        return
Beispiel #30
0
def merdb(name):
    try:
        sources = []
        searchUrl = base_url+'?search='
        movie_name = name[:-6]
        movie_name_short = name[:-7]
        movie_year = name[-6:]
        movie_year = movie_year.replace('(','').replace(')','')
        sname = movie_name.replace(" ","+")
        mername = sname[:-1]
        movie_match =movie_name.replace(" ","_")+movie_year
        surl = searchUrl + mername
        link = OPEN_URL(surl)
        #dp.update(80)
        match=re.compile('<div class="main_list_box"><a href="(.+?)" title="(.+?)"><img').findall(link)
        for url, name in match:
            if movie_match in url or movie_name_short == name:
                link = OPEN_URL(base_url+url)
                vidlinks=dom_parser.parse_dom(link, 'span',{'class':"movie_version_link"})
                linknames=dom_parser.parse_dom(link, 'span',{'class':"version_host"})
                for name, vidlink in zip(linknames, vidlinks):
                    #dp.update(80)
                    match=re.compile('<a href="(.+?)"').findall(vidlink)
                    for linkurl in match:
                        if "ads.php" not in linkurl and "Sponsor" not in name and "Host" not in name:
                            url = base_url+linkurl
                            #print "URLS IS = " +url
                            host = name.replace("'","")
                            #linkname = tools.get_hostname(name)
                            source = {'hostname':'MerDB','views':None,'url': url, 'host': host, 'direct':False}
                            sources.append(source)
        #dp.close()
        sources = main_scrape.apply_urlresolver(sources)
        return sources
    except Exception as e:
        hosters =[]
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='MerDb',msg='(error) %s  %s' % (str(e), ''),duration=5000,sound=None)
        return hosters
Beispiel #31
0
def main():
    dp = xbmcgui.DialogProgress()
    dp.create('KBuilds Installer', 'Checking for update...', '',
              'Please wait...')
    dp.update(100)

    # Get Current Version
    update_file = xbmc.translatePath(os.path.join('special://',
                                                  'home')) + 'update.zip'

    current = json.loads('{"config_version": "00000000"}')
    path = xbmc.translatePath(os.path.join('special://', 'userdata'))
    version_file = path + 'version.json'
    try:
        current = json.load(open(version_file))
    except:
        pass

    # Get Remote Settings
    try:
        # Prompt for Device ID if it is not set
        # if not kodi.get_setting('deviceid'):
        #     kb = xbmc.Keyboard('default', 'heading')
        #     kb.setHeading('Enter your name or something so I know who you are \r\nand will allow you access to updates')
        #     kb.setDefault('')
        #     kb.setHiddenInput(False)
        #     kb.doModal()
        #     if (kb.isConfirmed()):
        #         kb_input = kb.getText()
        #         if (len(kb_input) > 3):
        #             kodi.set_setting('deviceid', kb_input)
        #             kodi.notify('Device ID set!', '['+kb_input+']')
        #         else:
        #             kodi.notify('Access denied!', 'Device ID not set.')
        #             return
        #     else:
        #         kodi.notify('Access denied!', 'Device ID not set.')
        #         return

        # Prompt for Configuration Update
        # if kodi.get_setting('update_test') != 'true':
        #     current_version = current['config_version']
        # else:
        #     current_version = current['test_version']
        current_version = current['config_version']
        # params = {
        #             'd': kodi.getInfoLabel('Network.MacAddress'),
        #             'os': kodi.getInfoLabel('System.OSVersionInfo'),
        #             'id': kodi.get_setting('deviceid'),
        #             'kv': kodi.get_version()
        #         }

        # params['cv'] = current_version

        kodi.log('Config URL: ' + kodi.get_setting('update_url'))
        response = requests.get(kodi.get_setting('update_url'))
        remote = json.loads(response.text)
        if kodi.platform() == 'raspberry':
            kodi.log('Detected Platform = Raspberry Pi')
            remote_version = remote.get('raspberry')['config_version']
            url = remote.get('raspberry')['config_url']
            hash = remote.get('raspberry')['config_md5']
        else:
            kodi.log('Detected Platform = Other; Using Windows Config')
            remote_version = remote.get('windows')['config_version']
            url = remote.get('windows')['config_url']
            hash = remote.get('windows')['config_md5']

        #kodi.log(json.dumps(remote))
        dp.close()

        # if kodi.get_setting('update_test') != 'true':
        #     remote_version = remote['config_version']
        #     url = remote['config_url']
        #     hash = remote['config_md5']
        # else:
        #     remote_version = remote['test_version']
        #     url = remote['test_url']
        #     hash = remote['test_md5']

        # remote_version = remote['config_version']
        # url = remote['config_url']
        # hash = remote['config_md5']

        # Prompt for Kodi Update
        # if kodi.get_setting('update_kodi') == 'true':
        #     if kodi.platform() == 'android' and remote['kodi_version'] != kodi.get_version():
        #         choice = xbmcgui.Dialog().yesno('KBuilds Installer',
        #                                         'A new version of Kodi is available!',
        #                                         'Current version is [B]'+kodi.get_version()+'[/B].[CR]',
        #                                         'Would you like to install version [B]'+remote['kodi_version'] +'[/B]?')
        #         if choice == 1:
        #             installer.installAPK(remote['kodi_url'])

        kodi.log('Update File: ' + update_file)
        if os.path.exists(update_file):
            url = '/update.zip'
            hash = ''
            choice = xbmcgui.Dialog().yesno(
                'KBuilds Installer', 'An update file exists!', '',
                'Would you like to install this update?')
        else:
            if remote_version != current_version:
                choice = xbmcgui.Dialog().yesno(
                    'KBuilds Installer', 'A new configuration is available!',
                    'Current version is [B]' + current_version + '[/B].[CR]',
                    'Would you like to install version [COLOR green][B]' +
                    remote_version + '[/B][/COLOR]?')
            else:
                choice = xbmcgui.Dialog().yesno(
                    'KBuilds Installer',
                    'Current version is [B]' + current_version + '[/B].[CR]',
                    'Would you like to reinstall version [B]' +
                    remote_version + '[/B]?')

        if choice == 1:
            # Give service enough time to stop downloading
            time.sleep(3)

            if installer.installConfig(url, hash):

                # Save Installed Version to file
                with open(version_file, "w") as outfile:
                    json.dump(remote, outfile)

                choice = xbmcgui.Dialog().yesno(
                    'KBuilds Installer',
                    'A restart is required. Would you like to restart Kodi now?'
                )
                if choice == 1:
                    kodi.kill()

                xbmcgui.Dialog().ok('KBuilds Installer',
                                    'Update checks complete!')
            else:

                xbmcgui.Dialog().ok('KBuilds Installer', 'Update cancelled!')

    except Exception, e:
        kodi.log(str(e))
Beispiel #32
0
db_path = os.path.join(db_dir, 'Velocity_dl.db')

if not xbmcvfs.exists(os.path.dirname(db_path)):
    try: xbmcvfs.mkdirs(os.path.dirname(db_path))
    except: os.mkdir(os.path.dirname(db_path))

conn =db_lib.connect(db_path)

ADDON = xbmcaddon.Addon(id=kodi.addon_id)
addon_id=kodi.addon_id
addon = Addon(addon_id, sys.argv)


artwork = xbmc.translatePath(os.path.join('special://home','addons',addon_id,'resources','art/'))
fanart = artwork+'fanart.jpg'
download_path = kodi.get_setting('download_folder')



#========================Alternate Param Stuff=======================
mode = addon.queries['mode']
url = addon.queries.get('url', '')
name = addon.queries.get('name', '')
thumb = addon.queries.get('thumb', '')
ext = addon.queries.get('ext', '')
dlfoldername = addon.queries.get('dlfoldername', '')
favtype = addon.queries.get('favtype', '')
mainimg = addon.queries.get('mainimg', '')
headers = addon.queries.get('headers', '')
loggedin = addon.queries.get('loggedin', '')
season = addon.queries.get('season', '')
Beispiel #33
0
def find_source(name, thumb, media, movie_title):

    if media == 'shows':
        find_sourceTV(name, thumb, media, movie_title)
    else:
        try:
            if thumb is None:
                thumb = ''
            else:
                thumb = thumb

            title = name[:-7]
            movie_year = name[-6:]
            year = movie_year.replace('(', '').replace(')', '')
            video_type = 'movies'
            total_items = 0

            t1 = Thread(target=go_ice, args=(video_type, title, year))
            #############PRIMEWIRE########################
            t2 = Thread(target=go_prime, args=(video_type, title, year))
            ##############IWATCH COMPLETE####################
            t3 = Thread(target=go_iwatch, args=(video_type, title, year))
            #############AFDAH COMPLETE##################
            t4 = Thread(target=go_afdah, args=(video_type, title, year))
            ############PUTLOCKER COMPLETE##################
            t5 = Thread(target=go_putlocker, args=(video_type, title, year))

            t1.start()
            t2.start()
            t3.start()
            t4.start()
            t5.start()

            t1.join()
            t2.join()
            t3.join()
            t4.join()
            t5.join()

            for a in all_source:
                if a:
                    b = sorted(a, reverse=False)
                    try:
                        for e in b:
                            #total_items =len(e)
                            #kodi.log(total_items)
                            if 'debrid' in e:
                                premium = " [COLOR gold]" + str(
                                    e['debrid']) + " [/COLOR]"
                            else:
                                premium = ''
                            hostname = e['hostname']
                            provider = "[COLOR white][" + hostname + "][/COLOR] - "
                            names = e['host']
                            urls = e['url']
                            if e['views'] == None:
                                views = ''
                            else:
                                views = " [COLOR green]Views " + e[
                                    'views'] + "[/COLOR]"
                            if e['quality'] == None:
                                quals = ''
                            else:
                                quals = " [COLOR red][" + e[
                                    'quality'] + "][/COLOR]"
                            menu_items = []
                            menu_items.append(
                                ('[COLOR gold]Add to Downloads[/COLOR]',
                                 'XBMC.Container.Update(%s)' %
                                 addon.build_plugin_url(
                                     {
                                         'mode': 'setup_download',
                                         'name': name,
                                         'url': urls,
                                         'thumb': thumb,
                                         'media': media,
                                         'movie_title': movie_title
                                     })))

                            #TODO Make Dialog Selections
                            # passname = []
                            # pro_list = {'proname': provider + names + quals + views + premium, 'url': urls,'movie_title':movie_title,'thumb':thumb,'media':media }
                            #
                            # passname.append(pro_list)
                            # pick_list(passname)

                            kodi.addDir(provider + names + quals + views +
                                        premium,
                                        urls,
                                        'get_link',
                                        thumb,
                                        movie_title + movie_year,
                                        total_items,
                                        '',
                                        'movies',
                                        menu_items=menu_items,
                                        is_playable='true',
                                        fanart=fanart)
                            viewsetter.set_view('files')
                    except:
                        pass

        except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            if kodi.get_setting('error_notify') == "true":
                kodi.notify(header='Movie Scrapers',
                            msg='(error) %s  %s' % (str(e), ''),
                            duration=5000,
                            sound=None)
            return
Beispiel #34
0
import cookielib
net = Net()
addon_id = kodi.addon_id
addon = Addon(addon_id, sys.argv)
ADDON = xbmcaddon.Addon(id=kodi.addon_id)

#COOKIE STUFF
tools.create_directory(tools.AOPATH, "All_Cookies/PrimeWire")
cookiepath = xbmc.translatePath(
    os.path.join('special://home', 'addons', addon_id, 'All_Cookies',
                 'PrimeWire/'))
cookiejar = os.path.join(cookiepath, 'cookies.lwp')
cj = cookielib.LWPCookieJar()
cookie_file = os.path.join(cookiepath, 'cookies.lwp')

base_url = kodi.get_setting('primewire_base_url')
#base_url = 'http://www.primewire.ag/'


def LogNotify(title, message, times, icon):
    xbmc.executebuiltin("XBMC.Notification(" + title + "," + message + "," +
                        times + "," + icon + ")")


def OPEN_URL(url):
    req = urllib2.Request(url)
    req.add_header(
        'User-Agent',
        'Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'
    )
    response = urllib2.urlopen(req)
Beispiel #35
0
def get_cooked_url(url,
                   base_url,
                   timeout,
                   cookies=None,
                   data=None,
                   multipart_data=None,
                   headers=None,
                   allow_redirect=True,
                   cache_limit=8):
    if cookies is None: cookies = {}
    if timeout == 0: timeout = None
    if headers is None: headers = {}
    referer = headers['Referer'] if 'Referer' in headers else url
    if kodi.get_setting('debug') == "true":
        log_utils.log(
            'Getting Url: %s cookie=|%s| data=|%s| extra headers=|%s|' %
            (url, cookies, data, headers))
    if data is not None:
        if isinstance(data, basestring):
            data = data
        else:
            data = urllib.urlencode(data, True)

    if multipart_data is not None:
        headers['Content-Type'] = 'multipart/form-data; boundary=X-X-X'
        data = multipart_data

    try:
        cj = _set_cookies(base_url, cookies)
        request = urllib2.Request(url, data=data)
        request.add_header('User-Agent', _get_ua())
        #request.add_unredirected_header('Host', base_url)
        request.add_unredirected_header('Referer', referer)
        for key in headers:
            request.add_header(key, headers[key])
        cj.add_cookie_header(request)
        if not allow_redirect:
            opener = urllib2.build_opener(NoRedirection)
            urllib2.install_opener(opener)
        else:
            opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
            urllib2.install_opener(opener)
            opener2 = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
            urllib2.install_opener(opener2)

        response = urllib2.urlopen(request, timeout=timeout)
        cj.extract_cookies(response, request)
        if kodi.get_setting('debug') == "true":
            print 'Response Cookies: %s - %s' % (url, cookies_as_str(cj))
        __fix_bad_cookies()
        cj.save(ignore_discard=True)
        if not allow_redirect and (response.getcode() in [301, 302, 303, 307]
                                   or response.info().getheader('Refresh')):
            if response.info().getheader('Refresh') is not None:
                refresh = response.info().getheader('Refresh')
                return refresh.split(';')[-1].split('url=')[-1]
            else:
                return response.info().getheader('Location')

        content_length = response.info().getheader('Content-Length', 0)
        if int(content_length) > MAX_RESPONSE:
            print 'Response exceeded allowed size. %s => %s / %s' % (
                url, content_length, MAX_RESPONSE)

        if response.info().get('Content-Encoding') == 'gzip':
            buf = StringIO(response.read(MAX_RESPONSE))
            f = gzip.GzipFile(fileobj=buf)
            html = f.read()
        else:
            html = response.read(MAX_RESPONSE)
    except urllib2.HTTPError as e:
        if e.code == 503 and 'cf-browser-verification' in e.read():
            print "WAS ERROR"
            html = cloudflare.solve(url, cj, _get_ua())
            if not html:
                return ''
        else:
            print 'Error (%s) during THE scraper http get: %s' % (str(e), url)
            return ''
    except Exception as e:
        print 'Error (%s) during scraper http get: %s' % (str(e), url)
        return ''

    return html
Beispiel #36
0
except:
    pass

try:
    xmlurl = urllib.unquote_plus(params["xmlurl"])
except:
    pass

try:
    dataurl = urllib.unquote_plus(params["dataurl"])
except:
    pass

#ext = addon.queries.get('ext', '')

if kodi.get_setting('debug') == "true":
    print "Mode: " + str(mode)
    print "URL: " + str(url)
    print "Name: " + str(name)
    print "Thumb: " + str(thumb)

if mode == None:
    main_menu()

elif mode == 'system_info':
    system_info()

elif mode == 'get_libs':
    rtmp_lib()

elif mode == 'call_sports':
Beispiel #37
0
def get_link(url, movie_title, thumb, media):
    #kodi.log("Name IS NOW = " + movie_title)
    hmf = urlresolver.HostedMediaFile(url)
    ##########################################
    if hmf:
        try:
            url = urlresolver.resolve(url)
            params = {'url': url, 'title': movie_title, 'thumb': thumb}
            listitem = xbmcgui.ListItem(path=url,
                                        iconImage=thumb,
                                        thumbnailImage=thumb)
            listitem.setProperty('fanart_image', fanart)

            listitem.setPath(url)
            listitem.setInfo('video', params)

            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
            movie_name = movie_title[:-6]
            movie_name = '"' + movie_name + '"'
            movie_year_full = movie_title[-6:]
            movie_year = movie_year_full.replace('(', '').replace(')', '')
            if kodi.get_setting('trakt_oauth_token'):
                xbmc.sleep(30000)
                kodi.log("Velocity: Movie Scrobble  Start")
                try:
                    trakt_auth.start_movie_watch(movie_name, movie_year)
                except Exception as e:
                    log_utils.log('Error [%s]  %s' % (str(e), ''),
                                  xbmc.LOGERROR)
                    if kodi.get_setting('error_notify') == "true":
                        kodi.notify(header='Scrobble not loggged',
                                    msg='%s  %s' % (str(e), ''),
                                    duration=5000,
                                    sound=None)
            xbmc.sleep(30000)
            if kodi.get_setting('trakt_oauth_token'):
                check_player(movie_name, movie_year)
        except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            kodi.notify(header='Try Another Source',
                        msg='Link Removed or Failed',
                        duration=4000,
                        sound=None)

    if not hmf:
        try:
            params = {'url': url, 'title': movie_title, 'thumb': thumb}
            addon.add_video_item(params, {'title': movie_title}, img=thumb)
            liz = xbmcgui.ListItem(movie_title,
                                   iconImage="DefaultFolder.png",
                                   thumbnailImage=thumb)
            xbmc.sleep(1000)
            liz.setPath(str(url))
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
            #xbmc.Player ().play(url, liz, False)
            movie_name = movie_title[:-6]
            movie_name = '"' + movie_name + '"'
            movie_year_full = movie_title[-6:]
            movie_year = movie_year_full.replace('(', '').replace(')', '')
            if kodi.get_setting('trakt_oauth_token'):
                xbmc.sleep(30000)
                print "Velocity: Movie Scrobble  Start"
                try:
                    trakt_auth.start_movie_watch(movie_name, movie_year)
                except Exception as e:
                    log_utils.log('Error [%s]  %s' % (str(e), ''),
                                  xbmc.LOGERROR)
                    if kodi.get_setting('error_notify') == "true":
                        kodi.notify(header='Scrobble not loggged',
                                    msg='%s  %s' % (str(e), ''),
                                    duration=5000,
                                    sound=None)

            xbmc.sleep(30000)
            if kodi.get_setting('trakt_oauth_token'):
                check_player(movie_name, movie_year)
        except Exception as e:
            log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
            kodi.notify(header='Try Another Source',
                        msg='Link Removed or Failed',
                        duration=4000,
                        sound=None)
Beispiel #38
0
from t0mm0.common.addon import Addon
import tools
import string
from libs import cloudflare
from libs import log_utils
from tm_libs import dom_parser
import cookielib
import json
from StringIO import StringIO
import gzip
import xml.etree.ElementTree as ET
import main_scrape
import HTMLParser
addon_id = kodi.addon_id

timeout = int(kodi.get_setting('scraper_timeout'))


def __enum(**enums):
    return type('Enum', (), enums)


VIDEO_TYPES = __enum(TVSHOW='TV Show',
                     MOVIE='Movie',
                     EPISODE='Episode',
                     SEASON='Season')
#COOKIE STUFF

tools.create_directory(tools.AOPATH, "All_Cookies/IceFilms")
cookiepath = xbmc.translatePath(
    os.path.join('special://home', 'addons', addon_id, 'All_Cookies',
Beispiel #39
0
def apply_urlresolver(hosters):
    filter_debrid = kodi.get_setting('filter_debrid') == 'true'
    show_debrid = kodi.get_setting('show_debrid') == 'true'
    if not filter_debrid and not show_debrid:
        print "RETURNING NON FILTERED"
        return hosters
## New Resolver
    try:
        import urlresolver.plugnplay
        resolvers = urlresolver.plugnplay.man.implementors(
            urlresolver.UrlResolver)
        debrid_resolvers = [
            resolver for resolver in resolvers if resolver.isUniversal()
            and resolver.get_setting('enabled') == 'true'
        ]
    except:
        import urlresolver
        debrid_resolvers = [
            resolver()
            for resolver in urlresolver.relevant_resolvers(order_matters=True)
            if resolver.isUniversal()
        ]
##   End New Resolver
    filtered_hosters = []
    debrid_hosts = {}
    unk_hosts = {}
    known_hosts = {}

    for hoster in hosters:
        #print "HOSTERS ARE: "+str(hoster)
        if 'direct' in hoster and hoster['direct'] == False and hoster['host']:
            host = hoster['host']
            host = (host.lower())
            #
            if kodi.get_setting('filter_debrid') == 'true':
                if host in unk_hosts:
                    # log_utils.log('Unknown Hit: %s from %s' % (host, hoster['class'].get_name()), log_utils.LOGDEBUG)
                    unk_hosts[host] += 1
                    continue
                elif host in known_hosts:
                    # log_utils.log('Known Hit: %s from %s' % (host, hoster['class'].get_name()), log_utils.LOGDEBUG)
                    known_hosts[host] += 1
                    filtered_hosters.append(hoster)
                else:
                    hmf = urlresolver.HostedMediaFile(
                        host=host, media_id='dummy'
                    )  # use dummy media_id to force host validation
                    if hmf:
                        # log_utils.log('Known Miss: %s from %s' % (host, hoster['class'].get_name()), log_utils.LOGDEBUG)
                        known_hosts[host] = known_hosts.get(host, 0) + 1
                        filtered_hosters.append(hoster)
                    else:
                        # log_utils.log('Unknown Miss: %s from %s' % (host, hoster['class'].get_name()), log_utils.LOGDEBUG)
                        unk_hosts[host] = unk_hosts.get(host, 0) + 1
                        continue
            else:
                filtered_hosters.append(hoster)

            if host in debrid_hosts:
                log_utils.log(
                    'Debrid cache found for %s: %s' %
                    (host, debrid_hosts[host]), log_utils.LOGDEBUG)
                hoster['debrid'] = debrid_hosts[host]
                #print debrid_hosts[host]
            else:
                temp_resolvers = []
                for resolver in debrid_resolvers:
                    if resolver.valid_url('', host):
                        #print resolver.name
                        rname = resolver.name.replace('Real-Debrid',
                                                      'RD').replace(
                                                          'Premiumize.me',
                                                          'PRE')
                        temp_resolvers.append(rname.upper())
                        #temp_resolvers.append(resolver.name.upper())
                        if kodi.get_setting('debug') == "true":
                            print '%s supported by: %s' % (host,
                                                           temp_resolvers)
                        debrid_hosts[host] = temp_resolvers
                    else:
                        hoster['debrid'] = ''
                if temp_resolvers:
                    hoster['debrid'] = temp_resolvers
                    #print temp_resolvers
        else:
            filtered_hosters.append(hoster)

    #log_utils.log('Discarded Hosts: %s' % (sorted(unk_hosts.items(), key=lambda x: x[1], reverse=True)), xbmc.LOGDEBUG)
    if kodi.get_setting('debug') == "true":
        kodi.log("FILTERED HOSTERS ARE =" + str(filtered_hosters))
    return filtered_hosters
Beispiel #40
0
def main_menu():
    maintool.source_change()
    maintool.feed_change()
    # ########## TRY POP ########
    if len(kodi.get_setting('notify')) > 0:
        kodi.set_setting('notify', str(int(kodi.get_setting('notify')) + 1))
    else:
        kodi.set_setting('notify', "1")
    if int(kodi.get_setting('notify')) == 1:
        xbmcgui.Dialog().notification('Need Support?', 'www.tvaddons.co', artwork + 'icon.png', 3000, False)
    elif int(kodi.get_setting('notify')) == 5:
        kodi.set_setting('notify', "0")
    # ######## END POP ###########

    if kodi.get_setting('hasran') == 'false':
        kodi.set_setting('hasran', 'true')
        
    dp = xbmcgui.DialogProgress()
    try:
        if (not os.path.exists(ART)) or (not os.path.exists(ART2)) or (not os.path.exists(ART3)):
            dp.create(AddonTitle, 'Getting ' + AddonTitle + ' Ready......', 'Downloading ' + AddonTitle + ' Icons.....')
            dp.update(0)
            icons_zip = os.path.join(packagepath, AddonTitle + '_icons.zip')
            downloader.download(OPEN_URL('http://indigo.tvaddons.co/graphics/arts.txt'), icons_zip, dp)
            dp.update(0, 'Getting %s Ready........' % AddonTitle, 'Extracting %s Icons......' % AddonTitle)
            extract.all(icons_zip, addon_path, dp)
            dp.close()
    except Exception as e:
        kodi.log(str(e))
    # Check for old version of hubrepo and remove it
    try:
        if os.path.exists(hubpath):
            with open(hubpath, 'r') as content:
                if 'AG' in content:
                    shutil.rmtree(hubpath)
    except Exception as e:
        kodi.log(str(e))
    # # Check for HUBRepo and install it
    try:
        if not os.path.exists(hubpath):
            installer.HUBINSTALL('repository.xbmchub', 'http://github.com/tvaddonsco/tva-release-repo/raw/master/'
                                                       'repository.xbmchub/', 'repository.xbmchub')
            xbmc.executebuiltin("XBMC.InstallAddon(%s)" % 'repository.xbmchub')
            addon_able.set_enabled("repository.xbmchub")
            xbmc.executebuiltin("XBMC.UpdateAddonRepos()")
    except Exception as e:
        kodi.log(str(e))
    # Check for Log Uploader and install it
    try:
        if not os.path.exists(uploaderpath):
            installer.HUBINSTALL('script.tvaddons.debug.log',
                                 'http://github.com/tvaddonsco/tva-release-repo/raw/master'
                                 '/script.tvaddons.debug.log/', 'script.tvaddons.debug.log')
            addon_able.set_enabled('script.tvaddons.debug.log')
            # xbmc.executebuiltin("InstallAddon(%s)" % 'script.tvaddons.debug.log')
            xbmc.executebuiltin("XBMC.UpdateLocalAddons()")
    except Exception as e:
        kodi.log(str(e))
   
    # Check for old maintenance tools and remove them
    old_maintenance = (oldinstaller, oldnotify, oldmain, oldwiz, oldfresh)
    for old_file in old_maintenance:
        if os.path.exists(old_file):
            shutil.rmtree(old_file)

    # Notification Status
    if kodi.get_setting("notifications-on-startup") == "false":
        note_status = '(Opt Out)'
        note_art = 'notification_optout.png'
        note_description = 'Unsubscribe'
    else:
        note_status = '(Opt In)'
        note_art = 'notification_in.png'
        note_description = 'Subscribe'

    if kodi.get_setting('wizardran') == 'false':
        kodi.addItem("Config Wizard", '', 'call_wizard', artwork+'config_wizard.png',
                     description="Automatically configure Kodi with the best addons and goodies in seconds!")
    kodi.addDir("Addon Installer", '', 'call_installer', artwork + 'addon_installer.png',
                description="It’s like an App Store for Kodi addons!")
    kodi.addDir("Maintenance Tools", '', 'call_maintool', artwork + 'maintool.png',
                description="Keep your Kodi setup running at optimum performance!")
    # kodi.addDir("Kodi Librtmp Files", '', 'get_libs', artwork +'librtmp_files.png')
    kodi.addItem("Rejuvenate Kodi", '', 'call_rejuv', artwork + 'rejuvinate.png',
                 description="Wipe and reconfigure Kodi with the latest Config Wizard setup!")
    kodi.addDir("Factory Restore", '', 'call_restore', artwork + 'factory_restore.png',
                description="Start off fresh, wipe your Kodi setup clean!")
    if os.path.exists(uploaderpath):
        kodi.addItem("Log Uploader", '', 'log_upload', artwork + 'log_uploader.png',
                     description="Easily upload your error logs for troubleshooting!")
    kodi.addDir("Network Speed Test", '', 'runspeedtest', artwork + 'speed_test.png',
                description="How fast is your internet?")
    kodi.addDir("System Information", '', 'system_info', artwork + 'system_info.png',
                description="Useful information about your Kodi setup!")
    kodi.addDir("Sports Listings", '', 'call_sports', artwork + 'sports_list.png',
                description="Who’s playing what today?")
    kodi.addDir('Backup / Restore', '', 'backup_restore', artwork + 'backup_restore.png',
                description="Backup or restore your Kodi configuration in minutes!")
    kodi.addItem("Log Viewer", '', 'log_view', artwork + 'log_viewer.png',
                 description="Easily view your error log without leaving Kodi!")
    kodi.addItem("No-Coin Scan", '', 'nocoin', artwork + 'no_coin.png',
                 description="Scan your Kodi directory for coin mining.")
    kodi.addItem("Notifications " + note_status, '', 'toggle_notify', artwork + note_art,
                 description="%s to important TV ADDONS notifications on startup!" % note_description)
    kodi.addItem("Show Notification", '', 'show_note', artwork + 'notification.png',
                 description="Show TVA Notification. To get Important News, Tips, and Giveaways from TV ADDONS")
    viewsetter.set_view("sets")
Beispiel #41
0
def force_title(video):
    trakt_str = kodi.get_setting('force_title_match')
    trakt_list = trakt_str.split('|') if trakt_str else []
    return str(video.trakt_id) in trakt_list
import os
import sys
import xbmc
import xbmcaddon
import xbmcgui
from libs import kodi
from libs import viewsetter

dp = xbmcgui.DialogProgress()
AddonTitle = kodi.addon.getAddonInfo('name')
addon_id = kodi.addon_id
selfAddon = xbmcaddon.Addon(id=addon_id)

backupfull = selfAddon.getSetting('backup_database')
backupaddons = selfAddon.getSetting('backup_addon_data')
zip_setting = kodi.get_setting("zip")
zip_path = xbmc.translatePath(os.path.join(zip_setting))

# ICON = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
home_path = xbmc.translatePath('special://home/')
addons_path = xbmc.translatePath(os.path.join('special://home', 'addons', ''))
packages_path = xbmc.translatePath(os.path.join('special://home/addons/' + 'packages'))
userdata_path = xbmc.translatePath(os.path.join('special://home/userdata', ''))
addon_data_path = xbmc.translatePath(os.path.join(userdata_path, 'addon_data'))
databases_path = xbmc.translatePath(os.path.join(userdata_path, 'Database'))
navi_path = xbmc.translatePath(os.path.join(addons_path, 'script.navi-x'))
excludes_folder = xbmc.translatePath(os.path.join(userdata_path, 'BACKUP'))
dialog = xbmcgui.Dialog()


def backup_menu():
Beispiel #43
0
        xbmc.executebuiltin("UpdateLocalAddons")


def note(n_time, status=False):
    if not xbmc.Player().isPlaying():
        n_time = datetime.datetime.now()
        notification.check_news2("t", override_service=status)
    return n_time


block_time = datetime.datetime.now()
link = kodi.read_file(BlocksUrl).replace(' ',
                                         '').replace('\r',
                                                     '').replace('\n', '')
settings.setSetting("blockLink", link) if link else ''
block_time = blocker(block_time) if kodi.get_setting(
    'scriptblock') == 'true' else block_time
get_dir(addon_id,
        script_url) if not os.path.exists(addonspath + addon_id) else ''

old_maintenance = (oldinstaller, oldnotify, oldmain, oldwiz, oldfresh)
for old_file in old_maintenance:
    shutil.rmtree(old_file) if os.path.exists(old_file) else ''

if xbmc.getCondVisibility('System.HasAddon(script.service.twitter)'):
    search_string = xbmcaddon.Addon('script.service.twitter').getSetting(
        'search_string')
    search_string = search_string.replace('from:@', 'from:')
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'search_string', search_string)
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'enable_service', 'false')
Beispiel #44
0
from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib
net = Net()
addon_id = kodi.addon_id
addon = Addon(addon_id, sys.argv)

#COOKIE STUFF
tools.create_directory(tools.AOPATH, "All_Cookies/Two_Movies")
cookiepath = xbmc.translatePath(
    os.path.join('special://home', 'addons', addon_id, 'All_Cookies',
                 'Two_Movies/'))
cookiejar = os.path.join(cookiepath, 'cookies.lwp')
cj = cookielib.LWPCookieJar()
cookie_file = os.path.join(cookiepath, 'cookies.lwp')

base_url = kodi.get_setting('twomovies_base_url')
host_url = base_url.replace('http://', '').replace('/', '')


def LogNotify(title, message, times, icon):
    xbmc.executebuiltin("XBMC.Notification(" + title + "," + message + "," +
                        times + "," + icon + ")")


def OPEN_URLTM(url):

    try:
        req = urllib2.Request(url)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'
Beispiel #45
0
def createConfig():
    
    #Fix_Special:
    USERDATA     =  xbmc.translatePath(os.path.join('special://home/userdata',''))
    if kodi.get_setting('fix_special') == 'true':
                    try: FIX_SPECIAL(USERDATA)
                    except: pass
    
    source = [xbmc.translatePath(os.path.join('special://home', 'addons'))]
    source.append(xbmc.translatePath(os.path.join('special://', 'userdata')).rstrip(os.sep))

    path = xbmc.translatePath(os.path.join('special://','home'))
    version = time.strftime("%Y%m%d_%H%M")
    destination_file = 'kodi.'+version+'.zip'
    
    # Update version.json file
    current = json.loads('{"config_version": "'+version+'","test_version": "'+version+'"}')
    version_path = xbmc.translatePath(os.path.join('special://', 'userdata'))
    version_file = version_path+'version.json'
    with open(version_file, "w") as outfile:
        json.dump(current, outfile)

    # Delete archives and partial downloads
    try:
        for file in glob.glob(path+"kodi.*.zip"):
            os.remove(file)
        for file in glob.glob(version_path+"kodi.*.zip"):
            os.remove(file)
        for file in glob.glob(path+"kodi.*.part"):
            os.remove(file)
        for file in glob.glob(path+"kodi.*.md5"):
            os.remove(file)
    except: pass

    # Ignore standard addons
    #std_addons = xbmc.translatePath(os.path.join('special://home', 'addons', kodi.addon_id, 'resources', 'std_addons.dat'))
    #kodi.log(std_addons)
    #with open(std_addons, 'r') as myfile:
    #    exclusions = myfile.read().split('\n')

    # Ignore certain files too
    #exclusions.extend(
    exclusions = ['.pyc', '.pyd', '.pyo', 'Thumbs.db', '.DS_Store', '__MACOSX',
                       'addons/packages', 'addons/temp', 'userdata/library',
                       'userdata/peripheral_data', 'userdata/playlists', 'userdata/Thumbnails', 
                       'Textures13.db', 'MyMusic', 'MyVideos', '.lock']

    # Cleanse installer settings before backup
    deviceid = kodi.get_setting('deviceid')
    mac = kodi.get_setting('mac')
    update_test = kodi.get_setting('update_test')

    kodi.set_setting('deviceid', '')
    kodi.set_setting('mac', '')
    kodi.set_setting('update_text', 'false')

    # Backup Files
    dp.create('idolpx Installer', 
              'Creating Backup: '+destination_file, 
              '', 
              'Please wait...')
    kodi.log('Creating Configuration Backup: '+destination_file)
    if zip(source, path + destination_file, exclusions):
        validate_file(path + destination_file, "MD5")
        xbmcgui.Dialog().ok(
            'idolpx Installer',
            '[COLOR green]Backup Successful![/COLOR]',
            '',
            '[B]'+destination_file+'[/B]'
        )
    else:
        xbmcgui.Dialog().ok(
            'idolpx Installer',
            '[COLOR red]Backup Error![/COLOR]',
            '',
            '[B]'+destination_file+'[/B]'
        )
        
    # Restore installer settings after backup
    kodi.set_setting('deviceid', deviceid)
    kodi.set_setting('mac', mac)
    kodi.set_setting('update_text', update_test)
Beispiel #46
0
 def __init__(self, timeout=scrapeit.DEFAULT_TIMEOUT):
     self.timeout = timeout
     self.base_url = kodi.get_setting('icefilms_base_url')
Beispiel #47
0
def installConfig(url, hash=None):
    path = xbmc.translatePath(os.path.join('special://', 'home'))
    filename = url.split('/')[-1]
    destination_file = os.path.join(path, filename)

    # Download File
    dp.create('idolpx Installer',
              'Downloading: '+filename,
              '',
              'Please wait...')

    while 1:
        kodi.log('Downloading '+url+' to '+destination_file)
        if download_with_resume(url, destination_file, _download_progress):

            # Check to make sure file validates before install
            if validate_file(destination_file, hash) or hash == '':

                # Delete 'addons' folder
                dp.update(100, "Removing 'addons' folder",
                        '',
                        'Please wait...')
                try: shutil.rmtree(xbmc.translatePath(os.path.join('special://home', 'addons')))
                except: pass

                # Rename userdata folder
                try:
                    userdata = xbmc.translatePath(os.path.join('special://', 'userdata'))[:-1]
                    os.rename(userdata, userdata+'.old')
                except: pass

                try:
                    # Extract File
                    extract_path = xbmc.translatePath(os.path.join('special://', 'home'))
                    unzip(destination_file, extract_path)
                except: pass

                # Copy settings files back into place
                dp.update(100, 'Restoring Settings',
                        '',
                        'Please wait...')
                if kodi.get_setting('keepadv') == 'true':
                    try: shutil.copyfile(userdata+".old/advancedsettings.xml", userdata+"/advancedsettings.xml")
                    except: pass
                if kodi.get_setting('keepfavourites') == 'true':
                    try: shutil.copyfile(userdata+".old/favourites.xml", userdata+"/favourites.xml")
                    except: pass
                if kodi.get_setting('keepgui') == 'true':
                    try: shutil.copyfile(userdata+".old/guisettings.xml", userdata+"/guisettings.xml")
                    except: pass
                if kodi.get_setting('keepsources') == 'true':
                    try: shutil.copyfile(userdata+".old/sources.xml", userdata+"/sources.xml")
                    except: pass
                    try:
                        if kodi.get_setting('keepmuisc') == 'true':
                            for file in glob.glob(userdata+".old/Database/MyMusic*.db"):
                                shutil.copyfile(file, userdata+"/Database/")

                        if kodi.get_setting('keepvideos') == 'true':
                            for file in glob.glob(userdata+".old/Database/MyVideos*.db"):
                                shutil.copyfile(file, userdata+"/Database/")
                    except: pass

                # Copy addon settings back into place
                try: shutil.copyfile(userdata+".old/addon_data/"+kodi.addon_id+"/settings.xml",
                                    userdata+"/addon_data/"+kodi.addon_id+"/settings.xml")
                except: pass

                # Delete old 'userdata' folder
                dp.update(100, "Cleaning up",
                        '',
                        'Please wait...')
                try: shutil.rmtree(userdata+'.old')
                except: pass

                # Delete archives and partial downloads
                try:
                    for file in glob.glob(extract_path+"kodi.*.zip"):
                        os.remove(file)
                    for file in glob.glob(extract_path+"kodi.*.part"):
                        os.remove(file)
                    for file in glob.glob(extract_path+"kodi.*.md5"):
                        os.remove(file)
                    for file in glob.glob(extract_path+"update.*"):
                        os.remove(file)
                except: pass

                return True
                break

            else:
                choice = xbmcgui.Dialog().yesno('idolpx Installer',
                                                'File Validation Failed!',
                                                '',
                                                'Would you like to retry?')
                if choice == 0:
                    return False
                    break

        else:
            choice = xbmcgui.Dialog().yesno('idolpx Installer',
                                            'Transfer incomplete!',
                                            '',
                                            'Would you like to retry?')
            if choice == 0:
                return False
                break
Beispiel #48
0
def main_menu():

    # sourcePath = xbmc.translatePath(os.path.join('special://home','userdata'))
    # newSource = sourcePath+"/sources.xml"
    #
    # with open(newSource) as f:
    #   file_str = f.read()
    #   if 'fusion' not in file_str:
    #       kodi.log("FUSION NOT FOUND")
    #
    #       # do stuff with file_str
    #       #kodi.log(file_str)
    #       with open(newSource, "w") as f:
    #           f.write(file_str)
    #   else:
    #       kodi.log("FUSION IS INSTALLED")

    if kodi.get_setting('hasran') == 'false':
        kodi.set_setting('hasran', 'false')
    try:
        if not os.path.exists(hubpath):
            installer.HUBINSTALL(
                'repository.cyberxnuke',
                'https://github.com/CYBERxNUKE/xbmc-addon/raw/master/repository.cyberxnuke/repository.cyberxnuke-1.2.zip',
                '', 'addon', 'none')
            xbmc.executebuiltin("XBMC.UpdateLocalAddons()")
            addon_able.set_enabled("repository.cyberxnuke")
    except:
        pass
    try:
        if not os.path.exists(uploaderpath):
            installer.HUBINSTALL(
                'TVADDONS.AG.LogUploader',
                'https://offshoregit.com/xbmchub/xbmc-hub-repo/raw/master/script.tvaddons.debug.log/script.tvaddons.debug.log-1.0.7.zip',
                '', 'addon', 'none')
            xbmc.executebuiltin("XBMC.UpdateLocalAddons()")
            addon_able.set_enabled("script.tvaddons.debug.log")
    except:
        pass

    if os.path.exists(oldinstaller):
        shutil.rmtree(oldinstaller)
    if os.path.exists(oldnotify):
        shutil.rmtree(oldnotify)
    if os.path.exists(oldmain):
        shutil.rmtree(oldmain)
    if os.path.exists(oldwiz):
        shutil.rmtree(oldwiz)
    if os.path.exists(oldfresh):
        shutil.rmtree(oldfresh)

    #kodi.addItem("Config Wizard",'','call_wizard',artwork+'config_wizard.png',description="Automatically configure Kodi with the best addons and goodies in seconds!")
    kodi.addItem(
        "Update",
        '',
        'call_wizard1',
        artwork + 'config_wizard.png',
        description="Automatically configure Kodi with the new updates!")
    #kodi.addDir("Addon Installer",'','call_installer',artwork+'addon_installer.png',description="It’s like an App Store for Kodi addons!")
    kodi.addDir(
        "Maintenance Tools",
        '',
        'call_maintool',
        artwork + 'maintool.png',
        description="Keep your Kodi setup running at optimum performance!")
    #kodi.addDir("Kodi Librtmp Files",'','get_libs',artwork+'librtmp_files.png')
    kodi.addItem(
        "Refresh Kodi",
        '',
        'call_rejuv',
        artwork + 'rejuvinate.png',
        description=
        "Wipe and reconfigure Kodi with the latest Computertechs Installer setup!"
    )
    kodi.addDir("Factory Restore",
                '',
                'call_restore',
                artwork + 'factory_restore.png',
                description="Start off fresh, wipe your Kodi setup clean!")
    #kodi.addItem("Log Uploader",'','log_upload',artwork+'log_uploader.png',description="Easily upload your error logs for troubleshooting!")
    kodi.addDir("Network Speed Test",
                '',
                'runspeedtest',
                artwork + 'speed_test.png',
                description="How fast is your internet?")
    kodi.addDir("System Information",
                '',
                'system_info',
                artwork + 'system_info.png',
                description="Useful information about your Kodi setup!")
    #kodi.addDir("Sports Listings",'','call_sports',artwork+'sports_list.png',description="Who’s playing what today?")
    #kodi.addDir('Backup / Restore', '', 'backup_restore', artwork + 'backup_restore.png',description="Backup or restore your Kodi configuration in minutes!")
    kodi.addItem(
        "Log Viewer",
        '',
        'log_view',
        artwork + 'log_uploader.png',
        description="Easily view your error log without leaving Kodi!")
    #    if kodi.get_setting('notifications-on-startup') == 'false':
    #        kodi.addItem("Notifications (Opt Out)",'','enable_notify',artwork+'notification_optout.png',description="Unsubscribe from important TV ADDONS notifications!")
    #    if kodi.get_setting('notifications-on-startup') == 'true':
    #        kodi.addItem("Notifications (Opt In)",'','disable_notify',artwork+'notification_in.png',description="Subscribe to important TV ADDONS notifications!")

    viewsetter.set_view("sets")
import tools
from libs import kodi
from tm_libs import dom_parser
from libs import log_utils
import tools
from libs import cloudflare
from libs import log_utils
from tm_libs import dom_parser
import cookielib
from StringIO import StringIO
import gzip
import main_scrape
import base64
addon_id = kodi.addon_id

timeout = int(kodi.get_setting('scraper_timeout'))

tools.create_directory(tools.AOPATH, "All_Cookies/Putlocker")
cookiepath = xbmc.translatePath(
    os.path.join('special://home', 'addons', addon_id, 'All_Cookies',
                 'Putlocker/'))
cookiejar = os.path.join(cookiepath, 'cookies.lwp')
cj = cookielib.LWPCookieJar()
cookie_file = os.path.join(cookiepath, 'cookies.lwp')


def __enum(**enums):
    return type('Enum', (), enums)


MAX_RESPONSE = 1024 * 1024 * 2
        shutil.rmtree(oldfresh)
except:
    pass
##############################

if xbmc.getCondVisibility('System.HasAddon(script.service.twitter)'):
    search_string = xbmcaddon.Addon('script.service.twitter').getSetting(
        'search_string')
    search_string = search_string.replace('from:@', 'from:')
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'search_string', search_string)
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'enable_service', 'false')

## Start of notifications
if kodi.get_setting('hasran') == 'true':
    #kodi.log('Indigo has ran before')
    TypeOfMessage = "t"
    (NewImage, NewMessage) = Common.FetchNews()
    Common.CheckNews(TypeOfMessage, NewImage, NewMessage, True)
else:
    kodi.log('Indigo has NOT ran before')
## ################################################## ##
## ################################################## ##

## Start of program
support.service_checks()
support.scriptblock_checks()
## ################################################## ##
## ################################################## ##
Beispiel #51
0
def primewire(name):
    try:
        sources = []
        searchUrl = base_url + 'index.php?search_keywords='
        movie_name = name[:-6]
        movie_name_short = name[:-7]
        movie_year_full = name[-6:]
        movie_year = movie_year_full.replace('(', '').replace(')', '')
        sname = movie_name.replace(" ", "+")
        primename = sname[:-1]
        movie_match = movie_name.replace(" ", "_") + movie_year
        surl = searchUrl + primename
        link = OPEN_URL(surl)
        full_match = movie_name + movie_year_full
        match = re.compile('<a href="/(.+?)" title="Watch (.+?)">').findall(
            link)
        for url, name in match:
            if full_match == name:
                link = OPEN_URL(base_url + url)
                container_pattern = r'<table[^>]+class="movie_version[ "][^>]*>(.*?)</table>'
                item_pattern = (
                    r'quality_(?!sponsored|unknown)([^>]*)></span>.*?'
                    r'url=([^&]+)&(?:amp;)?domain=([^&]+)&(?:amp;)?(.*?)'
                    r'"version_veiws"> ([\d]+) views</')
                max_index = 0
                max_views = -1
                for container in re.finditer(container_pattern, link,
                                             re.DOTALL | re.IGNORECASE):
                    for i, source in enumerate(
                            re.finditer(item_pattern, container.group(1),
                                        re.DOTALL)):
                        qual, url, host, parts, views = source.groups()
                        if kodi.get_setting('debug') == "true":
                            print "PrimeWire Debug:"
                            print "Quality is " + qual
                            print "URL IS " + url.decode('base-64')
                            print "HOST IS  " + host.decode('base-64')
                            print "VIEWS ARE " + views
                        if host == 'ZnJhbWVndGZv':
                            continue  # filter out promo hosts
                        #host = tools.get_hostname(host.decode('base-64'))
                        source = {
                            'url': url.decode('base-64'),
                            'host': host.decode('base-64'),
                            'view': views,
                            'quality': qual,
                            'direct': False
                        }
                        sources.append(source)
        #print "MOVIE SOURCES ARE = "+str(sources)
        sources = main_scrape.apply_urlresolver(sources)
        return sources
    except Exception as e:
        hosters = []
        log_utils.log('Error [%s]  %s' % (str(e), ''), xbmc.LOGERROR)
        if kodi.get_setting('error_notify') == "true":
            kodi.notify(header='PrimeWire',
                        msg='(error) %s  %s' % (str(e), ''),
                        duration=5000,
                        sound=None)
        return hosters
Beispiel #52
0
def showAdult(status, pin='0'):
    global window

    if status == None:
        status = window.getProperty('idolpx.installer.adultstatus')

    if status == 'true':
        # Enable Adult Addons
        if pin == '0':
            pin = xbmcgui.Dialog().numeric(0,'Enter PIN')

        if pin == kodi.get_setting('adultpin'):
            status = 'true'
        else:
            status = 'abort'
    else:
        # Disable Adult Addons
        status = 'false'

    kodi.debug('Adult Addons Enabled: ' + status)
    if status != 'abort':
        window.setProperty('idolpx.installer.adultstatus', status)
        
        addonPath = xbmc.translatePath(os.path.join('special://home', 'addons'))
        resourcePath = os.path.join(addonPath, kodi.addon_id(), 'resources')
        nsfw_addons = os.path.join(resourcePath, 'nsfw_addons.dat')
        with open(nsfw_addons, 'r') as myfile:
            addons = myfile.read().split('\n')

        for addon in addons:
            try:
                # Move Addon
                if status == 'true':
                    shutil.move(os.path.join(resourcePath, addon), os.path.join(addonPath, addon))
                    #kodi.update_enabled(addon, 1)
                else:
                    shutil.move(os.path.join(addonPath, addon), os.path.join(resourcePath, addon))
                    #kodi.update_enabled(addon, 0)

                # Enable/Disable Addon
                query = '{"jsonrpc":"2.0", "id":1, "method":"Addons.SetAddonEnabled","params":{"addonid":"%s", "enabled":%s}}' % (addon, status)
                kodi.execute_jsonrpc(query)
                kodi.debug(query)
                xbmc.sleep(200)

            except:
                pass

        kodi.execute('UpdateLocalAddons()')
        kodi.execute('UpdateAddonRepos()')
        #xbmc.sleep(1000)
        #kodi.execute('ReloadSkin()')
        
        kodi.set_setting('adultstatus', status)         
        
        if status == 'true': 
            kodi.notify('Adult Addons','Enabled!')
        else: 
            kodi.notify('Adult Addons', 'Disabled!')
       
    else:
        kodi.notify('Adult Addons', 'Invalid PIN!')
Beispiel #53
0
            shutil.rmtree(old_file)
        except OSError:
            pass

# #############################
if xbmc.getCondVisibility('System.HasAddon(script.service.twitter)'):
    search_string = xbmcaddon.Addon('script.service.twitter').getSetting(
        'search_string')
    search_string = search_string.replace('from:@', 'from:')
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'search_string', search_string)
    xbmcaddon.Addon('script.service.twitter').setSetting(
        'enable_service', 'false')

# Start of notifications
if kodi.get_setting('hasran') == 'true':
    # kodi.log(AddonTitle + ' has ran before')
    TypeOfMessage = "t"
    (NewImage, NewMessage) = Common.FetchNews()
    Common.CheckNews(TypeOfMessage, NewImage, NewMessage, True)
else:
    kodi.log(AddonTitle + ' has NOT ran before')
# ################################################## ##
# ################################################## ##

# Start of program
# support.service_checks()
# support.scriptblock_checks()

# ################################################## ##
# ################################################## ##
Beispiel #54
0
                   HIGH='High',
                   HD720='HD720',
                   HD1080='HD1080')
VIDEO_TYPES = __enum(TVSHOW='TV Show',
                     MOVIE='Movie',
                     EPISODE='Episode',
                     SEASON='Season')
########ALL NEED ABOVE#############

QUALITY_MAP = {
    'DVD': QUALITIES.HIGH,
    'TS': QUALITIES.MEDIUM,
    'CAM': QUALITIES.LOW
}

BASE_URL = kodi.get_setting('primewire_base_url')


class Scraper(scrapeit.Scraper):
    base_url = BASE_URL

    def __init__(self, timeout=scrapeit.DEFAULT_TIMEOUT):
        self.timeout = timeout
        self.base_url = kodi.get_setting('primewire_base_url')

    @classmethod
    def provides(cls):
        return frozenset(
            [VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE, VIDEO_TYPES.MOVIE])

    @classmethod
Beispiel #55
0
def tool_menu():
    menu_cache_path = cache_path
    if not os.path.exists(temp_path) and not os.path.exists(cache_path):
        os.makedirs(temp_path)
    if os.path.exists(temp_path):
        menu_cache_path = temp_path
    if not os.path.exists(packages_path):
        os.makedirs(packages_path)
    cache_size = ''
    thumb_size = ''
    packages_size = ''
    paths = {
        menu_cache_path: cache_size,
        thumbnail_path: thumb_size,
        packages_path: packages_size
    }
    if kodi.get_setting("maint_check_folders") == "true":
        for path in paths:
            try:
                paths[path] = ' - [COLOR blue]' + convert_size(
                    get_size(path)) + '[/COLOR]'
            except Exception as e:
                kodi.log(str(e))
                paths[path] = ' - [COLOR red]Error reading thumbnails[/COLOR]'
    startup_clean = kodi.get_setting("acstartup")
    if startup_clean == "false":
        startup_onoff = "Enable"
        su_art = 'enable_am_startup.png'
    else:
        startup_onoff = "Disable"
        su_art = 'disable_am_startup.png'
    su_desc = startup_onoff + " maintenance on Kodi launch!"
    weekly_clean = kodi.get_setting("clearday")
    if weekly_clean == "7":
        weekly_onoff = "Enable"
        acw_art = 'enable_am_week.png'
        acw_desc = "Set your device to perform maintenance on a given day each week!"
    else:
        weekly_onoff = "Disable"
        acw_art = 'disable_am_week.png'
        acw_desc = weekly_onoff + " weekly maintenance on Kodi launch!"
    if kodi.get_setting('scriptblock') == 'false':
        scb_onoff = 'Enable'
        # scb_mode = 'toggleblocker'
        scb_art = 'enable_MSB.png'
    else:
        scb_onoff = 'Disable'
        # scb_mode = 'toggleblocker'
        scb_art = 'enable_MSB.png'
    scb_desc = scb_onoff + " protection against malicious scripts!"

    if not _is_debugging():
        debug_onoff = 'Enable'
        debug_art = 'enabledebug.png'
    else:
        debug_onoff = 'Disable'
        debug_art = 'disabledebug.png'
    debug_desc = debug_onoff + " Debugging!"

    # Maintenance Tool Menu
    kodi.add_item("Clear Cache " + str(paths[menu_cache_path]),
                  '',
                  'clear_cache',
                  artwork + 'currentcache.png',
                  description="Clear your device cache!")
    kodi.add_item("Delete Thumbnails " + str(paths[thumbnail_path]),
                  '',
                  'clear_thumbs',
                  artwork + 'currentthumbs.png',
                  description="Delete your Thumbnail cache!")
    kodi.add_item("Delete Packages " + str(paths[packages_path]),
                  '',
                  'purge_packages',
                  artwork + 'currentpackages.png',
                  description="Delete your addon installation files!")
    kodi.add_item("Delete Crash Logs",
                  '',
                  'crashlogs',
                  artwork + 'clearcrash.png',
                  description="Clear all crash logs from your device!")
    kodi.add_item("Delete Textures13.db",
                  '',
                  'deletetextures',
                  artwork + 'currentthumbs.png',
                  description="This will delete the Textures13 database")
    kodi.add_dir("Wipe Addons",
                 '',
                 'wipe_addons',
                 artwork + 'wipe_addons.png',
                 description="Erase all your Kodi addons in one shot!")
    kodi.add_item(
        "Run Auto Maintenance",
        '',
        'autoclean',
        artwork + 'run_am.png',
        description=
        "Clear your cache, thumbnails and delete addon packages in one click!")
    kodi.add_item(startup_onoff + ' Auto Maintenance on Startup',
                  '',
                  'autocleanstartup',
                  artwork + su_art,
                  description=su_desc)
    kodi.add_item(weekly_onoff + ' Weekly Auto Maintenance',
                  '',
                  'autocleanweekly',
                  artwork + acw_art,
                  description=acw_desc)
    kodi.add_item(debug_onoff + " Debugging Mode",
                  '',
                  'debug_onoff',
                  artwork + debug_art,
                  description=debug_desc)
    kodi.add_item(scb_onoff + " Malicious Scripts Blocker",
                  '',
                  'toggleblocker',
                  artwork + scb_art,
                  description=scb_desc)
    kodi.add_item(
        "Force Update Addons",
        '',
        'updateaddons',
        artwork + 'forceupdateaddons.png',
        description="Force a reload of all Kodi addons and repositories!")
    kodi.add_dir(
        "Install Custom Keymaps",
        '',
        'customkeys',
        artwork + 'custom_keymaps.png',
        description=
        "Get the best experience out of your device-specific remote control!")
    kodi.add_item("Reload Current Skin",
                  '',
                  'reloadskin',
                  artwork + 'reloadskin.png',
                  description="Reload the skin!")
    viewsetter.set_view("sets")
Beispiel #56
0
#from shutil import copyfile


dp = xbmcgui.DialogProgress()
AddonTitle = "Indigo"
AddonID = kodi.addon_id
addon_id = kodi.addon_id
selfAddon = xbmcaddon.Addon(id=AddonID)
backupfull = selfAddon.getSetting('backup_database')
backupaddons = selfAddon.getSetting('backup_addon_data')
PACKAGES = xbmc.translatePath(os.path.join('special://home/addons/' + 'packages'))
dialog = xbmcgui.Dialog()
ICON = xbmc.translatePath(os.path.join('special://home/addons/' + AddonID, 'icon.png'))
HOME         =  xbmc.translatePath('special://home/')
USERDATA     =  xbmc.translatePath(os.path.join('special://home/userdata',''))
zip = kodi.get_setting("zip")
USB          =  xbmc.translatePath(os.path.join(zip))
HOME         =  xbmc.translatePath('special://home/')
EXCLUDES_FOLDER     =  xbmc.translatePath(os.path.join(USERDATA,'BACKUP'))
ADDON_DATA   =  xbmc.translatePath(os.path.join(USERDATA,'addon_data'))
addon_path =  xbmc.translatePath(os.path.join('special://home','addons',''))
NAVI  =  xbmc.translatePath(os.path.join(addon_path,'script.navi-x'))
ADDON_DATA  =  xbmc.translatePath(os.path.join(USERDATA,'addon_data'))
DATABASES        =  xbmc.translatePath(os.path.join(USERDATA,'Database'))

def check_path():

    if zip ==  "Click Here":
        kodi.openSettings(addon_id,id1=0,id2=0)
        sys.exit(0)
    if HOME in USB:
Beispiel #57
0
def auto_clean(auto_clear=False):
    if not auto_clear:
        if not xbmcgui.Dialog().yesno(
                AddonName,
                'Selecting Yes runs maintenance based on your settings.',
                'Do you wish to continue?',
                yeslabel='Yes',
                nolabel='No'):
            return
    available_space, total_space = get_free_space_mb(
        kodi.translate_path('special://home'))
    err_default = (0, '0 B', '0M', '0 MB', '0 MB Free', '0 MB Total',
                   '0M Free', '0M Total')
    if str(available_space) in err_default or str(total_space) in err_default:
        if not auto_clear:
            if xbmcgui.Dialog().yesno(
                    'Auto Maintenance Error',
                    'Auto Maintenance encountered a problem and was not ran',
                    'Maintenace can still be done now or individually',
                    'Would you like to just clear the cache, packages, and thumbnails',
                    yeslabel='Yes',
                    nolabel='No'):
                delete_cache(auto_clear=True)
                delete_packages(auto_clear=True)
                delete_thumbnails(auto_clear=True)
                delete_crash_logs(auto_clear=True)
                xbmc.executebuiltin("Container.Refresh")
                xbmcgui.Dialog().ok(
                    AddonName, 'Auto Maintenance has been run successfully')
        return
    mb_settings = (0, 25, 50, 75, 100)
    for value in ('cachemb', 'thumbsmb', 'packagesmb'):
        available_space += mb_settings[int(kodi.get_setting(value))] * 10**6
    automb = kodi.get_setting("automb")
    cachemb = float(
        (mb_settings[int(kodi.get_setting("cachemb"))]) * 10**6)  # 35%
    for path in (cache_path, temp_path):
        if os.path.exists(path):
            try:
                if (automb and (cachemb >= float(available_space) * .35)) or \
                        ((cachemb == 0 and kodi.get_setting("accache") == 'true')
                         or (cachemb != 0 and (get_size(cache_path) >= int(cachemb)))):
                    delete_cache(auto_clear=True)
            except Exception as e:
                kodi.log(str(e))
    thumbsmb = float(
        (mb_settings[int(kodi.get_setting("thumbsmb"))]) * 10**6)  # 35%
    try:
        if (automb and (thumbsmb >= int(available_space) * .35)) or \
                ((thumbsmb == 0 and kodi.get_setting("acthumbs") == 'true')
                 or (thumbsmb != 0 and (get_size(thumbnail_path) >= int(thumbsmb)))):
            delete_thumbnails(auto_clear=True)
    except Exception as e:
        kodi.log(str(e))
    packagesmb = float(
        (mb_settings[int(kodi.get_setting("packagesmb"))]) * 10**6)  # 10%
    try:
        if (automb and (packagesmb >= int(available_space) * .10)) or \
                ((packagesmb == 0 and kodi.get_setting("acpackages") == 'true')
                 or (packagesmb != 0 and (get_size(packages_path) >= int(packagesmb)))):
            delete_packages(auto_clear=True)
    except Exception as e:
        kodi.log(str(e))
    if kodi.get_setting("accrash") == 'true':
        delete_crash_logs(auto_clear=True)

    if not auto_clear:
        xbmc.executebuiltin("Container.Refresh")
        xbmcgui.Dialog().ok(AddonName,
                            'Auto Maintenance has been run successfully')
Beispiel #58
0
def __enum(**enums):
    return type('Enum', (), enums)


FORCE_NO_MATCH = '***FORCE_NO_MATCH***'
QUALITIES = __enum(LOW='Low',
                   MEDIUM='Medium',
                   HIGH='High',
                   HD720='HD720',
                   HD1080='HD1080')
VIDEO_TYPES = __enum(TVSHOW='TV Show',
                     MOVIE='Movie',
                     EPISODE='Episode',
                     SEASON='Season')

BASE_URL = kodi.get_setting('icefilms_base_url')

QUALITY_MAP = {
    'HD': QUALITIES.HIGH,
    'HDTV': QUALITIES.HIGH,
    'DVD': QUALITIES.HIGH,
    '3D': QUALITIES.HIGH,
    'CAM': QUALITIES.LOW
}

QUALITY_MAP = {
    'HD720P': QUALITIES.HD720,
    'HD720P+': QUALITIES.HD720,
    'DVDRIP/STANDARDDEF': QUALITIES.HIGH,
    'SD/DVD480P': QUALITIES.HIGH,
    'DVDSCREENER': QUALITIES.HIGH,
Beispiel #59
0
import tools
from libs import kodi
from tm_libs import dom_parser
from libs import log_utils
import tools
from libs import cloudflare
from libs import log_utils
from tm_libs import dom_parser
import cookielib
from StringIO import StringIO
import gzip
import main_scrape
import base64
addon_id = kodi.addon_id

timeout = int(kodi.get_setting('scraper_timeout'))

tools.create_directory(tools.AOPATH, "All_Cookies/SantaSeries")
cookiepath = xbmc.translatePath(
    os.path.join('special://home', 'addons', addon_id, 'All_Cookies',
                 'SantaSeries/'))
cookiejar = os.path.join(cookiepath, 'cookies.lwp')
cj = cookielib.LWPCookieJar()
cookie_file = os.path.join(cookiepath, 'cookies.lwp')


def __enum(**enums):
    return type('Enum', (), enums)


MAX_RESPONSE = 1024 * 1024 * 2
def __enum(**enums):
    return type('Enum', (), enums)


FORCE_NO_MATCH = '***FORCE_NO_MATCH***'
QUALITIES = __enum(LOW='Low',
                   MEDIUM='Medium',
                   HIGH='High',
                   HD720='HD720',
                   HD1080='HD1080')
VIDEO_TYPES = __enum(TVSHOW='TV Show',
                     MOVIE='Movie',
                     EPISODE='Episode',
                     SEASON='Season')

BASE_URL = kodi.get_setting('afdah_base_url')


class Scraper(scrapeit.Scraper):
    base_url = BASE_URL

    def __init__(self, timeout=scrapeit.DEFAULT_TIMEOUT):
        self.timeout = timeout
        self.base_url = kodi.get_setting('afdah_base_url')
        #kodi.log(self.base_url)

    @classmethod
    def provides(cls):
        return frozenset([VIDEO_TYPES.MOVIE])

    @classmethod