예제 #1
0
def get_game_api_page(game_ids, page="1", query_type="games"):
    """Read a single page of games from the API and return the response

    Args:
        game_ids (list): list of game IDs, the ID type is determined by `query_type`
        page (str): Page of results to get
        query_type (str): Type of the IDs in game_ids, by default 'games' queries
                          games by their Lutris slug. 'gogid' can also be used.
    """
    url = settings.SITE_URL + "/api/games"

    if int(page) > 1:
        url += "?page={}".format(page)

    response = http.Request(url, headers={"Content-Type": "application/json"})
    if game_ids:
        payload = json.dumps({query_type: game_ids, "page": page}).encode("utf-8")
    else:
        raise ValueError("No game id provided will fetch all games from the API")
    try:
        response.get(data=payload)
    except http.HTTPError as ex:
        logger.error("Unable to get games from API: %s", ex)
        return None
    response_data = response.json
    logger.debug("Loaded %s games from page %s", len(response_data.get("results")), page)

    if not response_data:
        logger.warning("Unable to get games from API, status code: %s", response.status_code)
        return None
    return response_data
예제 #2
0
def search_games(query):
    if not query:
        return []
    query = query.lower().strip()[:32]
    if query == "open source games":
        url = "/api/bundles/open-source"
    elif query == "free to play games":
        url = "/api/bundles/free-to-play"
    else:
        url = "/api/games?%s" % urllib.parse.urlencode({"search": query})
    response = http.Request(settings.SITE_URL + url, headers={"Content-Type": "application/json"})
    try:
        response.get()
    except http.HTTPError as ex:
        logger.error("Unable to get games from API: %s", ex)
        return None
    response_data = response.json
    if "bundles" in url:
        api_games = response_data.get("games", [])
    else:
        api_games = response_data.get("results", [])
    for index, game in enumerate(api_games, 1):
        game["id"] = index * -1
        game["installed"] = 1
        game["runner"] = None
        game["platform"] = None
        game["lastplayed"] = None
        game["installed_at"] = None
        game["playtime"] = None
    return api_games
예제 #3
0
    def _iter_remote_runtimes():
        request = http.Request(RUNTIME_URL)
        response = request.get()
        runtimes = response.json or []
        for runtime in runtimes:

            # Skip 32bit runtimes on 64 bit systems except the lib32 one
            if (runtime["architecture"] == "i386"
                    and system.LINUX_SYSTEM.is_64_bit
                    and runtime["name"] != "lib32"):
                logger.debug(
                    "Skipping runtime %s for %s",
                    runtime["name"],
                    runtime["architecture"],
                )
                continue

            # Skip 64bit runtimes on 32 bit systems
            if runtime[
                    "architecture"] == "x86_64" and not system.LINUX_SYSTEM.is_64_bit:
                logger.debug(
                    "Skipping runtime %s for %s",
                    runtime["name"],
                    runtime["architecture"],
                )
                continue

            yield runtime
예제 #4
0
    def _iter_remote_runtimes():
        request = http.Request(settings.RUNTIME_URL)
        try:
            response = request.get()
        except http.HTTPError as ex:
            logger.error("Failed to get runtimes: %s", ex)
            return
        runtimes = response.json or []
        for runtime in runtimes:

            # Skip 32bit runtimes on 64 bit systems except the main runtime
            if (
                runtime["architecture"] == "i386" and system.LINUX_SYSTEM.is_64_bit
                and not runtime["name"].startswith(("Ubuntu", "lib32"))
            ):
                logger.debug(
                    "Skipping runtime %s for %s",
                    runtime["name"],
                    runtime["architecture"],
                )
                continue

            # Skip 64bit runtimes on 32 bit systems
            if runtime["architecture"] == "x86_64" and not system.LINUX_SYSTEM.is_64_bit:
                logger.debug(
                    "Skipping runtime %s for %s",
                    runtime["name"],
                    runtime["architecture"],
                )
                continue

            yield runtime
예제 #5
0
 def async_download(self, url, queue, stop_request=None):
     headers = {}
     if self.referer:
         headers["Referer"] = self.referer
     request = http.Request(url,
                            stop_request=stop_request,
                            headers=headers,
                            thread_queue=queue)
     return request.get()
예제 #6
0
파일: api.py 프로젝트: muzena/lutris
def get_http_response(url, payload):
    response = http.Request(url, headers={"Content-Type": "application/json"})
    try:
        response.get(data=payload)
    except http.HTTPError as ex:
        logger.error("Unable to get games from API: %s", ex)
        return None
    if response.status_code != 200:
        logger.error("API call failed: %s", response.status_code)
        return None
    return response.json
예제 #7
0
 def get_runtime_components(self):
     """Fetch runtime components from the API"""
     request = http.Request(settings.RUNTIME_URL + "/" + self.name)
     try:
         response = request.get()
     except http.HTTPError as ex:
         logger.error("Failed to get components: %s", ex)
         return []
     if not response.json:
         return []
     return response.json.get("components", [])
예제 #8
0
def get_library():
    """Return the remote library as a list of dicts."""
    credentials = read_api_key()
    if not credentials:
        return []
    url = settings.SITE_URL + "/api/games/library/%s" % credentials["username"]
    request = http.Request(url, headers={"Authorization": "Token " + credentials["token"]})
    response = request.get()
    response_data = response.json
    if response_data:
        return response_data["games"]
    return []
예제 #9
0
 def check_update():
     """Verify availability of client update."""
     version_request = http.Request("https://lutris.net/version")
     version_request.get()
     version = version_request.content
     if version:
         latest_version = settings.read_setting("latest_version")
         if version > (latest_version or settings.VERSION):
             dialogs.ClientUpdateDialog()
             # Store latest version seen to avoid showing
             # the dialog more than once.
             settings.write_setting("latest_version", version)
예제 #10
0
파일: api.py 프로젝트: muzena/lutris
def get_bundle(bundle):
    """Retrieve a lutris bundle from the API"""
    url = "/api/bundles/%s" % bundle
    response = http.Request(settings.SITE_URL + url,
                            headers={"Content-Type": "application/json"})
    try:
        response.get()
    except http.HTTPError as ex:
        logger.error("Unable to get bundle from API: %s", ex)
        return None
    response_data = response.json
    return response_data.get("games", [])
예제 #11
0
파일: api.py 프로젝트: muzena/lutris
def search_games(query):
    if not query:
        return []
    query = query.lower().strip()[:32]
    url = "/api/games?%s" % urllib.parse.urlencode({"search": query})
    response = http.Request(settings.SITE_URL + url,
                            headers={"Content-Type": "application/json"})
    try:
        response.get()
    except http.HTTPError as ex:
        logger.error("Unable to get games from API: %s", ex)
        return None
    response_data = response.json
    return response_data.get("results", [])
예제 #12
0
def get_user_info():
    """Retrieves the user info to cache it locally"""
    credentials = read_api_key()
    if not credentials:
        return []
    url = settings.SITE_URL + "/api/users/me"
    request = http.Request(url, headers={"Authorization": "Token " + credentials["token"]})
    response = request.get()
    account_info = response.json
    if not account_info:
        logger.warning("Unable to fetch user info for %s", credentials["username"])
    with open(USER_INFO_FILE_PATH, "w") as token_file:
        json.dump(account_info, token_file, indent=2)
    if account_info.get("avatar_url"):
        resources.download_media(account_info["avatar_url"], USER_ICON_FILE_PATH)
예제 #13
0
파일: api.py 프로젝트: Tom-Todd/lutris
def get_library():
    """Return the remote library as a list of dicts."""
    logger.debug("Fetching game library")
    credentials = read_api_key()
    if not credentials:
        return []
    username = credentials["username"]
    token = credentials["token"]
    url = settings.SITE_URL + "/api/games/library/%s" % username
    headers = {'Authorization': 'Token ' + token}
    request = http.Request(url, headers=headers)
    response = request.get()
    response_data = response.json
    if response_data:
        return response_data['games']
    return []
예제 #14
0
 def get_library(self):
     """Return the remote library as a list of dicts."""
     credentials = read_api_key()
     if not credentials:
         return []
     url = settings.SITE_URL + "/api/games/library/%s" % urllib.parse.quote(credentials["username"])
     request = http.Request(url, headers={"Authorization": "Token " + credentials["token"]})
     try:
         response = request.get()
     except http.HTTPError as ex:
         logger.error("Unable to load library: %s", ex)
         return []
     response_data = response.json
     if response_data:
         return response_data["games"]
     return []
예제 #15
0
def search_games(query):
    if not query:
        return {}
    query = query.lower().strip()[:255]
    url = "/api/games?%s" % urllib.parse.urlencode({
        "search": query,
        "with-installers": True
    })
    response = http.Request(settings.SITE_URL + url,
                            headers={"Content-Type": "application/json"})
    try:
        response.get()
    except http.HTTPError as ex:
        logger.error("Unable to get games from API: %s", ex)
        return {}
    return response.json
예제 #16
0
def get_games(game_slugs=None, page=1):
    url = settings.SITE_URL + "/api/games"

    if int(page) > 1:
        url += "?page={}".format(page)

    response = http.Request(url, headers={'Content-Type': 'application/json'})
    if game_slugs:
        payload = json.dumps({
            'games': game_slugs,
            'page': page
        }).encode('utf-8')
    else:
        payload = None
    response.get(data=payload)
    return response.json
예제 #17
0
파일: lutris.py 프로젝트: l10n-tw/lutris
def download_lutris_media(slug):
    """Downloads the banner and icon for a given lutris game"""
    url = settings.SITE_URL + "/api/games/%s" % slug
    request = http.Request(url)
    try:
        response = request.get()
    except http.HTTPError as ex:
        logger.debug("Unable to load %s: %s", slug, ex)
        return
    response_data = response.json
    icon_url = response_data.get("icon_url")
    if icon_url:
        download_icons({slug: icon_url}, LutrisIcon())

    banner_url = response_data.get("banner_url")
    if banner_url:
        download_icons({slug: banner_url}, LutrisBanner())
예제 #18
0
파일: runtime.py 프로젝트: Yilnis/lutris-1
    def _iter_runtimes(self):
        request = http.Request(RUNTIME_URL)
        response = request.get()
        runtimes = response.json or []
        for runtime in runtimes:

            # Skip 32bit runtimes on 64 bit systems except the lib32 one
            if (runtime['architecture'] == 'i386' and system.is_64bit
                    and runtime['name'] != 'lib32'):
                logger.debug('Skipping runtime %s for %s', runtime['name'],
                             runtime['architecture'])
                continue

            # Skip 64bit runtimes on 32 bit systems
            if (runtime['architecture'] == 'x86_64' and not system.is_64bit):
                logger.debug('Skipping runtime %s for %s', runtime['name'],
                             runtime['architecture'])
                continue

            yield runtime
예제 #19
0
def get_game_installers(game_slug, revision=None):
    """Get installers for a single game"""
    if not game_slug:
        raise ValueError("No game_slug provided. Can't query an installer")
    if revision:
        installer_url = settings.INSTALLER_REVISION_URL % (game_slug, revision)
    else:
        installer_url = settings.INSTALLER_URL % game_slug

    logger.debug("Fetching installer %s", installer_url)
    request = http.Request(installer_url)
    request.get()
    response = request.json
    if response is None:
        raise RuntimeError("Couldn't get installer at %s" % installer_url)

    if not revision:
        return response["results"]
    # Revision requests return a single installer
    return [response]
예제 #20
0
def search_games(query):
    query = query.lower().strip()[:32]
    url = settings.SITE_URL + "/api/games?%s" % urllib.parse.urlencode(
        {"search": query})
    response = http.Request(url, headers={"Content-Type": "application/json"})
    try:
        response.get()
    except http.HTTPError as ex:
        logger.error("Unable to get games from API: %s", ex)
        return None
    response_data = response.json
    api_games = response_data.get("results", [])
    for index, game in enumerate(api_games, 1):
        game["id"] = index * -1
        game["installed"] = 1
        game["runner"] = None
        game["platform"] = None
        game["lastplayed"] = None
        game["installed_at"] = None
        game["playtime"] = None
    return api_games
예제 #21
0
파일: api.py 프로젝트: Yilnis/lutris-1
def get_games(game_slugs=None, page=1):
    url = settings.SITE_URL + "/api/games"

    if int(page) > 1:
        url += "?page={}".format(page)

    response = http.Request(url, headers={'Content-Type': 'application/json'})
    if game_slugs:
        payload = json.dumps({
            'games': game_slugs,
            'page': page
        }).encode('utf-8')
    else:
        payload = None
    response.get(data=payload)
    response_data = response.json

    if not response_data:
        logger.warning('Unable to get games from API')
        return None

    results = response_data.get('results', [])
    while response_data.get('next'):
        page_match = re.search(r'page=(\d+)', response_data['next'])
        if page_match:
            page = page_match.group(1)
        else:
            logger.error("No page found in %s", response_data['next'])
            break
        page_result = get_games(game_slugs=game_slugs, page=page)
        if not page_result:
            logger.warning("Unable to get response for page %s", page)
            break
        else:
            results += page_result

    return results
예제 #22
0
파일: api.py 프로젝트: Tom-Todd/lutris
def get_game_api_page(game_slugs, page):
    """Read a single page of games from the API and return the response"""
    url = settings.SITE_URL + "/api/games"

    if int(page) > 1:
        url += "?page={}".format(page)

    response = http.Request(url, headers={'Content-Type': 'application/json'})
    if game_slugs:
        payload = json.dumps({
            'games': game_slugs,
            'page': page
        }).encode('utf-8')
    else:
        payload = None
    response.get(data=payload)
    response_data = response.json
    logger.info("Loaded %s games from page %s",
                len(response_data.get('results')), page)

    if not response_data:
        logger.warning('Unable to get games from API')
        return None
    return response_data
예제 #23
0
def get_runners(runner_name):
    """Return the available runners for a given runner name"""
    api_url = settings.SITE_URL + "/api/runners/" + runner_name
    response = http.Request(api_url).get()
    return response.json
예제 #24
0
파일: downloader.py 프로젝트: steevp/lutris
 def async_download(self, url, queue, stop_request=None):
     request = http.Request(url,
                            stop_request=stop_request,
                            thread_queue=queue)
     return request.get()
예제 #25
0
def get_runners(runner_name):
    api_url = settings.SITE_URL + "/api/runners/" + runner_name
    response = http.Request(api_url).get()
    return response.json