Skip to content

Commit

Permalink
Merge pull request #113 from diggyk/quest_end_notice
Browse files Browse the repository at this point in the history
Email quest participants when a quest finishes
  • Loading branch information
jathanism committed Dec 15, 2015
2 parents 6e6d922 + 14f96f9 commit 6c131a0
Show file tree
Hide file tree
Showing 8 changed files with 135 additions and 52 deletions.
11 changes: 7 additions & 4 deletions bin/hermes
Original file line number Diff line number Diff line change
Expand Up @@ -251,19 +251,22 @@ def list_event_types(args):
if len(str(event_type["id"])) > max_length:
max_length = len(str(event_type["id"]))

print"{}{}{}".format(
print "{}{}{}{}".format(
str.ljust("ID", max_length + 4),
str.ljust("CATEGORY", 20), str.ljust("STATE", 20)
str.ljust("CATEGORY", 20),
str.ljust("STATE", 20),
str.ljust("DESC", 20)
)
for event_type in event_types["eventTypes"]:
type_id = (
str(event_type["id"]) + "*"
if event_type["restricted"] else str(event_type["id"])
)
print "{}{}{}".format(
print "{}{}{}{}".format(
str.ljust("(" + type_id + ")", max_length + 4),
str.ljust(str(event_type["category"]), 20),
str.ljust(str(event_type["state"]), 20)
str.ljust(str(event_type["state"]), 20),
str.ljust(str(event_type["description"]), 20)
)

print "\n* = restricted; cannot be thrown by hand."
Expand Down
13 changes: 6 additions & 7 deletions bin/hermes-server
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
import argparse
import logging
import os
import sys
from threading import Thread
from time import sleep
import tornado.ioloop
import tornado.httpserver
import tornado.web
Expand Down Expand Up @@ -72,10 +69,10 @@ def main():
}

# load and register any hooks we have
hooks = get_hooks([settings.plugin_dir])
for hook in hooks:
logging.debug("registering hook {}".format(hook))
models.register_hook(hook)
# hooks = get_hooks([settings.plugin_dir])
# for hook in hooks:
# logging.debug("registering hook {}".format(hook))
# models.register_hook(hook)

my_settings = {
"db_uri": settings.database,
Expand All @@ -86,6 +83,8 @@ def main():

application = Application(my_settings=my_settings, **tornado_settings)

logging.info("HERMES SERVER v{}".format(version.__version__))

# If Sentry DSN is set, try to import raven
if settings.sentry_dsn:
if not raven_installed:
Expand Down
7 changes: 4 additions & 3 deletions hermes/handlers/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import time


from .util import ApiHandler, PluginHelper
from ..util import id_generator
from .util import ApiHandler
from ..util import id_generator, PluginHelper
from .. import exc
from ..models import Host, EventType, Event, Labor, Fate, Quest
from ..settings import settings
Expand Down Expand Up @@ -2034,7 +2034,7 @@ def post(self):

tx = id_generator()

log.info("QUEST [{}]: Creating a new quest", tx)
log.info("QUEST [{}]: Creating a new quest".format(tx))

try:
fate_id = self.jbody["fateId"]
Expand Down Expand Up @@ -2473,6 +2473,7 @@ def post(self):
"""
Pass through post to the external query handler
"""

json_data = json.loads(self.request.body)
response = PluginHelper.request_post(json_body=json_data)
if (
Expand Down
32 changes: 0 additions & 32 deletions hermes/handlers/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,38 +27,6 @@ class SentryHandler(SentryMixin, RequestHandler):

API_VER = "/api/v1"

class PluginHelper(object):
@classmethod
def request_get(cls, path="", params={}):
"""Make an HTTP GET request for the given path
Args:
path: the full path to the resource
params: the query parameters to send
Returns:
the http response
"""
response = requests.get(settings.query_server + path, params=params)

return response

@classmethod
def request_post(cls, path="", params={}, json_body={}):
"""Make an HTTP POST request for the given path
Args:
path: the full path to the resource
params: the query params to send
json_body: the body of the message in JSON format
Returns:
the http response
"""
response = requests.post(
settings.query_server + path, params=params, json=json_body
)

return response


class BaseHandler(RequestHandler):
def initialize(self):
Expand Down
44 changes: 42 additions & 2 deletions hermes/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
import textwrap

from requests.exceptions import HTTPError
from sqlalchemy import create_engine, or_, union_all, desc, and_
from sqlalchemy.event import listen
from sqlalchemy.exc import IntegrityError
Expand All @@ -17,7 +18,7 @@
from sqlalchemy.types import Integer, String, Boolean, BigInteger
from sqlalchemy.types import DateTime

from .util import slack_message, email_message
from .util import slack_message, email_message, PluginHelper
from .settings import settings
import exc

Expand Down Expand Up @@ -1232,11 +1233,50 @@ def check_for_victory(self):
len(self.labors)
)

# Get all the hosts that were in this labor
all_hosts = []
for labor in self.labors:
all_hosts.append(labor.host.hostname)
hosts = set(all_hosts)
hostnames = list(hosts)

# Now, look up the owners of those hosts
owners = []
try:
all_owners = []
log.info("Looking up participants {}".format(", ".join(hostnames)))
response = PluginHelper.request_post(
json_body={"hostnames": hostnames}
)
results = response.json()['results']
for host in hostnames:
all_owners.append(results[host])
owners = list(set(all_owners))
except HTTPError:
log.error(
"Quest {} could not load participants "
"to email about closure: {}".format(
self.id, response.status_code
)
)
except ValueError:
log.error(
"Quest {} could not load participants b/c of JSON error"
.format(self.id)
)
except Exception:
log.error(
"Quest {} could not load participants "
"b/c something horrible happened".format(self.id)
)

# Email quest creator and CC the participants
email_message(
self.creator, "Quest {} completed".format(self.id),
msg
msg, cc=owners
)


@classmethod
def get_open_quests(cls, session):
"""Get a list of open Quests
Expand Down
2 changes: 2 additions & 0 deletions hermes/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,6 @@ def __getattr__(self, name):
"auth_token_expiry": 600, # 10 minutes
"sentry_dsn": None,
"plugin_dir": "plugins ",
"environment": "dev",
"dev_email_recipient": "",
})
76 changes: 73 additions & 3 deletions hermes/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def slack_message(message):
log.warn("Error writing to Slack: {}".format(exc.message))


def email_message(recipients, subject, message, html_message=None):
def email_message(recipients, subject, message, html_message=None, cc=None):
"""Email a message to a user.
Args:
Expand All @@ -79,6 +79,38 @@ def email_message(recipients, subject, message, html_message=None):
else:
extra_recipients = [settings.email_always_copy]

if cc and isinstance(cc, basestring):
extra_recipients.append(cc)
elif cc:
extra_recipients.extend(cc)

# If this is the dev environment, we need to only send to the dev recipient
# and put a tag explaining what would have happened

if settings.environment == "dev":
recipients_statement = "To: {} CC: {}\n".format(
recipients, extra_recipients
)
subject = "[DEV] {}".format(subject)
message = (
"[DEV]: Sent to {}\nOriginally addressed as: {}\n\n{}".format(
settings.dev_email_recipient,
recipients_statement,
message
)
)
if html_message:
html_message = (
"<p><strong>DEV:</strong> Sent to {}<br />"
"Originally addressed as: {}<br/></p>{}".format(
settings.dev_email_recipient,
recipients_statement,
html_message
)
)
recipients = [settings.dev_email_recipient]
extra_recipients = []

part1 = MIMEText(message, 'plain')
if html_message:
part2 = MIMEText(html_message, 'html')
Expand All @@ -95,8 +127,13 @@ def email_message(recipients, subject, message, html_message=None):
msg["Subject"] = subject
msg["From"] = settings.email_sender_address
msg["To"] = ", ".join(recipients)
if extra_recipients:
msg["Cc"] = ", ".join(extra_recipients)
msg["Cc"] = ", ".join(extra_recipients)

logging.debug("Sending email: From {}, To {}, Msg: {}".format(
settings.email_sender_address,
recipients + extra_recipients,
msg.as_string()
))

try:
smtp = smtplib.SMTP("localhost")
Expand All @@ -108,3 +145,36 @@ def email_message(recipients, subject, message, html_message=None):
smtp.quit()
except Exception as exc:
log.warn("Error sending email: {}".format(exc.message))


class PluginHelper(object):
@classmethod
def request_get(cls, path="", params={}):
"""Make an HTTP GET request for the given path
Args:
path: the full path to the resource
params: the query parameters to send
Returns:
the http response
"""
response = requests.get(settings.query_server + path, params=params)

return response

@classmethod
def request_post(cls, path="", params={}, json_body={}):
"""Make an HTTP POST request for the given path
Args:
path: the full path to the resource
params: the query params to send
json_body: the body of the message in JSON format
Returns:
the http response
"""
response = requests.post(
settings.query_server + path, params=params, json=json_body
)

return response
2 changes: 1 addition & 1 deletion hermes/webapp/src/templates/laborList.html
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@
<img src="/img/loading.gif"/>
</div>
<!--LABOR ENTRY REPEATER-->
<div class="labor-list-row" ng-if="lsc.laborData && !lsc.errorMessage"
<div class="labor-list-row" ng-if="lsc.laborData"
ng-repeat="labor in (pageData = (lsc.laborData | limitTo:lsc.limit:lsc.offset)) track by labor.id">
<!-- QUEST HEADER -->
<div class="quest-info" ng-if="labor.quest && labor.quest.id != pageData[$index-1].quest.id">
Expand Down

0 comments on commit 6c131a0

Please sign in to comment.