time_tracker

Overview

This particular file allows for the creation of a TimeTracker object, which contains methods that allow an integration developer to keep track of the user’s play time for games in their library.

It is the developer’s responsibility to do the following:

  • Store the user’s play time cache for another session. A good implementation for doing so is to both save the play time cache to the persistent_cache and to write it locally to a file on the user’s disk. This ensures that the user’s play time is safe if the persistent_cache is erased (i.e., the user loses authentication). An example is shown below.

async def shutdown(self):
    if self.game_time_cache:  # Do not overwrite the file if the cache is empty. This prevents accidentally erasing
                              # the user's previous game time cache and resetting their play time.
        file = open("PlayTimeCache.txt", "w+")
        # Consider informing the user to not modify the game time cache file.
        file.write("# DO NOT EDIT THIS FILE\n")
        file.write(self.game_time_tracker.get_time_cache_hex())
        file.close()
    await self._http_client.close()
    await super().shutdown()

def game_times_import_complete(self):
    self.game_time_cache = self.game_time_tracker.get_time_cache()
    self.persistent_cache["game_time_cache"] = self.game_time_tracker.get_time_cache_hex()
    self.push_cache()
  • Retrieve the user’s play time cache from the previous session. Supposing that the cache was saved according to the previous example, a good implementation would be to retrieve it from the persistent_cache if possible, and then fall back to the locally stored file if it cannot be found there. In general, it is best to use a locally stored file to retrieve the game time cache only if all other methods fail. An example is shown below.

def handshake_complete(self):
    # Check the persistent cache first.
    if "game_time_cache" in self.persistent_cache:
        self.game_time_cache = pickle.loads(bytes.fromhex(self.persistent_cache["game_time_cache"]))
    # If the game time cache cannot be found in the persistent cache, then check a local file for it.
    else:
        try:
            file = open("PlayTimeCache.txt", "r")
            for line in file.readlines():
                if line[:1] != "#":
                    self.game_time_cache = pickle.loads(bytes.fromhex(line))
                    break
        except FileNotFoundError:
            # If the file does not exist, then use an empty game time cache.
            self.game_time_tracker = TimeTracker()
            return
    self.game_time_tracker = TimeTracker(game_time_cache=self.game_time_cache)

Documentation