summaryrefslogtreecommitdiff
path: root/breaker.py
diff options
context:
space:
mode:
Diffstat (limited to 'breaker.py')
-rwxr-xr-xbreaker.py151
1 files changed, 28 insertions, 123 deletions
diff --git a/breaker.py b/breaker.py
index 4bb5bf9..06c89cf 100755
--- a/breaker.py
+++ b/breaker.py
@@ -1,29 +1,18 @@
#!/usr/bin/python2.7
-from subprocess import call, Popen, PIPE
-import urllib
-import urllib2
import os
import sys
import random
import re
-import time
-urlencode = urllib.urlencode
-urlopen = urllib2.urlopen
-Request = urllib2.Request
+import lib.utils as utils
+import urllib
+from config import *
-#WORKING_DIR = "/tmp"
-WORKING_DIR = "/var/www/cache"
-BIN_CONVERT = "/usr/bin/convert"
-BIN_IDENTIFY = "/usr/bin/identify"
DEFAULT_FINALFORMAT = "png";
-
SUBTLE_BREAK_MARK = 'pron'
EXTREME_BREAK_MARK = 'sugar'
HEADER_OFFSET = 2000
-MAX_SIZE = 1024 * 1024 * 1.2 * 1.5
-
# 'CLASSIC':'jpg',
# 'REDUX':'pcds',
# 'BLURRY_BREAK':'viff',
@@ -37,99 +26,10 @@ MAX_SIZE = 1024 * 1024 * 1.2 * 1.5
# 'FAX_MACHINE':'cals',
# 'STRIPES':'exr',
# 'PHOTOCOPY':'art',
-TEST_PARAMS = {
- "url" : "http://i.asdf.us/im/27/1424816234661dumpfmpfifferkinggr_1424816412_pfifferking.gif" ,
- "breaktype" : "RGB_WASH",
- "finalformat" : "png",
- "breakmode" : "extreme",
- "breakangle" : "10",
- "username" : "donkey",
- "expanded" : "false"
-}
-
-def bool_correct(s):
- if re.match(r'^false$', s, re.IGNORECASE):
- return False
- elif re.match(r'^true$', s, re.IGNORECASE):
- return True
- else:
- return s
-
-#{{{Utility functions
-class dotdict(dict):
- """dot.notation access to dictionary attributes"""
- def __getattr__(self, attr):
- return self.get(attr)
- __setattr__= dict.__setitem__
- __delattr__= dict.__delitem__
-def sanitize (str):
- return re.sub(r'\W+', '', str)
-
-def now():
- return int(time.time())
-
-def browser_request (url, data=None):
- headers = {
- 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
- 'Accept': '*/*',
- }
- try:
- req = Request(url, data, headers)
- response = urlopen(req)
- except IOError, e:
- if hasattr(e, 'code'):
- sys.stderr.write( '%s - ERROR %s' % (url, e.code) )
- raise;
- return None
- else:
- return response
-
-def download(url, destination, max_size=MAX_SIZE):
- response = browser_request(url, None)
- rawimg = response.read()
- if len(rawimg) == 0:
- sys.stderr.write("got zero-length file")
- raise;
- if len(rawimg) > max_size:
- sys.stderr.write("file too big: max size {} KB / {} is {} KB".format(
- str(MAX_SIZE/1024),
- destination,
- str(len(rawimg)/1024)
- ))
- raise;
- f = open(destination, "w")
- f.write(rawimg)
- f.close()
-
-def dimensions (filepath):
- #works in lieu of a mimetype check (it reads the header as well)
- ident = (Popen([BIN_IDENTIFY, filepath], stdout=PIPE).communicate()[0]).split(" ")
- return ident[2].split("x")
-
-def file_size (filepath):
- try:
- return os.stat(file)[6]
- except Exception as e:
- sys.stderr.write(str(e))
- raise;
-
-def gif_frames(filepath):
- try:
- info = Popen([BIN_IDENTIFY,filepath], stdout=PIPE).communicate()[0]
- frames = filter((lambda x: x), map(
- (lambda x: x.split(" ")[0]),
- (info).split('\n')
- ))
- return frames
- except Exception as e:
- sys.stderr.write(str(e))
- raise;
-#}}}
class Breaker():
- def __init__(self, params):
+ def __init__(self, **kwargs):
self.params = {}
- self.now = now()
self.tag = "imBreak"
self.commands = [];
self._required_keys = [
@@ -143,31 +43,31 @@ class Breaker():
]
self.files_created = []
for k in self._required_keys:
- if k in params:
+ if k in kwargs:
if k == 'breaktype':
- self.params['breaktype'] = self._get_breaktype(params[k])
+ self.params['breaktype'] = self._get_breaktype(kwargs[k])
elif k == 'url':
- self.params[k] = params[k]
+ self.params[k] = kwargs[k]
else:
- self.params[k] = bool_correct(sanitize(params[k]))
+ self.params[k] = utils.bool_correct(utils.sanitize(kwargs[k]))
else:
self.params[k] = False;
- self.params = dotdict(self.params)
+ self.params = utils.dotdict(self.params)
self.basename, self._first_format = self._get_filename();
self._downloaded_file = os.path.join(WORKING_DIR, "IMBREAKTMP{}.{}".format(self.basename, self._first_format)) # same here
try:
- download(self.params.url, self._downloaded_file)
+ utils.download(self.params.url, self._downloaded_file)
self.files_created.append(self._downloaded_file)
except Exception as e:
sys.stderr.write(str(e))
raise;
- self._gif_frames = gif_frames(self._downloaded_file)
+ self._gif_frames = utils.gif_frames(self._downloaded_file)
self._gif_frames = self._gif_frames if len(self._gif_frames) > 1 else False
- self.width, self.height = dimensions(self._downloaded_file) # same here
+ self.width, self.height = utils.dimensions(self._downloaded_file) # same here
if not self.params.finalformat:
self.params.finalformat = DEFAULT_FINALFORMAT
@@ -179,19 +79,15 @@ class Breaker():
#final filepath is stored in self.filepath
self.filename = "{}.{}".format(self.basename, self.params.finalformat)
self.filepath = os.path.join(WORKING_DIR, self.filename)
- #lets go back to this in a second
self._conversion_file = os.path.join(WORKING_DIR, "IMBREAKTMP{}.{}".format(self.basename, self.params.breaktype)) # this
def _call_cmd(self, cmd, error=""):
try:
- call(cmd)
+ utils.call_cmd(cmd)
self.commands.append(" ".join(cmd));
- except Exception as e:
- if error:
- sys.stderr.write(error)
- else:
- sys.stderr.write(str(e))
+ except Exception:
+ raise Exception("Unable to call cmd {}".format(str(cmd)))
def _get_breaktype(self, key):
#{{{ conversion table
@@ -224,8 +120,8 @@ class Breaker():
name_part = url.split("/")[-1]
try:
parts = name_part.split(".")
- name_part = sanitize(parts[-2])
- file_format = sanitize(parts[-1])
+ name_part = utils.sanitize(parts[-2])
+ file_format = utils.sanitize(parts[-1])
if not name_part or not file_format:
sys.stderr.write( "Incompatible input file type")
raise;
@@ -237,7 +133,7 @@ class Breaker():
raise;
if (len(name_part) > 20):
name_part = name_part[:-20]
- return "{}{}_{}_{}".format(self.tag, name_part, self.now, self.params.username or ""), file_format
+ return "{}{}_{}_{}".format(self.tag, name_part, utils.now(), self.params.username or ""), file_format
#{{{#########rotatefunctions#######################################
def _rotate(self):
@@ -357,6 +253,15 @@ class Breaker():
self._cleanup()
if __name__ == "__main__":
- b = Breaker(TEST_PARAMS)
+ TEST_PARAMS = {
+ "url" : "http://i.asdf.us/im/27/1424816234661dumpfmpfifferkinggr_1424816412_pfifferking.gif" ,
+ "breaktype" : "RGB_WASH",
+ "finalformat" : "png",
+ "breakmode" : "extreme",
+ "breakangle" : "10",
+ "username" : "donkey",
+ "expanded" : "false"
+ }
+ b = Breaker(**TEST_PARAMS)
b.create();
print b.filepath