Fixed API code to work with tornado.

This commit is contained in:
echel0n 2014-06-15 14:45:09 -07:00
parent 1eb5fe4faf
commit 23e2a483b5
3 changed files with 15 additions and 19 deletions

View file

@ -36,8 +36,6 @@ from sickbeard import search_queue
from sickbeard.common import SNATCHED, SNATCHED_PROPER, DOWNLOADED, SKIPPED, UNAIRED, IGNORED, ARCHIVED, WANTED, UNKNOWN
from common import Quality, qualityPresetStrings, statusStrings
from sickbeard import image_cache
from tornado.httputil import HTTPHeaders
from tornado.web import RequestHandler
try:
import json
@ -66,12 +64,12 @@ result_type_map = {RESULT_SUCCESS: "success",
}
# basically everything except RESULT_SUCCESS / success is bad
class Api(RequestHandler):
class Api(webserve.IndexHandler):
""" api class that returns json results """
version = 4 # use an int since float-point is unpredictible
intent = 4
def default(self, *args, **kwargs):
def index(self, *args, **kwargs):
self.apiKey = sickbeard.API_KEY
access, accessMsg, args, kwargs = self._grand_access(self.apiKey, args, kwargs)
@ -163,10 +161,10 @@ class Api(RequestHandler):
def _out_as_json(self, dict):
""" set cherrypy response to json """
HTTPHeaders()['Content-Type'] = 'application/json;charset=UTF-8'
self.h["content-type"] = "application/json;charset=UTF-8"
try:
out = json.dumps(dict, indent=self.intent, sort_keys=True)
callback = 'callback' in HTTPHeaders() or 'jsonp' in HTTPHeaders()
callback = self.h.get('callback' ,None) or self.h.get('jsonp' ,None)
if callback != None:
out = callback + '(' + out + ');' # wrap with JSONP call if requested
except Exception, e: # if we fail to generate the output fake an error
@ -299,7 +297,7 @@ def filter_params(cmd, args, kwargs):
return curArgs, curKwargs
class ApiCall(object):
class ApiCall(Api):
_help = {"desc": "No help message available. Please tell the devs that a help msg is missing for this cmd"}
def __init__(self, args, kwargs):
@ -1314,6 +1312,7 @@ class CMD_SickBeardAddRootDir(ApiCall):
self.location = urllib.unquote_plus(self.location)
location_matched = 0
index = 0
# dissallow adding/setting an invalid dir
if not ek.ek(os.path.isdir, self.location):
@ -1338,7 +1337,6 @@ class CMD_SickBeardAddRootDir(ApiCall):
if (location_matched == 0):
if (self.default == 1):
index = 0
root_dirs.insert(0, self.location)
else:
root_dirs.append(self.location)
@ -1393,6 +1391,7 @@ class CMD_SickBeardDeleteRootDir(ApiCall):
if sickbeard.ROOT_DIRS == "":
return _responds(RESULT_FAILURE, _getRootDirs(), msg="No root directories detected")
newIndex = 0
root_dirs_new = []
root_dirs = sickbeard.ROOT_DIRS.split('|')
index = int(root_dirs[0])
@ -1507,7 +1506,7 @@ class CMD_SickBeardPing(ApiCall):
def run(self):
""" check to see if sickbeard is running """
HTTPHeaders()['Cache-Control'] = "max-age=0,no-cache,no-store"
self.h['Cache-Control'] = "max-age=0,no-cache,no-store"
if sickbeard.started:
return _responds(RESULT_SUCCESS, {"pid": sickbeard.PID}, "Pong")
else:

View file

@ -61,7 +61,6 @@ from sickbeard.scene_numbering import get_scene_numbering, set_scene_numbering,
from sickbeard.blackandwhitelist import BlackAndWhiteList
from webapi import Api
from browser import WebFileBrowser
from lib.dateutil import tz
@ -176,9 +175,6 @@ class IndexHandler(RedirectHandler):
if "X-Forwarded-Proto" in self.h:
self.sbHttpsEnabled = True if self.h['X-Forwarded-Proto'] == 'https' else False
if not self.get_secure_cookie('sickrage'):
self.set_secure_cookie('sickrage', str(time.time()))
def delist_arguments(self, args):
"""
Takes a dictionary, 'args' and de-lists any single-item lists then
@ -204,7 +200,7 @@ class IndexHandler(RedirectHandler):
return inspect.isclass(c) and c.__module__ == pred.__module__
try:
klass = [cls[1] for cls in inspect.getmembers(sys.modules[__name__], pred) if
klass = [cls[1] for cls in inspect.getmembers(sys.modules[__name__], pred) + [(self.__class__.__name__, self.__class__)] if
cls[0].lower() == method.lower() or method in cls[1].__dict__.keys()][0](self.application, self.request)
except:
klass = None
@ -218,7 +214,7 @@ class IndexHandler(RedirectHandler):
func = getattr(klass, method, None)
# Special index method handler for classes and subclasses:
if path.endswith('/'):
if path.startswith('/api') or path.endswith('/'):
if func and getattr(func, 'index', None):
func = getattr(func(self.application, self.request), 'index', None)
elif not func:
@ -481,7 +477,6 @@ class IndexHandler(RedirectHandler):
return ical
api = Api
browser = WebFileBrowser
class PageTemplate(Template):
@ -2518,7 +2513,7 @@ class HomePostProcess(IndexHandler):
return result
result = result.replace("\n", "<br />\n")
_genericMessage("Postprocessing results", result)
return _genericMessage("Postprocessing results", result)
class NewHomeAddShows(IndexHandler):
@ -3319,8 +3314,8 @@ class Home(IndexHandler):
t = PageTemplate(file="restart_bare.tmpl")
return _munge(t)
else:
return self.finish(_genericMessage("Update Failed",
"Update wasn't successful, not restarting. Check your log for more information."))
return _genericMessage("Update Failed",
"Update wasn't successful, not restarting. Check your log for more information.")
def displayShow(self, show=None):

View file

@ -1,6 +1,7 @@
import os
import sickbeard
import webserve
import webapi
from sickbeard import logger
from sickbeard.helpers import create_https_certificates
@ -102,6 +103,7 @@ def initWebServer(options={}):
app.add_handlers(".*$", [
(r"/", RedirectHandler, {'url': '/home/'}),
(r'/login', webserve.LoginHandler),
(r'/api', webapi.Api),
(r'%s(.*)(/?)' % options['web_root'], webserve.IndexHandler)
])