Ejemplo n.º 1
0
    def __init__(self):
        try:
            fetcher = FileFetcher('guides.ini', ADDON)
            if fetcher.fetchFile() < 0:
                xbmcgui.Dialog().ok(strings(FETCH_ERROR_TITLE),
                                    strings(FETCH_ERROR_LINE1),
                                    strings(FETCH_ERROR_LINE2))

            print self.filePath
            self.guideParser.read(self.filePath)
            guideTypes = []
            defaultGuideId = 0  # fallback to the first guide in case no default is actually set in the ini file
            for section in self.guideParser.sections():
                sectMap = self.SectionMap(section)
                id = int(sectMap['id'])
                fName = sectMap['file']
                sortOrder = int(sectMap['sort_order'])
                default = False
                if 'default' in sectMap and sectMap['default'] == 'true':
                    default = True
                    defaultGuideId = id
                guideTypes.append((id, sortOrder, section, fName, default))
            self.guideTypes = sorted(guideTypes,
                                     key=itemgetter(self.GUIDE_SORT))
            logger.debug('GuideTypes collected: %s' % str(self.guideTypes),
                         __name__)

            ADDON.setSetting('xmltv.type', str(defaultGuideId))
        except:
            logger.error('unable to parse guides.ini', __name__)
Ejemplo n.º 2
0
def _getHostFromUrl(sID, sEpisode, sServername):
    # Seite abrufen
    sHtmlContent = cRequestHandler(URL_GETLINK + sID + '/' + sEpisode).request()
    sHtmlContent = base64.b64decode(str(sHtmlContent))

    if sHtmlContent is None:
        logger.info("result string is none")
        return []

    try:
        getLinkResponseJson = json.loads(sHtmlContent)
    except (ValueError, TypeError):
        logger.debug("could not decode server response")
        return []

    if 'playinfo' not in getLinkResponseJson:
        logger.info("no playable sources")
        return []

    hosters = []

    for playableEntry in getLinkResponseJson['playinfo']:
        hoster = dict()
        quality = playableEntry["label"]
        url = playableEntry["file"]
        label = sServername + ' - ' + quality
        if quality in QUALITY_ENUM:
            hoster['quality'] = QUALITY_ENUM[quality]
        hoster['link'] = url
        hoster['name'] = label
        hoster['resolveable'] = True
        hosters.append(hoster)

    return hosters
def _validate_ambilight():
    logger.debug("Validate ambilight config. Enabled: {}".format(
        settings_storage['ambiEnabled']))
    if settings_storage['ambiEnabled']:
        if settings_storage['zones'] == "0":
            light_ids = ADDON.getSetting("group3_Lights")
            if light_ids == "-1":
                logger.error("No ambilights selected")
                xbmcgui.Dialog().notification(
                    _("Hue Service"),
                    _("No lights selected for Ambilight."),
                    icon=xbmcgui.NOTIFICATION_ERROR)
                ADDON.setSettingBool("group3_enabled", False)
                settings_storage['ambiEnabled'] = False
        if settings_storage['zones'] == "1":
            light_idsLeft = ADDON.getSetting("group3_LightsLeft")
            if light_idsLeft == "-1":
                logger.error("No ambilights selected for left zone")
                xbmcgui.Dialog().notification(
                    _("Hue Service"),
                    _("No lights selected for Ambilight in left zone."),
                    icon=xbmcgui.NOTIFICATION_ERROR)
                ADDON.setSettingBool("group3_enabled", False)
                settings_storage['ambiEnabled'] = False
            light_idsRight = ADDON.getSetting("group3_LightsRight")
            if light_idsRight == "-1":
                logger.error("No ambilights selected for right zone")
                xbmcgui.Dialog().notification(
                    _("Hue Service"),
                    _("No lights selected for Ambilight in right zone."),
                    icon=xbmcgui.NOTIFICATION_ERROR)
                ADDON.setSettingBool("group3_enabled", False)
                settings_storage['ambiEnabled'] = False
Ejemplo n.º 4
0
 def checkVideoActivation(self, infoTag):
     try:
         duration = infoTag.getDuration(
         ) / 60  # returns seconds, convert to minutes
         mediaType = infoTag.getMediaType()
         fileName = infoTag.getFile()
         logger.debug(
             "InfoTag contents: duration: {}, mediaType: {}, file: {}".
             format(duration, mediaType, fileName))
     except AttributeError:
         logger.exception("Can't read infoTag")
         return False
     logger.debug(
         "Video Activation settings({}): minDuration: {}, Movie: {}, Episode: {}, MusicVideo: {}, Other: {}"
         .format(self.kgroupID, settings_storage['videoMinimumDuration'],
                 settings_storage['video_enableMovie'],
                 settings_storage['video_enableEpisode'],
                 settings_storage['video_enableMusicVideo'],
                 settings_storage['video_enableOther']))
     logger.debug(
         "Video Activation ({}): Duration: {}, mediaType: {}".format(
             self.kgroupID, duration, mediaType))
     if (duration > settings_storage['videoMinimumDuration'] and (
         (settings_storage['video_enableMovie'] and mediaType == "movie") or
         (settings_storage['video_enableEpisode']
          and mediaType == "episode") or
         (settings_storage['video_enableMusicVideo']
          and mediaType == "MusicVideo"))
             or settings_storage['video_enableOther']):
         logger.debug("Video activation: True")
         return True
     logger.debug("Video activation: False")
     return False
Ejemplo n.º 5
0
    def onAVStarted(self):
        if self.enabled:
            logger.info(
                "In KodiGroup[{}], onPlaybackStarted. Group enabled: {},startBehavior: {} , isPlayingVideo: {}, isPlayingAudio: {}, self.mediaType: {},self.playbackType(): {}"
                .format(self.kgroupID, self.enabled, self.startBehavior,
                        self.isPlayingVideo(), self.isPlayingAudio(),
                        self.mediaType, self.playbackType()))
            self.state = STATE_PLAYING
            settings_storage['lastMediaType'] = self.playbackType()

            if self.isPlayingVideo(
            ) and self.mediaType == VIDEO:  # If video group, check video activation. Otherwise it's audio so ignore this and check other conditions.
                try:
                    self.videoInfoTag = self.getVideoInfoTag()
                except Exception as exc:
                    logger.debug("Get InfoTag Exception: {}".format(exc))
                    reporting.process_exception(exc)
                    return
                logger.debug("InfoTag: {}".format(self.videoInfoTag))
                if not self.checkVideoActivation(self.videoInfoTag):
                    return
            else:
                self.videoInfoTag = None

            if self.checkActiveTime(
            ) and self.startBehavior and self.mediaType == self.playbackType():
                self.run_play()
Ejemplo n.º 6
0
 def getGuideDataItem(self, id, item):
     value = None
     guide = self.getGuideById(id)
     try:
         value = guide[item]
     except IndexError:
         logger.debug('DataItem with index %s not found' % item, __name__)
     return value
Ejemplo n.º 7
0
 def getGuideById(self, id):
     logger.debug('Finding Guide with ID: %s' % id, __name__)
     ret = []
     for guide in self.guideTypes:
         if guide[self.GUIDE_ID] == int(id):
             ret = guide
             logger.debug('Found Guide with data: %s' % str(guide),
                          __name__)
     return ret
Ejemplo n.º 8
0
 def flash(self):
     logger.debug("in KodiGroup Flash")
     try:
         self.groupResource.action(alert="select")
     except QhueException() as exc:
         logger.error("Hue Error: {}".format(exc))
         reporting.process_exception(exc)
     except ConnectTimeout as exc:
         logger.error("Hue Error: {}".format(exc))
Ejemplo n.º 9
0
def _pluginSearch(pluginEntry, sSearchText, oGui):
    try:
        plugin = __import__(pluginEntry['id'], globals(), locals())
        function = getattr(plugin, '_search')
        function(oGui, sSearchText)
    except:
        logger.info(pluginEntry['name'] + ': search failed')
        import traceback
        logger.debug(traceback.format_exc())
Ejemplo n.º 10
0
 def activate(self):
     logger.info("Activate group [{}]. State: {}".format(self.kgroupID, self.state))
     xbmc.sleep(200)
     if self.state == STATE_PAUSED:
         self.onPlayBackPaused()
     elif self.state == STATE_PLAYING:
         self.onAVStarted()
     else:
         # if not playing and activate is called, probably should do nothing.
         logger.debug("Activate group [{}]. playback stopped, doing nothing. ".format(self.kgroupID))
Ejemplo n.º 11
0
 def SectionMap(self, section):
     dict1 = {}
     options = self.guideParser.options(section)
     for option in options:
         try:
             dict1[option] = self.guideParser.get(section, option)
             if dict1[option] == -1:
                 logger.debug('skip: %s' % option, __name__)
         except:
             print("exception on %s!" % option)
             dict1[option] = None
     return dict1
Ejemplo n.º 12
0
    def loadSettings(self):
        logger.debug("KodiGroup Load settings for group: {}".format(self.kgroupID))
        self.enabled = ADDON.getSettingBool("group{}_enabled".format(self.kgroupID))

        self.startBehavior = ADDON.getSettingBool("group{}_startBehavior".format(self.kgroupID))
        self.startScene = ADDON.getSettingString("group{}_startSceneID".format(self.kgroupID))

        self.pauseBehavior = ADDON.getSettingBool("group{}_pauseBehavior".format(self.kgroupID))
        self.pauseScene = ADDON.getSettingString("group{}_pauseSceneID".format(self.kgroupID))

        self.stopBehavior = ADDON.getSettingBool("group{}_stopBehavior".format(self.kgroupID))
        self.stopScene = ADDON.getSettingString("group{}_stopSceneID".format(self.kgroupID))
Ejemplo n.º 13
0
def _validate_schedule():
    logger.debug("Validate schedule. Schedule Enabled: {}".format(
        settings_storage['enableSchedule']))
    if settings_storage['enableSchedule']:
        try:
            convert_time(settings_storage['startTime'])
            convert_time(settings_storage['endTime'])
            logger.debug("Time looks valid")
        except ValueError as e:
            logger.error("Invalid time settings: {}".format(e))

            xbmcgui.Dialog().notification(
                _("Hue Service"),
                _("Invalid start or end time, schedule disabled"),
                icon=xbmcgui.NOTIFICATION_ERROR)
            ADDON.setSettingBool("EnableSchedule", False)
            settings_storage['enableSchedule'] = False
def showGenreList():
    # GUI-Element erzeugen
    oGui = cGui()

    # ParameterHandler erzeugen
    params = ParameterHandler()

    # URL vom ParameterHandler ermitteln
    entryUrl = params.getValue('sUrl')

    # Movie-Seite laden
    sHtmlContent = cRequestHandler(entryUrl).request()

    # Select für Generes-Container
    pattern = '<select[^>]*name="category"[^>]*>(.*?)</select[^>]*>'

    # Regex parsen
    isMatch, sContainer = cParser.parseSingleResult(sHtmlContent, pattern)

    # Nichts gefunden? => raus hier
    if not isMatch:
        logger.debug("genre regex not matched")
        return

    # Filter für Genres
    pattern = '<option[^>]*value="(\d[^ ]*)"[^>]*>(.*?)</option[>]'

    # Regex parsen
    isMatch, aResult = cParser.parse(sContainer, pattern)

    # Nichts gefunden? => raus hier
    if not isMatch:
        logger.debug("value regex not matched")
        return

    # Alle Genres durchlaufen und Liste erzeugen
    for sID, sGenre in sorted(aResult, key=lambda k: k[1]):
        params.setParam(
            'sUrl',
            entryUrl + 'category=' + sID + '&country=&order_f=last_update')
        oGui.addFolder(
            cGuiElement(sGenre.strip(), SITE_IDENTIFIER, 'showEntries'),
            params)

    # Liste abschließen
    oGui.setEndOfDirectory()
Ejemplo n.º 15
0
    def checkVideoActivation(self, infoTag):
        try:
            duration = infoTag.getDuration(
            ) / 60  # returns seconds, convert to minutes
            mediaType = infoTag.getMediaType()
            fileName = infoTag.getFile()
            if not fileName and self.isPlayingVideo():
                fileName = self.getPlayingFile()

            if not fileName and settings_storage['previousFileName']:
                fileName = settings_storage['previousFileName']
            elif fileName:
                settings_storage['previousFileName'] = fileName

            logger.debug(
                "InfoTag contents: duration: {}, mediaType: {}, file: {}".
                format(duration, mediaType, fileName))
        except AttributeError:
            logger.exception("Can't read infoTag")
            return False
        logger.debug(
            "Video Activation settings({}): minDuration: {}, Movie: {}, Episode: {}, MusicVideo: {}, PVR : {}, Other: {}"
            .format(self.kgroupID, settings_storage['videoMinimumDuration'],
                    settings_storage['video_enableMovie'],
                    settings_storage['video_enableEpisode'],
                    settings_storage['video_enableMusicVideo'],
                    settings_storage['video_enablePVR'],
                    settings_storage['video_enableOther']))
        logger.debug(
            "Video Activation ({}): Duration: {}, mediaType: {}, ispvr: {}".
            format(self.kgroupID, duration, mediaType, fileName[0:3] == "pvr"))
        if ((duration >= settings_storage['videoMinimumDuration']
             or fileName[0:3] == "pvr") and
            ((settings_storage['video_enableMovie'] and mediaType == "movie")
             or (settings_storage['video_enableEpisode']
                 and mediaType == "episode") or
             (settings_storage['video_enableMusicVideo']
              and mediaType == "MusicVideo") or
             (settings_storage['video_enablePVR'] and fileName[0:3] == "pvr")
             or (settings_storage['video_enableOther'] and mediaType != "movie"
                 and mediaType != "episode" and mediaType != "MusicVideo"
                 and fileName[0:3] != "pvr"))):
            logger.debug("Video activation: True")
            return True
        logger.debug("Video activation: False")
        return False
Ejemplo n.º 16
0
def menu():
    route = sys.argv[0]
    addon_handle = int(sys.argv[1])
    base_url = sys.argv[0]
    command = sys.argv[2][1:]
    parsed = parse_qs(command)

    logger.debug(
        "Menu started.  route: {}, handle: {}, command: {}, parsed: {}, Arguments: {}"
        .format(route, addon_handle, command, parsed, sys.argv))

    if route == "plugin://script.service.hue/":
        if not command:

            build_menu(base_url, addon_handle)

        elif command == "settings":
            logger.debug("Opening settings")
            ADDON.openSettings()

        elif command == "toggle":
            if cache.get("script.service.hue.service_enabled"
                         ) and get_status() != "Disabled by daylight":
                logger.info("Disable service")
                cache.set("script.service.hue.service_enabled", False)

            elif get_status() != "Disabled by daylight":
                logger.info("Enable service")
                cache.set("script.service.hue.service_enabled", True)
            else:
                logger.info("Disabled by daylight, ignoring")

            xbmc.executebuiltin('Container.Refresh')

    elif route == "plugin://script.service.hue/actions":
        action = parsed['action'][0]
        kgroupid = parsed['kgroupid'][0]
        logger.debug("Actions: {}, kgroupid: {}".format(action, kgroupid))
        if action == "menu":
            items = [
                (base_url + "?action=play&kgroupid=" + kgroupid,
                 ListItem(_("Play"))),
                (base_url + "?action=pause&kgroupid=" + kgroupid,
                 ListItem(_("Pause"))),
                (base_url + "?action=stop&kgroupid=" + kgroupid,
                 ListItem(_("Stop"))),
            ]

            xbmcplugin.addDirectoryItems(addon_handle, items, len(items))
            xbmcplugin.endOfDirectory(handle=addon_handle, cacheToDisc=True)

        else:
            cache.set("script.service.hue.action", (action, kgroupid),
                      expiration=(timedelta(seconds=5)))

    else:
        logger.error(
            "Unknown command. Handle: {}, route: {}, Arguments: {}".format(
                addon_handle, route, sys.argv))
Ejemplo n.º 17
0
    def checkKeepLightsOffRule(self, scene):
        if not scene:
            return True

        logger.debug("Check if lights should stay off, settings: enable {}".format(settings_storage['keep_lights_off']))
        if settings_storage['keep_lights_off']:
            try:
                sceneData = self.bridge.scenes[scene]()
                for light in sceneData["lights"]:
                    l = self.bridge.lights[light]()
                    if l["state"]["on"] == False: # one light is off, the scene should not be applied
                        logger.debug("Check if lights should stay off: True")
                        return False
                logger.debug("Check if lights should stay off: False")
            except QhueException as e:
                logger.error("checkKeepLightsOffRule: Hue call fail: {}".format(e))

        return True
Ejemplo n.º 18
0
    def checkAlreadyActive(self, scene):
        if not scene:
            return False

        logger.debug("Check if scene light already active, settings: enable {}".format(settings_storage['enable_if_already_active']))
        if settings_storage['enable_if_already_active']:
            try:
                sceneData = self.bridge.scenes[scene]()
                for light in sceneData["lights"]:
                    l = self.bridge.lights[light]()
                    if l["state"]["on"] == True: # one light is on, the scene can be applied
                        logger.debug("Check if scene light already active: True")
                        return True
                logger.debug("Check if scene light already active: False")
            except QhueException as e:
                logger.error("checkAlreadyActive: Hue call fail: {}".format(e))

        return False
Ejemplo n.º 19
0
    def checkActiveTime(self):
        service_enabled = cache.get("script.service.hue.service_enabled")
        daylight = cache.get("script.service.hue.daylight")
        logger.debug(
            "Schedule: {}, daylightDiable: {}, daylight: {}, startTime: {}, endTime: {}"
            .format(settings_storage['enableSchedule'],
                    settings_storage['daylightDisable'], daylight,
                    settings_storage['startTime'],
                    settings_storage['endTime']))

        if settings_storage['daylightDisable'] and daylight:
            logger.debug("Disabled by daylight")
            return False

        if service_enabled:
            if settings_storage['enableSchedule']:
                start = convert_time(settings_storage['startTime'])
                end = convert_time(settings_storage['endTime'])
                now = datetime.datetime.now().time()
                if (now > start) and (now < end):
                    logger.debug("Enabled by schedule")
                    return True
                logger.debug("Disabled by schedule")
                return False
            logger.debug("Schedule not enabled")
            return True
        else:
            logger.debug("Service disabled")
            return False
Ejemplo n.º 20
0
 gTypes = GuideTypes()
 for gType in gTypes.guideTypes:
     guideList.append(gType[gTypes.GUIDE_NAME])
 d = xbmcgui.Dialog()
 ret = d.select('Select what type of guide you want to use', guideList)
 if ret >= 0:
     guideId = gTypes.guideTypes[ret][gTypes.GUIDE_ID]
     typeId = str(guideId)
     typeName = gTypes.getGuideDataItem(guideId, gTypes.GUIDE_NAME)
     ver = getKodiVersion()
     if xbmc.getCondVisibility('system.platform.android') and int(ver) < 15:
         # This workaround is needed due to a Bug in the Kodi Android implementation
         # where setSetting() does not have any effect:
         #  #13913 - [android/python] addons can not save settings  [http://trac.kodi.tv/ticket/13913]
         logger.debug(
             'Running on ANDROID with Kodi v%s --> using workaround!' %
             str(ver), __name__)
         filePath = xbmc.translatePath(
             os.path.join('special://profile', 'addon_data',
                          'script.aftershocknow.guide', 'settings.xml'))
         tree = ET.parse(filePath)
         root = tree.getroot()
         updated = False
         for item in root.findall('setting'):
             if item.attrib['id'] == 'xmltv.type':
                 item.attrib['value'] = typeId
                 updated = True
             elif item.attrib['id'] == 'xmltv.type_select':
                 item.attrib['value'] = typeName
                 updated = True
         if updated:
Ejemplo n.º 21
0
__cwd__ = common.addonPath

# Add different library path
path.append(join(__cwd__, "resources", "lib"))
path.append(join(__cwd__, "resources", "lib", "gui"))
path.append(join(__cwd__, "resources", "lib", "handler"))
path.append(join(__cwd__, "resources", "art", "sites"))
path.append(join(__cwd__, "sites"))

# Run streamon
from streamon import run

logger.info('*---- Running streamon, version %s ----*' %
            __settings__.getAddonInfo('version'))
logger.info('Python-Version: %s' % platform.python_version())

try:
    run()
except Exception, err:
    if str(err) == 'UserAborted':
        logger.error("User aborted list creation")
    else:
        import traceback
        import xbmcgui

        logger.debug(traceback.format_exc())
        dialog = xbmcgui.Dialog().ok(
            'Error',
            str(err.__class__.__name__) + " : " + str(err),
            str(traceback.format_exc().splitlines()[-3].split('addons')[-1]))