4 signal.signal(signal.SIGINT, signal.SIG_DFL)
14 from optparse import OptionParser
16 from BeautifulSoup import BeautifulSoup
21 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
22 '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
23 '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
24 '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
26 standingvals = ('Able/Distinguished/Respected/Master'+
27 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
29 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
31 max_pirate_namelen = 12
39 def __init__(self, ocean, cachedir):
40 debug('Fetcher init %s' % cachedir)
42 self.cachedir = cachedir
43 try: os.mkdir(cachedir)
44 except (OSError,IOError), oe:
45 if oe.errno != errno.EEXIST: raise
46 self._cache_scan(time.time())
48 def _default_ocean(self):
49 if self.ocean is None:
52 def _cache_scan(self, now):
53 # returns list of ages, unsorted
55 debug('Fetcher scan_cache')
56 for leaf in os.listdir(self.cachedir):
57 if not leaf.startswith('#'): continue
58 path = self.cachedir + '/' + leaf
59 try: s = os.stat(path)
60 except (OSError,IOError), oe:
61 if oe.errno != errno.ENOENT: raise
63 age = now - s.st_mtime
64 if age > opts.expire_age:
65 debug('Fetcher expire %d %s' % (age, path))
67 except (OSError,IOError), oe:
68 if oe.errno != errno.ENOENT: raise
73 def _rate_limit_cache_clean(self, now):
74 ages = self._cache_scan(now)
76 debug('Fetcher ages ' + `ages`)
80 if age < min_age and age < 300:
81 debug('Fetcher morewait min=%d age=%d' %
83 need_wait = max(need_wait, min_age - age)
87 debug('Fetcher wait %d' % need_wait)
90 def fetch(self, url, max_age):
91 debug('Fetcher fetch %s' % url)
92 cache_corename = urllib.quote_plus(url)
93 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
94 try: f = file(cache_item, 'r')
95 except (OSError,IOError), oe:
96 if oe.errno != errno.ENOENT: raise
99 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
101 s = os.fstat(f.fileno())
102 age = now - s.st_mtime
104 debug('Fetcher stale %d < %d'% (max_age, age))
109 debug('Fetcher cached %d > %d' % (max_age, age))
112 debug('Fetcher fetch')
113 self._rate_limit_cache_clean(now)
115 stream = urllib2.urlopen(url)
117 cache_tmp = "%s/#%s~%d#" % (
118 self.cachedir, cache_corename, os.getpid())
119 f = file(cache_tmp, 'w')
122 os.rename(cache_tmp, cache_item)
123 debug('Fetcher stored')
126 def yoweb(self, kind, tail, max_age):
127 self._default_ocean()
128 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
129 self.ocean, kind, tail)
130 return self.fetch(url, max_age)
137 def soupm(self, obj, m):
138 self.msg(m + '; in ' + `obj`)
139 def needs_msgs(self, child_souplog):
140 self.msgs += child_souplog.msgs
141 child_souplog.msgs = [ ]
144 str = ''.join(obj.findAll(text=True))
147 class SomethingSoupInfo(SoupLog):
148 def __init__(self, kind, tail, max_age):
149 SoupLog.__init__(self)
150 html = fetcher.yoweb(kind, tail, max_age)
151 self._soup = BeautifulSoup(html,
152 convertEntities=BeautifulSoup.HTML_ENTITIES
155 class PirateInfo(SomethingSoupInfo):
156 # Public data members:
157 # pi.standings = { 'Treasure Haul': 'Able' ... }
159 # pi.crew = (id, name)
160 # pi.flag = (id, name)
161 # pi.msgs = [ 'message describing problem with scrape' ]
163 def __init__(self, pirate, max_age=300):
164 SomethingSoupInfo.__init__(self,
165 'pirate.wm?target=', pirate, max_age)
167 self._find_standings()
168 self.crew = self._find_crewflag('crew',
169 '^/yoweb/crew/info\\.wm')
170 self.flag = self._find_crewflag('flag',
171 '^/yoweb/flag/info\\.wm')
173 def _find_standings(self):
174 imgs = self._soup.findAll('img',
175 src=regexp.compile('/yoweb/images/stat.*'))
177 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
181 for skill in puzzles:
182 standings[skill] = [ ]
187 try: puzzle = img['alt']
188 except KeyError: continue
190 if not puzzle in puzzles:
191 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
193 key = img.findParent('td')
195 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
197 valelem = key.findNextSibling('td')
199 skl.soupm(key, 'puzzle missing sibling "%s"'
202 valstr = soup_text(valelem)
203 match = re.match(valstr)
205 skl.soupm(key, ('puzzle "%s" unparseable'+
206 ' standing "%s"') % (puzzle, valstr))
208 standing = match.group(match.lastindex)
209 standings[puzzle].append(standing)
213 for puzzle in puzzles:
214 sl = standings[puzzle]
216 skl.msg('puzzle "%s" multiple standings %s' %
220 skl.msg('puzzle "%s" no standing found' % puzzle)
223 for i in range(0, len(standingvals)-1):
224 if standing == standingvals[i]:
225 self.standings[puzzle] = i
226 if not puzzle in self.standings:
227 skl.msg('puzzle "%s" unknown standing "%s"' %
230 all_standings_ok = True
231 for puzzle in puzzles:
232 if not puzzle in self.standings:
235 def _find_crewflag(self, cf, yoweb_re):
236 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
238 self.msg('zero or several %s id references found' % cf)
241 id_re = '\\b%sid\\=(\\w+)$' % cf
242 id_haystack = thing['href']
243 match = regexp.compile(id_re).search(id_haystack)
245 self.soupm(thing, ('incomprehensible %s id ref'+
246 ' (%s in %s)') % (cf, id_re, id_haystack))
248 name = soup_text(thing)
249 return (match.group(1), name)
252 return `(self.crew, self.flag, self.standings, self.msgs)`
254 class CrewInfo(SomethingSoupInfo):
255 # Public data members:
256 # ci.crew = [ ('Captain', ['Pirate', ...]),
257 # ('Senior Officer', [...]),
259 # pi.msgs = [ 'message describing problem with scrape' ]
261 def __init__(self, crewid, max_age=300):
262 SomethingSoupInfo.__init__(self,
263 'crew/info.wm?crewid=', crewid, max_age)
266 def _find_crew(self):
268 capts = self._soup.findAll('img',
269 src='/yoweb/images/crew-captain.png')
271 self.msg('crew members: no. of captain images != 1')
274 while not tbl.find('a', href=pirate_ref_re):
275 tbl = tbl.findParent('table')
277 self.msg('crew members: cannot find table')
279 current_rank_crew = None
280 crew_rank_re = regexp.compile('/yoweb/images/crew')
281 for row in tbl.contents:
282 # findAll(recurse=False)
283 if isinstance(row, unicode):
286 is_rank = row.find('img', attrs={'src': crew_rank_re})
288 rank = soup_text(row)
289 current_rank_crew = []
290 self.crew.append((rank, current_rank_crew))
292 for cell in row.findAll('a', href=pirate_ref_re):
293 if current_rank_crew is None:
294 self.soupm(cell, 'crew members: crew'
297 current_rank_crew.append(soup_text(cell))
300 return `(self.crew, self.msgs)`
302 class StandingsTable:
303 def __init__(self, use_puzzles=None, col_width=6):
304 if use_puzzles is None:
307 'Navigating','Battle Navigation',
309 ['Sailing','Rigging'],
316 self._puzzles = use_puzzles
318 self._cw = col_width-1
320 def _pline(self, pirate, puzstrs):
321 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
323 self.s += ' %-*.*s' % (self._cw,self._cw, v)
326 def _puzstr(self, pi, puzzle):
327 if not isinstance(puzzle,list): puzzle = [puzzle]
328 try: standing = max([pi.standings[p] for p in puzzle])
329 except KeyError: return '?'
330 if not standing: return ''
333 c1 = standingvals[standing][0]
334 if standing < 3: c1 = c1.lower() # 3 = Master
338 s += '*' * (standing / 2)
339 s += '+' * (standing % 2)
343 def puzn_redact(name):
344 if isinstance(name,list):
346 ["%.*s" % (self._cw/2, puzn_redact(n))
349 if spc < 0: return name
350 return name[0:min(4,spc)] + name[spc+1:]
351 self._pline('', map(puzn_redact, self._puzzles))
352 def literalline(self, line):
353 self.s += line + '\n'
354 def pirate(self, pi):
355 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
356 self._pline(pi.name, puzstrs)
361 def do_pirate(pirates, bu):
363 for pirate in pirates:
364 info = PirateInfo(pirate)
365 print '%s: %s,' % (`pirate`, info)
368 def prep_crew_of(args, bu, max_age=300):
369 if len(args) != 1: bu('crew-of takes one pirate name')
370 pi = PirateInfo(args[0], max_age)
371 return CrewInfo(pi.crew[0], max_age)
373 def do_crew_of(args, bu):
374 ci = prep_crew_of(args, bu)
377 def do_standings_crew_of(args, bu):
378 ci = prep_crew_of(args, bu, 60)
379 tab = StandingsTable()
381 for (rank, members) in ci.crew:
382 if not members: continue
383 tab.literalline('%s:' % rank)
385 pi = PirateInfo(p, random.randint(900,1800))
394 def __init__(pa, v, time, event):
397 pa.last_event = event
400 class ShipCrewTracker:
401 def __init__(self, myself_pi):
402 self._pl = {} # self._pl['Pirate'] =
403 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
404 # self._vl['Vessel']['#lastaboard']
405 self._v = None # self._v =
406 self._vessel = None # self._vl[self._vessel]
408 self._myself = myself_pi
409 self._need_redisplay = False
412 self._need_redisplay = True
414 def _onboard_event(self,timestamp,pirate,event):
415 try: pa = self._pl[pirate]
416 except KeyError: pa = None
417 if pa is not None and pa.v is self._v:
418 pa.last_time = timestamp
419 pa.last_event = event
421 if pa is not None: del pa.v[pirate]
422 pa = PirateAboard(self._v, timestamp, event)
423 self._pl[pirate] = pa
425 self._v['#lastaboard'] = timestamp
429 def clear_vessel(self, timestamp):
430 if self._v is not None:
432 if p.startswith('#'): continue
434 self._v = {'#lastaboard': timestamp}
439 def chatline(self,l):
440 rm = lambda re: regexp.match(re,l)
441 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
443 self._date = m.groups()
445 if self._date is None:
447 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
449 self._warn('undated? '+l)
452 time_tuple = [int(x) for x in self._date + m.groups()]
453 time_tuple += (-1,-1,-1)
455 timestamp = time.mktime(time_tuple)
456 l = l[l.find(' ')+1:]
458 ob = lambda who, event: self._onboard_event(
459 timestamp, who, event)
460 oba = lambda m, did: ob(
461 m.group(1), '%s %s' % (did, m.group(2)))
463 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
465 self._vessel = m.group(1)
466 try: self._v = self._vl[self._vessel]
467 except KeyError: self._v = None
468 if self._v is not None: la = self._v['#lastaboard']
470 if timestamp - la > 3600:
471 self.clear_vessel(timestamp)
472 ob(self._myself.name, 'we boarded')
474 if self._v is None: return
476 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
478 pa = oba(m, 'ordered')
479 if m.group(2) == 'Gunning':
483 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
484 if m: oba(m,'abandoned'); return
486 m = rm('(\\w+) says, "')
487 if m: ob(m.group(1), 'talked'); return
489 m = rm('(\\w+) has left the vessel\.')
492 ob(who, 'disembarked')
499 def do_ship_aid(args, bu):
500 if len(args) != 1: bu('ship-aid takes only chat log filename')
502 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_chat-log-\\w+$'
503 match = regexp.match(logfn_re, logfn)
504 if not match: bu('ship-aid chat log filename is not in default format')
505 (pirate, fetcher.ocean) = match.groups()
506 myself_pi = PirateInfo(pirate,3600)
507 track = ShipCrewTracker(myself_pi)
517 # print `track.__dict__`
523 print `track.__dict__`
530 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
532 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
533 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
534 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
535 yoweb-scrape [--ocean OCEAN ...] ship-aid CHAT-LOG
538 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
539 help='select ocean OCEAN')
540 ao('--cache-dir', dest='cache_dir', metavar='DIR',
541 default='~/.yoweb-scrape-cache',
542 help='cache yoweb pages in DIR')
543 ao('-D','--debug', action='store_true', dest='debug', default=False,
544 help='enable debugging output')
545 ao('-q','--quiet', action='store_true', dest='quiet',
546 help='suppress warning output')
548 ao('--ship-duty', action='store_true', dest='ship_duty',
549 help='show ship duty station puzzles')
551 (opts,args) = pa.parse_args()
555 pa.error('need a mode argument')
558 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
559 try: mode_fn = globals()[mode_fn_name]
560 except KeyError: pa.error('unknown mode "%s"' % mode)
563 opts.min_max_age = 60
564 opts.expire_age = 3600
566 if opts.cache_dir.startswith('~/'):
567 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
569 fetcher = Fetcher(opts.ocean, opts.cache_dir)
571 mode_fn(args[1:], pa.error)