summaryrefslogtreecommitdiff
path: root/api.py
blob: 86c7e3581b539bf4652e375c3bd46edea6147df8 (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
#!/usr/bin/python

import asyncio
import os
import logging

import database
import crawler


db = database.Database()


async def crawl_region(region):
    """Get matches from a region and insert them
       until the DB is up to date. Repeat after five minutes."""
    api = crawler.Crawler()

    # fetch until exhausted
    while True:
        try:
            last_match_update = (await db.select(
                """
                SELECT data->'attributes'->>'createdAt' AS created
                FROM match
                WHERE data->'attributes'->>'shardId'='""" + region + """'
                ORDER BY data->'attributes'->>'createdAt' DESC LIMIT 1
                """)
            )[0]["created"]
        except:
            last_match_update = "2017-02-05T01:01:01Z"

        logging.info("%s: fetching matches since %s",
                     region, last_match_update)

        # wait for http requests
        matches = await api.matches_since(last_match_update,
                                          region=region,
                                          params={"page[limit]": 50})
        if len(matches) > 0:
            logging.debug("%s: %s objects", region, len(matches))
        else:
            logging.debug("%s: no objects, stopping", region)
            break
        # wait for db inserts
        await db.upsert(matches, True)

    logging.debug("%s: going to sleep", region)
    await asyncio.sleep(300)
    asyncio.ensure_future(crawl_region(region))  # restart self


async def start_crawlers():
    """Start the tasks that pull the data."""
    # TODO: insert API version (force update if changed)
    # TODO: create database indices

    for region in ["na", "eu"]:
        # fire workers
        asyncio.ensure_future(crawl_region(region))


logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.run_until_complete(db.connect(
    host=os.environ["POSTGRESQL_HOST"],
    port=os.environ["POSTGRESQL_PORT"],
    user=os.environ["POSTGRESQL_USER"],
    password=os.environ["POSTGRESQL_PASSWORD"],
    database=os.environ["POSTGRESQL_DB"]
))
loop.run_until_complete(
    start_crawlers()
)
loop.run_forever()