Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
kwanok committed Mar 14, 2024
1 parent 7d997fb commit 7ca9c55
Show file tree
Hide file tree
Showing 13 changed files with 868 additions and 8 deletions.
81 changes: 81 additions & 0 deletions web/league_entry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import asyncio
import os
import asyncpg
import aiohttp


class LeagueEntryCrawler:
def __init__(self):
self.session = aiohttp.ClientSession()

self.base_url = (
"https://kr.api.riotgames.com/lol/league/v4/entries/RANKED_SOLO_5x5"
)
self.api_key = os.environ.get("RIOT_API_KEY")
self.tiers = ["IRON", "BRONZE", "SILVER", "GOLD", "PLATINUM", "DIAMOND"]
self.divisions = ["I", "II", "III", "IV"]

async def run(self):
# for tier in self.tiers:
# for division in self.divisions:
# await self.get_league_entries(tier, division)

await self.get_league_entries(self.tiers[0], self.divisions[0])

await self.session.close()

async def get_league_entries(self, tier: str, division: str):
url = f"{self.base_url}/{tier}/{division}?api_key={self.api_key}"
page = 1

league_entries = await self._fetch(url + f"&page={page}")

summoners = []

while league_entries:
summoners.extend(league_entries)
print(f"Fetching page {page}")

page += 1
league_entries = await self._fetch(url + f"&page={page}")

print(summoners)

async def _fetch(self, url: str) -> list:
async with self.session.get(url) as response:
response = await self.session.get(url)

while response.status == 429:
retry_after = response.headers.get("Retry-After")
print(f"Retrying after {retry_after} seconds")

await asyncio.sleep(int(retry_after))
response = await self.session.get(url)

return await response.json()


async def main():
# crawler = LeagueEntryCrawler()
# await crawler.run()

db_user = os.environ.get("POSTGRES_USER")
db_password = os.environ.get("POSTGRES_PASSWORD")
db_host = "localhost"
db_port = os.environ.get("POSTGRES_PORT")
db_name = os.environ.get("POSTGRES_WEB_DB")

db_url = f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"

print(f"Connecting to database: {db_url}")

pool = await asyncpg.create_pool(db_url)

print("Connected to database")

await pool.close()


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
474 changes: 472 additions & 2 deletions web/poetry.lock

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions web/project/app/migrations/0002_champion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 5.0.2 on 2024-03-14 04:48

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("app", "0001_initial"),
]

operations = [
migrations.CreateModel(
name="Champion",
fields=[
("version", models.CharField(max_length=255)),
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("key", models.CharField(max_length=255)),
("name", models.CharField(max_length=255)),
("title", models.CharField(max_length=255)),
("blurb", models.TextField()),
("info", models.JSONField()),
("image", models.JSONField()),
("tags", models.JSONField()),
("partype", models.CharField(max_length=255)),
("stats", models.JSONField()),
],
),
]
25 changes: 25 additions & 0 deletions web/project/app/migrations/0003_summoner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 5.0.2 on 2024-03-14 05:48

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("app", "0002_champion"),
]

operations = [
migrations.CreateModel(
name="Summoner",
fields=[
(
"id",
models.CharField(max_length=100, primary_key=True, serialize=False),
),
("name", models.CharField(max_length=100)),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
],
),
]
47 changes: 47 additions & 0 deletions web/project/app/migrations/0004_leagueentry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Generated by Django 5.0.2 on 2024-03-14 05:49

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("app", "0003_summoner"),
]

operations = [
migrations.CreateModel(
name="LeagueEntry",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("tier", models.CharField(max_length=255)),
("rank", models.CharField(max_length=255)),
("league_points", models.IntegerField()),
("wins", models.IntegerField()),
("losses", models.IntegerField()),
("veteran", models.BooleanField()),
("inactive", models.BooleanField()),
("fresh_blood", models.BooleanField()),
("hot_streak", models.BooleanField()),
("queue_type", models.CharField(max_length=255)),
("league_id", models.CharField(max_length=255)),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"summoner",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="app.summoner"
),
),
],
),
]
44 changes: 44 additions & 0 deletions web/project/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,47 @@ class UserActivity(models.Model):

def __str__(self):
return f"{self.user.username} - {self.path}"


class Champion(models.Model):
version = models.CharField(max_length=255)
id = models.CharField(max_length=255, primary_key=True)
key = models.CharField(max_length=255)
name = models.CharField(max_length=255)
title = models.CharField(max_length=255)
blurb = models.TextField()
info = models.JSONField()
image = models.JSONField()
tags = models.JSONField()
partype = models.CharField(max_length=255)
stats = models.JSONField()


class Summoner(models.Model):
id = models.CharField(max_length=100, blank=False, null=False, primary_key=True)
name = models.CharField(max_length=100, blank=False, null=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

def __str__(self):
return self.name


class LeagueEntry(models.Model):
summoner = models.ForeignKey(Summoner, on_delete=models.CASCADE)
tier = models.CharField(max_length=255)
rank = models.CharField(max_length=255)
league_points = models.IntegerField()
wins = models.IntegerField()
losses = models.IntegerField()
veteran = models.BooleanField()
inactive = models.BooleanField()
fresh_blood = models.BooleanField()
hot_streak = models.BooleanField()
queue_type = models.CharField(max_length=255)
league_id = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

def __str__(self):
return f"{self.summoner.name} - {self.tier} {self.rank}"
53 changes: 53 additions & 0 deletions web/project/app/riot_assets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import requests
from app.models import Champion


class RiotAssets:
def __init__(self):
pass

def get_champion(self, champion_id: str) -> dict:
try:
champion = Champion.objects.get(key=champion_id)
except Champion.DoesNotExist:
champion = None

if champion is None:
self._upsert_champions()
champion = Champion.objects.get(key=champion_id)

return champion

def _fetch_all_champions(self) -> list:
champions = requests.get(
"https://ddragon.leagueoflegends.com/cdn/10.6.1/data/ko_KR/champion.json"
).json()["data"]
return champions

def _upsert_champions(self) -> None:
champions = self._fetch_all_champions()

for champion in champions:
data = champions[champion]
Champion.objects.update_or_create(
version=data["version"],
id=data["id"],
key=data["key"],
name=data["name"],
title=data["title"],
blurb=data["blurb"],
info=data["info"],
image=data["image"],
tags=data["tags"],
partype=data["partype"],
stats=data["stats"],
)

return None


riot_assets = RiotAssets()


def get_riot_assets():
return riot_assets
38 changes: 38 additions & 0 deletions web/project/app/riot_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
import requests


KR_API_HOST = "https://kr.api.riotgames.com"
ASIA_API_HOST = "https://asia.api.riotgames.com"


class RiotClient:
def __init__(self):
self.api_key = os.environ.get("RIOT_API_KEY")

def get_account_by_summoner_name(self, summoner_name) -> requests.Response:
url = f"{KR_API_HOST}/lol/summoner/v4/summoners/by-name/{summoner_name}"
response = requests.get(url, headers={"X-Riot-Token": self.api_key})
return response

def get_match_list(self, puuid: str) -> requests.Response:
url = f"{ASIA_API_HOST}/lol/match/v5/matches/by-puuid/{puuid}/ids"
response = requests.get(url, headers={"X-Riot-Token": self.api_key})
return response

def get_match(self, match_id: str) -> requests.Response:
url = f"{ASIA_API_HOST}/lol/match/v5/matches/{match_id}"
response = requests.get(url, headers={"X-Riot-Token": self.api_key})
return response

def get_champion_masteries_by_puuid_top(self, puuid: str) -> requests.Response:
url = f"{KR_API_HOST}/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top"
response = requests.get(url, headers={"X-Riot-Token": self.api_key})
return response


client = RiotClient()


def get_client():
return client
9 changes: 8 additions & 1 deletion web/project/app/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
from django.urls import path
from .views import index, get_account_by_summoner_name, recommend_ai, riot_txt
from .views import (
index,
get_account_by_summoner_name,
recommend_ai,
recommend_result,
riot_txt,
)

urlpatterns = [
path("riot.txt", riot_txt),
path("", index, name="home"),
path("summoner/", get_account_by_summoner_name, name="summoner"),
path("recommend-ai/", recommend_ai, name="recommend-ai"),
path("recommend-result/", recommend_result, name="recommend-result"),
]
18 changes: 15 additions & 3 deletions web/project/app/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import os
import uuid
from django.shortcuts import redirect, render
from django.core.handlers.wsgi import WSGIRequest
import requests
from django.contrib.auth.decorators import login_required

from users.models import SummonerInfo
from app.riot_client import get_client
from app.riot_assets import get_riot_assets


def riot_txt(request: WSGIRequest):
Expand Down Expand Up @@ -38,10 +42,9 @@ def get_account_by_summoner_name(request: WSGIRequest):

return render(request, "summoner/index.html", {"summoner": summoner_info})

url = f"https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-name/{summoner_name}"
api_key = os.environ.get("RIOT_API_KEY")
client = get_client()

response = requests.get(url, headers={"X-Riot-Token": api_key})
response = client.get_account_by_summoner_name(summoner_name)

if response.status_code == 200:
data = response.json()
Expand All @@ -65,3 +68,12 @@ def get_account_by_summoner_name(request: WSGIRequest):

def recommend_ai(request: WSGIRequest):
return render(request, "recommend/ai.html", {"user": request.user})


@login_required
def recommend_result(request: WSGIRequest):
return render(
request,
"recommend/result.html",
{"user": request.user},
)
Loading

0 comments on commit 7ca9c55

Please sign in to comment.