Exemplo n.º 1
0
 def __init__(self):
     xbmc.Player.__init__(self, xbmc.Player())
     if REAL_SETTINGS.getSetting("TraktDisable") == 'true':
         xbmcgui.Window(10000).setProperty('script.trakt.paused', 'true')
Exemplo n.º 2
0
__addon__ = xbmcaddon.Addon()
__path__ = __addon__.getAddonInfo('path')
__icon__ = os.path.join(xbmc.translatePath(__path__), 'resources', 'skins',
                        'Default', 'media', 'icon.png')
__icon2__ = os.path.join(xbmc.translatePath(__path__), 'resources', 'skins',
                         'Default', 'media', 'icon_alert.png')
__profiles__ = __addon__.getAddonInfo('profile')
__LS__ = __addon__.getLocalizedString

TEMP_STORAGE_CALENDARS = os.path.join(xbmc.translatePath(__profiles__),
                                      'calendars.json')
TEMP_STORAGE_NOTIFICATIONS = os.path.join(xbmc.translatePath(__profiles__),
                                          'notifications.json')

if t.getAddonSetting('show_onstart', sType=t.BOOL):
    xbmcgui.Window(10000).setProperty('reminders', '1')
else:
    xbmcgui.Window(10000).setProperty('reminders', '0')

_cycle = 0

try:
    googlecal = Calendar()
    while xbmcgui.Window(10000).getProperty('reminders') == '1':
        now = datetime.utcnow().isoformat() + 'Z'
        timemax = (datetime.utcnow() + relativedelta.relativedelta(
            months=t.getAddonSetting('timemax', sType=t.NUM))
                   ).isoformat() + 'Z'
        events = googlecal.get_events(
            TEMP_STORAGE_NOTIFICATIONS,
            now,
Exemplo n.º 3
0
def hideCancelButton():
    xbmc.sleep(250)
    WINDOW_PROGRESS = xbmcgui.Window(10101)
    CANCEL_BUTTON   = WINDOW_PROGRESS.getControl(10)
    CANCEL_BUTTON.setVisible(False)
Exemplo n.º 4
0
import xbmc
import xbmcgui
import xbmcaddon
from BaseClasses import *
from dialogs.DialogBaseInfo import DialogBaseInfo
from OnClickHandler import OnClickHandler
from common import *
from WindowManager import wm

ch = OnClickHandler()
ADDON = xbmcaddon.Addon()
ADDON_ID = ADDON.getAddonInfo('id')
ADDON_PATH = ADDON.getAddonInfo('path').decode("utf-8")
ADDON_DATA_PATH = xbmc.translatePath("special://profile/addon_data/%s" %
                                     ADDON_ID).decode("utf-8")
HOME = xbmcgui.Window(10000)
MOVIE_DATA_PATH = "D:/"
C_PANEL_T9 = 9090
C_LIST_SEARCH_ONE = 9091
C_LIST_SEARCH_TWO = 9092
C_LABEL_KEYWORD = 312
C_BUTTON_CLEAR = 261
C_BUTTON_DEL = 262
LIST_BUTTONS = [60101, 60102, 60103, 60104, 60105]
ACTION_PREVIOUS_MENU = [9, 92, 10]
LIST_KEYBOARD = [
    201, 202, 203, 204, 205, 206, 211, 212, 213, 214, 215, 216, 221, 222, 223,
    224, 225, 226, 231, 232, 233, 234, 235, 236, 241, 242, 243, 244, 245, 246,
    251, 252, 253, 254, 255, 256
]
Exemplo n.º 5
0
    def onAVStarted(self):
        xbmc.sleep(1000)
        self.type = None
        self.id = None

        # take the user start scrobble offset into account
        scrobbleStartOffset = kodiUtilities.getSettingAsInt(
            'scrobble_start_offset') * 60
        if scrobbleStartOffset > 0:
            waitFor = 10
            waitedFor = 0
            # check each 10 seconds if we can abort or proceed
            while scrobbleStartOffset > waitedFor:
                waitedFor += waitFor
                time.sleep(waitFor)
                if not self.isPlayingVideo():
                    logger.debug(
                        '[traktPlayer] Playback stopped before reaching the scrobble offset'
                    )
                    return

        # only do anything if we're playing a video
        if self.isPlayingVideo():
            # get item data from json rpc
            activePlayers = kodiUtilities.kodiJsonRequest({
                "jsonrpc": "2.0",
                "method": "Player.GetActivePlayers",
                "id": 1
            })
            logger.debug("[traktPlayer] onAVStarted() - activePlayers: %s" %
                         activePlayers)
            playerId = int(activePlayers[0]['playerid'])
            logger.debug(
                "[traktPlayer] onAVStarted() - Doing Player.GetItem kodiJsonRequest"
            )
            result = kodiUtilities.kodiJsonRequest({
                'jsonrpc': '2.0',
                'method': 'Player.GetItem',
                'params': {
                    'playerid': playerId
                },
                'id': 1
            })
            if result:
                logger.debug("[traktPlayer] onAVStarted() - %s" % result)
                # check for exclusion
                _filename = None
                try:
                    _filename = self.getPlayingFile()
                except:
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Exception trying to get playing filename, player suddenly stopped."
                    )
                    return

                if kodiUtilities.checkExclusion(_filename):
                    logger.debug(
                        "[traktPlayer] onAVStarted() - '%s' is in exclusion settings, ignoring."
                        % _filename)
                    return

                self.type = result['item']['type']

                data = {'action': 'started'}

                if (kodiUtilities.getSettingAsBool('scrobble_mythtv_pvr')):
                    logger.debug(
                        '[traktPlayer] Setting is enabled to try scrobbling mythtv pvr recording, if necessary.'
                    )

                # check type of item
                if 'id' not in result['item']:
                    # do a deeper check to see if we have enough data to perform scrobbles
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Started playing a non-library file, checking available data."
                    )

                    season = xbmc.getInfoLabel('VideoPlayer.Season')
                    episode = xbmc.getInfoLabel('VideoPlayer.Episode')
                    showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
                    year = xbmc.getInfoLabel('VideoPlayer.Year')
                    video_ids = xbmcgui.Window(10000).getProperty(
                        'script.trakt.ids')
                    if video_ids:
                        data['video_ids'] = json.loads(video_ids)

                    logger.debug(
                        "[traktPlayer] info - ids: %s, showtitle: %s, Year: %s, Season: %s, Episode: %s"
                        % (video_ids, showtitle, year, season, episode))

                    if season and episode and (showtitle or video_ids):
                        # we have season, episode and either a show title or video_ids, can scrobble this as an episode
                        self.type = 'episode'
                        data['type'] = 'episode'
                        data['season'] = int(season)
                        data['episode'] = int(episode)
                        data['showtitle'] = showtitle
                        data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                        if year.isdigit():
                            data['year'] = int(year)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Playing a non-library 'episode' - %s - S%02dE%02d - %s."
                            % (data['showtitle'], data['season'],
                               data['episode'], data['title']))
                    elif (year or video_ids) and not season and not showtitle:
                        # we have a year or video_id and no season/showtitle info, enough for a movie
                        self.type = 'movie'
                        data['type'] = 'movie'
                        if year.isdigit():
                            data['year'] = int(year)
                        data['title'] = xbmc.getInfoLabel('VideoPlayer.Title')
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Playing a non-library 'movie' - %s (%s)."
                            % (data['title'], data.get('year', 'NaN')))
                    elif showtitle:
                        title, season, episode = utilities.regex_tvshow(
                            showtitle)
                        data['type'] = 'episode'
                        data['season'] = season
                        data['episode'] = episode
                        data['title'] = data['showtitle'] = title
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Title: %s, showtitle: %s, season: %d, episode: %d"
                            % (title, showtitle, season, episode))
                    else:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Non-library file, not enough data for scrobbling, skipping."
                        )
                        return

                elif self.type == 'episode' or self.type == 'movie':
                    # get library id
                    self.id = result['item']['id']
                    data['id'] = self.id
                    data['type'] = self.type

                    if self.type == 'episode':
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Doing multi-part episode check."
                        )
                        result = kodiUtilities.kodiJsonRequest({
                            'jsonrpc': '2.0',
                            'method': 'VideoLibrary.GetEpisodeDetails',
                            'params': {
                                'episodeid':
                                self.id,
                                'properties':
                                ['tvshowid', 'season', 'episode', 'file']
                            },
                            'id': 1
                        })
                        if result:
                            logger.debug("[traktPlayer] onAVStarted() - %s" %
                                         result)
                            tvshowid = int(
                                result['episodedetails']['tvshowid'])
                            season = int(result['episodedetails']['season'])
                            currentfile = result['episodedetails']['file']

                            result = kodiUtilities.kodiJsonRequest({
                                'jsonrpc': '2.0',
                                'method': 'VideoLibrary.GetEpisodes',
                                'params': {
                                    'tvshowid': tvshowid,
                                    'season': season,
                                    'properties': ['episode', 'file'],
                                    'sort': {
                                        'method': 'episode'
                                    }
                                },
                                'id': 1
                            })
                            if result:
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - %s" %
                                    result)
                                # make sure episodes array exists in results
                                if 'episodes' in result:
                                    multi = []
                                    for i in range(result['limits']['start'],
                                                   result['limits']['total']):
                                        if currentfile == result['episodes'][
                                                i]['file']:
                                            multi.append(result['episodes'][i]
                                                         ['episodeid'])
                                    if len(multi) > 1:
                                        data['multi_episode_data'] = multi
                                        data['multi_episode_count'] = len(
                                            multi)
                                        logger.debug(
                                            "[traktPlayer] onAVStarted() - This episode is part of a multi-part episode."
                                        )
                                    else:
                                        logger.debug(
                                            "[traktPlayer] onAVStarted() - This is a single episode."
                                        )
                elif (kodiUtilities.getSettingAsBool('scrobble_mythtv_pvr')
                      and self.type == 'unknown' and result['item']['label']):
                    # If we have label/id but no show type, then this might be a PVR recording.

                    # As of Kodi v17, many of the VideoPlayer labels are populated by the MythTV PVR addon, though sadly this
                    # does not include IMDB number. That means we're still stuck using the show title/episode name to look up
                    # IDs to feed to the scrobbler. Still, much easier than previous versions!
                    foundShowName = xbmc.getInfoLabel('VideoPlayer.Title')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Title: %s"
                        % foundShowName)
                    foundEpisodeName = xbmc.getInfoLabel(
                        'VideoPlayer.EpisodeName')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.EpisodeName: %s"
                        % foundEpisodeName)
                    foundEpisodeYear = xbmc.getInfoLabel('VideoPlayer.Year')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Year: %s"
                        % foundEpisodeYear)
                    foundSeason = xbmc.getInfoLabel('VideoPlayer.Season')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Season: %s"
                        % foundSeason)
                    foundEpisode = xbmc.getInfoLabel('VideoPlayer.Episode')
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Found VideoPlayer.Episode: %s"
                        % foundEpisode)
                    if (foundShowName and foundEpisodeName
                            and foundEpisodeYear):
                        # If the show/episode/year are populated, we can skip all the mess of trying to extract the info from the
                        # Player.Filename infolabel.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Got info from VideoPlayer labels"
                        )
                    else:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - No love from VideoPlayer labels, trying Player.Filename infolabel"
                        )
                        # If that didn't work, we can fall back on the Player.Filename infolabel. It shows up like this:
                        # (v16) ShowName [sXXeYY ](year) EpisodeName, channel, PVRFileName
                        # (v17) ShowName [sXXeYY ](year) EpisodeName, channel, date, PVRFileName
                        # The season and episode info may or may not be present. Also, sometimes there are some URL encodings
                        # (i.e. %20 instead of space) so those need removing. For example:
                        # Powerless s01e08 (2017)%20Green%20Furious, TV%20(WOOD%20TV), 20170414_003000, 1081_1492129800_4e1.pvr
                        # DC's Legends of Tomorrow (2016) Pilot, Part 2, TV (CW W MI), 20160129_010000, 1081_1492129800_4e1.pvr
                        foundLabel = urllib.unquote(
                            xbmc.getInfoLabel('Player.Filename'))
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Found unknown video type with label: %s. Might be a PVR episode, searching Trakt for it."
                            % foundLabel)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - After urllib.unquote: %s."
                            % foundLabel)
                        splitLabel = foundLabel.rsplit(", ", 3)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Post-split of label: %s "
                            % splitLabel)
                        if len(splitLabel) != 4:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Label doesn't have the ShowName sXXeYY (year) EpisodeName, channel, date, PVRFileName format that was expected. Might be the v16 version with no date instead."
                            )
                            splitLabel = foundLabel.rsplit(", ", 2)
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Post-split of label: %s "
                                % splitLabel)
                            if len(splitLabel) != 3:
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - Label doesn't have the ShowName sXXeYY (year) EpisodeName, channel, PVRFileName format that was expected. Giving up."
                                )
                                return
                        foundShowAndEpInfo = splitLabel[0]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - show plus episode info: %s"
                            % foundShowAndEpInfo)
                        splitShowAndEpInfo = re.split(
                            r' (s\d\de\d\d)? ?\((\d\d\d\d)\) ',
                            foundShowAndEpInfo, 1)
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Post-split of show plus episode info: %s "
                            % splitShowAndEpInfo)
                        if len(splitShowAndEpInfo) != 4:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Show plus episode info doesn't have the ShowName sXXeYY (year) EpisodeName format that was expected. Giving up."
                            )
                            return
                        foundShowName = splitShowAndEpInfo[0]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - using show name: %s"
                            % foundShowName)
                        foundEpisodeName = splitShowAndEpInfo[3]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - using episode name: %s"
                            % foundEpisodeName)
                        foundEpisodeYear = splitShowAndEpInfo[2]
                        logger.debug(
                            "[traktPlayer] onAVStarted() - using episode year: %s"
                            % foundEpisodeYear)
                    epYear = None
                    try:
                        epYear = int(foundEpisodeYear)
                    except ValueError:
                        epYear = None
                    logger.debug(
                        "[traktPlayer] onAVStarted() - verified episode year: %d"
                        % epYear)
                    # All right, now we have the show name, episode name, and (maybe) episode year. All good, but useless for
                    # scrobbling since Trakt only understands IDs, not names.
                    data['video_ids'] = None
                    data['season'] = None
                    data['episode'] = None
                    data['episodeTitle'] = None
                    # First thing to try, a text query to the Trakt DB looking for this episode. Note
                    # that we can't search for show and episode together, because the Trakt function gets confused and returns nothing.
                    newResp = globals.traktapi.getTextQuery(
                        foundEpisodeName, "episode", epYear)
                    if not newResp:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Empty Response from getTextQuery, giving up"
                        )
                    else:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Got Response from getTextQuery: %s"
                            % str(newResp))
                        # We got something back. See if one of the returned values is for the show we're looking for. Often it's
                        # not, but since there's no way to tell the search which show we want, this is all we can do.
                        rightResp = None
                        for thisResp in newResp:
                            compareShowName = thisResp.show.title
                            logger.debug(
                                "[traktPlayer] onAVStarted() - comparing show name: %s"
                                % compareShowName)
                            if thisResp.show.title == foundShowName:
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - found the right show, using this response"
                                )
                                rightResp = thisResp
                                break
                        if rightResp is None:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Failed to find matching episode/show via text search."
                            )
                        else:
                            # OK, now we have a episode object to work with.
                            self.type = 'episode'
                            data['type'] = 'episode'
                            # You'd think we could just use the episode key that Trakt just returned to us, but the scrobbler
                            # function (see scrobber.py) only understands the show key plus season/episode values.
                            showKeys = {}
                            for eachKey in rightResp.show.keys:
                                showKeys[eachKey[0]] = eachKey[1]
                            data['video_ids'] = showKeys
                            # For some reason, the Trakt search call returns the season and episode as an array in the pk field.
                            # You'd think individual episode and season fields would be better, but whatever.
                            data['season'] = rightResp.pk[0]
                            data['episode'] = rightResp.pk[1]
                    # At this point if we haven't found the episode data yet, the episode-title-text-search method
                    # didn't work.
                    if (not data['season']):
                        # This text query API is basically the same as searching on the website. Works with alternative
                        # titles, unlike the scrobble function. Though we can't use the episode year since that would only
                        # match the show if we're dealing with season 1.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Searching for show title via getTextQuery: %s"
                            % foundShowName)
                        newResp = globals.traktapi.getTextQuery(
                            foundShowName, "show", None)
                        if not newResp:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Empty Show Response from getTextQuery, falling back on episode text query"
                            )
                        else:
                            logger.debug(
                                "[traktPlayer] onAVStarted() - Got Show Response from getTextQuery: %s"
                                % str(newResp))
                            # We got something back. Have to assume the first show found is the right one; if there's more than
                            # one, there's no way to know which to use. Pull the ids from the show data, and store 'em for scrobbling.
                            showKeys = {}
                            for eachKey in newResp[0].keys:
                                showKeys[eachKey[0]] = eachKey[1]
                            data['video_ids'] = showKeys
                            # Now to find the episode. There's no search function to look for an episode within a show, but
                            # we can get all the episodes and look for the title.
                            while (not data['season']):
                                logger.debug(
                                    "[traktPlayer] onAVStarted() - Querying for all seasons/episodes of this show"
                                )
                                epQueryResp = globals.traktapi.getShowWithAllEpisodesList(
                                    data['video_ids']['trakt'])
                                if not epQueryResp:
                                    # Nothing returned. Giving up.
                                    logger.debug(
                                        "[traktPlayer] onAVStarted() - No response received"
                                    )
                                    break
                                else:
                                    # Got the list back. Go through each season.
                                    logger.debug(
                                        "[traktPlayer] onAVStarted() - Got response with seasons: %s"
                                        % str(epQueryResp))
                                    for eachSeason in epQueryResp:
                                        # For each season, check each episode.
                                        logger.debug(
                                            "[traktPlayer] onAVStarted() - Processing season: %s"
                                            % str(eachSeason))
                                        for eachEpisodeNumber in eachSeason.episodes:
                                            thisEpTitle = None
                                            # Get the title. The try block is here in case the title doesn't exist for some entries.
                                            try:
                                                thisEpTitle = eachSeason.episodes[
                                                    eachEpisodeNumber].title
                                            except:
                                                thisEpTitle = None
                                            logger.debug(
                                                "[traktPlayer] onAVStarted() - Checking episode number %d with title %s"
                                                % (eachEpisodeNumber,
                                                   thisEpTitle))
                                            if (foundEpisodeName == thisEpTitle
                                                ):
                                                # Found it! Save the data. The scrobbler wants season and episode number. Which for some
                                                # reason is stored as a pair in the first item in the keys array.
                                                data[
                                                    'season'] = eachSeason.episodes[
                                                        eachEpisodeNumber].keys[
                                                            0][0]
                                                data[
                                                    'episode'] = eachSeason.episodes[
                                                        eachEpisodeNumber].keys[
                                                            0][1]
                                                # Title too, just for the heck of it. Though it's not actually used.
                                                data[
                                                    'episodeTitle'] = thisEpTitle
                                                break
                                        # If we already found our data, no need to go through the rest of the seasons.
                                        if (data['season']):
                                            break
                    # Now we've done all we can.
                    if (data['season']):
                        # OK, that's everything. Data should be all set for scrobbling.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Playing a non-library 'episode' : show trakt key %s, season: %d, episode: %d"
                            % (data['video_ids'], data['season'],
                               data['episode']))
                    else:
                        # Still no data? Too bad, have to give up.
                        logger.debug(
                            "[traktPlayer] onAVStarted() - Did our best, but couldn't get info for this show and episode. Skipping."
                        )
                        return
                else:
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Video type '%s' unrecognized, skipping."
                        % self.type)
                    return

                pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
                plSize = len(pl)
                if plSize > 1:
                    pos = pl.getposition()
                    if not self.plIndex is None:
                        logger.debug(
                            "[traktPlayer] onAVStarted() - User manually skipped to next (or previous) video, forcing playback ended event."
                        )
                        self.onPlayBackEnded()
                    self.plIndex = pos
                    logger.debug(
                        "[traktPlayer] onAVStarted() - Playlist contains %d item(s), and is currently on item %d"
                        % (plSize, (pos + 1)))

                self._playing = True

                # send dispatch
                self.action(data)
Exemplo n.º 6
0
def set_property(property, value, window=10000):
    xbmcgui.Window(window).setProperty(property, value)
Exemplo n.º 7
0
def clear_property(property, window=10000):
    xbmcgui.Window(window).clearProperty(property)
Exemplo n.º 8
0
 def __init__(self, *args, **kwargs):
     self.disable_quit = kwargs['disable_quit']
     self.auto_close = kwargs['auto_close']
     self.WINDOW = xbmcgui.Window(10000)
 def onInit(self):
     self.window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
     self.downloadStatusData = self.get_download_status_list()
     self.parse_local_movie_info(self.path)
Exemplo n.º 10
0
 def onInit(self):
     if not self.win:
         self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
         self.programsListBox = self.getControl(600)
         self.refreshButton = self.getControl(250)
         self.refresh()
Exemplo n.º 11
0
def Show_Update_Screen(disable_quit=False, auto_close=True):
    xbmcgui.Window(10000).clearProperty('update_icon')
    xbmcgui.Window(10000).clearProperty('update_percent')
    xbmcgui.Window(10000).clearProperty('update_spinner')
    xbmcgui.Window(10000).clearProperty('update_header')
    xbmcgui.Window(10000).clearProperty('update_main_text')
    xbmcgui.Window(10000).setProperty('update_background', 'whitebg.jpg')
    xbmcgui.Window(10000).setProperty('update_percent_color', '0xFF000000')
    xbmcgui.Window(10000).setProperty('update_bar_color', '0xFF000000')
    xbmcgui.Window(10000).setProperty('update_main_color', '0xFF000000')
    xbmcgui.Window(10000).setProperty('update_header_color', '0xFF000000')
    # Set a property so we can determine if update screen is active
    xbmcgui.Window(10000).setProperty('update_screen', 'active')
    d = MyUpdateScreen('Loading.xml',
                       koding_path,
                       disable_quit=disable_quit,
                       auto_close=auto_close)
    d.doModal()
    del d
    xbmcgui.Window(10000).clearProperty('update_screen')
Exemplo n.º 12
0
import codecs
from core import filetools
from core import httptools
from core import jsontools
from core.item import Item
from platformcode import config, logger

dict_servers_parameters = {}
""" CACHING SERVERS PARAMETERS """
alfa_caching = False
alfa_servers = {}
kodi = True
try:
    import xbmcgui
    import json
    window = xbmcgui.Window(10000)  # Home
except:
    kodi = False


def find_video_items(item=None, data=None):
    """
    Función genérica para buscar vídeos en una página, devolviendo un itemlist con los items listos para usar.
     - Si se pasa un Item como argumento, a los items resultantes mantienen los parametros del item pasado
     - Si no se pasa un Item, se crea uno nuevo, pero no contendra ningun parametro mas que los propios del servidor.

    @param item: Item al cual se quieren buscar vídeos, este debe contener la url válida
    @type item: Item
    @param data: Cadena con el contendio de la página ya descargado (si no se pasa item)
    @type data: str
def feed(name, url):
    """
    Show Feed
    """
    response = _get_url(url)
    root = ET.fromstring(response)
    for website_details in root.iter('channel'):
        website_title = website_details.find('title').text
        website_link = website_details.find('link').text

    for feed in root.iter('item'):
        feed_title = feed.find('title').text

        if feed_title == name:
            feed_link = feed.find('link').text
            feed_date = feed.find('pubDate').text
            feed_date = feed_date[:feed_date.find(' +')]
            feed_cats = feed.findall('category')
            feed_category = ''

            for cat in feed_cats:
                feed_category = feed_category + ', ' + cat.text

            if len(feed_category) > 0:
                feed_category = feed_category[2:]

            feed_category = feed_category.replace('<![CDATA[',
                                                  '').replace(']]>', '')
            feed_desc = feed.find('description').text
            namespaces = {
                'content': 'http://purl.org/rss/1.0/modules/content/'
            }
            feed_content = feed.find('content:encoded', namespaces).text
            #            feed_content = feed.find('description', namespaces).text.replace('\t', '')

            break

    desc = 'n/a'
    desc = feed_content
    imgsrc = re.search('img[^<>\\n]+src=[\'"]([^"\']+)[\'"]', desc)
    if imgsrc:
        feed_image = imgsrc.group(1)
    else:
        feed_image = ""

    #convert news text into plain text
    desc = re.sub('<p[^>\\n]*>', '\n\n', desc)
    desc = re.sub('<br[^>\\n]*>', '\n', desc)
    desc = re.sub('<li[^>\\n]*>', '      ', desc)
    desc = re.sub('<[^>\\n]+>', '', desc)
    desc = re.sub('\\n\\n+', '\n\n', desc)
    desc = re.sub('(\\w+,?) *\\n(\\w+)', '\\1 \\2', desc)
    desc = desc.replace('<![CDATA[', '').replace(']]>', '')
    desc = HTMLParser.HTMLParser().unescape(desc)
    feed_text = desc
    window = xbmcgui.WindowXMLDialog('script-rss-reader.xml',
                                     __addon__.getAddonInfo('path'))
    win = xbmcgui.Window(10147)
    win.setProperty('HeadingLabel', feed_title)
    win.setProperty('FeedImage', feed_image)
    win.setProperty('FeedName', feed_title)
    win.setProperty('FeedCategory', feed_category)
    win.setProperty('PubDate', feed_date)
    win.setProperty('AuthorName', website_title)
    win.setProperty('FeedWebsite', website_link)
    win.setProperty('Description', feed_text)
    window.doModal()
    del window
Exemplo n.º 14
0
 def onPlayBackStopped(self):
     log('onPlayBackStopped')
     xbmc.executebuiltin("PlayerControl(RepeatOff)")
     xbmcgui.Window(10000).clearProperty('script.trakt.paused')
     self.stop()
Exemplo n.º 15
0
def get_window_property(index):
    data = json.loads(
        xbmcgui.Window(10000).getProperty(
            "video.kino.pub-playback_data"))[index]
    return data
Exemplo n.º 16
0
 def getProperty(self, str):
     property = xbmcgui.Window(10000).getProperty(str)
     return property
 def status(self, value):
     xbmcgui.Window(10000).setProperty('script.module.youtube.dl_STATUS', value)
Exemplo n.º 18
0
 def setProperty(self, str1, str2):
     xbmcgui.Window(10000).setProperty(str1, str2)
Exemplo n.º 19
0
def get_property(property, window=10000):
    return xbmcgui.Window(window).getProperty(property)
Exemplo n.º 20
0
 def clearProperty(self, str):
     xbmcgui.Window(10000).clearProperty(str)
Exemplo n.º 21
0
def get_response(img, cookie):
    #on telecharge l'image
    PathCache = xbmc.translatePath(xbmcaddon.Addon('plugin.video.vstream').getAddonInfo("profile"))
    filename  = os.path.join(PathCache,'Captcha.raw').decode("utf-8")

    headers2 = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0',
        #'Referer' : url ,
        'Host' : 'protect.ddl-island.su',
        'Accept' : 'image/png,image/*;q=0.8,*/*;q=0.5',
        'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4',
        'Accept-Encoding' : 'gzip, deflate',
        #'Content-Type' : 'application/x-www-form-urlencoded',
        'Cookie' : cookie
        }

    try:
        req = urllib2.Request(img, None, headers2)
        image_on_web = urllib2.urlopen(req)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            downloaded_image = file(filename, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return ''
    except:
        return ''

    #on affiche le dialogue
    solution = ''

    if (True):
        ####nouveau captcha
        try:
            ##affichage du dialog perso
            class XMLDialog(xbmcgui.WindowXMLDialog):
                #"""
                #Dialog class for captcha
                #"""
                def __init__(self, *args, **kwargs):
                    xbmcgui.WindowXMLDialog.__init__(self)
                    pass

                def onInit(self):
                    #image background captcha
                    self.getControl(1).setImage(filename.encode("utf-8"), False)
                    #image petit captcha memory fail
                    self.getControl(2).setImage(filename.encode("utf-8"), False)
                    self.getControl(2).setVisible(False)
                    ##Focus clavier
                    self.setFocus(self.getControl(21))

                def onClick(self, controlId):
                    if controlId == 20:
                        #button Valider
                        solution = self.getControl(5000).getLabel()
                        xbmcgui.Window(10101).setProperty('captcha', str(solution))
                        self.close()
                        return

                    elif controlId == 30:
                        #button fermer
                        self.close()
                        return

                    elif controlId == 21:
                        #button clavier
                        self.getControl(2).setVisible(True)
                        kb = xbmc.Keyboard(self.getControl(5000).getLabel(), '', False)
                        kb.doModal()

                        if (kb.isConfirmed()):
                            self.getControl(5000).setLabel(kb.getText())
                            self.getControl(2).setVisible(False)
                        else:
                            self.getControl(2).setVisible(False)

                def onFocus(self, controlId):
                    self.controlId = controlId

                def _close_dialog(self):
                    self.close()

                def onAction(self, action):
                    #touche return 61448
                    if action.getId() in ( 9, 10, 11, 30, 92, 216, 247, 257, 275, 61467, 61448):
                        self.close()

            wd = XMLDialog('DialogCaptcha.xml', cConfig().getAddonPath().decode("utf-8"), 'default', '720p')
            wd.doModal()
            del wd
        finally:

            solution = xbmcgui.Window(10101).getProperty('captcha')
            if solution == '':
                cConfig().showInfo("Erreur", 'Vous devez taper le captcha', 4)

    else:
        #ancien Captcha
        try:
            img = xbmcgui.ControlImage(450, 0, 400, 130, filename.encode("utf-8"))
            wdlg = xbmcgui.WindowDialog()
            wdlg.addControl(img)
            wdlg.show()
            #xbmc.sleep(3000)
            kb = xbmc.Keyboard('', 'Tapez les Lettres/chiffres de l\'image', False)
            kb.doModal()
            if (kb.isConfirmed()):
                solution = kb.getText()
                if solution == '':
                    cConfig().showInfo("Erreur", 'Vous devez taper le captcha', 4)
            else:
                cConfig().showInfo("Erreur", 'Vous devez taper le captcha', 4)
        finally:
            wdlg.removeControl(img)
            wdlg.close()

    return solution
Exemplo n.º 22
0
import sys
import traceback

ADDON = xbmcaddon.Addon()
ADDON_NAME = ADDON.getAddonInfo('name')
ADDON_ID = ADDON.getAddonInfo('id')
ADDON_ICON = ADDON.getAddonInfo('icon')
ADDON_AUTHOR = ADDON.getAddonInfo('author')
ADDON_VERSION = ADDON.getAddonInfo('version')
ADDON_ARGUMENTS = str(sys.argv)
CWD = ADDON.getAddonInfo('path')
LANGUAGE = ADDON.getLocalizedString
PROFILE = xbmcvfs.translatePath(ADDON.getAddonInfo('profile'))
KODI_VERSION = xbmc.getInfoLabel('System.BuildVersion')
USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.0.1) Gecko/2008070208 Firefox/3.6"
WEATHER_WINDOW = xbmcgui.Window(12600)


def log(message, exception_instance=None, level=xbmc.LOGDEBUG):
    """
    Log a message to the Kodi debug log, if debug logging is turned on.

    :param message: required, the message to log
    :param exception_instance: optional, an instance of some Exception
    :param level: optional, the Kodi log level to use, default LOGDEBUG
    """

    message = f'### {ADDON_NAME} {ADDON_VERSION} - {message}'
    message_with_exception = message + f' ### Exception: {traceback.format_exc(exception_instance)}'

    if exception_instance is None:
Exemplo n.º 23
0
 def onInit(self):
     self.window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
Exemplo n.º 24
0
 def finishDialog(self, dialog):
     if xbmcgui.Window(10101).getProperty('search') != 'true':
         dialog.close()
         xbmc.log('\t[PLUGIN] Vstream: close dialog')
         del dialog
         return False
Exemplo n.º 25
0
import resources.lib.notification as DKT

__addon__ = xbmcaddon.Addon()
__path__ = __addon__.getAddonInfo('path')
__icon__ = os.path.join(xbmc.translatePath(__path__), 'resources', 'skins',
                        'Default', 'media', 'icon.png')
__icon2__ = os.path.join(xbmc.translatePath(__path__), 'resources', 'skins',
                         'Default', 'media', 'icon_alert.png')
__profiles__ = __addon__.getAddonInfo('profile')
__LS__ = __addon__.getLocalizedString

TEMP_STORAGE_NOTIFICATIONS = os.path.join(xbmc.translatePath(__profiles__),
                                          'notifications.json')

if t.getAddonSetting('show_onstart', sType=t.BOOL):
    xbmcgui.Window(10000).setProperty('reminders', '1')
else:
    xbmcgui.Window(10000).setProperty('reminders', '0')

_cycle = 0

googlecal = Calendar()
monitor = xbmc.Monitor()
while xbmcgui.Window(10000).getProperty(
        'reminders') == '1' and not monitor.abortRequested():
    now = datetime.utcnow().isoformat() + 'Z'
    timemax = (datetime.utcnow() + relativedelta.relativedelta(
        months=t.getAddonSetting('timemax', sType=t.NUM))).isoformat() + 'Z'
    events = googlecal.get_events(TEMP_STORAGE_NOTIFICATIONS,
                                  now,
                                  timemax,
Exemplo n.º 26
0
    def onInit(self):
        if not self.win:
            log.debug('onInit')
            self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())

            # Nav Buttons
            self.testSettingsButton = self.getControl(253)
            self.clearCacheButton = self.getControl(405)

            self.streamingEnabledRadioButton = self.getControl(208)
            self.recordingsButton = self.getControl(205)

            # MythTV Settings
            if hasattr(self.settings, 'master') and self.settings.master:
                self.setWindowProperty(
                    'MasterBackendHostname',
                    '%s / %s' % (self.settings.master.hostname,
                                 self.settings.master.ipAddress))
                self.setWindowProperty('MasterBackendPort',
                                       str(self.settings.master.port))

            self.register(
                Setting(self.settings, 'streaming_enabled', bool, None,
                        self.getControl(208)))
            self.register(
                Setting(
                    self.settings, 'paths_recordedprefix', str,
                    ExternalizedSettingValidator(
                        MythSettings.verifyRecordingDirs),
                    self.getControl(205)))
            self.register(
                Setting(self.settings, 'confirm_on_delete', bool, None,
                        self.getControl(206)))
            self.register(
                Setting(self.settings, 'aggressive_caching', bool, None,
                        self.getControl(207)))

            # MySQL Settings
            self.register(
                Setting(
                    self.settings, 'mysql_host', str,
                    ExternalizedSettingValidator(MythSettings.verifyMySQLHost),
                    self.getControl(301)))
            self.register(
                Setting(
                    self.settings, 'mysql_port', int,
                    ExternalizedSettingValidator(MythSettings.verifyMySQLPort),
                    self.getControl(302)))
            self.register(
                Setting(
                    self.settings, 'mysql_database', str,
                    ExternalizedSettingValidator(
                        MythSettings.verifyMySQLDatabase),
                    self.getControl(303)))
            self.register(
                Setting(
                    self.settings, 'mysql_user', str,
                    ExternalizedSettingValidator(MythSettings.verifyMySQLUser),
                    self.getControl(304)))
            self.register(
                Setting(self.settings, 'mysql_password', str, None,
                        self.getControl(305)))

            # Fanart Settings
            self.register(
                Setting(self.settings, 'fanart_tvdb', bool, None,
                        self.getControl(401)))
            self.register(
                Setting(self.settings, 'fanart_tvrage', bool, None,
                        self.getControl(406)))
            self.register(
                Setting(self.settings, 'fanart_tmdb', bool, None,
                        self.getControl(402)))
            self.register(
                Setting(self.settings, 'fanart_imdb', bool, None,
                        self.getControl(403)))
            self.register(
                Setting(self.settings, 'fanart_google', bool, None,
                        self.getControl(404)))

            # Advanced Settings
            self.register(
                Setting(self.settings, 'logging_enabled', bool, None,
                        self.getControl(502)))
            self.register(
                Setting(self.settings, 'feeds_twitter', str, None,
                        self.getControl(503)))
            self.setWindowProperty(
                'debugLogLocation',
                self.translator.get(m.DEBUG_LOG_LOCATION) %
                self.platform.getDebugLog())

            # Playback settings
            self.advanced.get = self.advanced.getSetting
            self.advanced.put = self.advanced.setSetting
            self.register(
                Setting(self.advanced, 'video/timeseekforward', Seconds, None,
                        self.getControl(602)))
            self.register(
                Setting(self.advanced, 'video/timeseekbackward',
                        NegativeSeconds, None, self.getControl(603)))
            self.register(
                Setting(self.advanced, 'video/timeseekforwardbig', Seconds,
                        None, self.getControl(604)))
            self.register(
                Setting(self.advanced, 'video/timeseekbackwardbig',
                        NegativeSeconds, None, self.getControl(605)))

            self.render()
Exemplo n.º 27
0
tmdb = params.get('tmdb')
tvdb = params.get('tvdb')
season = params.get('season')
episode = params.get('episode')
tvshowtitle = params.get('tvshowtitle')
premiered = params.get('premiered')
type = params.get('type')
url = params.get('url')
meta = params.get('meta')
query = params.get('query')
source = params.get('source')

windowedtrailer = params.get('windowedtrailer')
windowedtrailer = int(windowedtrailer) if windowedtrailer in ("0", "1") else 0

homeWindow = xbmcgui.Window(10000)
playAction = xbmcaddon.Addon('plugin.video.venom').getSetting('hosts.mode')
autoPlay = 'true' if playAction == '2' else ''
homeWindow.setProperty('plugin.video.venom.autoPlay', autoPlay)

if action is None:
    from resources.lib.menus import navigator
    from resources.lib.modules import cache
    run = control.setting('first.info')
    if run == '':
        run = 'true'  #clean install scenerio
    if cache._find_cache_version():
        run = 'true'
    if run == 'true':
        control.execute(
            'RunPlugin(plugin://plugin.video.venom/?action=cleanSettings)')
Exemplo n.º 28
0
def set_window_property(value):
    xbmcgui.Window(10000).clearProperty("video.kino.pub-playback_data")
    if not isinstance(value, basestring):
        value = json.dumps(value)
    xbmcgui.Window(10000).setProperty("video.kino.pub-playback_data", value)
Exemplo n.º 29
0
import gc
try:
    from multiprocessing.pool import ThreadPool
    SUPPORTS_POOL = True
except Exception:
    SUPPORTS_POOL = False

import xbmc
import xbmcaddon
import xbmcgui

from . import path_ops, variables as v

LOG = getLogger('PLEX.utils')

WINDOW = xbmcgui.Window(10000)
ADDON = xbmcaddon.Addon(id='plugin.video.plexkodiconnect')

# If several threads access  the settings.xml file concurrently, it gets
# corrupted
SETTINGS_LOCK = Lock()

# Grab Plex id from '...plex_id=XXXX....'
REGEX_PLEX_ID = re.compile(r'''plex_id=(\d+)''')
# Return the numbers at the end of an url like '.../.../XXXX'
REGEX_END_DIGITS = re.compile(r'''/(.+)/(\d+)$''')
REGEX_PLEX_DIRECT = re.compile(r'''\.plex\.direct:\d+$''')
# Plex API
REGEX_IMDB = re.compile(r'''/(tt\d+)''')
REGEX_TVDB = re.compile(r'''thetvdb:\/\/(.+?)\?''')
# Plex music
Exemplo n.º 30
0
ADDON_ID = 'plugin.video.tvland'
REAL_SETTINGS = xbmcaddon.Addon(id=ADDON_ID)
ADDON_NAME = REAL_SETTINGS.getAddonInfo('name')
SETTINGS_LOC = REAL_SETTINGS.getAddonInfo('profile')
ADDON_PATH = REAL_SETTINGS.getAddonInfo('path').decode('utf-8')
ADDON_VERSION = REAL_SETTINGS.getAddonInfo('version')
ICON = REAL_SETTINGS.getAddonInfo('icon')
FANART = REAL_SETTINGS.getAddonInfo('fanart')
LANGUAGE = REAL_SETTINGS.getLocalizedString

## GLOBALS ##
TIMEOUT = 15
CONTENT_TYPE = 'files'
DEBUG = REAL_SETTINGS.getSetting('Enable_Debugging') == 'true'
QUALITY = int(REAL_SETTINGS.getSetting('Quality'))
PTVL_RUNNING = xbmcgui.Window(10000).getProperty('PseudoTVRunning') == 'True'
BASE_URL = 'http://www.tvland.com'
IGNORE_LIST = ['ent_m100', 'ent_m150', 'ent_m151', 'ent_m112', 'ent_m116']
MAIN_MENU = [("Latest Episodes", BASE_URL + '/full-episodes', 1),
             ("Browse Shows", BASE_URL + '/shows', 1)]


def log(msg, level=xbmc.LOGDEBUG):
    if DEBUG == False and level != xbmc.LOGERROR: return
    if level == xbmc.LOGERROR: msg += ' ,' + traceback.format_exc()
    xbmc.log(ADDON_ID + '-' + ADDON_VERSION + '-' + msg, level)


def getParams():
    return dict(urlparse.parse_qsl(sys.argv[2][1:]))