Compare commits

..

3 Commits
main ... crap

Author SHA1 Message Date
stupidcomputer b552539e29 crap 2024-11-10 22:42:39 -06:00
stupidcomputer 779cc2ccba crap 2024-11-10 22:42:37 -06:00
stupidcomputer ea5d197833 some initial ideas -- needs to be cleaned up a lot 2024-11-09 23:36:26 -06:00
11 changed files with 302 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
tfbbridge.sqlite3
__pycache__/
*.pyc
tfbbridge/config.json

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"nixEnvSelector.nixFile": "${workspaceFolder}/shell.nix"
}

8
shell.nix Normal file
View File

@ -0,0 +1,8 @@
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
# nativeBuildInputs is usually what you want -- tools you need to run
nativeBuildInputs = with pkgs; [
buildPackages.python311Packages.requests
buildPackages.python311Packages.flask
];
}

129
tfbbridge/__init__.py Normal file
View File

@ -0,0 +1,129 @@
from flask import Flask, request, render_template, g, redirect
import requests
from .dbutils import get_and_init_db, get_db
from .groupme import group_sharing_url_to_id, get_oauth_auth_url, custom_get_oauth_auth
import json
import uuid
app = Flask(__name__)
app.config.from_mapping(
DATABASE_LOCATION = "tfbbridge.sqlite3",
)
app.config.from_file("config.json", load=json.load)
@app.route("/groupme/oauth_callback")
def oauth_callback():
token = request.args.get("access_token")
r = requests.get("https://api.groupme.com/v3/groups?token={}".format(token))
try:
print(r.text)
print(token)
data = r.json()["response"]
except KeyError:
return "Couldn't find something", 500
data = [
{
"group_id": i["group_id"],
"name": i["name"],
}
for i in data]
return render_template("what_group.html", groups=data, token=token)
@app.route("/groupme/add_group", methods=["POST"])
def add_group():
token = request.form["token"]
target_group = request.form["to_add"]
headers = {
'Content-Type': 'application/json',
}
params = {
'token': token,
}
json_data = {
'bot': {
'name': 'tfbbot',
'group_id': target_group,
},
}
r = requests.post('https://api.groupme.com/v3/bots', params=params, headers=headers, json=json_data)
payload = r.json()
return payload
bot_id = payload["response"]["bot"]["bot_id"]
group_name = payload["response"]["bot"]["group_name"]
group_id = payload["response"]["bot"]["group_id"]
db = get_db()
try:
db.execute(
"INSERT INTO channels (group_name, group_id, bot_id, chan_type, organization)"
)
return r.text
@app.route("/groupme/authorize")
def authorize():
return redirect(get_oauth_auth_url())
@app.route("/groupme/create_organization", methods=["GET", "POST"])
def create_organization():
if request.method == "GET":
return render_template("new_org.html")
elif request.method == "POST":
name = request.form["orgname"]
db = get_db()
try:
db.execute(
"INSERT INTO organizations (org_name, admin_url, addition_url) VALUES (?, ?, ?)",
(name, uuid.uuid4().hex, uuid.uuid4().hex,),
)
db.commit()
return "testing"
except db.IntegrityError:
return "This group is already registered."
@app.route("/groupme/list_orgs")
def list_orgs():
db = get_db()
cursor = db.cursor()
cursor.execute('SELECT * FROM organizations')
results = cursor.fetchall()
results = [(i[0], i[1], i[2], i[3]) for i in results]
print(results)
return results
@app.route("/groupme/org_info/<org>")
def org_info(org):
db = get_db()
cursor = db.cursor()
cursor.execute('SELECT id, org_name FROM organizations WHERE admin_url=?', (org,))
org_id, name = cursor.fetchone()
cursor.execute('SELECT group_name, group_id, bot_id, chan_type FROM channels WHERE organization=?', (org_id,))
results = cursor.fetchall()
results = [
{
"name": i[0],
"group_id": i[1],
"bot_id": i[2],
"chan_type": i[3],
}
for i in results]
return results
@app.route("/groupme/add_chan_to_org/<org>")
def add_chan_to_org(org):
db = get_db()
cursor = db.cursor()
cursor.execute('SELECT id, org_name FROM organizations WHERE addition_url=?', (org,))
org_id, name = cursor.fetchone()
return redirect(
"https://oauth.groupme.com/oauth/authorize?client_id=qAAAc8GSUlTA8C3Ypo9CMiFQwQCQnU8zPU5KGEtz3FYHDqP5&response_type=token"
)

34
tfbbridge/dbutils.py Normal file
View File

@ -0,0 +1,34 @@
"""
Database shenanigans
"""
import sqlite3
import os
from flask import current_app, g
def get_and_init_db(database: str):
# check if the file exists first
new_database = not os.path.exists(database)
db = sqlite3.connect(
database,
detect_types=sqlite3.PARSE_DECLTYPES
)
db.row_factory = sqlite3.Row
if new_database:
with current_app.open_resource("schema.sql") as handle:
schema = handle.read().decode('utf8')
db.executescript(schema)
print("I've initialized the database!")
return db
def get_db():
# given a global object, populate it if necessary and return the db
if 'db' not in g:
g.db = get_and_init_db(current_app.config["DATABASE_LOCATION"])
return g.db

53
tfbbridge/groupme.py Normal file
View File

@ -0,0 +1,53 @@
# misc groupme utilities
from urllib.parse import urlparse, urlencode
from flask import current_app
from typing import Optional
def group_sharing_url_to_id(url: str) -> str:
"""
Convert a GroupMe group sharing url to an ID.
For example, given a URL https://groupme.com/join_group/91994372/901HvAj3, the
returned ID should be 91994372.
The return type is a string because of BigNum future concerns.
"""
parsed = urlparse(url)
splitted = parsed.path.split('/')
group_id = splitted[2]
return group_id
def build_oauth_auth_url(state: Optional[str] = None, user_params: Optional[dict] = {}):
"""
Build the OAuth redirect url to GroupMe.
state is optional -- it is usually in reference to the organization in question.
If so, state should be set to the organization's `addition_url`. (see schema.sql for info)
"""
base = current_app.config["REDIRECT_URL"]
params = {}
if state:
params["state"] = state
params = params | user_params
urlencoded = urlencode(params)
if urlencoded:
base += "&"
return base + urlencoded
def get_oauth_auth_url(state: None | str = None):
return build_oauth_auth_url(
state
)
def custom_get_oauth_auth(params):
return build_oauth_auth_url(
None,
params
)

32
tfbbridge/schema.sql Normal file
View File

@ -0,0 +1,32 @@
DROP TABLE IF EXISTS child_groups;
DROP TABLE IF EXISTS parent_groups;
CREATE TABLE organizations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
org_name TEXT NOT NULL,
admin_url TEXT UNIQUE NOT NULL, /* should be private */
addition_url TEXT UNIQUE NOT NULL /* can be public */
);
CREATE TABLE channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_name TEXT NOT NULL,
group_id TEXT UNIQUE NOT NULL,
bot_id TEXT UNIQUE,
/*
chan_type enum
1: a channel that recieves only announcements -- no one within may send things.
2: a channel that can recieve annonuncements, and select people can send announcements.
3: a channel in which everyone can send announcements.
*/
chan_type TEXT CHECK( chan_type in ('1', '2', '3') ) NOT NULL,
organization INTEGER NOT NULL,
FOREIGN KEY(organization) REFERENCES organizations(id)
);
CREATE TABLE allowlisted_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
channel INTEGER NOT NULL,
FOREIGN KEY(channel) REFERENCES channels(id)
);

View File

@ -0,0 +1,9 @@
{% block title %}Add bot{% endblock %}
{% block content %}
<form method="post">
<label for="chaturl">GroupMe Chat URL</label>
<input name="chaturl" id="chaturl" required>
<input type="submit" value="Add bot!">
</form>
{% endblock %}

View File

@ -0,0 +1,9 @@
<!DOCTYPE html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
{% block content %}{% endblock %}
</body>

View File

@ -0,0 +1,9 @@
{% block title %}New organization{% endblock %}
{% block content %}
<form method="post">
<label for="orgname">Organization name</label>
<input name="orgname" id="orgname" required>
<input type="submit" value="Create organization!">
</form>
{% endblock %}

View File

@ -0,0 +1,12 @@
{% block title %}Add bot{% endblock %}
{% block content %}
<form method="post" action="/groupme/add_group">
{% for group in groups %}
<input type="radio" id="{{ group.group_id }}" name="to_add" value="{{ group.group_id }}">
<label for="{{ group.group_id }}">{{ group.name }}</label>
{% endfor %}
<input type="hidden" name="token" value="{{ token }}">
<input type="submit" value="Add this group">
</form>
{% endblock %}