# # extlib : s60-simplejson.py # # # $Id: s60-simplejson.py,v 1.4 2007/01/14 03:11:52 asc Exp $ # # # This is a bare bones port, for Series 60 Python, of Bob Ippolito's # simplejson.py : http://cheeseshop.python.org/pypi/simplejson # # If you are reading this it is also very early days and may # yet change (translation : may be broken). # # Since installing custom libraries in Series 60 3rd Edition Python is # such a pain in the ass, it is designed to be something that a person # can simply copy and paste in to their own scripts/applications # (translation : beware of namespace collisions) # # For documentation, please see the '__main__' block below # # Aaron Straup Cope # http://aaronland.info/python/s60-simplejson/ # # required for the 'yield' love in py 2.2 # from __future__ import generators import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from sre import VERBOSE, MULTILINE, DOTALL import re FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL WHITESPACE = re.compile(r'\s*', FLAGS) # # random global functions # def pattern(pattern, flags=FLAGS): def decorator(fn): fn.pattern = pattern fn.regex = re.compile(pattern, flags) return fn return decorator # # Not defined in py 2.2 # def enumerate (list) : # list of tuples lot = [] for i in list : lot.append((len(lot), i)) return lot # # scanner.py # class Scanner(object): def __init__(self, lexicon, flags=FLAGS): self.actions = [None] # combine phrases into a compound pattern s = sre_parse.Pattern() s.flags = flags p = [] for idx, token in enumerate(lexicon): phrase = token.pattern try: subpattern = sre_parse.SubPattern(s, [(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))]) except sre_constants.error: raise p.append(subpattern) self.actions.append(token) p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def iterscan(self, string, idx=0, context=None): match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is None: break matchbegin, matchend = m.span() if lastend == matchend: break action = actions[m.lastindex] if action is not None: rval, next_pos = action(m, context) if next_pos is not None and next_pos != matchend: # "fast forward" the scanner matchend = next_pos match = self.scanner.scanner(string, matchend).match yield rval, matchend lastend = matchend # # decoder.py # def _floatconstants(): import struct import sys _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') # # Not sure if s60 py is 'big' or not # but sys.byteorder is not defined # # if sys.byteorder != 'big': # _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, 'true': True, 'false': False, 'null': None, } def JSONConstant(match, context, c=_CONSTANTS): return c[match.group(0)], None pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant) def JSONNumber(match, context): match = JSONNumber.regex.match(match.string, *match.span()) integer, frac, exp = match.groups() if frac or exp: res = float(integer + (frac or '') + (exp or '')) else: res = int(integer) return res, None pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber) STRINGCHUNK = re.compile(r'(.*?)(["\\])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match): if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) if terminator == '"': break try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) if esc != 'u': try: m = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: esc = s[end + 1:end + 5] try: m = unichr(int(esc, 16)) if len(esc) != 4 or not esc.isalnum(): raise ValueError except ValueError: raise ValueError(errmsg("Invalid \\uXXXX escape", s, end)) end += 5 _append(m) return u''.join(chunks), end def JSONString(match, context): encoding = getattr(context, 'encoding', None) return scanstring(match.string, match.end(), encoding) pattern(r'"')(JSONString) def JSONObject(match, context, _w=WHITESPACE.match): pairs = {} s = match.string end = _w(s, match.end()).end() nextchar = s[end:end + 1] # trivial empty object if nextchar == '}': return pairs, end + 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 encoding = getattr(context, 'encoding', None) iterscan = JSONScanner.iterscan while True: key, end = scanstring(s, end, encoding) end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end = _w(s, end + 1).end() try: value, end = iterscan(s, idx=end, context=context).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == '}': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) object_hook = getattr(context, 'object_hook', None) if object_hook is not None: pairs = object_hook(pairs) return pairs, end pattern(r'{')(JSONObject) def JSONArray(match, context, _w=WHITESPACE.match): values = [] s = match.string end = _w(s, match.end()).end() # look-ahead for trivial empty array nextchar = s[end:end + 1] if nextchar == ']': return values, end + 1 iterscan = JSONScanner.iterscan while True: try: value, end = iterscan(s, idx=end, context=context).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) values.append(value) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) end = _w(s, end).end() return values, end pattern(r'\[')(JSONArray) ANYTHING = [ JSONObject, JSONArray, JSONString, JSONConstant, JSONNumber, ] JSONScanner = Scanner(ANYTHING) class JSONDecoder(object): _scanner = Scanner(ANYTHING) __all__ = ['__init__', 'decode', 'raw_decode'] def __init__(self, encoding=None, object_hook=None): self.encoding = encoding self.object_hook = object_hook def decode(self, s, _w=WHITESPACE.match): obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, **kw): kw.setdefault('context', self) try: obj, end = self._scanner.iterscan(s, **kw).next() except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end # # simplejson.py # class simplejson : def __init__ (self) : pass def dump(self, obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, **kw): if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(self, obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, **kw): if cls is None: cls = JSONEncoder return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, **kw).encode(obj) def load(self, fp, encoding=None, cls=None, object_hook=None, **kw): if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook return cls(encoding=encoding, **kw).decode(fp.read()) def loads(self, s, encoding=None, cls=None, object_hook=None, **kw): if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook return cls(encoding=encoding, **kw).decode(s) # # END # # # extlib : s60-simplehttp.py # import httplib import base64 class simplehttp : def __init__ (self, creds=None) : self.__auth__ = None if not creds == None : user = creds[0] pswd = creds[1] self.__auth__ = base64.encodestring(user + ":" + pswd) # # # def get (self, host, path, headers={}) : return self.execute_http_request('GET', host, path, headers) # # # def post (self, host, path, params=None, headers={}) : return self.execute_http_request('POST', host, path, params) # # # def execute_http_request(self, meth, host, path, params=None, headers={}) : if self.__auth__ : headers['Authorization'] = "Basic %s" % self.__auth__ c = httplib.HTTPConnection(host) c.request(meth, path, params, headers) r = c.getresponse() return r.read() # # extlib : s60-simplestore.py # import e32 class simplestore : def __init__ (self, path) : self.__path__ = path self.__db__ = None self.open() # # # def open (self) : if e32.in_emulator() : import anydbm self.__db__ = anydbm.open(self.__path__, 'c') else : import e32dbm self.__db__ = e32dbm.open(self.__path__, 'c') # # # def close (self) : self.__db__.close() self.__db__ = None # # # def read (self, key) : key = str(key) if self.__db__.has_key(key) : return self.__db__[key] return None # # # def write (self, key, value) : key = str(key) value = str(value) self.__db__[key] = value self.save() # # # def save (self) : # hack... self.close() self.open() # # extlib : s60-simplenumbers.py # import graphics class simplenumbers : def __init__ (self, num, sq=5) : self.__char__ = 3 self.__border__ = 0 self.__fill__ = (0,0,0) self.__num__ = num self.__sq__ = sq # # # def border (self, width=3) : self.__border__ = width # # # def fill (self, tpl) : self.__fill__ = tpl # # # def draw (self) : num = str(self.__num__) count = len(num) h = self.__sq__ * (5 + 2) w = self.__sq__ * ((count * 3) + (count - 1) + 2) # im = graphics.Image.new((w, h)) x = self.__sq__ y = self.__sq__ for char in num : if char == '1' : self.one(im, x, y) elif char == '2' : self.two(im, x, y) elif char == '3' : self.three(im, x, y) elif char == '4' : self.four(im, x, y) elif char == '5' : self.five(im, x, y) elif char == '6' : self.six(im, x, y) elif char == '7' : self.seven(im, x, y) elif char == '8' : self.eight(im, x, y) elif char == '9' : self.nine(im, x, y) elif char == '0' : self.zero(im, x, y) elif char == '.' : self.dot(im, x, y) else : pass x += self.__sq__ + (self.__sq__ * self.__char__) y = self.__sq__ # if self.__border__ : im.rectangle((0, 0, w, h), outline=self.__fill__, width=self.__border__) # return im # # use draw_line; draw_rect # def one (self, im, x, y) : # cap x_start = x y_start = y x_end = x_start + self.__sq__ y_end = y_start + self.__sq__ self.draw_rect(im, (x_start, y_start, x_end, y_end)) # center bar x_start = x + self.__sq__ y_start = y x_end = x_start + self.__sq__ y_end = y + (self.__sq__ * 4) self.draw_rect(im, (x_start, y_start, x_end, y_end)) # foot x_start = x y_start = y + (self.__sq__ * 4) x_end = x_start + (self.__sq__ * self.__char__) y_end = y_start + self.__sq__ self.draw_rect(im, (x_start, y_start, x_end, y_end)) # # # def two (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # foo y += self.__sq__ self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # center y += self.__sq__ self.draw_line(im, 'h', x, y) # bar y += self.__sq__ self.draw_rect(im, (x, y, x + self.__sq__, y + self.__sq__)) # bottom y += self.__sq__ self.draw_line(im, 'h', x, y) # # # def three (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # foo y += self.__sq__ self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # center y += self.__sq__ self.draw_line(im, 'h', x, y) # bar y += self.__sq__ self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # bottom y += self.__sq__ self.draw_line(im, 'h', x, y) # # # def four (self, im, x, y) : # left arm self.draw_rect(im, (x, y, x + self.__sq__, y + (self.__sq__ * 2))) # center self.draw_line(im, 'h', x, y + (self.__sq__ * 2)) # right side self.draw_line(im, 'v', x + (self.__sq__ * 2), y) # # # def five (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # foo y += self.__sq__ self.draw_rect(im, (x, y, x + self.__sq__, y + self.__sq__)) # center y += self.__sq__ self.draw_line(im, 'h', x, y) # bar y += self.__sq__ self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # bottom y += self.__sq__ self.draw_line(im, 'h', x, y) # # # def six (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # foo y += self.__sq__ self.draw_rect(im, (x, y, x + self.__sq__, y + self.__sq__)) # center y += self.__sq__ self.draw_line(im, 'h', x, y) # bar y += self.__sq__ self.draw_rect(im, (x, y, x + self.__sq__, y + self.__sq__)) self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # bottom y += self.__sq__ self.draw_line(im, 'h', x, y) # # # def seven (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # center self.draw_rect(im, (x + self.__sq__, y + (self.__sq__ * 2), x + (self.__sq__ * 2), y + (self.__sq__ * 3))) # right side self.draw_line(im, 'v', x + (self.__sq__ * 2), y) # # # def eight (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # left side self.draw_line(im, 'v', x, y) # center self.draw_line(im, 'h', x, y + (self.__sq__ * 2)) # right side self.draw_line(im, 'v', x + (self.__sq__ * 2), y) # bottom self.draw_line(im, 'h', x, y + (self.__sq__ * 4)) # # # def nine (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # foo y += self.__sq__ self.draw_rect(im, (x, y, x + self.__sq__, y + self.__sq__)) self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # center y += self.__sq__ self.draw_line(im, 'h', x, y) # bar y += self.__sq__ self.draw_rect(im, (x + (self.__sq__ * 2), y, x + (self.__sq__ * 3), y + self.__sq__)) # bottom y += self.__sq__ self.draw_line(im, 'h', x, y) # # # def zero (self, im, x, y) : # top self.draw_line(im, 'h', x, y) # left side self.draw_line(im, 'v', x, y) # right side self.draw_line(im, 'v', x + (self.__sq__ * 2), y) # bottom self.draw_line(im, 'h', x, y + (self.__sq__ * 4)) # # # def dot (self, im, x, y) : start_x = x + self.__sq__ start_y = y + (self.__sq__ * 4) end_x = start_x + self.__sq__ end_y = start_y + self.__sq__ self.draw_rect(im, (start_x, start_y, end_x, end_y)) # # # def draw_line (self, im, dir, x, y) : if dir == 'h' : start_x = x start_y = y end_x = start_x + (self.__sq__ * 3) end_y = start_y + self.__sq__ else : start_x = x start_y = y end_x = start_x + self.__sq__ end_y = start_y + (self.__sq__ * 5) self.draw_rect(im, (start_x, start_y, end_x, end_y)) # # # def draw_rect (self, im, coords) : im.rectangle(coords, fill=self.__fill__) # # END # # # extlib : s60-simpleflickr.py # # s60_include : /home/asc/lib/python/s60-simplejson/s60-simplejson.py # s60_include : /home/asc/lib/python/s60-simplehttp/s60-simplehttp.py import urllib import md5 class simpleflickr : def __init__ (self, key, secret=None, token=None) : self.__host__ = 'api.flickr.com' self.__endpoint__ = '/services/rest' self.__apikey__ = key self.__appsecret__ = secret self.__authtoken__ = token # # # def get_token (self, frob) : pass # # # def get_frob (self) : pass # # # def execute_method (self, method, kwargs={}) : kwargs['method'] = method kwargs['format'] = 'json' kwargs['nojsoncallback'] = 1 kwargs['api_key'] = self.__apikey__ if self.__authtoken__ : kwargs['auth_token'] = self.__authtoken__ kwargs['api_sig'] = self.sign_args(kwargs) path = '%s?%s' % (self.__endpoint__, urllib.urlencode(kwargs)) http = simplehttp() json = http.get(self.__host__, path) sj = simplejson() return sj.loads(json) # # # def sign_args (self, args) : params = args.keys() params.sort() sig = unicode(self.__appsecret__) for key in params : sig += unicode(key) + unicode(args[key]) return md5.md5(sig).hexdigest() # # # # # extlib : s60-simpleapp.py # import e32 import appuifw class simpleapp : def __init__ (self) : self.__log__ = u"" self.__kill__ = False self.__poll__ = False self.__current__ = u"" self.__activity__ = [] if self.use_lock() : self.__lock__ = e32.Ao_lock() appuifw.app.exit_key_handler = self.abort # # # def abort (self) : self.__kill__ = True self.__lock__.signal() # # # def loop (self) : if self.setup() : self.run() if self.use_lock() : self.__lock__.wait() # # # def setup (self) : self.log("I am running") # # # def run (self) : self.poll() # # # def poll (self) : if self.__poll__ : self.error("Already polling") return False self.__poll__ = True self.do_poll() self.__poll__ = False self.sleep() # # # def do_poll (self) : pass # # # def sleep (self, secs=600) : self.record_activity("Sleeping for %s seconds" % secs) # if e32.in_emulator() : return time.sleep(secs) self.poll() else : timer = e32.Ao_timer() timer.after(secs, self.poll) self.__timer__ = timer # # # def use_lock (self) : if e32.in_emulator() : return True return False # # "STDOUT" # def log (self, msg, reset=False) : if reset : self.__log__ = unicode("") self.__log__ += "%s\n" % msg self.write(unicode(self.__log__)) # # # def write(self, txt) : if e32.in_emulator() : t = appuifw.Text() t.write(txt) appuifw.app.body = t else : appuifw.app.body = appuifw.Text(txt) # # # def announce (self, msg, type='info') : self.note(msg, type, True) # # # def notice (self, msg) : self.note(msg, 'info') # # # def error (self, msg) : self.note(msg, 'error') # # # def note (self, msg, type, gbl=False) : if not e32.in_emulator and gbl : appuifw.note(unicode(msg), type, gbl) else : appuifw.note(unicode(msg), type) # # # def prompt (self, query, type="text") : if e32.in_emulator() : return raw_input("%s : " % query) return appuifw.query(unicode(query), type) # # # def record_activity (self, msg, display=True) : self.__activity__.append(unicode("* %s" % msg)) if display : self.display_activity() # # # def display_activity (self) : msg = "\n".join(self.__activity__) reset = True self.log(msg, reset) # # # def switch_to_app (self) : self.display_app() self.setup_app_menu() # # # def display_app (self) : pass # # # def switch_to_activity (self) : self.display_activity() self.setup_activity_menu() # # # def setup_activity_menu (self) : pass # # # def setup_app_menu (self) : pass # # # def setup_simplestore(self, storename) : storepath = storename if not e32.in_emulator() : import sysinfo if 'E:' in sysinfo.free_drivespace().keys() : storepath = 'e:\\%s' % storename else : storepath = 'c:\\%s' % storename # try : self.__store__ = simplestore(storepath) except Exception, e : self.error("Failed to open local datastore, %s" % e) return False return True # # # def vibrate (self) : try : import misty misty.vibrate(500, 100) except Exception, e : return False # # # # # extlib : s60-simpleflickrapp.py # # s60_include : /home/aaron/lib/python/s60-simplejson/s60-simplejson.py # s60_include : /home/aaron/lib/python/s60-simplehttp/s60-simplehttp.py # s60_include : /home/aaron/lib/python/s60-simplestore/s60-simplestore.py # s60_include : /home/aaron/lib/python/s60-simplenumbers/s60-simplenumbers.py # s60_include : /home/aaron/lib/python/s60-simpleflickr/s60-simpleflickr.py # s60_include : /home/aaron/lib/python/s60-simpleapp/s60-simpleapp.py import appuifw import graphics import os import os.path import md5 # # # class simpleflickrapp (simpleapp) : def __init__(self, key, secret, token) : simpleapp.__init__(self) self.__store__ = None self.__images__ = [] self.__pending__ = [] self.__show__ = False self.__ph__ = None self.__tw__ = None self.__twim__ = None self.__fl__ = simpleflickr(key, secret, token) # # # def setup (self) : if not self.setup_simplestore('flickr') : return False self.setup_app_menu() return True # # # def setup_app_menu (self) : appuifw.app.menu = [ (unicode("Next image"), self.show_next_image), (unicode("Fetch new images"), self.poll), (unicode("View logs"), self.switch_to_activity) ] # # # def do_poll (self) : self.__show__ = False self.record_activity(u"Collecting images") self.get_images() # # # def get_flickr_photos (self) : self.error("You must define your own 'get_flickr_photos' method") return None # # # def flickr_api_call(self, method, args={}) : try : res = self.__fl__.execute_method(method, args) except Exception, e : self.error("API error : %s" % e) return None return self.test_flickr_rsp(res) # # # def test_flickr_rsp (self, res) : if not res : self.error("OMGWTF! No Flickr response") return None if res['stat'] != 'ok' : msg = "(%s) %s" % (res['code']. res['message']) self.error(msg) return None return res # # # def get_images (self) : res = self.get_flickr_photos() if not res : return False # pending = len(self.__images__) for ph in res['photos']['photo'] : uid = unicode(ph['id']) if self.__store__.read(uid) : self.record_activity("skip %s (seen)" % uid) continue if uid in self.__pending__ : self.record_activity("skip %s (pending)" % uid) continue self.record_activity("add %s" % uid) self.__images__.append(ph) self.__pending__.append(uid) current = len(self.__images__) # if pending != current : new = (current - pending) self.record_activity("%s new images" % new) self.show_next_image() self.vibrate() else : self.record_activity("no new images") self.show_number(0) # return True # # # def fetch_image (self, url) : hex = self.digesterize(url) store = unicode("c:\\fl-" + hex + ".jpg") self.record_activity("fetch %s" % url) self.record_activity("store as %s" % store) # if not os.path.exists(store) : try : urllib.urlretrieve(url, store) except Exception, e : self.error("Failed to retrieve image, %s" % e) return None # if e32.in_emulator() : os.unlink(store) return True try : image = graphics.Image.open(store) except Exception, e : self.error("Failed to open image, %s" % e) os.unlink(store) return None os.unlink(store) # (w, h) = image.size image.rectangle((0, 0, (w-1) , (h-1)), outline=(0, 0, 0), width=2) # return image # # # def show_next_image (self) : self.__show__ = False if len(self.__images__) == 0 : self.show_number(0) self.log("Waiting for someone to take a picture...", True) return False # self.show_beachball() # c = len(self.__images__) self.record_activity("%s remaining images" % c) ph = self.__images__.pop(0) url = "http://farm%s.static.flickr.com/%s/%s_%s_t.jpg" % (ph['farm'], ph['server'], ph['id'], ph['secret']) c = len(self.__images__) self.record_activity("%s remaining images" % c) try : image = self.fetch_image(url) self.show_photo(image, ph) except Exception, e : self.error("Failed to show %s, %s" % (ph['title'], e)) return False uid = unicode(ph['id']) self.mark_as_seen(uid) return True # # # def mark_as_seen(self, uid) : self.__pending__.remove(uid) self.__store__.write(uid, '1') self.__store__.save() # # # def show_photo (self, image, ph) : self.__show__ = True self.__ph__ = ph self.show_image(image) self.display_photo_info(ph) # # # def show_beachball (self) : self.show_number('...') # # # def show_number(self, num) : sn = simplenumbers(num, 5) sn.border(2) sn.fill((255, 0, 0)) image = sn.draw() self.show_image(image) # # # def show_image (self, image) : if e32.in_emulator() : self.record_activity("show image %s" % image) return True # try : import topwindow except Exception, e : self.error("Can not load topwindow") return False if not self.__tw__ : self.__tw__ = topwindow.TopWindow() else : self.__tw__.hide() self.__tw__.remove_image(self.__twim__) sz = image.size cv = appuifw.Canvas() cw = cv.size[0] self.__tw__.size = sz self.__tw__.position = ((cw - 25 - sz[0]), 15) self.__tw__.add_image(image, (0, 0)) self.__tw__.show() self.__twim__ = image # # # def display_photo_info (self, ph) : msg = "\"%s\"\n---\nby %s" % (ph['title'], ph['username']) reset = True self.log(msg, reset) # # # def digesterize (self, url) : return md5.md5(url).hexdigest() # # # def record_activity (self, msg) : display = True if self.__show__ : display = False simpleapp.record_activity(self, msg, display) # # # def open_url (self, url) : if e32.in_emulator() : self.record_activity("open %s" % url) return apprun = 'z:\\system\\programs\\apprun.exe' browser = 'z:\\System\\Apps\\Browser\\Browser.app' e32.start_exe(apprun, browser + ' "%s"' % url , 1) # # # class flickrwidgt (simpleflickrapp) : def get_flickr_photos (self) : return self.flickr_api_call('flickr.photos.getContactsPhotos', {'count':50}) if __name__ == '__main__' : key = 'yer flickr api api' secret = 'yer flickr app secret' token = 'yer flickr auth token' app = flickrwidgt(key, secret, token) app.loop()