Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
kwanok committed Mar 18, 2024
1 parent db0ec15 commit 82ae9e3
Show file tree
Hide file tree
Showing 14 changed files with 303 additions and 90 deletions.
22 changes: 11 additions & 11 deletions web/league_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@ def __init__(self):
self.api_key = os.environ.get("RIOT_API_KEY")
self.tiers = ["IRON", "BRONZE", "SILVER", "GOLD", "PLATINUM", "DIAMOND"]
self.divisions = ["I", "II", "III", "IV"]

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

self.pool = None

async def create_db_pool(self):
self.pool = await asyncpg.create_pool(
user=self.db_user,
password=self.db_password,
host=self.db_host,
port=self.db_port,
database=self.db_name,
)
)

async def run(self):
await self.create_db_pool()
Expand All @@ -50,18 +50,19 @@ async def get_league_entries(self, tier: str, division: str):
league_entries = await self._fetch(url + f"&page={page}")

while league_entries:
print(f"Fetching {tier} {division} page {page}... entries: {len(league_entries)}")
print(
f"Fetching {tier} {division} page {page}... entries: {len(league_entries)}"
)
summoners = [
(
league_entry["summonerId"],
league_entry["summonerName"],
datetime.datetime.now(),
datetime.datetime.now(),
)
for league_entry
in league_entries
for league_entry in league_entries
]

async with self.pool.acquire() as connection:
async with connection.transaction():
await connection.executemany(
Expand Down Expand Up @@ -93,8 +94,7 @@ async def get_league_entries(self, tier: str, division: str):
datetime.datetime.now(),
datetime.datetime.now(),
)
for league_entry
in league_entries
for league_entry in league_entries
]
async with self.pool.acquire() as connection:
async with connection.transaction():
Expand Down Expand Up @@ -123,7 +123,7 @@ async def get_league_entries(self, tier: str, division: str):

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

return []

async def _fetch(self, url: str) -> list:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Generated by Django 5.0.2 on 2024-03-15 06:51

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("app", "0006_summoner_app_summone_name_9a15eb_idx"),
]

operations = [
migrations.AddField(
model_name="summoner",
name="account_id",
field=models.CharField(max_length=100, null=True),
),
migrations.AddField(
model_name="summoner",
name="profile_icon_id",
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name="summoner",
name="puuid",
field=models.CharField(max_length=100, null=True),
),
migrations.AddField(
model_name="summoner",
name="revision_date",
field=models.BigIntegerField(null=True),
),
migrations.AddField(
model_name="summoner",
name="summoner_level",
field=models.IntegerField(null=True),
),
]
18 changes: 11 additions & 7 deletions web/project/app/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Create your models here.

from django.contrib.postgres.search import SearchVector, SearchVectorField
from users.models import AppUser as User
from django.db import models

Expand Down Expand Up @@ -31,16 +30,19 @@ class Champion(models.Model):
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)
puuid = models.CharField(max_length=100, blank=False, null=True)
account_id = models.CharField(max_length=100, blank=False, null=True)
profile_icon_id = models.IntegerField(blank=False, null=True)
revision_date = models.BigIntegerField(blank=False, null=True)
summoner_level = models.IntegerField(blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

def __str__(self):
return self.name

class Meta:
indexes = [
models.Index(fields=['name'])
]
indexes = [models.Index(fields=["name"])]


class LeagueEntry(models.Model):
Expand All @@ -61,8 +63,10 @@ class LeagueEntry(models.Model):

def __str__(self):
return f"{self.summoner.name} - {self.tier} {self.rank}"

class Meta:
constraints = [
models.UniqueConstraint(fields=['summoner', 'queue_type'], name='unique_league_entry')
models.UniqueConstraint(
fields=["summoner", "queue_type"], name="unique_league_entry"
)
]
7 changes: 7 additions & 0 deletions web/project/app/riot_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ def get_champion_masteries_by_puuid_top(self, puuid: str) -> requests.Response:
response = requests.get(url, headers={"X-Riot-Token": self.api_key})
return response

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


client = RiotClient()

Expand Down
3 changes: 2 additions & 1 deletion web/project/app/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from app.models import Summoner, LeagueEntry
from rest_framework import serializers


class SummonerSerializer(serializers.ModelSerializer):
class Meta:
model = Summoner
Expand All @@ -10,4 +11,4 @@ class Meta:
class LeagueEntrySerializer(serializers.ModelSerializer):
class Meta:
model = LeagueEntry
fields = "__all__"
fields = "__all__"
15 changes: 12 additions & 3 deletions web/project/app/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from django.urls import path, include
from rest_framework import routers

from project import settings
from .views import (
index,
get_account_by_summoner_name,
recommend_ai,
recommend_result,
riot_txt,
search_summoners_by_name,
save_summoner,
)

urlpatterns = [
Expand All @@ -15,6 +17,13 @@
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"),
path("summoners/search/", search_summoners_by_name, name="search-summoners-by-name"),
path("__debug__/", include("debug_toolbar.urls")),
path(
"summoners/search/", search_summoners_by_name, name="search-summoners-by-name"
),
path("profile/summoner", save_summoner, name="save-summoner-info"),
]

if settings.DEBUG:
import debug_toolbar

urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns
100 changes: 71 additions & 29 deletions web/project/app/views.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import os
import uuid
from django.http import JsonResponse
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.models import Summoner
from rest_framework.decorators import api_view
from app.riot_client import get_client
from app.riot_assets import get_riot_assets
from rest_framework import viewsets
from app.serializers import SummonerSerializer, LeagueEntrySerializer
from app.models import Summoner, LeagueEntry
from app.models import LeagueEntry
from users.models import AppUser


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

def get_account_by_summoner_name(request: WSGIRequest):
summoner_name = request.GET.get("summoner_name")
if SummonerInfo.objects.filter(name=summoner_name).exists():
summoner_info = SummonerInfo.objects.get(name=summoner_name)
if Summoner.objects.filter(name=summoner_name).exists():
summoner = Summoner.objects.get(name=summoner_name)

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

client = get_client()

Expand All @@ -54,7 +50,7 @@ def get_account_by_summoner_name(request: WSGIRequest):
if response.status_code == 200:
data = response.json()

summoner_info = SummonerInfo(
summoner = Summoner(
id=data["id"],
account_id=data["accountId"],
profile_icon_id=data["profileIconId"],
Expand All @@ -64,9 +60,9 @@ def get_account_by_summoner_name(request: WSGIRequest):
summoner_level=data["summonerLevel"],
)

summoner_info.save()
summoner.save()

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

return render(request, "summoner/index.html", {"error": response.json()})

Expand All @@ -90,40 +86,86 @@ def search_summoners_by_name(request: WSGIRequest):
count = request.GET.get("count")
if not name or not count:
return JsonResponse({"error": "name, count are required"}, status=400)

try:
count = int(count)
except ValueError:
return JsonResponse({"error": "count must be an integer"}, status=400)

if count > 10:
return JsonResponse({"error": "count must be less than or equal to 10"}, status=400)

return JsonResponse(
{"error": "count must be less than or equal to 10"}, status=400
)

queryset = Summoner.objects.filter(name__startswith=name)[:count]
serializer = SummonerSerializer(queryset, many=True)

summoners = serializer.data

summoner_ids = [
summoner["id"]
for summoner in serializer.data
]


summoner_ids = [summoner["id"] for summoner in serializer.data]

queryset = LeagueEntry.objects.filter(summoner_id__in=summoner_ids)
serializer = LeagueEntrySerializer(queryset, many=True)

league_entries = serializer.data


for summoner in summoners:
if summoner["puuid"] is None:
new_summoner = get_client().get_summoner_by_encrypted_summoner_id(
summoner["id"]
)

if new_summoner.status_code == 200:
summoner["puuid"] = new_summoner.json()["puuid"]
summoner["account_id"] = new_summoner.json()["accountId"]
summoner["profile_icon_id"] = new_summoner.json()["profileIconId"]
summoner["revision_date"] = new_summoner.json()["revisionDate"]
summoner["summoner_level"] = new_summoner.json()["summonerLevel"]

Summoner.objects.filter(id=summoner["id"]).update(
puuid=summoner["puuid"],
account_id=summoner["account_id"],
profile_icon_id=summoner["profile_icon_id"],
revision_date=summoner["revision_date"],
summoner_level=summoner["summoner_level"],
)

result = [
{
"summoner": summoner,
"league_entries": [
league_entry
for league_entry in league_entries
if league_entry["summoner"] == summoner["id"]
]
],
}
for summoner in summoners
]

return JsonResponse(result, safe=False)

return JsonResponse(result, safe=False)


@api_view(["POST"])
def save_summoner(request: WSGIRequest):
me = request.user

summoner_id = request.data["summoner_id"]

if not summoner_id:
return JsonResponse({"error": "id is required"}, status=400)

summoner = Summoner.objects.get(id=summoner_id)

AppUser.objects.filter(id=me.id).update(summoner=summoner)

return JsonResponse(
{
"name": summoner.name,
"puuid": summoner.puuid,
"level": summoner.summoner_level,
"account_id": summoner.account_id,
"profile_icon_id": summoner.profile_icon_id,
"revision_date": summoner.revision_date,
},
safe=False,
)
8 changes: 4 additions & 4 deletions web/project/project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

# SECURITY WARNING: don't run with debug turned on in production!
if ENV == "production":
DEBUG = True
DEBUG = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SESSION_COOKIE_SECURE = True
Expand Down Expand Up @@ -177,10 +177,10 @@
AUTH_USER_MODEL = "users.AppUser"

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 10,
}

INTERNAL_IPS = [
"127.0.0.1",
]
]
Loading

0 comments on commit 82ae9e3

Please sign in to comment.