Skip to content

Commit

Permalink
Merge pull request #90 from henworth/black_format
Browse files Browse the repository at this point in the history
Format all files using black
  • Loading branch information
henworth authored Sep 9, 2021
2 parents cd72a3a + 921efd7 commit b7a5989
Show file tree
Hide file tree
Showing 29 changed files with 2,403 additions and 1,526 deletions.
3 changes: 2 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ migra = {extras = ["pg"],version = "*"}
pika = "*"
pylama = "*"
pyopenssl = "*"
black = "==21.8b0"

[packages]
aiohttp = ">=3.7.4"
Expand Down Expand Up @@ -37,7 +38,7 @@ tortoise-orm = {extras = ["asyncpg"], version = "*"}
urllib3 = ">=1.26.4"

[pipenv]
allow_prereleases = false
allow_prereleases = true

[scripts]
lint = "python -m pylama"
795 changes: 456 additions & 339 deletions Pipfile.lock

Large diffs are not rendered by default.

40 changes: 24 additions & 16 deletions arq_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@
from seraphsix.database import Database
from seraphsix.models import deserializer, serializer
from seraphsix.tasks.activity import (
get_characters, process_activity, store_member_history, store_last_active, store_all_games,
save_last_active
get_characters,
process_activity,
store_member_history,
store_last_active,
store_all_games,
save_last_active,
)
from seraphsix.tasks.core import set_cached_members
from seraphsix.tasks.config import Config, log_config
Expand All @@ -19,33 +23,37 @@


async def startup(ctx):
ctx['destiny'] = Pydest(
ctx["destiny"] = Pydest(
api_key=config.destiny.api_key,
client_id=config.destiny.client_id,
client_secret=config.destiny.client_secret,
)

database = Database(config.database_url, config.database_conns)
await database.initialize()
ctx['database'] = database
ctx['redis_cache'] = await aioredis.create_redis_pool(config.redis_url)
ctx['redis_jobs'] = ctx['redis']
ctx["database"] = database
ctx["redis_cache"] = await aioredis.create_redis_pool(config.redis_url)
ctx["redis_jobs"] = ctx["redis"]


async def shutdown(ctx):
await ctx['destiny'].close()
if 'database' in ctx:
await ctx['database'].close()
if 'redis_cache' in ctx:
ctx['redis_cache'].close()
await ctx['redis_cache'].wait_closed()
await ctx["destiny"].close()
if "database" in ctx:
await ctx["database"].close()
if "redis_cache" in ctx:
ctx["redis_cache"].close()
await ctx["redis_cache"].wait_closed()


class WorkerSettings:
functions = [
set_cached_members, get_characters, process_activity,
store_member_history, store_all_games,
func(save_last_active, keep_result=240), func(store_last_active, keep_result=240)
set_cached_members,
get_characters,
process_activity,
store_member_history,
store_all_games,
func(save_last_active, keep_result=240),
func(store_last_active, keep_result=240),
]
on_startup = startup
on_shutdown = shutdown
Expand All @@ -60,7 +68,7 @@ def job_deserializer(b):
return deserializer(b)


if __name__ == '__main__':
if __name__ == "__main__":
logging.config.dictConfig(log_config())
worker = Worker(**get_kwargs(WorkerSettings))
worker.run()
4 changes: 2 additions & 2 deletions bot_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ def main():
bot = SeraphSix(config)
bot.run(config.discord_api_key)
except Exception:
logging.config.dictConfig(log_config('DEBUG'))
logging.config.dictConfig(log_config("DEBUG"))
log = logging.getLogger(__name__)
log.exception("Caught exception")


if __name__ == '__main__':
if __name__ == "__main__":
main()
99 changes: 49 additions & 50 deletions oauth_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,98 +24,97 @@


class DestinyClient(OAuth2):
site = 'https://www.bungie.net'
authorization_url = '/en/oauth/authorize/'
token_url = '/platform/app/oauth/token/'
site = "https://www.bungie.net"
authorization_url = "/en/oauth/authorize/"
token_url = "/platform/app/oauth/token/"


destiny_auth = DestinyClient(
client_id=config.destiny.client_id,
client_secret=config.destiny.client_secret,
redirect_uri=f'https://{config.destiny.redirect_host}/oauth/callback'
redirect_uri=f"https://{config.destiny.redirect_host}/oauth/callback",
)


@app.route('/')
@app.route("/")
def index():
session['code'] = request.args.get('code')
session["code"] = request.args.get("code")

if not session.get('access_token'):
log.debug(f'No access_token found in session, redirecting to /oauth, {session}')
return redirect(
url_for('oauth_index')
)
if not session.get("access_token"):
log.debug(f"No access_token found in session, redirecting to /oauth, {session}")
return redirect(url_for("oauth_index"))

user_info = dict(
membership_id=session.get('membership_id'),
access_token=session.get('access_token'),
refresh_token=session.get('refresh_token')
membership_id=session.get("membership_id"),
access_token=session.get("access_token"),
refresh_token=session.get("refresh_token"),
)

pickled_info = pickle.dumps(user_info)
try:
red.publish(session['state'], pickled_info)
red.publish(session["state"], pickled_info)
except Exception:
log.exception(f'/: Failed to publish state info to redis: {user_info} {session}')
return render_template('message.html', message='Something went wrong.')
return render_template('redirect.html', site=DestinyClient.site, message='Success!')
log.exception(
f"/: Failed to publish state info to redis: {user_info} {session}"
)
return render_template("message.html", message="Something went wrong.")
return render_template("redirect.html", site=DestinyClient.site, message="Success!")


@app.route('/oauth')
@app.route("/oauth")
def oauth_index():
session['state'] = request.args.get('state')
session["state"] = request.args.get("state")

if not session.get('access_token'):
log.debug(f'No access_token found in session, redirecting to /oauth/callback, {session}')
return redirect(
url_for('oauth_callback')
if not session.get("access_token"):
log.debug(
f"No access_token found in session, redirecting to /oauth/callback, {session}"
)
return redirect(url_for("oauth_callback"))

with requests.Session() as s:
s.auth = OAuth2BearerToken(session['access_token'])
s.headers.update({'X-API-KEY': config.destiny.api_key})
r = s.get(f'{DestinyClient.site}/platform/User/GetMembershipsForCurrentUser/')
s.auth = OAuth2BearerToken(session["access_token"])
s.headers.update({"X-API-KEY": config.destiny.api_key})
r = s.get(f"{DestinyClient.site}/platform/User/GetMembershipsForCurrentUser/")

r.raise_for_status()
log.debug(f'/oauth: {session} {request.args}')
return redirect('/')
log.debug(f"/oauth: {session} {request.args}")
return redirect("/")


@app.route('/oauth/callback')
@app.route("/oauth/callback")
def oauth_callback():
code = request.args.get('code')
error = request.args.get('error')
code = request.args.get("code")
error = request.args.get("error")

if error:
log.error(repr(error))
return render_template('message.html', message='Something went wrong.')
return render_template("message.html", message="Something went wrong.")

if not code:
log.debug(f'No code found, redirecting to bungie, {session}')
return redirect(destiny_auth.authorize_url(
response_type='code',
state=session['state']
))
log.debug(f"No code found, redirecting to bungie, {session}")
return redirect(
destiny_auth.authorize_url(response_type="code", state=session["state"])
)

data = destiny_auth.get_token(
code=code,
grant_type='authorization_code',
grant_type="authorization_code",
)

session['code'] = code
session['access_token'] = data.get('access_token')
session['refresh_token'] = data.get('refresh_token')
session['membership_id'] = data.get('membership_id')
log.debug(f'/oauth/callback: {session} {request.args}')
return redirect(url_for('index'))
session["code"] = code
session["access_token"] = data.get("access_token")
session["refresh_token"] = data.get("refresh_token")
session["membership_id"] = data.get("membership_id")
log.debug(f"/oauth/callback: {session} {request.args}")
return redirect(url_for("index"))


@app.route('/the100webhook/<int:guild_id>/slack', methods=['POST'])
@app.route("/the100webhook/<int:guild_id>/slack", methods=["POST"])
def the100_webhook(guild_id):
data = request.get_json(force=True)
log.info(f'{guild_id} {data}')
return render_template('message.html', message='Success!')
log.info(f"{guild_id} {data}")
return render_template("message.html", message="Success!")


if __name__ == '__main__':
app.run(debug=True, ssl_context='adhoc')
if __name__ == "__main__":
app.run(debug=True, ssl_context="adhoc")
2 changes: 1 addition & 1 deletion seraphsix/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from seraphsix.database import Database

__all__ = ['Database']
__all__ = ["Database"]
Loading

0 comments on commit b7a5989

Please sign in to comment.