def add_token(code): """ Adds a token to the current Account using the given SSO code :param code: SSO auth code to use to get token info """ tokens = authorize(code) re_token = tokens['refresh_token'] acc_token = tokens['access_token'] exp_in = int(tokens['expires_in']) token: SSOToken = SSOToken( refresh_token=re_token, access_token=acc_token, accountID=current_user.id, access_token_expires=(datetime.utcnow() + timedelta(seconds=exp_in))) auth_info = who_am_i(token) char_name = auth_info['CharacterName'] char_id = auth_info['CharacterID'] if char_name != current_user.get_eve_name(): flask.abort( 409, 'You did not grant authorization for the right character "' + current_user.get_eve_name() + '". Instead you granted it for "' + char_name + '"') scopenames = auth_info['Scopes'].split(' ') token.characterID = char_id for scope_name in scopenames: token.scopes.append(EveApiScope(scopeName=scope_name)) current_user.add_sso_token(token) db.session.commit()
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 bans_change_single(): action = request.form['change'] # ban, unban target = request.form['target'] # name of target target = target.strip() ban_admin = current_user.get_eve_name() ban_name = target if action == "ban": reason = request.form['reason'] # reason for ban ban_char = get_character_by_name(ban_name) admin_char = get_character_by_name(ban_admin) logger.info("Banning %s for %s as %s.", ban_name, reason, current_user.username) if ban_char is None: logger.error("Did not find ban target %s", ban_name) flash("Could not find Character " + ban_name, "danger") return eve_id = ban_char.get_eve_id() admin_id = admin_char.get_eve_id() if eve_id is None or admin_id is None: logger.error("Failed to correctly parse: %", target) flash("Failed to correctly parse " + target, "danger") return # check if ban already there if db.session.query(Ban).filter(Ban.id == eve_id).count() == 0: # ban him new_ban = Ban() new_ban.id = eve_id new_ban.name = ban_name new_ban.reason = reason new_ban.admin = admin_id db.session.add(new_ban) db.session.commit() elif action == "unban": logger.info("%s is unbanning %s", current_user.username, target) eve_id = outgate.character.get_char_corp_all_id_by_name(target) if eve_id is None: flash("Character/Corp/Alliance " + target + " does not exist!") else: # check that there is a ban if db.session.query(Ban).filter(Ban.id == eve_id).count() > 0: db.session.query(Ban).filter(Ban.id == eve_id).delete() db.session.commit() return redirect(url_for(".bans"))
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 whitelist_by_name(whitelist_info, reason=""): target = whitelist_info.strip() wl_name, wl_reason, wl_admin = get_info_from_ban(target) if wl_reason is None or not perm_custom_reason.can(): wl_reason = reason if wl_admin is None or not perm_custom_name.can(): wl_admin = current_user.get_eve_name() logger.info("Whitelisting %s for %s by %s as %s.", wl_name, wl_reason, wl_admin, current_user.username) eve_id, ban_type = outgate.character.get_char_corp_all_id_by_name(wl_name) admin_char = get_character_by_name(wl_admin) if eve_id is None: logger.error("Did not find whitelist target %s", wl_name) flash( gettext("Could not find Character %(wl_name)s for whitelisting", wl_name=wl_name), "danger") return admin_id = admin_char.get_eve_id() if eve_id is None or admin_id is None: logger.error("Failed to correctly parse: %", target) flash(gettext("Failed to correctly parse %(target)s", target=target), "danger") return target_name = get_char_corp_all_name_by_id_and_type( eve_id, CharacterTypes[ban_type]) # check if ban already there if db.session.query(Whitelist).filter( Whitelist.characterID == eve_id).count() == 0: # ban him new_whitelist = Whitelist() new_whitelist.characterID = eve_id new_whitelist.reason = wl_reason new_whitelist.admin = admin_char new_whitelist.targetType = CharacterTypes[ban_type] new_whitelist.name = target_name db.session.add(new_whitelist) db.session.commit()
def submit(): current_time = datetime.utcnow() if current_time < startTime or current_time > endTime: flask.abort(404, "Voting period is from %s to %s and is over or did not start yet" % (startTime, endTime)) if current_user.type != "character": flask.abort(403, "For voting you need to be on a normal linemember login," + " please log out and use the linemember auth.") fc_vote = int(request.form.get('fc-vote')) lm_vote = int(request.form.get('lm-vote')) if has_voted_today(current_user.get_eve_id()): flask.abort(500, "You already voted today!") if (not is_fc(fc_vote)) or (not is_lm(lm_vote)): flask.abort("Either the FC you voted for is not an FC or the LM you voted for is not an LM!") logger.info("%s is voting for fc=%d and lm=%d", current_user.get_eve_name(), fc_vote, lm_vote) if fc_vote == -1: fc_vote = None if lm_vote == -1: lm_vote = None add_vote(current_user.get_eve_id(), fc_vote, lm_vote) flask.flash("Thank you for voting, you can vote again after the next eve downtime!", "success") return redirect(url_for('index'))
def whitelist_by_name(whitelist_info, reason=""): target = whitelist_info.strip() wl_name, wl_reason, wl_admin = get_info_from_ban(target) if wl_reason is None or not perm_custom_reason.can(): wl_reason = reason if wl_admin is None or not perm_custom_name.can(): wl_admin = current_user.get_eve_name() logger.info("Whitelisting %s for %s by %s as %s.", wl_name, wl_reason, wl_admin, current_user.username) wl_char = get_character_by_name(wl_name) admin_char = get_character_by_name(wl_admin) if wl_char is None: logger.error("Did not find whitelist target %s", wl_name) flash("Could not find Character " + wl_name + " for whitelisting", "danger") return eve_id = wl_char.get_eve_id() admin_id = admin_char.get_eve_id() if eve_id is None or admin_id is None: logger.error("Failed to correctly parse: %", target) flash("Failed to correctly parse " + target, "danger") return # check if ban already there if db.session.query(Whitelist).filter(Whitelist.characterID == eve_id).count() == 0: # ban him new_whitelist = Whitelist() new_whitelist.character = wl_char new_whitelist.reason = wl_reason new_whitelist.admin = admin_char db.session.add(new_whitelist) db.session.commit()
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 account_self_edit(): acc_id = current_user.id char_name = request.form['default_char_name'] char_name = char_name.strip() if char_name == "": char_name = None acc: Account = db.session.query(Account).filter( Account.id == acc_id).first() if acc is None: return flask.abort(400) if char_name is not None and (current_user.get_eve_name() is None or char_name != current_user.get_eve_name()): try: char_info = outgate.character.get_info_by_name(char_name) if char_info is None: flash( gettext( "Character with name %(char_name)s could not be found!", char_name=char_name), 'danger') else: char_id = char_info.id # find out if there is a character like that in the database # or create one character = get_character_by_id(char_id) # check if character is linked to this account link = db.session.query(linked_chars) \ .filter( (linked_chars.c.id == acc_id) & ( linked_chars.c.char_id == char_id)).first() if link is None: if config.require_auth_for_chars: # this is a new link, lets redirect him # to check if he owns the character # after we saved the charid session['link_charid'] = character.id return get_sso_redirect("alt_verification", 'publicData') else: acc.characters.append(character) send_alt_link_added(account_self_edit, current_user.id, acc.id, character.id) db.session.flush() if acc.current_char != char_id: # we have a link and it is not the current char if config.require_auth_for_chars: # we need authentication for char change # so lets see if the token works auth_token: SSOToken = acc.get_a_sso_token_with_scopes( [], char_id) # we need new auth if auth_token is None: logger.debug( "Could not find a valid authorization for this character" ) session['link_charid'] = character.id return get_sso_redirect("alt_verification", 'publicData') try: auth_info = who_am_i(auth_token) except APIException: flash( gettext( 'Failed to get info for this character because of sso error' )) redirect(url_for('.account_self'), code=303) # if we don't have this the token was invalid if 'CharacterOwnerHash' not in auth_info: logger.debug( "CharacterOwnerHash was not in authorization info" ) db.session.delete(auth_token) db.session.commit() # let them re authenticate session['link_charid'] = character.id return get_sso_redirect("alt_verification", 'publicData') if auth_info[ 'CharacterOwnerHash'] != character.owner_hash: # owner hash does not match db.session.delete(auth_token) db.session.commit() session['link_charid'] = character.id logger.debug( "Character owner_owner hash did not match") return get_sso_redirect("alt_verification", 'publicData') acc.current_char = char_id except ApiException as e: flash( gettext("Could not execute action, ApiException %(ex)s", ex=e), 'danger') db.session.commit() return redirect(url_for('.account_self'), 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 bans_change(): action = request.form['change'] # ban, unban target = request.form['target'] # name of target reason = '' if action == "ban": reason = request.form['reason'] # reason for ban targets = target.split("\n") try: # pre-cache names for a faster api to not hit request limit names_to_cache = [] for line in targets: line = line.strip() ban_name, _, ban_admin = get_info_from_ban(line) names_to_cache.append(ban_name) if ban_admin is not None: names_to_cache.append(ban_admin) if action == "ban": for target in targets: target = target.strip() ban_name, ban_reason, ban_admin = get_info_from_ban(target) if ban_reason is None: ban_reason = reason if ban_admin is None: ban_admin = current_user.get_eve_name() logger.info("Banning %s for %s by %s as %s.", ban_name, ban_reason, ban_admin, current_user.username) ban_id, ban_type = outgate.character.get_char_corp_all_id_by_name( ban_name) admin_char = get_character_by_name(ban_admin) if ban_id is None: logger.error("Did not find ban target %s", ban_name) flash( gettext("Could not find Character %(ban_name)s", ban_name=ban_name), "danger") continue ban_name = get_char_corp_all_name_by_id_and_type( ban_id, CharacterTypes[ban_type]) admin_id = admin_char.get_eve_id() if ban_id is None or admin_id is None: logger.error("Failed to correctly parse: %", target) flash( gettext("Failed to correctly parse %(target)s", target=target), "danger") continue # check if ban already there if db.session.query(Ban).filter(Ban.id == ban_id).count() == 0: # ban him new_ban = Ban() new_ban.id = ban_id new_ban.reason = ban_reason new_ban.admin = admin_id new_ban.targetType = CharacterTypes[ban_type] new_ban.name = ban_name db.session.add(new_ban) db.session.commit() except ApiException as e: flash(gettext("Could not execute action, ApiException %(ex)s", ex=e), 'danger') return redirect(url_for(".bans"))
def bans_change_single(): try: action = request.form['change'] # ban, unban target = request.form['target'] # name of target target = target.strip() ban_admin = current_user.get_eve_name() if action == "ban": reason = request.form['reason'] # reason for ban ban_id, ban_type = outgate.character.get_char_corp_all_id_by_name( target) admin_char = get_character_by_name(ban_admin) logger.info("Banning %s for %s as %s.", ban_name, reason, current_user.username) if ban_id is None: logger.error("Did not find ban target %s", ban_name) flash( gettext("Could not find Character %(name)s", name=target), "danger") return admin_id = admin_char.get_eve_id() if ban_id is None or admin_id is None: logger.error("Failed to correctly parse: %", target) flash( gettext("Failed to correctly parse %(target)s", target=target), "danger") return ban_name = get_char_corp_all_name_by_id_and_type( ban_id, CharacterTypes[ban_type]) # check if ban already there if db.session.query(Ban).filter(Ban.id == eve_id).count() == 0: # ban him new_ban = Ban() new_ban.id = ban_id new_ban.reason = reason new_ban.admin = admin_id new_ban.targetType = CharacterTypes[ban_type] new_ban.name = ban_name db.session.add(new_ban) db.session.commit() elif action == "unban": ban_id = int(target) logger.info("%s is unbanning %s", current_user.username, target) if eve_id is None: flash( gettext( "Character/Corp/Alliance %(target)s does not exist!", target=target), 'danger') else: # check that there is a ban if db.session.query(Ban).filter(Ban.id == ban_id).count() > 0: db.session.query(Ban).filter(Ban.id == ban_id).delete() db.session.commit() except ApiException as e: flash(gettext("Could not execute action, ApiException %(ex)s", ex=e), 'danger') return redirect(url_for(".bans"))
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 test_poke(): send_poke(current_user.get_eve_name(), "Test Poke") resp = jsonify(status_code=201, message="Poke was send!") resp.status_code = 201 return resp
def bans_change(): action = request.form['change'] # ban, unban target = request.form['target'] # name of target reason = '' if action == "ban": reason = request.form['reason'] # reason for ban targets = target.split("\n") # pre-cache names for a faster api to not hit request limit names_to_cache = [] for line in targets: line = line.strip() ban_name, _, ban_admin = get_info_from_ban(line) names_to_cache.append(ban_name) if ban_admin is not None: names_to_cache.append(ban_admin) if action == "ban": for target in targets: target = target.strip() ban_name, ban_reason, ban_admin = get_info_from_ban(target) if ban_reason is None: ban_reason = reason if ban_admin is None: ban_admin = current_user.get_eve_name() logger.info("Banning %s for %s by %s as %s.", ban_name, ban_reason, ban_admin, current_user.username) ban_id = outgate.character.get_char_corp_all_id_by_name(ban_name) admin_char = get_character_by_name(ban_admin) if ban_id is None: logger.error("Did not find ban target %s", ban_name) flash("Could not find Character " + ban_name, "danger") continue admin_id = admin_char.get_eve_id() if ban_id is None or admin_id is None: logger.error("Failed to correctly parse: %", target) flash("Failed to correctly parse " + target, "danger") continue # check if ban already there if db.session.query(Ban).filter(Ban.id == ban_id).count() == 0: # ban him new_ban = Ban() new_ban.id = ban_id new_ban.name = ban_name new_ban.reason = ban_reason new_ban.admin = admin_id db.session.add(new_ban) db.session.commit() elif action == "unban": for target in targets: target = target.strip() logger.info("%s is unbanning %s", current_user.username, target) eve_id = outgate.character.get_char_corp_all_id_by_name(target) if eve_id is None: flash("Character/Corp/Alliance " + target + " does not exist!") else: # check that there is a ban if db.session.query(Ban).filter(Ban.id == eve_id).count() > 0: db.session.query(Ban).filter(Ban.id == eve_id).delete() db.session.commit() return redirect(url_for(".bans"))