summaryrefslogtreecommitdiff
path: root/Pb/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'Pb/__init__.py')
-rw-r--r--Pb/__init__.py167
1 files changed, 50 insertions, 117 deletions
diff --git a/Pb/__init__.py b/Pb/__init__.py
index 909f03b..0212235 100644
--- a/Pb/__init__.py
+++ b/Pb/__init__.py
@@ -7,33 +7,64 @@ import sys
import os
import random
from subprocess import Popen,PIPE,call
-from Pb.Params import Params
+from Params import Params
+import time
Request = urllib2.Request
urlencode = urllib.urlencode
urlopen = urllib2.urlopen
+_max_filename_length = 20;
class Pb(object):
def __init__(self):
- self.params = Params();
+ self._now = str(int(time.time()));
+ self.params = Params(classname=self.__class__.__name__, now=self._now);
+ self._files_created = []
+ self.commands = [];
self._working_dir = WORKING_DIR
+ def _filename_create(self, url=None, namepart=""):
+ if url:
+ _basename = os.path.basename(url)
+ namepart = re.split(r'\.')[0]
+ namepart = self.params.sanitize(_namepart)[0:_max_filename_length]
+ name = ""
+ if namepart: name += "%s-" % namepart
+ name += "%s_%s" % (self.__class__.__name__, self._now)
+ if self.params.username : name += "_%s" % self.params.username
+ return name
+
+ def _filepath_create(self, filename, directory=WORKING_DIR):
+ return os.path.join(directory, filename)
+
+ def _filename_filepath_create(self, url=None, namepart="", directory=WORKING_DIR):
+ _filename = self._filename_create(url=url, namepart=namepart);
+ _filepath = _filename_create(_filename, directory=directory);
+ return _filename, _filepath
+
+ def _tempfilepath_create(self, namepart="temp", directory=WORKING_DIR):
+ _filename = self._filename_create(namepart=namepart)
+ return _filepath_create(_filename, directory=directory)
+
def _call_cmd(self, cmd):
- try:
- call(cmd)
- except Exception as e:
- self.err_warn("Could not call cmd: {}".format(str(cmd)))
- self.err_warn(str(e))
+ try:
+ self.call_cmd(cmd)
+ self.commands.append(" ".join(cmd));
+ except Exception:
+ raise Exception("Unable to call cmd {}".format(str(cmd)))
@staticmethod
- def is_color(s):
- if s == "":
- return "transparent"
- if re.match('(rgba?\([0-9]+,[0-9]+,[0-9]+\))|([a-zA-Z]+)|(\#[A-Ha-h0-9]+)', s):
- return s.replace(' ', '');
- else:
- sys.stderr.write("Not a color: {}\n".format(s))
- raise ValueError
+ 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:
+ self.err_warn("couldn't get gif frames")
+ raise e;
@staticmethod
def dimensions (filepath):
@@ -42,77 +73,6 @@ class Pb(object):
return ident[2].split("x")
@staticmethod
- def is_number(s):
- try:
- return int(s)
- except (ValueError, TypeError):
- return False
-
- def bool_correct(self, s):
- try:
- if re.match(r'^false$', str(s), re.IGNORECASE):
- return False
- elif re.match(r'^true$', str(s), re.IGNORECASE):
- return True
- else:
- return s
- except Exception as e:
- sys.stderr.write("WHAT THE FUCK")
-
- @staticmethod
- def get_mimetype(f):
- try:
- mimetype = Popen(
- [BIN_IDENTIFY, f], stdout=PIPE
- ).communicate()[0].split(" ")[1].lower()
- return mimetype
- except Exception as e:
- sys.stderr.write("couldn't determine mimetype")
- sys.stderr.write(str(e))
- raise;
-
- def sanitize (self, s):
- return re.sub(r'\W+', '', s)
-
- @staticmethod
- def now():
- return int(time.time())
-
- @staticmethod
- 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(self, url, destination, max_size=MAX_SIZE):
- response = self.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()
-
- @staticmethod
def file_size (filepath):
try:
return os.stat(filepath)[6]
@@ -121,37 +81,6 @@ class Pb(object):
sys.stderr.write(str(e)+"\n")
raise;
- def gif_frames(self, 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("{} couldn't get gif frames".format(self.__class__.__name__))
- sys.stderr.write(str(e))
- raise;
-
- def tempname_create(self, basename=None, fmt="png"):
- if not basename: basename = self.random_string_create()
- return os.path.join(self._working_dir, "{}{}.{}".format(self.__class__.__name__, basename, fmt)) # this
-
- def _get_filename_and_type_from_url (self, url):
- name = re.sub(r'(?:\s|\?.*|.*/)', '', urllib.unquote(url));
- try:
- basename, ext = map(lambda s: self.sanitize(s), re.search(r'(^.*)\.(.*$)', name).groups());
- except Exception as e:
- self.err_warn("Incompatible input file type")
- if (len(basename) > 20):
- basename = basename[:-20]
- return "{}{}_{}_{}".format(self.tag, basename, self._now, self.params.username or ""), ext
-
- def random_string_create(self):
- return "{}".format(random.uniform(0, 100000));
-
-
def _file_read(self, filepath):
f = open(filepath, 'r');
data = f.read()
@@ -161,6 +90,10 @@ class Pb(object):
def err_warn(self, s):
sys.stderr.write("ERROR:{} - {}\n".format(self.__class__.__name__, s))
+ def _cleanup(self):
+ cmd = ["rm"]+self._files_created
+ self._call_cmd(cmd)
+
def err_fatal(self, s):
sys.stderr.write("ERROR[FATAL]:{} - {}\n".format(self.__class__.__name__, s))
sys.exit(1);