Exemplo n.º 1
0
    def getLog(self,iDisplayStart=0,iDisplayLength=100,iSortCol_0=0,sSortDir_0="desc",sSearch="",**kwargs):
        iDisplayStart = int(iDisplayStart)
        iDisplayLength = int(iDisplayLength)
        filtered = []
        if sSearch == "":
            filtered = lazylibrarian.LOGLIST[::]
        else:
            filtered = [row for row in lazylibrarian.LOGLIST for column in row if sSearch in column]

        sortcolumn = 0
        if iSortCol_0 == '1':
            sortcolumn = 2
        elif iSortCol_0 == '2':
            sortcolumn = 1
        filtered.sort(key=lambda x:x[sortcolumn],reverse=sSortDir_0 == "desc")        

        rows = filtered[iDisplayStart:(iDisplayStart+iDisplayLength)]
        rows = [[row[0],row[2],row[1]] for row in rows]

        dict = {'iTotalDisplayRecords':len(filtered),
                'iTotalRecords':len(lazylibrarian.LOGLIST),
                'aaData':rows,
                }
        s = simplejson.dumps(dict)
        return s
Exemplo n.º 2
0
    def getInfo(self, ArtistID=None, AlbumID=None):

        from headphones import cache

        info_dict = cache.getInfo(ArtistID, AlbumID)

        return simplejson.dumps(info_dict)
Exemplo n.º 3
0
    def getImageLinks(self, ArtistID=None, AlbumID=None):

        from headphones import cache

        image_dict = cache.getImageLinks(ArtistID, AlbumID)

        return simplejson.dumps(image_dict)
Exemplo n.º 4
0
    def getLog(self,iDisplayStart=0,iDisplayLength=100,iSortCol_0=0,sSortDir_0="desc",sSearch="",**kwargs):
        iDisplayStart = int(iDisplayStart)
        iDisplayLength = int(iDisplayLength)
        filtered = []
        if sSearch == "":
            filtered = lazylibrarian.LOGLIST[::]
        else:
            filtered = [row for row in lazylibrarian.LOGLIST for column in row if sSearch in column]

        sortcolumn = 0
        if iSortCol_0 == '1':
            sortcolumn = 2
        elif iSortCol_0 == '2':
            sortcolumn = 1
        filtered.sort(key=lambda x:x[sortcolumn],reverse=sSortDir_0 == "desc")        

        rows = filtered[iDisplayStart:(iDisplayStart+iDisplayLength)]
        rows = [[row[0],row[2],row[1]] for row in rows]

        dict = {'iTotalDisplayRecords':len(filtered),
                'iTotalRecords':len(lazylibrarian.LOGLIST),
                'aaData':rows,
                }
        s = simplejson.dumps(dict)
        return s
Exemplo n.º 5
0
class settings(object):
    exposed = True

    def GET(self, token=None):

        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        configuration = {
            "server": {
                "appName": cherrystrap.APP_NAME,
                "logDir": cherrystrap.LOGDIR,
                "httpHost": cherrystrap.HTTP_HOST,
                "httpPort": int(cherrystrap.HTTP_PORT),
                "sslEnabled": bool(cherrystrap.HTTPS_ENABLED),
                "sslKey": cherrystrap.HTTPS_KEY,
                "sslCert": cherrystrap.HTTPS_CERT,
                "sslVerify": bool(cherrystrap.VERIFY_SSL),
                "launchBrowser": bool(cherrystrap.LAUNCH_BROWSER)
            },
            "interface": {
                "httpUser": cherrystrap.HTTP_USER,
                "httpPass": cherrystrap.HTTP_PASS,
                "httpLook": cherrystrap.HTTP_LOOK,
                "apiToken": cherrystrap.API_TOKEN
            },
            "database": {
                "dbType": cherrystrap.DATABASE_TYPE,
                "mysqlHost": cherrystrap.MYSQL_HOST,
                "mysqlPort": int(cherrystrap.MYSQL_PORT),
                "mysqlUser": cherrystrap.MYSQL_USER,
                "mysqlPass": cherrystrap.MYSQL_PASS
            },
            "git": {
                "gitEnabled": bool(cherrystrap.GIT_ENABLED),
                "gitPath": cherrystrap.GIT_PATH,
                "gitUser": cherrystrap.GIT_USER,
                "gitRepo": cherrystrap.GIT_REPO,
                "gitBranch": cherrystrap.GIT_BRANCH,
                "gitUpstream": cherrystrap.GIT_UPSTREAM,
                "gitLocal": cherrystrap.GIT_LOCAL,
                "gitStartup": bool(cherrystrap.GIT_STARTUP),
                "gitInterval": int(cherrystrap.GIT_INTERVAL),
                "gitOverride": bool(cherrystrap.GIT_OVERRIDE)
            }
        }

        #===============================================================
        # Import a variable injector from your app's __init__.py
        try:
            from jiraappy import injectApiConfigGet
            configuration.update(injectApiConfigGet())
        except Exception, e:
            logger.debug(
                "There was a problem injection application variables into API-GET: %s"
                % e)
        #================================================================

        config = json.dumps(configuration)
        return config
Exemplo n.º 6
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        networking_array = subroutine.networkload_subroutine()

        return json.dumps(networking_array)
Exemplo n.º 7
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        partition_list = subroutine.partitions_subroutine()

        return json.dumps(partition_list)
Exemplo n.º 8
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        combined_final_list = subroutine.diskio_subroutine()

        return json.dumps(combined_final_list)
Exemplo n.º 9
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        cpu_arr = subroutine.static_subroutine()

        return json.dumps(cpu_arr)
Exemplo n.º 10
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        logfiles = subroutine.syslogs_subroutine()

        return json.dumps(logfiles)
Exemplo n.º 11
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        proc_tree = subroutine.sysprocesses_subroutine()

        return json.dumps(proc_tree)
def dump_json(data):
    logger.info("core.jsontools.dump_json Probando simplejson en directorio lib")

    try:
        logger.info("core.jsontools.dump_json Probando simplejson en directorio lib")
        from lib import simplejson

        json_data = simplejson.dumps(data, indent=4, skipkeys=True, sort_keys=True, ensure_ascii=False)
        # json_data = byteify(json_data)
        logger.info("core.jsontools.dump_json -> " + repr(json_data))
        return json_data
    except:
        logger.info(traceback.format_exc())

        try:
            logger.info("core.jsontools.dump_json Probando simplejson incluido en el interprete")
            import simplejson

            json_data = simplejson.dumps(data, indent=4, skipkeys=True, sort_keys=True, ensure_ascii=False)
            logger.info("core.jsontools.dump_json -> " + repr(json_data))
            return json_data
        except:
            logger.info(traceback.format_exc())

            try:
                logger.info("core.jsontools.dump_json Probando json incluido en el interprete")
                import json

                json_data = json.dumps(data, indent=4, skipkeys=True, sort_keys=True, ensure_ascii=False)
                logger.info("core.jsontools.dump_json -> " + repr(json_data))
                return json_data
            except:
                logger.info(traceback.format_exc())

                try:
                    logger.info("core.jsontools.dump_json Probando JSON de Plex")
                    json_data = JSON.StringFromObject(data)  # , encoding="utf-8")
                    logger.info("core.jsontools.dump_json -> " + repr(json_data))
                    return json_data
                except:
                    logger.info(traceback.format_exc())

    logger.info("core.jsontools.dump_json No se ha encontrado un parser de JSON valido")
    logger.info("core.jsontools.dump_json -> (nada)")
    return ""
Exemplo n.º 13
0
    def fetchData(self):

        if self.data == "OK":
            logger.info("Recieved API command: " + self.cmd)
            methodToCall = getattr(self, "_" + self.cmd)
            result = methodToCall(**self.kwargs)
            if "callback" not in self.kwargs:
                if type(self.data) == type(""):
                    return self.data
                else:
                    return simplejson.dumps(self.data)
            else:
                self.callback = self.kwargs["callback"]
                self.data = simplejson.dumps(self.data)
                self.data = self.callback + "(" + self.data + ");"
                return self.data
        else:
            return self.data
Exemplo n.º 14
0
 def fetchData(self):
     
     if self.data == 'OK':   
         logger.info('Recieved API command: ' + self.cmd)
         methodToCall = getattr(self, "_" + self.cmd)
         result = methodToCall(**self.kwargs)
         if 'callback' not in self.kwargs:
             if type(self.data) == type(''):
                 return self.data
             else:
                 return simplejson.dumps(self.data)
         else:
             self.callback = self.kwargs['callback']
             self.data = simplejson.dumps(self.data)
             self.data = self.callback + '(' + self.data + ');'
             return self.data
     else:
         return self.data
Exemplo n.º 15
0
    def fetchData(self):

        if self.data == 'OK':
            logger.info('Recieved API command: ' + self.cmd)
            methodToCall = getattr(self, "_" + self.cmd)
            result = methodToCall(**self.kwargs)
            if 'callback' not in self.kwargs:
                if type(self.data) == type(''):
                    return self.data
                else:
                    return simplejson.dumps(self.data)
            else:
                self.callback = self.kwargs['callback']
                self.data = simplejson.dumps(self.data)
                self.data = self.callback + '(' + self.data + ');'
                return self.data
        else:
            return self.data
Exemplo n.º 16
0
def dump_json(data):
    #logger.info("tvalacarta.core.jsontools.dump_json Probando simplejson en directorio lib")

    try:
        #logger.info("tvalacarta.core.jsontools.dump_json Probando simplejson en directorio lib")
        from lib import simplejson
        json_data = simplejson.dumps(data, indent=4, skipkeys=True, sort_keys=True, ensure_ascii=False)
        # json_data = byteify(json_data)
        logger.info("tvalacarta.core.jsontools.dump_json -> "+repr(json_data))
        return json_data
    except:
        logger.info(traceback.format_exc())

        try:
            logger.info("tvalacarta.core.jsontools.dump_json Probando simplejson incluido en el interprete")
            import simplejson
            json_data = simplejson.dumps(data, indent=4, skipkeys=True, sort_keys=True, ensure_ascii=False)
            logger.info("tvalacarta.core.jsontools.dump_json -> "+repr(json_data))
            return json_data
        except:
            logger.info(traceback.format_exc())

            try:
                logger.info("tvalacarta.core.jsontools.dump_json Probando json incluido en el interprete")
                import json
                json_data = json.dumps(data, indent=4, skipkeys=True, sort_keys=True, ensure_ascii=False)
                logger.info("tvalacarta.core.jsontools.dump_json -> "+repr(json_data))
                return json_data
            except:
                logger.info(traceback.format_exc())

                try:
                    logger.info("tvalacarta.core.jsontools.dump_json Probando JSON de Plex")
                    json_data = JSON.StringFromObject(data)  #, encoding="utf-8")
                    logger.info("tvalacarta.core.jsontools.dump_json -> "+repr(json_data))
                    return json_data
                except:
                    logger.info(traceback.format_exc())

    logger.info("tvalacarta.core.jsontools.dump_json No se ha encontrado un parser de JSON valido")
    logger.info("tvalacarta.core.jsontools.dump_json -> (nada)")
    return ""
Exemplo n.º 17
0
 def callMethod(self, method, params=None):
     self.log.info("Calling method %s." % method)
     data = {
             'method': method,
             'id': self.id,
             'jsonrpc': "2.0"
             }
     if params:
         data['params'] = params
     self.buffer = simplejson.dumps(data)
     self.id = self.id + 1
Exemplo n.º 18
0
    def _request(self, method, url, postdata=None, params=None, files=None):
        headers = {"Accept": "application/json", "Content-Type": "application/json", "User-Agent": "pyPushBullet"}

        if postdata:
            postdata = json.dumps(postdata)

        r = requests.request(
            method, url, data=postdata, params=params, headers=headers, files=files, auth=HTTPBasicAuth(self.apiKey, "")
        )

        r.raise_for_status()
        return r.json()
Exemplo n.º 19
0
    def GET(self, token=None, draw=1, start=0, length=100, **kwargs):

        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        proc_tree = subroutine.sysprocesses_subroutine()

        start = int(start)
        length = int(length)

        search = ""
        sortcolumn = 4
        sortdir = 'desc'

        if kwargs is not None:
            for key, value in kwargs.iteritems():
                if key == 'search[value]':
                    search = str(value).lower()
                if key == 'order[0][dir]':
                    sortdir = str(value)
                if key == 'order[0][column]':
                    sortcolumn = int(value)

        # Fix for column reordering without having to install a plugin
        newOrder = [2,0,5,1,4,3]
        procArr = []
        if proc_tree:
            for item in proc_tree:
                newList = []
                for key, value in item.iteritems():
                    newList.append(value)
                procList = [ newList[i] for i in newOrder]
                procArr.append(tuple(procList))

        filtered = []
        if search == "":
            filtered = procArr
        else:
            filtered = list(set([row for row in procArr for column in row if search in column.lower()]))

        filtered.sort(key=lambda x:x[sortcolumn],reverse=sortdir == "desc")

        rows = filtered[start:(start+length)]

        dict = {'draw': draw,
                'recordsTotal':len(procArr),
                'recordsFiltered':len(filtered),
                'data':rows,
                }
        s = json.dumps(dict)
        return s
Exemplo n.º 20
0
 def createCall(self, method, params=None):
     self.log.debug("Creating call for %s." % method)
     data = {
             'method': method,
             'id': self.id,
             'jsonrpc': "2.0"
             }
     if params:
         data['params'] = params
     self.log.debug("Call created with id: %i" % self.id)
     self.log.debug("Call created: %s" % (str(data)))
     self.id = self.id + 1
     return simplejson.dumps(data)        
Exemplo n.º 21
0
	def fetchData(self):
		
		if self.data == 'OK':	
			logger.info('Recieved API command: ' + self.cmd)
			methodToCall = getattr(self, "_" + self.cmd)
			result = methodToCall(**self.kwargs)

			if type(self.data) == type(''):
				return self.data
			else:
				return simplejson.dumps(self.data)
			
		else:
			return self.data
Exemplo n.º 22
0
    def GET(self, token=None, draw=1, start=0, length=100, **kwargs):

        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        start = int(start)
        length = int(length)

        search = ""
        sortcolumn = 0
        sortdir = 'desc'

        if kwargs is not None:
            for key, value in kwargs.iteritems():
                if key == 'search[value]':
                    search = str(value).lower()
                if key == 'order[0][dir]':
                    sortdir = str(value)
                if key == 'order[0][column]':
                    sortcolumn = int(value)

        # Fix for column reordering without having to install a plugin
        newOrder = [0, 2, 3, 1]
        logArr = []
        for line in cherrystrap.LOGLIST:
            logList = [line[i] for i in newOrder]
            logArr.append(tuple(logList))

        filtered = []
        if search == "":
            filtered = logArr
        else:
            filtered = list(
                set([
                    row for row in logArr for column in row
                    if search in column.lower()
                ]))

        filtered.sort(key=lambda x: x[sortcolumn], reverse=sortdir == "desc")

        rows = filtered[start:(start + length)]

        dict = {
            'draw': draw,
            'recordsTotal': len(logArr),
            'recordsFiltered': len(filtered),
            'data': rows,
        }
        s = json.dumps(dict)
        return s
Exemplo n.º 23
0
    def GET(self, token=None, draw=1, start=0, length=100, **kwargs):

        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        subroutine = subroutines()
        logfiles = subroutine.syslogs_subroutine()
        start = int(start)
        length = int(length)

        search = ""
        sortcolumn = 0
        sortdir = 'asc'

        if kwargs is not None:
            for key, value in kwargs.iteritems():
                if key == 'search[value]':
                    search = str(value).lower()
                if key == 'order[0][dir]':
                    sortdir = str(value)
                if key == 'order[0][column]':
                    sortcolumn = int(value)

        # Fix for column reordering without having to install a plugin
        newOrder = [0,2,1]
        logArr = []
        for record in logfiles:
            entry = [record['program'], record['logpath'], record['logline']]
            logList = [ entry[i] for i in newOrder]

            logArr.append(tuple(logList))

        filtered = []
        if search == "":
            filtered = logArr
        else:
            filtered = list(set([row for row in logArr for column in row if search in column.lower()]))

        filtered.sort(key=lambda x:x[sortcolumn],reverse=sortdir == "desc")

        rows = filtered[start:(start+length)]

        dict = {'draw': draw,
                'recordsTotal':len(logArr),
                'recordsFiltered':len(filtered),
                'data':rows,
                }
        s = json.dumps(dict)
        return s
Exemplo n.º 24
0
    def fetchData(self):

        if self.data == 'OK':
            logger.fdebug('Recieved API command: ' + self.cmd)
            methodToCall = getattr(self, "_" + self.cmd)
            result = methodToCall(**self.kwargs)
            if 'callback' not in self.kwargs:
                if self.img:
                    return serve_file(path=self.img, content_type='image/jpeg')
                if self.file and self.filename:
                    return serve_download(path=self.file, name=self.filename)
                if isinstance(self.data, basestring):
                    return self.data
                else:
                    cherrypy.response.headers['Content-Type'] = "application/json"
                    return simplejson.dumps(self.data)
            else:
                self.callback = self.kwargs['callback']
                self.data = simplejson.dumps(self.data)
                self.data = self.callback + '(' + self.data + ');'
                cherrypy.response.headers['Content-Type'] = "application/javascript"
                return self.data
        else:
            return self.data
Exemplo n.º 25
0
    def fetchData(self):

        if self.data == 'OK':
            logger.info('Recieved API command: ' + self.cmd)
            methodToCall = getattr(self, "_" + self.cmd)
            result = methodToCall(**self.kwargs)
            if 'callback' not in self.kwargs:
                if self.img:
                    return serve_file(path=self.img, content_type='image/jpeg')
                if self.file and self.filename:
                    return serve_download(path=self.file, name=self.filename)
                if isinstance(self.data, basestring):
                    return self.data
                else:
                    cherrypy.response.headers['Content-Type'] = "application/json"
                    return simplejson.dumps(self.data)
            else:
                self.callback = self.kwargs['callback']
                self.data = simplejson.dumps(self.data)
                self.data = self.callback + '(' + self.data + ');'
                cherrypy.response.headers['Content-Type'] = "application/javascript"
                return self.data
        else:
            return self.data
Exemplo n.º 26
0
    def _notifyTrakt(self, method, api, username, password, data={}):
        logger.log("trakt_notifier: Call method " + method, logger.DEBUG)

        json._toggle_speedups(False)

        if not api:
            api = self._api()
        if not username:
            username = self._username()
        if not password:
            password = self._password()
        password = sha1(password).hexdigest()

        method = method.replace("%API%", api)

        data["username"] = username
        data["password"] = password

        encoded_data = json.dumps(data)

        try:
            logger.log(
                "trakt_notifier: Calling method http://api.trakt.tv/" +
                method + ", with data" + encoded_data, logger.DEBUG)
            stream = urllib2.urlopen("http://api.trakt.tv/" + method,
                                     encoded_data)
            resp = stream.read()

            resp = json.loads(resp)

            if ("error" in resp):
                raise Exception(resp["error"])
        except (IOError, json.JSONDecodeError):
            logger.log("trakt_notifier: Failed calling method", logger.ERROR)
            return False

        if (resp["status"] == "success"):
            logger.log(
                "trakt_notifier: Succeeded calling method. Result: " +
                resp["message"], logger.DEBUG)
            return True

        logger.log("trakt_notifier: Failed calling method", logger.ERROR)
        return False
Exemplo n.º 27
0
    def get(self):
        import random, string
        def random_string(length):
            return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(length))

        blobs_to_process = [random_string(100) for _ in xrange(35)]

        tasks_amount = 100000000
        for i in xrange(tasks_amount):
            task = (random_string(100), random_string(100), "2012-02-24")

            tools.debug("EnqueueTasks", "add-task-%d" % i)

            taskqueue.add(\
                    name=("Process_%s_files---%s--%s--%s--%s" % \
                                (len(blobs_to_process), task[1], task[0], task[2], int(time.time()))),\
                    queue_name="files-processor",\
                    url="/run_task/",\
                    params={"processing_task": json.dumps({"profile": task, "blobs_to_process": blobs_to_process})})
Exemplo n.º 28
0
    def request(self, path, method="GET", params={}, data=None):
        """ springnote에 request를 보냅니다. 
            SpringnoteResource를 상속 받는 모든 하위클래스에서 사용합니다. """

        url = "http://%s/%s" % (Springnote.BASEURL, path.lstrip('/'))
        headers = {'Content-Type': 'application/json'}
        if data: # set body if any
            data = {self.__class__.__name__.lower(): data}
            data = json.dumps(data, ensure_ascii=False)
            data = data.encode('utf-8')

        conn = Springnote.springnote_request(method, url, params, headers, data, sign_token=self.access_token, secure=False)

        # get response
        response = conn.getresponse()
        if response.status != httplib.OK:
            raise SpringnoteError.find_error(response)

        self.build_from_response(response.read())
Exemplo n.º 29
0
    def _request(self, method, url, postdata=None, params=None, files=None):
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "User-Agent": "pyPushBullet"
        }

        if postdata:
            postdata = json.dumps(postdata)

        r = requests.request(method,
                             url,
                             data=postdata,
                             params=params,
                             headers=headers,
                             files=files,
                             auth=HTTPBasicAuth(self.apiKey, ""))

        r.raise_for_status()
        return r.json()
Exemplo n.º 30
0
    def _notifyTrakt(self, method, api, username, password, data = {}):
        logger.log("trakt_notifier: Call method " + method, logger.DEBUG)

        json._toggle_speedups(False)

        if not api:
            api = self._api()
        if not username:
            username = self._username()
        if not password:
            password = self._password()
        password = sha1(password).hexdigest()

        method = method.replace("%API%", api)

        data["username"] = username
        data["password"] = password

        encoded_data = json.dumps(data);

        try:
            logger.log("trakt_notifier: Calling method http://api.trakt.tv/" + method + ", with data" + encoded_data, logger.DEBUG)
            stream = urllib2.urlopen("http://api.trakt.tv/" + method, encoded_data)
            resp = stream.read()

            resp = json.loads(resp)
            
            if ("error" in resp):
                raise Exception(resp["error"])
        except (IOError, json.JSONDecodeError):
            logger.log("trakt_notifier: Failed calling method", logger.ERROR)
            return False

        if (resp["status"] == "success"):
            logger.log("trakt_notifier: Succeeded calling method. Result: " + resp["message"], logger.DEBUG)
            return True

        logger.log("trakt_notifier: Failed calling method", logger.ERROR)
        return False
Exemplo n.º 31
0
    def GET(self, token=None):
        if token != cherrystrap.API_TOKEN:
            return "{\"status\": \"error\", \"message\": \"Invalid Token\"}"

        ruleList = []

        myDB = database.SQLite_DBConnection()
        rules_kvs = myDB.select('SELECT * from rules ORDER BY rule1 ASC')

        for entry in rules_kvs:
            record = {
                'id':    entry['id'],
                'rule1': entry['rule1'],
                'rule2': entry['rule2'],
                'rule3': entry['rule3'],
                'rule4': entry['rule4'],
                'rule5': entry['rule5'],
                'rule6': entry['rule6'],
                'rule7': entry['rule7']
            }
            ruleList.append(record)

        return json.dumps(ruleList)
Exemplo n.º 32
0
    def getLog(self, iDisplayStart=0, iDisplayLength=100, iSortCol_0=0, sSortDir_0="desc", sSearch="", **kwargs):

        iDisplayStart = int(iDisplayStart)
        iDisplayLength = int(iDisplayLength)

        filtered = []
        if sSearch == "":
            filtered = headphones.LOG_LIST[::]
        else:
            filtered = [row for row in headphones.LOG_LIST for column in row if sSearch in column]

        sortcolumn = 0
        if iSortCol_0 == "1":
            sortcolumn = 2
        elif iSortCol_0 == "2":
            sortcolumn = 1
        filtered.sort(key=lambda x: x[sortcolumn], reverse=sSortDir_0 == "desc")

        rows = filtered[iDisplayStart : (iDisplayStart + iDisplayLength)]
        rows = [[row[0], row[2], row[1]] for row in rows]

        dict = {"iTotalDisplayRecords": len(filtered), "iTotalRecords": len(headphones.LOG_LIST), "aaData": rows}
        s = simplejson.dumps(dict)
        return s
        request.add_header("Authorization", "Basic %s" % base64string)
    opener = urllib2.build_opener()
    try:
        data = opener.open(request).read()
    except urllib2.HTTPError, e:
        if e.code == 409:
            sessionid = e.hdrs['x-transmission-session-id']
        else:
            logger.error('Could not connect to Transmission. Error: ' + str(e))
    except Exception, e:
        logger.error('Could not connect to Transmission. Error: ' + str(e))
    
    if not sessionid:
        logger.error("Error getting Session ID from Transmission")
        return
        
    request.add_header('x-transmission-session-id', sessionid)
        
    postdata = json.dumps({ 'method': method, 
                       'arguments': arguments })
                                      
    request.add_data(postdata)
                                      
    try:    
        response = json.loads(opener.open(request).read())
    except Exception, e:
        logger.error("Error sending torrent to Transmission: " + str(e))
        return
        
    return response
Exemplo n.º 34
0
    opener = urllib2.build_opener()
    try:
        data = opener.open(request).read()
    except urllib2.HTTPError, e:
        if e.code == 409:
            sessionid = e.hdrs['x-transmission-session-id']
        else:
            logger.error('Could not connect to Transmission. Error: ' + str(e))
    except Exception, e:
        logger.error('Could not connect to Transmission. Error: ' + str(e))

    if not sessionid:
        logger.error("Error getting Session ID from Transmission")
        return

    request.add_header('x-transmission-session-id', sessionid)

    postdata = json.dumps({'method': method, 'arguments': arguments})

    request.add_data(postdata)

    try:
        #logger.debug(u"Req: %s" % postdata)
        response = json.loads(opener.open(request).read())
        #logger.debug(u"Rsp: %s" % response)
    except Exception, e:
        logger.error("Error sending torrent to Transmission: " + str(e))
        return

    return response
Exemplo n.º 35
0
 def save_association_data(self, user_data):
     name = self.AUTH_BACKEND_NAME + 'association_data'
     self.request.session[name] = simplejson.dumps(user_data)
Exemplo n.º 36
0
 def getInfo(self, ComicID=None, IssueID=None):
     
     from mylar import cache
     info_dict = cache.getInfo(ComicID, IssueID)
     
     return simplejson.dumps(info_dict)
Exemplo n.º 37
0
    def getArtists_json(self,iDisplayStart=0,iDisplayLength=100,sSearch="",iSortCol_0='0',sSortDir_0='asc',**kwargs):
        iDisplayStart = int(iDisplayStart)
        iDisplayLength = int(iDisplayLength)
        filtered = []
        totalcount = 0        
        myDB = db.DBConnection()
        
        
        sortcolumn = 'ArtistSortName'
        sortbyhavepercent = False
        if iSortCol_0 == '2':
            sortcolumn = 'Status'
        elif iSortCol_0 == '3':
            sortcolumn = 'ReleaseDate'
        elif iSortCol_0 == '4':
            sortbyhavepercent = True

        if sSearch == "":
            query = 'SELECT * from artists order by %s COLLATE NOCASE %s' % (sortcolumn,sSortDir_0)    
            filtered = myDB.select(query)
            totalcount = len(filtered) 
        else:
            query = 'SELECT * from artists WHERE ArtistSortName LIKE "%' + sSearch + '%" OR LatestAlbum LIKE "%' + sSearch +'%"' +  'ORDER BY %s COLLATE NOCASE %s' % (sortcolumn,sSortDir_0)
            filtered = myDB.select(query)
            totalcount = myDB.select('SELECT COUNT(*) from artists')[0][0]

        if sortbyhavepercent:
            filtered.sort(key=lambda x:(float(x['HaveTracks'])/x['TotalTracks'] if x['TotalTracks'] > 0 else 0.0,x['HaveTracks'] if x['HaveTracks'] else 0.0),reverse=sSortDir_0 == "asc")

        #can't figure out how to change the datatables default sorting order when its using an ajax datasource so ill 
        #just reverse it here and the first click on the "Latest Album" header will sort by descending release date
        if sortcolumn == 'ReleaseDate':
            filtered.reverse()
            

        artists = filtered[iDisplayStart:(iDisplayStart+iDisplayLength)]
        rows = []
        for artist in artists:
            row = {"ArtistID":artist['ArtistID'],
                      "ArtistSortName":artist["ArtistSortName"],
                      "Status":artist["Status"],
                      "TotalTracks":artist["TotalTracks"],
                      "HaveTracks":artist["HaveTracks"],
                      "LatestAlbum":"",                      
                      "ReleaseDate":"",
                      "ReleaseInFuture":"False",
                      "AlbumID":"",
                      }

            if not row['HaveTracks']:
                row['HaveTracks'] = 0
            if artist['ReleaseDate'] and artist['LatestAlbum']:
                row['ReleaseDate'] = artist['ReleaseDate']
                row['LatestAlbum'] = artist['LatestAlbum']
                row['AlbumID'] = artist['AlbumID']
                if artist['ReleaseDate'] > today():
                    row['ReleaseInFuture'] = "True"
            elif artist['LatestAlbum']:
                row['ReleaseDate'] = ''
                row['LatestAlbum'] = artist['LatestAlbum']
                row['AlbumID'] = artist['AlbumID']
              
            rows.append(row)


        dict = {'iTotalDisplayRecords':len(filtered),
                'iTotalRecords':totalcount,
                'aaData':rows,
                }
        s = simplejson.dumps(dict)
        cherrypy.response.headers['Content-type'] = 'application/json'
        return s
Exemplo n.º 38
0
    def getArtists_json(self,
                        iDisplayStart=0,
                        iDisplayLength=100,
                        sSearch="",
                        iSortCol_0='0',
                        sSortDir_0='asc',
                        **kwargs):
        iDisplayStart = int(iDisplayStart)
        iDisplayLength = int(iDisplayLength)
        filtered = []
        totalcount = 0
        myDB = db.DBConnection()

        sortcolumn = 'ArtistSortName'
        sortbyhavepercent = False
        if iSortCol_0 == '2':
            sortcolumn = 'Status'
        elif iSortCol_0 == '3':
            sortcolumn = 'ReleaseDate'
        elif iSortCol_0 == '4':
            sortbyhavepercent = True

        if sSearch == "":
            query = 'SELECT * from artists order by %s COLLATE NOCASE %s' % (
                sortcolumn, sSortDir_0)
            filtered = myDB.select(query)
            totalcount = len(filtered)
        else:
            query = 'SELECT * from artists WHERE ArtistSortName LIKE "%' + sSearch + '%" OR LatestAlbum LIKE "%' + sSearch + '%"' + 'ORDER BY %s COLLATE NOCASE %s' % (
                sortcolumn, sSortDir_0)
            filtered = myDB.select(query)
            totalcount = myDB.select('SELECT COUNT(*) from artists')[0][0]

        if sortbyhavepercent:
            filtered.sort(key=lambda x:
                          (float(x['HaveTracks']) / x['TotalTracks']
                           if x['TotalTracks'] > 0 else 0.0, x['HaveTracks']
                           if x['HaveTracks'] else 0.0),
                          reverse=sSortDir_0 == "asc")

        #can't figure out how to change the datatables default sorting order when its using an ajax datasource so ill
        #just reverse it here and the first click on the "Latest Album" header will sort by descending release date
        if sortcolumn == 'ReleaseDate':
            filtered.reverse()

        artists = filtered[iDisplayStart:(iDisplayStart + iDisplayLength)]
        rows = []
        for artist in artists:
            row = {
                "ArtistID": artist['ArtistID'],
                "ArtistSortName": artist["ArtistSortName"],
                "Status": artist["Status"],
                "TotalTracks": artist["TotalTracks"],
                "HaveTracks": artist["HaveTracks"],
                "LatestAlbum": "",
                "ReleaseDate": "",
                "ReleaseInFuture": "False",
                "AlbumID": "",
            }

            if not row['HaveTracks']:
                row['HaveTracks'] = 0
            if artist['ReleaseDate'] and artist['LatestAlbum']:
                row['ReleaseDate'] = artist['ReleaseDate']
                row['LatestAlbum'] = artist['LatestAlbum']
                row['AlbumID'] = artist['AlbumID']
                if artist['ReleaseDate'] > today():
                    row['ReleaseInFuture'] = "True"
            elif artist['LatestAlbum']:
                row['ReleaseDate'] = ''
                row['LatestAlbum'] = artist['LatestAlbum']
                row['AlbumID'] = artist['AlbumID']

            rows.append(row)

        dict = {
            'iTotalDisplayRecords': len(filtered),
            'iTotalRecords': totalcount,
            'aaData': rows,
        }
        s = simplejson.dumps(dict)
        cherrypy.response.headers['Content-type'] = 'application/json'
        return s
Exemplo n.º 39
0
    def getImageLinks(self, ArtistID=None, AlbumID=None):

        from headphones import cache
        image_dict = cache.getImageLinks(ArtistID, AlbumID)

        return simplejson.dumps(image_dict)
Exemplo n.º 40
0
    def getInfo(self, ArtistID=None, AlbumID=None):

        from headphones import cache
        info_dict = cache.getInfo(ArtistID, AlbumID)

        return simplejson.dumps(info_dict)
Exemplo n.º 41
0
 def save_association_data(self, user_data):
     name = self.AUTH_BACKEND_NAME + 'association_data'
     self.request.session[name] = simplejson.dumps(user_data)
Exemplo n.º 42
0
def state(*args):
	''' Get the currect url for a particular state in the plugin '''
	global PLUGIN
	return "plugin://" + PLUGIN + "/" + json.dumps(args)
Exemplo n.º 43
0
    def getArtists_json(
        self, iDisplayStart=0, iDisplayLength=100, sSearch="", iSortCol_0="0", sSortDir_0="asc", **kwargs
    ):
        iDisplayStart = int(iDisplayStart)
        iDisplayLength = int(iDisplayLength)
        filtered = []
        totalcount = 0
        myDB = db.DBConnection()

        sortcolumn = "ArtistSortName"
        sortbyhavepercent = False
        if iSortCol_0 == "2":
            sortcolumn = "Status"
        elif iSortCol_0 == "3":
            sortcolumn = "ReleaseDate"
        elif iSortCol_0 == "4":
            sortbyhavepercent = True

        if sSearch == "":
            query = "SELECT * from artists order by %s COLLATE NOCASE %s" % (sortcolumn, sSortDir_0)
            filtered = myDB.select(query)
            totalcount = len(filtered)
        else:
            query = (
                'SELECT * from artists WHERE ArtistSortName LIKE "%'
                + sSearch
                + '%" OR LatestAlbum LIKE "%'
                + sSearch
                + '%"'
                + "ORDER BY %s COLLATE NOCASE %s" % (sortcolumn, sSortDir_0)
            )
            filtered = myDB.select(query)
            totalcount = myDB.select("SELECT COUNT(*) from artists")[0][0]

        if sortbyhavepercent:
            filtered.sort(
                key=lambda x: (
                    float(x["HaveTracks"]) / x["TotalTracks"] if x["TotalTracks"] > 0 else 0.0,
                    x["HaveTracks"] if x["HaveTracks"] else 0.0,
                ),
                reverse=sSortDir_0 == "asc",
            )

        # can't figure out how to change the datatables default sorting order when its using an ajax datasource so ill
        # just reverse it here and the first click on the "Latest Album" header will sort by descending release date
        if sortcolumn == "ReleaseDate":
            filtered.reverse()

        artists = filtered[iDisplayStart : (iDisplayStart + iDisplayLength)]
        rows = []
        for artist in artists:
            row = {
                "ArtistID": artist["ArtistID"],
                "ArtistSortName": artist["ArtistSortName"],
                "Status": artist["Status"],
                "TotalTracks": artist["TotalTracks"],
                "HaveTracks": artist["HaveTracks"],
                "LatestAlbum": "",
                "ReleaseDate": "",
                "ReleaseInFuture": "False",
                "AlbumID": "",
            }

            if not row["HaveTracks"]:
                row["HaveTracks"] = 0
            if artist["ReleaseDate"] and artist["LatestAlbum"]:
                row["ReleaseDate"] = artist["ReleaseDate"]
                row["LatestAlbum"] = artist["LatestAlbum"]
                row["AlbumID"] = artist["AlbumID"]
                if artist["ReleaseDate"] > today():
                    row["ReleaseInFuture"] = "True"
            elif artist["LatestAlbum"]:
                row["ReleaseDate"] = ""
                row["LatestAlbum"] = artist["LatestAlbum"]
                row["AlbumID"] = artist["AlbumID"]

            rows.append(row)

        dict = {"iTotalDisplayRecords": len(filtered), "iTotalRecords": totalcount, "aaData": rows}
        s = simplejson.dumps(dict)
        cherrypy.response.headers["Content-type"] = "application/json"
        return s