Beispiel #1
0
def player_replay(challenge_id):
    # Check to see if replay is a player requested one
    db = Database()
    replay = db.get_single_replay(challenge_id=challenge_id)
    if replay.player_requested:
        return True
    else:
        return False
Beispiel #2
0
def challenge_exists(challenge_id):
    # Checks to see if current challenge exists
    db = Database()
    replay = db.get_single_replay(challenge_id=challenge_id)
    if replay == None:
        return False
    else:
        return True
Beispiel #3
0
def check_if_finished(challenge_id):
    if challenge_exists(challenge_id):
        # Checks to see if challenge is already finished
        db = Database()
        replay = db.get_single_replay(challenge_id=challenge_id)
        if replay.status == 'FINISHED':
            return ('FINISHED')
        else:
            return ('NOT_FINISHED')
    else:
        return ("NO_DATA")
Beispiel #4
0
class Getreplay:
    def __init__(self):
        if 'REMOTE_DEBUG' in os.environ:
            import debugpy
            debugpy.listen(("0.0.0.0", 5678))
            debugpy.wait_for_client()

        self.config = Config().config
        self.db = Database()

    @retry(wait_random_min=5000,
           wait_random_max=10000,
           stop_max_attempt_number=3)
    def get_data(self, query):
        r = requests.post("https://www.fightcade.com/api/", json=query)
        if r.status_code == 500:
            Logging().error("500 Code, trying up to 3 times")
            raise IOError("Unable to get data")
        else:
            return r

    def add_replay(self, replay, emulator, game, player_replay=True):
        challenge_id = replay['quarkid']
        p1_loc = replay['players'][0]['country']
        p2_loc = replay['players'][1]['country']
        p1 = replay['players'][0]['name']
        p2 = replay['players'][1]['name']
        date_replay = datetime.datetime.fromtimestamp(replay['date'] // 1000)
        length = replay['duration']
        created = False
        failed = False
        status = 'ADDED'
        date_added = datetime.datetime.utcnow()
        player_requested = player_replay

        if 'rank' in replay['players'] or 'rank' in replay['players'][1]:
            if replay['players'][0]['rank'] is None:
                p1_rank = '0'
            else:
                p1_rank = replay['players'][0]['rank']
            if replay['players'][1]['rank'] is None:
                p2_rank = '0'
            else:
                p2_rank = replay['players'][1]['rank']
        else:
            p1_rank = '0'
            p2_rank = '0'

        # Insert into database
        Logging().info(f"Looking for {challenge_id}")

        # Check if replay exists
        data = self.db.get_single_replay(challenge_id=challenge_id)
        if data is None:
            # Limit the length of videos
            if length > int(self.config['min_replay_length']) and length < int(
                    self.config['max_replay_length']):
                Logging().info(f"Adding {challenge_id} to queue")
                self.db.add_replay(challenge_id=challenge_id,
                                   p1_loc=p1_loc,
                                   p2_loc=p2_loc,
                                   p1_rank=p1_rank,
                                   p2_rank=p2_rank,
                                   p1=p1,
                                   p2=p2,
                                   date_replay=date_replay,
                                   length=length,
                                   created=created,
                                   failed=failed,
                                   status=status,
                                   date_added=date_added,
                                   player_requested=player_requested,
                                   game=game,
                                   emulator=emulator,
                                   video_processed=False)
                return ('ADDED')
            else:
                Logging().info(f"{challenge_id} is only {length} not adding")
                if player_replay:
                    return ('TOO_SHORT')
        else:
            Logging().info(f"{challenge_id} already exists")
            if player_replay:
                # Check if the returned replay is a player replay
                if data.player_requested:
                    return ('ALREADY_EXISTS')
                else:
                    # Update DB to mark returned replay as player replay
                    self.db.update_player_requested(challenge_id=challenge_id)
                    return ('MARKED_PLAYER')
            return ('ALREADY_EXISTS')

    def get_game_replays(self, game):
        """Get game replays

        Args:
            game (String): Gameid
        """
        if game not in self.config['supported_games']:
            return ('UNSUPPORTED_GAME')

        query = {'req': 'searchquarks', 'gameid': game}

        r = self.get_data(query)

        for i in r.json()['results']['results']:
            if i['emulator'] == 'fbneo' and i['live'] is False:
                status = self.add_replay(replay=i,
                                         emaultor=i['emaultor'],
                                         game=game,
                                         player_replay=False)
                if status != 'ADDED':
                    Logging().info(f'Not adding game, Status: {status}')

        return ("ADDED")

    def get_top_weekly(self):
        """Get the top weekly replays
        """
        today = datetime.datetime.today()
        start_week = today - timedelta(days=today.weekday())
        start_week_ms = int(start_week.timestamp() * 1000)
        query = {'req': 'searchquarks', 'best': True, 'since': start_week_ms}

        replays = []
        for i in range(0, 3):
            query['offset'] = i * 15
            r = self.get_data(query)
            replays += r.json()['results']['results']

        for i in replays:
            if i['gameid'] not in self.config['supported_games']:
                Logging().info(
                    f"Game {i['gameid']} not supported for replay {i['quarkid']}"
                )
                continue
            status = self.add_replay(replay=i,
                                     emulator=i['emulator'],
                                     game=i['gameid'],
                                     player_replay=False)
            if status != 'ADDED':
                Logging().info(
                    f"Not adding replay {i['quarkid']}, Status: {status}")

        return ("ADDED")

    def get_ranked_replays(self, game, username=None, pages=None):
        """Get ranked replays

        Args:
            game (String): Gameid
            username (String, optional): Player profile name. Defaults to None.
        """
        if game not in self.config['supported_games']:
            return ('UNSUPPORTED_GAME')

        query = {"req": "searchquarks", "best": True, "gameid": game}

        if username is not None:
            query['username'] = username

        replays = []
        if pages is None:
            query['offset'] = 0
            r = self.get_data(query)
            replays += r.json()['results']['results']
        else:
            for page in range(0, pages):
                query['offset'] = page
                r = self.get_data(query)
                replays += r.json()['results']['results']

        for i in replays:
            if i['emulator'] == 'fbneo' and i['live'] is False:
                status = self.add_replay(replay=i,
                                         emulator=i['emulator'],
                                         game=game,
                                         player_replay=False)
                if status != 'ADDED':
                    Logging().info(f'Not adding game, Status: {status}')

        return ("ADDED")

    def get_replay(self, url, player_requested=False):
        """Get a single replay

        Args:
            url (String): Link to replay
        """
        # Validate url, this could probably be done better
        pattern = re.compile(
            '^https://replay.fightcade.com/fbneo/.*/[0-9]*-[0-9]*$')
        if not pattern.match(url):
            return ('INVALID_URL')

        # Parse url
        emulator = url.split('/')[3]
        game = url.split('/')[4]
        challenge_id = url.split('/')[5]
        Logging().debug(
            f"Parsed url: emulator: {emulator}, game: {game}, challenge_id: {challenge_id}"
        )

        if game not in self.config['supported_games']:
            return ('UNSUPPORTED_GAME')

        # Get play replays
        query = {"req": "searchquarks", "quarkid": challenge_id}
        r = self.get_data(query)

        # Look for replay in results:
        for i in r.json()['results']['results']:
            if challenge_id == i['quarkid']:
                return self.add_replay(replay=i,
                                       emulator=emulator,
                                       game=game,
                                       player_replay=player_requested)
        return False
Beispiel #5
0
def get_current_job_details():
    challenge_id = get_current_job_id()
    db = Database()
    replay = db.get_single_replay(challenge_id=challenge_id)
    logging.info(f"Current job rowdata is: {replay}")
    return (replay)
Beispiel #6
0
def get_replay_status(challenge_id):
    db = Database()
    replay = db.get_single_replay(challenge_id=challenge_id)
    logging.info(f"Current job STATUS is: {replay.status}")
    return (replay.status)
Beispiel #7
0
class Cli(cmd2.Cmd):
    def __init__(self):
        super().__init__()

        # Show this as the prompt when asking for input
        self.prompt = 'fcreplay> '

        # Used as prompt for multiline commands after the first line
        self.continuation_prompt = '... '

        self.db = Database()

    delete_failed_parser = cmd2.Cmd2ArgumentParser(
        description='Delete a failed replay')
    delete_failed_parser.add_argument('challenge_id',
                                      help='Challenge id of replay')

    delete_all_failed_parser = cmd2.Cmd2ArgumentParser(
        description='Delete all failed replays')
    delete_all_failed_parser.add_argument('-y',
                                          '--yes',
                                          action='store_true',
                                          help='Force yes')

    delete_pending_parser = cmd2.Cmd2ArgumentParser(
        description='Delete a pending replay')
    delete_pending_parser.add_argument('challenge_id',
                                       help='Challenge id of the replay')

    delete_all_pending_parser = cmd2.Cmd2ArgumentParser(
        description='Delete all pending replays')
    delete_all_pending_parser.add_argument('-y',
                                           '--yes',
                                           action='store_true',
                                           help='Force yes')

    retry_replay_parser = cmd2.Cmd2ArgumentParser(
        description='Mark a replay to be re-encoded')
    retry_replay_parser.add_argument('challenge_id',
                                     help='Challenge id of replay')

    retry_all_failed_replays_parser = cmd2.Cmd2ArgumentParser(
        description='Mark all failed replays to be re-encoded')
    retry_all_failed_replays_parser.add_argument('-y',
                                                 '--yes',
                                                 action='store_true',
                                                 help='Force yes')

    list_replays_parser = cmd2.Cmd2ArgumentParser(description='List replays')
    list_replays_parser.add_argument('type',
                                     type=str,
                                     nargs=1,
                                     choices=['failed', 'finished', 'pending'],
                                     help='Type of replays to return')
    list_replays_parser.add_argument('-l',
                                     '--limit',
                                     default=10,
                                     type=int,
                                     help='Limit number of results')

    count_parser = cmd2.Cmd2ArgumentParser(description='List replays')
    count_parser.add_argument('type',
                              type=str,
                              nargs=1,
                              choices=['failed', 'finished', 'pending', 'all'],
                              help='Type of replays to count')

    def yes_or_no(self, question):
        while "the answer is invalid":
            reply = str(input(question + ' continue? (y/n): ')).lower().strip()
            if reply[:1] == 'y':
                return True
            if reply[:1] == 'n':
                return False

    @cmd2.with_argparser(delete_failed_parser)
    def do_delete_failed(self, args):
        if self.yes_or_no(
                f"This will delete failed replay: {args.challenge_id},"):
            replay = self.db.get_single_replay(args.challenge_id)

            if replay is not None:
                if replay.failed is True:
                    self.db.delete_replay(args.challenge_id)
                    print(f"Deleated replay {args.challenge_id}")
                else:
                    print(f"Replay {args.challenge_id} isn't a faild replay")
                    return
            else:
                print(f"Replay {args.challenge_id} doesn't exist")
                return

    @cmd2.with_argparser(delete_all_failed_parser)
    def do_delete_all_failed(self, args):
        if not args.yes:
            if not self.yes_or_no("This will delete all failed replays,"):
                return

        failed_replays = self.db.get_all_failed_replays(limit=9999)

        if failed_replays is not None:
            for r in failed_replays:
                self.db.delete_replay(r.id)
                print(f"Removed replay: {r.id}")
        else:
            print("No failed replays")
            return

    @cmd2.with_argparser(delete_pending_parser)
    def do_delete_pending(self, args):
        if self.yes_or_no(
                f"This will delete the pending replay: {args.challenge_id},"):
            replay = self.db.get_single_replay(args.challenge_id)

            if replay is not None:
                if replay.failed is not True and replay.finished is not True:
                    self.db.delete_replay(replay.id)
                else:
                    print("Replay isn't a pending replay")
                    return
            else:
                print("No replay found")
                return

    @cmd2.with_argparser(delete_all_pending_parser)
    def do_delete_all_pending(self, args):
        if not args.yes:
            if not self.yes_or_no("This will delete all pending replays,"):
                return

        pending_replays = self.db.get_all_queued_replays(limit=9999)

        if pending_replays is not None:
            for r in pending_replays:
                self.db.delete_replay(r.id)
                print(f"Removed replay: {r.id}")
        else:
            print("No pending replays")
            return

    @cmd2.with_argparser(retry_replay_parser)
    def do_retry_replay(self, args):
        replay = self.db.get_single_replay(args.challenge_id)

        if replay is not None:
            self.db.rerecord_replay(args.challenge_id)
            print(f"Marked replay {args.challenge_id} to be re-encoded")
        else:
            print(f"Replay {args.challenge_id} doesn't exist")

    @cmd2.with_argparser(retry_all_failed_replays_parser)
    def do_retry_all_failed_replays(self, args):
        if not args.yes:
            if not self.yes_or_no("This will retry all failed replays,"):
                return

        failed_replays = self.db.get_all_failed_replays()
        if failed_replays is None:
            print("No failed replays to retry")
        else:
            for r in failed_replays:
                self.db.rerecord_replay(r.id)
                print(f"Marked failed replay {r.id} to be re-encoded")

    @cmd2.with_argparser(list_replays_parser)
    def do_ls(self, args):
        replays = None

        if 'failed' in args.type:
            replays = self.db.get_all_failed_replays(limit=args.limit)
        elif 'finished' in args.type:
            replays = self.db.get_all_finished_replays(limit=args.limit)
        elif 'pending' in args.type:
            replays = self.db.get_all_queued_replays(limit=args.limit)
        else:
            return

        if replays is not None:
            pp = pprint.PrettyPrinter()
            for r in replays:
                pp.pprint(r.__dict__)
        else:
            print(f"No replays found for query: {args}")

    @cmd2.with_argparser(count_parser)
    def do_count(self, args):
        replay_count = None

        if 'failed' in args.type:
            replay_count = self.db.get_failed_count()
        elif 'finished' in args.type:
            replay_count = self.db.get_finished_count()
        elif 'pending' in args.type:
            replay_count = self.db.get_pending_count()
        elif 'all' in args.type:
            replay_count = self.db.get_all_count()

        if replay_count is None:
            print("0")
        else:
            print(replay_count)