summaryrefslogtreecommitdiff
path: root/gamelocker/api.py
blob: dee307d65421d3adca6e7001f7a9fb6486942b60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/python
# -*- coding: utf-8 -*-
# TODO: generate documentation

"""
requests.api

This module implements the Gamelocker API.
"""

import inspect
import requests
import requests_jwt
import gamelocker.datatypes


class Gamelocker(object):
    """Implementation of the Gamelocker API.

    :param apikey: API key used.
    :type apikey: str
    :param title: Title data is fetched for.
    :type title: str
    """

    def __init__(self, apikey, datacenter="dc01"):
        """Constructs a :class:`Gamelocker <Gamelocker>`.

        :param apikey: API key to authenticate with.
        :type apikey: str
        :param datacenter: (optional) API endpoint datacenter to use.
        :type datacenter: str
        :return: :class:`Gamelocker <Gamelocker>` object
        :rtype: gamelocker.Gamelocker

        Usage::

            >>> import gamelocker
            >>> gamelocker.Gamelocker("getoffmylawn").status()
            "v1.0.5"
        """

        self.apikey = apikey
        self._apiurl = "https://api." + datacenter + ".gamelockerapp.com/"
        self.title = ""

    def _req(self, method, params=None):
        """Sends a GET request to the API endpoint.

        :param method: Method to query.
        :type method: str
        :param params: (optional) Parameters to send.
        :type params: dict
        :return: Parsed JSON object.
        :rtype: dict
        """
        headers = {
            "Authorization": "Bearer " + self.apikey,
            "X-TITLE-ID": self.title,
            "Accept": "application/vnd.api+json"
        }
        http = requests.get(self._apiurl + method,
                            headers=headers,
                            params=params)
        http.raise_for_status()
        return http.json()

    def _get(self, endpoint, elid="", params=None):
        """Returns an object or a list of objects from the API.

        :param endpoint: API slug to use.
        :type endpoint: str
        :param elid: (optional) ID of the object to query for.
        :type elid: str
        :param params: (optional) Parameters to pass with the http request.
        :type params: dict
        :return: Data object.
        :rtype: :class:`janus.DataMessage`
        """
        data = self._req(endpoint + "/" + elid, params=params)

        # collect related data
        includes = []
        if "included" in data:
            for incl in data["included"]:
                element = gamelocker.datatypes.data_to_object(incl)
                includes.append(element)

        # main data object
        if isinstance(data["data"], (list, tuple)):
            elements = []
            for dat in data["data"]:
                element = gamelocker.datatypes.data_to_object(dat)
                # link related data
                element = gamelocker.datatypes.link_to_object(
                    element, includes)
                elements.append(element)
            return elements
        else:
            element = gamelocker.datatypes.data_to_object(data["data"])
            # link related data
            element = gamelocker.datatypes.link_to_object(element, includes)
            return element

    def vainglory(self):
        """Sets title to Vainglory.

        :return: :class:`Gamelocker <Gamelocker>` object
        :rtype: gamelocker.Gamelocker
        """
        self.title = "semc-vainglory"
        return self

    def status(self):
        """Returns the API status JSON string.

        :return: API status JSON.
        :rtype: str
        """
        return self._req("status")

    def match(self, elid):
        """Returns a match.

        :param elid: ID of the match.
        :type elid: str
        :return: A match with the given ID.
        :rtype: :class:`Match`
        """
        return self._get("matches", elid)

    def player(self, elid):
        """Returns a player.

        :param elid: ID of the player.
        :type elid: str
        :return: A player with the given ID.
        :rtype: :class:`Player`
        """
        return self._get("players", elid)

    def matches(self, limit=None, offset=None, sort=None):
        """Returns a list of recent matches.

        :param limit: Maximum number of matches to return.
        :type limit: int
        :param offset: Offset parameter for pagination.
        :type limit: int
        :param sort: Sort query to use.
        :type sort: str
        :return: List of matches.
        :rtype: list of dict
        """
        params = dict()
        # TODO: deprecate by ?limit=x&offset=y soon
        if limit:
            params["page[limit]"] = limit
        if offset:
            params["page[offset]"] = offset
        if sort:  # TODO make this nice and usable
            params["sort"] = sort
        return self._get("matches", params=params)