Exemplo n.º 1
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)
Exemplo n.º 2
0
def fetch_from_db(url):
    koding.reset_db()
    pcastone_plugin_spec = {
        "columns": {
            "url": "TEXT",
            "item": "TEXT",
            "created": "TEXT"
        },
        "constraints": {
            "unique": "url"
        }
    }
    koding.Create_Table("pcastone_com_plugin", pcastone_plugin_spec)
    match = koding.Get_From_Table(
        "pcastone_com_plugin", {"url": url})
    if match:
        match = match[0]
        if not match["item"]:
            return None
        created_time = match["created"]
        if created_time and float(created_time) + CACHE_TIME >= time.time():
            match_item = match["item"]
            try:
                result = base64.b64decode(match_item)
            except:
                return None
            return result
        else:
            return
    else:
        return 
Exemplo n.º 3
0
def get_xml(link):
    import time
    xml_cache_spec = {
        "columns": {
            "xml": "TEXT",
            "link": "TEXT",
            "created": "TEXT",
            "changed": "TEXT"
        },
        "constraints": {
            "unique": "link"
        }
    }
    koding.Create_Table("xml_cache", xml_cache_spec)

    url = replace_url(link)
    req = requests.get(url, verify=False)
    changed = req.headers["Last-Modified"]
    result = koding.Get_From_Table("xml_cache", {"link": link})
    if result:
        if result[0]["changed"] == changed:
            return result[0]["xml"]
        else:
            koding.Remove_From_Table("xml_cache", {"link": link})
    xml = req.content
    koding.Add_To_Table("xml_cache", {
        "xml": xml,
        "link": link,
        "created": time.time(),
        "changed": changed
    })
    return xml
Exemplo n.º 4
0
def fetch_from_db(url):
    koding.reset_db()
    lastfm_plugin_spec = {
        "columns": {
            "url": "TEXT",
            "item": "TEXT",
            "created": "TEXT"
        },
        "constraints": {
            "unique": "url"
        }
    }
    koding.Create_Table("lastfm_plugin", lastfm_plugin_spec)
    match = koding.Get_From_Table("lastfm_plugin", {"url": url})
    if match:
        match = match[0]
        if not match["item"]:
            return None
        created_time = match["created"]
        if created_time and float(created_time) + float(
                CACHE_TIME) >= time.time():
            match_item = match["item"].replace("'", "\"")
            return pickle.loads(match_item)
        else:
            return []
    else:
        return []
Exemplo n.º 5
0
def fetch_from_db(url):
    koding.reset_db()
    tmdb_plugin_spec = {
        "columns": {
            "url": "TEXT",
            "item": "TEXT",
            "created": "TEXT"
        },
        "constraints": {
            "unique": "url"
        }
    }
    koding.Create_Table("tmdb_plugin", tmdb_plugin_spec)
    match = koding.Get_From_Table(
        "tmdb_plugin", {"url": url})
    if match:
        match = match[0]
        if not match["item"]:
            return None
        created_time = match["created"]
        if created_time and float(created_time) + CACHE_TIME >= time.time():
            match_item = match["item"].replace("'", "\"")
            try:
                match_item = match_item.encode('ascii', 'ignore')
            except:
                match_item = match_item.decode('utf-8').encode('ascii', 'ignore')
            return pickle.loads(match_item)
        else:
            return []
    else:
        return []
Exemplo n.º 6
0
def set_list_view_mode(content):
    skin = xbmc.getSkinDir()
    koding.reset_db()
    match = koding.Get_From_Table("addonviews", {
        "skin": skin,
        "content": content
    })
    if match:
        match = match[0]
        xbmc.executebuiltin('Container.SetViewMode(%s)' % str(match["viewid"]))
Exemplo n.º 7
0
def fetch_episode_from_db(identifier, season, episode, provider, lang):
    """
    get episode's meta info from database
    Args:
        identifier: identifier of the item
        season: season number of the episode
        episode: episode number of the episode
        provider: metadata provider to fetch info for
        lang: language to fetch info for
    Returns:
        item's metadata
    """
    import koding

    versionspec = {"columns": {"version": "TEXT"}}
    koding.Create_Table("version", versionspec)
    if not koding.Get_All_From_Table("version"):
        koding.Add_To_Table("version", {"version": "0.0.1"})

    episode_meta_spec = {
        "columns": {
            "identifier": "TEXT",
            "season": "TEXT",
            "episode": "TEXT",
            "provider": "TEXT",
            "lang": "TEXT",
            "meta": "TEXT",
            "created": "TEXT"
        },
        "constraints": {
            "unique": "identifier, provider, lang",
        }
    }
    koding.Create_Table("episode_meta", episode_meta_spec)
    match = koding.Get_From_Table(
        "episode_meta", {
            "identifier": identifier,
            "provider": provider,
            "season": season,
            "episode": episode,
            "lang": lang
        })
    if match:
        match = match[0]
        if not match["meta"]:
            return None, match["created"]
        match_meta = match["meta"].replace("'", "\"")
        try:
            match_meta = match_meta.encode('ascii', 'ignore')
        except:
            match_meta = match_meta.decode('utf-8').encode('ascii', 'ignore')
        return pickle.loads(match_meta), match["created"]
    else:
        return [], None
Exemplo n.º 8
0
def fetch_from_db(url):
    koding.reset_db()
    trakt_plugin_spec = {
        "columns": {
            "url": "TEXT",
            "item": "TEXT",
            "content_type": "TEXT",
            "created": "TEXT"
        },
        "constraints": {
            "unique": "url"
        }
    }
    koding.Create_Table("trakt_plugin", trakt_plugin_spec)
    match = koding.Get_From_Table("trakt_plugin", {"url": url})
    if match:
        match = match[0]
        if not match["item"]:
            return None
        created_time = match["created"]
        if "tmdb" in url:
            if created_time and float(
                    created_time) + CACHE_TMDB_TIME >= time.time():
                match_item = match["item"].replace("'", "\"")
                try:
                    match_item = match_item.encode('ascii', 'ignore')
                except:
                    match_item = match_item.decode('utf-8').encode(
                        'ascii', 'ignore')
                result = pickle.loads(match_item)
                if type(result) == str and result.startswith("{"):
                    result = eval(result)
                return result
        if created_time and float(created_time) + float(
                CACHE_TIME) >= time.time():
            match_item = match["item"].replace("'", "\"")
            content_type = match["content_type"]
            try:
                match_item = match_item.encode('ascii', 'ignore')
            except:
                match_item = match_item.decode('utf-8').encode(
                    'ascii', 'ignore')
            return (pickle.loads(match_item), content_type)
        else:
            return []
    else:
        return []
Exemplo n.º 9
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") or preset.endswith('.torrent') or preset.startswith('magnet'):
            # 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()
Exemplo n.º 10
0
    def get_list(self, input_list=None, skip_meta=False, skip_dialog=False):
        """
        returns the list of items in a format suitable for kodiswift
        Returns:
        list of jen items
        """
        items = []
        meta = ADDON.getSetting("metadata") == "true"
        try:
            is_widget = __builtin__.JEN_WIDGET
        except:
            is_widget = False
        if is_widget:
            skip_dialog = True
        if input_list is None:
            input_list = self.list

        xbmc.log("input_list: " + repr(input_list))

        dialog = None
        dialog2 = None

        if not skip_dialog:
            if ADDON.getSetting("disable_metadata_dialog") == "false":
                dialog = xbmcgui.DialogProgress()
                addon_name = ADDON.getAddonInfo("name")
                dialog.create(addon_name, _("Loading items"))

        if meta and not skip_meta:
            info_thread = threadWithReturn(target=get_info,
                                           args=(input_list, dialog))
            info_thread.start()
        else:
            info_thread = None

        num_items = len(input_list)
        for index, item_xml in enumerate(input_list):
            if dialog2:
                percent = ((index + 1) * 100) / num_items
                dialog2.update(percent,
                               _("[COLORorange]processing item[/COLOR]"),
                               "%s of %s" % (index + 1, num_items))
            result_item = self.process_item(item_xml)
            if result_item:
                items.append(result_item)
        if dialog2:
            dialog2.close()

        if info_thread:
            info = info_thread.join()  # wait till for thread to finish
            if info:
                skip = 0
                for index, item in enumerate(items):
                    if not item.get("summary", None) and not item.get(
                            "imdb", None):
                        continue
                    if index <= len(info) - 1:
                        for info_item in info[index + skip:]:
                            if not info_item:
                                break
                            if info_item.get("manual", ""):
                                item["info"]["plot"] = info_item["plot"]
                                break
                            if "imdb_id" in info_item:
                                if info_item["imdb_id"] == item["imdb"]:
                                    item["info"].update(info_item)
                                    break
                                else:
                                    skip = skip + 1
                            else:
                                break
                    else:
                        break

        for item in items:
            if not item.get("imdb", ""):
                continue
            match = koding.Get_From_Table(
                "watched", {
                    "identifier": item["imdb"],
                    "season": item["season"],
                    "episode": item["episode"]
                })
            if match:
                match = match[0]
                if match["watched"] and match["watched"] == "1":
                    item["info"]["playcount"] = 1
                    item["info"]["watched"] = 1

        if ADDON.getSetting("trailer_context") == "true":
            for item in items:
                if "trailer" in item["info"]:
                    try:
                        item["context"].append(
                            (_("Trailer"),
                             "PlayMedia({0})".format(item["info"]["trailer"])))
                    except:
                        pass
        return items
Exemplo n.º 11
0
# -*- coding: utf-8 -*-
Exemplo n.º 12
0
# -*- coding: utf-8 -*-
Exemplo n.º 13
0
 def get_cached(self, url, cached=True):
     if not url.startswith("http"):
         return
     if __builtin__.BOB_BASE_DOMAIN not in url and "norestrictions" not in url:
         return requests.get(url).content
     xml_cache_spec = {
         "columns": {
             "url": "TEXT",
             "xml": "TEXT",
             "cache_time": "TEXT",
             "created": "TEXT"
         },
         "constraints": {
             "unique": "url"
         }
     }
     koding.Create_Table("xml_cache", xml_cache_spec)
     if not cached:
         koding.dolog("uncached requested")
         response = requests.get(url, verify=False)
         xml = response.content
         response.close()
     else:
         match = koding.Get_From_Table("xml_cache", {"url": url})
         if match:
             koding.dolog("match: " + repr(match))
             match = match[0]
             created_time = float(match["created"])
             cache_time = int(match["cache_time"])
             koding.dolog("expire time: " + repr(created_time + cache_time))
             koding.dolog("created_time: " + repr(created_time))
             koding.dolog("now: " + repr(time.mktime(time.gmtime())))
             if time.mktime(time.gmtime()) <= created_time + cache_time:
                 koding.dolog("loading from cache, cache time not reached")
                 return pickle.loads(match["xml"])
             else:
                 try:
                     response = requests.get(url, verify=False, timeout=10)
                     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 epoch_changed < created_time:
                         koding.dolog(
                             "loading from cache, list not changed")
                         #xml = pickle.loads(match["xml"])
                         xml = response.content
                         response.close()
                     else:
                         koding.dolog("refreshing content")
                         xml = response.content
                         response.close()
                 except Exception as e:
                     koding.dolog("cache error: " + repr(e))
                     return pickle.loads(match["xml"])
         else:
             koding.dolog("initial load")
             response = requests.get(url, verify=False)
             xml = response.content
             response.close()
     if not xml:
         xbmcgui.Dialog().notification(ADDON.getAddonInfo("name"),
                                       "Server under high load, try again")
         return ""
     info = JenItem(xml.split('<item>')[0].split('<dir>')[0])
     cache_time = int(info.get("cache", 21600))
     koding.dolog("cache_time: " + repr(cache_time))
     created_time = time.mktime(time.gmtime())
     try:
         koding.Remove_From_Table("xml_cache", {
             "url": url,
         })
     except Exception, e:
         koding.dolog("Database error: " + repr(e))