4 signal.signal(signal.SIGINT, signal.SIG_DFL)
13 from optparse import OptionParser
15 from BeautifulSoup import BeautifulSoup
20 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
21 '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
22 '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
23 '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
25 standingvals = ('Able/Distinguished/Respected/Master'+
26 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
28 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
30 max_pirate_namelen = 20
38 def __init__(self, ocean, cachedir):
39 debug('Fetcher init %s' % cachedir)
41 self.cachedir = cachedir
42 try: os.mkdir(cachedir)
43 except (OSError,IOError), oe:
44 if oe.errno != errno.EEXIST: raise
45 self._cache_scan(time.time())
47 def _cache_scan(self, now):
48 # returns list of ages, unsorted
50 debug('Fetcher scan_cache')
51 for leaf in os.listdir(self.cachedir):
52 if not leaf.startswith('#'): continue
53 path = self.cachedir + '/' + leaf
54 try: s = os.stat(path)
55 except (OSError,IOError), oe:
56 if oe.errno != errno.ENOENT: raise
58 age = now - s.st_mtime
59 if age > opts.expire_age:
60 debug('Fetcher expire %d %s' % (age, path))
62 except (OSError,IOError), oe:
63 if oe.errno != errno.ENOENT: raise
68 def _rate_limit_cache_clean(self, now):
69 ages = self._cache_scan(now)
71 debug('Fetcher ages ' + `ages`)
76 debug('Fetcher morewait min=%d age=%d' %
78 need_wait = max(need_wait, min_age - age)
82 debug('Fetcher wait %d' % need_wait)
85 def fetch(self, url, max_age):
86 debug('Fetcher fetch %s' % url)
87 cache_corename = urllib.quote_plus(url)
88 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
89 try: f = file(cache_item, 'r')
90 except (OSError,IOError), oe:
91 if oe.errno != errno.ENOENT: raise
94 max_age = max(opts.min_max_age, max(max_age, opts.expire_age))
96 s = os.fstat(f.fileno())
97 age = now - s.st_mtime
99 debug('Fetcher stale')
104 debug('Fetcher cached %d > %d' % (max_age, age))
107 debug('Fetcher fetch')
108 self._rate_limit_cache_clean(now)
110 stream = urllib2.urlopen(url)
112 cache_tmp = "%s/#%s~%d#" % (
113 self.cachedir, cache_corename, os.getpid())
114 f = file(cache_tmp, 'w')
117 os.rename(cache_tmp, cache_item)
118 debug('Fetcher stored')
121 def yoweb(self, kind, tail, max_age):
122 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
123 self.ocean, kind, tail)
124 return self.fetch(url, max_age)
131 def soupm(self, obj, m):
132 self.msg(m + '; in ' + `obj`)
133 def needs_msgs(self, child_souplog):
134 self.msgs += child_souplog.msgs
135 child_souplog.msgs = [ ]
138 str = ''.join(obj.findAll(text=True))
141 class SomethingSoupInfo(SoupLog):
142 def __init__(self, kind, tail, max_age):
143 SoupLog.__init__(self)
144 html = fetcher.yoweb(kind, tail, max_age)
145 self._soup = BeautifulSoup(html,
146 convertEntities=BeautifulSoup.HTML_ENTITIES
149 class PirateInfo(SomethingSoupInfo):
150 # Public data members:
151 # pi.standings = { 'Treasure Haul': 'Able' ... }
152 # pi.crew = (id, name)
153 # pi.flag = (id, name)
154 # pi.msgs = [ 'message describing problem with scrape' ]
156 def __init__(self, pirate, max_age=300):
157 SomethingSoupInfo.__init__(self,
158 'pirate.wm?target=', pirate, max_age)
159 self._find_standings()
160 self.crew = self._find_crewflag('crew',
161 '^/yoweb/crew/info\\.wm')
162 self.flag = self._find_crewflag('flag',
163 '^/yoweb/flag/info\\.wm')
165 def _find_standings(self):
166 imgs = self._soup.findAll('img',
167 src=regexp.compile('/yoweb/images/stat.*'))
169 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
173 for skill in puzzles:
174 standings[skill] = [ ]
179 try: puzzle = img['alt']
180 except KeyError: continue
182 if not puzzle in puzzles:
183 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
185 key = img.findParent('td')
187 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
189 valelem = key.findNextSibling('td')
191 skl.soupm(key, 'puzzle missing sibling "%s"'
194 valstr = soup_text(valelem)
195 match = re.match(valstr)
197 skl.soupm(key, ('puzzle "%s" unparseable'+
198 ' standing "%s"') % (puzzle, valstr))
200 standing = match.group(match.lastindex)
201 standings[puzzle].append(standing)
205 for puzzle in puzzles:
206 sl = standings[puzzle]
208 skl.msg('puzzle "%s" multiple standings %s' %
212 skl.msg('puzzle "%s" no standing found' % puzzle)
215 for i in range(0, len(standingvals)-1):
216 if standing == standingvals[i]:
217 self.standings[puzzle] = i
218 if not puzzle in self.standings:
219 skl.msg('puzzle "%s" unknown standing "%s"' %
222 all_standings_ok = True
223 for puzzle in puzzles:
224 if not puzzle in self.standings:
227 def _find_crewflag(self, cf, yoweb_re):
228 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
230 self.msg('zero or several %s id references found' % cf)
233 id_re = '\\b%sid\\=(\\w+)$' % cf
234 id_haystack = thing['href']
235 match = regexp.compile(id_re).search(id_haystack)
237 self.soupm(thing, ('incomprehensible %s id ref'+
238 ' (%s in %s)') % (cf, id_re, id_haystack))
240 name = soup_text(thing)
241 return (match.group(1), name)
244 return `(self.crew, self.flag, self.standings, self.msgs)`
246 class CrewInfo(SomethingSoupInfo):
247 # Public data members:
248 # ci.crew = [ ('Captain', ['Pirate', ...]),
249 # ('Senior Officer', [...]),
251 # pi.msgs = [ 'message describing problem with scrape' ]
253 def __init__(self, crewid, max_age=300):
254 SomethingSoupInfo.__init__(self,
255 'crew/info.wm?crewid=', crewid, max_age)
258 def _find_crew(self):
260 capts = self._soup.findAll('img',
261 src='/yoweb/images/crew-captain.png')
263 self.msg('crew members: no. of captain images != 1')
266 while not tbl.find('a', href=pirate_ref_re):
267 tbl = tbl.findParent('table')
269 self.msg('crew members: cannot find table')
271 current_rank_crew = None
272 crew_rank_re = regexp.compile('/yoweb/images/crew')
273 for row in tbl.contents:
274 # findAll(recurse=False)
275 if isinstance(row, unicode):
278 is_rank = row.find('img', attrs={'src': crew_rank_re})
280 rank = soup_text(row)
281 current_rank_crew = []
282 self.crew.append((rank, current_rank_crew))
284 for cell in row.findAll('a', href=pirate_ref_re):
285 if current_rank_crew is None:
286 self.soupm(cell, 'crew members: crew'
289 current_rank_crew.append(soup_text(cell))
292 return `(self.crew, self.msgs)`
294 class StandingsTable:
295 def __init__(self, use_puzzles=puzzles):
296 self._puzzles = use_puzzles
299 def _pline(self, pirate, puzstrs):
300 self.s += '%-*s' % (max_pirate_namelen, pirate)
302 self.s += ' %-*.*s' % (5,5, v)
305 def _puzstr(self, pi, puzzle):
306 if not isinstance(puzzle,list): puzzle = [puzzle]
307 try: standing = max([pi.standings[p] for p in puzzle])
308 except KeyError: return '?'
309 c1 = standingvals[standing][0]
310 if standing < 3: c1 = c1.lower() # 3 = Master
311 hashes = '*' * (standing / 2)
312 equals = '+' * (standing % 2)
313 return c1 + hashes + equals
316 def puzn_redact(name):
317 if isinstance(name,list):
319 ["%.2s" % puzn_redact(n)
322 if spc < 0: return name
323 return name[0:min(4,spc)] + name[spc+1:]
324 self._pline('', map(puzn_redact, self._puzzles))
325 def literalline(self, line):
326 self.s += line + '\n'
327 def pirate(self, pirate):
328 pi = PirateInfo(pirate, 600)
329 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
330 self._pline(pirate, puzstrs)
335 def do_pirate(pirates, bu):
337 for pirate in pirates:
338 info = PirateInfo(pirate)
339 print '%s: %s,' % (`pirate`, info)
342 def prep_crew_of(args, bu, max_age=300):
343 if len(args) != 1: bu('crew-of takes one pirate name')
344 pi = PirateInfo(args[0])
345 return CrewInfo(pi.crew[0])
347 def do_crew_of(args, bu):
348 ci = prep_crew_of(args, bu)
351 def do_standings_crew_of(args, bu):
352 ci = prep_crew_of(args, bu, 60)
353 tab = StandingsTable()
355 for (rank, members) in ci.crew:
356 if not members: continue
357 tab.literalline('%s:' % rank)
366 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
368 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
369 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
370 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
373 ao('-O','--ocean',dest='ocean', metavar='OCEAN',
375 help='select ocean OCEAN')
376 ao('--cache-dir', dest='cache_dir', metavar='DIR',
377 default='~/.yoweb-scrape-cache',
378 help='cache yoweb pages in DIR')
379 ao('-D','--debug', action='store_true', dest='debug', default=False,
380 help='enable debugging output')
381 ao('-q','--quiet', action='store_true', dest='quiet',
382 help='suppress warning output')
383 (opts,args) = pa.parse_args()
386 pa.error('need a mode argument')
389 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
390 try: mode_fn = globals()[mode_fn_name]
391 except KeyError: pa.error('unknown mode "%s"' % mode)
394 opts.min_max_age = 60
395 opts.expire_age = 3600
397 if opts.cache_dir.startswith('~/'):
398 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
400 fetcher = Fetcher(opts.ocean, opts.cache_dir)
402 mode_fn(args[1:], pa.error)