def create_botType(**kwargs): con = database.get_con() cur = database.get_cur(con) query = ( """INSERT INTO rb_botTypes (name, description, moduleName) VALUES (?,?,?) ;""", ( kwargs["description"].lower().strip().replace(" ", "-"), kwargs["description"], kwargs["moduleName"], ), ) result = database.db_qry(query, con=con, cur=cur) if isinstance(result, str) and result.find("ERROR") != -1: con.commit() con.close() return result else: insert_id = database.db_qry("SELECT last_insert_rowid() as id;", con=con, cur=cur)[0]["id"] if insert_id > 0: log.info("Created botType ({}) with id: {}.".format( kwargs["description"], insert_id)) else: insert_id = "ERROR: Failed to insert record." con.commit() con.close() return insert_id
def delete_bot(self): con = database.get_con() cur = database.get_cur(con) queries = [ ("DELETE FROM rb_bots WHERE id=?;", (self.id,)), ("DELETE FROM rb_botConfig WHERE botId=?;", (self.id,)), ( "DELETE FROM rb_privileges WHERE privilege like 'rb_bot_{}_%';".format( self.id ) ), ] botConfigTables = database.db_qry( "select name from sqlite_master where type='table' and name like 'rb_bot_{}_%';".format( self.id ), con=con, cur=cur, commit=False, closeAfter=False, ) if isinstance(botConfigTables, dict): for v in botConfigTables.values(): queries.append(("DROP TABLE {};", (v,))) result = database.db_qry(queries, commit=True, closeAfter=True) if isinstance(result, list): user.remove_privilege("rb_bot_{}_ro".format(self.id)) user.remove_privilege("rb_bot_{}_startstop".format(self.id)) user.remove_privilege("rb_bot_{}_rw".format(self.id)) self.__del__() return result
def update_config(data): if isinstance(data, list): con = database.get_con() cur = database.get_cur(con) for item in data: if item.get("type") == "bool": item["val"] = (item["val"] if isinstance(item["val"], bool) else (item["val"].lower() == "true")) elif item.get("type") == "int": item["val"] = int(item["val"]) query = ( "UPDATE rb_config SET val = ? WHERE category = ? and key = ?;", (serialize_key(item["val"]), item["category"], item["key"]), ) log.debug("Result: {}".format( database.db_qry(query=query, con=con, cur=cur))) con.commit() con.close() else: if data.get("type") == "bool": data["val"] = (data["val"] if isinstance(data["val"], bool) else (data["val"].lower() == "true")) if data.get("options") in ("", [], None): data["options"] = [True, False] elif data.get("type") == "int": data["val"] = int(data["val"]) query = ( "UPDATE rb_config SET val = ? WHERE category = ? and key = ?;", (serialize_key(data["val"]), data["category"], data["key"]), ) database.db_qry(query, commit=True, closeAfter=True) return True
def log_login(uid): database.db_qry( ( "UPDATE rb_users set lastLogin=?, loginCount=loginCount+1 where id=?", (time.time(), uid), ), commit=True, closeAfter=True, )
def create_bot(self, name, botType, autoRun, redditAuth): con = database.get_con() cur = database.get_cur(con) query = ( "INSERT INTO rb_bots (name,botType,autoRun,redditAuth) values (?,?,?,?);", (name, botType, autoRun, redditAuth), ) result = database.db_qry(query, con=con, cur=cur) if isinstance(result, str) and result.find("ERROR") != -1: con.commit() con.close() return result else: insert_id = database.db_qry("SELECT last_insert_rowid() as id;", con=con, cur=cur)[0]["id"] log.info("Created bot with id: {}. Inserting default settings...". format(insert_id)) self.id = insert_id self.name = name self.botType = botType self.autoRun = autoRun self.redditAuth = redditAuth config.add_default_bot_config(insert_id, con, cur) botTypeInfo = config.get_botTypes(botType) if (botTypeInfo["defaultSettings"] and len(botTypeInfo["defaultSettings"]) > 2): defaultSettings = botTypeInfo["defaultSettings"] result = config.add_bot_config( botId=insert_id, multi=defaultSettings, replace=True, con=con, cur=cur, commit=False, closeAfter=False, ) # Create privileges and grant to creator q = """INSERT INTO rb_privileges ('privilege', 'description') VALUES ('rb_bot_{}_ro', 'Read-only access to bot id {}.'), ('rb_bot_{}_startstop', 'Access to start and stop bot id {}.'), ('rb_bot_{}_rw', 'Full access to bot id {}.') ;""".format(insert_id, insert_id, insert_id, insert_id, insert_id, insert_id) database.db_qry(q, con=con, cur=cur) con.commit() con.close() return insert_id
def create_user(**kwargs): con = database.get_con() cur = database.get_cur(con) if kwargs.get("userid") in [None, ""]: return "User ID cannot be blank." elif kwargs.get("password") and kwargs["password"] != kwargs.get( "confirm_password" ): return "Password and confirmation do not match." elif kwargs.get("password") in [None, ""]: return "Password cannot be blank." if kwargs.get("name") in [None, ""]: kwargs.update({"name": kwargs["userid"].capitalize()}) if kwargs.get("privileges") in [None, ""]: kwargs.update({"privileges": []}) query = ( """INSERT INTO rb_users (userid, name, password, email, reddit_userid, privileges, lastUpdate) VALUES (?,?,?,?,?,?,?) ;""", ( kwargs["userid"], kwargs["name"], hash_password(kwargs["password"]), kwargs["email"], kwargs["reddit_userid"], config.serialize_key(kwargs["privileges"]), time.time(), ), ) result = database.db_qry(query, con=con, cur=cur) if isinstance(result, str) and result.find("ERROR") != -1: con.commit() con.close() return result else: insert_id = database.db_qry( "SELECT last_insert_rowid() as id;", con=con, cur=cur )[0]["id"] if insert_id > 0: log.info( "Created user ({}) with id: {}.".format(kwargs["userid"], insert_id) ) else: insert_id = "ERROR: Failed to insert record." con.commit() con.close() return insert_id
def get_bots(botId=None): query = "SELECT * FROM rb_bots WHERE 1=1" local_args = tuple() fetchone = False if botId: query += " AND id=?" local_args = (botId,) fetchone = True query += " ORDER BY id ASC;" if len(local_args): bots = database.db_qry((query, local_args), fetchone=fetchone) else: bots = database.db_qry(query, fetchone=fetchone) if isinstance(bots, list): for bot in bots: if redball.BOTS.get(str(bot["id"])): bot.update( { "status": "Running" if redball.BOTS[str(bot["id"])].isRunning() else "Stopped" } ) if ( redball.BOTS.get(str(bot["id"])) and redball.BOTS[str(bot["id"])].detailedState ): bot.update( {"detailedState": redball.BOTS[str(bot["id"])].detailedState} ) elif isinstance(bots, dict): if redball.BOTS.get(str(bots["id"])): bots.update( { "status": "Running" if redball.BOTS[str(bots["id"])].isRunning() else "Stopped" } ) if ( redball.BOTS.get(str(bots["id"])) and redball.BOTS[str(bots["id"])].detailedState ): bots.update({"detailedState": redball.BOTS[str(bots["id"])].detailedState}) return bots
def add_default_bot_config(botId, con=None, cur=None): boolOptions = serialize_key([True, False]) logLevelOptions = serialize_key(["DEBUG", "INFO", "WARNING", "ERROR"]) sq = ( """INSERT OR IGNORE INTO rb_botConfig (botId, category, key, description, type, val, options, subkeys, parent_key, read_only, system) VALUES (?, 'Logging', 'LOG_TO_FILE', 'Log to File', 'bool', 'true', ?, '["FILE_LOG_LEVEL"]', '', 'False', 'True'), (?, 'Logging', 'FILE_LOG_LEVEL', 'File Log Level', 'str', '"DEBUG"', ?, '[]', 'LOG_TO_FILE', 'False', 'True'), (?, 'Logging', 'LOG_TO_CONSOLE', 'Log to Console', 'bool', 'true', ?, '["CONSOLE_LOG_LEVEL"]', '', 'False', 'True'), (?, 'Logging', 'CONSOLE_LOG_LEVEL', 'Console Log Level', 'str', '"INFO"', ?, '[]', 'LOG_TO_CONSOLE', 'False', 'True'), (?, 'Logging', 'PROPAGATE', 'Propagate Logs', 'bool', 'false', ?, '[]', '', 'False', 'True') ;""", ( botId, boolOptions, botId, logLevelOptions, botId, boolOptions, botId, logLevelOptions, botId, boolOptions, ), ) sres = database.db_qry(sq, con=con, cur=cur) if isinstance(sres, str): return "Error inserting default config: {}".format(sres) else: return sres
def update_info(self, **kwargs): local_args = tuple() q = "UPDATE rb_bots set" fields = [] if kwargs.get("name"): fields.append(" name=?") local_args += (kwargs["name"], ) if kwargs.get("botType"): fields.append(" botType=?") local_args += (int(kwargs["botType"]), ) if kwargs.get("autoRun"): fields.append(" autoRun=?") local_args += (kwargs["autoRun"], ) if kwargs.get("redditAuth"): fields.append(" redditAuth=?") local_args += (kwargs["redditAuth"], ) q += ",".join(fields) q += " WHERE id=?" local_args += (self.id, ) if q == "UPDATE rb_bots set WHERE id=?": return "ERROR: Nothing provided to update." query = (q, local_args) result = database.db_qry(query, commit=True, closeAfter=True) if result in ["", []]: self.refresh_info() return result
def update_redditAuth(id, **kwargs): local_args = tuple() q = "UPDATE rb_redditAuth set" fields = [] if kwargs.get("description"): fields.append(" description=?") local_args += (kwargs["description"], ) if kwargs.get("reddit_appId"): fields.append(" reddit_appId=?") local_args += (kwargs["reddit_appId"], ) if kwargs.get("reddit_appSecret"): fields.append(" reddit_appSecret=?") local_args += (kwargs["reddit_appSecret"], ) if kwargs.get("reddit_scopes"): fields.append(" reddit_scopes=?") local_args += (serialize_key(kwargs["reddit_scopes"]), ) if kwargs.get("reddit_refreshToken"): fields.append(" reddit_refreshToken=?") local_args += (kwargs["reddit_refreshToken"], ) q += ",".join(fields) q += " WHERE id=?" local_args += (int(id), ) if q == "UPDATE rb_redditAuth set WHERE id=?": return "ERROR: Nothing provided to update." query = (q, local_args) result = database.db_qry(query, commit=True, closeAfter=True) return result
def update_botType(id, **kwargs): local_args = tuple() q = "UPDATE rb_botTypes set" fields = [] if kwargs.get("name"): fields.append(" name=?") local_args += (kwargs["name"], ) if kwargs.get("description"): fields.append(" description=?") local_args += (kwargs["description"], ) if kwargs.get("moduleName"): fields.append(" moduleName=?") local_args += (kwargs["moduleName"], ) if kwargs.get("defaultSettings"): fields.append(" defaultSettings=?") local_args += (json.dumps(kwargs.get("defaultSettings", "{}"), indent=2), ) q += ",".join(fields) q += " WHERE id=?" local_args += (int(id), ) if q == "UPDATE rb_botTypes set WHERE id=?": return "ERROR: Nothing provided to update." query = (q, local_args) result = database.db_qry(query, commit=True, closeAfter=True) return result
def get_redditAuths(id=None): query = "SELECT * FROM rb_redditAuth WHERE 1=1" local_args = tuple() fetchone = False if id is not None: query += " AND id=?" local_args = (int(id), ) fetchone = True query += " ORDER BY id ASC;" if len(local_args): auths = database.db_qry((query, local_args), fetchone=fetchone) else: auths = database.db_qry(query, fetchone=fetchone) return auths
def update_bot_config(botId, data): if isinstance(data, dict): data = [data] if isinstance(data, list): con = database.get_con() cur = database.get_cur(con) for item in data: if item.get("id"): q = "UPDATE rb_botConfig SET" local_args = tuple() for k, v in item.items(): if q[-1:] == "?": q += "," q += " {}=?".format(k) local_args += (v, ) q += " WHERE botId=? and id=?;" local_args += (botId, item["id"]) query = (q, local_args) else: if item.get("type") == "bool": item["val"] = (item["val"] if isinstance( item["val"], bool) else (item["val"].lower() == "true")) elif item.get("type") == "int": item["val"] = int(item["val"]) query = ( "UPDATE rb_botConfig SET val = ? WHERE category = ? and key = ? and botId=?;", (serialize_key(item["val"]), item["category"], item["key"], botId), ) log.debug("Result: {}".format( database.db_qry(query=query, con=con, cur=cur))) con.commit() con.close() else: query = ( "UPDATE rb_config SET val = ? WHERE category = ? and key = ?;", (serialize_key(data["val"]), data["category"], data["key"]), ) database.db_qry(query, commit=True, closeAfter=True) return True
def upgrade_database(toVer=None): # toVer = database version to upgrade to # returns True if version is satisfactory, False if error toVer = toVer if toVer else max(upgradeScripts.keys()) fromVer = database.get_database_version(logg=log) if fromVer == toVer: log.info("Database is up to date (version: {})!".format(fromVer)) return True elif fromVer > toVer: log.warning( "Current version ({}) is higher than requested version ({}). Someting's wrong but there's nothing to upgrade...".format( fromVer, toVer ) ) return True else: log.info( "Current database version {}; desired version: {}.".format(fromVer, toVer) ) log.info("Creating a backup of the database...") database.backup_database(logg=log, manual=False) con = database.get_con(logg=log) cur = database.get_cur(con=con, logg=log) while fromVer < toVer: # Apply upgrade scripts one version at a time until the database is up-to-date log.info( "Upgrading database from version {} to version {}...".format( fromVer, fromVer + 1 ) ) if len(upgradeScripts.get(fromVer + 1, [])) > 0: results = database.db_qry( query=upgradeScripts[fromVer + 1], con=con, cur=cur, commit=False, closeAfter=False, logg=log, ) if None in results: log.error( "One or more database upgrade queries failed: {}".format( results ) ) # Upgrade scripts failed. Do not commit and do not continue. return False else: con.commit() fromVer += 1 log.debug("Database upgraded to version {}.".format(fromVer)) con.close() log.debug("Database upgrade process is complete.") return True
def get_privileges(): # Return list of privileges from rb_privileges q = "SELECT * FROM rb_privileges;" result = database.db_qry(q, closeAfter=True, logg=log) if isinstance(result, str): return [] elif isinstance(result, dict): return [result] else: return result
def update_user(id, **kwargs): local_args = tuple() q = "UPDATE rb_users set" fields = [] if kwargs.get("apikey") is not None: # apikey gets updated by itself fields.append(" apikey=?") local_args += (kwargs["apikey"], ) else: if kwargs.get("userid") in [None, ""]: return "User ID cannot be blank." if kwargs.get("name") in [None, ""]: kwargs.update({"name": kwargs["userid"].capitalize()}) if kwargs.get("privileges") in [None, ""]: kwargs.update({"privileges": []}) if kwargs.get("userid") is not None: fields.append(" userid=?") local_args += (kwargs["userid"], ) if kwargs.get("name") is not None: fields.append(" name=?") local_args += (kwargs["name"], ) if kwargs.get("email") is not None: fields.append(" email=?") local_args += (kwargs["email"], ) if kwargs.get("reddit_userid") is not None: fields.append(" reddit_userid=?") local_args += (kwargs["reddit_userid"], ) if kwargs.get("privileges") is not None: fields.append(" privileges=?") local_args += (config.serialize_key(kwargs["privileges"]), ) fields.append(" lastUpdate=?") local_args += (time.time(), ) q += ",".join(fields) q += " WHERE id=?" local_args += (int(id), ) if q == "UPDATE rb_users set WHERE id=?": return True query = (q, local_args) result = database.db_qry(query, commit=True, closeAfter=True) if isinstance(result, str): return result else: return True
def in_use(botTypeId=None, redditAuthId=None): query = "SELECT count(*) FROM rb_bots WHERE " if botTypeId: query = (query + "botType=?;", (botTypeId, )) elif redditAuthId: query = (query + "redditAuth=?;", (redditAuthId, )) else: return None result = database.db_qry(query, fetchone=True, closeAfter=True) return result["count(*)"]
def get_sys_config(category=None, key=None, includeChildren=False): query = "SELECT * FROM rb_config WHERE 1=1" local_args = tuple() if category and key: query += " AND (category=? AND key=?)" local_args += (category, key) elif category: query += " AND category=?" local_args += (category, ) elif key: query += " AND key=?" local_args += (key, ) if includeChildren and key: query += " OR parent_key=?" local_args += (key, ) query += " ORDER BY category ASC;" if len(local_args): config = database.db_qry((query, local_args)) else: config = database.db_qry(query) # Deserialize val, options, and subkeys if isinstance(config, list): for c in config: c.update({ "val": deserialize_key(c["val"], c["type"]), "options": deserialize_key(c["options"]), "subkeys": deserialize_key(c["subkeys"]), }) elif isinstance(config, dict): config.update({ "val": deserialize_key(c["val"], c["type"]), "options": deserialize_key(c["options"]), "subkeys": deserialize_key(c["subkeys"]), }) return config
def callBack_redditAuth(state, code): redditAuth = database.db_qry( ("SELECT * FROM rb_redditAuth WHERE reddit_uniqueCode=?;", (state, )), fetchone=True, ) if isinstance(redditAuth, str) or len(redditAuth) == 0: return False webConfig = get_sys_config(category="Web/Security") # Get refresh token log.debug( "Exchanging code {} for refresh token for redditAuth id {}.".format( code, redditAuth["id"])) reddit = praw.Reddit( client_id=redditAuth["reddit_appId"], client_secret=redditAuth["reddit_appSecret"], redirect_uri="{}/authorize".format( next(x["val"] for x in webConfig if x["key"] == "HTTP_ROOT")), user_agent="{} v{} - Callback Handler".format(redball.APP_NAME, redball.__version__), ) try: refreshToken = reddit.auth.authorize(code) except Exception as e: log.error("Error exchanging code for refresh token: {}".format(e)) return "ERROR: {}".format(e) log.debug("Refresh token: {}.".format(refreshToken)) upd = database.db_qry( ( "UPDATE rb_redditAuth SET reddit_refreshToken=? WHERE reddit_uniqueCode=?;", (refreshToken, state), ), commit=True, closeAfter=True, ) if upd in [[], [[]]]: return True else: return False
def get_redditScopes(id=None, name=None): query = "SELECT * FROM rb_redditScopes WHERE 1=1" local_args = tuple() fetchone = False if id: query += " AND id=?" local_args += (int(id), ) fetchone = True if name: query += " AND name=?" local_args += (int(name), ) fetchone = True query += " ORDER BY name ASC;" if len(local_args): types = database.db_qry((query, local_args), fetchone=fetchone) else: types = database.db_qry(query, fetchone=fetchone) return types
def create_redditAuth(**kwargs): con = database.get_con() cur = database.get_cur(con) query = ( """INSERT INTO rb_redditAuth (description, reddit_appId, reddit_appSecret, reddit_scopes, reddit_refreshToken, reddit_uniqueCode) VALUES (?,?,?,?,?,?) ;""", ( kwargs["description"], kwargs["reddit_appId"], kwargs["reddit_appSecret"], serialize_key(kwargs["reddit_scopes"]), kwargs.get("reddit_refreshToken"), uuid.uuid4().hex, ), ) result = database.db_qry(query, con=con, cur=cur) if isinstance(result, str) and result.find("ERROR") != -1: con.commit() con.close() return result else: insert_id = database.db_qry("SELECT last_insert_rowid() as id;", con=con, cur=cur)[0]["id"] if insert_id > 0: log.info("Created redditAuth ({}) with id: {}.".format( kwargs["description"], insert_id)) redball.REDDIT_AUTH_LOCKS.update({str(insert_id): Lock()}) else: insert_id = "ERROR: Failed to insert record." con.commit() con.close() return insert_id
def get_user_info(userid=None, apikey=None, uid=None, field=None, sensitive=True): # userid = rb_users.userid # apikey = rb_users.apikey # uid = rb_users.id # return dict of user info, or empty dict if user not found # or list of dicts if run with no parameters # field not supported without userid, apikey, or uid q = "SELECT * FROM rb_users WHERE 1=1" local_args = tuple() if userid: if sensitive: q += " AND userid=?" else: q += " AND userid like ?" local_args += (userid, ) if uid: q += " AND id=?" local_args += (uid, ) if apikey: q += " AND apikey=?" local_args += (apikey, ) result = database.db_qry((q, local_args), fetchone=True if len(local_args) > 0 else False, logg=log) if isinstance(result, dict): if field == "privileges": return result.get(field, "[]") elif field: return result.get(field, "") elif not userid and not uid and not apikey: return [result] else: return result elif isinstance(result, list): # field not supported for multiple records return result else: if field == "privileges": return "[]" elif field: return "" else: return {}
def get_botTypes(id=None): query = "SELECT * FROM rb_botTypes WHERE 1=1" local_args = tuple() fetchone = False if id: query += " AND id=?" local_args = (int(id), ) fetchone = True query += " ORDER BY id ASC;" if len(local_args): types = database.db_qry((query, local_args), fetchone=fetchone) else: types = database.db_qry(query, fetchone=fetchone) if isinstance(types, dict): types = [types] if len(types) == 1: types = types[0] return types
def remove_privilege(privilege): # privilege = rb_privilege.privilege # Removes the privilege from all users # Remove from redball.LOGGED_IN_USERS[x]['PRIVS'] for x in redball.LOGGED_IN_USERS: if privilege in x: x.pop(x.index(privilege)) # Remove from rb_users.privileges con = database.get_con() cur = database.get_cur(con) users = database.db_qry("SELECT id,privileges FROM rb_users;", con=con, cur=cur, logg=log) queries = [] for x in users: p = json.loads(x["privileges"]) if privilege in p: p.pop(p.index(privilege)) queries.append(( "UPDATE rb_users SET privileges = ? WHERE id = ?;", (json.dumps(p), x["id"]), )) if len(queries): database.db_qry(queries, con=con, cur=cur, commit=True, closeAfter=True, logg=log) else: con.close()
def delete_bot_config(botId, category=None, key=None, confId=None, all=False): if all: query = ("DELETE FROM rb_botConfig WHERE botId=? and system!='True';", (botId, )) elif confId: query = ( "DELETE FROM rb_botConfig WHERE botId=? and id=? and system!='True';", (botId, int(confId)), ) else: query = ( "DELETE FROM rb_botConfig WHERE botId=? AND category=? AND key=? and system!='True';", (botId, category, key), ) return database.db_qry(query, commit=True, closeAfter=True)
def create_bot(self, name, botType, autoRun, redditAuth): con = database.get_con() cur = database.get_cur(con) query = ( "INSERT INTO rb_bots (name,botType,autoRun,redditAuth) values (?,?,?,?);", (name, botType, autoRun, redditAuth), ) result = database.db_qry(query, con=con, cur=cur) if isinstance(result, str) and result.find("ERROR") != -1: con.commit() con.close() return result else: insert_id = database.db_qry("SELECT last_insert_rowid() as id;", con=con, cur=cur)[0]["id"] log.info("Created bot with id: {}. Inserting default settings...". format(insert_id)) self.id = insert_id self.name = name self.botType = botType self.autoRun = autoRun self.redditAuth = redditAuth config.add_default_bot_config(insert_id, con, cur) botTypeInfo = config.get_botTypes(botType) defaultSettingsFile = os.path.join( redball.BOT_PATH, f"{botTypeInfo['moduleName']}_config.json") log.debug( f"Default settings file for botType {botTypeInfo['name']}: {defaultSettingsFile}" ) if os.path.isfile(defaultSettingsFile): try: with open(defaultSettingsFile) as f: defaultSettings = json.load(f) except Exception as e: log.error( f"Error occurred while loading default config for [{botTypeInfo['description']}] bot type from json file [{defaultSettingsFile}]: {e}." ) defaultSettings = {} if len(defaultSettings): log.debug( f"Loaded default settings for botType {botTypeInfo['name']}: {defaultSettings}. Adding to bot {insert_id}..." ) result = config.add_bot_config( botId=insert_id, multi=defaultSettings, replace=True, con=con, cur=cur, commit=False, closeAfter=False, ) else: log.debug( f"No default settings found in the json file for botType {botTypeInfo['name']}." ) else: log.warning( f"No default settings json file found for [{botTypeInfo['description']}] bot type." ) # Create privileges and grant to creator q = """INSERT INTO rb_privileges ('privilege', 'description') VALUES ('rb_bot_{}_ro', 'Read-only access to bot id {}.'), ('rb_bot_{}_startstop', 'Access to start and stop bot id {}.'), ('rb_bot_{}_rw', 'Full access to bot id {}.') ;""".format(insert_id, insert_id, insert_id, insert_id, insert_id, insert_id) database.db_qry(q, con=con, cur=cur) con.commit() con.close() return insert_id
def delete_redditAuth(id): query = ("DELETE FROM rb_redditAuth WHERE id=?;", (id, )) result = database.db_qry(query, commit=True, closeAfter=True) return result
def delete_botType(id): query = ("DELETE FROM rb_botTypes WHERE id=?;", (id, )) result = database.db_qry(query, commit=True, closeAfter=True) return result
def get_bot_config( botId, category=None, key=None, includeChildren=False, confId=None, excludeSysFields=False, sortByCategory=False, ): query = "SELECT * FROM rb_botConfig WHERE botId=?" local_args = (botId, ) if confId: query += " AND id=?" local_args += (confId, ) if category and key: query += " AND (category=? AND key=?)" local_args += (category, key) elif category: query += " AND category=?" local_args += (category, ) elif key: query += " AND key=?" local_args += (key, ) if includeChildren and key: query += " OR parent_key=?" local_args += (key, ) query += " ORDER BY category ASC;" if len(local_args): config = database.db_qry((query, local_args)) else: config = database.db_qry(query) if excludeSysFields: # Remove system fields for x in config: x.pop("read_only") x.pop("system") for x in config: x.update({ "val": deserialize_key(x["val"], x["type"]), "subkeys": deserialize_key(x["subkeys"]), "options": deserialize_key(x["options"]), }) sortedConfig = {} if sortByCategory: for cat in set(c["category"] for c in config): sortedConfig.update({cat: []}) log.debug("sortedConfig after adding cat: {}".format(sortedConfig)) for a in (a for a in config if a["category"] == cat): sortedConfig[cat].append(a) for x in sortedConfig: for y in sortedConfig[x]: y.pop("category") return sortedConfig return config
def add_bot_config( botId, category=None, key=None, val=None, description="", dataType="str", options="", subkeys="", parent_key="", multi=None, replace=False, clean=False, con=None, cur=None, commit=True, closeAfter=True, ): if clean: log.debug( "Clearing config for bot id {} per clean parameter".format(botId)) delete_bot_config(botId, category, key, all=True) if replace: log.debug("Replacing existing values...") q = "INSERT OR REPLACE INTO rb_botConfig (botId, category, key, val, description, type, options, subkeys, parent_key, system) VALUES " else: log.debug("Preserving existing values...") q = "INSERT OR IGNORE INTO rb_botConfig (botId, category, key, val, description, type, options, subkeys, parent_key, system) VALUES " if isinstance(multi, dict): local_args = tuple() for k, v in multi.items(): for z in v: if z.get("type") == "bool": z["val"] = (z["val"] if isinstance(z["val"], bool) else (z["val"].lower() == "true")) if z.get("options") in ("", [], None): z["options"] = [True, False] elif z.get("type") == "int": z["val"] = int(z["val"]) if len(local_args): q += ", " q += "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" local_args += ( int(botId), k, z["key"], serialize_key(z["val"]), z.get("description", ""), z.get("type", "str"), serialize_key(z.get("options")) if z.get("options") not in ["", None] else "[]", serialize_key(z.get("subkeys")) if z.get("subkeys") not in ["", None] else "[]", z.get("parent_key", ""), "True" if k == "Logging" and z["key"] in [ "LOG_TO_FILE", "FILE_LOG_LEVEL", "LOG_TO_CONSOLE", "CONSOLE_LOG_LEVEL", "PROPAGATE", ] else "False", ) q += ";" query = (q, local_args) else: if dataType == "bool": val = val if isinstance(val, bool) else (val.lower() == "true") if options in ("", [], None): options = [True, False] elif dataType == "int": val = int(val) query = ( q + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", ( botId, category, key, serialize_key(val), description, dataType, serialize_key(options if isinstance(options, list) else []), serialize_key(subkeys if isinstance(subkeys, list) else []), parent_key, "True" if category == "Logging" and key in [ "LOG_TO_FILE", "FILE_LOG_LEVEL", "LOG_TO_CONSOLE", "CONSOLE_LOG_LEVEL", "PROPAGATE", ] else "False", ), ) return database.db_qry(query, con=con, cur=cur, commit=commit, closeAfter=closeAfter)