Skip to content
This repository has been archived by the owner on Mar 12, 2023. It is now read-only.

Commit

Permalink
Merge pull request #41 from barrucadu/github-actions
Browse files Browse the repository at this point in the history
Switch to GitHub Actions for CI
  • Loading branch information
barrucadu committed May 14, 2020
2 parents b64cccb + b316322 commit b43d467
Show file tree
Hide file tree
Showing 10 changed files with 386 additions and 306 deletions.
21 changes: 21 additions & 0 deletions .github/workflows/ci.yaml
@@ -0,0 +1,21 @@
name: Run tests

on: pull_request

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- name: Setup
run: |
set -ex
python -m pip install --upgrade pip
pip install flake8 black
- name: Lint
run: |
set -ex
flake8 .
black .
git diff --exit-code
12 changes: 0 additions & 12 deletions .travis.yml

This file was deleted.

68 changes: 37 additions & 31 deletions backend/backend.py
Expand Up @@ -41,11 +41,13 @@ def command_serve(args):
try:
with open(args["--config"], "r") as f:
config = json.loads(f.read())
except:
except FileNotFoundError:
raise Exception("--config must be a site configuration file")
except json.decoder.JSONDecodeError:
raise Exception("--config must be a site configuration file")
try:
args["PORT"] = int(args["PORT"])
except:
except ValueError:
raise Exception("PORT must be an integer between 1 and 65535")
if args["PORT"] < 1 or args["PORT"] > 65535:
raise Exception("PORT must be an integer between 1 and 65535")
Expand All @@ -57,22 +59,26 @@ def command_serve(args):

try:
db.make_superadmin()
channels, livestream = stream.start_stream_monitor(config["channels"], config["influxdb"])
web.serve(port=args["PORT"],
httpdir=args["--http-dir"],
channels=channels,
livestream=livestream)
except:
print("could not bind to port")
channels, livestream = stream.start_stream_monitor(
config["channels"], config["influxdb"]
)
web.serve(
port=args["PORT"],
httpdir=args["--http-dir"],
channels=channels,
livestream=livestream,
)
except Exception as e:
print(f"could not bind to port: {e.args[0]}")
exit(2)


def command_newuser(args):
"""Create a new user."""

new_user = db.make_user(args['USER'])
new_user = db.make_user(args["USER"])
if new_user is None:
print('User "{}" already exists!'.format(args['USER']))
print('User "{}" already exists!'.format(args["USER"]))
exit(1)

print('User "{}" created with password "{}".'.format(*new_user))
Expand All @@ -81,64 +87,64 @@ def command_newuser(args):
def command_newpass(args):
"""Change the password of a user."""

new_pass = db.change_password(args['USER'])
new_pass = db.change_password(args["USER"])
print('Changed password to "{}".'.format(new_pass))


def command_ban(args):
"""Ban a user."""

if args['USER'] == 'superadmin':
print('Cannot ban the superadmin!')
if args["USER"] == "superadmin":
print("Cannot ban the superadmin!")
exit(1)

res = db.update_dj_status(args['USER'], 'banned', True)
res = db.update_dj_status(args["USER"], "banned", True)
if res is not None:
print('User "{}" is now banned.'.format(args['USER']))
print('User "{}" is now banned.'.format(args["USER"]))


def command_unban(args):
"""Unban a user."""

res = db.update_dj_status(args['USER'], 'banned', False)
res = db.update_dj_status(args["USER"], "banned", False)
if res is not None:
print('User "{}" is now unbanned.'.format(args['USER']))
print('User "{}" is now unbanned.'.format(args["USER"]))


def command_promote(args):
"""Promote a user to admin."""

res = db.update_dj_status(args['USER'], 'admin', True)
res = db.update_dj_status(args["USER"], "admin", True)
if res is not None:
print('User "{}" is now an admin.'.format(args['USER']))
print('User "{}" is now an admin.'.format(args["USER"]))


def command_demote(args):
"""Demote an admin to user."""

if args['USER'] == 'superadmin':
print('Cannot demote the superadmin!')
if args["USER"] == "superadmin":
print("Cannot demote the superadmin!")
exit(1)

res = db.update_dj_status(args['USER'], 'admin', False)
res = db.update_dj_status(args["USER"], "admin", False)
if res is not None:
print('User "{}" is no longer an admin.'.format(args['USER']))
print('User "{}" is no longer an admin.'.format(args["USER"]))


if __name__ == "__main__":
args = docopt(__doc__)

if args['serve']:
if args["serve"]:
command_serve(args)
elif args['newuser']:
elif args["newuser"]:
command_newuser(args)
elif args['newpass']:
elif args["newpass"]:
command_newpass(args)
elif args['ban']:
elif args["ban"]:
command_ban(args)
elif args['unban']:
elif args["unban"]:
command_unban(args)
elif args['promote']:
elif args["promote"]:
command_promote(args)
elif args['demote']:
elif args["demote"]:
command_demote(args)
42 changes: 21 additions & 21 deletions backend/database.py
Expand Up @@ -6,28 +6,28 @@

# save/load livestream related data

SAVEDATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'savedata')
SAVEDATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "savedata")
if not os.path.exists(SAVEDATA_PATH):
os.mkdir(SAVEDATA_PATH)


def save_pickle(savedata):
pickle_path = os.path.join(SAVEDATA_PATH, 'livestream_save.pickle')
with open(pickle_path, 'wb') as file_handle:
pickle_path = os.path.join(SAVEDATA_PATH, "livestream_save.pickle")
with open(pickle_path, "wb") as file_handle:
pickle.dump(savedata, file_handle, protocol=pickle.HIGHEST_PROTOCOL)


def load_pickle(default):
pickle_path = os.path.join(SAVEDATA_PATH, 'livestream_save.pickle')
pickle_path = os.path.join(SAVEDATA_PATH, "livestream_save.pickle")
if not os.path.exists(pickle_path):
return default
else:
with open(pickle_path, 'rb') as file_handle:
with open(pickle_path, "rb") as file_handle:
return pickle.load(file_handle)


# our tinydb
THE_DB = TinyDB(os.path.join(SAVEDATA_PATH, 'db.json'))
THE_DB = TinyDB(os.path.join(SAVEDATA_PATH, "db.json"))


def get_a_list(of_what):
Expand All @@ -42,13 +42,13 @@ def get_a_list(of_what):
if w in user:
found_what = user[w]
insrt_row.append(found_what)
tor.append((user['id'], insrt_row))
tor.append((user["id"], insrt_row))

return tor


def make_superadmin():
new_admin = make_user('superadmin', True)
new_admin = make_user("superadmin", True)
if new_admin is not None:
print('User "superadmin" created with password "{}".'.format(new_admin[1]))

Expand All @@ -61,14 +61,14 @@ def make_user(username, admin=False):
# generates a random 32 hex digit password
password = "%032x" % random.getrandbits(128)
new_user = {
'id': username,
'password': password,
'banned': False,
'admin': admin,
'dj_name': username,
'dj_pic': '',
'stream_title': '',
'stream_desc': '',
"id": username,
"password": password,
"banned": False,
"admin": admin,
"dj_name": username,
"dj_pic": "",
"stream_title": "",
"stream_desc": "",
}

THE_DB.insert(new_user)
Expand All @@ -90,7 +90,7 @@ def update_dj_info(username, form_dict):
return False
# trust no one, even if someone modified their response we don't want them to
# most of these require different levels of permission
dont_touch = ['admin', 'banned', 'id', 'password']
dont_touch = ["admin", "banned", "id", "password"]
for k in dont_touch:
if k in form_dict:
del form_dict[k]
Expand All @@ -115,7 +115,7 @@ def change_password(username, new_pass=None):
if new_pass is None:
# generates a random 32 hex digit password
new_pass = "%032x" % random.getrandbits(128)
THE_DB.update({'password': new_pass}, check_query.id == username)
THE_DB.update({"password": new_pass}, check_query.id == username)
return new_pass


Expand All @@ -135,11 +135,11 @@ def check_state(self, what_state):

@property
def is_active(self):
return not self.check_state('banned')
return not self.check_state("banned")

@property
def is_admin(self):
return self.check_state('admin')
return self.check_state("admin")

@property
def is_authenticated(self):
Expand All @@ -162,7 +162,7 @@ def get(cls, u_id):
user_query = Query()
db_res = THE_DB.search(user_query.id == u_id)
if len(db_res) > 0:
found_user = DJUser(db_res[0]['id'], db_res[0]['password'])
found_user = DJUser(db_res[0]["id"], db_res[0]["password"])
else:
found_user = None
return found_user

0 comments on commit b43d467

Please sign in to comment.