1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-24 03:54:20 +00:00

Risolto il problema delle sessioni!

This commit is contained in:
Steffo 2017-10-30 10:46:37 +01:00
parent 2e89de4445
commit c1436ffa05
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS.
GPG key ID: C27544372FBB445D
7 changed files with 112 additions and 52 deletions

41
db.py
View file

@ -8,6 +8,7 @@ from errors import RequestError, NotFoundError, AlreadyExistingError
import re import re
import enum import enum
from discord import User as DiscordUser from discord import User as DiscordUser
from telegram import User as TelegramUser
# Init the config reader # Init the config reader
import configparser import configparser
@ -19,9 +20,6 @@ engine = create_engine(config["Database"]["database_uri"])
Base = declarative_base(bind=engine) Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine) Session = sessionmaker(bind=engine)
# Create a new default session
session = Session()
class Royal(Base): class Royal(Base):
__tablename__ = "royals" __tablename__ = "royals"
@ -29,7 +27,7 @@ class Royal(Base):
username = Column(String, unique=True, nullable=False) username = Column(String, unique=True, nullable=False)
@staticmethod @staticmethod
def create(username): def create(session: Session, username: str):
r = session.query(Royal).filter_by(username=username).first() r = session.query(Royal).filter_by(username=username).first()
if r is not None: if r is not None:
raise AlreadyExistingError(repr(r)) raise AlreadyExistingError(repr(r))
@ -50,6 +48,24 @@ class Telegram(Base):
last_name = Column(String) last_name = Column(String)
username = Column(String) username = Column(String)
@staticmethod
def create(session: Session, royal_username, telegram_user: TelegramUser):
t = session.query(Telegram).filter_by(telegram_id=telegram_user.id).first()
if t is not None:
raise AlreadyExistingError(repr(t))
r = session.query(Royal).filter(Royal.username == royal_username).first()
if r is None:
raise NotFoundError("No Royal exists with that username")
t = session.query(Telegram).filter(Telegram.royal_id == r.id).first()
if t is not None:
raise AlreadyExistingError(repr(t))
return Telegram(royal=r,
telegram_id=telegram_user.id,
first_name=telegram_user.first_name,
last_name=telegram_user.last_name,
username=telegram_user.username)
def __repr__(self): def __repr__(self):
return f"<Telegram {self.id}>" return f"<Telegram {self.id}>"
@ -86,7 +102,7 @@ class Steam(Base):
return f"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/{self.avatar_hex[0:2]}/{self.avatar_hex}.jpg" return f"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/{self.avatar_hex[0:2]}/{self.avatar_hex}.jpg"
@staticmethod @staticmethod
def create(royal_id, steam_id): def create(session: Session, royal_id: int, steam_id: str):
s = session.query(Steam).get(steam_id) s = session.query(Steam).get(steam_id)
if s is not None: if s is not None:
raise AlreadyExistingError(repr(s)) raise AlreadyExistingError(repr(s))
@ -160,7 +176,7 @@ class RocketLeague(Base):
return f"<RocketLeague {self.steam_id}>" return f"<RocketLeague {self.steam_id}>"
@staticmethod @staticmethod
def create(steam_id): def create(session: Session, steam_id: str):
rl = session.query(RocketLeague).get(steam_id) rl = session.query(RocketLeague).get(steam_id)
if rl is not None: if rl is not None:
raise AlreadyExistingError(repr(rl)) raise AlreadyExistingError(repr(rl))
@ -242,7 +258,7 @@ class Dota(Base):
losses = Column(Integer, nullable=False) losses = Column(Integer, nullable=False)
@staticmethod @staticmethod
def create(steam_id): def create(session: Session, steam_id: int):
d = session.query(Dota).get(steam_id) d = session.query(Dota).get(steam_id)
if d is not None: if d is not None:
raise AlreadyExistingError(repr(d)) raise AlreadyExistingError(repr(d))
@ -314,7 +330,7 @@ class LeagueOfLegends(Base):
twtr_rank = Column(Enum(RomanNumerals)) twtr_rank = Column(Enum(RomanNumerals))
@staticmethod @staticmethod
def create(royal_id, summoner_name=None, summoner_id=None): def create(session: Session, royal_id, summoner_name=None, summoner_id=None):
if summoner_name: if summoner_name:
lol = session.query(LeagueOfLegends).filter(LeagueOfLegends.summoner_name == summoner_name).first() lol = session.query(LeagueOfLegends).filter(LeagueOfLegends.summoner_name == summoner_name).first()
elif summoner_id: elif summoner_id:
@ -395,7 +411,7 @@ class Osu(Base):
mania_pp = Column(Float) mania_pp = Column(Float)
@staticmethod @staticmethod
def create(royal_id, osu_name): def create(session: Session, royal_id, osu_name):
o = session.query(Osu).filter(Osu.osu_name == osu_name).first() o = session.query(Osu).filter(Osu.osu_name == osu_name).first()
if o is not None: if o is not None:
raise AlreadyExistingError(repr(o)) raise AlreadyExistingError(repr(o))
@ -456,7 +472,7 @@ class Discord(Base):
return f"<Discord user {self.discord_id}>" return f"<Discord user {self.discord_id}>"
@staticmethod @staticmethod
def create(royal_username, discord_user: DiscordUser): def create(session: Session, royal_username, discord_user: DiscordUser):
d = session.query(Discord).filter(Discord.discord_id == discord_user.id).first() d = session.query(Discord).filter(Discord.discord_id == discord_user.id).first()
if d is not None: if d is not None:
raise AlreadyExistingError(repr(d)) raise AlreadyExistingError(repr(d))
@ -502,7 +518,7 @@ class Overwatch(Base):
return f"<Overwatch {self}>" return f"<Overwatch {self}>"
@staticmethod @staticmethod
def create(royal_id, battletag, discriminator=None): def create(session: Session, royal_id, battletag, discriminator=None):
if discriminator is None: if discriminator is None:
battletag, discriminator = battletag.split("#", 1) battletag, discriminator = battletag.split("#", 1)
o = session.query(Overwatch).filter_by(battletag=battletag, discriminator=discriminator).first() o = session.query(Overwatch).filter_by(battletag=battletag, discriminator=discriminator).first()
@ -565,6 +581,7 @@ class Diario(Base):
@staticmethod @staticmethod
def import_from_json(file): def import_from_json(file):
import json import json
session = Session()
file = open(file, "r") file = open(file, "r")
j = json.load(file) j = json.load(file)
for entry in j: for entry in j:
@ -578,9 +595,9 @@ class Diario(Base):
print(d) print(d)
session.add(d) session.add(d)
session.commit() session.commit()
session.close()
# If run as script, create all the tables in the db # If run as script, create all the tables in the db
if __name__ == "__main__": if __name__ == "__main__":
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
session.close()

View file

@ -13,6 +13,9 @@ import configparser
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read("config.ini") config.read("config.ini")
# Open a new postgres session
session = db.Session()
# Init the discord bot # Init the discord bot
client = discord.Client() client = discord.Client()
@ -25,14 +28,15 @@ async def on_message(message: discord.Message):
await client.send_message(message.channel, "⚠️ Non hai specificato un username!") await client.send_message(message.channel, "⚠️ Non hai specificato un username!")
return return
try: try:
d = db.Discord.create(royal_username=username, d = db.Discord.create(session,
royal_username=username,
discord_user=message.author) discord_user=message.author)
except errors.AlreadyExistingError: except errors.AlreadyExistingError:
await client.send_message(message.channel, "⚠ Il tuo account Discord è già collegato a un account RYG o l'account RYG che hai specificato è già collegato a un account Discord.") await client.send_message(message.channel, "⚠ Il tuo account Discord è già collegato a un account RYG o l'account RYG che hai specificato è già collegato a un account Discord.")
return return
db.session.add(d) session.add(d)
db.session.commit() session.commit()
await client.send_message(message.channel, "✅ Sincronizzazione completata!") await client.send_message(message.channel, "✅ Sincronizzazione completata!")
client.run(config["Discord"]["bot_token"]) client.run(config["Discord"]["bot_token"])
db.session.close() session.close()

View file

@ -1,43 +1,44 @@
import db import db
user = db.Royal.create(input("Nome account: ")) session = db.Session()
db.session.add(user) user = db.Royal.create(session, input("Nome account: "))
db.session.commit() session.add(user)
session.commit()
try: try:
steam = db.Steam.create(user.id, input("Steam ID 1: ")) steam = db.Steam.create(session, user.id, input("Steam ID 1: "))
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
db.session.add(steam) session.add(steam)
try: try:
dota = db.Dota.create(steam.steam_id) dota = db.Dota.create(session, steam.steam_id)
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
db.session.add(dota) session.add(dota)
try: try:
rl = db.RocketLeague.create(steam.steam_id) rl = db.RocketLeague.create(session, steam.steam_id)
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
db.session.add(rl) session.add(rl)
try: try:
osu = db.Osu.create(user.id, input("Osu! username: ")) osu = db.Osu.create(session, user.id, input("Osu! username: "))
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
db.session.add(osu) session.add(osu)
try: try:
overwatch = db.Overwatch.create(user.id, input("Battle.net battletag: ")) overwatch = db.Overwatch.create(session, user.id, input("Battle.net battletag: "))
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
db.session.add(overwatch) session.add(overwatch)
try: try:
lol = db.LeagueOfLegends.create(user.id, input("League summoner name: ")) lol = db.LeagueOfLegends.create(session, user.id, input("League summoner name: "))
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
db.session.add(lol) session.add(lol)
db.session.commit() session.commit()
db.session.close() session.close()

36
telegrambot.py Normal file
View file

@ -0,0 +1,36 @@
import db
import errors
from telegram import Bot, Update, Message
from telegram.ext import Updater, CommandHandler
# Init the config reader
import configparser
config = configparser.ConfigParser()
config.read("config.ini")
def cmd_register(bot: Bot, update: Update):
session = db.Session()
try:
username = update.message.text.split(" ", 1)[1]
except IndexError:
bot.send_message(update.message.chat.id, "⚠️ Non hai specificato un username!")
return
try:
t = db.Telegram.create(session,
royal_username=username,
telegram_user=update.message.from_user)
except errors.AlreadyExistingError:
bot.send_message(update.message.chat.id, "⚠ Il tuo account Telegram è già collegato a un account RYG o l'account RYG che hai specificato è già collegato a un account Telegram.")
return
session.add(t)
session.commit()
bot.send_message(update.message.chat.id, "✅ Sincronizzazione completata!")
session.close()
u = Updater(config["Telegram"]["bot_token"])
u.dispatcher.add_handler(CommandHandler("register", cmd_register))
u.start_polling()
try:
u.idle()
except KeyboardInterrupt:
pass

View file

@ -2,11 +2,12 @@ import db
import errors import errors
import time import time
session = db.Session()
# Stop updating if Ctrl-C is pressed # Stop updating if Ctrl-C is pressed
try: try:
# Update Steam # Update Steam
print("STEAM") print("STEAM")
for user in db.session.query(db.Steam).all(): for user in session.query(db.Steam).all():
t = time.clock() t = time.clock()
print(f"Updating {user.royal.username}", end="\t\t", flush=True) print(f"Updating {user.royal.username}", end="\t\t", flush=True)
try: try:
@ -22,7 +23,7 @@ try:
time.sleep(sleep_time if sleep_time > 0 else 0) time.sleep(sleep_time if sleep_time > 0 else 0)
# Update Rocket League # Update Rocket League
print("ROCKET LEAGUE") print("ROCKET LEAGUE")
for user in db.session.query(db.RocketLeague).all(): for user in session.query(db.RocketLeague).all():
t = time.clock() t = time.clock()
print(f"Updating {user.steam.royal.username}", end="\t\t", flush=True) print(f"Updating {user.steam.royal.username}", end="\t\t", flush=True)
try: try:
@ -38,7 +39,7 @@ try:
time.sleep(sleep_time if sleep_time > 0 else 0) time.sleep(sleep_time if sleep_time > 0 else 0)
# Update Dota 2 # Update Dota 2
print("DOTA 2") print("DOTA 2")
for user in db.session.query(db.Dota).all(): for user in session.query(db.Dota).all():
t = time.clock() t = time.clock()
print(f"Updating {user.steam.royal.username}", end="\t\t", flush=True) print(f"Updating {user.steam.royal.username}", end="\t\t", flush=True)
try: try:
@ -54,7 +55,7 @@ try:
time.sleep(sleep_time if sleep_time > 0 else 0) time.sleep(sleep_time if sleep_time > 0 else 0)
# Update League of Legends # Update League of Legends
print("LEAGUE OF LEGENDS") print("LEAGUE OF LEGENDS")
for user in db.session.query(db.LeagueOfLegends).all(): for user in session.query(db.LeagueOfLegends).all():
t = time.clock() t = time.clock()
print(f"Updating {user.royal.username}", end="\t\t", flush=True) print(f"Updating {user.royal.username}", end="\t\t", flush=True)
try: try:
@ -70,7 +71,7 @@ try:
time.sleep(sleep_time if sleep_time > 0 else 0) time.sleep(sleep_time if sleep_time > 0 else 0)
# Update Osu! # Update Osu!
print("OSU!") print("OSU!")
for user in db.session.query(db.Osu).all(): for user in session.query(db.Osu).all():
t = time.clock() t = time.clock()
print(f"Updating {user.royal.username}", end="\t\t", flush=True) print(f"Updating {user.royal.username}", end="\t\t", flush=True)
try: try:
@ -86,7 +87,7 @@ try:
time.sleep(sleep_time if sleep_time > 0 else 0) time.sleep(sleep_time if sleep_time > 0 else 0)
# Update Overwatch # Update Overwatch
print("OVERWATCH") print("OVERWATCH")
for user in db.session.query(db.Overwatch).all(): for user in session.query(db.Overwatch).all():
t = time.clock() t = time.clock()
print(f"Updating {user.royal.username}", end="\t\t", flush=True) print(f"Updating {user.royal.username}", end="\t\t", flush=True)
try: try:
@ -104,6 +105,5 @@ except KeyboardInterrupt:
pass pass
finally: finally:
print("Committing...\t\t") print("Committing...\t\t")
db.session.commit() session.commit()
print("OK") print("OK")
db.session.close()

View file

@ -1,5 +1,6 @@
from flask import Flask, render_template from flask import Flask, render_template
from db import session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends
from sqlalchemy.orm import joinedload
app = Flask(__name__) app = Flask(__name__)
@ -8,11 +9,13 @@ app.jinja_env.lstrip_blocks = True
@app.route("/leaderboards") @app.route("/leaderboards")
def page_leaderboards(): def page_leaderboards():
dota_data = session.query(Dota).join(Steam).join(Royal).all() session = Session()
rl_data = session.query(RocketLeague).join(Steam).join(Royal).all() dota_data = session.query(Dota).options(joinedload(Dota.steam).joinedload(Steam.royal)).join(Steam).join(Royal).all()
ow_data = session.query(Overwatch).join(Royal).all() rl_data = session.query(RocketLeague).options(joinedload(RocketLeague.steam).joinedload(Steam.royal)).join(Steam).join(Royal).all()
osu_data = session.query(Osu).join(Royal).all() ow_data = session.query(Overwatch).options(joinedload(Overwatch.royal)).join(Royal).all()
lol_data = session.query(LeagueOfLegends).join(Royal).all() osu_data = session.query(Osu).options(joinedload(Osu.royal)).join(Royal).all()
lol_data = session.query(LeagueOfLegends).options(joinedload(LeagueOfLegends.royal)).join(Royal).all()
session.close()
return render_template("leaderboards.html", dota_data=dota_data, rl_data=rl_data, ow_data=ow_data, osu_data=osu_data, lol_data=lol_data) return render_template("leaderboards.html", dota_data=dota_data, rl_data=rl_data, ow_data=ow_data, osu_data=osu_data, lol_data=lol_data)
if __name__ == "__main__": if __name__ == "__main__":
@ -20,4 +23,3 @@ if __name__ == "__main__":
app.run(host="0.0.0.0", port=1234, debug=True) app.run(host="0.0.0.0", port=1234, debug=True)
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
session.close()