def self_remove_all(): # remove your self from all wls # sse list _events = [] logger.info("%s removed them selfs from waitlists", current_user.get_eve_name()) # queue = db.session.query(Waitlist).filter(Waitlist.name == WaitlistNames.xup_queue).first() # remove from all lists except queue entries = db.session.query(WaitlistEntry).filter(WaitlistEntry.user == current_user.get_eve_id()) fittings = [] for entry in entries: fittings.extend(entry.fittings) h_entry = create_history_object(current_user.get_eve_id(), HistoryEntry.EVENT_SELF_RM_WLS_ALL, None, fittings) db.session.add(h_entry) for entry in entries: logger.info("%s removed own entry with id=%s", current_user.get_eve_name(), entry.id) event = EntryRemovedSSE(entry.waitlist.group.groupID, entry.waitlist_id, entry.id) _events.append(event) db.session.delete(entry) db.session.commit() for event in _events: send_server_sent_event(event) return "success"
def self_remove_fit(fitid): # remove one of your fittings by id fit = db.session.query(Shipfit).filter(Shipfit.id == fitid).first() # this fit is not on any waitlist # if we get this case it means some ones UI did not update if fit.waitlist is None: logger.info(f"{current_user.get_eve_name()} tried to remove own fit with id={fit.id}" f" while it was not on any waitlist anymore") return "This fit is not on a waitlist anymore" wlentry = db.session.query(WaitlistEntry).filter(WaitlistEntry.id == fit.waitlist.id).first() if wlentry.user == current_user.get_eve_id(): logger.info("%s removed their fit with id %d from group %s", current_user.get_eve_name(), fitid, wlentry.waitlist.group.groupName) event = FitRemovedSSE(wlentry.waitlist.group.groupID, wlentry.waitlist_id, wlentry.id, fit.id, wlentry.user) wlentry.fittings.remove(fit) # don't delete anymore we need them for history # db.session.delete(fit) if len(wlentry.fittings) <= 0: event = EntryRemovedSSE(wlentry.waitlist.group.groupID, wlentry.waitlist_id, wlentry.id) db.session.delete(wlentry) send_server_sent_event(event) h_entry = create_history_object(current_user.get_eve_id(), HistoryEntry.EVENT_SELF_RM_FIT, None, [fit]) h_entry.exref = wlentry.waitlist.group.groupID db.session.add(h_entry) db.session.commit() else: flask.abort(403) return "success"
def api_wls_remove_player(): # sse events _events = [] player_id = int(request.form['playerId']) group_id = int(request.form['groupId']) if player_id is None: logger.error("Tried to remove player with None id from waitlists.") group = db.session.query(WaitlistGroup).get(group_id) # don't remove from queue waitlist_entries = db.session.query(WaitlistEntry).filter( (WaitlistEntry.user == player_id) & ((WaitlistEntry.waitlist_id == group.logiwlID) | (WaitlistEntry.waitlist_id == group.dpswlID) | (WaitlistEntry.waitlist_id == group.sniperwlID))).all() fittings = [] for entry in waitlist_entries: fittings.extend(entry.fittings) # check if there is an other waitlist if group.otherwlID is not None: entry = db.session.query(WaitlistEntry).filter( (WaitlistEntry.user == player_id) & (WaitlistEntry.waitlist_id == group.otherwlID)).one_or_none() if entry is not None: fittings.extend(entry.fittings) waitlist_entries = db.session.query(WaitlistEntry).filter( (WaitlistEntry.user == player_id) & ((WaitlistEntry.waitlist_id == group.logiwlID) | (WaitlistEntry.waitlist_id == group.dpswlID) | (WaitlistEntry.waitlist_id == group.sniperwlID))).all() for entry in waitlist_entries: event = EntryRemovedSSE(entry.waitlist.groupID, entry.waitlist_id, entry.id) _events.append(event) db.session.query(WaitlistEntry).filter( (WaitlistEntry.user == player_id) & ((WaitlistEntry.waitlist_id == group.logiwlID) | (WaitlistEntry.waitlist_id == group.dpswlID) | (WaitlistEntry.waitlist_id == group.sniperwlID))).delete() # if other waitlist delete those entries too if group.otherwlID is not None: db.session.query(WaitlistEntry).filter((WaitlistEntry.user == player_id) & (WaitlistEntry.waitlist_id == group.otherwlID)).delete() h_entry = create_history_object(player_id, HistoryEntry.EVENT_COMP_RM_PL, current_user.id, fittings) h_entry.exref = group.groupID db.session.add(h_entry) db.session.commit() character = db.session.query(Character).filter(Character.id == player_id).first() logger.info("%s removed %s from %s waitlist.", current_user.username, character.eve_name, group.groupName) for event in _events: send_server_sent_event(event) return "OK"
def self_remove_wl_entry(entry_id): # remove your self from a wl by wl entry id entry = db.session.query(WaitlistEntry).filter( (WaitlistEntry.id == entry_id) & (WaitlistEntry.user == current_user.get_eve_id())).first() if entry is None: flask.abort(404, "This Waitlist Entry does not exist.") event = EntryRemovedSSE(entry.waitlist.groupID, entry.waitlist_id, entry.id) logger.info("%s removed their own entry with id %d", current_user.get_eve_name(), entry_id) h_entry = create_history_object(current_user.get_eve_id(), HistoryEntry.EVENT_SELF_RM_ETR, None, entry.fittings) h_entry.exref = entry.waitlist.group.groupID db.session.add(h_entry) db.session.delete(entry) db.session.commit() send_server_sent_event(event) return "success"
def wl_remove_entry(): entry_id = int(request.form['entryId']) entry = db.session.query(WaitlistEntry).get(entry_id) if entry is None: flask.abort(404, "Waitlist Entry does not exist!") h_entry = create_history_object(entry.user_data.get_eve_id(), HistoryEntry.EVENT_COM_RM_ETR, current_user.id, entry.fittings) h_entry.exref = entry.waitlist.group.groupID db.session.add(h_entry) logger.info("%s removed %s from waitlist %s of group %s", current_user.username, entry.user_data.get_eve_name(), entry.waitlist.name, entry.waitlist.group.groupName) event = EntryRemovedSSE(entry.waitlist.groupID, entry.waitlist_id, entry.id) db.session.query(WaitlistEntry).filter(WaitlistEntry.id == entry_id).delete() db.session.commit() send_server_sent_event(event) return "OK"
def send_notification( player_id: int, waitlist_id: int, message: str = "You are invited to fleet as {0}") -> None: if player_id is None: logger.error("Tried to send notification to player with None ID.") flask.abort(400, "Tried to send notification to player with None ID") # lets check that the given wl exists waitlist = db.session.query(Waitlist).get(waitlist_id) if waitlist is None: logger.error("Given waitlist id %s is not valid.", str(waitlist_id)) flask.abort(400, f"Given waitlist id {waitlist_id} is not valid.") # don't remove from queue # queue = db.session.query(Waitlist).filter(Waitlist.name == WaitlistNames.xup_queue).first() # db.session.query(WaitlistEntry).filter((WaitlistEntry.user == playerId) # & (WaitlistEntry.waitlist_id != queue.id)).delete() # db.session.commit() event = GongSSE(player_id) send_server_sent_event(event) # publish(event) character = db.session.query(Character).filter( Character.id == player_id).first() if not config.disable_teamspeak and character.poke_me: # only poke if he didn't disable it try: message = message.format(waitlist.name) send_poke(character.eve_name, message) except TS3QueryError: pass # ignore it a user that is not on TS h_entry = create_history_object(character.get_eve_id(), HistoryEntry.EVENT_COMP_NOTI_PL, current_user.id) h_entry.exref = waitlist.group.groupID db.session.add(h_entry) db.session.commit() logger.info("%s send notification to %s.", current_user.username, character.eve_name)
def fleet_status_set(gid: int) -> Response: action = request.form['action'] group = db.session.query(WaitlistGroup).get(gid) if action == "status": text = request.form['status'] xup = request.form.get('xup', 'off') influence = request.form.get('influence') influence = False if influence is None else True xup_text = "closed" if xup == 'off': xup = False else: xup = True xup_text = "open" if xup != group.enabled: group.enabled = xup logger.info("XUP was set to %s by %s", xup, current_user.username) if influence != group.influence: group.influence = influence logger.info("Influence setting of grp %s was changed to %s by %s", group.groupID, influence, current_user.username) if perm_custom_status.can(): group.status = text logger.info("Status was set to %s by %s", group.status, current_user.username) flash("Status was set to " + text + ", xup is " + xup_text, "success") else: if text == "Running" or text == "Down" or text == "Forming": group.status = text logger.info("Status was set to %s by %s", group.status, current_user.username) flash("Status was set to " + text + ", xup is " + xup_text, "success") else: logger.info( "%s tried to set the status to %s and did not have the rights", current_user.username, group.status) flash( "You do not have the rights to change the status to " + text, "danger") flash("XUP is now " + xup_text, "success") elif action == "fc": group.fcs.append(current_user) with open("set_history.log", "a+") as f: f.write('{} - {} sets them self as FC\n'.format( datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), current_user.username)) flash("You added your self to FCs " + current_user.get_eve_name(), "success") elif action == "manager": group.manager.append(current_user) with open("set_history.log", "a+") as f: f.write('{} - {} sets them self as Fleet Manager\n'.format( datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), current_user.username)) flash("You added your self to manager " + current_user.get_eve_name(), "success") elif action == "manager-remove": account_id = int(request.form['accountID']) account = db.session.query(Account).get(account_id) with open("set_history.log", "a+") as f: f.write('{} - {} is removed as Fleet Manager by {}\n'.format( datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), account.username, current_user.username)) try: group.manager.remove(account) except ValueError: pass elif action == "fc-remove": account_id = int(request.form['accountID']) account = db.session.query(Account).get(account_id) with open("set_history.log", "a+") as f: f.write('{} - {} is removed as FC by {}\n'.format( datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), account.username, current_user.username)) try: group.fcs.remove(account) except ValueError: pass elif action == "add-backseat": group.backseats.append(current_user) with open("set_history.log", "a+") as f: f.write('{} - {} sets them self as Backseat\n'.format( datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), current_user.username)) flash("You added your self as Backseat " + current_user.get_eve_name(), "success") elif action == "remove-backseat": account_id = int(request.form['accountID']) account = db.session.query(Account).get(account_id) with open("set_history.log", "a+") as f: f.write('{} - {} is removed as Backseat by {}\n'.format( datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), account.username, current_user.username)) try: group.backseats.remove(account) except ValueError: pass elif action == "check-in": # check if in a fleet if member_info.is_member_in_fleet(current_user.get_eve_id()): postfix = "was found in fleet" else: postfix = "was not found in fleet" with open("set_history.log", "a+") as f: f.write( f'{datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")}' f' - {current_user.username} checked in for activity, {postfix}\n' ) flash( f"Your activity report has been submitted {current_user.username}", "success") elif action == "change_display_name": # if we have no permissions to set a custom name, we are done if not perm_manager.get_permission('fleet_custom_display_name').can(): flash( f"{current_user.username} has no permissions to set a custom display name for a waitlist!", "danger") return redirect(url_for(".fleet"), code=303) # TODO: this should be configurable and also set the dropdown options unrestricted_display_names = ["Headquarter", "Assault", "Vanguard"] display_name = request.form.get("display_name", None) # if we are not given a valid new custom name we are done if display_name is None: flash(f"No valid new display name given (given was None)", "danger") return redirect(url_for(".fleet"), code=303) # it is not a unresticted name and we do not have the power to set abitrary names, then we are done if not ((display_name in unrestricted_display_names) or perm_manager. get_permission('fleet_custom_display_name_all').can()): flash( f"You gave no unrestricted display name and do not have the power to set abitrary names!", "danger") return redirect(url_for(".fleet"), code=303) # we checked that we are allowed to do this, let do it and logg it group.displayName = display_name logging.info( f"{current_user.username} set the displayName of group with id={group.groupID} to {display_name}" ) db.session.commit() event = StatusChangedSSE(group) send_server_sent_event(event) return redirect(url_for(".fleet"), code=303)
def submit(): """ Parse the submited fitts Check which fits need additional Info Rattlesnake, Rokh, that other ugly thing Caldari BS lvl Basilisk, Scimitar Logi Lvl -> put info into comment of the fit """ # used for spawning the right SSEs _newEntryCreated = False _newFits = [] fittings = request.form['fits'] group_id = int(request.form['groupID']) logger.info("%s submitted %s for group %d", current_user.get_eve_name(), fittings, group_id) eve_id = current_user.get_eve_id() group = db.session.query(WaitlistGroup).filter( WaitlistGroup.groupID == group_id).one() if not group.enabled: # xups are disabled atm flash(gettext("X-UP is disabled!!!")) return redirect(url_for("index")) poke_me = 'pokeMe' in request.form if current_user.poke_me != poke_me: current_user.poke_me = poke_me db.session.commit() # check if it is scruffy if not disable_scruffy_mode and fittings.lower().startswith("scruffy"): # scruffy mode scruffy fittings = fittings.lower() _, _, ship_type = fittings.rpartition(" ") ship_types = [] # check for , to see if it is a multi value shiptype allowed_types = [ tpl[0].strip() for tpl in db.session.query(Waitlist.waitlistType).filter( (~Waitlist.group.has(WaitlistGroup.queueID == Waitlist.id)) & (Waitlist.groupID == group_id)) ] if "," in ship_type: for stype in ship_type.split(","): stype = stype.strip() if stype in allowed_types: ship_types.append(stype) else: if ship_type in allowed_types: ship_types.append(ship_type) # check if shiptype is valid if len(ship_types) <= 0: flash( gettext("Valid entries are scruffy %(types)s", types=','.join(allowed_types)), 'danger') return redirect(url_for('index')) queue = group.xuplist wl_entry = db.session.query( WaitlistEntry).filter((WaitlistEntry.waitlist_id == queue.id) & (WaitlistEntry.user == eve_id)).first() if wl_entry is None: wl_entry = WaitlistEntry() wl_entry.creation = datetime.utcnow() wl_entry.user = eve_id queue.entries.append(wl_entry) _newEntryCreated = True h_entry = create_history_object(current_user.get_eve_id(), "xup") for stype in ship_types: wl = db.session.query( Waitlist).filter((Waitlist.groupID == group_id) & (Waitlist.waitlistType == stype)).first() target_wl_id = None if wl is not None: target_wl_id = wl.id if target_wl_id is None: target_wl_id = db.session.query(ShipCheckCollection).filter( (ShipCheckCollection.waitlistGroupID == group_id )).one().defaultTargetID fit: Shipfit = Shipfit() fit.ship_type = 0 # #System >.> fit.wl_type = stype fit.modules = ':' fit.targetWaitlistID = target_wl_id wl_entry.fittings.append(fit) if not _newEntryCreated: _newFits.append(fit) h_entry.fittings.append(fit) db.session.add(h_entry) db.session.commit() if _newEntryCreated: event = EntryAddedSSE(wl_entry, group_id, queue.id, True) send_server_sent_event(event) else: for fit in _newFits: event = FitAddedSSE(group_id, queue.id, wl_entry.id, fit, True, wl_entry.user) send_server_sent_event(event) flash(gettext("You were added as %(ship_type)s", ship_type=ship_type), "success") return redirect(url_for('index') + "?groupId=" + str(group_id)) # ### END SCRUFFY CODE logilvl = request.form['logi'] if logilvl == "": logilvl = "0" caldari_bs_lvl = request.form['cbs'] if caldari_bs_lvl == "": caldari_bs_lvl = "0" logilvl = int(logilvl) caldari_bs_lvl = int(caldari_bs_lvl) newbro = request.form.get('newbro', "off") newbro = (newbro is not "off") current_user.is_new = newbro current_user.cbs_level = caldari_bs_lvl current_user.lc_level = logilvl logger.debug("Fittings to parse: %s", fittings) # lets normalize linebreaks fittings = fittings.replace("[\n\r]+", "\n") fittings = fittings.strip() # lets first find out what kind of fitting is used end_line_idx = fittings.find('\n') + 1 first_line = fittings[:end_line_idx] format_type = get_fit_format(first_line) fits = [] if format_type == "eft": # split fittings up in its fittings string_fits = [] fit_iter = re.finditer("\[.*,.*\]", fittings) s_idx = 0 first_iter = True for fitMatch in fit_iter: if not first_iter: e_idx = fitMatch.start() - 1 string_fits.append(fittings[s_idx:e_idx].split('\n')) else: first_iter = False s_idx = fitMatch.start() string_fits.append(fittings[s_idx:].split('\n')) logger.debug("Split fittings into %d fits", len(string_fits)) for fit in string_fits: try: dbfit = parse_eft(fit) if dbfit is None: abort(400, "Fit was not parseable.") fits.append(dbfit) except ValueError: abort(400, "Invalid module amounts") else: # parse chat links lines = fittings.split('\n') for line in lines: fit_iter = re.finditer( "<url=fitting:(\d+):((?:\d+_{0,1};\d+:)+:)>", line) for fitMatch in fit_iter: ship_type = int(fitMatch.group(1)) dna_fit = fitMatch.group(2) fit = Shipfit() fit.ship_type = ship_type fit.modules = dna_fit mod_list = parse_dna_fitting(dna_fit) for location_flag, mod_map in enumerate(mod_list): for mod_id in mod_map: mod = mod_map[mod_id] # lets check the value actually exists inv_type = db.session.query(InvType).get(mod[0]) if inv_type is None: raise ValueError('No module with ID=' + str(mod[0])) db_module = FitModule(moduleID=mod[0], amount=mod[1], locationFlag=location_flag) fit.moduleslist.append(db_module) fits.append(fit) fit_count = len(fits) logger.debug("Parsed %d fits", fit_count) if fit_count <= 0: flash( ngettext( "You submitted one fit to be check by a fleet comp before getting on the waitlist.", "You submitted %(num)d fits to be check by a fleet comp before getting on the waitlist.", fit_count), "danger") return redirect(url_for('index') + "?groupId=" + str(group_id)) for fit in fits: if fit.ship_type in resist_ships: if logilvl == 0: pass # TODO ask for caldari bs lvl if fit.comment is None: fit.comment = "<b>Cal BS: " + str(caldari_bs_lvl) + "</b>" else: fit.comment += " <b>Cal BS: " + str(caldari_bs_lvl) + "</b>" else: if fit.ship_type in logi_ships: if logilvl == 0: pass # TODO ask for logi if logilvl <= 3: comment_string = "<b class=\"bg-danger\">Logi: {0}</b>" else: comment_string = "<b>Logi: {0}</b>" if fit.comment is None: fit.comment = comment_string.format(logilvl) else: fit.comment += " " + comment_string.format(logilvl) # get current users id eve_id = current_user.get_eve_id() fits_ready = [] # split his fits into types for the different waitlist_entries for fit in fits: tag, waitlist_id = get_waitlist_type_for_fit(fit, group_id) fit.wl_type = tag fit.targetWaitlistID = waitlist_id fits_ready.append(fit) # get the waitlist entries of this user queue = group.xuplist wl_entry = db.session.query( WaitlistEntry).filter((WaitlistEntry.waitlist_id == queue.id) & (WaitlistEntry.user == eve_id)).first() if wl_entry is None: wl_entry = WaitlistEntry() wl_entry.creation = datetime.utcnow() wl_entry.user = eve_id queue.entries.append(wl_entry) _newEntryCreated = True logger.info("%s submitted %s fits to be checked by a fleetcomp", current_user.get_eve_name(), len(fits_ready)) for fit in fits_ready: logger.debug("%s submits %s", current_user.get_eve_name(), fit.get_dna()) wl_entry.fittings.append(fit) h_entry = create_history_object(current_user.get_eve_id(), HistoryEntry.EVENT_XUP, None, fits_ready) db.session.add(h_entry) db.session.commit() if _newEntryCreated: event = EntryAddedSSE(wl_entry, group_id, queue.id, True) send_server_sent_event(event) else: for fit in fits_ready: event = FitAddedSSE(group_id, queue.id, wl_entry.id, fit, True, wl_entry.user) send_server_sent_event(event) flash( ngettext( "You submitted one fit to be check by a fleet comp before getting on the waitlist.", "You submitted %(num)d fits to be check by a fleet comp before getting on the waitlist.", fit_count), "success") return redirect(url_for('index') + "?groupId=" + str(group_id))
def check_invite_and_remove_timer(char_id: int, group_id: int, fleet_id: int): try: logger.info( f"Check Invite and remove timer triggered for" f" char_id={char_id}, group_id={group_id} and fleet_id={fleet_id}") max_runs: int = 4 current_run: int = 1 timer_id = (char_id, group_id, fleet_id) if timer_id in check_timers: current_run = check_timers[timer_id] + 1 check_timers[timer_id] = current_run logger.info( f"New Timer count={check_timers[timer_id]} for timer_id={timer_id}" ) # hold SSE till sending _events = [] logger.info( "Checking invite for charID[%d] groupID[%d] fleetID[%d] current_run[%d]", char_id, group_id, fleet_id, current_run) group: WaitlistGroup = db.session.query(WaitlistGroup).get(group_id) crest_fleet = db.session.query(CrestFleet).get(fleet_id) # the fleet was deleted meanwhile or has no fleetcomp if group is None or crest_fleet is None or crest_fleet.comp is None: if group is None: logger.error("On Invitecheck group is None") if crest_fleet is None: logger.error("On Invitecheck crestFleet is None") elif crest_fleet.comp is None: logger.error("On Invitecheck FleetComp is None") db.session.remove() return member = member_info.get_fleet_members(fleet_id, crest_fleet.comp) character = db.session.query(Character).filter( Character.id == char_id).first() waitlist_entries = db.session.query(WaitlistEntry)\ .filter((WaitlistEntry.user == char_id) & (WaitlistEntry.waitlist_id != group.xuplist.id) ).all() if char_id in member: # he is in the fleet logger.info("Member %s found in members", char_id) fittings = [] for entry in waitlist_entries: fittings.extend(entry.fittings) for entry in waitlist_entries: event = EntryRemovedSSE(entry.waitlist.group.groupID, entry.waitlist_id, entry.id) _events.append(event) db.session.query(WaitlistEntry).filter( (WaitlistEntry.user == char_id) & (WaitlistEntry.waitlist_id != group.xuplist.id)).delete() h_entry = create_history_object(char_id, HistoryEntry.EVENT_AUTO_RM_PL, None, fittings) h_entry.exref = group.groupID db.session.add(h_entry) db.session.commit() for event in _events: send_server_sent_event(event) logger.info("auto removed %s from %s waitlist.", character.eve_name, group.groupName) # we are done delete timer entry check_timers.pop(timer_id, None) else: logger.info("Character %d %s not found in fleetmembers", char_id, character.eve_name) if current_run == max_runs: # he reached his invite timeout logger.info( "Max Runs reached and Member %s not found in members", str(char_id)) for entry in waitlist_entries: entry.inviteCount += 1 h_entry = create_history_object( char_id, HistoryEntry.EVENT_AUTO_CHECK_FAILED, None, None) h_entry.exref = group.groupID db.session.add(h_entry) db.session.commit() send_server_sent_event(InviteMissedSSE(group_id, char_id)) logger.info("%s missed his invite", character.eve_name) # we are done delete the timer entry check_timers.pop(timer_id, None) else: # we want to wait some more, set up new timer logger.info( 'charID[%d] groupID[%d] fleetID[%d] %s was not in fleet this time, checking again in 20s', char_id, group_id, fleet_id, character.eve_name) t = Timer(20.0, check_invite_and_remove_timer, [char_id, group_id, fleet_id]) t.start() db.session.remove() except Exception as e: logger.exception("Some thing went wrong during invite check!")
def move_to_waitlists(): """ Move a whole entry to a the corresponding waitlists """ # variables for SSE spawning _sseEvents = [] _createdEntriesList = [] entry_id = int(request.form['entryId']) fit_ids = request.form['fitIds'] fit_ids = [int(x) for x in fit_ids.split(",")] entry = db.session.query(WaitlistEntry).filter( WaitlistEntry.id == entry_id).first() if entry is None or entry.waitlist is None: flask.abort( 404, "This entry does not exist or not belong to a waitlist anymore!") group: WaitlistGroup = entry.waitlist.group if entry is None: return "OK" logger.info("%s approved %s", current_user.username, entry.user_data.get_eve_name()) # get waitlists in this group waitlist_ids = [] for wl in group.waitlists: waitlist_ids.append(wl.id) # get all entries that are in one of these waitlists and from the current user waitlist_entries = db.session.query(WaitlistEntry) \ .filter((WaitlistEntry.user == entry.user) & WaitlistEntry.waitlist_id.in_(waitlist_ids)).all() logi_entry = None sniper_entry = None dps_entry = None other_entry = None if len(waitlist_entries) > 0: # there are actually existing entries # if there are existing wl entries assign them to appropriate variables for wl in waitlist_entries: if wl.waitlist.name == WaitlistNames.logi: logi_entry = wl continue if wl.waitlist.name == WaitlistNames.dps: dps_entry = wl continue if wl.waitlist.name == WaitlistNames.sniper: sniper_entry = wl elif wl.waitlist.name == WaitlistNames.other: other_entry = wl # find out what timestamp a possibly new entry should have # rules are: if no wl entry, take timestamp of x-up # if there is a wl entry take the waitlist entry timestamp (a random one since they should all have the same) new_entry_timedate = entry.creation for entry_t in waitlist_entries: if entry_t.creation < new_entry_timedate: new_entry_timedate = entry_t.creation # sort fittings by ship type logi = [] dps = [] sniper = [] other = [] h_entry = create_history_object(entry.user, HistoryEntry.EVENT_COMP_MV_XUP_ETR, current_user.id) for fit in entry.fittings: if fit.id not in fit_ids: continue h_entry.fittings.append(fit) fits_to_remove = [] for fit in entry.fittings: if fit.id not in fit_ids: logger.info("Skipping %s because not in %s", fit, fit_ids) continue logger.info("Sorting fit %s by type into %s", str(fit), fit.wl_type) if fit.wl_type == WaitlistNames.logi: logi.append(fit) elif fit.wl_type == WaitlistNames.dps: dps.append(fit) elif fit.wl_type == WaitlistNames.sniper: sniper.append(fit) elif fit.wl_type == WaitlistNames.other: other.append(fit) else: logger.error("Failed to add %s do a waitlist.", fit) fits_to_remove.append(fit) for fit in fits_to_remove: event = FitRemovedSSE(entry.waitlist.group.groupID, entry.waitlist.id, entry.id, fit.id, entry.user) _sseEvents.append(event) entry.fittings.remove(fit) # we have a logi fit but no logi wl entry, so create one if len(logi) and logi_entry is None: logi_entry = WaitlistEntry() logi_entry.creation = new_entry_timedate # for sorting entries logi_entry.user = entry.user # associate a user with the entry group.logilist.entries.append(logi_entry) _createdEntriesList.append(logi_entry) # same for dps if len(dps) and dps_entry is None: dps_entry = WaitlistEntry() dps_entry.creation = new_entry_timedate # for sorting entries dps_entry.user = entry.user # associate a user with the entry group.dpslist.entries.append(dps_entry) _createdEntriesList.append(dps_entry) # and sniper if len(sniper) and sniper_entry is None: sniper_entry = WaitlistEntry() sniper_entry.creation = new_entry_timedate # for sorting entries sniper_entry.user = entry.user # associate a user with the entry group.sniperlist.entries.append(sniper_entry) _createdEntriesList.append(sniper_entry) # and other if other exists if len(other) and other_entry is None and group.otherlist is not None: other_entry = WaitlistEntry() other_entry.creation = new_entry_timedate # for sorting entries other_entry.user = entry.user # associate a user with the entry group.otherlist.entries.append(other_entry) _createdEntriesList.append(other_entry) # iterate over sorted fits and add them to their entry for logifit in logi: logi_entry.fittings.append(logifit) if logi_entry not in _createdEntriesList: for fit in logi: event = FitAddedSSE(group.groupID, logi_entry.waitlist_id, logi_entry.id, fit, False, logi_entry.user) _sseEvents.append(event) for dpsfit in dps: dps_entry.fittings.append(dpsfit) if dps_entry not in _createdEntriesList: for fit in dps: event = FitAddedSSE(group.groupID, dps_entry.waitlist_id, dps_entry.id, fit, False, dps_entry.user) _sseEvents.append(event) for sniperfit in sniper: sniper_entry.fittings.append(sniperfit) if sniper_entry not in _createdEntriesList: for fit in sniper: event = FitAddedSSE(group.groupID, sniper_entry.waitlist_id, sniper_entry.id, fit, False, sniper_entry.user) _sseEvents.append(event) # if there is no other list sort other fits in dps if group.otherlist is not None: for otherfit in other: other_entry.fittings.append(otherfit) if other_entry not in _createdEntriesList: for fit in other: event = FitAddedSSE(group.groupID, other_entry.waitlist_id, other_entry.id, fit, False, other_entry.user) _sseEvents.append(event) else: # it fits should go to dps wl make sure it is there if len(other) > 0 and dps_entry is None: dps_entry = WaitlistEntry() dps_entry.creation = new_entry_timedate # for sorting entries dps_entry.user = entry.user # associate a user with the entry group.dpslist.entries.append(dps_entry) _createdEntriesList.append(dps_entry) for otherfit in other: dps_entry.fittings.append(otherfit) if dps_entry not in _createdEntriesList: for fit in other: event = FitAddedSSE(group.groupID, dps_entry.waitlist_id, dps_entry.id, fit, False, dps_entry.user) _sseEvents.append(event) # add history entry to db db.session.add(h_entry) db.session.commit() if len(entry.fittings) <= 0: event = EntryRemovedSSE(entry.waitlist.group.groupID, entry.waitlist.id, entry.id) send_server_sent_event(event) db.session.delete(entry) db.session.commit() else: for fitEvent in _sseEvents: if isinstance(fitEvent, FitRemovedSSE): send_server_sent_event(fitEvent) for fitAddedEvent in _sseEvents: if isinstance(fitAddedEvent, FitAddedSSE): send_server_sent_event(fitAddedEvent) for createdEntry in _createdEntriesList: event = EntryAddedSSE(createdEntry, group.groupID, createdEntry.waitlist_id, False) send_server_sent_event(event) return "OK"
def api_move_fit_to_waitlist(): fit_id = int(request.form['fit_id']) fit = db.session.query(Shipfit).filter(Shipfit.id == fit_id).first() # fit doesn't exist or is not in a waitlist, probably double trigger when moving some one if fit is None or fit.waitlist is None: return "OK" entry = db.session.query(WaitlistEntry).filter( WaitlistEntry.id == fit.waitlist.id).first() group: WaitlistGroup = entry.waitlist.group logger.info("%s approved fit %s from %s", current_user.username, fit, entry.user_data.get_eve_name()) # get the entry for the wl we need waitlist = None if fit.wl_type == WaitlistNames.logi: waitlist = group.logilist elif fit.wl_type == WaitlistNames.dps: waitlist = group.dpslist elif fit.wl_type == WaitlistNames.sniper: waitlist = group.sniperlist elif fit.wl_type == WaitlistNames.other: if group.otherlist is not None: waitlist = group.otherlist else: waitlist = group.dpslist waitlist_ids: List[int] = [] for wl in group.waitlists: waitlist_ids.append(wl.id) waitlist_entries = db.session.query(WaitlistEntry) \ .filter((WaitlistEntry.user == entry.user) & WaitlistEntry.waitlist_id.in_(waitlist_ids)).all() creation_time = entry.creation for centry in waitlist_entries: if centry.creation < creation_time: creation_time = centry.creation wl_entry = db.session.query(WaitlistEntry).join(Waitlist) \ .filter((WaitlistEntry.user == entry.user) & (Waitlist.id == waitlist.id)).first() new_entry = False # if it doesn't exist create it if wl_entry is None: wl_entry = WaitlistEntry() wl_entry.creation = creation_time wl_entry.user = entry.user new_entry = True # remove fit from old entry event = FitRemovedSSE(entry.waitlist.group.groupID, entry.waitlist_id, entry.id, fit.id, entry.user) entry.fittings.remove(fit) send_server_sent_event(event) # add the fit to the entry wl_entry.fittings.append(fit) if not new_entry: event = FitAddedSSE(wl_entry.waitlist.group.groupID, wl_entry.waitlist_id, wl_entry.id, fit, False, wl_entry.user) send_server_sent_event(event) # add a history entry h_entry = create_history_object(entry.user, HistoryEntry.EVENT_COMP_MV_XUP_FIT, current_user.id, [fit]) db.session.add(h_entry) if new_entry: waitlist.entries.append(wl_entry) db.session.commit() if len(entry.fittings) == 0: event = EntryRemovedSSE(entry.waitlist.group.groupID, entry.waitlist_id, entry.id) db.session.delete(entry) db.session.commit() send_server_sent_event(event) if new_entry: event = EntryAddedSSE(wl_entry, wl_entry.waitlist.group.groupID, wl_entry.waitlist_id, False) send_server_sent_event(event) return "OK"
def submit(): """ Parse the submited fitts Check which fits need additional Info Rattlesnake, Rokh, that other ugly thing Caldari BS lvl Basilisk, Scimitar Logi Lvl -> put info into comment of the fit """ # used for spawning the right SSEs _newEntryCreated = False _newFits = [] fittings = request.form['fits'] logger.info("%s submitted %s", current_user.get_eve_name(), fittings) group_id = int(request.form['groupID']) logger.info("%s submitted for group %s", current_user.get_eve_name(), group_id) eve_id = current_user.get_eve_id() group = db.session.query(WaitlistGroup).filter( WaitlistGroup.groupID == group_id).one() if not group.enabled: # xups are disabled atm flash("X-UP is disabled!!!") return redirect(url_for("index")) poke_me = 'pokeMe' in request.form if current_user.poke_me != poke_me: current_user.poke_me = poke_me db.session.commit() # check if it is scruffy if fittings.lower().startswith("scruffy"): # scruffy mode scruffy fittings = fittings.lower() _, _, ship_type = fittings.rpartition(" ") ship_types = [] # check for , to see if it is a multi value shiptype if "," in ship_type: for stype in ship_type.split(","): stype = stype.strip() if stype == WaitlistNames.logi or stype == WaitlistNames.dps or stype == WaitlistNames.sniper: ship_types.append(stype) else: if ship_type == WaitlistNames.logi or ship_type == WaitlistNames.dps or ship_type == WaitlistNames.sniper: ship_types.append(ship_type) # check if shiptype is valid if len(ship_types) <= 0: flash("Valid entries are scruffy [dps|logi|sniper,..]") return redirect(url_for('index')) queue = group.xuplist wl_entry = db.session.query( WaitlistEntry).filter((WaitlistEntry.waitlist_id == queue.id) & (WaitlistEntry.user == eve_id)).first() if wl_entry is None: wl_entry = WaitlistEntry() wl_entry.creation = datetime.utcnow() wl_entry.user = eve_id queue.entries.append(wl_entry) _newEntryCreated = True h_entry = create_history_object(current_user.get_eve_id(), "xup") for stype in ship_types: fit = Shipfit() fit.ship_type = 1 # #System >.> fit.wl_type = stype fit.modules = ':' wl_entry.fittings.append(fit) if not _newEntryCreated: _newFits.append(fit) h_entry.fittings.append(fit) db.session.add(h_entry) db.session.commit() if _newEntryCreated: event = EntryAddedSSE(wl_entry, group_id, queue.id, True) send_server_sent_event(event) else: for fit in _newFits: event = FitAddedSSE(group_id, queue.id, wl_entry.id, fit, True, wl_entry.user) send_server_sent_event(event) flash("You were added as " + ship_type, "success") return redirect(url_for('index') + "?groupId=" + str(group_id)) # ### END SCRUFFY CODE logilvl = request.form['logi'] if logilvl == "": logilvl = "0" caldari_bs_lvl = request.form['cbs'] if caldari_bs_lvl == "": caldari_bs_lvl = "0" logilvl = int(logilvl) caldari_bs_lvl = int(caldari_bs_lvl) newbro = request.form.get('newbro', "off") newbro = (newbro is not "off") get_character(current_user).newbro = newbro current_user.cbs_level = caldari_bs_lvl current_user.lc_level = logilvl logger.debug("Fittings to parse: %s", fittings) # lets normalize linebreaks fittings = fittings.replace("[\n\r]+", "\n") fittings = fittings.strip() # lets first find out what kind of fitting is used end_line_idx = fittings.find('\n') + 1 first_line = fittings[:end_line_idx] format_type = get_fit_format(first_line) fits = [] if format_type == "eft": # split fittings up in its fittings string_fits = [] fit_iter = re.finditer("\[.*,.*\]", fittings) s_idx = 0 first_iter = True for fitMatch in fit_iter: if not first_iter: e_idx = fitMatch.start() - 1 string_fits.append(fittings[s_idx:e_idx].split('\n')) else: first_iter = False s_idx = fitMatch.start() string_fits.append(fittings[s_idx:].split('\n')) logger.debug("Split fittings into %d fits", len(string_fits)) for fit in string_fits: try: dbfit = parse_eft(fit) fits.append(dbfit) except ValueError: flask.abort(400, message="Invalid module amounts") else: # parse chat links lines = fittings.split('\n') for line in lines: fit_iter = re.finditer("<url=fitting:(\d+):((?:\d+;\d+:)+:)>", line) for fitMatch in fit_iter: ship_type = int(fitMatch.group(1)) dna_fit = fitMatch.group(2) fit = Shipfit() fit.ship_type = ship_type fit.modules = dna_fit mod_map = create_mod_map(dna_fit) for modid in mod_map: mod = mod_map[modid] # lets check the value actually exists inv_type = db.session.query(InvType).get(mod[0]) if inv_type is None: raise ValueError('No module with ID=' + str(mod[0])) db_module = FitModule(moduleID=mod[0], amount=mod[1]) fit.moduleslist.append(db_module) fits.append(fit) fit_count = len(fits) logger.debug("Parsed %d fits", fit_count) if fit_count <= 0: flash( "You submitted {0} fits to be check by a fleet comp before getting on the waitlist." .format(fit_count), "danger") return redirect(url_for('index') + "?groupId=" + str(group_id)) for fit in fits: if fit.ship_type in resist_ships: if logilvl == 0: pass # TODO ask for caldari bs lvl if fit.comment is None: fit.comment = "<b>Cal BS: " + str(caldari_bs_lvl) + "</b>" else: fit.comment += " <b>Cal BS: " + str(caldari_bs_lvl) + "</b>" else: if fit.ship_type in logi_ships: if logilvl == 0: pass # TODO ask for logi if logilvl <= 3: comment_string = "<b class=\"bg-danger\">Logi: {0}</b>" else: comment_string = "<b>Logi: {0}</b>" if fit.comment is None: fit.comment = comment_string.format(logilvl) else: fit.comment += " " + comment_string.format(logilvl) # get current users id eve_id = current_user.get_eve_id() # query to check if sth is a weapon module ''' SELECT count(1) FROM invtypes JOIN invmarketgroups AS weapongroup ON invtypes.marketGroupID = weapongroup.marketGroupID JOIN invmarketgroups AS wcat ON weapongroup.parentGroupID = wcat.marketGroupID JOIN invmarketgroups AS mcat ON wcat.parentGroupID = mcat.marketGroupID WHERE invtypes.typeName = ? AND mcat.parentGroupID = 10;/*10 == Turrets & Bays*/ ''' fits_ready = [] # split his fits into types for the different waitlist_entries for fit in fits: try: mod_map = create_mod_map(fit.modules) except ValueError: flask.abort(400, message="Invalid module amounts") # check that ship is an allowed ship # it is a logi put on logi wl if fit.ship_type in logi_ships: fit.wl_type = WaitlistNames.logi fits_ready.append(fit) continue is_allowed = False if fit.ship_type in sniper_ships or fit.ship_type in dps_ships or fit.ship_type in t3c_ships: is_allowed = True if not is_allowed: # not an allowed ship, push it on other list :P fit.wl_type = WaitlistNames.other fits_ready.append(fit) continue # filter out mods that don't exist at least 4 times # this way we avoid checking everything or choosing the wrong weapon on ships that have 7turrents + 1launcher possible_weapons = [] for mod in mod_map: if mod_map[mod][1] >= 4: possible_weapons.append(mod) weapon_type = "None" for weapon in possible_weapons: if weapon in sniper_weapons: weapon_type = WaitlistNames.sniper break if weapon in dps_weapons: weapon_type = WaitlistNames.dps break if weapon_type == "None": # try to decide by market group for weapon in possible_weapons: weapon_db = db.session.query(InvType).filter( InvType.typeID == weapon).first() if weapon_db is None: continue market_group = db.session.query(MarketGroup).filter( MarketGroup.marketGroupID == weapon_db.marketGroupID).first() if market_group is None: continue parent_group = db.session.query(MarketGroup).filter( MarketGroup.marketGroupID == market_group.parentGroupID).first() if parent_group is None: continue # we have a parent market group if parent_group.marketGroupName in weapongroups['dps']: weapon_type = WaitlistNames.dps break if parent_group.marketGroupName in weapongroups['sniper']: weapon_type = WaitlistNames.sniper break # ships with no valid weapons put on other wl if weapon_type == "None": fit.wl_type = WaitlistNames.other fits_ready.append(fit) continue # ships with sniper weapons put on sniper wl if weapon_type == WaitlistNames.sniper: fit.wl_type = WaitlistNames.sniper fits_ready.append(fit) continue if weapon_type == WaitlistNames.dps: fit.wl_type = WaitlistNames.dps fits_ready.append(fit) continue """ #this stuff is needed somewhere else now # get the waitlist entries of this user """ queue = group.xuplist wl_entry = db.session.query( WaitlistEntry).filter((WaitlistEntry.waitlist_id == queue.id) & (WaitlistEntry.user == eve_id)).first() if wl_entry is None: wl_entry = WaitlistEntry() wl_entry.creation = datetime.utcnow() wl_entry.user = eve_id queue.entries.append(wl_entry) _newEntryCreated = True logger.info("%s submitted %s fits to be checked by a fleetcomp", current_user.get_eve_name(), len(fits_ready)) for fit in fits_ready: logger.info("%s submits %s", current_user.get_eve_name(), fit.get_dna()) wl_entry.fittings.append(fit) h_entry = create_history_object(current_user.get_eve_id(), HistoryEntry.EVENT_XUP, None, fits_ready) db.session.add(h_entry) db.session.commit() if _newEntryCreated: event = EntryAddedSSE(wl_entry, group_id, queue.id, True) send_server_sent_event(event) else: for fit in fits_ready: event = FitAddedSSE(group_id, queue.id, wl_entry.id, fit, True, wl_entry.user) send_server_sent_event(event) flash( "You submitted {0} fits to be check by a fleet comp before getting on the waitlist." .format(fit_count), "success") return redirect(url_for('index') + "?groupId=" + str(group_id))
def move_to_waitlists(): """ Move a whole entry to the corresponding waitlists """ # variables for SSE spawning _sseEvents = [] _createdEntriesList = [] entry_id = int(request.form['entryId']) fit_ids = request.form['fitIds'] fit_ids = [int(x) for x in fit_ids.split(",")] entry = db.session.query(WaitlistEntry).filter( WaitlistEntry.id == entry_id).first() if entry is None or entry.waitlist is None: flask.abort( 404, "This entry does not exist or not belong to a waitlist anymore!") group: WaitlistGroup = entry.waitlist.group if entry is None: return "OK" logger.info("%s approved %s", current_user.username, entry.user_data.get_eve_name()) # get waitlists in this group waitlist_ids = [] for wl in group.waitlists: waitlist_ids.append(wl.id) # get all entries that are in one of these waitlists and from the current user waitlist_entries = db.session.query(WaitlistEntry) \ .filter((WaitlistEntry.user == entry.user) & WaitlistEntry.waitlist_id.in_(waitlist_ids)).all() # find out what timestamp a possibly new entry should have # rules are: if no wl entry, take timestamp of x-up # if there is a wl entry take the waitlist entry timestamp (a random one since they should all have the same) new_entry_timedate = entry.creation for entry_t in waitlist_entries: if entry_t.creation < new_entry_timedate: new_entry_timedate = entry_t.creation h_entry = create_history_object(entry.user, HistoryEntry.EVENT_COMP_MV_XUP_ETR, current_user.id) for fit in entry.fittings: if fit.id not in fit_ids: continue h_entry.fittings.append(fit) fit_list = [fit for fit in entry.fittings] for fit in fit_list: event = FitRemovedSSE(entry.waitlist.group.groupID, entry.waitlist.id, entry.id, fit.id, entry.user) _sseEvents.append(event) entry.fittings.remove(fit) is_new, new_entry = get_waitlist_entry_for_list( fit.targetWaitlistID, new_entry_timedate, waitlist_entries, entry.user) new_entry.fittings.append(fit) # fits in a created entry will be sent out later a whole entry if is_new: _createdEntriesList.append(new_entry) else: event = FitAddedSSE(group.groupID, new_entry.waitlist_id, new_entry.id, fit, False, new_entry.user) _sseEvents.append(event) # add history entry to db db.session.add(h_entry) db.session.commit() if len(entry.fittings) <= 0: event = EntryRemovedSSE(entry.waitlist.group.groupID, entry.waitlist.id, entry.id) send_server_sent_event(event) db.session.delete(entry) db.session.commit() else: for fitEvent in _sseEvents: if isinstance(fitEvent, FitRemovedSSE): send_server_sent_event(fitEvent) for fitAddedEvent in _sseEvents: if isinstance(fitAddedEvent, FitAddedSSE): send_server_sent_event(fitAddedEvent) for createdEntry in _createdEntriesList: event = EntryAddedSSE(createdEntry, group.groupID, createdEntry.waitlist_id, False) send_server_sent_event(event) return "OK"
def api_move_fit_to_waitlist(): fit_id = int(request.form['fit_id']) fit = db.session.query(Shipfit).filter(Shipfit.id == fit_id).first() # fit doesn't exist or is not in a waitlist, probably double trigger when moving some one if fit is None or fit.waitlist is None: flask.abort( 404, "This fit does not exist or not belong to a waitlist anymore!") entry = db.session.query(WaitlistEntry).filter( WaitlistEntry.id == fit.waitlist.id).first() group: WaitlistGroup = entry.waitlist.group logger.info("%s approved fit %s from %s", current_user.username, fit, entry.user_data.get_eve_name()) waitlist = fit.targetWaitlist waitlist_ids: List[int] = [] for wl in group.waitlists: waitlist_ids.append(wl.id) waitlist_entries = db.session.query(WaitlistEntry) \ .filter((WaitlistEntry.user == entry.user) & WaitlistEntry.waitlist_id.in_(waitlist_ids)).all() creation_time = entry.creation for centry in waitlist_entries: if centry.creation < creation_time: creation_time = centry.creation wl_entry = db.session.query(WaitlistEntry).join(Waitlist) \ .filter((WaitlistEntry.user == entry.user) & (Waitlist.id == waitlist.id)).first() # is already on target if fit.waitlist is not None and wl_entry is not None and fit.waitlist.id == wl_entry.id: flask.abort(409, 'This fit was already moved') is_entry_new, wl_entry = get_waitlist_entry_for_list( fit.targetWaitlistID, creation_time, [wl_entry] if wl_entry is not None else [], entry.user) # remove fit from old entry event = FitRemovedSSE(entry.waitlist.group.groupID, entry.waitlist_id, entry.id, fit.id, entry.user) entry.fittings.remove(fit) send_server_sent_event(event) # add the fit to the entry wl_entry.fittings.append(fit) if not is_entry_new: event = FitAddedSSE(wl_entry.waitlist.group.groupID, wl_entry.waitlist_id, wl_entry.id, fit, False, wl_entry.user) send_server_sent_event(event) # add a history entry h_entry = create_history_object(entry.user, HistoryEntry.EVENT_COMP_MV_XUP_FIT, current_user.id, [fit]) db.session.add(h_entry) if is_entry_new: waitlist.entries.append(wl_entry) db.session.commit() if len(entry.fittings) == 0: event = EntryRemovedSSE(entry.waitlist.group.groupID, entry.waitlist_id, entry.id) db.session.delete(entry) db.session.commit() send_server_sent_event(event) if is_entry_new: event = EntryAddedSSE(wl_entry, wl_entry.waitlist.group.groupID, wl_entry.waitlist_id, False) send_server_sent_event(event) return "OK"