示例#1
0
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"
示例#2
0
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"
示例#3
0
def send_esi_mail():
    """
    Sends mails to characters.
    mailRecipients => JSON String recipients=[{"recipient_id": 0, "recipient_type": "character|alliance"}]
    mailBody => String
    mailSubject => String
    """

    token: SSOToken = current_user.get_a_sso_token_with_scopes(
        esi_scopes.mail_scopes)

    if token is None:
        return flask.abort(412, 'Not Authenticated for esi-mail.send_mail.v1')

    body = request.form.get('mailBody')
    subject = request.form.get('mailSubject')
    recipients = json.loads(request.form.get('mailRecipients'))
    target_chars = []
    for rec in recipients:
        if rec['recipient_type'] == 'character':
            target_chars.append(rec['recipient_id'])
    target_accs = db.session.query(Account).filter(
        or_(Account.current_char == charid for charid in target_chars)).all()

    resp = send_mail(token, recipients, body, subject)
    if resp.status == 201:
        history_entry: AccountNote = AccountNote(
            accountID=current_user.id,
            byAccountID=current_user.id,
            type=account_notes.TYPE_SENT_ACCOUNT_MAIL)
        history_entry.jsonPayload = {
            'sender_character_id': current_user.get_eve_id(),
            'recipients': recipients,
            'body': body,
            'subject': subject
        }
        db.session.add(history_entry)
        for acc in target_accs:
            acc.had_welcome_mail = True
            history_entry = AccountNote(
                accountID=acc.id,
                byAccountID=current_user.id,
                type=account_notes.TYPE_GOT_ACCOUNT_MAIL)
            history_entry.jsonPayload = {
                'sender_character_id': current_user.get_eve_id(),
                'target_character_id': acc.current_char,
                'mail_body': body,
                'subject': subject
            }
            db.session.add(history_entry)
        db.session.commit()
    else:
        esi_resp: ESIResponse = make_error_response(resp)
        if esi_resp.is_monolith_error():
            return make_response(esi_resp.get_monolith_error()['error_label'],
                                 resp.status)

    return make_response(
        str(resp.data) if resp.data is not None else '', resp.status)
def process_submission(trivia_id: int) -> Optional[Response]:
    # we are going to hard restrict submissions to
    # one per account and character
    trivia = db.session.query(Trivia).get(trivia_id)
    if trivia is None:
        flask.abort(404, 'This trivia does not exist')
    timenow = datetime.utcnow()
    if trivia.toTime < timenow:
        flask.abort(
            410,
            f'This trivia is over, it ended at {trivia.toTime} and it is {timenow}'
        )
    if trivia.fromTime > timenow:
        flask.abort(
            428,
            f'This trivia did not start yet, it starts at {trivia.fromTime} and it is {timenow}'
        )

    # lets see if we find a submisson by this character or account
    if current_user.type == "account":
        filter_criteria = (
            (TriviaSubmission.submittorAccountID == current_user.id)
            | (TriviaSubmission.submittorID == current_user.get_eve_id()))
    else:
        filter_criteria = (
            TriviaSubmission.submittorID == current_user.get_eve_id())

    filter_criteria &= (TriviaSubmission.triviaID == trivia_id)

    existing_submission = db.session.query(TriviaSubmission).filter(
        filter_criteria).first()

    if existing_submission is not None:
        flask.abort(409, 'You already submitted answers for this trivia.')

    submission = TriviaSubmission(triviaID=trivia_id)
    submission.submittorID = current_user.get_eve_id()

    if current_user.type == "account":
        submission.submittorAccountID = current_user.id

    for name in request.form:
        if name.startswith(QUESTION_PREFIX):
            try:
                add_answer_to_database(submission,
                                       get_question_id_from_name(name),
                                       request.form[name])
            except ValueError:
                logger.exception('Add Answer for a question to database')
                flask.abort(400, 'Invalid Request sent')

    db.session.add(submission)
    db.session.commit()
    flask.flash(
        gettext(
            'Thank you for participating, winners will be announced after the trivia is finished'
        ), 'info')
    return redirect(url_for('index'))
示例#5
0
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"
示例#6
0
def waitlist():
    group_id_str = request.args.get('group')
    try:
        group_id = int(group_id_str)
    except ValueError:
        flask.abort(400, "You are missing a Waitlist Group.")
        return None
    jsonwls = []
    group = db.session.query(WaitlistGroup).get(group_id)
    waitlists = [
        group.xuplist, group.logilist, group.dpslist, group.sniperlist
    ]
    if group.otherlist is not None:
        waitlists.append(group.otherlist)

    # is the requester allowed to see fits?
    exclude_fits = not perm_fits_view.can()
    include_fits_from = [current_user.get_eve_id()]
    for wl in waitlists:
        jsonwls.append(
            make_json_wl(wl,
                         exclude_fits,
                         include_fits_from,
                         scramble_names=(config.scramble_names
                                         and exclude_fits),
                         include_names_from=include_fits_from))
    return jsonify(waitlists=jsonwls,
                   groupName=group.groupName,
                   groupID=group.groupID,
                   displayName=group.displayName)
示例#7
0
def move_fleetmembers_to_safety():
    fleet_id = int(request.form.get('fleetID'))
    crest_fleet = db.session.query(CrestFleet).get(fleet_id)
    if not crest_fleet.comp.get_eve_id() == current_user.get_eve_id():
        flask.abort(403, "You are not the Fleet Comp of this fleet!")

    teamspeak_id = sget_active_ts_id()
    if teamspeak_id is None:
        flask.abort(500, "No TeamSpeak Server set!")

    teamspeak: TeamspeakDatum = db.session.query(TeamspeakDatum).get(
        teamspeak_id)
    if teamspeak.safetyChannelID is None:
        flask.abort(500, "No TeamSpeak Safety Channel set!")

    # get the safety fleet channel id
    member = member_info.get_fleet_members(fleet_id, crest_fleet.comp)
    for charID in member:
        char_id: int = member[charID].character_id()
        char = db.session.query(Character).get(char_id)
        if char is None:
            continue
        safety_channel_id: int = teamspeak.safetyChannelID
        move_to_safety_channel(char.eve_name, safety_channel_id)
    return make_response("OK", 200)
示例#8
0
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 take_over_fleet():
    # lets make sure we got the token we need

    token: SSOToken = current_user.get_a_sso_token_with_scopes(
        esi_scopes.fleetcomp_scopes)
    if token is None:
        # if not, get it. And then return here
        return get_sso_redirect('get_fleet_token',
                                ' '.join(esi_scopes.fleetcomp_scopes))

    fleet_id = get_character_fleet_id(token, current_user.get_eve_id())
    if fleet_id is None:
        flask.flash(
            gettext(
                "You are not in a fleet, or didn't not provide rights to read them."
            ), "danger")
        return redirect(url_for("fleetoptions.fleet"))

    fleet_ep: EveFleetEndpoint = EveFleetEndpoint(token, fleet_id)

    settings_resp: Union[EveFleet, ESIResponse] = fleet_ep.get_fleet_settings()
    if settings_resp.is_error():
        flask.flash(gettext('You are not the boss of the fleet you are in.'),
                    'danger')
        return redirect(url_for("fleetoptions.fleet"))

    fleet = db.session.query(CrestFleet).get(fleet_id)

    if fleet is None:
        # we don't have a setup fleet
        # this is the fleetsetup page
        return render_template("fleet/setup/fleet_url.html", fleetID=fleet_id)
    else:
        # if we got a fleet
        # lets remove the current use from a fleet he might be assigned too
        # and assign him as the new fleets comp
        if fleet.compID != current_user.id:
            oldfleet = db.session.query(CrestFleet).filter(
                (CrestFleet.compID == current_user.id)).first()
            if oldfleet is not None:
                oldfleet.compID = None
            fleet.compID = current_user.id
            db.session.commit()
            with open("set_history.log", "a+") as f:
                f.write('{} - {} is taking a fleet on CREST\n'.format(
                    datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                    fleet.comp.username))
    return redirect(url_for('fleetoptions.fleet'))
示例#10
0
def index():
    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.")
    if has_voted_today(current_user.get_eve_id()):
        flask.abort(403, "You already voted during this Eve-Day, you can vote again after Downtime!")
    # noinspection PyPep8
    active_fc_accounts = db.session.query(Account).join(Account.roles).filter(
        ((Role.name == 'fc') | (Role.name == 'tbadge'))
        & (Account.disabled == False)).order_by(asc(Account.username)).all()
    # noinspection PyPep8
    active_lm_accounts = db.session.query(Account).join(Account.roles).filter(
        ((Role.name == 'lm') | (Role.name == 'rbadge'))
        & (Account.disabled == False)).order_by(asc(Account.username)).all()
    return render_template("waitlist/ccvote.html", fcs=active_fc_accounts, lms=active_lm_accounts)
示例#11
0
def submit() -> Response:
    title = request.form['title']
    if title is None or len(title) > 50:
        return flask.abort(400, "Title is to long (max 50)")
    message = request.form['message']
    if message is None:
        return flask.abort(400)

    char_id = current_user.get_eve_id()
    if message != "":
        ticket = Ticket(title=title,
                        characterID=char_id,
                        message=message,
                        state="new")
        db.session.add(ticket)

    db.session.commit()

    flash(gettext("Thank You for your feedback!"), "info")

    return flask.redirect(url_for('.index'))
示例#12
0
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)
示例#13
0
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))
示例#14
0
def is_on_wl():
    eve_id = current_user.get_eve_id()
    entry = db.session.query(WaitlistEntry).filter(WaitlistEntry.user == eve_id).first()
    return entry is not None
示例#15
0
def events():
    """
    Available eventGroups:
    'waitlistUpdates', 'gong', 'statusChanged'
    """
    connect_try = request.args.get('connect_try', None)

    event_groups_str = request.args.get('events', None)
    if event_groups_str is None:
        flask.abort(400, "No EventGroups defined")

    event_group_strs = event_groups_str.split(",")
    event_list = []
    ip = request.headers.get('X-Real-IP', 'NoIP')

    if not current_user.is_authenticated:
        logger.info('SSE reconnection without login on try %s from %s',
                    connect_try, ip)
        db.session.remove()  # make sure there is no db session anymore
        return Response(reload_gen(), mimetype="text/event-stream")

    # userId can be None for accounts that have no character set currently
    options = {'userId': current_user.get_eve_id()}

    try:
        if connect_try is not None and int(connect_try) > 0:
            logger.info('SSE reconnection for %s on try %s from %s',
                        current_user, connect_try, ip)
    except ValueError:
        logger.error(
            'SSE connection for %s with invalid connect_try %s from %s',
            current_user, connect_try, ip)

    logger.debug('User eveId=%d requesting=%s', current_user.get_eve_id(),
                 event_group_strs)
    group_id_str = request.args.get('groupId', None)
    if group_id_str is not None:
        options['groupId'] = int(group_id_str)

    if 'waitlistUpdates' in event_group_strs:
        logger.debug("adding waitlist update events, to subscription")
        if group_id_str is None:
            flask.abort(400, "No GroupId defined")
        event_list += [
            FitAddedSSE, EntryAddedSSE, EntryRemovedSSE, FitRemovedSSE,
            InviteMissedSSE
        ]

    if 'statusChanged' in event_group_strs:
        logger.debug("Adding statusChanged event to subscription")
        event_list += [StatusChangedSSE]

    if 'gong' in event_group_strs:
        event_list += [GongSSE]

    # is the subscriber allowed to see fits?
    options['shouldGetFits'] = perm_fits_view.can()

    if len(event_list) <= 0:
        flask.abort("No valid eventgroups specified")
    subs = Subscription(event_list, options)

    # make sure there is no sqlalchemy session anymore
    db.session.remove()

    return Response(event_gen(subs), mimetype="text/event-stream")
示例#16
0
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))
示例#17
0
def index() -> Response:
    # get old feedback and input data back
    char_id = current_user.get_eve_id()
    tickets = db.session.query(Ticket).filter(
        Ticket.characterID == char_id).all()
    return render_template("feedback/index.html", tickets=tickets)