예제 #1
0
파일: DataBase.py 프로젝트: helloman37/repo
def count_item_DB(file,table,row,match,operator=None):
	''' Counts matches in DB either single row match or multiple row match with operator
	 if more the one coloum is to be matched row and match must be list in order
	file = path to file 
	table = table of file to be checked
	row = row to be checked if more then 1 row to match sent as a list of strings
	match = if multiple match sent through as tuple of strings, single row to match sent as string 
	operator = AND,OR or NOT do not pass through if using single row to match

	              ######multiple match example####
	count = count_item_DB(file=filename,table='sixteen_seventeen',row=['Comp','awayteam'],match=("premier league","tottenham"),operator='AND')

	              ######single row match example##### 
	count = count_item_DB(file=filename,table='sixteen_seventeen',row='Comp',match=("premier league")''' 

	conn = sqlite3.connect(file)
	cursor = conn.cursor()
	if operator==None:
		match = (match,)
		cursor.execute("SELECT count(*) FROM %s WHERE %s LIKE ?"%(table,row),match)
	else:
		sql = "SELECT count(*) FROM {} WHERE".format(table)
		for Row in row:
			if not row.index(Row) == len(row)-1:
				sql += " lower({}) LIKE '%{}%'{}".format(Row,match[row.index(Row)],operator)
			if row.index(Row) == len(row)-1:
				sql +=" lower({}) LIKE '%{}%' ".format(Row,match[row.index(Row)])
		cursor.execute(sql)
	count = cursor.fetchone()
	count = count[0]
	koding.dolog(count,line_info=True)
	sql = ''
	return count
def get_temp_path():
    koding.dolog("get_temp_path")

    dev = xbmc.translatePath("special://temp/")
    koding.dolog("get_temp_path ->'" + str(dev) + "'")

    return dev
예제 #3
0
파일: youtube.py 프로젝트: helloman37/repo
 def video_single(self, url):
     html = koding.Open_URL(url, cookiejar=self.CookieJar, timeout=20)
     match = re.compile(
         '<span id="eow-title" class="watch-title" dir="ltr" title="(.+?)"',
         re.DOTALL).findall(html)
     match2 = re.compile('<p id="eow-description" class="" >(.+?)</p>',
                         re.DOTALL).findall(html)
     match3 = re.compile('<meta itemprop="datePublished" content="(.+?)">',
                         re.DOTALL).findall(html)
     koding.dolog(match, my_debug=True)
     for title in match:
         title = title
     for description in match2:
         match4 = re.compile('(<.*?>)', re.DOTALL).findall(str(description))
         for unwanted in match4:
             if len(match4) >= 1:
                 description = (description).replace((unwanted), '')
             else:
                 description = description
     for date in match3:
         date = date
     vid_id = url.split('v=')[1]
     playlink = 'plugin://plugin.video.youtube/play/?video_id=%s' % vid_id
     icon = 'https://i.ytimg.com/vi/%s/hqdefault.jpg' % vid_id
     self.CHANNEL_VIDEO.append({
         'title': title,
         'playlink': playlink,
         'icon': icon,
         'date': date,
         'description': description
     })
예제 #4
0
def Dependency_OpenSettings():
    DepList = [str(addon_id)]
    dependencies = koding.Dependency_Check(addon_id=addon_id, recursive=True)
    addons_path = koding.Physical_Path('special://home/addons/')
    for dependacy in dependencies:
        if not dependacy in DepList:
            DepList.append(dependacy)
            path = str(addons_path) + str(
                dependacy) + '/resources/settings.xml'
            if xbmcvfs.exists(path):
                try:
                    Addon = xbmcaddon.Addon(str(dependacy))
                    AddonTitle = Addon.getAddonInfo('name')
                    AddonFanart = Addon.getAddonInfo('fanart')
                    AddonIcon = Addon.getAddonInfo('icon')
                    koding.dolog(str(AddonTitle) + ' has file ' + str(path),
                                 line_info=True)
                    BYB.addDir_file(
                        ItemColor('{} {}'.format(local_string(30073),
                                                 AddonTitle)), dependacy, 103,
                        AddonIcon, AddonFanart,
                        '{} {}'.format(local_string(30073),
                                       AddonTitle), '', '', '')
                except:
                    pass
예제 #5
0
def tmdb_check_key(tmdb_apikey):
    Token, StatusMessage, Success = tmdb_request_token(tmdb_apikey)
    if Success == True:
        koding.dolog('api key success')
    else:
        koding.dolog('api key check failed due to ' + str(StatusMessage),
                     line_info=True)
예제 #6
0
    def keep_alive(self):
        koding.dolog("staying alive")
        # keep connection alive
        self.totalTime = 0
        self.currentTime = 0

        if self.resume:
            koding.Create_Table("watched", self.tablespec)
            match = koding.Get_From_Table("watched", {
                "identifier": self.identifier,
                "season": self.season,
                "episode": self.episode
            })
            if match:
                match = match[0]
                if match["currentTime"]:
                        seconds = float(match["currentTime"])
                        xbmc.Player().seekTime(seconds)

        for i in range(0, 240):
            if self.isPlaying():
                break
            xbmc.sleep(1000)
        while self.isPlaying():
            try:
                self.totalTime = self.getTotalTime()
                self.currentTime = self.getTime()
            except:
                pass
            xbmc.sleep(2000)
        xbmc.sleep(5000)
예제 #7
0
def clear_cookies():
	pDialog.create('Deleting Cookies','')
	pDialog.update(0,line1='Searching Cookies in '+str(COOKIES))
	xbmc.sleep(1000)
	cookie_files = koding.Get_Contents(COOKIES,folders=False,subfolders=False,full_path=False)
	total_cookies = len(cookie_files)
	count = 0
	if total_cookies >= 1:
		percent_per_item = 100.00/total_cookies
		for cookie_file in cookie_files:
			count +=1
			percent_update = percent_per_item*count
			pDialog.update(int(percent_update),line1='Removing '+str(cookie_file)+' Cookie file')
			Cookies_deleted = koding.Delete_Cookies(cookie_file)
			deleted = ''
			if Cookies_deleted:
				#deleted.append(cookie_file)
				deleted += '%s,'%cookie_file
		deleted = deleted.rstrip(',')
		message = 'Process Complete'
		message2 =  'Files deleted\n%s'%deleted
	else:
		message ='No Files to delete'
		message2 = 'The Cookie Jar is empty'
	koding.dolog('Total Cookie files = %s Cookie files = %s %s %s'%(total_cookies,cookie_files,message,message2))			
	pDialog.update(100,line1=message,line2=message2)
	xbmc.sleep(1000)
	pDialog.close()
예제 #8
0
def tmdb_session(tmdb_apikey):
    Token, StatusMessage, Success = tmdb_request_token(tmdb_apikey)
    url = 'https://www.themoviedb.org/authenticate/' + str(Token)
    if Success == True:
        BYB.WebBrowse(url)
        auth = koding.YesNo_Dialog(
            title='TMDB Authentication',
            message='Has TMDB Authentication been granted?')
        if auth:
            Url = 'https://api.themoviedb.org/3/authentication/session/new?api_key=' + str(
                tmdb_apikey) + '&request_token=' + str(Token)
            r = requests.get(Url)
            session = r.json()
            Success = session.get('success', 'False')
            SessionId = session.get('session_id', '')
            StatusMessage = session.get("status_message", "NoErrorMessage")
            if Success == True and StatusMessage == 'NoErrorMessage':
                Auth = True
            else:
                Auth = False

        else:
            Auth = False
    else:
        Auth = False
    if Auth == False:
        koding.dolog('tmdb_session failed resason ' + str(StatusMessage),
                     line_info=True)
    return Auth, SessionId, StatusMessage
예제 #9
0
 def onPlayBackStopped(self):
     koding.dolog("playback stopped")
     if self.identifier == "0":
         return
     if not self.currentTime > 1:
         return
     koding.Create_Table("watched", self.tablespec)
     try:
         koding.Remove_From_Table(
             "watched", {
                 "identifier": self.identifier,
                 "season": self.season,
                 "episode": self.episode
             })
     except:
         pass
     koding.Add_To_Table(
         "watched", {
             "identifier": self.identifier,
             "season": self.season,
             "episode": self.episode,
             "watched": "0",
             "currentTime": self.currentTime
         })
     return True
def get_runtime_path():
    koding.dolog("get_runtime_path")

    dev = xbmc.translatePath(__settings__.getAddonInfo('Path'))
    koding.dolog("get_runtime_path ->'" + str(dev) + "'")

    return dev
예제 #11
0
 def UrlDefine(self, url, name):
     if not url.startswith('http') and not url.startswith('plugin:'):
         url = 'http:{}'.format(url)
     if url.startswith(self.SportdevilToPlay):
         url = 'plugin://plugin.video.SportsDevil/?mode=1&amp;item=catcher%3dstreams%26url={url}'.format(
             url=url)
     if url.endswith('.ts'):
         url = 'plugin://plugin.video.f4mTester/?url={url}&amp;streamtype=TSDOWNLOADER&amp;name={name}'.format(
             url=urllib.quote_plus(url), name=name)
     if url.endswith('.m3u8'):
         url = 'plugin://plugin.video.f4mTester/?url={url}&amp;streamtype=HLSRETRY&amp;name={name}'.format(
             url=urllib.quote_plus(url), name=name)
     if url.endswith('.f4m'):
         url = 'plugin://plugin.video.f4mTester/?url={url}&amp;name={name}'.format(
             url=urllib.quote_plus(url), name=name)
     if '|' in url and any(x in url for x in self.f4m):
         _url = url.split('|')[0]
         if _url.endswith('.ts'):
             url = 'plugin://plugin.video.f4mTester/?url={url}&amp;streamtype=TSDOWNLOADER&amp;name={name}'.format(
                 url=urllib.quote_plus(url), name=name)
         if _url.endswith('.m3u8'):
             url = 'plugin://plugin.video.f4mTester/?url={url}&amp;streamtype=HLSRETRY&amp;name={name}'.format(
                 url=urllib.quote_plus(url), name=name)
         if _url.endswith('.f4m'):
             url = 'plugin://plugin.video.f4mTester/?url={url}&amp;name={name}'.format(
                 url=urllib.quote_plus(url), name=name)
     else:
         url = url
     koding.dolog('UrlDefine= {}'.format(url), line_info=True)
     return url
def add_item(action="",
             title="",
             plot="",
             url="",
             thumbnail="",
             fanart="",
             show="",
             episode="",
             extra="",
             page="",
             info_labels=None,
             isPlayable=False,
             folder=True):
    koding.dolog("add_item action=[" + action + "] title=[" + title +
                 "] url=[" + url + "] thumbnail=[" + thumbnail + "] fanart=[" +
                 fanart + "] show=[" + show + "] episode=[" + episode +
                 "] extra=[" + extra + "] page=[" + page + "] isPlayable=[" +
                 str(isPlayable) + "] folder=[" + str(folder) + "]")

    listitem = xbmcgui.ListItem(title,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=thumbnail)
    if info_labels is None:
        info_labels = {"Title": title, "FileName": title, "Plot": plot}
    listitem.setInfo("video", info_labels)

    if fanart != "":
        listitem.setProperty('fanart_image', fanart)
        xbmcplugin.setPluginFanart(int(sys.argv[1]), fanart)

    if url.startswith("plugin://"):
        itemurl = url
        listitem.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                    url=itemurl,
                                    listitem=listitem,
                                    isFolder=folder)
    elif isPlayable:
        listitem.setProperty("Video", "true")
        listitem.setProperty('IsPlayable', 'true')
        itemurl = '%s?action=%s&title=%s&url=%s&thumbnail=%s&plot=%s&extra=%s&page=%s' % (
            sys.argv[0], action, urllib.quote_plus(title),
            urllib.quote_plus(url), urllib.quote_plus(thumbnail),
            urllib.quote_plus(plot), urllib.quote_plus(extra),
            urllib.quote_plus(page))
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                    url=itemurl,
                                    listitem=listitem,
                                    isFolder=folder)
    else:
        itemurl = '%s?action=%s&title=%s&url=%s&thumbnail=%s&plot=%s&extra=%s&page=%s' % (
            sys.argv[0], action, urllib.quote_plus(title),
            urllib.quote_plus(url), urllib.quote_plus(thumbnail),
            urllib.quote_plus(plot), urllib.quote_plus(extra),
            urllib.quote_plus(page))
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                    url=itemurl,
                                    listitem=listitem,
                                    isFolder=folder)
예제 #13
0
def addcontent(url,fanart):
	url = url.lstrip('#podcast=')
	koding.dolog('adding podcast content url='+str(url),line_info=True)
	if url.startswith('http'):
		AddAllContent(url,fanart)
	elif url.startswith('episode'):
		url = url.lstrip('episode=')
		AddEpisodes(url,fanart)
def read(url):
    koding.dolog("read " + url)

    f = urllib2.urlopen(url)
    data = f.read()
    f.close()

    return data
def selector(option_list, title="Select one"):
    koding.dolog("selector title='" + title + "', options=" +
                 repr(option_list))

    dia = xbmcgui.Dialog()
    selection = dia.select(title, option_list)

    return selection
def get_setting(name):
    koding.dolog("get_setting name='" + name + "'")

    dev = __settings__.getSetting(name)

    koding.dolog("get_setting ->'" + str(dev) + "'")

    return dev
def doLogin(login_url):

    ''' to call login,source_data = weblogin.dologin(login_url)  

    login_url = site to login into e.g login_url = 'http://p.xxe.press/login.php'
    '''

    source_data = ''
    Addon_Name    = koding.Addon_Info(id='name')
    Addon_Version = koding.Addon_Info(id='version')
    Addon_Profile = koding.Addon_Info(id='profile')
    Cookie_Folder = os.path.join(Addon_Profile,'cookies')
    cookie_name = web.cookie_name_create(login_url)
    cookiepath = os.path.join(Cookie_Folder,str(cookie_name)+'.lwp')
    cookiepath =  koding.Physical_Path(cookiepath)
    username = koding.Addon_Setting('username')
    password = koding.Addon_Setting('password')

    #delete any old version of the cookie file
    try:
        os.remove(cookiepath)
    except:
        pass
    koding.dolog('UserName = %s %s Password = %s %s'%(username,len(username),password,len(password)),line_info=True)
    koding.dolog('cookiepath = %s'%cookiepath,line_info=True)
    if len(username) == 0  or len(password) == 0:
        yesno = koding.YesNo_Dialog(title=str(Addon_Name)+' Login for'+str(login_url),message='There is no UserName or Password set, would you like to set it now?')
        if yesno == True:
            koding.Open_Settings()
        else:
            return False
    if username and password:
        #the header used to pretend you are a browser
        header_string = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
	#build the form data necessary for the login
        login_data = urllib.urlencode({'username':username, 'password':password})
        #build the request we will make
        req = urllib2.Request(login_url, login_data)
        req.add_header('User-Agent',header_string)
        #initiate the cookielib class
        cj = cookielib.LWPCookieJar()
        #install cookielib into the url opener, so that cookies are handled
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        #do the login and get the response
        response = opener.open(req)
        source = response.read()
        source_data += str(source)
        response.close()
        #check the received html for a string that will tell us if the user is logged in
        #pass the username, which can be used to do this.
        login = check_login(source,username)
        #if login suceeded, save the cookiejar to disk
        if login == True:
            cj.save(cookiepath)
        #return whether we are logged in or not
        return login,source_data
    else:
        return False
예제 #18
0
def read_DB_col(filename, table, col):
    #read entire contents of a coloum
    conn = sqlite3.connect(filename)
    cursor = conn.cursor()
    cursor.execute('SELECT %s FROM %s' % (col, table))
    res = cursor.fetchall()
    for items in res:
        DB_list.append(items)
    koding.dolog('read_DB_col = %s' % DB_list, line_info=True)
예제 #19
0
def MyLists(name,url):
	Name = name.lower().lstrip('my').strip()
	content_type = 'movies' if 'movies' in Name else 'tv'
	list_type = Name.split(' ')[0]
	koding.dolog(url,line_info=True)
	session_id,apikey = url.split('+')
	BYBAPI.tmdb_my_lists(apikey,session_id,content_type,list_type)
	for items in BYBAPI.Details_list:
		addDir(items.get('title','Title Missing'),'tmdb='+items.get('ID',''),404,items.get('poster_path',icon_tmdb),items.get('backdrop_path',fanart_tmdb),items.get('overview',''),'',items.get('release_date',''),'','')
예제 #20
0
def read_DB_row_match(filename, table, row, match):
    conn = sqlite3.connect(filename)
    cursor = conn.cursor()
    match = (match, )
    cursor.execute("SELECT * FROM %s WHERE %s=?" % (table, row), match)
    res = cursor.fetchall()
    for matches in res:
        DB_list.append(matches)
    koding.dolog('read_DB_row_match = %s' % DB_list, line_info=True)
예제 #21
0
def Modes(mode):
	if mode==100:
		koding.dolog('Opening Settings',line_info=True)
		xbmcaddon.Addon().openSettings()
		xbmcplugin.endOfDirectory(int(sys.argv[1]))
	elif mode==101:
		koding.dolog('Clearing Cookies',line_info=True)
		clear_cookies()
		xbmcplugin.endOfDirectory(int(sys.argv[1]))
예제 #22
0
def tool_index():
    BYB.addDir_file('[COLOR red]Settings[/COLOR]', '', 100, paths.icon,
                    paths.fanart, '', '', '', '')
    BYB.addDir_file('[COLOR red]Clear Cached password[/COLOR]', '', 104,
                    paths.icon, paths.fanart, '', '', '', '')
    koding.dolog(settings.DEVMODE, line_info=True)
    if settings.DEVMODE == 'true':
        BYB.addDir_file('[COLOR red]Dev Mode tester[/COLOR]', '', 102,
                        paths.icon, paths.fanart, '', '', '', '')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
def message(text1, text2="", text3=""):
    koding.dolog("message text1='" + text1 + "', text2='" + text2 +
                 "', text3='" + text3 + "'")

    if text3 == "":
        xbmcgui.Dialog().ok(text1, text2)
    elif text2 == "":
        xbmcgui.Dialog().ok("", text1)
    else:
        xbmcgui.Dialog().ok(text1, text2, text3)
def find_single_match(text, pattern):
    koding.dolog("find_single_match pattern=" + pattern)

    result = ""
    try:
        matches = re.findall(pattern, text, flags=re.DOTALL)
        result = matches[0]
    except:
        result = ""

    return result
예제 #25
0
def DecodeUrl(url):
    try:
        DecodedUrl = base64.urlsafe_b64decode(url)
        return DecodedUrl
    except TypeError:
        koding.dolog('DecodeUrl url = {} TypeError = {}'.format(
            url, TypeError),
                     line_info=True)
    except:
        koding.dolog('DecodeUrl url = {} Unknown Error'.format(url),
                     line_info=True)
예제 #26
0
	def PlayMethod(self,url):
		if url.startswith('plugin://plugin'):
			playmethod='plugin'
		elif url.startswith('http'):
			playmethod = 'http'
		else:
			xbmc_executebuiltin.Notify(message='url format not correct',times=5000)
			koding.dolog('url format not correct %s'%url,line_info=True)
			playmethod = 'false'
		koding.dolog('PlayMethod = %s  %s'%(playmethod,url),line_info=True)
		return url,playmethod
예제 #27
0
def channel_search(url,fanart):
	search_item = koding.Keyboard(heading=SingleColor(local_string(30053),_Edit.DialogBoxColor1))
	koding.dolog('search item = %s'%search_item,line_info=True)
	YouTube_Scraper.channel_search(url,search_item)
	for items in YouTube_Scraper.CHANNEL_SEARCH:
		title = items.get('title','Title Missing')
		playlink = items.get('playlink','')
		icon = items.get('artwork','')
		date = items.get('date','')
		description = items.get('description','')
		BYB.addDir_file(ItemColor(title),playlink,33,icon,fanart,description,'',date,'')
 def Items(self, url, amount='all'):
     #pull a set amount of podcasts or all if amount is not determined (podcasts name,image,description,publish date and playlink)  in rss feed
     ParseRSS = feedparser.parse(url)
     feed = ParseRSS.feed
     entries = ParseRSS.entries
     if str(amount).isdigit():
         amount = int(amount)
         for i in range(amount):
             try:
                 image = self._ImageResolve(entries[i].image)
             except:
                 image = self._ImageResolve(feed.image)
             playlink = self._PlayLinkResolve(entries[i].links)
             date = self._DateResolve(entries[i].published)
             try:
                 description = entries[i].description
                 description = HTMLParser().unescape(description)
                 description = self._DescriptionClean(description)
             except:
                 description = ''
             self.ITEM.append({
                 'title': entries[i].title.encode('utf8'),
                 'image': image,
                 'description': description.encode('utf8'),
                 'date': date,
                 'playlink': playlink
             })
     elif amount == 'all':
         for entry in entries:
             try:
                 image = self._ImageResolve(entry.image)
             except:
                 image = self._ImageResolve(feed.image)
             playlink = self._PlayLinkResolve(entry.links)
             date = self._DateResolve(entry.published)
             try:
                 description = entry.description
                 description = HTMLParser().unescape(description)
                 description = self._DescriptionClean(description)
             except:
                 description = ''
             self.ITEM.append({
                 'title': entry.title.encode('utf8'),
                 'image': image,
                 'description': description.encode('utf8'),
                 'date': date,
                 'playlink': playlink
             })
     else:
         pass
         koding.dolog(
             'Podcast RSS Feed Wrong value entered for amount must be int value entered ='
             + str(amount) + ' Url of rss = ' + str(url),
             line_info=True)
예제 #29
0
def search(search_item=None):
	if search_item == None:
		search_item = koding.Keyboard(heading=SingleColor(local_string(30053),_Edit.DialogBoxColor1))
		koding.dolog('search item = %s'%search_item,line_info=True)
	fanart = addon_fanart if _Edit.YT_SearchFanart == '' else _Edit.YT_SearchFanart
	YouTube_Scraper.search(search_item)
	for items in YouTube_Scraper.SEARCH_VIDEO:
		title = items.get('title','Title Missing')
		playlink = items.get('playlink','')
		icon = items.get('icon')
		BYB.addDir_file(ItemColor(title),playlink,33,icon,fanart,'','','','')
def message_yes_no(text1, text2="", text3=""):
    koding.dolog("message_yes_no text1='" + text1 + "', text2='" + text2 +
                 "', text3='" + text3 + "'")

    if text3 == "":
        yes_pressed = xbmcgui.Dialog().yesno(text1, text2)
    elif text2 == "":
        yes_pressed = xbmcgui.Dialog().yesno("", text1)
    else:
        yes_pressed = xbmcgui.Dialog().yesno(text1, text2, text3)

    return yes_pressed
예제 #31
0
def get_list(url):
    """display jen list"""
    global content_type
    jen_list = JenList(url)
    if not jen_list:
        koding.dolog(_("returned empty for ") + url)
    items = jen_list.get_list()
    content = jen_list.get_content_type()
    if items == []:
        return False
    if content:
        content_type = content
    display_list(items, content_type)
    return True
예제 #32
0
def get_info(items, dialog=None):
    from resources.lib.util.xml import JenItem
    result = run_hook("get_info", items, dialog)
    if result:
        return result
    koding.reset_db()
    info = []
    num_items = len(items)
    for index, item_xml in enumerate(items):
        if dialog:
            if dialog.iscanceled():
                dialog.close()
                break
            percent = ((index + 1) * 100) / num_items
            dialog.update(percent, _("processing metadata"),
                          "%s of %s" % (index + 1, num_items))
        if type(item_xml) == dict:
            item = item_xml
        else:
            item = JenItem(item_xml)
        item_info = {}
        content = item.get("content", "")
        try:
            if content == "movie":
                item_info = get_movie_metadata(item["imdb"])
            elif content in ["tvshow", "season"]:
                item_info = get_show_metadata(item["imdb"])
            elif content == "episode":
                item_info = get_episode_metadata(item["imdb"], item["season"],
                                                 item["episode"])
            if type(item_info) == list:
                item_info = {}
            if not item_info.get("plotoutline", None):
                item_info["plotoutline"] = item_info.get("plot", "")
        except Exception as e:
            koding.dolog("info error: " + repr(e))
        summary = item.get("summary", False)
        if summary:
            if not item_info or type(item_info) != dict:
                item_info = {}
            item_info["plot"] = summary
            item_info["manual"] = True

        info.append(item_info)
    if dialog:
        dialog.close()
    tvdb.clear_cache()
    return info
예제 #33
0
파일: url.py 프로젝트: vphuc81/MyRepository
def __replace_gif(url):
    """ put gifs in local cache
    try to put gif in cache to enable motion
    Keyword Arguments:
    url -- url pointing to gif
    """
    if not url.endswith(".gif"):
        return url
    else:
        base_folder = xbmcaddon.Addon().getSetting("cache_folder")
        dest_folder = os.path.join(xbmc.translatePath(base_folder), "artcache")
        xbmcvfs.mkdirs(dest_folder)
        parts = url.split("/")
        dest = xbmc.makeLegalFilename(
            # TODO make sure this is unique
            os.path.join(dest_folder, parts[-2] + parts[-1]))
        if not xbmcvfs.exists(dest):
            try:
                response = requests.get(url, timeout=10, verify=False)
            except:
                return None
            if response.status_code == 200:
                with open(dest, 'wb') as out_file:
                    data = response.content
                    response.close()
                    out_file.write(data)
                    # shutil.copyfileobj(response.raw, out_file)
                    del data
                    del response
                if os.path.getsize(dest) == 0:
                    koding.dolog("0 size gif: " + repr(dest))
                    os.remove(dest)
                    return None
                else:
                    koding.dolog("size: " + repr(os.path.getsize(dest)))
            else:
                koding.Text_Box(xbmcaddon.Addon().getAddonInfo('name'),
                                _("gif not found: ") + url)
                return None
        xbmc.log("gif done: " + repr(dest))
        return dest
예제 #34
0
    def set_theme(theme):
        """set jen theme"""
        import random
        theme_list = run_hook("get_theme_list")

        if theme.lower() == "user":
            user_theme_folder = os.path.join(
                xbmc.translatePath(
                    xbmcaddon.Addon().getSetting("cache_folder")),
                "theme")
            if os.path.isdir(user_theme_folder):
                user_files = []
                for ufile in os.listdir(user_theme_folder):
                    if os.path.isfile(os.path.join(user_theme_folder, ufile)):
                        user_files.append(
                            os.path.join(user_theme_folder, ufile))
                theme_list["user"] = user_files
            else:
                koding.dolog("huh?: " + repr(theme))
                return xbmcaddon.Addon().getAddonInfo('fanart')
        return replace_url(random.choice(theme_list[theme.lower()]))
예제 #35
0
 def __init__(self, url, cached=True):
     if cached:
         xml = run_hook("get_xml", url)
     else:
         xml = run_hook("get_xml_uncached", url)
     if not xml:
         if url.endswith(".xml") or url.startswith("http"):
             try:
                 xml = requests.get(url).content
             except Exception as e:
                 xml = None
                 koding.dolog("error: " + repr(e))
                 koding.dolog("url: " + repr(url))
                 koding.dolog("#####################")
         else:
             xml = url
     if xml:
         self.xml = xml
         self.content = ""
         self.list = JenList.list_pattern.findall(xml)
         info = JenItem(xml.split('<item>')[0].split('<dir>')[0])
         intro = info.get("intro", "")
         if intro:
             import resources.lib.sources as sources
             sources.get_sources(intro)
         self.playlister = info.get('poster', '0')
         self.list_image = replace_url(info.get("animated_thumbnail", ""))
         if not self.list_image:
             self.list_image = replace_url(
                 info.get('thumbnail', ADDON.getAddonInfo('icon')))
         self.list_fanart = replace_url(info.get("animated_fanart", ""))
         if not self.list_fanart:
             self.list_fanart = replace_url(info.get('fanart', "0"))
         if self.list_fanart == "0":
             theme = xbmcaddon.Addon().getSetting('theme')
             if theme and theme != 'DEFAULT' and theme != 'none':
                 self.list_fanart = self.set_theme(theme)
             else:
                 self.list_fanart = xbmcaddon.Addon().getAddonInfo('fanart')
         self.metadata = {}
     else:
         self.list = []
예제 #36
0
def do_search(term=None):
    import os
    import xbmc
    import xbmcgui
    import time
    import datetime
    import urllib2
    import shutil

    search_term = term.lower()

    result = run_hook("do_search", search_term)
    if result:
        display_list(result, "videos")
        return
    jenlist = JenList("")
    jenlist.list_image = xbmcaddon.Addon().getAddonInfo('icon')
    theme = xbmcaddon.Addon().getSetting('theme')
    if theme and theme != 'DEFAULT' and theme != 'none':
        jenlist.list_fanart = jenlist.set_theme(theme)
    else:
        jenlist.list_fanart = xbmcaddon.Addon().getAddonInfo('fanart')
    result_list = []
    exact_result_list = []
    item_xml_result_list = []
    exact_item_xml_result_list = []
    dest_file = os.path.join(xbmc.translatePath(
        xbmcaddon.Addon().getSetting("cache_folder")), "search.db")

    url = __builtin__.search_db_location
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    try:
        changed = response.headers["Last-Modified"]
        changed_struct = time.strptime(changed, "%a, %d %b %Y %H:%M:%S GMT")
        epoch_changed = int(time.mktime(changed_struct))
        if not os.path.exists(dest_file) or \
           int(os.path.getmtime(dest_file)) < epoch_changed:
            dp = xbmcgui.DialogProgress()
            dp.create(_('Loading database file'), _('Please Wait'))
            if response.getcode() == 200:
                with open(dest_file, 'wb') as out_file:
                    shutil.copyfileobj(response, out_file)
                if os.path.getsize(dest_file) == 0:
                    koding.dolog("0 size db: " + repr(dest_file))
                    os.remove(dest_file)
            dp.close()
    except:  # server down
        if not os.path.exists(dest_file):
            import xbmcgui
            addon_name = xbmcaddon.Addon().getAddonInfo('name')
            xbmcgui.Dialog().ok(addon_name, _("no local file found, and server seems down"))
            dp.close()
    response.close()

    results = koding.DB_Query(dest_file, 'SELECT * from search where item like "%%%s%%"' % search_term)
    for result in results:
        item = jenlist.process_item(result["item"])
        playlister = result["poster"]
        title = item["label"].lower()
        if search_term in title:
            item["info"] = {}
            try:
                item['label'] = '{0} - {1}'.format(playlister,
                                                   item["label"])
            except:
                import xbmc
                koding.dolog("playlister: " + repr(playlister))
                koding.dolog("label:" + repr(item["lable"]))
                koding.dolog("item: " + repr(item))
                raise Exception()
            if title.startswith(search_term + " "):
                exact_result_list.append(item)
                exact_item_xml_result_list.append(result["item"])
                continue
            result_list.append(item)
            item_xml_result_list.append(result["item"])
    meta = xbmcaddon.Addon().getSetting("metadata") == "true"
    if meta:
        # TODO find way to get it all in single cal
        info = get_info(exact_item_xml_result_list)
        if info:
            for index, item in enumerate(exact_result_list):
                item["info"].update(info[index])

        info = get_info(item_xml_result_list)
        if info:
            for index, item in enumerate(result_list):
                item["info"].update(info[index])
    exact_result_list = sorted(exact_result_list,
                               key=lambda item: title)
    exact_result_list.extend(sorted(result_list,
                                    key=lambda item: title))
    display_list(exact_result_list, "videos")
예제 #37
0
파일: xml.py 프로젝트: vphuc81/MyRepository
# -*- coding: utf-8 -*-
예제 #38
0
    def process_item(self, item_xml):
        hook_result = run_hook("process_item", item_xml)
        if hook_result:
            if hook_result.get("content", ""):
                self.content = hook_result["content"]
            return hook_result
        try:
            is_widget = __builtin__.JEN_WIDGET
        except:
            is_widget = False
        item = JenItem(item_xml)
        enable_gifs = xbmcaddon.Addon().getSetting('enable_gifs') == "true"
        if item.item_string.startswith("<item>"):
            title = item["title"]
            if title == "":
                title = item["name"]
                koding.dolog("depricated: <name>")
                koding.dolog("name: " + repr(title))
                koding.dolog("Use <title> instead of <name> in your xml")
                koding.dolog("#####################")
            try:
                title = xbmcaddon.Addon().getLocalizedString(int(title))
            except ValueError:
                pass
            is_playable = True
            mode = "get_sources"
            link = item_xml
        elif item.item_string.startswith("<dir>"):
            title = item["name"]
            if title == "":
                title = item["title"]
            try:
                title = xbmcaddon.Addon().getLocalizedString(int(title))
            except ValueError:
                pass
            if item["link"].startswith("message"):
                is_playable = True
                mode = "message"
                link = item["link"].replace("message(", "")[:-1]
                if link.startswith("http"):
                    text = requests.request("GET", replace_url(link), verify=False).content
                    link = text
            else:
                is_playable = False
                mode = "get_list"
                link = item["link"]
        elif item.item_string.startswith("<plugin>"):
            link = item["link"]
            title = item["name"]
            if title == "":
                title = item["title"]
            try:
                title = xbmcaddon.Addon().getLocalizedString(int(title))
            except ValueError:
                pass
            if link.endswith("openSettings"):
                is_playable = True
                link = ""
                mode = "Settings"
            elif link.endswith("developer"):
                import os
                is_playable = False
                link = '{"file_name":"testings.xml"}'
                mode = "Testings"
                path = xbmcaddon.Addon().getAddonInfo('profile')
                profile_path = xbmc.translatePath(path).decode('utf-8')
                test_file = os.path.join(profile_path, "testings.xml")
                if not os.path.exists(test_file):
                    return
            elif link.endswith("search"):
                is_playable = False
                link = ""
                mode = "Search"
            else:
                if "youtube" in link and ("user" in link or "playlist" in link):
                    is_playable = True
                    mode = 'get_sources'
                    link = item_xml
                else:
                    is_playable = True
                    mode = 'get_sources'
                    link = item_xml
        else:
            koding.dolog("other: " + repr(item), xbmc.LOGDEBUG)
            raise Exception()

        # filter out "unreleased"
        if title == "" or " /title" in title or "/ title" in title:
            return

        if is_widget:
            if mode == "message":
                return

        context = get_context_items(item)

        content = item["content"]
        if content == "boxset":
            content = "set"
        if content != '':
            self.content = content
        imdb = item["imdb"]
        season = item["season"] or '0'
        episode = item["episode"] or '0'
        year = item["year"] or '0'
        fanart = None
        if enable_gifs:
            fan_url = item.get("animated_fanart", "")
            if fan_url and fan_url != "0":
                fanart = replace_url(fan_url)
        if not fanart:
            fanart = replace_url(
                item.get("fanart", self.list_fanart), replace_gif=False)
        thumbnail = None
        if enable_gifs:
            thumb_url = item.get("animated_thumbnail", "")
            if thumb_url and thumb_url != "0":
                thumbnail = replace_url(thumb_url)
        if not thumbnail:
            thumbnail = replace_url(
                item.get("thumbnail", self.list_image), replace_gif=False)

        premiered = item.get("premiered", "")
        if premiered:
            try:
                today_tt = datetime.date.today().timetuple()
                premiered_tt = time.strptime(premiered, "%Y-%m-%d")
                if today_tt < premiered_tt:
                    title = "[COLORyellow]" + title + "[/COLOR]"
            except:
                koding.dolog("wrong premiered format")
                pass
        result_item = {
            'label': title,
            'icon': thumbnail,
            'fanart': fanart,
            'mode': mode,
            'url': link,
            'folder': not is_playable,
            'imdb': imdb,
            'content': content,
            'season': season,
            'episode': episode,
            'info': {},
            'year': year,
            'context': context,
            'plot': item.get("summary", None),
            "summary": item.get("summary", None)
        }
        if fanart:
            result_item["properties"] = {'fanart_image': fanart}
            result_item['fanart_small'] = fanart

        if content in ['movie', 'episode']:
            # only add watched data for applicable items
            result_item['info']['watched'] = 0
        return result_item
예제 #39
0
def get_sources(item):
    """
    get video_link and try to play it
    Keyword Arguments:
    item -- JenItem to try playing
    """
    result = run_hook("get_sources", item)
    if result:
        return
    if item.startswith("<plugin>"):
        # link to plugin
        link = JenItem(item)["link"]
        sublinks = JenItem(link).getAll("sublink")
        if sublinks:
            if len(sublinks) > 1:
                link = choose_quality(link)
            else:
                link = sublinks[0]
        link = link.replace("&amp;", "&")
        xbmc.executebuiltin('Container.update(' + link + ')')
        return
    item = JenItem(item)

    link = item["link"]
    if not link or link.replace("\t", "") == "":
        return
    meta = JenItem(item["meta"])
    title = meta["title"]
    year = meta.get("year", '').split("-")[0].strip()
    imdb = meta.get("imdb", "")
    tvdb = meta.get("tvdb", "")
    season = meta.get("season", "")
    episode = meta.get("episode", "")
    tvshowtitle = meta.get("tvshowtitle", None)
    premiered = meta.get("premiered", "")
    try:
        premiered = premiered.split("-")[0].strip()
    except:
        if len(premiered) == 4:
            pass
        elif not premiered:
            pass
        else:
            koding.dolog("wrong premiered format")
    busy_dialog = xbmcgui.DialogProgress()
    dialog = xbmcgui.Dialog()
    icon = ADDON.getAddonInfo('icon')

    jenplayer = JenPlayer(resume=False)
    try:
        spec = {
            "identifier": imdb,
            "season": season or "0",
            "episode": episode or "0"
        }
        match = koding.Get_From_Table("watched", spec)
        if match:
            match = match[0]
            if match["currentTime"] and not match["currentTime"] == "0":
                if dialog.yesno(ADDON.getAddonInfo("name"),
                                _("Previous playback detected"),
                                yeslabel=_("Resume"),
                                nolabel=_("Restart")):
                    jenplayer = JenPlayer(resume=True)
    except:
        pass

    jenplayer.setItem(item)

    busy_dialog.create(xbmcaddon.Addon().getAddonInfo('name'),
                       _("Processing Link"))
    preset = choose_quality(link)
    message = get_searching_message(preset)
    played = False
    infolabels = {}
    if preset:
        preset = preset.replace("&amp;", "&")
        busy_dialog.update(0, message)
        listitem = None
        fetch_meta = ADDON.getSetting("metadata") == "true"
        listitem = xbmcgui.ListItem(
            path=link,
            iconImage=item.get("thumbnail", icon),
            thumbnailImage=item.get("thumbnail", icon))
        infolabels = {}
        if fetch_meta and imdb != "0":  # only try valid items with imdb
            try:
                info, created = get_info([item.item_string])
                if info and type(info) == dict:
                    infolabels = info
            except:
                pass
        else:
            infolabels["title"] = title
            infolabels["name"] = title
        if "plotoutline" not in infolabels:
            infolabels["plotoutline"] = infolabels.get("plot", "")
        if item.get("content", "") == "song":
            listitem.setInfo(type='Music',
                             infoLabels={'title': meta.get("title", ""),
                                         'artist': meta.get("artist", "")})
        else:
            listitem.setInfo(type="video", infoLabels=infolabels)
            listitem.setLabel(item.get("title", item.get("name", "")))

        if "search" in preset:
            exclude_scrapers_content = item.get("exclude_scrapers", "")
            if exclude_scrapers_content:
                exclude_scrapers = exclude_scrapers_content.split(";")
            else:
                exclude_scrapers = None
            # nanscraper link
            if item.get("content", "") == "song":
                artist = item.get("artist", "")
                played = Sources.get_music_sources(title, artist,
                                                   preset=preset,
                                                   dialog=busy_dialog,
                                                   exclude=exclude_scrapers,
                                                   listitem=listitem,
                                                   player=jenplayer)
            else:
                played = Sources.get_sources(
                    title,
                    year,
                    imdb,
                    tvdb,
                    season,
                    episode,
                    tvshowtitle,
                    premiered,
                    preset=preset,
                    dialog=busy_dialog,
                    listitem=listitem,
                    exclude=exclude_scrapers,
                    player=jenplayer)
        elif preset.startswith("http") or preset.startswith("plugin"):
            # direct link
            if "/playlist" in preset and "youtube" in preset:
                busy_dialog.close()
                xbmc.executebuiltin('Container.update(' + preset + ')')
                return
            elif "plugin://plugin.video.youtube/play/?video_id=" in preset:
                xbmc.executebuiltin("PlayMedia(%s)" % preset)
                played = True
            elif item["content"] == "image":
                busy_dialog.close()
                xbmc.executebuiltin("ShowPicture(%s)" % preset)
                played = True
            else:
                played = koding.Play_Video(
                    preset,
                    showbusy=False,
                    ignore_dp=True,
                    item=listitem,
                    player=jenplayer,
                    resolver=resolveurl)
        else:
            # who knows
            busy_dialog.close()
            koding.dolog("unknown link type: " + repr(preset))
            raise Exception()
    busy_dialog.close()
    if played:
        jenplayer.keep_alive()