Commit cfe6580a authored by Jeremy Pallats's avatar Jeremy Pallats 💬
Browse files

Use kos_info structure instead of args where applies.

parent 90260dfd
Loading
Loading
Loading
Loading
Loading
+24 −17
Original line number Diff line number Diff line
@@ -128,24 +128,31 @@ class Action():

        return self.__duser

    async def send_to_moderation(self, *, cmdr, squad, reason, is_friendly):
    async def moderate_kos_report(self, kos_info):
        """
        Send a request to approve or deny aa KOS addition.

        Args:
            kos_info: A dictionary of the form below, same as kos_info from should_cmdr_be_on_kos in cog.inara.
                {
                    'is_friendly': True | False, # If the user is friendly or hostile,
                    'cmdr': String, # The name of cmdr.
                    'reason': String, # Reason to add cmdr,
                    'squad': String, # The squadron of the cmdr if known.
                }
        """
        # Check for dupes before bothering, KOS list should have unique cmdr names.
        scanner = get_scanner('hudson_kos')
        await scanner.update_cells()
        cnt, row = scanner.find_dupe(cmdr)
        cnt, row = scanner.find_dupe(kos_info['cmdr'])
        if cnt:
            raise cog.exc.InvalidCommandArgs(f'Duplicate "{cmdr}" reported as {row[2]} on row {cnt} with reason: {row[-1]}.\n\nCheck sheet. KOS addition aborted.')
            raise cog.exc.InvalidCommandArgs(f"Duplicate *{kos_info['cmdr']}* reported as {row[2]} on row {cnt} with reason: {row[-1]}.\n\nCheck sheet. KOS addition aborted.")

        # Request approval
        chan = self.msg.guild.get_channel(cog.util.CONF.channels.ops)
        squad = squad.capitalize() if squad == cog.inara.EMPTY_INARA else squad
        kos_info['squad'] = kos_info['squad'].capitalize() if kos_info['squad'] == cog.inara.EMPTY_INARA else kos_info['squad']
        sent = await chan.send(
            embed=cog.inara.kos_report_cmdr_embed(
                self.msg.author.name, cmdr=cmdr, squad=squad, reason=reason, is_friendly=is_friendly,
            ),
            embed=cog.inara.kos_report_cmdr_embed(self.msg.author.name, kos_info),
            components=[
                dcom.Button(label=cog.inara.BUT_APPROVE, style=dcom.ButtonStyle.green),
                dcom.Button(label=cog.inara.BUT_DENY, style=dcom.ButtonStyle.red),
@@ -158,11 +165,9 @@ class Action():
        response = "No change to KOS made."
        if inter.component.label == cog.inara.BUT_APPROVE:
            await scanner.update_cells()
            payload = scanner.add_report_dict(
                cmdr, squad, reason, is_friendly
            )
            payload = scanner.add_report_dict(kos_info)
            await scanner.send_batch(payload)
            cogdb.query.kos_add_cmdr(self.session, cmdr, squad, reason, is_friendly)
            cogdb.query.kos_add_cmdr(self.session, kos_info)
            self.session.commit()
            response = "CMDR has been added to KOS."

@@ -1208,11 +1213,13 @@ class KOS(Action):
        First ask for approval of addition, then add to kos list.
        """
        cmdr = ' '.join(self.args.cmdr)
        squad = ' '.join(self.args.faction)
        reason = ' '.join(self.args.reason) + " -{}".format(self.msg.author.name)
        is_friendly = self.args.is_friendly
        await self.msg.channel.send('CMDR {} has been reported for moderation.'.format(cmdr))
        await self.moderate_kos_report(cmdr=cmdr, squad=squad, reason=reason, is_friendly=is_friendly)
        await self.moderate_kos_report({
            'cmdr': cmdr,
            'squad': ' '.join(self.args.squad),
            'reason': ' '.join(self.args.reason) + " -{}".format(self.msg.author.name),
            'is_friendly': self.args.is_friendly,
        })

    async def execute(self):
        msg = 'KOS: Invalid subcommand'
@@ -1233,7 +1240,7 @@ class KOS(Action):
            cmdrs = cogdb.query.kos_search_cmdr(self.session, self.args.term)
            if cmdrs:
                lines = [['CMDR Name', 'Faction', 'Is Friendly?', 'Reason']]
                lines += [[x.cmdr, x.faction, x.friendly, x.reason] for x in cmdrs]
                lines += [[x.cmdr, x.squad, x.friendly, x.reason] for x in cmdrs]
                msg += cog.tbl.format_table(lines, header=True)[0]
            else:
                msg += "No matches!"
@@ -2023,7 +2030,7 @@ class WhoIs(Action):
        kos_info = await cog.inara.api.search_inara_and_kos(cmdr_name, self.msg)

        if kos_info and kos_info.pop('add'):
            await self.moderate_kos_report(**kos_info)
            await self.moderate_kos_report(kos_info)


def is_near_tick():
+8 −7
Original line number Diff line number Diff line
@@ -100,6 +100,7 @@ KOS_INFO_PROTO = {
    'reason': EMPTY_INARA,
    'squad': EMPTY_INARA,
}
RATE_WINDOW = 60


class InaraNoResult(Exception):
@@ -154,7 +155,7 @@ class RateLimiter():
    Rate of requests will be limited to max_rate within window seconds.
    Requests once they exceed maximum will resume when they hit the resume_rate.
    """
    def __init__(self, *, max_rate, resume_rate, window=60):
    def __init__(self, *, max_rate, resume_rate, window=RATE_WINDOW):
        self.window = window  # Window of the rate limiter in seconds
        self.rate = 0  # Rate of requests in last 60 seconds
        self.max_rate = max_rate
@@ -740,7 +741,7 @@ def kos_lookup_cmdr_embeds(session, cmdr_name, cmdr_pic=None):
            },
            "fields": [
                {'name': 'Name', 'value': kos.cmdr, 'inline': True},
                {'name': 'Reg Squadron', 'value': kos.faction if kos.faction else "Indy", 'inline': True},
                {'name': 'Reg Squadron', 'value': kos.squad if kos.squad else "Indy", 'inline': True},
                {'name': 'Is Friendly ?', 'value': kos.friendly, 'inline': True},
                {'name': 'Reason', 'value': kos.reason if kos.reason else "No reason.", 'inline': False},
            ],
@@ -749,13 +750,13 @@ def kos_lookup_cmdr_embeds(session, cmdr_name, cmdr_pic=None):
    return embeds


def kos_report_cmdr_embed(reporter, cmdr, squad, reason, is_friendly=False):
def kos_report_cmdr_embed(reporter, kos_info):
    """
    Return an embed that be used to inform of a report.

    Returns: A discord embed.
    """
    kill = "FRIENDLY" if is_friendly else "KILL"
    kill = "FRIENDLY" if kos_info['is_friendly'] else "KILL"

    return discord.Embed.from_dict({
        'color': KOS_COLORS[kill],
@@ -773,10 +774,10 @@ def kos_report_cmdr_embed(reporter, cmdr, squad, reason, is_friendly=False):
            'text': "Review this information and use thumbs to decide if allowed.",
        },
        "fields": [
            {'name': 'CMDR', 'value': cmdr, 'inline': True},
            {'name': 'Squad', 'value': squad, 'inline': True},
            {'name': 'CMDR', 'value': kos_info['cmdr'], 'inline': True},
            {'name': 'Squad', 'value': kos_info['squad'], 'inline': True},
            {'name': 'Kill', 'value': kill, 'inline': True},
            {'name': 'Reason', 'value': reason, 'inline': False},
            {'name': 'Reason', 'value': kos_info['reason'], 'inline': False},
        ],
    })

+3 −3
Original line number Diff line number Diff line
@@ -404,9 +404,9 @@ def subs_kos(subs, prefix):
    """ Subcommand parsing for kos """
    desc = """KOS related commands. Examples:

**{prefix}kos report -c CMDR Name -f The Faction -r Explain why he is reported here.**
**{prefix}kos report -c CMDR Name -s The Squad -r Explain why he is reported here.**
        Report an enemy PP user for KOS addition.
**{prefix}kos report --friendly -c CMDR Name -f The Faction -r Explain why he is reported here.**
**{prefix}kos report --friendly -c CMDR Name -s The Squad -r Explain why he is reported here.**
        Request whitelisting a friendly.
**{prefix}kos search user_name**
        Search for a user, list all possible matching users.
@@ -420,7 +420,7 @@ def subs_kos(subs, prefix):
                                 description='KOS subcommands', dest='subcmd')
    subcmd = subcmds.add_parser('report', help='Report user to KOS.')
    subcmd.add_argument('-c', '--cmdr', nargs='+', help='The cmdr reported.')
    subcmd.add_argument('-f', '--faction', nargs='+', default=['Indy'], help='The faction of the cmdr reported.')
    subcmd.add_argument('-s', '--squad', nargs='+', default=['Indy'], help='The squad of the cmdr reported.')
    subcmd.add_argument('-r', '--reason', nargs='+', default=['No reason given, assuming hostile.'], help='The reason reported.')
    subcmd.add_argument('--friendly', dest='is_friendly', default=False, action='store_true', help='Report user to kill.')
    subcmd = subcmds.add_parser('search', help='Search for a user.')
+3 −2
Original line number Diff line number Diff line
@@ -860,7 +860,7 @@ def kos_search_cmdr(session, term):
    return session.query(KOS).filter(KOS.cmdr.ilike(term)).all()


def kos_add_cmdr(session, cmdr, faction, reason, is_friendly=False):
def kos_add_cmdr(session, kos_info):
    """
    Add a kos entry to the local database.

@@ -870,7 +870,8 @@ def kos_add_cmdr(session, cmdr, faction, reason, is_friendly=False):
        reason: The reason for addition if provided.
        is_friendly: If this user should be treated as friendly.
    """
    return session.add(KOS(cmdr=cmdr, faction=faction, reason=reason, is_friendly=is_friendly))
    return session.add(KOS(cmdr=kos_info['cmdr'], squad=kos_info['squad'],
                           reason=kos_info['reason'], is_friendly=kos_info['is_friendly']))


def track_add_systems(session, systems, distance):
+5 −9
Original line number Diff line number Diff line
@@ -743,7 +743,7 @@ class KOSScanner(FortScanner):

        for cnt, row in enumerate(self.cells_row_major[1:], 1):
            is_friendly = row[2][0] in ('f', 'F')
            found += [cogdb.schema.KOS(id=cnt, cmdr=row[0], faction=row[1], reason=row[3],
            found += [cogdb.schema.KOS(id=cnt, cmdr=row[0], squad=row[1], reason=row[3],
                                       is_friendly=is_friendly)]

        return found
@@ -752,21 +752,17 @@ class KOSScanner(FortScanner):
        """ Return the next free kos row. """
        return len(self.cells_col_major[0]) + 1

    def add_report_dict(self, cmdr, faction, reason, is_friendly=False):
    def add_report_dict(self, kos_info):
        """
        Create an update system dict. See AsyncGSheet.batch_update

        Args:
            cmdr: The cmdr name.
            faction: The faction of the cmdr.
            reason: The reason for adding this user

        Kwargs:
            is_friendly: If the cmdr is friendly or not.
            kos_info: A kos_info object, see cog.inara

        Returns: A list of update dicts to pass to batch_update.
        """
        values = [cmdr, faction, "FRIENDLY" if is_friendly else "KILL", reason]
        values = [kos_info['cmdr'], kos_info['squad'],
                  "FRIENDLY" if kos_info['is_friendly'] else "KILL", kos_info['reason']]
        cell_range = 'A{row}:D{row}'.format(row=self.next_free_row())
        return [{'range': cell_range, 'values': [values]}]

Loading