CreatePleromaApp/create_app.py

155 lines
4.1 KiB
Python
Raw Permalink Normal View History

#! /usr/bin/env python3
# CreatePleromaApp, a python script to generate OAuth tokens for fedi
# Copyright (C) 2024 Anon <@Anon@yandere.cc>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import getpass
import os
import re
import sys
import argparse
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonAPIError, MastodonIOError
class CreateAppError(Exception):
pass
# Modify this section to suit your default preferances
def default(key):
defaults={
"app": "app",
"domain": "https://yandere.cc",
"scopes": "write",
}
return defaults[key]
def printerr(s, end=None):
print(s, file=sys.stderr, end=end if end != None else os.linesep)
def inputerr(q):
sys.stdout.flush()
sys.stderr.flush()
printerr(q, end="")
return input()
# Function to format user input consistently with lables
def _input(lable, ans=""):
if ans:
q = "{} (Default: {}): ".format(
lable, ans)
return inputerr(q) or ans
else:
q = "{}: ".format(lable)
return inputerr(q)
def get_client_id_and_secret(app, permissions, domain):
try:
return Mastodon.create_app(app, scopes=permissions, api_base_url=domain)
except MastodonIOError:
raise CreateAppError("An error occurred. Make sure the domain name is correct.")
def get_api(client_id, client_secret, domain):
api = Mastodon(
client_id,
client_secret,
api_base_url=domain,
feature_set="pleroma"
)
return api
def get_token(api, email, password, permissions):
try:
token = api.log_in(email, password, scopes=permissions)
return token
except MastodonIllegalArgumentError:
raise CreateAppError("Username or Password is incorrect.")
except MastodonAPIError:
raise CreateAppError("Could not grant scopes:", ", ".join(permissions))
def main():
# Parser
parser = argparse.ArgumentParser(
description="A script to generate OAuth tokens for fedi",
epilog="",
add_help=True)
_ = parser.parse_args()
try:
# Settings Dictionary
settings = {}
# Create App
printerr("Generate and register Mastodon App")
printerr("You can just hit enter to accept the default for prompts that have them")
printerr("Ctrl+C to Quit\n")
# Get instance information
app_name = _input("Enter your app name", default("app"))
settings["API_BASE_URL"] = _input("URL of Instance", default("domain"))
email = _input("Enter your email")
password = getpass.getpass("Enter password: ")
printerr("Scopes: read, write, follow, push")
printerr("Separate each scope with a comma (example above).")
printerr("!!! Accept the default unless you intend to modify FediStatusPoster !!!")
ans = _input("Scopes", default("scopes"))
ans = re.sub(r"\s+", "", ans, flags=re.UNICODE)
permissions = ans.split(",")
printerr("Granting: {}".format(str(permissions)))
# Begin logging in
settings["CLIENT_ID"], settings["CLIENT_SECRET"] =\
get_client_id_and_secret(
app_name,
permissions,
settings["API_BASE_URL"]
)
api = get_api(
settings["CLIENT_ID"],
settings["CLIENT_SECRET"],
settings["API_BASE_URL"]
)
settings["ACCESS_TOKEN"] = get_token(api, email, password, permissions)
# Output the user's new credentials
for k, v in settings.items():
v = settings[k]
print("{}={}".format(k, v))
printerr("Success :)")
return 0
except (KeyboardInterrupt, EOFError):
printerr("\nUser Quit :|")
return 1
except CreateAppError as e:
printerr(e)
printerr("Error :(")
return 2
except Exception as e:
printerr(e)
printerr("Unhandled Exception ¯\\_(ツ)_/¯")
return 3
if __name__ == "__main__":
sys.exit(main())