Example #1
0
	def post(self):
		global AUTHTOKEN
		# Let's start by checking if the server is online
		if plexTV().auth2myPlex():
			token = ''
			try:
				# Authenticate
				retVal = plexTV().isServerOwner(plexTV().login(self))
				self.clear()
				if retVal == 0:
					# All is good
					self.allow()
					self.redirect('/')
				elif retVal == 1:
					# Server not found				
					self.set_status(404)
				elif retVal == 2:
					# Not the owner
					self.set_status(403)
				else:
					# Unknown error
					self.set_status(403)
			except Ex.HTTPError, e:
				self.clear()
				self.set_status(e.code)
				self.finish(e)
				return self
Example #2
0
 def post(self):
     global AUTHTOKEN
     # Let's start by checking if the server is online
     if plexTV().auth2myPlex():
         token = ''
         try:
             # Authenticate
             retVal = plexTV().isServerOwner(plexTV().login(self))
             self.clear()
             if retVal == 0:
                 # All is good
                 self.allow()
                 self.redirect('/')
             elif retVal == 1:
                 # Server not found
                 self.set_status(404)
             elif retVal == 2:
                 # Not the owner
                 self.set_status(403)
             else:
                 # Unknown error
                 self.set_status(403)
         except Ex.HTTPError, e:
             self.clear()
             self.set_status(e.code)
             self.finish(e)
             return self
Example #3
0
 def getVersion(self):
     retVal = {
         'version': VERSION,
         'PasswordSet': Dict['pwdset'],
         'PlexTVOnline': plexTV().auth2myPlex()
     }
     Log.Info('Version requested, returning ' + str(retVal))
     return retVal
Example #4
0
 def GETUSERS(self, req, *args):
     include = 0
     try:
         if args:
             # We got additional arguments
             if len(args) > 0:
                 # Get them in lower case
                 arguments = [item.lower() for item in list(args)[0]]
             # Get include parameter
             if 'include' in arguments:
                 # Get the include
                 include = arguments[arguments.index('include') + 1]
                 if not include.isdigit():
                     INCLUDE = misc.enum('users', 'users_self', 'users_all',
                                         'users_self_all')
                     include = getattr(INCLUDE, include)
             else:
                 # Copy from the Owner
                 include = 0
         else:
             include = 0
     except:
         pass
     """Get list of users"""
     try:
         users = plexTV().getUserList()
         if include > 0:
             addSelf = '-- ' + self.GETTRANSLATE(
                 None, None, Internal=True, String='Self') + ' --'
             addAll = '-- ' + self.GETTRANSLATE(
                 None, None, Internal=True, String='All') + ' --'
         if include == '1':
             users['1'] = {"username": addSelf, "title": addSelf}
         elif include == '2':
             users['2'] = {"username": addAll, "title": addAll}
         elif include == '3':
             users['1'] = {"username": addSelf, "title": addSelf}
             users['2'] = {"username": addAll, "title": addAll}
         else:
             pass
         req.clear()
         if users is None:
             Log.Error('Access denied towards plex.tv')
             req.set_status(401)
         else:
             req.set_status(200)
             req.set_header('Content-Type',
                            'application/json; charset=utf-8')
             req.finish(json.dumps(users))
     except Exception, e:
         Log.Exception('Fatal error happened in wt.getUsers: ' + str(e))
         req.clear()
         req.set_status(e.code)
         req.finish('Fatal error happened in wt.getUsers: %s' % (str(e)))
Example #5
0
 def GETUSERS(self, req, *args):
     try:
         users = plexTV().getUserList()
         req.clear()
         if users == None:
             Log.Error('Access denied towards plex.tv')
             req.set_status(401)
         else:
             req.set_status(200)
             req.set_header(
                 'Content-Type', 'application/json; charset=utf-8')
             req.finish(json.dumps(users))
     except Exception, e:
         Log.Exception('Fatal error happened in wt.getUsers: ' + str(e))
         req.clear()
         req.set_status(e.code)
         req.finish('Fatal error happened in wt.getUsers: %s' % (str(e)))
Example #6
0
 def getVersion(self):
     try:
         scheme = Dict['wt_csstheme']
         if scheme == None:
             scheme = ''
         retVal = {
             'version': VERSION,
             'PasswordSet': Dict['pwdset'],
             'PlexTVOnline': plexTV().auth2myPlex(),
             'wt_csstheme': scheme,
             'UILanguageDebug': UILANGUAGEDEBUG,
             'UILanguage': Dict['UILanguage'],
             'WT_URL': WT_URL
         }
         Log.Info('Version requested, returning ' + str(retVal))
         return retVal
     except Exception, e:
         Log.Exception('Exception in getVersion: %s' % (str(e)))
Example #7
0
 def LIST(self, req, *args):
     try:
         user = None
         if args != None:
             # We got additional arguments
             if len(args) > 0:
                 # Get them in lower case
                 arguments = [item.lower() for item in list(args)[0]]
                 if 'user' in arguments:
                     # Get key of the user
                     user = arguments[arguments.index('user') + 1]
         # So now user is either none or a keyId
         if user == None:
             playlists = XML.ElementFromURL(self.getListsURL)
         else:
             # Darn....Hard work ahead..We have to logon as another user here :-(
             users = plexTV().getUserList()
             myHeader = {}
             myHeader['X-Plex-Token'] = users[user]['accessToken']
             # TODO Change to native framework call, when Plex allows token in header
             request = urllib2.Request(self.getListsURL, headers=myHeader)
             playlists = XML.ElementFromString(
                 urllib2.urlopen(request).read())
             # playlists = XML.ElementFromURL(self.getListsURL, headers=myHeader)
         result = {}
         for playlist in playlists:
             id = playlist.get('ratingKey')
             result[id] = {}
             result[id]['title'] = playlist.get('title')
             result[id]['summary'] = playlist.get('summary')
             result[id]['smart'] = playlist.get('smart')
             result[id]['playlistType'] = playlist.get('playlistType')
         req.set_status(200)
         req.set_header('Content-Type', 'application/json; charset=utf-8')
         req.finish(json.dumps(result))
     except Exception, e:
         Log.Exception('Fatal error happened in playlists.list: ' + str(e))
         req.clear()
         req.set_status(500)
         req.finish('Fatal error happened in playlists.list: %s' % (str(e)))
Example #8
0
 def LIST(self, req, *args):
     try:
         user = None
         if args != None:
             # We got additional arguments
             if len(args) > 0:
                 # Get them in lower case
                 arguments = [item.lower() for item in list(args)[0]]
                 if 'user' in arguments:
                     # Get key of the user
                     user = arguments[arguments.index('user') + 1]
         # So now user is either none or a keyId
         if user == None:
             playlists = XML.ElementFromURL(self.getListsURL)
         else:
             # Darn....Hard work ahead..We have to logon as another user here :-(
             users = plexTV().getUserList()
             myHeader = {}
             myHeader['X-Plex-Token'] = users[user]['accessToken']
             # TODO Change to native framework call, when Plex allows token in header
             request = urllib2.Request(self.getListsURL, headers=myHeader)
             playlists = XML.ElementFromString(
                 urllib2.urlopen(request).read())
             # playlists = XML.ElementFromURL(self.getListsURL, headers=myHeader)
         result = {}
         for playlist in playlists:
             id = playlist.get('ratingKey')
             result[id] = {}
             result[id]['title'] = playlist.get('title')
             result[id]['summary'] = playlist.get('summary')
             result[id]['smart'] = playlist.get('smart')
             result[id]['playlistType'] = playlist.get('playlistType')
         req.set_status(200)
         req.set_header('Content-Type', 'application/json; charset=utf-8')
         req.finish(json.dumps(result))
     except Exception, e:
         Log.Exception('Fatal error happened in playlists.list: ' + str(e))
         req.clear()
         req.set_status(500)
         req.finish('Fatal error happened in playlists.list: %s' % (str(e)))
Example #9
0
 def COPY(self, req, *args):
     users = None
     # Start by getting the key of the PlayList
     if args != None:
         # We got additional arguments
         if len(args) > 0:
             # Get them in lower case
             arguments = [item.lower() for item in list(args)[0]]
         else:
             Log.Critical('Missing Arguments')
             req.clear()
             req.set_status(412)
             req.finish('Missing Arguments')
         # Get playlist Key
         if 'key' in arguments:
             # Get key of the user
             key = arguments[arguments.index('key') + 1]
         else:
             Log.Error('Missing key of playlist')
             req.clear()
             req.set_status(412)
             req.finish('Missing key of playlist')
         # Get UserFrom
         if 'userfrom' in arguments:
             # Get the userfrom
             userfrom = arguments[arguments.index('userfrom') + 1]
         else:
             # Copy from the Owner
             userfrom = None
         # Get UserTo
         if 'userto' in arguments:
             # Get the userto
             userto = arguments[arguments.index('userto') + 1]
         else:
             Log.Error('Missing target user of playlist')
             req.clear()
             req.set_status(412)
             req.finish('Missing targetuser of playlist')
         # Get user list, among with access token
         users = plexTV().getUserList()
         # Get the playlist that needs to be copied
         url = misc.GetLoopBack() + '/playlists/' + key + '/items'
         if userfrom == None:
             # Get it from the owner
             playlist = XML.ElementFromURL(url)
         else:
             # We need to logon as specified user
             try:
                 # Get user playlist
                 # TODO Change to native framework call, when Plex allows token in header
                 opener = urllib2.build_opener(urllib2.HTTPHandler)
                 request = urllib2.Request(url)
                 request.add_header('X-Plex-Token',
                                    users[userfrom]['accessToken'])
                 response = opener.open(request).read()
                 playlist = XML.ElementFromString(response)
             except Ex.HTTPError, e:
                 Log.Exception(
                     'HTTP exception  when downloading a playlist for the owner was: %s'
                     % (e))
                 req.clear()
                 req.set_status(e.code)
                 req.finish(str(e))
             except Exception, e:
                 Log.Exception(
                     'Exception happened when downloading a playlist for the user was: %s'
                     % (str(e)))
                 req.clear()
                 req.set_status(500)
                 req.finish(
                     'Exception happened when downloading a playlist for the user was: %s'
                     % (str(e)))
Example #10
0
class viewstate(object):
    @classmethod
    def init(self):
        return

    '''
    This metode will import a viewlist file
    * Param: localFile (In the payload)
    * Param: User (In param, optional, and if missing, is the uwner)
    * Param: Section (In param, and mandentory)
    '''
    @classmethod
    def IMPORT(self, req, *args):
        print '*********** GED ***********'
        print 'Ged logon as not owner', 'Check access denied', 'Make it a thread', 'Make a method to grap status', 'Make it possible to abort'

        Log.Info('ViewState Import called')
        # Payload Upload file present?
        if not 'localFile' in req.request.files:
            req.clear()
            req.set_status(412)
            req.finish(
                'Missing upload file parameter named \
                localFile from the payload')
        else:
            localFile = req.request.files['localFile'][0]['body']
        # Get parameters from url
        try:
            user = None
            if args is not None:
                # We got additional arguments
                if len(args) > 0:
                    # Get them in lower case
                    arguments = [item.lower() for item in list(args)[0]]
                    if 'user' in arguments:
                        # Get key of the user
                        user = arguments[arguments.index('user') + 1]
                    if 'section' in arguments:
                        # Get Section Number
                        section = arguments[arguments.index('section') + 1]
                    else:
                        section = None
            if not section:
                req.clear()
                req.set_status(412)
                req.finish('Missing import file parameter named Section')
        except Exception, e:
            Log.Exception(
                'Exception happened in ViewState Import was: %s' % (str(e)))
            req.clear()
            req.set_status(500)
            req.finish(
                'Exception happened in ViewState Import was: %s' % (str(e)))

        # So now user is either none or a keyId
        if user:
            # Darn....Hard work ahead..We have
            # to logon as another user here :-(
            result['user'] = user
            # Get user list, among with their access tokens
            users = plexTV().getUserList()

            print 'Ged Users', users
        else:
            print 'User is the owner'

        try:
            ViewState = json.loads(localFile)
            Log.Info('Import returned %s' %
                     (json.dumps(ViewState, ensure_ascii=False)))
            watched = ViewState['watched']
            print 'Ged Watched', watched
            ServerId = ViewState['serverId']
            sectionType = ViewState['sectionType']

            CurrentServerId = XML.ElementFromURL(
                misc.GetLoopBack() + '/identity').get('machineIdentifier')
            print 'Ged ServedID', CurrentServerId, ServerId
            self.ImportFile(ServerId == CurrentServerId)
            '''
            if ServerId == CurrentServerId:
                # Same Server, so no need to search here :)
                print 'Ged Same server detected'
                Log.Debug('Same Server detected, so no need to search here')
                self.setWatched(req, watched, user, None)

            else:
                # We need to search sadly
                Log.Debug(
                    'New server, so we need to search here, limited to selected section key')
                print 'Ged do stuff but search first'
                watched = self.SearchMedia(req, watched, section, sectionType)
                self.setWatched(req, watched, user, None)
            '''
        except Exception, e:
            Log.Exception(
                'Exception happened in ViewState Import was: %s' % (str(e)))
            req.clear()
            req.set_status(500)
            req.finish(
                'Exception happened in ViewState Import was: %s' % (str(e)))
Example #11
0
	def getVersion(self):
		retVal = {'version': VERSION, 
						'PasswordSet': Dict['pwdset'],
						'PlexTVOnline': plexTV().auth2myPlex()}
		Log.Info('Version requested, returning ' + str(retVal))
		return retVal
Example #12
0
         req.set_status(e.code)
         req.finish(str(e))
     except Exception, e:
         Log.Exception(
             'Exception happened when deleting a playlist for the owner was: %s'
             % (str(e)))
         req.clear()
         req.set_status(500)
         req.finish(
             'Exception happened when deleting a playlist for the owner was: %s'
             % (str(e)))
 else:
     # We need to logon as a user in order to nuke the playlist
     try:
         # Get user list, among with their access tokens
         users = plexTV().getUserList()
         # Detele the playlist
         deletePlayLIstforUsr(req, key, users[user]['accessToken'])
     except Ex.HTTPError, e:
         Log.Exception(
             'HTTP exception  when deleting a playlist for the owner was: %s'
             % (e))
         req.clear()
         req.set_status(e.code)
         req.finish(str(e))
     except Exception, e:
         Log.Exception(
             'Exception happened when deleting a playlist for the user was: %s'
             % (str(e)))
         req.clear()
         req.set_status(500)
Example #13
0
	def post(self):
		global AUTHTOKEN
		# Check for an auth header, in case a frontend wanted to use that
		# Header has precedence compared to params
		auth_header = self.request.headers.get('Authorization', None)
		if auth_header is None or not auth_header.startswith('Basic '):
			Log.Info('No Basic Auth header, so looking for params')
			user = self.get_argument('user', '')
			if user == '':
				if plexTV().auth2myPlex():
					Log.Info('Missing username')
					self.clear()
					self.set_status(412)
					self.finish("<html><body>Missing username</body></html>")
			pwd = self.get_argument('pwd', '')
			if pwd == '':
				Log.Info('Missing password')
				self.clear()
				self.set_status(412)
				self.finish("<html><body>Missing password</body></html>")
		else:
			Log.Info('Auth header found')
			auth_decoded = String.Base64Decode(auth_header[6:])
			user, pwd = auth_decoded.split(':', 2)
		Log.Info('User is: ' + user)
		# Allow no password when in debug mode
		if DEBUGMODE:
			if not WT_AUTH:
				self.allow()
				Log.Info('All is good, we are authenticated')
				self.redirect('/')
			else:
				# Let's start by checking if the server is online
				if plexTV().auth2myPlex():
					token = ''
					try:
						# Authenticate
						login_token = plexTV().login(user, pwd)
						if login_token == None:	
							Log.ERROR('Bad credentials detected, denying access')
							self.clear()
							self.set_status(401)
							self.finish('Authentication error')
							return self
						retVal = plexTV().isServerOwner(login_token)
						self.clear()
						if retVal == 0:
							# All is good
							self.allow()
							Log.Info('All is good, we are authenticated')
							self.redirect('/')
						elif retVal == 1:
							# Server not found
							Log.Info('Server not found on plex.tv')
							self.set_status(404)
						elif retVal == 2:
							# Not the owner
							Log.Info('USer is not the server owner')
							self.set_status(403)
						else:
							# Unknown error
							Log.Critical('Unknown error, when authenticating')
							self.set_status(403)
					except Ex.HTTPError, e:
						Log.Exception('Exception in Login: ' + str(e))
						self.clear()
						self.set_status(e.code)
						self.finish(str(e))
						return self
Example #14
0
	def post(self):
		global AUTHTOKEN

		# Check for an auth header, in case a frontend wanted to use that
		# Header has precedence compared to params
		auth_header = self.request.headers.get('Authorization', None)
		if auth_header is None or not auth_header.startswith('Basic '):
			Log.Info('No Basic Auth header, so looking for params')
			user = self.get_argument('user', '')
			if user == '':
				if plexTV().auth2myPlex():
					Log.Info('Missing username')
					self.clear()
					self.set_status(412)
					self.finish("<html><body>Missing username</body></html>")
			pwd = self.get_argument('pwd', '')
			if pwd == '':
				Log.Info('Missing password')
				self.clear()
				self.set_status(412)
				self.finish("<html><body>Missing password</body></html>")
		else:
			Log.Info('Auth header found')
			auth_decoded = String.Base64Decode(auth_header[6:])
			user, pwd = auth_decoded.split(':', 2)
		Log.Info('User is: ' + user)
		# Allow no password when in debug mode
		if DEBUGMODE:
			self.allow()
			Log.Info('All is good, we are authenticated')
			self.redirect('/')
		# Let's start by checking if the server is online
		if plexTV().auth2myPlex():
			token = ''
			try:
				# Authenticate
				retVal = plexTV().isServerOwner(plexTV().login(user, pwd))
				self.clear()
				if retVal == 0:
					# All is good
					self.allow()
					Log.Info('All is good, we are authenticated')
					self.redirect('/')
				elif retVal == 1:
					# Server not found
					Log.Info('Server not found on plex.tv')
					self.set_status(404)
				elif retVal == 2:
					# Not the owner
					Log.Info('USer is not the server owner')
					self.set_status(403)
				else:
					# Unknown error
					Log.Critical('Unknown error, when authenticating')
					self.set_status(403)
			except Ex.HTTPError, e:
				Log.Critical('Exception in Login: ' + str(e))
				self.clear()
				self.set_status(e.code)
				self.finish(e)
				return self
Example #15
0
							# Not the owner
							Log.Info('USer is not the server owner')
							self.set_status(403)
						else:
							# Unknown error
							Log.Critical('Unknown error, when authenticating')
							self.set_status(403)
					except Ex.HTTPError, e:
						Log.Exception('Exception in Login: '******'s start by checking if the server is online
			if plexTV().auth2myPlex():
				token = ''
				try:
					# Authenticate
					login_token = plexTV().login(user, pwd)
					if login_token == None:	
						Log.ERROR('Bad credentials detected, denying access')
						self.clear()
						self.set_status(401)
						self.finish('Authentication error')
						return self
					retVal = plexTV().isServerOwner(login_token)
					self.clear()
					if retVal == 0:
						# All is good
						self.allow()
Example #16
0
 def getVersion(self):
     try:
         scheme = Dict['wt_csstheme']
         if scheme == None:
             scheme = ''
         retVal = {'version': VERSION, 'PasswordSet': Dict['pwdset'], 'PlexTVOnline': plexTV().auth2myPlex(
         ), 'wt_csstheme': scheme, 'UILanguageDebug': UILANGUAGEDEBUG, 'UILanguage': Dict['UILanguage'], 'WT_URL': WT_URL}
         Log.Info('Version requested, returning ' + str(retVal))
         return retVal
     except Exception, e:
         Log.Exception('Exception in getVersion: %s' % (str(e)))
Example #17
0
             except Ex.HTTPError, e:
                 Log.Exception('Exception in Login: '******'Exception in Login: '******'s start by checking if the server is online
     try:
         if plexTV().auth2myPlex():
             token = ''
             try:
                 # Authenticate
                 login_token = plexTV().login(user, pwd)
                 if login_token == None:
                     Log.Error(
                         'Bad credentials detected, denying access')
                     self.clear()
                     self.set_status(401)
                     self.finish('Authentication error')
                     return self
                 retVal = plexTV().isServerOwner(login_token)
                 self.clear()
                 if retVal == 0:
                     # All is good
Example #18
0
             'HTTP exception  when deleting a playlist for the owner was: %s' % (e))
         req.clear()
         req.set_status(e.code)
         req.finish(str(e))
     except Exception, e:
         Log.Exception(
             'Exception happened when deleting a playlist for the owner was: %s' % (str(e)))
         req.clear()
         req.set_status(500)
         req.finish(
             'Exception happened when deleting a playlist for the owner was: %s' % (str(e)))
 else:
     # We need to logon as a user in order to nuke the playlist
     try:
         # Get user list, among with their access tokens
         users = plexTV().getUserList()
         # Detele the playlist
         deletePlayLIstforUsr(req, key, users[user]['accessToken'])
     except Ex.HTTPError, e:
         Log.Exception(
             'HTTP exception  when deleting a playlist for the owner was: %s' % (e))
         req.clear()
         req.set_status(e.code)
         req.finish(str(e))
     except Exception, e:
         Log.Exception(
             'Exception happened when deleting a playlist for the user was: %s' % (str(e)))
         req.clear()
         req.set_status(500)
         req.finish(
             'Exception happened when deleting a playlist for the user was: %s' % (str(e)))
Example #19
0
 def COPY(self, req, *args):
     users = None
     # Start by getting the key of the PlayList
     if args != None:
         # We got additional arguments
         if len(args) > 0:
             # Get them in lower case
             arguments = [item.lower() for item in list(args)[0]]
         else:
             Log.Critical('Missing Arguments')
             req.clear()
             req.set_status(412)
             req.finish('Missing Arguments')
         # Get playlist Key
         if 'key' in arguments:
             # Get key of the user
             key = arguments[arguments.index('key') + 1]
         else:
             Log.Error('Missing key of playlist')
             req.clear()
             req.set_status(412)
             req.finish('Missing key of playlist')
         # Get UserFrom
         if 'userfrom' in arguments:
             # Get the userfrom
             userfrom = arguments[arguments.index('userfrom') + 1]
         else:
             # Copy from the Owner
             userfrom = None
         # Get UserTo
         if 'userto' in arguments:
             # Get the userto
             userto = arguments[arguments.index('userto') + 1]
         else:
             Log.Error('Missing target user of playlist')
             req.clear()
             req.set_status(412)
             req.finish('Missing targetuser of playlist')
         # Get user list, among with access token
         users = plexTV().getUserList()
         # Get the playlist that needs to be copied
         url = misc.GetLoopBack() + '/playlists/' + key + '/items'
         if userfrom == None:
             # Get it from the owner
             playlist = XML.ElementFromURL(url)
         else:
             # We need to logon as specified user
             try:
                 # Get user playlist
                 # TODO Change to native framework call, when Plex allows token in header
                 opener = urllib2.build_opener(urllib2.HTTPHandler)
                 request = urllib2.Request(url)
                 request.add_header(
                     'X-Plex-Token', users[userfrom]['accessToken'])
                 response = opener.open(request).read()
                 playlist = XML.ElementFromString(response)
             except Ex.HTTPError, e:
                 Log.Exception(
                     'HTTP exception  when downloading a playlist for the owner was: %s' % (e))
                 req.clear()
                 req.set_status(e.code)
                 req.finish(str(e))
             except Exception, e:
                 Log.Exception(
                     'Exception happened when downloading a playlist for the user was: %s' % (str(e)))
                 req.clear()
                 req.set_status(500)
                 req.finish(
                     'Exception happened when downloading a playlist for the user was: %s' % (str(e)))