Esempio n. 1
0
async def reload(ctx,cog_to_reload = None):
	print(f"reloading {cog_to_reload if cog_to_reload in ['Games','Fun','Meta'] else ''}")
	if cog_to_reload in ["Games","Fun","Meta"]:
		if cog_to_reload == "Games":
			client.remove_cog("Games")
			importlib.reload(games)
			client.add_cog(games.Games(client))
		if cog_to_reload == "Fun":
			client.remove_cog("Fun")
			importlib.reload(fun)
			client.add_cog(games.Fun(client))
		if cog_to_reload == "Meta":
			client.remove_cog("Meta")
			importlib.reload(meta)
			client.add_cog(games.Meta(client))
	else:
		client.remove_cog("Games")
		client.remove_cog("Fun")
		client.remove_cog("Meta")
		importlib.reload(games)
		importlib.reload(fun)
		importlib.reload(meta)
		client.add_cog(games.Games(client))
		client.add_cog(fun.Fun(client))
		client.add_cog(meta.Meta(client))
	await ctx.send("Reload complete!")
Esempio n. 2
0
 def get_game_list(self):
     """Return a Games object containing the list of games available on the system."""
     game_list = RomList(self.conf.rom_dirs)
     mame_games = games.Games()
     try:
         mame_games.load_from_xml(self.conf.mame_xml, game_list)
     except games.XMLError:
         raise XMLError
     return mame_games
Esempio n. 3
0
 def get_largest_franchise_ids(self):
     """ Uses the list of games to find the highest occuring franchise IDs"""
     franchise_ids_list = []
     p = processor.Processor()
     g = games.Games(self.platform_id)
     game_list = g.get_top_game_list()
     for game in game_list:
         if 'franchise' in game.keys():
             franchise_ids_list.append(game['franchise'])
     sorted_list = sorted(set(franchise_ids_list), key=lambda x: -franchise_ids_list.count(x))
     logging.info('Identified {} franchises for {} platform'.format(len(sorted_list), self.platform_name))
     return sorted_list
Esempio n. 4
0
 def make_top_list(self):
     ''' 
     Makes a new list of rom files based on most popular and what you have. 
     Then copies them to a new folder.
     '''
     logging.info('Beginning to create a new list of files to copy.')
     for i in self.config_data:
         g = games.Games(i['platformID'])
         r = roms.Roms(i['platformID'])
         f = franchises.Franchises(i['platformID'])
         top_list = sorted(g.get_top_game_list())
         file_list = sorted(r.get_rom_file_list())
         franchise_list = f.get_franchise_list()
         clean_file_list = map(lambda x: self.santize_string(x), file_list)
         best_list = []
         logging.info(u'PROCESSING: {}'.format(g.get_console_name()))
         for t in top_list:
             game = self.santize_string(t['name'])
             try:
                 highest = process.extractOne(game, clean_file_list)
                 score = str(highest[1])
                 idx = clean_file_list.index(highest[0])
                 filename = file_list[idx]
                 if int(score) >= 90:
                     logging.info(
                         u'MATCHED: {} | {} | high score {}'.format(
                             t['name'], filename, score))
                     best_list.append(filename)
                 else:
                     logging.warning(
                         u'SKIPPED DUE TO SCORE: {} | {} | high score {}'.
                         format(t['name'], filename, score))
             except Exception as e:
                 logging.exception(str(e))
                 pass
         try:
             if include_franchise == True:
                 skipped_file_list = set(file_list) - set(best_list)
                 skipped_file_list = map(str, skipped_file_list)
                 for filename in skipped_file_list:
                     if any(f.lower() in filename.lower()
                            for f in franchise_list):
                         logging.info(
                             u'MATCHED FRANCHISE MEMBER: {}'.format(
                                 filename))
                         best_list.append(filename)
         except Exception as e:
             logging.exception(str(e))
         r.make_new_rom_set(best_list)
     return
Esempio n. 5
0
def refresh_all():
    logging.info('Detected API key, refreshing rom lists')
    platforms_obj = platforms.Platforms()
    platform_list = platforms_obj.refresh_platform_list()
    write_file('./yamls/platform_list.yml', platform_list)
    for p in platform_list:
        games_obj = games.Games(p['id'])
        console_name = games_obj.get_console_name()
        game_list_filename = './yamls/game_lists/' + console_name + '.yml'
        #write_file(game_list_filename, games_obj.refresh_game_list())
        franchises_obj = franchises.Franchises(p['id'])
        franchise_list = franchises_obj.refresh_franchise_list()
        franchise_list_filename = './yamls/franchise_lists/' + console_name + '.yml'
        write_file(franchise_list_filename, franchise_list)
Esempio n. 6
0
    def __init__(self):
        self.minibatch_size = 32  # Given in the paper
        self.number_of_actions = 4  # XXX Game "Breakout" has 4 possible actions

        # Properties of the neural net which come from the paper
        self.nnet = NeuralNet([1, 4, 84, 84],
                              filter_shapes=[[16, 4, 8, 8], [32, 16, 4, 4]],
                              strides=[4, 2],
                              n_hidden=256,
                              n_out=self.number_of_actions)
        self.ale = ALE()
        self.frames_played = 0
        self.iterations_per_choice = 4
        self.games = games.Games()
Esempio n. 7
0
async def on_ready():
	print(f"logged in as {client.user}")
	print(f"https://discord.com/oauth2/authorize?client_id={client.user.id}&permissions=8192&scope=bot")
	for guild in client.guilds:
		print(f"In guild: {guild.name}")
	print(f"In {len(client.guilds)} guilds")
	global log_channel, bug_channel, suggestion_channel, t0
	log_channel = client.get_channel(784583344188817428)
	bug_channel = client.get_channel(775770636353011752)
	suggestion_channel = client.get_channel(775770609191616512)
	await log_channel.send("waking up")
	await client.change_presence(activity=discord.Game("games"))
	client.add_cog(games.Games(client))
	client.add_cog(fun.Fun(client))
	client.add_cog(meta.Meta(client))
	t0 = datetime.now()
Esempio n. 8
0
    def put_new_game(self, game):
        # Add a new game to the database
        try:
            game_model = games.Games(game=game,
                                     info=json.dumps([]),
                                     parent=games.key(),
                                     key_name=util.get_code(game))
        except db.BadValueError:
            return False

        game_model.put()
        logging.warning("Put new game " + game + " in database.")

        # Update memcache
        self.update_gamelist_snp_put(game)

        return True
Esempio n. 9
0
    @commands.command()
    async def games(self, ctx):
        await ctx.send(self.bot.games)

    @commands.command()
    async def cache(self, ctx):
        await ctx.send(self.bot.cache)

    @commands.command()
    async def flags(self, ctx):
        await ctx.send(self.bot.flags)

if __name__ == '__main__':
    logging.basicConfig(handlers = [logging.FileHandler('_bot.log', 'w', 'utf-8')],
                        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                        datefmt='%H:%M:%S',
                        level=logging.INFO)
    bot = RefBot(command_prefix='!', description='Referee Core Bot.')
    @bot.event
    async def on_ready():
        print(f'{bot.user.name}: {bot.user.id}')


    with open('_bot.creds', 'r') as file:
        creds = file.read()

    bot.add_cog(Debug(bot))
    bot.add_cog(Main(bot))
    bot.add_cog(games.Games(bot))
    bot.run(creds)
Esempio n. 10
0
    def change_categories( self, params ):
        res = ''

        # Grab the old game model
        old_game_code = util.get_code( params['old_game'] )
        if old_game_code == params['new_game_code']:
            old_game_model = params['new_game_model']
        else:
            old_game_model = self.get_game_model( old_game_code )
        if old_game_model is None:
            return "Did not find game [" + params['old_game'] + "]"

        if params['new_game_model'] is None:
            # New game does not exist, so create it
            params['new_game_model'] = games.Games( 
                game = params['new_game'],
                info = json.dumps( [ ] ),
                num_pbs = 0,
                parent = games.key( ),
                key_name = params['new_game_code'] )
            res += ( 'Created new game model for game [' + params['new_game'] 
                     + ']<br>' )
        
        if not params['new_category_found']:
            # Add the new category to the new game model
            gameinfolist = json.loads( params['new_game_model'].info )
            d = dict( category=params['new_category'], 
                      bk_runner=None,
                      bk_seconds=None,
                      bk_video=None,
                      bk_datestr=None,
                      bk_updater=None )
            gameinfolist.append( d )
            params['new_game_model'].info = json.dumps( gameinfolist )
            res += 'Added new category [' + params['new_category'] + ']<br>'

        # Grab the gameinfo for the old game
        oldgameinfolist = json.loads( old_game_model.info )
        oldgameinfo = None
        for g in oldgameinfolist:
            if( util.get_code( params['old_category'] ) == util.get_code( 
                    g['category'] ) ):
                oldgameinfo = g
                break
        if oldgameinfo is None:
            return "Did not find old category [" + params['old_category'] + ']'

        # Grab the gameinfo for the new game
        newgameinfolist = json.loads( params['new_game_model'].info )
        newgameinfo = None
        for g in newgameinfolist:
            if( util.get_code( params['new_category'] ) == util.get_code( 
                    g['category'] ) ):
                newgameinfo = g
                break
        if newgameinfo is None:
            return "Did not find new category [" + params['new_category'] + ']'

        # Update best known time if necessary
        if( oldgameinfo.get( 'bk_seconds' ) is not None
            and ( newgameinfo.get( 'bk_seconds' ) is None 
                  or oldgameinfo.get( 'bk_seconds' ) 
                  < newgameinfo.get( 'bk_seconds' ) ) ):
            newgameinfo['bk_seconds'] = oldgameinfo.get( 'bk_seconds' )
            newgameinfo['bk_runner'] = oldgameinfo.get( 'bk_runner' )
            newgameinfo['bk_datestr'] = oldgameinfo.get( 'bk_datestr' )
            newgameinfo['bk_video'] = oldgameinfo.get( 'bk_video' )
            newgameinfo['bk_updater'] = oldgameinfo.get( 'bk_updater' )
            params['new_game_model'].info = json.dumps( newgameinfolist )
            res += 'Updated bkt<br>'

        # Update num_pbs for old game, new game
        res += ( 'Previous num_pbs for old game, category = ' 
                 + str( old_game_model.num_pbs ) + '<br>' )
        res += ( 'Previous num_pbs for new game, category = ' 
                 + str( params['new_game_model'].num_pbs ) + '<br>' )
        q = db.Query( runs.Runs, projection=['username'], distinct=True )
        q.ancestor( runs.key() )
        q.filter( 'game =', params['old_game'] )
        q.filter( 'category =', params['old_category'] )
        for run in q.run( limit=1000 ):
            old_game_model.num_pbs -= 1
            q2 = db.Query( runs.Runs )
            q2.ancestor( runs.key() )
            q2.filter( 'game =', params['new_game'] )
            q2.filter( 'category =', params['new_category'] )
            q2.filter( 'username ='******'new_game_model'].num_pbs += 1
            else:
                # Need to decrement runner's num_pbs
                runner = self.get_runner( util.get_code( run.username ) )
                runner.num_pbs -= 1
                runner.put( )
                res += ( "Updated " + run.username + " num_pbs from "
                         + str( runner.num_pbs + 1 ) + " to " 
                         + str( runner.num_pbs ) + "<br>" )
                
        res += ( 'Updated num_pbs for old game, category = ' 
                 + str( old_game_model.num_pbs ) + '<br>' )
        res += ( 'Updated num_pbs for new game, category = ' 
                 + str( params['new_game_model'].num_pbs ) + '<br>' )

        # Update old, new game models in database
        old_game_model.put( )
        if old_game_code != params['new_game_code']:
            params['new_game_model'].put( )

        # Change the runs
        res += "<br>Changed runs:<br>"
        q = db.Query( runs.Runs )
        q.ancestor( runs.key() )
        q.filter( 'game =', params['old_game'] )
        q.filter( 'category =', params['old_category'] )
        for run in q.run( limit = 10000 ):
            # Update the run
            run.game = params['new_game']
            run.category = params['new_category']
            run.put( )
            res += ( 'Runner=' + run.username + ' time=' 
                     + util.seconds_to_timestr( run.seconds ) + '<br>' )

        if not memcache.flush_all( ):
            res += "Failed to flush memcache<br>"

        # All dun
        return res
Esempio n. 11
0
def v007_to_v008(gdb_inp, ldb_inp):
    """
    Converts
    """

    gamelist = games.Games()
    gamelist.translate_json(json.dumps(gdb_inp))

    out_games = {}
    out_local = {"game_data": {}, "emulators": {}}
    out_games["multipack"] = gdb_inp["multipack"]
    out_games["actions"] = gdb_inp["actions"]
    out_games["games"] = {}
    print("starting:", len(gdb_inp["games"]))
    ran = 0
    collisions = 0
    changed_keys = {}
    for key in gdb_inp["games"]:
        ran += 1
        game = gdb_inp["games"][key]
        if not game["name"]:
            print("ERROR", key)
            continue

        new = copy.deepcopy(game)

        game = games.Game(**game)
        orig = game.dict()
        oldid = game.gameid
        game.generate_gameid()
        new["gameid"] = game.gameid

        changed_keys[oldid] = new["gameid"]

        cur_local = ldb_inp["game_data"].get(oldid, None)

        if game.gameid in out_games["games"]:
            collisions += 1
            print("COLLISION:")
            print(new)
            print(out_games["games"][game.gameid])
        out_games["games"][game.gameid] = new
        if cur_local:
            out_local["game_data"][game.gameid] = cur_local

    for key in out_games["games"]:
        game = out_games["games"][key]
        if not game["package_data"]:
            continue
        if game["package_data"]["type"] == "bundle":
            for child in game["package_data"]["contents"]:
                child["gameid"] = changed_keys[child["gameid"]]
        elif game["package_data"]["type"] == "content":
            parent = game["package_data"]["parent"]
            if parent["gameid"] in changed_keys:
                parent["gameid"] = changed_keys[parent["gameid"]]

    print("looped", ran, "times")
    print(len(out_games["games"]), len(gdb_inp["games"]))
    print(collisions, len(gdb_inp["games"]) - collisions)
    return out_games, out_local
Esempio n. 12
0
def v006_to_v007(inp):
    """
    Converts install_path to external local exe information

    "mother_1.0": {
            "gameid": "mother_1.0",
            "install_path": "C:\\emu\\gb\\mother12.gba",
            "lastplayed": "13:32:54 2015-01-19",
            "name": "Mother 1",
            "website": "",
            "sources": [
                {
                    "source": "gba"
                }
            ],
        },

    >>>

    local_db = {
        "game_data":{
            "mother_1.0":{
                "files": [
                    {"type":"rom","primary":True,"path":"C:\\emu\\gb\\mother12.gba","source":"gba"}
                ]
            }
        },
        "emulators":{
            "gba":{
                "path":"C:\\emu\\retroarch\\retroarch.exe",
                "cmd":"$program -c C:\\emu\\retroarch\\retroarch-gba.cfg $path"
            }
        }
    }
    """

    gamelist = games.Games()
    gamelist.translate_json(json.dumps(inp))

    out_games = {}
    out_local = {"game_data": {}, "emulators": {}}
    out_games["multipack"] = inp["multipack"]
    out_games["actions"] = inp["actions"]
    out_games["games"] = {}
    print("starting:", len(inp["games"]))
    ran = 0
    for key in inp["games"]:
        ran += 1
        game = inp["games"][key]
        if not game["name"]:
            print("ERROR", key)
            continue
        new = copy.deepcopy(game)

        game = games.Game(**game)

        if game.install_path:
            li = []
            out_local["game_data"][game.gameid] = {"files": li}
            for s in game.sources:
                file = {"source": s, "primary": True}
                if s["source"] in ["gba", "snes", "n64", "nds"]:
                    file.update({"type": "rom", "path": game.install_path})
                else:
                    file.update({"type": "exe", "path": game.install_path})
                li.append(file)

        del new["install_path"]
        out_games["games"][game.gameid] = new
    print("looped", ran, "times")
    print(len(out_games["games"]), len(inp["games"]))
    return out_games, out_local
Esempio n. 13
0
def v005_to_v006(inp):
    """
    Games that are a package (is_package==True) will have:
    package_data: {"type":"bundle","contents":[(gameid,name) for all games in package]}

    Games that are in a package (is_package==False, but have package info elsewhere)
    package_data: {"type":"content","parent":[(gameid,name) for package],"source_info":{"gog_id","humble_package"}}
    source_info is just for auditing

    Games that are not a package, nor are they in a package (is_package==False, no other packaging keys),
    package_data: {}

    delete is_package identifyer (gotten with package_data)
    """

    gamelist = games.Games()
    gamelist.translate_json(json.dumps(inp))

    out = {}
    out["multipack"] = inp["multipack"]
    out["actions"] = []
    out["games"] = {}
    print("starting:", len(inp["games"]))
    ran = 0
    for key in inp["games"]:
        ran += 1
        game = inp["games"][key]
        if not game["name"]:
            print("ERROR", key)
            continue
        new = copy.deepcopy(game)

        game = games.Game(**game)

        package = gamelist.get_package_for_game_converter(game)

        def get_source_info(source):
            if source["source"] == "gog":
                return {
                    "package_source": "gog",
                    "package_id": source["id"],
                    "id_within_package": game.packageid
                }
            elif source["source"] == "humble":
                return {
                    "package_source": "humble",
                    "package_id": source["package"],
                    "id_within_package": source["id"]
                }

        assert len(game.sources) == 1

        if game.is_package:
            print("Converting package:", game.gameid)
            inside = game.games_for_pack_converter(gamelist)
            new["package_data"] = {
                "type": "bundle",
                "contents": [{
                    "gameid": g.gameid,
                    "name": g.name
                } for g in inside],
                "source_info": get_source_info(game.sources[0])
            }
        else:
            if package:
                print("Converting content item:", game.gameid)
                source_info = get_source_info(game.sources[0])
                new["package_data"] = {
                    "type": "content",
                    "parent": {
                        "gameid": package.gameid,
                        "name": package.name
                    },
                    "source_info": source_info
                }
            else:
                new["package_data"] = {}
        del new["is_package"]
        del new["packageid"]

        out["games"][game.gameid] = new
    print("looped", ran, "times")
    print(len(out["games"]), len(inp["games"]))
    return out
Esempio n. 14
0
            pass
    links = links[0:5]
    final_links = []
    headlines = []
    for link in links:
        final_link = link
        if "http" not in final_link:
            final_link = NEWS_BASE_URL + link
        link_content = requests.get(final_link)
        soup = BeautifulSoup(link_content.text)
        headlines.append(soup.title.text)
        final_links.append(final_link)
    for i in range(5):
        print_string += headlines[i]
        print_string += "\n<"
        print_string += final_links[i]
        print_string += ">\n"
    await ctx.send(print_string)


alexa.add_cog(games.Games(alexa))


@alexa.event
async def on_connect():
    print("Success!")
    await alexa.change_presence(activity=discord.Game(name="Alexa, help"))


alexa.run(os.getenv("token"))
Esempio n. 15
0
 def filter_list(self, game_list, game_filter):
     """Take the parameter game_list, apply game_filter, and return the filtered list of games."""
     return games.Games(game_list, game_filter)
Esempio n. 16
0
    def update_games_put(self, params, delta_num_pbs):
        user = params['user']
        game_model = params['game_model']
        game = params['game']
        category = params['category']
        game_code = params['game_code']
        category_found = params['category_found']
        seconds = params['seconds']
        datestr = params['datestr']
        video = params['video']
        is_bkt = params['is_bkt']

        if game_model is None:
            # Add a new game to the database
            d = dict(category=category,
                     bk_runner=None,
                     bk_seconds=None,
                     bk_datestr=None,
                     bk_video=None,
                     bk_updater=None)
            if is_bkt:
                d['bk_runner'] = user.username
                d['bk_seconds'] = seconds
                d['bk_datestr'] = datestr
                d['bk_video'] = video
                d['bk_updater'] = user.username
            game_model = games.Games(game=game,
                                     info=json.dumps([d]),
                                     num_pbs=1,
                                     parent=games.key(),
                                     key_name=game_code)
            game_model.put()
            logging.warning("Put new game " + game + " with " + " category " +
                            category + " in database.")

            # Update memcache
            self.update_cache_game_model(game_code, game_model)
            categories = self.get_categories(no_refresh=True)
            if categories is not None and categories != self.OVER_QUOTA_ERROR:
                categories[str(game)] = [str(category)]
                self.update_cache_categories(categories)

            return

        game_model.num_pbs += delta_num_pbs

        if not category_found:
            # Add a new category for this game in the database
            info = json.loads(game_model.info)
            d = dict(category=category,
                     bk_runner=None,
                     bk_seconds=None,
                     bk_video=None)
            if is_bkt:
                d['bk_runner'] = user.username
                d['bk_seconds'] = seconds
                d['bk_datestr'] = datestr
                d['bk_video'] = video
                d['bk_updater'] = user.username
            info.append(d)
            game_model.info = json.dumps(info)
            game_model.put()
            logging.debug("Added category " + category + " to game " + game +
                          " in database.")

            # Update memcache
            self.update_cache_game_model(game_code, game_model)
            categories = self.get_categories(no_refresh=True)
            if categories is not None and categories != self.OVER_QUOTA_ERROR:
                categories[str(game)].append(str(category))
                categories[str(game)].sort()
                self.update_cache_categories(categories)

            return

        if is_bkt:
            # Update the best known time for this game, category
            gameinfolist = json.loads(game_model.info)
            for gameinfo in gameinfolist:
                if gameinfo['category'] == category:
                    gameinfo['bk_runner'] = user.username
                    gameinfo['bk_seconds'] = seconds
                    gameinfo['bk_datestr'] = datestr
                    gameinfo['bk_video'] = video
                    gameinfo['bk_updater'] = user.username
                    game_model.info = json.dumps(gameinfolist)
                    logging.debug("Updated best known time for game " + game +
                                  ", category " + category + " in database")
                    break

        if is_bkt or delta_num_pbs != 0:
            # We made some changes, so store in db and update memcache
            game_model.put()
            self.update_cache_game_model(game_code, game_model)
Esempio n. 17
0
class TimeCheck:

    games = games.Games().games

    def __init__(self, time_before, log_level, hold_dh_game2_thread,
                 post_thread_enabled):
        self.time_before = time_before
        self.log_level = log_level
        self.hold_dh_game2_thread = hold_dh_game2_thread
        self.post_thread_enabled = post_thread_enabled

    def endofdaycheck(self):
        today = datetime.today()
        while True:
            check = datetime.today()
            if today.day != check.day:
                if self.log_level > 1:
                    print datetime.strftime(check,
                                            "%d %I:%M:%S %p") + " NEW DAY"
                return
            else:
                if self.log_level > 1:
                    print "Last date check: " + datetime.strftime(
                        check, "%d %I:%M:%S %p")
                time.sleep(600)

    def gamecheck(self, thisgame=1, gamecount=1, just_get_time=False):
        if self.games[thisgame].get('gamesub'):
            return True  #game thread is already posted
        if self.games[thisgame].get('doubleheader') and str(
                self.games[thisgame].get('gameNumber')) == '2':
            if self.hold_dh_game2_thread and not just_get_time:
                if self.games[self.games[thisgame].get('othergame')].get(
                        'doubleheader') and not self.games[self.games[
                            thisgame].get('othergame')].get('final'):
                    if self.log_level > 1:
                        print datetime.strftime(
                            datetime.today(), "%d %I:%M:%S %p"
                        ), "Holding doubleheader Game", self.games[
                            thisgame].get(
                                'gameNumber'), "until Game", self.games[
                                    self.games[thisgame].get('othergame')].get(
                                        'gameNumber'
                                    ), "is final, sleeping for 5 seconds..."
                    time.sleep(5)
                    return False
            else:
                if self.log_level > 2:
                    print "Doubleheader Game 2 start time:", self.games[
                        thisgame].get('gameInfo').get(
                            'date_object'), "; Game 1 start time:", self.games[
                                self.games[thisgame].get('othergame')].get(
                                    'gameInfo').get('date_object')
                if self.games[self.games[thisgame].get('othergame')].get(
                        'gameInfo').get('date_object') > self.games[
                            thisgame].get('gameInfo').get(
                                'date_object'
                            ):  #game 1 start time is after game 2 start time
                    if self.log_level > 1:
                        print "Detected doubleheader Game 2 start time is before Game 1 start time. Using Game 1 start time + 3.5 hours for Game 2..."
                    self.games[thisgame]['gameInfo'].update(
                        {
                            'date_object':
                            self.games[self.games[thisgame].get('othergame')].
                            get('gameInfo').get('date_object') +
                            timedelta(hours=3, minutes=30)
                        }
                    )  #use game 1 start time + 3.5 hours for game 2 start time
                    if self.log_level > 2:
                        print "Game 2 start time:", self.games[thisgame].get(
                            'gameInfo').get(
                                'date_object'
                            ), "; Game 1 start time:", self.games[
                                self.games[thisgame].get('othergame')].get(
                                    'gameInfo').get('date_object')
        if just_get_time:
            return self.games[thisgame].get('gameInfo').get(
                'date_object').replace(hour=self.games[thisgame].get(
                    'gameInfo').get('date_object').hour -
                                       self.time_before / 60 / 60)
        if self.games[thisgame].get('status').get('detailedState').startswith(
                'Postponed') or self.games[thisgame].get('status').get(
                    'detailedState').startswith(
                        'Suspended') or self.games[thisgame].get('status').get(
                            'detailedState').startswith('Cancelled'):
            if self.post_thread_enabled:
                if self.log_level > 1:
                    print datetime.strftime(
                        datetime.today(),
                        "%d %I:%M:%S %p"), "Game", thisgame, "is", self.games[
                            thisgame].get('status').get(
                                'detailedState') + ", skipping game thread..."
                self.games[thisgame].update({'skipflag': True})
            else:
                if self.log_level > 1:
                    print datetime.strftime(
                        datetime.today(), "%d %I:%M:%S %p"
                    ), "Game", thisgame, "is", self.games[thisgame].get(
                        'status'
                    ).get(
                        'detailedState'
                    ) + ", overriding hours before setting for game thread since postgame thread is disabled..."
            return True  #go ahead and post the postgame thread since the game is postponed/suspended/canceled
        while True:
            check = datetime.utcnow().replace(tzinfo=tz.utc).astimezone(
                tzlocal.get_localzone())
            if self.games[thisgame].get('gameInfo').get(
                    'date_object_utc').astimezone(
                        tzlocal.get_localzone()) >= check:
                if (self.games[thisgame].get('gameInfo').get('date_object_utc')
                        .astimezone(tzlocal.get_localzone()) -
                        check).seconds <= self.time_before:
                    return True
                else:
                    if self.log_level > 2:
                        print "Time to post game thread:", self.games[
                            thisgame].get('gameInfo').get(
                                'date_object_utc'
                            ).astimezone(tzlocal.get_localzone()).replace(
                                hour=self.games[thisgame].get('gameInfo').get(
                                    'date_object_utc').astimezone(
                                        tzlocal.get_localzone()).hour -
                                self.time_before / 60 / 60)
                    if gamecount > 1:
                        if self.log_level > 1:
                            print datetime.strftime(
                                check, "%d %I:%M:%S %p"
                            ), "Not time to post game thread yet, sleeping for 5 seconds..."
                        time.sleep(5)
                    return False
            else:
                return True

    def pregamecheck(self, pre_time):
        date_object = datetime.strptime(pre_time, "%I%p")
        while True:
            check = datetime.today()
            if date_object.hour <= check.hour:
                return
            else:
                if self.log_level > 1:
                    print "Last pre-game/offday check: " + datetime.strftime(
                        check, "%d %I:%M:%S %p")
                time.sleep(600)
Esempio n. 18
0
    def change_categories(self, params):
        res = ''

        # Grab the old game model
        old_game_code = util.get_code(params['old_game'])
        if old_game_code == params['new_game_code']:
            old_game_model = params['new_game_model']
        else:
            old_game_model = self.get_game_model(old_game_code)
        if old_game_model == self.OVER_QUOTA_ERROR:
            self.error(403)
            self.render("403.html")
            return
        if old_game_model is None:
            return "Did not find game [" + params['old_game'] + "]"

        if params['new_game_model'] is None:
            # New game does not exist, so create it
            params['new_game_model'] = games.Games(
                game=params['new_game'],
                info=json.dumps([]),
                num_pbs=0,
                parent=games.key(),
                key_name=params['new_game_code'])
            res += ('Created new game model for game [' + params['new_game'] +
                    ']<br>')

        if not params['new_category_found']:
            # Add the new category to the new game model
            gameinfolist = json.loads(params['new_game_model'].info)
            d = dict(category=params['new_category'],
                     bk_runner=None,
                     bk_seconds=None,
                     bk_video=None,
                     bk_datestr=None,
                     bk_updater=None)
            gameinfolist.append(d)
            params['new_game_model'].info = json.dumps(gameinfolist)
            res += 'Added new category [' + params['new_category'] + ']<br>'

        # Grab the gameinfo for the old game
        oldgameinfolist = json.loads(old_game_model.info)
        oldgameinfo = None
        for g in oldgameinfolist:
            if (util.get_code(params['old_category']) == util.get_code(
                    g['category'])):
                oldgameinfo = g
                break
        if oldgameinfo is None:
            return "Did not find old category [" + params['old_category'] + ']'

        # Grab the gameinfo for the new game
        newgameinfolist = json.loads(params['new_game_model'].info)
        newgameinfo = None
        for g in newgameinfolist:
            if (util.get_code(params['new_category']) == util.get_code(
                    g['category'])):
                newgameinfo = g
                break
        if newgameinfo is None:
            return "Did not find new category [" + params['new_category'] + ']'

        # Update best known time if necessary
        if (oldgameinfo.get('bk_seconds') is not None and
            (newgameinfo.get('bk_seconds') is None or
             oldgameinfo.get('bk_seconds') < newgameinfo.get('bk_seconds'))):
            newgameinfo['bk_seconds'] = oldgameinfo.get('bk_seconds')
            newgameinfo['bk_runner'] = oldgameinfo.get('bk_runner')
            newgameinfo['bk_datestr'] = oldgameinfo.get('bk_datestr')
            newgameinfo['bk_video'] = oldgameinfo.get('bk_video')
            newgameinfo['bk_updater'] = oldgameinfo.get('bk_updater')
            params['new_game_model'].info = json.dumps(newgameinfolist)
            res += 'Updated bkt<br>'

        if not memcache.flush_all():
            res += "Failed to flush memcache<br>"

        # Update num_pbs for old game, new game
        res += ('Previous num_pbs for old game, category = ' +
                str(old_game_model.num_pbs) + '<br>')
        res += ('Previous num_pbs for new game, category = ' +
                str(params['new_game_model'].num_pbs) + '<br>')
        try:
            q = db.Query(runs.Runs, projection=['username'], distinct=True)
            q.ancestor(runs.key())
            q.filter('game =', params['old_game'])
            q.filter('category =', params['old_category'])
            for run in q.run(limit=1000):
                old_game_model.num_pbs -= 1
                q2 = db.Query(runs.Runs)
                q2.ancestor(runs.key())
                q2.filter('game =', params['new_game'])
                q2.filter('category =', params['new_category'])
                q2.filter('username ='******'new_game_model'].num_pbs += 1
                else:
                    # Need to decrement runner's num_pbs
                    runner = self.get_runner(util.get_code(run.username))
                    if runner == self.OVER_QUOTA_ERROR:
                        return 'Over quota error'
                    runner.num_pbs -= 1
                    runner.put()
                    res += ("Updated " + run.username + " num_pbs from " +
                            str(runner.num_pbs + 1) + " to " +
                            str(runner.num_pbs) + "<br>")
        except apiproxy_errors.OverQuotaError, msg:
            logging.error(msg)
            return "Ran out of quota"