Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plex auth #41

Merged
merged 2 commits into from
Sep 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions app/bot/cogs/app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import discord
from discord.ext import commands
import asyncio
from plexapi.server import PlexServer
from plexapi.myplex import MyPlexAccount
from discord import Webhook, AsyncWebhookAdapter
import app.bot.helper.db as db
Expand All @@ -9,23 +10,20 @@
import os
from os import path
import configparser
CONFIG_PATH = 'app/config/config.ini'
BOT_SECTION = 'bot_envs'
from app.bot.helper.confighelper import CONFIG_PATH, BOT_SECTION

# settings
roles = None
PLEXUSER = ""
PLEXPASS = ""
PLEX_SERVER_NAME = ""
PLEX_TOKEN = ""
PLEX_URL = ""
Plex_LIBS = None

if(path.exists('app/config/config.ini')):
try:
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
PLEXUSER = config.get(BOT_SECTION, 'plex_user')
PLEXPASS = config.get(BOT_SECTION, 'plex_pass')
PLEX_SERVER_NAME = config.get(BOT_SECTION, 'plex_server_name')
PLEX_TOKEN = config.get(BOT_SECTION, 'plex_token')
PLEX_URL = config.get(BOT_SECTION, 'plex_url')
except:
pass
if(path.exists('app/config/config.ini')):
Expand All @@ -40,8 +38,8 @@
pass

try:
account = MyPlexAccount(PLEXUSER, PLEXPASS)
plex = account.resource(PLEX_SERVER_NAME).connect() # returns a PlexServer instance
plex = PlexServer(PLEX_URL, PLEX_TOKEN)
account = MyPlexAccount(PLEX_TOKEN)
print('Logged into plex!')
except:
print('Error with plex login. Please check username and password and Plex server name or setup plex in the bot.')
Expand Down Expand Up @@ -99,7 +97,7 @@ def check(m):

async def addtoplex(self, email, channel):
if(plexhelper.verifyemail(email)):
if plexhelper.plexadd(plex,email,Plex_LIBS):
if plexhelper.plexadd(plex,account,email,Plex_LIBS):
await self.embedinfo(channel, 'This email address has been added to plex')
return True
else:
Expand All @@ -111,7 +109,7 @@ async def addtoplex(self, email, channel):

async def removefromplex(self, email, channel):
if(plexhelper.verifyemail(email)):
if plexhelper.plexremove(plex,email):
if plexhelper.plexremove(account,email):
await self.embedinfo(channel, 'This email address has been removed from plex.')
return True
else:
Expand All @@ -136,7 +134,7 @@ async def on_member_update(self, before, after):
email = await self.getemail(after)
if email is not None:
await self.embedinfo(after, "Got it we will be adding your email to plex shortly!")
if plexhelper.plexadd(plex,email,Plex_LIBS):
if plexhelper.plexadd(plex,account,email,Plex_LIBS):
db.save_user(str(after.id), email)
await asyncio.sleep(5)
await self.embedinfo(after, 'You have Been Added To Plex! Login to plex and accept the invite!')
Expand All @@ -148,7 +146,7 @@ async def on_member_update(self, before, after):
try:
user_id = after.id
email = db.get_useremail(user_id)
plexhelper.plexremove(plex,email)
plexhelper.plexremove(account,email)
deleted = db.delete_user(user_id)
if deleted:
print("Removed {} from db".format(email))
Expand All @@ -163,7 +161,7 @@ async def on_member_update(self, before, after):
@commands.Cog.listener()
async def on_member_remove(self, member):
email = db.get_useremail(member.id)
plexhelper.plexremove(plex,email)
plexhelper.plexremove(account,email)
deleted = db.delete_user(member.id)
if deleted:
print("Removed {} from db because user left discord server.".format(email))
Expand Down
Binary file not shown.
16 changes: 7 additions & 9 deletions app/bot/helper/confighelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@
BOT_SECTION = 'bot_envs'
config = configparser.ConfigParser()

CONFIG_KEYS = ['username', 'password', 'discord_bot_token', 'plex_user', 'plex_pass',
'roles', 'plex_server_name', 'plex_libs', 'owner_id', 'channel_id',
CONFIG_KEYS = ['username', 'password', 'discord_bot_token', 'plex_token', 'plex_url',
'roles', 'plex_libs', 'owner_id', 'channel_id', 'identifier',
'auto_remove_user']

# settings
Discord_bot_token = ""
roles = None
PLEXUSER = ""
PLEXPASS = ""
PLEX_SERVER_NAME = ""
PLEX_TOKEN = ""
PLEX_URL = ""
Plex_LIBS = None
switch = 0

Expand All @@ -40,9 +39,8 @@
try:
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
PLEXUSER = config.get(BOT_SECTION, 'plex_user')
PLEXPASS = config.get(BOT_SECTION, 'plex_pass')
PLEX_SERVER_NAME = config.get(BOT_SECTION, 'plex_server_name')
PLEX_TOKEN = config.get(BOT_SECTION, 'plex_token')
PLEX_URL = config.get(BOT_SECTION, 'plex_url')
except:
pass

Expand Down Expand Up @@ -91,4 +89,4 @@ def change_config(key, value):
config.write(configfile)
except Exception as e:
print(e)
print("Cannot write to config.")
print("Cannot write to config.")
11 changes: 5 additions & 6 deletions app/bot/helper/plexhelper.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from plexapi.server import PlexServer
from plexapi.myplex import MyPlexAccount
import re

def plexadd(plex, plexname, Plex_LIBS):
def plexadd(plex, account, plexname, Plex_LIBS):
try:
if Plex_LIBS[0] == "all":
Plex_LIBS = plex.library.sections()
plex.myPlexAccount().inviteFriend(user=plexname, server=plex, sections=Plex_LIBS, allowSync=False,
account.inviteFriend(user=plexname, server=plex, sections=Plex_LIBS, allowSync=False,
allowCameraUpload=False, allowChannels=False, filterMovies=None,
filterTelevision=None, filterMusic=None)
print(plexname +' has been added to plex')
Expand All @@ -15,18 +16,16 @@ def plexadd(plex, plexname, Plex_LIBS):
return False


def plexremove(plex, plexname):
def plexremove(account, plexname):
try:
plex.myPlexAccount().removeFriend(user=plexname)
account.removeFriend(user=plexname)
print(plexname +' has been removed from plex')
return True
except Exception as e:
print(e)
return False
'''

plex python api has no tools to remove unaccepted invites...

print("Trying to remove invite...")
removeinvite = plexremoveinvite(plex, plexname)
if removeinvite:
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
discord.py
plex.py==0.9.0
PlexAPI==4.0.0
PlexAPI==4.13.0
texttable
python-dotenv
75 changes: 50 additions & 25 deletions run.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import discord
import os
from os import path
from discord.ext import commands, tasks
from discord.utils import get
from plexapi.myplex import MyPlexPinLogin
import asyncio
import sys
from app.bot.helper.confighelper import switch, Discord_bot_token, roles
import secrets
from app.bot.helper.confighelper import switch, Discord_bot_token, roles, CONFIG_PATH, BOT_SECTION
import app.bot.helper.confighelper as confighelper
import configparser
maxroles = 10



if roles is None:
roles = []
else:
Expand Down Expand Up @@ -40,9 +46,9 @@ async def on_message(message):
def reload():
bot.reload_extension(f'app.bot.cogs.app')

async def getplex(ctx, type):
async def getplex(ctx, message):
username = None
await ctx.author.send("Please reply with your Plex {}:".format(type))
await ctx.author.send(message)
while(username == None):
def check(m):
return m.author == ctx.author and not m.guild
Expand All @@ -53,6 +59,21 @@ def check(m):
message = "Timed Out. Try again."
return None

async def gettoken(ctx, identifier):
try:
headers = {
'X-Plex-Product': 'Invitarr',
'X-Plex-Client-Identifier': str(identifier)
}
pinlogin = MyPlexPinLogin(headers=headers, requestTimeout=300, oauth=True)
await ctx.author.send("Please follow this link within five minutes to authenticate Invitarr:\n{}".format(pinlogin.oauthUrl()))
pinlogin.run()
pinlogin.waitForLogin()
return pinlogin.token
except asyncio.TimeoutError:
await ctx.author.send("Timed Out. Try again.")
return None

@bot.command()
@commands.has_permissions(administrator=True)
async def roleadd(ctx, role: discord.Role):
Expand All @@ -69,29 +90,33 @@ async def roleadd(ctx, role: discord.Role):
@bot.command()
@commands.has_permissions(administrator=True)
async def setupplex(ctx):
username = ""
pasword = ""
servername = ""
username = await getplex(ctx, "username")
if username is None:
token = ""
plexurl = ""
identifier = None
if(path.exists('app/config/config.ini')):
try:
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
identifier = config.get(BOT_SECTION, 'identifier')
except:
pass
if identifier is None:
identifier = "{} (Invitarr)".format(secrets.token_urlsafe(16))
print(identifier)
confighelper.change_config("identifier", identifier)
token = await gettoken(ctx, identifier)
if token is None:
return
else:
password = await getplex(ctx, "password")
if password is None:
return
else:
servername = await getplex(ctx, "servername")
if servername is None:
return
else:
confighelper.change_config("plex_user", str(username))
confighelper.change_config("plex_pass", str(password))
confighelper.change_config("plex_server_name", str(servername))
print("Plex username, password, and plex server name updated. Restarting bot.")
await ctx.author.send("Plex username, password, and plex server name updated. Restarting bot. Please wait.")
reload()
await ctx.author.send("Bot has been restarted. Give it a few seconds. Please check logs and make sure you see the line: `Logged into plex`. If not run this command again and make sure you enter the right values. ")
print("Bot has been restarted. Give it a few seconds.")
plexurl = await getplex(ctx, "Please reply with the url to your plex server:")
if plexurl is None:
return
confighelper.change_config("plex_token", str(token))
confighelper.change_config("plex_url", str(plexurl))
print("Plex token and plex url updated. Restarting bot.")
await ctx.author.send("Plex token and plex url updated. Restarting bot. Please wait.")
reload()
await ctx.author.send("Bot has been restarted. Give it a few seconds. Please check logs and make sure you see the line: `Logged into plex`. If not run this command again and make sure you enter the right values. ")
print("Bot has been restarted. Give it a few seconds.")

@bot.command()
@commands.has_permissions(administrator=True)
Expand Down