feat: Adds database entries for Jellyfin

- Adds database columns and expands database commands to acccomodate
 jellyfin

task: none
This commit is contained in:
Yoruio
2022-07-09 02:44:42 -06:00
parent a64c43904b
commit d2e184144b
4 changed files with 109 additions and 36 deletions

View File

@@ -24,7 +24,7 @@ This command is used to add an email to plex
This command is used to remove an email from plex This command is used to remove an email from plex
.dbls .dbls
This command is used to list Invitarrs database This command is used to list Invitarrs database
.dbadd <email> <@user> .dbadd <@user> "<email>" "<jellyfinUsername>"
This command is used to add exsisting users email and discord id to the DB. This command is used to add exsisting users email and discord id to the DB.
.dbrm <position> .dbrm <position>
This command is used to remove a record from the Db. Use -db ls to determine record position. ex: -db rm 1 This command is used to remove a record from the Db. Use -db ls to determine record position. ex: -db rm 1

View File

@@ -19,6 +19,8 @@ PLEXPASS = ""
PLEX_SERVER_NAME = "" PLEX_SERVER_NAME = ""
Plex_LIBS = None Plex_LIBS = None
USE_PLEX = False
if(path.exists('app/config/config.ini')): if(path.exists('app/config/config.ini')):
try: try:
config = configparser.ConfigParser() config = configparser.ConfigParser()
@@ -38,14 +40,14 @@ if(path.exists('app/config/config.ini')):
Plex_LIBS = config.get(BOT_SECTION, 'plex_libs') Plex_LIBS = config.get(BOT_SECTION, 'plex_libs')
except: except:
pass pass
if USE_PLEX:
try: try:
account = MyPlexAccount(PLEXUSER, PLEXPASS) account = MyPlexAccount(PLEXUSER, PLEXPASS)
plex = account.resource(PLEX_SERVER_NAME).connect() # returns a PlexServer instance plex = account.resource(PLEX_SERVER_NAME).connect() # returns a PlexServer instance
print('Logged into plex!') print('Logged into plex!')
except Exception as e: except Exception as e:
print('Error with plex login. Please check username and password and Plex server name or setup plex in the bot.') print('Error with plex login. Please check username and password and Plex server name or setup plex in the bot.')
print(f'Error: {e}') print(f'Error: {e}')
if plex_roles is not None: if plex_roles is not None:
plex_roles = list(plex_roles.split(',')) plex_roles = list(plex_roles.split(','))
@@ -181,17 +183,23 @@ class app(commands.Cog):
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.command() @commands.command()
async def dbadd(self, ctx, email, member: discord.Member): async def dbadd(self, ctx, member: discord.Member, email, jellyfin_username):
email = email.strip()
jellyfin_username = jellyfin_username.strip()
await self.embedinfo(ctx.channel, f"username: {member.name} email: {email} jellyfin: {jellyfin_username}")
#await self.addtoplex(email, ctx.channel) #await self.addtoplex(email, ctx.channel)
if plexhelper.verifyemail(email):
try: # Check email if provided
db.save_user(str(member.id), email) if email and not plexhelper.verifyemail(email):
await self.embedinfo(ctx.channel,'email and user were added to the database.') await self.embederror(ctx.channel, "Invalid email.")
except Exception as e: return
await self.embedinfo(ctx.channel, 'There was an error adding this email address to database.')
print(e) try:
else: db.save_user_all(str(member.id), email, jellyfin_username)
await self.embederror(ctx.channel, 'Invalid email.') await self.embedinfo(ctx.channel,'User was added to the database.')
except Exception as e:
await self.embedinfo(ctx.channel, 'There was an error adding this user to database.')
print(e)
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.command() @commands.command()
@@ -200,21 +208,23 @@ class app(commands.Cog):
embed = discord.Embed(title='Invitarr Database.') embed = discord.Embed(title='Invitarr Database.')
all = db.read_useremail() all = db.read_useremail()
table = texttable.Texttable() table = texttable.Texttable()
table.set_cols_dtype(["t", "t", "t"]) table.set_cols_dtype(["t", "t", "t", "t"])
table.set_cols_align(["c", "c", "c"]) table.set_cols_align(["c", "c", "c", "c"])
header = ("#", "Name", "Email") header = ("#", "Name", "Email", "Jellyfin")
table.add_row(header) table.add_row(header)
print(all)
for index, peoples in enumerate(all): for index, peoples in enumerate(all):
index = index + 1 index = index + 1
id = int(peoples[1]) id = int(peoples[1])
dbuser = self.bot.get_user(id) dbuser = self.bot.get_user(id)
dbemail = peoples[2] dbemail = peoples[2] if peoples[2] else "No Plex"
dbjellyfin = peoples[3] if peoples[3] else "No Jellyfin"
try: try:
username = dbuser.name username = dbuser.name
except: except:
username = "User Not Found." username = "User Not Found."
embed.add_field(name=f"**{index}. {username}**", value=dbemail+'\n', inline=False) embed.add_field(name=f"**{index}. {username}**", value=dbemail+'\n'+dbjellyfin+'\n', inline=False)
table.add_row((index, username, dbemail)) table.add_row((index, username, dbemail, dbjellyfin))
total = str(len(all)) total = str(len(all))
if(len(all)>25): if(len(all)>25):
@@ -226,12 +236,11 @@ class app(commands.Cog):
await ctx.channel.send(embed = embed) await ctx.channel.send(embed = embed)
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.command() @commands.command()
async def dbrm(self, ctx, position): async def dbrm(self, ctx, position):
embed = discord.Embed(title='Invitarr Database.') embed = discord.Embed(title='Invitarr Database.')
all = db.read_useremail() all = db.read_useremail() # TODO: no need to read from DB or make a table here.
table = texttable.Texttable() table = texttable.Texttable()
table.set_cols_dtype(["t", "t", "t"]) table.set_cols_dtype(["t", "t", "t"])
table.set_cols_align(["c", "c", "c"]) table.set_cols_align(["c", "c", "c"])

View File

@@ -29,22 +29,61 @@ conn = create_connection(DB_URL)
if checkTableExists(conn, 'clients'): if checkTableExists(conn, 'clients'):
print('Table exists.') print('Table exists.')
else: else:
conn.execute(''' conn.execute(
CREATE TABLE "clients" ( '''CREATE TABLE "clients" (
"id" INTEGER NOT NULL UNIQUE, "id" INTEGER NOT NULL UNIQUE,
"discord_username" TEXT NOT NULL UNIQUE, "discord_username" TEXT NOT NULL UNIQUE,
"email" TEXT NOT NULL, "email" TEXT,
"jellyfin_username" TEXT,
PRIMARY KEY("id" AUTOINCREMENT) PRIMARY KEY("id" AUTOINCREMENT)
); );''')
''')
def save_user(username, email): def save_user_email(username, email):
if username and email: if username and email:
conn.execute("INSERT INTO clients (discord_username, email) VALUES ('"+ username +"', '" + email + "')") conn.execute(f"""
INSERT OR REPLACE INTO clients(discord.username, email)
VALUES('{username}', '{email}')
""")
conn.commit() conn.commit()
print("User added to db.") print("User added to db.")
else: else:
return "Username or email cannot be empty" return "Username and email cannot be empty"
def save_user(username):
if username:
conn.execute("INSERT INTO clients (discord_username) VALUES ('"+ username +"')")
conn.commit()
print("User added to db.")
else:
return "Username cannot be empty"
def save_user_jellyfin(username, jellyfin_username):
if username and jellyfin_username:
conn.execute(f"""
INSERT OR REPLACE INTO clients(discord_username, jellyfin_username)
VALUES('{username}', '{jellyfin_username}')
""")
conn.commit()
print("User added to db.")
else:
return "Discord and Jellyfin usernames cannot be empty"
def save_user_all(username, email, jellyfin_username):
if username and email and jellyfin_username:
conn.execute(f"""
INSERT OR REPLACE INTO clients(discord_username, email, jellyfin_username)
VALUES('{username}', '{email}', '{jellyfin_username}')
""")
conn.commit()
print("User added to db.")
elif username and email:
save_user_email(username, email)
elif username and jellyfin_username:
save_user_jellyfin(username, jellyfin_username)
elif username:
save_user(username)
else:
return "Discord username must all be provided"
def get_useremail(username): def get_useremail(username):
if username: if username:
@@ -61,6 +100,29 @@ def get_useremail(username):
else: else:
return "username cannot be empty" return "username cannot be empty"
def get_jellyfin_username(username):
"""
Get jellyfin username of user based on discord username
param username: discord username
return jellyfin username
"""
if username:
try:
cursor = conn.execute('SELECT discord_username, jellyfin_username from clients where discord_username="{}";'.format(username))
for row in cursor:
jellyfin_username = row[1]
if jellyfin_username:
return jellyfin_username
else:
return "No users found"
except:
return "error in fetching from db"
else:
return "username cannot be empty"
def delete_user(username): def delete_user(username):
if username: if username:
try: try:
@@ -80,4 +142,4 @@ def read_useremail():
for row in rows: for row in rows:
#print(row[1]+' '+row[2]) #print(row[1]+' '+row[2])
all.append(row) all.append(row)
return all return all

2
run.py
View File

@@ -8,6 +8,8 @@ from app.bot.helper.confighelper import switch, Discord_bot_token, plex_roles
import app.bot.helper.confighelper as confighelper import app.bot.helper.confighelper as confighelper
maxroles = 10 maxroles = 10
print(f"Discord Bot Token: {Discord_bot_token}")
if plex_roles is None: if plex_roles is None:
plex_roles = [] plex_roles = []
else: else: