def Prepare(self): self.name = 'Sample' self.GenTP = Procedures.Toolpath_Generate(self.apparatus, self.executor) self.PrintTP = Procedures.Toolpath_Print(self.apparatus, self.executor) self.Planner = Procedures.Planner_Combinatorial( self.apparatus, self.executor)
def DeleteTank(self, tankName, current=None): self.refresh_action() # Must check if the tank exists, and if it belongs to this account. results = self.database.do_query( Procedures.tank_exists_under_account(), tankName, self.name) if len(results) != 1: # Tank does not exist. Log.quick_log( "User %s tried to delete a tank that doesn't exist or belong to him: %s" % (self.name, tankName)) raise BadInformationException("That tank does not exist.") changed = self.database.do_insert(Procedures.delete_tank(), tankName) if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't delete tank: DB error: %s -- " \ "data: name=%s" % (self, self.database.get_last_error(), tankName)) raise VTankException( "Internal database error. Please try again later.") self.refresh_tank_list() return True
def CreateAccount(self, username, password, email, current=None): """ Allow the user to attempt to create a new account on the server. """ # Validate. p = re.compile("[^A-Za-z0-9]"); if p.search(username): # Invalid character. raise BadInformationException("Username contains invalid characters."); # Validating e-mails are hard to do, so let's keep it simple. if '@' not in email or '.' not in email: # Invalid e-mail. raise BadInformationException("Invalid e-mail address."); # Hash the password. password = hash_password(password); results = self.database.do_query(Procedures.account_exists(), username); if len(results) != 0: self.report("Sorry %s, but that account already exists." % username); return False; results = self.database.do_insert(Procedures.new_account(), username, password, Utils.get_timestamp(), Utils.get_timestamp(), 0, 0, email); if results != 1: # No rows updated. self.report("Account creation failed! Reason: %s." % self.database.get_last_error()); raise VTankException("Internal database error -- please report this!"); self.report("Account created: %s (email: %s)." % (username, email)); return True;
def award_points(self, statistics): """ Gives a player ranking points based on the statistics of a game. @param statistics: A statistics object (kills, assists, deaths, objectives) """ if statistics.kills == 0 and statistics.assists == 0 and \ statistics.objectivesCaptured == 0 and statistics.objectivesCompleted: return totalPoints = 0 totalPoints += statistics.kills * 10 totalPoints += statistics.assists * 5 totalPoints += statistics.objectivesCompleted * 20 totalPoints += statistics.objectivesCaptured * 20 accountName_query_result = self.database.do_query( Procedures.get_account_from_tank(), statistics.tankName) if accountName_query_result == None: self.report( "Error: Could not find account for tank %s to calculate points" % statistics.tankName) return elif len(accountName_query_result) < 1: self.report( "Error: Could not find account for tank %s to calculate points" % statistics.tankName) return else: accountName = accountName_query_result[0][0] points_query_result = self.database.do_query( Procedures.get_account_points(), accountName) if points_query_result == None: self.report( "Error: Failed to retrieve points for account %s from database" % accountName) return elif len(points_query_result) < 1: self.report( "Error: Failed to retrieve points for account %s from database" % accountName) return else: accountPoints = points_query_result[0][0] accountPoints += totalPoints points_insert_result = self.database.do_insert( Procedures.update_account_points(), accountPoints, accountName) if points_insert_result == -1: # Failure. error = self.database.get_last_error() self.report("ERROR: Could not update points for player %s: %s." % (statistics.tankName, str(error)))
def Prepare(self): self.name = 'InitialImage' self.requirements['samplename'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'name of this sample for logging purposes' } self.requirements['nozzlename'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'name of the nozzle' } self.requirements['zOffset'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'z offset of nozzle during alignment pictures' } self.motionset = Procedures.Aerotech_A3200_Set(self.apparatus, self.executor) self.move = Procedures.Motion_RefRelLinearMotion( self.apparatus, self.executor) self.pmove = Procedures.Motion_RefRelPriorityLineMotion( self.apparatus, self.executor) self.image = Procedures.Camera_Capture_Image(self.apparatus, self.executor) self.getPos = Procedures.Aerotech_A3200_getPosition( self.apparatus, self.executor) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'StartAlignFile' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'StartAlignPosition' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'EndAlignFile' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'EndAlignPosition' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'InitialFile' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'InitialPosition' ])
def BanUserByAccountName(self, accountName, reason, current=None): self.refresh_action(); results = self.database.do_query(Procedures.account_exists(), accountName); if len(results) != 1: self.report("Account ban failed: %s doesn't exist." % accountName); raise BadInformationException("That account name does not exist."); result = self.database.do_insert(Procedures.set_user_level(), -99, accountName); if result == -1: self.report("Failed to ban account %s" % accountName);
def Prepare(self): self.name = 'PrintSample' self.requirements['samplename'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'name of this sample for logging purposes' } self.gentp = Procedures.Toolpath_Generate(MyApparatus, MyExecutor) self.printtp = Procedures.Toolpath_Print(MyApparatus, MyExecutor) self.planner = Procedures.Planner_Combinatorial( self.apparatus, self.executor)
def UnbanUserByAccountName(self, accountName, current=None): self.refresh_action(); results = self.database.do_query(Procedures.account_exists(), accountName); if len(results) != 1: self.report("Account unbanning failed: %s doesn't exist." % accountName); raise BadInformationException("That account name does not exist."); result = self.database.do_insert(Procedures.set_user_level(), 0, accountName); if result == -1: self.report("Failed to unban account %s" % accountName); raise VTankException("Internal database error -- please report this!");
def BanUserByAccountName(self, accountName, reason, current=None): self.refresh_action() results = self.database.do_query(Procedures.account_exists(), accountName) if len(results) != 1: self.report("Account ban failed: %s doesn't exist." % accountName) raise BadInformationException("That account name does not exist.") result = self.database.do_insert(Procedures.set_user_level(), -99, accountName) if result == -1: self.report("Failed to ban account %s" % accountName)
def CreateTank(self, tank, current=None): self.refresh_action() #self.validate_tank_attributes(tank); # Extract attributes. name = tank.name weapon_id = tank.weaponID speed_factor = tank.speedFactor armor_factor = tank.armorFactor lcolor = to_long(tank.color) model = tank.model skin = tank.skin # Validate the tank's name. self.validate_tank_name(name) # Insert the tank. changed = self.database.do_insert(Procedures.new_tank(), name, self.name, speed_factor, armor_factor, lcolor, weapon_id, model, skin) if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't insert tank: DB error: %s -- " \ "data: name=%s weapon_id=%i color=%s" % (self, self.database.get_last_error(), name, weapon_id, str(lcolor))) raise VTankException( "Internal database error. Please try again later.") # Now attempt to create the statistics table for this tank. changed = self.database.do_insert(Procedures.new_statistics(), name) if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't insert statistics: DB error: %s -- " \ "data: name=%s weapon_id=%i color=%s" % (self, self.database.get_last_error(), name, weapon_id, str(lcolor))) raise VTankException( "Internal database error. Please try again later.") self.refresh_tank_list() self.report("%s created a new tank (%s)." % (self.name, name)) return True
def SendStatistics(self, statistics, current=None): self.refresh_action() if len(statistics) == 0: return # TODO: Only allow for approved servers. for statistic in statistics: if statistic.kills == 0 and statistic.assists == 0 and statistic.deaths == 0 and\ statistic.objectivesCompleted == 0 and statistic.objectivesCaptured == 0: continue statistics_query = self.database.do_query( Procedures.get_tank_statistics(), statistic.tankName) if statistics_query == None: self.report( "Error: Failed to retrieve current statistics for tank %s from database" % statistic.tankName) return elif len(statistics_query) < 1: self.report( "Error: Failed to retrieve current statistics for tank %s from database" % statistic.tankName) return else: current_statistics = statistics_query[0] result = self.database.do_insert( Procedures.update_statistics(), str(int(current_statistics[1]) + statistic.kills), str(int(current_statistics[2]) + statistic.assists), str(int(current_statistics[3]) + statistic.deaths), str( int(current_statistics[4]) + statistic.objectivesCompleted), str(int(current_statistics[5]) + statistic.objectivesCaptured), statistic.tankName) if result == -1: # Failure. error = self.database.get_last_error() self.report( "ERROR: Could not update statistics for player %s: %s." % (statistic.tankName, str(error))) else: self.award_points(statistic)
def get_complete_userlist(self): """ Get the full list of users who are online and offline. @return Array of OnlineUser structs. """ userlist = self.get_full_userlist(); results = self.database.do_query(Procedures.get_userlist()); if results == None: self.report("Internal database error: %s." % str(self.database.get_last_error())); raise VTankException("Internal database error. Please report this immediately."); for row in results: username = row[0]; email = row[1]; userlevel = row[5]; exists = False; for existing_user in userlist: if existing_user.username.lower() == username.lower(): exists = True; break; if not exists: userlist.append(OnlineUser(username, "Offline", userlevel, False, False)); return userlist;
def save(self, filename, map_object): """ Save a map object in the database. @param filename Name of the file. @param map_object Map to save. @return True if successful. """ result = self.database.do_insert(Procedures.new_map(), map_object.title, filename, map_object.filesize, map_object.get_raw_data()); if result == None: error = str(self.database.get_last_error()); self.report("Database insert failed: %s." % error); Log.quick_log("Database insert failed: %s." % error); return False; if result <= 0: error = str(self.database.get_last_error()); self.report("Couldn't save map %s: probably already exists. (error=%s)" % ( filename, error)); Log.quick_log("Couldn't save map %s: probably already exists. (error=%s)" % ( filename, error)); return False; self.refresh_map_list(); return True;
def get_complete_userlist(self): """ Get the full list of users who are online and offline. @return Array of OnlineUser structs. """ userlist = self.get_full_userlist() results = self.database.do_query(Procedures.get_userlist()) if results == None: self.report("Internal database error: %s." % str(self.database.get_last_error())) raise VTankException( "Internal database error. Please report this immediately.") for row in results: username = row[0] email = row[1] userlevel = row[5] exists = False for existing_user in userlist: if existing_user.username.lower() == username.lower(): exists = True break if not exists: userlist.append( OnlineUser(username, "Offline", userlevel, False, False)) return userlist
def GetRanksOfTanks(self, tanks, current=None): """ Get the ranks of a list of tanks. @param tanks: A list of tank names @return: A list of integers representing their ranks """ self.refresh_action(); account_query_result = self.database.do_query(Procedures.get_tanks_and_points(tuple(tanks))) if account_query_result == None: self.report("Error: Failed to retrieve points from database for tanks" % str(tanks)); return; elif len(account_query_result) < 1: self.report("Error: Failed to retrieve points from database for tanks" % str(tanks)); return; ranks = []; for tank_name in tanks: for row in account_query_result: if str.lower(tank_name) == str.lower(row[0]): if row[1] == None: ranks.append(-1); else: ranks.append(int(self.get_rank_from_points(int(row[1])))); return tuple(ranks);
def save(self, filename, map_object): """ Save a map object in the database. @param filename Name of the file. @param map_object Map to save. @return True if successful. """ result = self.database.do_insert(Procedures.new_map(), map_object.title, filename, map_object.filesize, map_object.get_raw_data()) if result == None: error = str(self.database.get_last_error()) self.report("Database insert failed: %s." % error) Log.quick_log("Database insert failed: %s." % error) return False if result <= 0: error = str(self.database.get_last_error()) self.report( "Couldn't save map %s: probably already exists. (error=%s)" % (filename, error)) Log.quick_log( "Couldn't save map %s: probably already exists. (error=%s)" % (filename, error)) return False self.refresh_map_list() return True
def GetRanksOfTanks(self, tanks, current=None): """ Get the ranks of a list of tanks. @param tanks: A list of tank names @return: A list of integers representing their ranks """ self.refresh_action() account_query_result = self.database.do_query( Procedures.get_tanks_and_points(tuple(tanks))) if account_query_result == None: self.report( "Error: Failed to retrieve points from database for tanks" % str(tanks)) return elif len(account_query_result) < 1: self.report( "Error: Failed to retrieve points from database for tanks" % str(tanks)) return ranks = [] for tank_name in tanks: for row in account_query_result: if str.lower(tank_name) == str.lower(row[0]): if row[1] == None: ranks.append(-1) else: ranks.append( int(self.get_rank_from_points(int(row[1])))) return tuple(ranks)
def EditAccountByName(self, accountName, newInformation, current=None): self.refresh_action() # Validate. p = re.compile("[^A-Za-z0-9]") if p.search(accountName): # Invalid character. raise BadInformationException( "Old account name cannot exist (has invalid characters).") if p.search(newInformation.accountName): # Invalid character in new account name. raise BadInformationException( "New account name has invalid characters.") # Validating e-mails is hard to do, so let's keep it simple. if '@' not in newInformation.email or '.' not in newInformation.email: # Invalid e-mail. raise BadInformationException("Invalid e-mail address.") results = self.database.do_query(Procedures.account_exists(), accountName) if len(results) != 1: self.report("Account edit failed: %s doesn't exist." % username) raise BadInformationException("That account name does not exist.") pass
def award_points(self, statistics): """ Gives a player ranking points based on the statistics of a game. @param statistics: A statistics object (kills, assists, deaths, objectives) """ if statistics.kills == 0 and statistics.assists == 0 and \ statistics.objectivesCaptured == 0 and statistics.objectivesCompleted: return; totalPoints = 0; totalPoints += statistics.kills * 10; totalPoints += statistics.assists * 5; totalPoints += statistics.objectivesCompleted * 20; totalPoints += statistics.objectivesCaptured * 20; accountName_query_result = self.database.do_query(Procedures.get_account_from_tank(), statistics.tankName); if accountName_query_result == None: self.report("Error: Could not find account for tank %s to calculate points" % statistics.tankName); return; elif len(accountName_query_result) < 1: self.report("Error: Could not find account for tank %s to calculate points" % statistics.tankName); return; else: accountName = accountName_query_result[0][0]; points_query_result = self.database.do_query(Procedures.get_account_points(), accountName); if points_query_result == None: self.report("Error: Failed to retrieve points for account %s from database" % accountName); return; elif len(points_query_result) < 1: self.report("Error: Failed to retrieve points for account %s from database" % accountName); return; else: accountPoints = points_query_result[0][0]; accountPoints += totalPoints; points_insert_result = self.database.do_insert(Procedures.update_account_points(), accountPoints, accountName); if points_insert_result == -1: # Failure. error = self.database.get_last_error(); self.report("ERROR: Could not update points for player %s: %s." % ( statistics.tankName, str(error)));
def Prepare(self): self.name = 'Sample' self.GenTP = Procedures.Toolpath_Generate(self.apparatus, self.executor) self.PrintTP = Procedures.Toolpath_Print(self.apparatus, self.executor) self.Planner = Procedures.Planner_Combinatorial( self.apparatus, self.executor) self.move = Procedures.Motion_RefRelLinearMotion( self.apparatus, self.executor) self.pmove = Procedures.Motion_RefRelPriorityLineMotion( self.apparatus, self.executor) self.requirements['material'] = { 'source': 'direct', 'address': '', 'value': '', 'desc': 'material to be used', }
def UnbanUserByAccountName(self, accountName, current=None): self.refresh_action() results = self.database.do_query(Procedures.account_exists(), accountName) if len(results) != 1: self.report("Account unbanning failed: %s doesn't exist." % accountName) raise BadInformationException("That account name does not exist.") result = self.database.do_insert(Procedures.set_user_level(), 0, accountName) if result == -1: self.report("Failed to unban account %s" % accountName) raise VTankException( "Internal database error -- please report this!")
def CreateTank(self, tank, current=None): self.refresh_action(); #self.validate_tank_attributes(tank); # Extract attributes. name = tank.name; weapon_id = tank.weaponID; speed_factor = tank.speedFactor; armor_factor = tank.armorFactor; lcolor = to_long(tank.color); model = tank.model; skin = tank.skin; # Validate the tank's name. self.validate_tank_name(name); # Insert the tank. changed = self.database.do_insert(Procedures.new_tank(), name, self.name, speed_factor, armor_factor, lcolor, weapon_id, model, skin); if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't insert tank: DB error: %s -- " \ "data: name=%s weapon_id=%i color=%s" % (self, self.database.get_last_error(), name, weapon_id, str(lcolor))); raise VTankException("Internal database error. Please try again later."); # Now attempt to create the statistics table for this tank. changed = self.database.do_insert(Procedures.new_statistics(), name); if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't insert statistics: DB error: %s -- " \ "data: name=%s weapon_id=%i color=%s" % (self, self.database.get_last_error(), name, weapon_id, str(lcolor))); raise VTankException("Internal database error. Please try again later."); self.refresh_tank_list(); self.report("%s created a new tank (%s)." % (self.name, name)); return True;
def CreateAccount(self, username, password, email, userlevel, current=None): self.refresh_action() # Validate. p = re.compile("[^A-Za-z0-9]") if p.search(username): # Invalid character. raise BadInformationException( "Username contains invalid characters.") # Validating e-mails is hard to do, so let's keep it simple. if '@' not in email or '.' not in email: # Invalid e-mail. raise BadInformationException("Invalid e-mail address.") # Make sure password is filled in. if not password: raise BadInformationException("Password cannot be empty.") # Hash the password. password = sha1(password).hexdigest() results = self.database.do_query(Procedures.account_exists(), username) if len(results) != 0: self.report("Account creation failed: %s exists." % username) raise BadInformationException("That account name already exists.") results = self.database.do_insert(Procedures.new_account(), username, password, Utils.get_timestamp(), Utils.get_timestamp(), 0, userlevel, email) if results != 1: # No rows updated. self.report("Account creation failed! Reason: %s." % self.database.get_last_error()) raise BadInformationException( "Internal database error -- please report this!") self.report("Account created: %s (email: %s)." % (username, email))
def GetAccountByName(self, accountName, current=None): self.refresh_action(); result = self.database.do_query(Procedures.get_account_info(), accountName); if len(result) != 1: raise BadInformationException("That account does not exist."); row = result[0]; # Format: [0]email, [1]creation_date, [2]last_logged_in, [3]rank_level, [4]user_level, [5]points return Admin.Account(accountName, row[0], row[1], row[2], row[3], row[4], row[5]);
def update_last_login_time(reporter, database_obj, username): """ Utility function for doing an insert on an active database. Updates the last login time for the given username. """ result = database_obj.do_insert(Procedures.update_account(), get_timestamp(), username) if result < 0: # Less than zero indicates an error. if reporter != None: reporter("Update account last login error: %s." % str(database_obj.get_last_error())) raise VTankException("Internal database error. Please report this!")
def tank_name_exists(self, tank_name): """ Do a check on the database to see if a certain tank name exists. @return True if the name exists, otherwise false. """ results = self.database.do_query(Procedures.tank_exists(), tank_name); if len(results) > 0: # Tank exists. return True; return False;
def tank_name_exists(self, tank_name): """ Do a check on the database to see if a certain tank name exists. @return True if the name exists, otherwise false. """ results = self.database.do_query(Procedures.tank_exists(), tank_name) if len(results) > 0: # Tank exists. return True return False
def UpdateTank(self, oldTankName, newTank, current=None): self.refresh_action() # Must check if the tank exists, and if it belongs to this account. results = self.database.do_query( Procedures.tank_exists_under_account(), oldTankName, self.name) if len(results) != 1: # Tank does not exist. Log.log_print( Utils.filename_today(), "players", "User %s tried to update a tank that doesn't exist or belong to him: %s" % (self.name, oldTankName)) raise BadInformationException("That tank does not exist.") self.validate_tank_name(newTank.name, False) #self.validate_tank_attributes(newTank); # Extract attributes. weapon_id = newTank.weaponID speed_factor = newTank.speedFactor armor_factor = newTank.armorFactor lcolor = to_long(newTank.color) model = newTank.model skin = newTank.skin changed = self.database.do_insert(Procedures.update_tank(), speed_factor, armor_factor, lcolor, weapon_id, model, skin, oldTankName) if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't update tank: DB error: %s -- " \ "data: oldname=%s name=%s weapon_id=%i armor_id=%i color=%s" % (self, self.database.get_last_error(), oldTankName, newTank.name, weapon_id, armor_factor, str(lcolor))) #raise VTankException("Internal database error. Please try again later."); return False self.refresh_tank_list() return True
def GetAccountList(self, current=None): self.refresh_action(); result = self.database.do_query(Procedures.get_account_list()); accounts = []; for row in result: # Format: [0]account_name, [1]email, [2]creation_date, [3]last_logged_in, [4]rank_level, [5]user_level, [6]points accounts.append(Admin.Account(row[0], row[1], row[2], row[3], row[4], row[5], row[6])); return accounts;
def GetAccountByName(self, accountName, current=None): self.refresh_action() result = self.database.do_query(Procedures.get_account_info(), accountName) if len(result) != 1: raise BadInformationException("That account does not exist.") row = result[0] # Format: [0]email, [1]creation_date, [2]last_logged_in, [3]rank_level, [4]user_level, [5]points return Admin.Account(accountName, row[0], row[1], row[2], row[3], row[4], row[5])
def SendStatistics(self, statistics, current=None): self.refresh_action(); if len(statistics) == 0: return; # TODO: Only allow for approved servers. for statistic in statistics: if statistic.kills == 0 and statistic.assists == 0 and statistic.deaths == 0 and\ statistic.objectivesCompleted == 0 and statistic.objectivesCaptured == 0: continue; statistics_query = self.database.do_query(Procedures.get_tank_statistics(), statistic.tankName); if statistics_query == None: self.report("Error: Failed to retrieve current statistics for tank %s from database" % statistic.tankName); return; elif len(statistics_query) < 1: self.report("Error: Failed to retrieve current statistics for tank %s from database" % statistic.tankName); return; else: current_statistics = statistics_query[0]; result = self.database.do_insert(Procedures.update_statistics(), str(int(current_statistics[1]) + statistic.kills), str(int(current_statistics[2]) + statistic.assists), str(int(current_statistics[3]) + statistic.deaths), str(int(current_statistics[4]) + statistic.objectivesCompleted), str(int(current_statistics[5]) + statistic.objectivesCaptured), statistic.tankName); if result == -1: # Failure. error = self.database.get_last_error(); self.report("ERROR: Could not update statistics for player %s: %s." % ( statistic.tankName, str(error))); else: self.award_points(statistic);
def UpdateTank(self, oldTankName, newTank, current=None): self.refresh_action(); # Must check if the tank exists, and if it belongs to this account. results = self.database.do_query(Procedures.tank_exists_under_account(), oldTankName, self.name); if len(results) != 1: # Tank does not exist. Log.log_print(Utils.filename_today(), "players", "User %s tried to update a tank that doesn't exist or belong to him: %s" % ( self.name, oldTankName)); raise BadInformationException("That tank does not exist."); self.validate_tank_name(newTank.name, False); #self.validate_tank_attributes(newTank); # Extract attributes. weapon_id = newTank.weaponID; speed_factor = newTank.speedFactor; armor_factor = newTank.armorFactor; lcolor = to_long(newTank.color); model = newTank.model; skin = newTank.skin; changed = self.database.do_insert(Procedures.update_tank(), speed_factor, armor_factor, lcolor, weapon_id, model, skin, oldTankName); if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't update tank: DB error: %s -- " \ "data: oldname=%s name=%s weapon_id=%i armor_id=%i color=%s" % (self, self.database.get_last_error(), oldTankName, newTank.name, weapon_id, armor_factor, str(lcolor))); #raise VTankException("Internal database error. Please try again later."); return False; self.refresh_tank_list(); return True;
def refresh_weapon_list(self): """ Refresh the list of weapons by grabbing the newest ones out of the database. """ with self._lock: weapons = self._db.do_query(Procedures.get_weapon_list()) if not weapons: Log.log_print(Utils.filename_today(), "misc", "Error: %s" % \ str(self._db.get_last_error())) else: for set in weapons: # weapon_id, name, cooldown, projectile_id, model, sound_effect, can_charge self._weapons[set[0]] = set[1]
def GetAccountList(self, current=None): self.refresh_action() result = self.database.do_query(Procedures.get_account_list()) accounts = [] for row in result: # Format: [0]account_name, [1]email, [2]creation_date, [3]last_logged_in, [4]rank_level, [5]user_level, [6]points accounts.append( Admin.Account(row[0], row[1], row[2], row[3], row[4], row[5], row[6])) return accounts
def refresh_weapon_list(self): """ Refresh the list of weapons by grabbing the newest ones out of the database. """ with self._lock: weapons = self._db.do_query(Procedures.get_weapon_list()); if not weapons: Log.log_print(Utils.filename_today(), "misc", "Error: %s" % \ str(self._db.get_last_error())); else: for set in weapons: # weapon_id, name, cooldown, projectile_id, model, sound_effect, can_charge self._weapons[set[0]] = set[1];
def CreateAccount(self, username, password, email, userlevel, current=None): self.refresh_action(); # Validate. p = re.compile("[^A-Za-z0-9]"); if p.search(username): # Invalid character. raise BadInformationException("Username contains invalid characters."); # Validating e-mails is hard to do, so let's keep it simple. if '@' not in email or '.' not in email: # Invalid e-mail. raise BadInformationException("Invalid e-mail address."); # Make sure password is filled in. if not password: raise BadInformationException("Password cannot be empty."); # Hash the password. password = sha1(password).hexdigest(); results = self.database.do_query(Procedures.account_exists(), username); if len(results) != 0: self.report("Account creation failed: %s exists." % username); raise BadInformationException("That account name already exists."); results = self.database.do_insert(Procedures.new_account(), username, password, Utils.get_timestamp(), Utils.get_timestamp(), 0, userlevel, email); if results != 1: # No rows updated. self.report("Account creation failed! Reason: %s." % self.database.get_last_error()); raise BadInformationException("Internal database error -- please report this!"); self.report("Account created: %s (email: %s)." % (username, email));
def DeleteTank(self, tankName, current=None): self.refresh_action(); # Must check if the tank exists, and if it belongs to this account. results = self.database.do_query(Procedures.tank_exists_under_account(), tankName, self.name); if len(results) != 1: # Tank does not exist. Log.quick_log("User %s tried to delete a tank that doesn't exist or belong to him: %s" % ( self.name, tankName)); raise BadInformationException("That tank does not exist."); changed = self.database.do_insert(Procedures.delete_tank(), tankName); if not changed: # Nothing was changed: database error. Log.log_print(Utils.filename_today(), "players", "User %s couldn't delete tank: DB error: %s -- " \ "data: name=%s" % (self, self.database.get_last_error(), tankName)); raise VTankException("Internal database error. Please try again later."); self.refresh_tank_list(); return True;
def download_map(self, filename): """ Download a map. @param filename Name of the map. @return Map object on success, None on error. """ # [0]filename, [1]title, [2]filesize, [3]map_data map_data = self.database.do_query(Procedures.get_map(), filename); map = Map(self.reporter); try: if not map.read_map(map_data[0][3]): raise Exception, "Unknown corruption error." % filename; except Exception, e: self.report("Map file %s is corrupted (%s). Discarding." % (filename, str(e))); Log.quick_log("The map %s is corrupted: %s." % (filename, str(e))); return None;
def GetAccountPoints(self, current=None): """ Get the total points an account has from the database. @param accountName: The account in question. @return: The number of points this account has. """ self.refresh_action(); account_points_query = self.database.do_query(Procedures.get_account_points(), self.name); if account_points_query == None: self.report("ERROR: Failed to retrieve %s's account points from the database" % self.name); return None; elif len(account_points_query) < 1: return None; return account_points_query[0][0];
def refresh_utilities_list(self): """ Refresh the list of utilities by grabbing the newest ones out of the database. """ with self._lock: utilities = self._db.do_query(Procedures.get_utilities_list()); if not utilities: Log.log_print(Utils.filename_today(), "misc", "Error: %s" %\ str(self._db.get_last_error())); else: for set in utilities: # [0]utility_id, [3]duration, [4]damage_factor, [5]speed_factor, # [6]rate_factor, [7]health_increase, [8]health_factor # [1]name, [9]model, [2]description self._utilities[set[0]] = VTankObject.Utility( set[0], set[3], set[4], set[5], set[6], set[7], set[8], set[1], set[9], set[2]);
def download_map(self, filename): """ Download a map. @param filename Name of the map. @return Map object on success, None on error. """ # [0]filename, [1]title, [2]filesize, [3]map_data map_data = self.database.do_query(Procedures.get_map(), filename) map = Map(self.reporter) try: if not map.read_map(map_data[0][3]): raise Exception, "Unknown corruption error." % filename except Exception, e: self.report("Map file %s is corrupted (%s). Discarding." % (filename, str(e))) Log.quick_log("The map %s is corrupted: %s." % (filename, str(e))) return None
def GetPointsByTank(self, tankName): """ Get the total points a tank has from the database. @param tankName: The name of the tank in question. @return: The current number of points he has earned. """ result = self.database.do_query(Procedures.get_tank(), tankName); if result == -1: error = self.database.get_last_error(); self.report("ERROR: Failed to retrieve data for rank computation for tank %s: %s" % (tankName, str(error))); points = 0; for tank in result: points = tank[5]; return points;
def Prepare(self): self.name = "Suggest" self.requirements['prevSample'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'information about previous sample' } self.requirements['prevSample']['address'] = [ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters' ] self.requirements['material'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'material printed for sample' } self.requirements['yGap'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'y gap for span' } self.requirements['zGap'] = { 'source': 'apparatus', 'address': '', 'value': '', 'desc': 'z gap for span' } # provide necessary structure self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'speed' ]) self.apparatus.createAppEntry([ 'information', 'ProcedureData', 'SpanningSample', 'cur_parameters', 'Class' ]) self.newsample = SpanningSample(self.apparatus, self.executor) self.classify = ImPredict(self.apparatus, self.executor) self.recordData = Procedures.Data_JSON_Store(self.apparatus, self.executor)
def refresh_utilities_list(self): """ Refresh the list of utilities by grabbing the newest ones out of the database. """ with self._lock: utilities = self._db.do_query(Procedures.get_utilities_list()) if not utilities: Log.log_print(Utils.filename_today(), "misc", "Error: %s" %\ str(self._db.get_last_error())) else: for set in utilities: # [0]utility_id, [3]duration, [4]damage_factor, [5]speed_factor, # [6]rate_factor, [7]health_increase, [8]health_factor # [1]name, [9]model, [2]description self._utilities[set[0]] = VTankObject.Utility( set[0], set[3], set[4], set[5], set[6], set[7], set[8], set[1], set[9], set[2])
def Prepare(self): self.name = 'Sample' self.ProbeMeasure = Procedures.Touch_Probe_A3200_MeasureGrid( MyApparatus, MyExecutor) self.ProbeCorrect = Procedures.Touch_Probe_A3200_EnableCalibration( MyApparatus, MyExecutor) self.ProbeStopCorrect = Procedures.Touch_Probe_A3200_DisableCalibration( MyApparatus, MyExecutor) self.Camera = Procedures.Camera_Capture_ImageXY( MyApparatus, MyExecutor) self.Cleaner = Procedures.Aerotech_A3200_AirClean( MyApparatus, MyExecutor) self.Pause = Procedures.Data_User_Input_Options( MyApparatus, MyExecutor) self.testMaterial = Procedures.ROSEDA_TestMaterial( MyApparatus, MyExecutor) self.rparameters = Make_TPGen_Data(mat0)
def delete(self, filename): """ Delete a map from the database. @param filename Name of the map to remove. @return True if the map was removed without issue. """ result = self.database.do_insert(Procedures.delete_map(), filename) if result <= 0: # No rows affected. error = str(self.database.get_last_error()) self.report("Couldn't delete map %s. (error=%s)" % (filename, error)) Log.quick_log("Couldn't save map %s. (error=%s)" % (filename, error)) return False self.refresh_map_list() return result == 1
def GetAccountPoints(self, current=None): """ Get the total points an account has from the database. @param accountName: The account in question. @return: The number of points this account has. """ self.refresh_action() account_points_query = self.database.do_query( Procedures.get_account_points(), self.name) if account_points_query == None: self.report( "ERROR: Failed to retrieve %s's account points from the database" % self.name) return None elif len(account_points_query) < 1: return None return account_points_query[0][0]
def GetPointsByTank(self, tankName): """ Get the total points a tank has from the database. @param tankName: The name of the tank in question. @return: The current number of points he has earned. """ result = self.database.do_query(Procedures.get_tank(), tankName) if result == -1: error = self.database.get_last_error() self.report( "ERROR: Failed to retrieve data for rank computation for tank %s: %s" % (tankName, str(error))) points = 0 for tank in result: points = tank[5] return points
def delete(self, filename): """ Delete a map from the database. @param filename Name of the map to remove. @return True if the map was removed without issue. """ result = self.database.do_insert(Procedures.delete_map(), filename); if result <= 0: # No rows affected. error = str(self.database.get_last_error()); self.report("Couldn't delete map %s. (error=%s)" % ( filename, error)); Log.quick_log("Couldn't save map %s. (error=%s)" % ( filename, error)); return False; self.refresh_map_list(); return result == 1;
def refresh_map_list(self): """ This obtains a list of maps from the database. While it records all of the map names, it does not necessarily cache the maps. Map caching is dealt with by the rest of the class. """ self.report("Refreshing maps...") self.size = 0 self.maps = {} results = self.database.do_query(Procedures.get_map_list()) if results == None: error = str(self.database.get_last_error()) self.report("Database error: %s." % error) raise RuntimeError, error if not len(results): # No maps. self.report("No maps to download.") self.maps = {} return for set in results: # [0]filename, [1]filesize filename = set[0] filesize = set[1] if self.size + filesize > CACHE_LIMIT: # Do not download map: it breaks the cache limit. self.maps[filename] = None else: # Download map. downloaded_map = self.download_map(filename) if not downloaded_map: self.report("Didn't download map: %s." % filename) continue self.maps[filename] = downloaded_map self.size += filesize self.report("Added map: %s (size=%i, totalsize=%i)." % (filename, filesize, self.size)) World.get_world().update_game_server_maps()
def refresh_map_list(self): """ This obtains a list of maps from the database. While it records all of the map names, it does not necessarily cache the maps. Map caching is dealt with by the rest of the class. """ self.report("Refreshing maps..."); self.size = 0; self.maps = {}; results = self.database.do_query(Procedures.get_map_list()); if results == None: error = str(self.database.get_last_error()); self.report("Database error: %s." % error); raise RuntimeError, error; if not len(results): # No maps. self.report("No maps to download."); self.maps = {}; return; for set in results: # [0]filename, [1]filesize filename = set[0]; filesize = set[1]; if self.size + filesize > CACHE_LIMIT: # Do not download map: it breaks the cache limit. self.maps[filename] = None; else: # Download map. downloaded_map = self.download_map(filename); if not downloaded_map: self.report("Didn't download map: %s." % filename); continue; self.maps[filename] = downloaded_map; self.size += filesize; self.report("Added map: %s (size=%i, totalsize=%i)." % ( filename, filesize, self.size)); World.get_world().update_game_server_maps();
def refresh_tank_list(self): """ Perform a SQL search of the client's tank list and cache the results. """ results = self.database.do_query(Procedures.get_tank_list(), self.name); if results == None: self.report("MySQL error: %s." % (self.database.get_last_error())); self.tank_list = {}; return; tanks = {}; # Travel through results row-by-row for set in results: # Format: 0:tank_name, 1:color, 2:weapon_id, 3:speed_factor, 4:armor_factor, 5:points 6:model 7:skin #weapon = Equipment_Manager.get_manager().get_weapon(set[2]); color = to_color(set[1]); color = VTankObject.VTankColor(color.r(), color.g(), color.b()); tank = VTankObject.TankAttributes(set[0], set[3], set[4], set[5], TANK_HEALTH, set[6], set[7], set[2], color); tanks[set[0]] = tank; self.tank_list = tanks;
def EditAccountByName(self, accountName, newInformation, current=None): self.refresh_action(); # Validate. p = re.compile("[^A-Za-z0-9]"); if p.search(accountName): # Invalid character. raise BadInformationException("Old account name cannot exist (has invalid characters)."); if p.search(newInformation.accountName): # Invalid character in new account name. raise BadInformationException("New account name has invalid characters."); # Validating e-mails is hard to do, so let's keep it simple. if '@' not in newInformation.email or '.' not in newInformation.email: # Invalid e-mail. raise BadInformationException("Invalid e-mail address."); results = self.database.do_query(Procedures.account_exists(), accountName); if len(results) != 1: self.report("Account edit failed: %s doesn't exist." % username); raise BadInformationException("That account name does not exist."); pass;