Skip to content
Snippets Groups Projects
Commit 7b961a3b authored by Davide Vaghetti's avatar Davide Vaghetti
Browse files

eduGAIN Communication Challenge first commit

parent 60cb5159
Branches
No related tags found
No related merge requests found
# emacs
*~
\#*\#
# vi
*.swp
# Compiled python modules
*.pyc
# Tests artifacts
.cache
__pycache__
# Python
*.egg-info
bin
include
lib
share
#venv
venv
#coverage
.coverage
#vscode
.vscode
#pycharm
.idea
#db
db.sqlite3
# IdP-in-the-Cloud environment
.env
# IdM logs
*.log
# File temporanei e migrazioni
indire/data/tmp/*
indire/accounts/migrations/0*
indire/ldap_accounts/migrations/0*
indire/institutions/migrations/0*
#Staticfiles
staticfiles
#Setting file
settings.py
\ No newline at end of file
# Commchlng # Commchlng
This repository contains the tools used to run the eduGAIN Communication Challenge:
https://wiki.geant.org/display/eduGAIN/Communication+Challenges
## Getting started ## Components
To make it easy for you to get started with GitLab, here's a list of recommended next steps. `reaction-master/reaction.py` provides the web services to measure the reaction time.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! `reaction-mailcreate-master/createMails.py` creates the emails with the links to check
the reaction time.
## Add your files ## Licenses
`reaction-master/reaction.py` is licensed with GNU GPL version 3 or later.
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files `reaction-mailcreate-master/createMails.py` is licensed under the GNU Affero GPL.
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.software.geant.org/edugain/commchlng.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.software.geant.org/edugain/commchlng/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment ## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status Authors of the software are Tobias Dussa from DFN-CERT and EGI developers.
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
This diff is collapsed.
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Reaction Mailcreate
# Copyright (C) 2020 Tobias Dussa <tobias-reaction-mailcreate@dussa.de>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from email.message import EmailMessage
from email.utils import formatdate
import argparse
import csv
import datetime
import getpass
import hashlib
import jinja2
import os
import requests
import secrets
import smtplib
import sys
parser = argparse.ArgumentParser()
if sys.version_info < (3, 8):
class ExtendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest) or []
items.extend(values)
setattr(namespace, self.dest, items)
parser.register('action', 'extend', ExtendAction)
# Parse args
parser.add_argument('-b', '--basedir', dest='basedir', default='Mails', help='base directory for all output (default: "Mails")')
parser.add_argument('-B', '--bcc', dest='bcc', default=[], nargs=1, action='extend', help='additional mail recipient to bcc (default: None)')
parser.add_argument('-c', '--campaign', dest='campaign', default='Test', help='campaign name (default: "Test")')
parser.add_argument('-d', '--dry-run', dest='dryrun', default=False, action='store_true', help='dry run -- do not actually send mails or create targets (default: False)')
parser.add_argument('-f', '--from', dest='sender', default='Nobody <nobody@example.com>', help='sender mail address (default: "Nobody <nobody@example.com>"; implies dry-run if not set)')
parser.add_argument('-F', '--force', dest='force', default=False, action='store_true', help='force insecure login without TLS/SSL (default: False)')
parser.add_argument('-H', '--hashstring', dest='hashstring', default='{salt}{campaign}{infix}-{site}', help='string to be hashed for the URL (default: "{salt}{campaign}{infix}-{site}" where "{salt}" is a random string)')
parser.add_argument('-i', '--input', dest='input', default='{basedir}/{campaign}/Input{infix}.lst', help='input file (default: "{basedir}/{campaign}/Input{infix}.lst")')
parser.add_argument('-o', '--output', dest='output', default='{basedir}/{campaign}/{site}/Mail{infix}.txt', help='output file name template (default: "{basedir}/{campaign}/{site}/Mail{infix}.txt")')
parser.add_argument( '--salt', dest='salt', default=None, help='salt to use for hashing (default: random 8-byte hex string)')
parser.add_argument('-R', '--reply-to', dest='replyto', default=None, help='reply-to mail address (default: None)')
parser.add_argument('-s', '--subject', dest='subject', default='Security Challenge for {site} -- {campaign}{infix}', help='mail subject (default: "Security Challenge Message -- {campaign}{infix}")')
parser.add_argument('-S', '--smtpserver', dest='smtpserver', default='localhost', help='SMTP server to use (default: "localhost"); port can be specified with "<host>:<port>" notation and takes precedence over implied ports and port specification')
parser.add_argument( '--smtpport', dest='smtpport', default=0, type=int, help='SMTP port to use (default: 25); takes precedence over implied ports')
parser.add_argument( '--smtpuser', dest='smtpuser', default=None, help='SMTP user to login with (default: none); implies TLS (port 465) unless STARTTLS is set as well')
parser.add_argument( '--smtppass', dest='smtppass', default=None, help='SMTP password to login with (default: none); implies TLS (port 465) unless STARTTLS is set as well; will be queried interactively if set to "-"')
parser.add_argument( '--starttls', dest='starttls', default=False, action='store_true', help='login using STARTTLS (default: False); implies port 587')
parser.add_argument('-t', '--template', dest='template', default='{basedir}/{campaign}/Mail.template', help='mail template file (default: "{basedir}/{campaign}/Mail.template")')
parser.add_argument('-T', '--to', dest='to', default='{firstname} {lastname} <{email}>', help='recipient mail address (default: "{firstname} {lastname} <{email}>")')
parser.add_argument('-u', '--url', dest='url', default='{webserver}/{campaign}{infix}-{hash}', help='URL template to use (default: "{webserver}/{campaign}{infix}-{hash}"')
parser.add_argument('-v', '--verbose', dest='verbose', default=False, action='store_true', help='increase verbosity')
parser.add_argument('-w', '--webserver', dest='webserver', default='https://challenge.example.com', help='web server to use (default: "https://challenge.example.com"; implies dry-run if not set')
parser.add_argument('infix', default='', nargs='?', help='infix for ID purposes, default empty')
args = parser.parse_args()
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
if (args.sender == 'Nobody <nobody@example.com>') or \
(args.webserver == 'https://challenge.example.com'):
args.dryrun = True
if (len(args.smtpserver.split(':')) == 2) or \
(']:' in args.smtpserver):
args.smtpport = args.smtpserver.rsplit(':', 1)[1]
args.smtpserver = args.smtpserver.rsplit(':', 1)[0]
if (args.smtpport == 0):
if args.starttls:
args.smtpport = 587
elif args.smtpuser or args.smtppass:
args.smtpport = 465
else:
args.smtpport = 25
if args.smtpuser and not args.smtppass:
args.smtppass = ''
if args.smtppass and not args.smtpuser:
args.smtpuser = ''
if args.smtppass == '-':
args.smtppass = getpass.getpass('SMTP authentication password: ')
if args.dryrun:
print('DRY RUN. Not actually sending e-mails or creating targets, just creating mail files and URLs.')
if args.force:
print('FORCE INSECURE LOGIN. Will send authentication data even if no secure connection can be established.')
if args.starttls:
print('STARTTLS enabled.')
elif args.verbose:
print('STARTTLS disabled.')
# Generate salt to use for secure hashing if unset
if not args.salt:
args.salt = secrets.token_hex(8)
if args.verbose:
print(f'Using "{args.basedir}" as base directory.')
if args.bcc:
print(f'Using "{", ".join(args.bcc)}" as silent mail recipients.')
print(f'Using "{args.campaign}" as campaign.')
print(f'Using "{args.sender}" as sender mail address.')
if args.replyto:
print(f'Using "{args.replyto}" as reply-to mail address.')
print(f'Using "{args.hashstring.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver))}" as hash string.')
print(f'Using "{args.input.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as input file.')
print(f'Using "{args.output.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as output file name template.')
print(f'Using "{args.salt.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as salt.')
print(f'Using "{args.subject.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as mail subject.')
print(f'Using "{args.template.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as template file.')
print(f'Using "{args.to.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as recipient mail address.')
print(f'Using "{args.url.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))}" as URL template.')
print(f'Using "{args.webserver}" as web server.')
print(f'Using "{args.infix}" as infix.')
print(f'Using "{args.smtpserver}" as SMTP server.')
print(f'Using {str(args.smtpport)} as SMTP port.')
if args.smtpuser:
print(f'Using "{args.smtpuser}" as user for SMTP authentication.')
if args.smtppass:
print('Using "{args.smtppass}" as password for SMTP authentication.')
if (args.smtpuser or args.smtppass) and \
(args.smtpport == 25) and \
not args.starttls and \
not args.force:
print('SMTP authentication specified, but port 25 used (without STARTTLS). Bailing out.')
sys.exit(-1)
elif args.force:
print('WARNING: SMTP authentication specified, but port 25 used (without STARTTLS)!')
data = dict()
template = jinja2.Template(open(args.template.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt))).read())
def toHex(serial):
tmpString = hex(serial)[2:].upper()
if ((len(tmpString) % 2) == 1):
tmpString = '0' + tmpString
return ':'.join([tmpString[i:i+2] for i in range(0, len(tmpString), 2)])
def createMail(data):
output = args.output.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash'], URL=data['URL']))
directory = os.path.dirname(output)
print(f'Writing mail to {output}')
if not os.path.exists(directory):
os.makedirs(directory)
with open(output, 'wb') as mailfile:
template.stream(data).dump(mailfile, encoding='utf-8')
message = EmailMessage()
with open(output, 'r') as mailfile:
message.set_content(mailfile.read())
message['Date'] = formatdate(localtime=True)
message['Subject'] = args.subject.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash'], URL=data['URL']))
message['From'] = args.sender.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash'], URL=data['URL']))
message['Reply-To'] = args.replyto.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash'], URL=data['URL']))
message['To'] = args.to.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash'], URL=data['URL']))
message['Bcc'] = ', '.join(args.bcc).format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash'], URL=data['URL']))
if not args.dryrun:
if message['Bcc']:
print(f'Sending mail to {message["To"]} (and {message["Bcc"]})')
else:
print(f'Sending mail to {message["To"]}')
if args.starttls:
with smtplib.SMTP(args.smtpserver, args.smtpport) as smtp:
smtp.starttls()
smtp.login(args.smtpuser, args.smtppass)
smtp.send_message(message)
elif args.smtpuser or args.smtppass:
with smtplib.SMTP_SSL(args.smtpserver, args.smtpport) as smtp:
smtp.login(args.smtpuser, args.smtppass)
smtp.send_message(message)
else:
with smtplib.SMTP(args.smtpserver, args.smtpport) as smtp:
smtp.send_message(message)
print(f'Creating target at {data["URL"]}/create')
requests.get(f'{data["URL"]}/create')
def generateHashAndURL(data):
data['hash'] = hashlib.sha256(args.hashstring.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'])).encode('utf-8')).hexdigest()
data['URL'] = args.url.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt, site=data['site'], firstname=data['firstname'], lastname=data['lastname'], email=data['email'], hash=data['hash']))
with open(args.input.format_map(SafeDict(basedir=args.basedir, campaign=args.campaign, infix=args.infix, webserver=args.webserver, salt=args.salt)), 'r') as inputfile:
data = csv.DictReader(inputfile, fieldnames=['site', 'firstname', 'lastname', 'email'], delimiter=',')
for row in data:
if (row['site'] != 'site') or \
(row['firstname'] != 'firstname') or \
(row['lastname'] != 'lastname') or \
(row['email'] != 'email'):
generateHashAndURL(row)
createMail(row)
jinja2
requests
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# reaction
# Copyright (C) 2021 EGI-IRTF
#
# 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/>.
from datetime import datetime, timedelta
try:
from jinja2 import Template
jinja2 = True
except:
jinja2 = False
import glob
import io
import os
try:
import matplotlib.pyplot as plot
matplotlib = True
except:
matplotlib = False
BASEDIR = 'stats/'
if jinja2:
LATEXTEMPLATE = Template(r'''
<pre>
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{width=\textwidth,compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
title={Communication Challenge -- {{title}}},
xlabel={Time [hours]},
ylabel={Reactions [number of participants]},
xmin=0, xmax={{xmax}},
ymin=0, ymax={{ymax}},
legend pos=south east,
ymajorgrids=true,
grid style=dashed,
]
\addplot[color=blue, mark=square]
coordinates { {{coordinates}} };
\addlegendentry{ {{responses}} participants ({{percentageResponses}}\,\%) have reacted}
\addplot[color=red]
coordinates { (0, {{sitesNumber}})({{xmax}}, {{sitesNumber}}) };
\addlegendentry{ {{sitesNumber}} participants have been challenged}
\addplot[color=green]
coordinates { (24, 0)(24, {{ymax}}) };
\addlegendentry{ {{quickSitesNumber}} participants ({{percentageQuick}}\,\%) have reacted within 24 h}
\end{axis}
\end{tikzpicture}
\end{document}
</pre>
''')
def floatPart(string):
return(float(string.split('/')[-1].split('-', 1)[0]))
def hashtagPart(string):
return(string.split('/')[-1].split('-', 1)[-1])
class ReactionApp(object):
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def format(self, code, msg):
self.start(code, [('Content-type', 'text/html; charset=UTF-8')])
return '<html><body><p>{msg}</p></body></html>'.format(msg=msg).encode('UTF-8')
def image(self, code, type, image):
self.start(code, [('Content-type', 'image/{}'.format(type))])
return image
def updatefile(self, folder, hashtag):
with open(folder + hashtag, 'a') as tagfile:
tagfile.write(str((datetime.now()-datetime(1970, 1, 1)).total_seconds()) + '\n')
def checkresults(self, folder, hashtag):
if os.path.isfile(folder + '.LOCKED'):
return self.format('200 OK', 'This campaign has been closed!')
with open(folder + hashtag, 'r') as tagfile:
lines = tagfile.read().splitlines()
if len(lines) < 2:
return self.format('500 Internal Server Error', 'Unfortunately, this campaign is broken!')
elapsedtime = datetime.fromtimestamp(float(lines[1])) - datetime.fromtimestamp(float(lines[0]))
if not os.path.isfile(folder + str(elapsedtime.total_seconds()) + '-' + hashtag):
open(folder + str(elapsedtime.total_seconds()) + '-' + hashtag, 'a').close()
responses = glob.glob(folder + '*-*')
responses.sort(key=floatPart)
responses = list(map(hashtagPart, responses))
message = '<p>Reaction time: ' + str(elapsedtime) + '</p>'
return self.format('200 OK', message)
def gatherdata(self, folder):
if not os.path.isdir(folder):
return False
responseFiles = glob.glob(folder + '*-*')
data = {}
data['title'] = folder.split('/')[-2]
data['sites'] = set([hashtagPart(x) for x in glob.glob(folder + '*')])
data['sitesNumber'] = len(data['sites'])
data['responses'] = len(responseFiles)
data['responseTimes'] = {hashtagPart(x): floatPart(x) for x in responseFiles}
data['responsePoints'] = {hashtagPart(x): os.path.getctime(x) for x in responseFiles}
data['missingSites'] = list(filter(lambda x: x not in data['responseTimes'], data['sites']))
data['missingSitesNumber'] = len(data['missingSites'])
data['quickSites'] = list(filter(lambda x: x<(24*3600), data['responseTimes'].values()))
data['quickSitesNumber'] = len(data['quickSites'])
data['percentageResponses'] = round(100*data['responses']/len(data['sites']))
data['percentageQuick'] = round(100*len(data['quickSites'])/len(data['sites']))
return data
def getresults(self, folder):
ReactionApp.getresults.rank = 0
def steprank():
ReactionApp.getresults.rank += 1
return(ReactionApp.getresults.rank)
if not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
data = self.gatherdata(folder)
message = '<h1>Communication Challenge — {title}'.format_map(data)
message += ' {status} Results</h1>'
message += '{responses} participants ({percentageResponses} %) have reacted<br>'.format_map(data)
message += '{sitesNumber} participants have been challenged<br>'.format_map(data)
message += '{quickSitesNumber} participants ({percentageQuick} %) have reacted within 24 h<br>'.format_map(data)
message += '<h2>Reaction Times</h2>'
message += '<table cellspacing="2" cellpadding="5" bgcolor="#000000"><tr bgcolor="#ffffff"><th align="left">Sequence #</th><th align="left">Timestamp</th><th align="left">Participant</th><th align="left">Reaction Time</th></tr>'
message += '<tr bgcolor="#ffffff">' + '</tr><tr bgcolor="#ffffff">'.join(map(lambda x: '<td align="right">'+str(steprank())+'</td><td>'+datetime.fromtimestamp(data['responsePoints'][x], tz=datetime.now().astimezone().tzinfo).isoformat()+'</td><td><code>'+x+'</code></td><td align="right">'+str(timedelta(seconds=data['responseTimes'][x]))+'</td>', sorted(data['responseTimes'].keys(), key=lambda x: data['responseTimes'][x]))) + '</tr></table>'
if (data['missingSitesNumber'] > 0):
message += '<h2>Missing Reactions</h2>'
message += '<ul><li><code>' + '...</code></li><li><code>'.join(map(lambda x: x[0:48], sorted(data['missingSites']))) + '...</code></li></ul>'
status = 'Preliminary'
else:
status = 'Final'
if os.path.isfile(folder + '.LOCKED'):
status = 'Final'
return self.format('200 OK', message.format(status=status))
usa def getlatex(self, folder):
if not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
data = self.gatherdata(folder)
responseTimes = [round(x/3600, 3) for x in data['responseTimes'].values()]
responseTimes.sort()
data['coordinates'] = '(0, 0)'
data['coordinates'] += ''.join(['('+str(responseTimes[x])+', '+str(x+1)+')' for x in range(data['responses'])])
data['xmax'] = round(max(responseTimes) * 1.2, -1)
data['ymax'] = round(data['sitesNumber'] * 1.2, -1)
return self.format('200 OK', LATEXTEMPLATE.render(data))
def getgraph(self, folder, format):
if not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
data = self.gatherdata(folder)
responseTimes = [round(x/3600, 3) for x in data['responseTimes'].values()]
responseTimes.append(0)
responseTimes.sort()
xmax = round(max(responseTimes) * 1.2, -1)
ymax = round(data['sitesNumber'] * 1.2, -1)
plot.figure()
plot.plot(responseTimes, range(data['responses']+1), marker='.', color='blue', label='{responses} participants ({percentageResponses} %) have reacted'.format_map(data), zorder=3)
plot.axhline(y=data['sitesNumber'], color='red', label='{sitesNumber} participants have been challenged'.format_map(data), zorder=2)
plot.axvline(x=24, color='lightgreen', label='{quickSitesNumber} participants ({percentageQuick} %) have reacted within 24 h'.format_map(data), zorder=1)
plot.title('Communication Challenge — {title}'.format_map(data))
plot.xlabel('Time [hours]')
plot.ylabel('Reactions [number of participants]')
plot.legend(loc='lower right')
plot.plot
with io.BytesIO() as buffer:
plot.savefig(buffer, format=format)
buffer.seek(0)
return self.image('200 OK', format, buffer.read())
def process(self):
path = self.environ['PATH_INFO'].split('/')[1:]
try:
prefix, hashtag = path[0].rsplit('-', 1)
except ValueError:
prefix = ''
hashtag = path[0]
try:
int(hashtag, 16)
except (KeyError, ValueError):
return self.format('400 Bad Request', 'This is not a valid link!')
if prefix:
folder = os.path.abspath(BASEDIR + prefix) + '/'
if not folder.startswith(BASEDIR):
self.format('400 Bad Request', 'Good try!')
else:
folder = BASEDIR
if not os.path.isfile(folder + hashtag):
if len(path) == 2 and path[1] == 'create':
if not os.path.isdir(folder):
os.makedirs(folder)
self.updatefile(folder, hashtag)
return self.format('200 OK', 'File {tag} created'.format(tag=hashtag))
elif len(path) != 1:
return self.format('400 Bad Request', 'What are you trying to do?')
elif not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
else:
return self.format('404 Not Found', 'This id does not exist!')
if 'HTTP_REFERER' in self.environ:
referer = self.environ['HTTP_REFERER']
else:
referer = ''
if 'HTTPS' in self.environ and self.environ['HTTPS']:
url = 'https://'
else:
url = 'http://'
url += '{host}{URI}'.format(host=self.environ['HTTP_HOST'],
URI=self.environ['REQUEST_URI'])
if referer == url:
self.updatefile(folder, hashtag)
return self.checkresults(folder, hashtag)
elif len(path) == 2:
if path[1] == 'results':
return self.getresults(folder)
elif path[1] == 'graph' and matplotlib:
return self.getgraph(folder, 'png')
elif path[1] == 'latex' and jinja2:
return self.getlatex(folder)
else:
return self.format('400 Bad Request', 'Nice try!')
elif len(path) == 3 and path[1] == 'graph' and matplotlib:
if path[2] == 'jpg':
return self.getgraph(folder, 'jpg')
elif path[2] == 'pdf':
return self.getgraph(folder, 'pdf')
elif path[2] == 'png':
return self.getgraph(folder, 'png')
elif path[2] == 'svg':
return self.getgraph(folder, 'svg')
else:
return self.format('400 Bad Request', 'Nice try!')
elif os.path.isfile(folder + '.LOCKED'):
return self.format('200 OK', 'This campaign has been closed!')
else:
return self.format('200 OK', 'Please click <a href="{URL}">here</a> to confirm your submission!'.format(URL=url))
def __iter__(self):
yield self.process()
This diff is collapsed.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# reaction
# Copyright (C) 2021 EGI-IRTF
#
# 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/>.
from datetime import datetime, timedelta
try:
from jinja2 import Template
jinja2 = True
except:
jinja2 = False
import glob
import io
import os
try:
import matplotlib.pyplot as plot
matplotlib = True
except:
matplotlib = False
BASEDIR = 'stats/'
if jinja2:
LATEXTEMPLATE = Template(r'''
<pre>
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{width=\textwidth,compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
title={Communication Challenge -- {{title}}},
xlabel={Time [hours]},
ylabel={Reactions [number of participants]},
xmin=0, xmax={{xmax}},
ymin=0, ymax={{ymax}},
legend pos=south east,
ymajorgrids=true,
grid style=dashed,
]
\addplot[color=blue, mark=square]
coordinates { {{coordinates}} };
\addlegendentry{ {{responses}} participants ({{percentageResponses}}\,\%) have reacted}
\addplot[color=red]
coordinates { (0, {{sitesNumber}})({{xmax}}, {{sitesNumber}}) };
\addlegendentry{ {{sitesNumber}} participants have been challenged}
\addplot[color=green]
coordinates { (24, 0)(24, {{ymax}}) };
\addlegendentry{ {{quickSitesNumber}} participants ({{percentageQuick}}\,\%) have reacted within 24 h}
\end{axis}
\end{tikzpicture}
\end{document}
</pre>
''')
def floatPart(string):
return(float(string.split('/')[-1].split('-', 1)[0]))
def hashtagPart(string):
return(string.split('/')[-1].split('-', 1)[-1])
class ReactionApp(object):
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def format(self, code, msg):
self.start(code, [('Content-type', 'text/html; charset=UTF-8')])
return '<html><body><p>{msg}</p></body></html>'.format(msg=msg).encode('UTF-8')
def image(self, code, type, image):
self.start(code, [('Content-type', 'image/{}'.format(type))])
return image
def updatefile(self, folder, hashtag):
with open(folder + hashtag, 'a') as tagfile:
tagfile.write(str((datetime.now()-datetime(1970, 1, 1)).total_seconds()) + '\n')
def checkresults(self, folder, hashtag):
if os.path.isfile(folder + '.LOCKED'):
return self.format('200 OK', 'This campaign has been closed!')
with open(folder + hashtag, 'r') as tagfile:
lines = tagfile.read().splitlines()
if len(lines) < 2:
return self.format('500 Internal Server Error', 'Unfortunately, this campaign is broken!')
elapsedtime = datetime.fromtimestamp(float(lines[1])) - datetime.fromtimestamp(float(lines[0]))
if not os.path.isfile(folder + str(elapsedtime.total_seconds()) + '-' + hashtag):
open(folder + str(elapsedtime.total_seconds()) + '-' + hashtag, 'a').close()
responses = glob.glob(folder + '*-*')
responses.sort(key=floatPart)
responses = list(map(hashtagPart, responses))
message = '<p>Reaction time: ' + str(elapsedtime) + '</p>'
return self.format('200 OK', message)
def gatherdata(self, folder):
if not os.path.isdir(folder):
return False
responseFiles = glob.glob(folder + '*-*')
data = {}
data['title'] = folder.split('/')[-2]
data['sites'] = set([hashtagPart(x) for x in glob.glob(folder + '*')])
data['sitesNumber'] = len(data['sites'])
data['responses'] = len(responseFiles)
data['responseTimes'] = {hashtagPart(x): floatPart(x) for x in responseFiles}
data['responsePoints'] = {hashtagPart(x): os.path.getctime(x) for x in responseFiles}
data['missingSites'] = list(filter(lambda x: x not in data['responseTimes'], data['sites']))
data['missingSitesNumber'] = len(data['missingSites'])
data['quickSites'] = list(filter(lambda x: x<(24*3600), data['responseTimes'].values()))
data['quickSitesNumber'] = len(data['quickSites'])
data['percentageResponses'] = round(100*data['responses']/len(data['sites']))
data['percentageQuick'] = round(100*len(data['quickSites'])/len(data['sites']))
return data
def getresults(self, folder):
ReactionApp.getresults.rank = 0
def steprank():
ReactionApp.getresults.rank += 1
return(ReactionApp.getresults.rank)
if not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
data = self.gatherdata(folder)
message = '<h1>Communication Challenge — {title}'.format_map(data)
message += ' — {status} Results</h1>'
message += '{responses} participants ({percentageResponses} %) have reacted<br>'.format_map(data)
message += '{sitesNumber} participants have been challenged<br>'.format_map(data)
message += '{quickSitesNumber} participants ({percentageQuick} %) have reacted within 24 h<br>'.format_map(data)
message += '<h2>Reaction Times</h2>'
message += '<table cellspacing="2" cellpadding="5" bgcolor="#000000"><tr bgcolor="#ffffff"><th align="left">Sequence #</th><th align="left">Timestamp</th><th align="left">Participant</th><th align="left">Reaction Time</th></tr>'
message += '<tr bgcolor="#ffffff">' + '</tr><tr bgcolor="#ffffff">'.join(map(lambda x: '<td align="right">'+str(steprank())+'</td><td>'+datetime.fromtimestamp(data['responsePoints'][x], tz=datetime.now().astimezone().tzinfo).isoformat()+'</td><td><code>'+x+'</code></td><td align="right">'+str(timedelta(seconds=data['responseTimes'][x]))+'</td>', sorted(data['responseTimes'].keys(), key=lambda x: data['responseTimes'][x]))) + '</tr></table>'
if (data['missingSitesNumber'] > 0):
message += '<h2>Missing Reactions</h2>'
message += '<ul><li><code>' + '...</code></li><li><code>'.join(map(lambda x: x[0:48], sorted(data['missingSites']))) + '...</code></li></ul>'
status = 'Preliminary'
else:
status = 'Final'
if os.path.isfile(folder + '.LOCKED'):
status = 'Final'
return self.format('200 OK', message.format(status=status))
def getlatex(self, folder):
if not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
data = self.gatherdata(folder)
responseTimes = [round(x/3600, 3) for x in data['responseTimes'].values()]
responseTimes.sort()
data['coordinates'] = '(0, 0)'
data['coordinates'] += ''.join(['('+str(responseTimes[x])+', '+str(x+1)+')' for x in range(data['responses'])])
data['xmax'] = round(max(responseTimes) * 1.2, -1)
data['ymax'] = round(data['sitesNumber'] * 1.2, -1)
return self.format('200 OK', LATEXTEMPLATE.render(data))
def getgraph(self, folder, format):
if not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
data = self.gatherdata(folder)
responseTimes = [round(x/3600, 3) for x in data['responseTimes'].values()]
responseTimes.append(0)
responseTimes.sort()
xmax = round(max(responseTimes) * 1.2, -1)
ymax = round(data['sitesNumber'] * 1.2, -1)
plot.figure()
plot.plot(responseTimes, range(data['responses']+1), marker='.', color='blue', label='{responses} participants ({percentageResponses} %) have reacted'.format_map(data), zorder=3)
plot.axhline(y=data['sitesNumber'], color='red', label='{sitesNumber} participants have been challenged'.format_map(data), zorder=2)
plot.axvline(x=24, color='lightgreen', label='{quickSitesNumber} participants ({percentageQuick} %) have reacted within 24 h'.format_map(data), zorder=1)
plot.title('Communication Challenge — {title}'.format_map(data))
plot.xlabel('Time [hours]')
plot.ylabel('Reactions [number of participants]')
plot.legend(loc='lower right')
plot.plot
with io.BytesIO() as buffer:
plot.savefig(buffer, format=format)
buffer.seek(0)
return self.image('200 OK', format, buffer.read())
def process(self):
path = self.environ['PATH_INFO'].split('/')[1:]
try:
prefix, hashtag = path[0].rsplit('-', 1)
except ValueError:
prefix = ''
hashtag = path[0]
try:
int(hashtag, 16)
except (KeyError, ValueError):
return self.format('400 Bad Request', 'This is not a valid link!')
if prefix:
folder = os.path.abspath(BASEDIR + prefix) + '/'
if not folder.startswith(BASEDIR):
self.format('400 Bad Request', 'Good try!')
else:
folder = BASEDIR
if not os.path.isfile(folder + hashtag):
if len(path) == 2 and path[1] == 'create':
if not os.path.isdir(folder):
os.makedirs(folder)
self.updatefile(folder, hashtag)
return self.format('200 OK', 'File {tag} created'.format(tag=hashtag))
elif len(path) != 1:
return self.format('400 Bad Request', 'What are you trying to do?')
elif not os.path.isdir(folder):
return self.format('404 Not Found', 'This campaign does not exist!')
else:
return self.format('404 Not Found', 'This id does not exist!')
if 'HTTP_REFERER' in self.environ:
referer = self.environ['HTTP_REFERER']
else:
referer = ''
if 'HTTPS' in self.environ and self.environ['HTTPS']:
url = 'https://'
else:
url = 'http://'
url += '{host}{URI}'.format(host=self.environ['HTTP_HOST'],
URI=self.environ['REQUEST_URI'])
if referer == url:
self.updatefile(folder, hashtag)
return self.checkresults(folder, hashtag)
elif len(path) == 2:
if path[1] == 'results':
return self.getresults(folder)
elif path[1] == 'graph' and matplotlib:
return self.getgraph(folder, 'png')
elif path[1] == 'latex' and jinja2:
return self.getlatex(folder)
else:
return self.format('400 Bad Request', 'Nice try!')
elif len(path) == 3 and path[1] == 'graph' and matplotlib:
if path[2] == 'jpg':
return self.getgraph(folder, 'jpg')
elif path[2] == 'pdf':
return self.getgraph(folder, 'pdf')
elif path[2] == 'png':
return self.getgraph(folder, 'png')
elif path[2] == 'svg':
return self.getgraph(folder, 'svg')
else:
return self.format('400 Bad Request', 'Nice try!')
elif os.path.isfile(folder + '.LOCKED'):
return self.format('200 OK', 'This campaign has been closed!')
else:
return self.format('200 OK', 'Please click <a href="{URL}">here</a> to confirm your submission!'.format(URL=url))
def __iter__(self):
yield self.process()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment