moved into new project structure

This commit is contained in:
Morgan McMillian 2024-12-15 16:25:17 -08:00
parent 5638805481
commit d2a3d031ec
6 changed files with 54 additions and 127 deletions

View file

@ -1,118 +0,0 @@
import logging
import yaml
import time
import pnutpy
from matrix_bot_api.matrix_bot_api import MatrixBotAPI
from matrix_bot_api.mregex_handler import MRegexHandler
from matrix_bot_api.mcommand_handler import MCommandHandler
from models import Avatars, Rooms, Events, Users
from database import db_session
from sqlalchemy import and_
def help_cb(room, event):
reply = "This is an admin room for controlling your connection to pnut.io\n"
reply += "The following commands are available.\n\n"
reply += "!auth - Authorize your account on pnut.io\n"
reply += "!save <token> - Save your pnut.io auth token\n"
reply += "!drop - Drop your pnut.io auth token\n"
reply += "!status - Status of your pnut.io auth token\n"
room.send_notice(reply)
def auth_cb(room, event):
reply = "Visit the following URL to authorize your account on pnut.io.\n\n"
reply += "https://pnut.io/oauth/authenticate"
reply += "?client_id=6SeCRCpCZkmZOKFLFGWbcdAeq2fX1M5t"
reply += "&redirect_uri=urn:ietf:wg:oauth:2.0:oob"
reply += "&scope=write_post,presence,messages&response_type=token\n\n"
reply += "You will be provided with a token that you store with the !save command.\n"
room.send_notice(reply)
def save_cb(room, event):
args = event['content']['body'].split(' ', maxsplit=1)
if len(args) < 2:
reply = "You must provide a token with this command.\n"
reply += "!save <token>"
room.send_notice(reply)
return
pnutpy.api.add_authorization_token(args[1])
try:
response, meta = pnutpy.api.get_user('me')
user = Users(
matrix_id=event['sender'],
pnut_user_id=response.id,
pnut_user_token=args[1]
)
db_session.add(user)
db_session.commit()
reply = "Success! You are now authorized as " + response['username']
except pnutpy.errors.PnutAuthAPIException as e:
reply = "Error! Unable to authorize your account."
except Exception as e:
logging.exception('!save')
reply = "Error! Problem saving your token."
room.send_notice(reply)
def drop_cb(room, event):
try:
user = Users.query.filter(Users.matrix_id == event['sender']).one_or_none()
if user is not None:
db_session.delete(user)
db_session.commit()
reply = "Success! Your auth token has been removed."
else:
reply = "You do not appear to be registered."
except Exception as e:
logging.exception('!drop')
reply = "Error! Problem removing your token."
room.send_notice(reply)
def status_cb(room, event):
try:
user = Users.query.filter(Users.matrix_id == event['sender']).one_or_none()
if user is None:
reply = "You are currently not authorized on pnut.io"
else:
pnutpy.api.add_authorization_token(user.pnut_user_token)
response, meta = pnutpy.api.get_user('me')
reply = "You are currently authorized as " + response.username
except pnutpy.errors.PnutAuthAPIException as e:
reply = "You are currently not authorized on pnut.io"
except Exception as e:
logging.exception('!status')
reply = "Error! There was a problem checking your account."
room.send_notice(reply)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
with open("config.yaml", "rb") as config_file:
config = yaml.load(config_file)
bot = MatrixBotAPI(config['TBOT_USER'], config['TBOT_PASS'], config['MATRIX_HOST'])
bot.add_handler(MCommandHandler("help", help_cb))
bot.add_handler(MCommandHandler("auth", auth_cb))
bot.add_handler(MCommandHandler("save", save_cb))
bot.add_handler(MCommandHandler("drop", drop_cb))
bot.add_handler(MCommandHandler("status", status_cb))
bot.start_polling()
while True:
time.sleep(1)

37
pyproject.toml Normal file
View file

@ -0,0 +1,37 @@
[project]
name = "pnut-matrix"
version = "1.3.99"
authors = [
{ name="Morgan McMillian", email="morgan@mcmillian.dev" },
]
description = "A matrix appservice bridge for pnut.io"
readme = "README.md"
requires-python = ">=3.9"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent",
]
dependencies = [
"pyyaml",
"requests",
"Flask[async]",
"pnutpy>=0.5.0",
"sqlalchemy",
"filemagic",
"mautrix>=0.20.6,<0.21",
"websockets",
"asyncclick",
]
[project.urls]
"Homepage" = "https://git.dreamfall.space/spacenerdmo/pnut-matrix"
"Bug Tracker" = "https://git.dreamfall.space/spacenerdmo/pnut-matrix/issues"
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project.entry-points.console_scripts]
pnutservice = "pnut_matrix.pnutservice:main"
matrixappsvc = "pnut_matrix.appservice:main"

View file

@ -12,8 +12,8 @@ import os
from mautrix.client import ClientAPI from mautrix.client import ClientAPI
from mautrix.types import * from mautrix.types import *
from models import Avatars, Rooms, Events, Users, DirectRooms, ControlRooms from pnut_matrix.models import Avatars, Rooms, Events, Users, DirectRooms, ControlRooms
from database import db_session from pnut_matrix.database import db_session
from sqlalchemy import and_ from sqlalchemy import and_
from flask import Flask, jsonify, request, abort from flask import Flask, jsonify, request, abort
@ -939,7 +939,7 @@ class MLogFilter(logging.Filter):
return True return True
if __name__ == '__main__': def main():
configyaml = os.environ.get("CONFIG_FILE") configyaml = os.environ.get("CONFIG_FILE")
with open(configyaml, "rb") as config_file: with open(configyaml, "rb") as config_file:
@ -953,3 +953,6 @@ if __name__ == '__main__':
app.config.update(config) app.config.update(config)
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
app.run(host=config['LISTEN_HOST'], port=config['LISTEN_PORT']) app.run(host=config['LISTEN_HOST'], port=config['LISTEN_PORT'])
if __name__ == '__main__':
main()

View file

@ -20,5 +20,5 @@ def init_db():
# import all modules here that might define models so that # import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise # they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db() # you will have to import them first before calling init_db()
import models import pnut_matrix.models
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)

View file

@ -1,5 +1,5 @@
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean from sqlalchemy import Column, ForeignKey, Integer, String, Boolean
from database import Base from pnut_matrix.database import Base
class Avatars(Base): class Avatars(Base):
__tablename__ = 'avatars' __tablename__ = 'avatars'

View file

@ -19,12 +19,14 @@ from mautrix.errors.request import MNotFound, MForbidden
from websockets.asyncio.client import connect from websockets.asyncio.client import connect
from websockets.exceptions import ConnectionClosed from websockets.exceptions import ConnectionClosed
from models import Avatars, Rooms, Events, DirectRooms, Users from pnut_matrix.models import Avatars, Rooms, Events, DirectRooms, Users
from database import db_session, init_db from pnut_matrix.database import db_session, init_db
from sqlalchemy import and_ from sqlalchemy import and_
logger = logging.getLogger() logger = logging.getLogger()
config = None
class MLogFilter(logging.Filter): class MLogFilter(logging.Filter):
ACCESS_TOKEN_RE = re.compile(r"(\?.*access(_|%5[Ff])token=)[^&]*(\s.*)$") ACCESS_TOKEN_RE = re.compile(r"(\?.*access(_|%5[Ff])token=)[^&]*(\s.*)$")
@ -486,8 +488,8 @@ async def asmain():
except ConnectionClosed: except ConnectionClosed:
continue continue
if __name__ == '__main__': def main():
global config
a_parser = argparse.ArgumentParser() a_parser = argparse.ArgumentParser()
a_parser.add_argument( a_parser.add_argument(
'-d', action='store_true', dest='debug', '-d', action='store_true', dest='debug',
@ -515,3 +517,6 @@ if __name__ == '__main__':
asyncio.run(asmain()) asyncio.run(asmain())
logger.info('!! shutdown initiated !!') logger.info('!! shutdown initiated !!')
if __name__ == '__main__':
main()