Merge pull request #898 from Hellowlol/ap_fix

fix result type, fixup responses from the ui to api
This commit is contained in:
JonnyWong16 2016-11-11 12:48:18 -08:00 committed by GitHub
commit 21d9091b43
3 changed files with 78 additions and 57 deletions

36
API.md
View file

@ -37,11 +37,11 @@ Get to the chopper!
### backup_config ### backup_config
Create a manual backup of the `config.ini` file. Create a manual backup of the `config.ini` file.
### backup_db ### backup_db
Create a manual backup of the `plexpy.db` file. Create a manual backup of the `plexpy.db` file.
### delete_all_library_history ### delete_all_library_history
@ -142,6 +142,18 @@ Returns:
``` ```
### delete_temp_sessions
Flush out all of the temporary sessions in the database.
```
Required parameters:
None
Required parameters:
None
```
### delete_user ### delete_user
Delete a user from PlexPy. Also erases all history for the user. Delete a user from PlexPy. Also erases all history for the user.
@ -158,11 +170,11 @@ Returns:
### docs ### docs
Return the api docs as a dict where commands are keys, docstring are value. Return the api docs as a dict where commands are keys, docstring are value.
### docs_md ### docs_md
Return the api docs formatted with markdown. Return the api docs formatted with markdown.
### download_log ### download_log
@ -755,11 +767,11 @@ Optional parameters:
Returns: Returns:
json: json:
[{"loglevel": "DEBUG", [{"loglevel": "DEBUG",
"msg": "Latest version is 2d10b0748c7fa2ee4cf59960c3d3fffc6aa9512b", "msg": "Latest version is 2d10b0748c7fa2ee4cf59960c3d3fffc6aa9512b",
"thread": "MainThread", "thread": "MainThread",
"time": "2016-05-08 09:36:51 " "time": "2016-05-08 09:36:51 "
}, },
{...}, {...},
{...} {...}
] ]
@ -1814,15 +1826,15 @@ Returns:
### refresh_libraries_list ### refresh_libraries_list
Refresh the PlexPy libraries list. Refresh the PlexPy libraries list.
### refresh_users_list ### refresh_users_list
Refresh the PlexPy users list. Refresh the PlexPy users list.
### restart ### restart
Restart PlexPy. Restart PlexPy.
### search ### search
@ -1905,7 +1917,7 @@ Uninstalls the GeoLite2 database
### update ### update
Check for PlexPy updates on Github. Check for PlexPy updates on Github.
### update_metadata_details ### update_metadata_details

View file

@ -47,7 +47,7 @@ class API2:
self._api_cmd = None self._api_cmd = None
self._api_apikey = None self._api_apikey = None
self._api_callback = None # JSONP self._api_callback = None # JSONP
self._api_result_type = 'failed' self._api_result_type = 'error'
self._api_profileme = None # For profiling the api call self._api_profileme = None # For profiling the api call
self._api_kwargs = None # Cleaned kwargs self._api_kwargs = None # Cleaned kwargs
@ -95,7 +95,7 @@ class API2:
self._api_msg = 'Parameter cmd is required. Possible commands are: %s' % ', '.join(self._api_valid_methods) self._api_msg = 'Parameter cmd is required. Possible commands are: %s' % ', '.join(self._api_valid_methods)
elif 'cmd' in kwargs and kwargs.get('cmd') not in self._api_valid_methods: elif 'cmd' in kwargs and kwargs.get('cmd') not in self._api_valid_methods:
self._api_msg = 'Unknown command: %s. Possible commands are: %s' % (kwargs.get('cmd', ''), ', '.join(self._api_valid_methods)) self._api_msg = 'Unknown command: %s. Possible commands are: %s' % (kwargs.get('cmd', ''), ', '.join(sorted(self._api_valid_methods)))
self._api_callback = kwargs.pop('callback', None) self._api_callback = kwargs.pop('callback', None)
self._api_apikey = kwargs.pop('apikey', None) self._api_apikey = kwargs.pop('apikey', None)
@ -137,17 +137,16 @@ class API2:
Returns: Returns:
json: json:
[{"loglevel": "DEBUG", [{"loglevel": "DEBUG",
"msg": "Latest version is 2d10b0748c7fa2ee4cf59960c3d3fffc6aa9512b", "msg": "Latest version is 2d10b0748c7fa2ee4cf59960c3d3fffc6aa9512b",
"thread": "MainThread", "thread": "MainThread",
"time": "2016-05-08 09:36:51 " "time": "2016-05-08 09:36:51 "
}, },
{...}, {...},
{...} {...}
] ]
``` ```
""" """
logfile = os.path.join(plexpy.CONFIG.LOG_DIR, logger.FILENAME) logfile = os.path.join(plexpy.CONFIG.LOG_DIR, logger.FILENAME)
templog = [] templog = []
start = int(kwargs.get('start', 0)) start = int(kwargs.get('start', 0))
@ -213,7 +212,6 @@ class API2:
if order == 'desc': if order == 'desc':
templog = templog[::-1] templog = templog[::-1]
self.data = templog
return templog return templog
def get_settings(self, key=''): def get_settings(self, key=''):
@ -257,7 +255,7 @@ class API2:
config[k]['interface_list'] = interface_list config[k]['interface_list'] = interface_list
if key: if key:
return config.get(key, None) return config.get(key)
return config return config
@ -297,18 +295,13 @@ class API2:
db = database.MonitorDatabase() db = database.MonitorDatabase()
rows = db.select(query) rows = db.select(query)
self.data = rows
return rows return rows
def backup_config(self): def backup_config(self):
""" Create a manual backup of the `config.ini` file. """ """ Create a manual backup of the `config.ini` file. """
data = config.make_backup() data = config.make_backup()
self._api_result_type = 'success' if data else 'error'
if data:
self.result_type = 'success'
else:
self.result_type = 'failed'
return data return data
@ -316,11 +309,7 @@ class API2:
""" Create a manual backup of the `plexpy.db` file. """ """ Create a manual backup of the `plexpy.db` file. """
data = database.make_backup() data = database.make_backup()
self._api_result_type = 'success' if data else 'error'
if data:
self.result_type = 'success'
else:
self.result_type = 'failed'
return data return data
@ -329,34 +318,26 @@ class API2:
plexpy.SIGNAL = 'restart' plexpy.SIGNAL = 'restart'
self._api_msg = 'Restarting plexpy' self._api_msg = 'Restarting plexpy'
self.result_type = 'success' self._api_result_type = 'success'
def update(self, **kwargs): def update(self, **kwargs):
""" Check for PlexPy updates on Github. """ """ Check for PlexPy updates on Github. """
plexpy.SIGNAL = 'update' plexpy.SIGNAL = 'update'
self._api_msg = 'Updating plexpy' self._api_msg = 'Updating plexpy'
self.result_type = 'success' self._api_result_type = 'success'
def refresh_libraries_list(self, **kwargs): def refresh_libraries_list(self, **kwargs):
""" Refresh the PlexPy libraries list. """ """ Refresh the PlexPy libraries list. """
data = pmsconnect.refresh_libraries() data = pmsconnect.refresh_libraries()
self._api_result_type = 'success' if data else 'error'
if data:
self.result_type = 'success'
else:
self.result_type = 'failed'
return data return data
def refresh_users_list(self, **kwargs): def refresh_users_list(self, **kwargs):
""" Refresh the PlexPy users list. """ """ Refresh the PlexPy users list. """
data = plextv.refresh_users() data = plextv.refresh_users()
self._api_result_type = 'success' if data else 'error'
if data:
self.result_type = 'success'
else:
self.result_type = 'failed'
return data return data
@ -423,30 +404,33 @@ General optional parameters:
string: "apikey" string: "apikey"
``` ```
""" """
data = None
apikey = hashlib.sha224(str(random.getrandbits(256))).hexdigest()[0:32] apikey = hashlib.sha224(str(random.getrandbits(256))).hexdigest()[0:32]
if plexpy.CONFIG.HTTP_USERNAME and plexpy.CONFIG.HTTP_PASSWORD: if plexpy.CONFIG.HTTP_USERNAME and plexpy.CONFIG.HTTP_PASSWORD:
if username == plexpy.HTTP_USERNAME and password == plexpy.CONFIG.HTTP_PASSWORD: if username == plexpy.HTTP_USERNAME and password == plexpy.CONFIG.HTTP_PASSWORD:
if plexpy.CONFIG.API_KEY: if plexpy.CONFIG.API_KEY:
self.data = plexpy.CONFIG.API_KEY data = plexpy.CONFIG.API_KEY
else: else:
self.data = apikey data = apikey
plexpy.CONFIG.API_KEY = apikey plexpy.CONFIG.API_KEY = apikey
plexpy.CONFIG.write() plexpy.CONFIG.write()
else: else:
self._api_msg = 'Authentication is enabled, please add the correct username and password to the parameters' self._api_msg = 'Authentication is enabled, please add the correct username and password to the parameters'
else: else:
if plexpy.CONFIG.API_KEY: if plexpy.CONFIG.API_KEY:
self.data = plexpy.CONFIG.API_KEY data = plexpy.CONFIG.API_KEY
else: else:
# Make a apikey if the doesn't exist # Make a apikey if the doesn't exist
self.data = apikey data = apikey
plexpy.CONFIG.API_KEY = apikey plexpy.CONFIG.API_KEY = apikey
plexpy.CONFIG.write() plexpy.CONFIG.write()
return self.data return data
def _api_responds(self, result_type='success', data=None, msg=''): def error(self, **kwargs):
return 1 / 0
def _api_responds(self, result_type='error', data=None, msg=''):
""" Formats the result to a predefined dict so we can hange it the to """ Formats the result to a predefined dict so we can hange it the to
the desired output by _api_out_as """ the desired output by _api_out_as """
@ -483,6 +467,7 @@ General optional parameters:
logger.info(u'PlexPy APIv2 :: ' + traceback.format_exc()) logger.info(u'PlexPy APIv2 :: ' + traceback.format_exc())
out['message'] = traceback.format_exc() out['message'] = traceback.format_exc()
out['result'] = 'error' out['result'] = 'error'
elif self._api_out_type == 'xml': elif self._api_out_type == 'xml':
cherrypy.response.headers['Content-Type'] = 'application/xml' cherrypy.response.headers['Content-Type'] = 'application/xml'
try: try:
@ -524,13 +509,16 @@ General optional parameters:
# We allow this to fail so we get a # We allow this to fail so we get a
# traceback in the browser # traceback in the browser
if self._api_debug: try:
result = call(**self._api_kwargs) result = call(**self._api_kwargs)
else: except Exception as e:
try: logger.error(u'PlexPy APIv2 :: Failed to run %s %s %s' % (self._api_cmd, self._api_kwargs, e))
result = call(**self._api_kwargs) if self._api_debug:
except Exception as e: cherrypy.request.show_tracebacks = True
logger.error(u'PlexPy APIv2 :: Failed to run %s %s %s' % (self._api_cmd, self._api_kwargs, e)) # Reraise the exception so the traceback hits the browser
raise
self._api_msg = 'Check the log'
ret = None ret = None
# The api decorated function can return different result types. # The api decorated function can return different result types.
@ -561,4 +549,14 @@ General optional parameters:
else: else:
self._api_result_type = 'error' self._api_result_type = 'error'
# Since some of them metods use a api like response for the ui
# {result: error, message: 'Some shit happend'}
if isinstance(ret, dict):
if ret.get('message'):
self._api_msg = ret.get('message', {})
ret = {}
if ret.get('result'):
self._api_result_type = ret.get('result')
return self._api_out_as(self._api_responds(result_type=self._api_result_type, msg=self._api_msg, data=ret)) return self._api_out_as(self._api_responds(result_type=self._api_result_type, msg=self._api_msg, data=ret))

View file

@ -329,7 +329,18 @@ class WebInterface(object):
@cherrypy.expose @cherrypy.expose
@cherrypy.tools.json_out() @cherrypy.tools.json_out()
@requireAuth(member_of("admin")) @requireAuth(member_of("admin"))
@addtoapi()
def delete_temp_sessions(self, **kwargs): def delete_temp_sessions(self, **kwargs):
""" Flush out all of the temporary sessions in the database.
```
Required parameters:
None
Required parameters:
None
```
"""
result = database.delete_sessions() result = database.delete_sessions()