Beispiel #1
0
def chooseServer():
    """
    Lets user choose from list of PMS
    """
    log.info("Choosing PMS server requested, starting")

    import initialsetup
    setup = initialsetup.InitialSetup()
    server = setup.pick_pms(showDialog=True)
    if server is None:
        log.error('We did not connect to a new PMS, aborting')
        plex_command('SUSPEND_USER_CLIENT', 'False')
        plex_command('SUSPEND_LIBRARY_THREAD', 'False')
        return

    log.info("User chose server %s" % server['name'])
    setup.write_pms_to_settings(server)

    if not __LogOut():
        return

    from utils import wipe_database
    # Wipe Kodi and Plex database as well as playlists and video nodes
    wipe_database()

    # Log in again
    __LogIn()
    log.info("Choosing new PMS complete")
    # '<PMS> connected'
    dialog('notification',
           lang(29999),
           '%s %s' % (server['name'], lang(39220)),
           icon='{plex}',
           time=3000,
           sound=False)
Beispiel #2
0
def resetAuth():
    # User tried login and failed too many times
    resp = dialog('yesno', heading="{plex}", line1=lang(39206))
    if resp == 1:
        log.info("Reset login attempts.")
        plex_command('PMS_STATUS', 'Auth')
    else:
        executebuiltin('Addon.OpenSettings(plugin.video.plexkodiconnect)')
Beispiel #3
0
def __LogIn():
    """
    Resets (clears) window properties to enable (re-)login

    SUSPEND_LIBRARY_THREAD is set to False in service.py if user was signed
    out!
    """
    plex_command('RUN_LIB_SCAN', 'full')
    # Restart user client
    plex_command('SUSPEND_USER_CLIENT', 'False')
 def onSettingsChanged(self):
     """
     Monitor the PKC settings for changes made by the user
     """
     LOG.debug('PKC settings change detected')
     changed = False
     # Reset the window variables from the settings variables
     for settings_value, window_value in WINDOW_SETTINGS.iteritems():
         if window(window_value) != settings(settings_value):
             changed = True
             LOG.debug('PKC window settings changed: %s is now %s',
                       settings_value, settings(settings_value))
             window(window_value, value=settings(settings_value))
     # Reset the state variables in state.py
     for settings_value, state_name in STATE_SETTINGS.iteritems():
         new = settings(settings_value)
         if new == 'true':
             new = True
         elif new == 'false':
             new = False
         if getattr(state, state_name) != new:
             changed = True
             LOG.debug('PKC state settings %s changed from %s to %s',
                       settings_value, getattr(state, state_name), new)
             setattr(state, state_name, new)
             if state_name == 'FETCH_PMS_ITEM_NUMBER':
                 LOG.info('Requesting playlist/nodes refresh')
                 plex_command('RUN_LIB_SCAN', 'views')
     # Special cases, overwrite all internal settings
     set_replace_paths()
     state.BACKGROUND_SYNC_DISABLED = settings(
         'enableBackgroundSync') == 'false'
     state.FULL_SYNC_INTERVALL = int(settings('fullSyncInterval')) * 60
     state.BACKGROUNDSYNC_SAFTYMARGIN = int(
         settings('backgroundsync_saftyMargin'))
     state.SYNC_THREAD_NUMBER = int(settings('syncThreadNumber'))
     state.SSL_CERT_PATH = settings('sslcert') \
         if settings('sslcert') != 'None' else None
     # Never set through the user
     # state.KODI_PLEX_TIME_OFFSET = float(settings('kodiplextimeoffset'))
     if changed is True:
         # Assume that the user changed the settings so that we can now find
         # the path to all media files
         state.STOP_SYNC = False
         state.PATH_VERIFIED = False
Beispiel #5
0
 def play():
     """
     Start up playback_starter in main Python thread
     """
     # Put the request into the 'queue'
     plex_command('PLAY', argv[2])
     # Wait for the result
     while not pickl_window('plex_result'):
         sleep(50)
     result = unpickle_me()
     if result is None:
         log.error('Error encountered, aborting')
         dialog('notification',
                heading='{plex}',
                message=lang(30128),
                icon='{error}',
                time=3000)
         setResolvedUrl(HANDLE, False, ListItem())
     elif result.listitem:
         listitem = convert_PKC_to_listitem(result.listitem)
         setResolvedUrl(HANDLE, True, listitem)
Beispiel #6
0
def togglePlexTV():
    if settings('plexToken'):
        log.info('Reseting plex.tv credentials in settings')
        settings('plexLogin', value="")
        settings('plexToken', value="")
        settings('plexid', value="")
        settings('plexHomeSize', value="1")
        settings('plexAvatar', value="")
        settings('plex_status', value=lang(39226))

        window('plex_token', clear=True)
        plex_command('PLEX_TOKEN', '')
        plex_command('PLEX_USERNAME', '')
    else:
        log.info('Login to plex.tv')
        import initialsetup
        initialsetup.InitialSetup().plex_tv_sign_in()
    dialog('notification',
           lang(29999),
           lang(39221),
           icon='{plex}',
           time=3000,
           sound=False)
Beispiel #7
0
def chooseServer():
    """
    Lets user choose from list of PMS
    """
    log.info("Choosing PMS server requested, starting")

    import initialsetup
    setup = initialsetup.InitialSetup()
    server = setup.PickPMS(showDialog=True)
    if server is None:
        log.error('We did not connect to a new PMS, aborting')
        plex_command('SUSPEND_USER_CLIENT', 'False')
        plex_command('SUSPEND_LIBRARY_THREAD', 'False')
        return

    log.info("User chose server %s" % server['name'])
    setup.WritePMStoSettings(server)

    if not __LogOut():
        return

    from utils import deletePlaylists, deleteNodes
    # First remove playlists
    deletePlaylists()
    # Remove video nodes
    deleteNodes()

    # Log in again
    __LogIn()
    log.info("Choosing new PMS complete")
    # '<PMS> connected'
    dialog('notification',
           lang(29999),
           '%s %s' % (server['name'], lang(39220)),
           icon='{plex}',
           time=3000,
           sound=False)
Beispiel #8
0
def __LogOut():
    """
    Finishes lib scans, logs out user.

    Returns True if successfully signed out, False otherwise
    """
    # Resetting, please wait
    dialog('notification',
           lang(29999),
           lang(39207),
           icon='{plex}',
           time=3000,
           sound=False)
    # Pause library sync thread
    plex_command('SUSPEND_LIBRARY_THREAD', 'True')
    # Wait max for 10 seconds for all lib scans to shutdown
    counter = 0
    while window('plex_dbScan') == 'true':
        if counter > 200:
            # Failed to reset PMS and plex.tv connects. Try to restart Kodi.
            dialog('ok', lang(29999), lang(39208))
            # Resuming threads, just in case
            plex_command('SUSPEND_LIBRARY_THREAD', 'False')
            log.error("Could not stop library sync, aborting")
            return False
        counter += 1
        sleep(50)
    log.debug("Successfully stopped library sync")

    counter = 0
    # Log out currently signed in user:
    window('plex_serverStatus', value='401')
    plex_command('PMS_STATUS', '401')
    # Above method needs to have run its course! Hence wait
    while window('plex_serverStatus') == "401":
        if counter > 100:
            # 'Failed to reset PKC. Try to restart Kodi.'
            dialog('ok', lang(29999), lang(39208))
            log.error("Could not sign out user, aborting")
            return False
        counter += 1
        sleep(50)
    # Suspend the user client during procedure
    plex_command('SUSPEND_USER_CLIENT', 'True')
    return True
Beispiel #9
0
    def onNotification(self, sender, method, data):

        if data:
            data = loads(data, 'utf-8')
            log.debug("Method: %s Data: %s" % (method, data))

        if method == "Player.OnPlay":
            self.PlayBackStart(data)

        elif method == "Player.OnStop":
            # Should refresh our video nodes, e.g. on deck
            # xbmc.executebuiltin('ReloadSkin()')
            pass

        elif method == "VideoLibrary.OnUpdate":
            # Manually marking as watched/unwatched
            playcount = data.get('playcount')
            item = data.get('item')

            try:
                kodiid = item['id']
                item_type = item['type']
            except (KeyError, TypeError):
                log.info("Item is invalid for playstate update.")
            else:
                # Send notification to the server.
                with plexdb.Get_Plex_DB() as plexcur:
                    plex_dbitem = plexcur.getItem_byKodiId(kodiid, item_type)
                try:
                    itemid = plex_dbitem[0]
                except TypeError:
                    log.error("Could not find itemid in plex database for a "
                              "video library update")
                else:
                    # Stop from manually marking as watched unwatched, with
                    # actual playback.
                    if window('plex_skipWatched%s' % itemid) == "true":
                        # property is set in player.py
                        window('plex_skipWatched%s' % itemid, clear=True)
                    else:
                        # notify the server
                        if playcount > 0:
                            scrobble(itemid, 'watched')
                        else:
                            scrobble(itemid, 'unwatched')

        elif method == "VideoLibrary.OnRemove":
            pass

        elif method == "System.OnSleep":
            # Connection is going to sleep
            log.info("Marking the server as offline. SystemOnSleep activated.")
            window('plex_online', value="sleep")

        elif method == "System.OnWake":
            # Allow network to wake up
            sleep(10000)
            window('plex_onWake', value="true")
            window('plex_online', value="false")

        elif method == "GUI.OnScreensaverDeactivated":
            if settings('dbSyncScreensaver') == "true":
                sleep(5000)
                plex_command('RUN_LIB_SCAN', 'full')

        elif method == "System.OnQuit":
            log.info('Kodi OnQuit detected - shutting down')
            state.STOP_PKC = True
Beispiel #10
0
    def __init__(self):
        log.debug('Full sys.argv received: %s' % argv)
        # Parse parameters
        params = dict(parse_qsl(argv[2][1:]))
        mode = params.get('mode', '')
        itemid = params.get('id', '')

        if mode == 'play':
            self.play()

        elif mode == 'plex_node':
            self.play()

        elif mode == 'ondeck':
            entrypoint.getOnDeck(itemid, params.get('type'),
                                 params.get('tagname'),
                                 int(params.get('limit')))

        elif mode == 'recentepisodes':
            entrypoint.getRecentEpisodes(itemid, params.get('type'),
                                         params.get('tagname'),
                                         int(params.get('limit')))

        elif mode == 'nextup':
            entrypoint.getNextUpEpisodes(params['tagname'],
                                         int(params['limit']))

        elif mode == 'inprogressepisodes':
            entrypoint.getInProgressEpisodes(params['tagname'],
                                             int(params['limit']))

        elif mode == 'browseplex':
            entrypoint.browse_plex(key=params.get('key'),
                                   plex_section_id=params.get('id'))

        elif mode == 'getsubfolders':
            entrypoint.GetSubFolders(itemid)

        elif mode == 'watchlater':
            entrypoint.watchlater()

        elif mode == 'channels':
            entrypoint.channels()

        elif mode == 'settings':
            executebuiltin('Addon.OpenSettings(%s)' % v.ADDON_ID)

        elif mode == 'enterPMS':
            entrypoint.enterPMS()

        elif mode == 'reset':
            reset()

        elif mode == 'togglePlexTV':
            entrypoint.togglePlexTV()

        elif mode == 'resetauth':
            entrypoint.resetAuth()

        elif mode == 'passwords':
            passwords_xml()

        elif mode == 'switchuser':
            entrypoint.switchPlexUser()

        elif mode in ('manualsync', 'repair'):
            if window('plex_online') != 'true':
                # Server is not online, do not run the sync
                dialog('ok', lang(29999), lang(39205))
                log.error('Not connected to a PMS.')
            else:
                if mode == 'repair':
                    log.info('Requesting repair lib sync')
                    plex_command('RUN_LIB_SCAN', 'repair')
                elif mode == 'manualsync':
                    log.info('Requesting full library scan')
                    plex_command('RUN_LIB_SCAN', 'full')

        elif mode == 'texturecache':
            log.info('Requesting texture caching of all textures')
            plex_command('RUN_LIB_SCAN', 'textures')

        elif mode == 'chooseServer':
            entrypoint.chooseServer()

        elif mode == 'refreshplaylist':
            log.info('Requesting playlist/nodes refresh')
            plex_command('RUN_LIB_SCAN', 'views')

        elif mode == 'deviceid':
            self.deviceid()

        elif mode == 'fanart':
            log.info('User requested fanarttv refresh')
            plex_command('RUN_LIB_SCAN', 'fanart')

        elif '/extrafanart' in argv[0]:
            plexpath = argv[2][1:]
            plexid = itemid
            entrypoint.getExtraFanArt(plexid, plexpath)
            entrypoint.getVideoFiles(plexid, plexpath)

        # Called by e.g. 3rd party plugin video extras
        elif ('/Extras' in argv[0] or '/VideoFiles' in argv[0]
              or '/Extras' in argv[2]):
            plexId = itemid or None
            entrypoint.getVideoFiles(plexId, params)

        else:
            entrypoint.doMainListing(content_type=params.get('content_type'))