Skip to content

Commit

Permalink
Discord notifications - basic support
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbolvansky committed Oct 7, 2023
1 parent 67bd4bb commit 3824beb
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 21 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ New features:
* Added column 'Username' in 'Job Info' -> 'Hashes'.
* Added column 'Username' in 'Hashes'.
* Added dropdown menu to specify input format.
* Discord notifications.

General improvements:
* Improved/reimplemeted generator and scheduling logic. Better precision, more predictable workunit sizes. Default desired seconds per workunit changed to 600 seconds.
Expand Down
13 changes: 6 additions & 7 deletions backend/src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
from src.api.fitcrack.endpoints.pcfg.pcfg import ns as pcfg_ns
from src.api.fitcrack.endpoints.settings.settings import ns as settings_ns

from src.api.fitcrack.endpoints.notifications.notifier import notify

from src.database import db
from src.database.models import FcUser

Expand Down Expand Up @@ -122,17 +124,14 @@ def main():

db.init_app(app)

def my_job():
def notifier():
with app.app_context():
# Read from User table
users = FcUser.query.all()
print("List of users:")
for user in users:
print(user.username)
for user in FcUser.query.all():
notify(user.id)

scheduler = APScheduler()
scheduler.init_app(app)
# scheduler.add_job(id='my_job_id', func=my_job, trigger='interval', seconds=5)
scheduler.add_job(id='notifier', func=notifier, trigger='interval', seconds=10)
scheduler.start()

if __name__ == "__main__":
Expand Down
1 change: 1 addition & 0 deletions backend/src/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ msgpack==1.0.4
PyJWT==2.7.0
werkzeug==2.3.7
SQLAlchemy==2.0.20
apprise==1.5.0
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@ def get(self):
args = notifications_parser.parse_args(request)
page = args.get('page', 1)
per_page = args.get('per_page', 10)
markAsSeen = args.get('seen', True)
mark_as_seen = args.get('seen', True)

notifications = getNotifications(current_user.id, page, per_page, markAsSeen)
# notifications = getNotifications(7, page, per_page, markAsSeen)
notifications = getNotifications(current_user.id, page, per_page, mark_as_seen)
return notifications

@ns.route('/count')
Expand All @@ -50,6 +49,4 @@ def get(self):
count = FcNotification.query.filter(FcNotification.user_id == current_user.id).filter(
FcNotification.seen == False).count()

# count = FcNotification.query.filter(FcNotification.user_id == 7).filter(
# FcNotification.seen == False).count()
return {'count': count}
31 changes: 31 additions & 0 deletions backend/src/src/api/fitcrack/endpoints/notifications/notifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import apprise

from src.database.models import FcNotification, FcSettings, FcUser
from src.database import db

from src.api.fitcrack.lang import job_status_text_info_to_code_dict

class Notification:
def __init__(self, title, body):
self.title = title
self.body = body

def notify(userId):
settings = FcSettings.query.filter_by(user_id=userId).one()
apobj = apprise.Apprise()

if settings.discord_notifications:
apobj.add(settings.discord_webhook_url)

for user in FcUser.query.all():
new_notifications = FcNotification.query.filter(FcNotification.user_id == userId).filter(FcNotification.discord_sent == False)

for notif in new_notifications:
title = notif.source.name if notif.source else '<Removed Job>'
body = title + ": " + job_status_text_info_to_code_dict[notif.new_value]
print(title, body)

apobj.notify(body=body)
notif.discord_sent = True

db.session.commit()
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@
settings_arguments.add_argument('verify_hash_format', type=bool, help='', required=False, location='json')
settings_arguments.add_argument('auto_add_hosts_to_running_jobs', type=bool, help='', required=False, location='json')
settings_arguments.add_argument('bench_runtime_limit', type=int, help='', required=False, location='json')
settings_arguments.add_argument('workunit_status_update', type=int, help='', required=False, location='json')
settings_arguments.add_argument('workunit_status_update', type=int, help='', required=False, location='json')

settings_arguments.add_argument('discord_notifications', type=bool, help='', required=False, location='json')
settings_arguments.add_argument('discord_webhook_url', type=str, help='', required=False, location='json')
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@
'auto_add_hosts_to_running_jobs': fields.Boolean(),
'bench_runtime_limit': fields.Integer(),
'workunit_status_update': fields.Integer(),
'discord_notifications': fields.Boolean(),
'discord_webhook_url': fields.String(),
})
16 changes: 15 additions & 1 deletion backend/src/src/api/fitcrack/endpoints/settings/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from src.api.fitcrack.endpoints.settings.responseModels import settings_model
from src.api.fitcrack.responseModels import simpleResponse
from src.database import db
from src.database.models import FcSettings
from src.database.models import FcSettings, FcNotification

log = logging.getLogger(__name__)
ns = api.namespace('settings', description='Endpoints for manipulating system settings.')
Expand Down Expand Up @@ -47,6 +47,9 @@ def post(self):
bench_runtime_limit = args['bench_runtime_limit']
workunit_status_update = args['workunit_status_update']

discord_notifications = args['discord_notifications']
discord_webhook_url = args['discord_webhook_url']

settings = FcSettings.query.filter_by(user_id=current_user.id).one_or_none()
if not settings:
abort(404, 'User settings not found.')
Expand All @@ -58,6 +61,17 @@ def post(self):
if (auto_add_hosts_to_running_jobs is not None): settings.auto_add_hosts_to_running_jobs = auto_add_hosts_to_running_jobs
if (bench_runtime_limit is not None): settings.bench_runtime_limit = bench_runtime_limit
if (workunit_status_update is not None): settings.workunit_status_update = workunit_status_update

if discord_notifications:
if not discord_webhook_url:
abort(400, 'Discord webhook URL is required when enabling Discord notifications.')
settings.discord_notifications = discord_notifications

FcNotification.query.filter(FcNotification.user_id == current_user.id).update({FcNotification.discord_sent: True})

if discord_webhook_url:
settings.discord_webhook_url = discord_webhook_url

db.session.commit()

return {
Expand Down
4 changes: 4 additions & 0 deletions backend/src/src/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,9 @@ class FcSettings(Base):
bench_runtime_limit = Column(Integer, nullable=False, server_default=text("'30'"))
workunit_status_update = Column(Integer, nullable=False, server_default=text("'5'"))

discord_notifications = Column(Integer, nullable=False, server_default=text("'0'"))
discord_webhook_url = Column(String(200), nullable=True)

user = relationship('FcUser')

class FcJobGraph(Base):
Expand Down Expand Up @@ -763,6 +766,7 @@ class FcNotification(Base):
old_value = Column(SmallInteger)
new_value = Column(SmallInteger)
seen = Column(Integer, server_default=text("'0'"))
discord_sent = Column(Integer, server_default=text("'0'"))
time = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))

source = relationship('FcJob')
Expand Down
36 changes: 30 additions & 6 deletions frontend/src/components/settings/settingsView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@
</v-card-text>

<v-card-title>
<v-icon left>
mdi-cursor-pointer
</v-icon>
<span>Behavior</span>
</v-card-title>
<v-card-text>
<v-icon left>
mdi-cursor-pointer
</v-icon>
<span>Behavior</span>
</v-card-title>
<v-card-text>
<v-row>
<v-col>
<v-switch
Expand Down Expand Up @@ -146,6 +146,30 @@
/>
</v-row>
</v-card-text>

<v-card-title>
<v-icon left>
mdi-alert-circle-outline
</v-icon>
<span>Notifications</span>
</v-card-title>
<v-card-text>
<v-switch
v-model="settings.discord_notifications"
:loading="loading"
outlined
label="Discord notifications"
persistent-hint
class="mb-4 mt-0"
/>
<v-text-field
v-model="settings.discord_webhook_url"
outlined
label="Discord webhook URL"
persistent-hint
class="mb-4 mt-0"
/>
</v-card-text>
</v-card>
<v-expansion-panels flat class="mt-6">
<v-expansion-panel>
Expand Down
4 changes: 4 additions & 0 deletions server/sql/10_create_tables.sql
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ CREATE TABLE IF NOT EXISTS `fc_notification` (
`old_value` smallint(6) DEFAULT NULL,
`new_value` smallint(6) DEFAULT NULL,
`seen` tinyint(1) DEFAULT '0',
`discord_sent` tinyint(1) DEFAULT '0',
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
Expand Down Expand Up @@ -493,6 +494,9 @@ CREATE TABLE IF NOT EXISTS `fc_settings` (
`auto_add_hosts_to_running_jobs` tinyint(1) unsigned NOT NULL DEFAULT '0',
`bench_runtime_limit` int(10) unsigned NOT NULL DEFAULT '30',
`workunit_status_update` int(10) unsigned NOT NULL DEFAULT '5',

`discord_notifications` tinyint(1) unsigned NOT NULL DEFAULT '0',
`discord_webhook_url` varchar(200) NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Expand Down
2 changes: 1 addition & 1 deletion server/sql/20_create_triggers.sql
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ CREATE TRIGGER `job_notification` AFTER UPDATE ON `fc_job`
IF done THEN
LEAVE user_loop;
END IF;
INSERT INTO fc_notification VALUES (DEFAULT, userID, DEFAULT,NEW.id,OLD.status,NEW.status,DEFAULT, DEFAULT);
INSERT INTO fc_notification VALUES (DEFAULT, userID, DEFAULT,NEW.id,OLD.status,NEW.status, DEFAULT, DEFAULT, DEFAULT);
END LOOP;
CLOSE usersCursor;
END IF;
Expand Down

0 comments on commit 3824beb

Please sign in to comment.