-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbsubmit
executable file
·510 lines (389 loc) · 17.7 KB
/
fbsubmit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (C) 2010 - 2011 Chris Jerdonek. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * The names of the copyright holders may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
"""
A script for submitting puzzle solutions to the Facebook PuzzleBot.
For help documentation, execute this script with the -h or --help option.
"""
import datetime
from email import Encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE
import getpass
import logging
from optparse import OptionParser
import os
from smtplib import SMTP
import sys
import tarfile
_log = logging.getLogger("fbsubmit")
SMTP_HOST = "smtp.gmail.com"
SMTP_PORT = 587
# Consult the setup section of the help documentation for information
# on the two configuration values below.
SENDER_EMAIL_ADDRESS = ""
TEST_EMAIL_ADDRESS = ""
SENDER_ENV_NAME = "FACEBOOK_PUZZLE_SENDER_EMAIL_ADDRESS"
TEST_ENV_NAME = "FACEBOOK_PUZZLE_TEST_EMAIL_ADDRESS"
DEBUG_OPTION = "-v"
EXCLUDE_FROM_TAR = [".pyc"]
LIB_DIRECTORY_NAME = "lib"
FACEBOOK_EMAIL_ADDRESS = "1051962371@fb.com"
VALID_PUZZLE_NAMES = [
"battleship",
"breathalyzer",
"dancebattle",
"dinoisland",
"facebull",
"fridgemadness",
"gattaca",
"hoppity",
"liarliar",
"meepmeep",
"peaktraffic",
"rushhour",
"simonsays",
"smallworld",
"sophie",
"swarm",
"usrbincrash",
]
# Escape the leading "%" so that the leading "%p" is not interpreted
# as a Python string formatting conversion specifier. The optparse
# module, however, recognizes "%prog" by replacing it with the current
# script name.
USAGE = """%%prog [options] directory
This script sends to the Facebook PuzzleBot a puzzle solution contained in
the given directory.
The script also CC's the solution to the sender.
Setup:
You will need to configure the sender and test e-mail addresses prior
to using this script.
The sender e-mail address is the e-mail address from which to send
puzzle solutions to Facebook (i.e. the "From:" for the e-mails sent to
Facebook). This is also the address used to log into the SMTP server
configured in the script.
The test e-mail address is the e-mail address to use for testing this
script. When running the script in "test mode," the script e-mails
the puzzle solution to the test e-mail address instead of to Facebook.
Consult the rest of the help documentation for information on how
to run the script in "real mode" vs. "test mode."
You can configure the sender and test e-mail addresses in two ways.
The simplest way is to modify the script code itself by setting the
script's SENDER_EMAIL_ADDRESS and TEST_EMAIL_ADDRESS constants to the
desired values.
The second way is to set corresponding environment variables.
If you are familiar with setting environment variables, you can store
the e-mail addresses as environment variables with names--
* %(sender_env_name)s
* %(test_env_name)s
The environment variables, if set, take precedence over the script constants.
Folder hierarchy:
The script places certain requirements on the folder hierarchy, as follows.
The name of the parent directory of the provided directory must match
the name of the puzzle being submitted. For example,
dev/facebook-puzzles/hoppity/python is a valid directory to provide
because the parent directory has name "hoppity". The script pulls the
puzzle name from that parent directory.
The script attaches at most two files from the directory, as follows:
(1) If the given directory contains a file called "Makefile" (case-sensitive),
the script attaches the makefile. Otherwise, the script searches for
a file in the given directory whose name matches the name of the puzzle
being submitted (i.e. the puzzle executable), and it attaches that.
(2) Optionally, the given directory can include a library subdirectory
called "%(lib_folder)s". If this directory exists, the script tars,
gzips, and attaches this directory as a file called "%(lib_folder)s.tar.gz".
The script excludes from the tar file certain files like hidden files.
Below is an example of how to organize your files for use with this script.
facebook-puzzles/
hoppity/
c/
Makefile
log.txt (ignored, not attached to e-mail)
%(lib_folder)s/
meepmeep.c
python/
hoppity (executable)
test.py (ignored, not attached to e-mail)
%(lib_folder)s/
__init__.py
hoppity.py
meepmeep/
solution1/
<makefile or executable, and optional library directory>
solution2/
<makefile or executable, and optional library directory>
With the above hierarchy, all of the following are valid directories
to provide to the script:
* facebook-puzzles/hoppity/c
* facebook-puzzles/hoppity/python
* facebook-puzzles/meepmeep/solution1
* facebook-puzzles/meepmeep/solution2""" % {
"lib_folder": LIB_DIRECTORY_NAME,
"sender_env_name": SENDER_ENV_NAME,
"test_env_name": TEST_ENV_NAME
}
class Error(Exception):
"""Base class for exceptions in this module."""
pass
def configure_logging(logging_level=None):
if logging_level is None:
logging_level = logging.INFO
logger = logging.getLogger() # the root logger.
stream = sys.stderr
handler = logging.StreamHandler(stream)
formatter = logging.Formatter("[%(levelname)s] %(message)s")
handler.setFormatter(formatter)
logger.setLevel(logging_level)
logger.addHandler(handler)
_log.debug("Debug logging enabled.")
def create_parser(usage, args):
parser = OptionParser(usage=usage)
parser.add_option("--real", dest="real_mode", action="store_true", default=False,
help='run the script in "real mode" and send the '
'solution to Facebook. Otherwise, run the '
'script in "test mode" and use the test e-mail '
'address. The script defaults to "test mode" to '
'prevent accidental submissions.')
parser.add_option("-m", "--message", dest="message", metavar="MESSAGE", default="",
help="include MESSAGE in the e-mail body")
parser.add_option(DEBUG_OPTION, dest="verbose", action="store_true",
help="log verbosely")
return parser
def read_user_configuration(short_name, descriptive_name, env_name, default_value):
"""Check and return a user-specified configuration value."""
value = os.getenv(env_name, default_value)
if not value:
message = """The %s has not been configured.
Follow the setup instructions in the help documentation, and configure the
%s before using this script.""" % (descriptive_name, short_name)
raise Error(message)
_log.debug('User-configuration: read %s: "%s"' % (short_name, value))
return value
def read_arguments(args):
"""Check the arguments, and return the puzzle name and directory."""
help_message = ("You must provide a path to the directory containing "
"your puzzle solution.")
if not args:
raise Error("""No submission directory was provided.
%s""" % help_message)
submission_directory = args[0]
if not os.path.isdir(submission_directory):
raise Error("""The path provided is not a path to a directory: %s
%s""" % (submission_directory, help_message))
# Convert to a normalized absolute path to determine the name of the
# parent directory. Normalizing also strips off any trailing
# slashes (e.g. "hoppity/c/"). Otherwise, calling os.path.basename()
# can result in a base name that is an empty string.
submission_directory = os.path.abspath(submission_directory)
puzzle_directory = os.path.dirname(submission_directory)
puzzle_name = os.path.basename(puzzle_directory)
if puzzle_name not in VALID_PUZZLE_NAMES:
raise Error("""The name of the parent directory "%s" does not match the name
of a puzzle in the script's list of valid puzzle names:
%s
If necessary, correct the script's VALID_PUZZLE_NAMES constant.""" % (
puzzle_name,
"\n ".join(VALID_PUZZLE_NAMES)))
return (puzzle_name, submission_directory)
def should_exclude_from_tar(path):
"""Return whether to exclude the given path from the tar file."""
for extension in EXCLUDE_FROM_TAR:
if path.endswith(extension):
return True
base_name = os.path.basename(path)
if base_name.startswith("."):
return True
return False
def create_tar_gz(source_directory):
"""
Create a tar file of the given source directory.
This function creates the tar file in the same directory as the
directory containing the source directory. The name of the tar
file is *.tar.gz, where * is the base name of the given source
directory.
"""
_log.debug("Creating tar of: %s" % source_directory)
# Strip off any trailing slashes.
source_directory = os.path.normpath(source_directory)
directory_name = os.path.basename(source_directory)
characters_to_strip = len(source_directory) - len(directory_name)
# Write the tar file into the same directory as the source directory
# (so that *.tar.gz is a sibling of what is being tarred).
target_path = "%s.tar.gz" % source_directory
try:
_log.debug("Writing tar to: %s" % target_path)
tar = tarfile.open(name=target_path, mode="w:gz")
for result in os.walk(source_directory):
dir_path = result[0]
for file_name in result[2]:
path_to_add = os.path.join(dir_path, file_name)
path_to_add = os.path.normpath(path_to_add)
# For example, if source_directory is--
# /hoppity/python/lib
# and path_to_add is--
# /hoppity/python/lib/hoppity.pyc
# then arc_name is--
# lib/hoppity.pyc
arc_name = path_to_add[characters_to_strip:]
if should_exclude_from_tar(path_to_add):
# Display the shorter arc_name for easier readability.
_log.info("Excluding from tar: %s" % arc_name)
continue
# If we don't include the arcname parameter, then the source
# directory can extract into a subdirectory of the newly
# created directory, depending on the current working directory.
_log.debug('Adding to tar: %s' % arc_name)
tar.add(path_to_add, arcname=arc_name)
finally:
tar.close()
return target_path
def prep_attachments(puzzle_name, submission_directory):
"""
Return a list of paths of the files to attach.
This function also creates the tar file, if necessary.
"""
_log.info("Examining submission directory:\n %s" % submission_directory)
attachment_paths = []
# We include a script executable or a Makefile, but not both.
makefile_path = os.path.join(submission_directory, "Makefile")
if os.path.exists(makefile_path):
_log.info("Found makefile.")
file_path = makefile_path
else:
_log.info("No makefile found: skipping.")
executable_path = os.path.join(submission_directory, puzzle_name)
if not os.path.exists(executable_path) or not os.path.isfile(executable_path):
raise Error("""Neither a makefile nor a puzzle executable was found.
The submission directory for puzzle "%(puzzle_name)s" must contain
either a makefile called "Makefile" (case-sensitive), or a puzzle
executable called "%(puzzle_name)s" (also case-sensitive). Note that
the file name of the puzzle executable, if provided, should have no
extension. The Facebook rules require this.""" % {"puzzle_name": puzzle_name})
_log.info("Found puzzle executable.")
file_path = executable_path
attachment_paths.append(file_path)
# Add library folder.
lib_directory = os.path.join(submission_directory, LIB_DIRECTORY_NAME)
if not os.path.exists(lib_directory):
_log.info("No library directory found: skipping.")
else:
_log.info("Found library directory: tar/gzipping...")
attachment_path = create_tar_gz(source_directory=lib_directory)
_log.info("Created tar/gzip at:\n %s" % attachment_path)
attachment_paths.append(attachment_path)
return attachment_paths
def add_attachment(mime_multipart, attachment_path):
"""Add an attachment to the given MIMEMultipart instance."""
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attachment_path, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attachment_path))
mime_multipart.attach(part)
def send_email(smtp_host, smtp_port, sender_address, sender_pwd,
to_addresses, cc_addresses, subject, body, attachment_paths):
"""Send an e-mail."""
multi = MIMEMultipart()
multi["From"] = sender_address
multi["To"] = COMMASPACE.join(to_addresses)
multi["Cc"] = COMMASPACE.join(cc_addresses)
multi["Subject"] = subject
multi.attach(MIMEText(body))
for attachment_path in attachment_paths:
add_attachment(multi, attachment_path)
_log.info("Connecting to: %s:%s..." % (smtp_host, smtp_port))
smtp_connection = SMTP(smtp_host, smtp_port)
smtp_connection.ehlo()
smtp_connection.starttls()
smtp_connection.ehlo()
_log.info("Logging in as: %s..." % sender_address)
smtp_connection.login(sender_address, sender_pwd)
recipient_addresses = to_addresses + cc_addresses
_log.info("Sending mail to: %s..." % ", ".join(recipient_addresses))
smtp_connection.sendmail(sender_address, recipient_addresses, multi.as_string())
smtp_connection.close()
def submit_solution(args):
"""Submit a puzzle solution to the Facebook PuzzleBot."""
parser = create_parser(usage=USAGE, args=args)
(options, args) = parser.parse_args(args)
sender_address = read_user_configuration("sender e-mail address",
"e-mail address to send from",
SENDER_ENV_NAME, SENDER_EMAIL_ADDRESS)
test_address = read_user_configuration("test e-mail address",
"test submission e-mail address",
TEST_ENV_NAME, TEST_EMAIL_ADDRESS)
puzzle_name, submission_directory = read_arguments(args)
submission_address = (FACEBOOK_EMAIL_ADDRESS if options.real_mode else test_address)
message = options.message
attachment_paths = prep_attachments(puzzle_name, submission_directory)
_log.info("""Submitting puzzle "%(puzzle_name)s"...
To: %(submission_address)s (%(mode)s mode)
Message:
%(message)s
Attachments:
%(attachment_paths)s""" % {"puzzle_name": puzzle_name,
"submission_address": submission_address,
"mode": "real" if options.real_mode else "test",
"message": ('"%s"' % message) if message else "None",
"attachment_paths": "\n ".join(attachment_paths)})
sender_pwd = getpass.getpass(prompt="Password for %s: " % sender_address)
email_body = "Facebook PuzzleBot submission: %s\n" % message
send_email(smtp_host=SMTP_HOST,
smtp_port=SMTP_PORT,
sender_address=sender_address,
sender_pwd=sender_pwd,
to_addresses=[submission_address],
cc_addresses=[sender_address], # CC to the sender.
subject=puzzle_name,
body=email_body,
attachment_paths=attachment_paths)
def exit_with_error(message):
"""Display an error message, and exit the program."""
# Skip to the beginning of the next line, e.g. in case we are in
# the middle of the password prompt.
print
_log.error("""%s
Pass -h or --help for help documentation and available options.""" % message)
exit(1)
def main(sys_argv):
args = sys_argv[1:]
# Configure logging prior to parsing options.
configure_logging(logging.DEBUG if DEBUG_OPTION in args else None)
try:
submit_solution(args)
except KeyboardInterrupt, err:
exit_with_error("Script aborted by user.")
except Error, err:
exit_with_error(err.message)
if __name__ == "__main__":
result = main(sys.argv)
sys.exit(result)