2016-10-16 20:32:00 -06:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
import argparse
|
2016-10-17 19:58:51 -06:00
|
|
|
from collections import defaultdict, namedtuple
|
2016-10-16 20:32:00 -06:00
|
|
|
import glob
|
2016-10-17 19:58:51 -06:00
|
|
|
import hashlib
|
|
|
|
from importlib.machinery import SourceFileLoader
|
2016-10-16 20:32:00 -06:00
|
|
|
import mistune
|
2016-10-17 13:24:54 -06:00
|
|
|
import os
|
2016-10-16 20:32:00 -06:00
|
|
|
import random
|
2016-10-17 19:58:51 -06:00
|
|
|
import tempfile
|
2016-10-16 20:32:00 -06:00
|
|
|
|
|
|
|
messageChars = b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
|
|
|
|
|
|
def djb2hash(buf):
|
|
|
|
h = 5381
|
|
|
|
for c in buf:
|
|
|
|
h = ((h * 33) + c) & 0xffffffff
|
|
|
|
return h
|
|
|
|
|
2016-10-17 19:58:51 -06:00
|
|
|
# We use a named tuple rather than a full class, because any random name generation has
|
|
|
|
# to be done with Puzzle's random number generator, and it's cleaner to not pass that around.
|
|
|
|
PuzzleFile = namedtuple('PuzzleFile', ['path', 'handle', 'name', 'visible'])
|
2016-10-18 13:11:53 -06:00
|
|
|
PuzzleFile.__doc__ = """A file associated with a puzzle.
|
|
|
|
path: The path to the original input file. May be None (when this is created from a file handle
|
|
|
|
and there is no original input.
|
|
|
|
handle: A File-like object set to read the file from. You should be able to read straight
|
|
|
|
from it without having to seek to the beginning of the file.
|
|
|
|
name: The name of the output file.
|
|
|
|
visible: A boolean indicating whether this file should visible to the user. If False,
|
|
|
|
the file is still expected to be accessible, but it's path must be known
|
|
|
|
(or figured out) to retrieve it."""
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
|
2016-10-17 19:58:51 -06:00
|
|
|
class Puzzle:
|
|
|
|
|
|
|
|
KNOWN_KEYS = [
|
|
|
|
'answer',
|
|
|
|
'author',
|
2016-10-17 21:26:56 -06:00
|
|
|
'file',
|
|
|
|
'hidden',
|
|
|
|
'name'
|
|
|
|
'resource',
|
2016-10-17 19:58:51 -06:00
|
|
|
'summary'
|
|
|
|
]
|
|
|
|
REQUIRED_KEYS = [
|
|
|
|
'author',
|
|
|
|
'answer',
|
|
|
|
]
|
|
|
|
SINGULAR_KEYS = [
|
2016-10-17 21:26:56 -06:00
|
|
|
'name'
|
2016-10-17 19:58:51 -06:00
|
|
|
]
|
|
|
|
|
|
|
|
# Get a big list of clean words for our answer file.
|
|
|
|
ANSWER_WORDS = [w.strip() for w in open(os.path.join(os.path.dirname(__file__),
|
|
|
|
'answer_words.txt'))]
|
|
|
|
|
2016-10-18 13:23:14 -06:00
|
|
|
def __init__(self, category_seed, path=None, points=None):
|
2016-10-18 13:29:41 -06:00
|
|
|
"""A MOTH Puzzle.
|
2016-10-18 11:24:46 -06:00
|
|
|
:param category_seed: A byte string to use as a seed for random numbers for this puzzle.
|
|
|
|
It is combined with the puzzle points.
|
|
|
|
:param path: An optional path to a puzzle directory. The point value for the puzzle is taken
|
|
|
|
from the puzzle directories name (it must be an integer greater than zero).
|
|
|
|
Within this directory, we expect:
|
|
|
|
(optional) A puzzle.moth file in RFC2822 format. The puzzle will get its attributes
|
|
|
|
from the headers, and the body will be the puzzle description in
|
|
|
|
Markdown format.
|
|
|
|
(optional) A puzzle.py file. This is expected to have a callable called make
|
|
|
|
that takes a single positional argument (this puzzle object).
|
|
|
|
This callable can then do whatever it needs to with this object.
|
2016-10-18 13:23:14 -06:00
|
|
|
:param points: The point value of the puzzle. Mutually exclusive with path.
|
2016-10-18 11:24:46 -06:00
|
|
|
If neither of the above are given, the point value for the puzzle will have to
|
2016-10-18 13:23:14 -06:00
|
|
|
be set at instantiation.
|
2016-10-18 13:29:41 -06:00
|
|
|
|
|
|
|
For puzzle attributes, this class acts like a dictionary that in most cases assigns
|
|
|
|
always returns a list. Certain keys, however behave differently:
|
|
|
|
- Keys in Puzzle.SINGULAR_KEYS can only have one value, and writing to these overwrites
|
|
|
|
that value.
|
|
|
|
- The keys 'hidden', 'file', and 'resource' all create a new PuzzleFile object that
|
|
|
|
gets added under the 'files' key.
|
|
|
|
- The 'answer' also adds a new hash under the the 'hash' key.
|
2016-10-17 21:26:56 -06:00
|
|
|
"""
|
|
|
|
|
2016-10-17 13:24:54 -06:00
|
|
|
super().__init__()
|
|
|
|
|
2016-10-18 13:23:14 -06:00
|
|
|
if (points is None and path is None) or (points is not None and path is not None):
|
|
|
|
raise ValueError("Either points or path must be set, but not both.")
|
2016-10-18 09:51:33 -06:00
|
|
|
|
2016-10-17 19:58:51 -06:00
|
|
|
self._dict = defaultdict(lambda: [])
|
|
|
|
if os.path.isdir(path):
|
2016-10-19 15:02:38 -06:00
|
|
|
self.puzzle_dir = path
|
2016-10-17 19:58:51 -06:00
|
|
|
else:
|
2016-10-19 15:02:38 -06:00
|
|
|
self.puzzle_dir = None
|
2016-10-16 20:32:00 -06:00
|
|
|
self.message = bytes(random.choice(messageChars) for i in range(20))
|
2016-10-17 13:24:54 -06:00
|
|
|
self.body = ''
|
|
|
|
|
2016-10-18 20:11:20 -06:00
|
|
|
# This defaults to a dict, not a list like most things
|
|
|
|
self._dict['files'] = {}
|
|
|
|
|
2016-10-18 11:24:46 -06:00
|
|
|
# A list of temporary files we've created that will need to be deleted.
|
|
|
|
self._temp_files = []
|
2016-10-18 13:23:14 -06:00
|
|
|
if path is not None:
|
|
|
|
if not os.path.isdir(path):
|
|
|
|
raise ValueError("No such directory: {}".format(path))
|
2016-10-18 11:24:46 -06:00
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
pathname = os.path.split(path)[-1]
|
2016-10-17 19:58:51 -06:00
|
|
|
try:
|
2016-10-17 21:26:56 -06:00
|
|
|
self.points = int(pathname)
|
|
|
|
except ValueError:
|
2016-10-18 13:23:14 -06:00
|
|
|
raise ValueError("Directory name must be a point value: {}".format(path))
|
|
|
|
elif points is not None:
|
|
|
|
self.points = points
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-17 23:20:48 -06:00
|
|
|
self._seed = category_seed * self.points
|
2016-10-17 19:58:51 -06:00
|
|
|
self.rand = random.Random(self._seed)
|
|
|
|
|
2016-10-19 15:02:38 -06:00
|
|
|
self._logs = []
|
|
|
|
|
2016-10-18 13:23:14 -06:00
|
|
|
if path is not None:
|
2016-10-17 19:58:51 -06:00
|
|
|
files = os.listdir(path)
|
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
if 'puzzle.moth' in files:
|
|
|
|
self._read_config(open(os.path.join(path, 'puzzle.moth')))
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
if 'puzzle.py' in files:
|
2016-10-17 19:58:51 -06:00
|
|
|
# Good Lord this is dangerous as fuck.
|
2016-10-17 21:26:56 -06:00
|
|
|
loader = SourceFileLoader('puzzle_mod', os.path.join(path, 'puzzle.py'))
|
2016-10-17 19:58:51 -06:00
|
|
|
puzzle_mod = loader.load_module()
|
|
|
|
if hasattr(puzzle_mod, 'make'):
|
2016-10-18 13:23:14 -06:00
|
|
|
self.body = '# `puzzle.body` was not set by the `make` function'
|
2016-10-17 19:58:51 -06:00
|
|
|
puzzle_mod.make(self)
|
2016-10-18 13:23:14 -06:00
|
|
|
else:
|
|
|
|
self.body = '# `puzzle.py` does not define a `make` function'
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
def cleanup(self):
|
|
|
|
"""Cleanup any outstanding temporary files."""
|
|
|
|
for path in self._temp_files:
|
|
|
|
if os.path.exists(path):
|
|
|
|
try:
|
|
|
|
os.unlink(path)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
|
2016-10-19 15:02:38 -06:00
|
|
|
def log(self, msg):
|
|
|
|
"""Add a new log message to this puzzle."""
|
|
|
|
self._logs.append(msg)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def logs(self):
|
|
|
|
"""Get all the log messages, as strings."""
|
|
|
|
|
|
|
|
_logs = []
|
|
|
|
for log in self._logs:
|
|
|
|
if type(log) is bytes:
|
|
|
|
log = log.decode('utf-8')
|
|
|
|
elif type(log) is not str:
|
|
|
|
log = str(log)
|
|
|
|
|
|
|
|
_logs.append(log)
|
|
|
|
|
|
|
|
return _logs
|
|
|
|
|
2016-10-17 19:58:51 -06:00
|
|
|
def _read_config(self, stream):
|
|
|
|
"""Read a configuration file (ISO 2822)"""
|
2016-10-16 20:32:00 -06:00
|
|
|
body = []
|
|
|
|
header = True
|
|
|
|
for line in stream:
|
|
|
|
if header:
|
|
|
|
line = line.strip()
|
|
|
|
if not line.strip():
|
|
|
|
header = False
|
|
|
|
continue
|
|
|
|
key, val = line.split(':', 1)
|
|
|
|
val = val.strip()
|
2016-10-17 19:58:51 -06:00
|
|
|
self[key] = val
|
2016-10-16 20:32:00 -06:00
|
|
|
else:
|
|
|
|
body.append(line)
|
2016-10-17 19:58:51 -06:00
|
|
|
self.body = ''.join(body)
|
|
|
|
|
|
|
|
def random_hash(self):
|
|
|
|
"""Create a random hash from our number generator suitable for use as a filename."""
|
|
|
|
return hashlib.sha1(str(self.rand.random()).encode('ascii')).digest()
|
|
|
|
|
|
|
|
def _puzzle_file(self, path, name, visible=True):
|
2016-10-17 21:26:56 -06:00
|
|
|
"""Make a puzzle file instance for the given file. To add files as you would in the config
|
|
|
|
file (to 'file', 'hidden', or 'resource', simply assign to that keyword in the object:
|
|
|
|
puzzle['file'] = 'some_file.txt'
|
|
|
|
puzzle['hidden'] = 'some_hidden_file.txt'
|
|
|
|
puzzle['resource'] = 'some_file_in_the_category_resource_directory_omg_long_name.txt'
|
2016-10-17 19:58:51 -06:00
|
|
|
:param path: The path to the file
|
|
|
|
:param name: The name of the file. If set to None, the published file will have
|
|
|
|
a random hash as a name and have visible set to False.
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Make sure it actually exists.
|
|
|
|
if not os.path.exists(path):
|
2016-10-18 20:11:20 -06:00
|
|
|
raise ValueError("Included file {} does not exist.".format(path))
|
2016-10-17 19:58:51 -06:00
|
|
|
|
|
|
|
file = open(path, 'rb')
|
|
|
|
|
|
|
|
return PuzzleFile(path=path, handle=file, name=name, visible=visible)
|
|
|
|
|
2016-10-18 20:11:20 -06:00
|
|
|
def make_temp_file(self, name=None, visible=True):
|
2016-10-17 21:26:56 -06:00
|
|
|
"""Get a file object for adding dynamically generated data to the puzzle. When you're
|
|
|
|
done with this file, flush it, but don't close it.
|
|
|
|
:param name: The name of the file for links within the puzzle. If this is None, a name
|
|
|
|
will be generated for you.
|
|
|
|
:param visible: Whether or not the file will be visible to the user.
|
2016-10-17 19:58:51 -06:00
|
|
|
:return: A file object for writing
|
|
|
|
"""
|
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
if name is None:
|
|
|
|
name = self.random_hash()
|
|
|
|
|
2016-10-18 20:11:20 -06:00
|
|
|
file = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
|
2016-10-17 21:26:56 -06:00
|
|
|
file_read = open(file.name, 'rb')
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
self._dict['files'][name] = PuzzleFile(path=file.name, handle=file_read,
|
|
|
|
name=name, visible=visible)
|
2016-10-17 19:58:51 -06:00
|
|
|
|
|
|
|
return file
|
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
def make_handle_file(self, handle, name, visible=True):
|
|
|
|
"""Add a file to the puzzle from a file handle.
|
|
|
|
:param handle: A file object or equivalent.
|
|
|
|
:param name: The name of the file in the final puzzle.
|
|
|
|
:param visible: Whether or not it's visible.
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
|
2016-10-17 19:58:51 -06:00
|
|
|
def __setitem__(self, key, value):
|
2016-10-17 21:26:56 -06:00
|
|
|
"""Set a value for this puzzle, as if it were set in the config file. Most values default
|
|
|
|
being added to a list. Files (regardless of type) go in a dict under ['files']. Keys
|
|
|
|
in Puzzle.SINGULAR_KEYS are single values that get overwritten with subsequent assignments.
|
|
|
|
Only keys in Puzzle.KNOWN_KEYS are accepted.
|
|
|
|
:param key:
|
|
|
|
:param value:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
|
|
|
|
key = key.lower()
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-19 15:02:38 -06:00
|
|
|
if key in ('file', 'resource', 'hidden') and self.puzzle_dir is None:
|
2016-10-17 19:58:51 -06:00
|
|
|
raise KeyError("Cannot set a puzzle file for single file puzzles.")
|
2016-10-16 20:32:00 -06:00
|
|
|
|
|
|
|
if key == 'answer':
|
2016-10-17 19:58:51 -06:00
|
|
|
# Handle adding answers to the puzzle
|
2016-10-18 13:29:41 -06:00
|
|
|
self._dict['hash'].append(djb2hash(value.encode('utf8')))
|
|
|
|
self._dict['answer'].append(value)
|
2016-10-17 19:58:51 -06:00
|
|
|
elif key == 'file':
|
|
|
|
# Handle adding files to the puzzle
|
2016-10-19 15:02:38 -06:00
|
|
|
path = os.path.join(self.puzzle_dir, 'files', value)
|
2016-10-17 19:58:51 -06:00
|
|
|
self._dict['files'][value] = self._puzzle_file(path, value)
|
|
|
|
elif key == 'resource':
|
|
|
|
# Handle adding category files to the puzzle
|
2016-10-19 15:02:38 -06:00
|
|
|
path = os.path.join(self.puzzle_dir, '../res', value)
|
2016-10-17 19:58:51 -06:00
|
|
|
self._dict['files'].append(self._puzzle_file(path, value))
|
|
|
|
elif key == 'hidden':
|
|
|
|
# Handle adding secret, 'hidden' files to the puzzle.
|
2016-10-19 15:02:38 -06:00
|
|
|
path = os.path.join(self.puzzle_dir, 'files', value)
|
2016-10-17 19:58:51 -06:00
|
|
|
name = self.random_hash()
|
|
|
|
self._dict['files'].append(self._puzzle_file(path, name, visible=False))
|
|
|
|
elif key in self.SINGULAR_KEYS:
|
|
|
|
# These keys can only have one value
|
|
|
|
self._dict[key] = value
|
|
|
|
elif key in self.KNOWN_KEYS:
|
|
|
|
self._dict[key].append(value)
|
|
|
|
else:
|
|
|
|
raise KeyError("Invalid Attribute: {}".format(key))
|
|
|
|
|
|
|
|
def __getitem__(self, item):
|
2016-10-17 21:26:56 -06:00
|
|
|
return self._dict[item.lower()]
|
2016-10-17 19:58:51 -06:00
|
|
|
|
2016-10-18 09:51:33 -06:00
|
|
|
def make_answer(self, word_count, sep=' '):
|
2016-10-17 19:58:51 -06:00
|
|
|
"""Generate and return a new answer. It's automatically added to the puzzle answer list.
|
|
|
|
:param int word_count: The number of words to include in the answer.
|
|
|
|
:param str|bytes sep: The word separator.
|
2016-10-18 09:51:33 -06:00
|
|
|
:returns: The answer string
|
2016-10-17 19:58:51 -06:00
|
|
|
"""
|
|
|
|
|
|
|
|
answer = sep.join(self.rand.sample(self.ANSWER_WORDS, word_count))
|
|
|
|
self['answer'] = answer
|
|
|
|
|
|
|
|
return answer
|
|
|
|
|
2016-10-16 20:32:00 -06:00
|
|
|
def htmlify(self):
|
2016-10-17 21:26:56 -06:00
|
|
|
"""Format and return the markdown for the puzzle body."""
|
2016-10-16 20:32:00 -06:00
|
|
|
return mistune.markdown(self.body)
|
|
|
|
|
2016-10-17 21:26:56 -06:00
|
|
|
def publish(self):
|
2016-10-16 20:32:00 -06:00
|
|
|
obj = {
|
2016-10-17 13:24:54 -06:00
|
|
|
'author': self['author'],
|
2016-10-17 19:58:51 -06:00
|
|
|
'hashes': self['hashes'],
|
2016-10-16 20:32:00 -06:00
|
|
|
'body': self.htmlify(),
|
|
|
|
}
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def secrets(self):
|
|
|
|
obj = {
|
2016-10-17 19:58:51 -06:00
|
|
|
'answers': self['answers'],
|
2016-10-17 13:24:54 -06:00
|
|
|
'summary': self['summary'],
|
2016-10-16 20:32:00 -06:00
|
|
|
}
|
|
|
|
return obj
|
2016-10-17 20:28:24 -06:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2016-10-16 20:32:00 -06:00
|
|
|
parser = argparse.ArgumentParser(description='Build a puzzle category')
|
|
|
|
parser.add_argument('puzzledir', nargs='+', help='Directory of puzzle source')
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
for puzzledir in args.puzzledir:
|
|
|
|
puzzles = {}
|
|
|
|
secrets = {}
|
|
|
|
for puzzlePath in glob.glob(os.path.join(puzzledir, "*.moth")):
|
|
|
|
filename = os.path.basename(puzzlePath)
|
|
|
|
points, ext = os.path.splitext(filename)
|
|
|
|
points = int(points)
|
2016-10-17 19:58:51 -06:00
|
|
|
puzzle = Puzzle(puzzlePath, "test")
|
2016-10-16 20:32:00 -06:00
|
|
|
puzzles[points] = puzzle
|
|
|
|
|
|
|
|
for points in sorted(puzzles):
|
|
|
|
puzzle = puzzles[points]
|
|
|
|
print(puzzle.secrets())
|
|
|
|
|
2016-10-17 23:02:05 -06:00
|
|
|
|
|
|
|
class Category:
|
|
|
|
def __init__(self, path, seed):
|
|
|
|
self.path = path
|
|
|
|
self.seed = seed
|
|
|
|
self.pointvals = []
|
|
|
|
for fpath in glob.glob(os.path.join(path, "[0-9]*")):
|
|
|
|
pn = os.path.basename(fpath)
|
|
|
|
points = int(pn)
|
|
|
|
self.pointvals.append(points)
|
|
|
|
self.pointvals.sort()
|
|
|
|
|
|
|
|
def puzzle(self, points):
|
|
|
|
path = os.path.join(self.path, str(points))
|
2016-10-18 20:11:20 -06:00
|
|
|
return Puzzle(self.seed, path=path)
|
2016-10-17 23:02:05 -06:00
|
|
|
|
|
|
|
def puzzles(self):
|
|
|
|
for points in self.pointvals:
|
|
|
|
yield self.puzzle(points)
|