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 need_wait(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)
88 def _rate_limit_cache_clean(self, now):
89 need_wait = self.need_wait(now)
91 debug('Fetcher wait %d' % need_wait)
94 def fetch(self, url, max_age):
95 debug('Fetcher fetch %s' % url)
96 cache_corename = urllib.quote_plus(url)
97 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
98 try: f = file(cache_item, 'r')
99 except (OSError,IOError), oe:
100 if oe.errno != errno.ENOENT: raise
103 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
105 s = os.fstat(f.fileno())
106 age = now - s.st_mtime
108 debug('Fetcher stale %d < %d'% (max_age, age))
113 debug('Fetcher cached %d > %d' % (max_age, age))
116 debug('Fetcher fetch')
117 self._rate_limit_cache_clean(now)
119 stream = urllib2.urlopen(url)
121 cache_tmp = "%s/#%s~%d#" % (
122 self.cachedir, cache_corename, os.getpid())
123 f = file(cache_tmp, 'w')
126 os.rename(cache_tmp, cache_item)
127 debug('Fetcher stored')
130 def yoweb(self, kind, tail, max_age):
131 self._default_ocean()
132 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
133 self.ocean, kind, tail)
134 return self.fetch(url, max_age)
141 def soupm(self, obj, m):
142 self.msg(m + '; in ' + `obj`)
143 def needs_msgs(self, child_souplog):
144 self.msgs += child_souplog.msgs
145 child_souplog.msgs = [ ]
148 str = ''.join(obj.findAll(text=True))
151 class SomethingSoupInfo(SoupLog):
152 def __init__(self, kind, tail, max_age):
153 SoupLog.__init__(self)
154 html = fetcher.yoweb(kind, tail, max_age)
155 self._soup = BeautifulSoup(html,
156 convertEntities=BeautifulSoup.HTML_ENTITIES
159 class PirateInfo(SomethingSoupInfo):
160 # Public data members:
161 # pi.standings = { 'Treasure Haul': 'Able' ... }
163 # pi.crew = (id, name)
164 # pi.flag = (id, name)
165 # pi.msgs = [ 'message describing problem with scrape' ]
167 def __init__(self, pirate, max_age=300):
168 SomethingSoupInfo.__init__(self,
169 'pirate.wm?target=', pirate, max_age)
171 self._find_standings()
172 self.crew = self._find_crewflag('crew',
173 '^/yoweb/crew/info\\.wm')
174 self.flag = self._find_crewflag('flag',
175 '^/yoweb/flag/info\\.wm')
177 def _find_standings(self):
178 imgs = self._soup.findAll('img',
179 src=regexp.compile('/yoweb/images/stat.*'))
181 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
185 for skill in puzzles:
186 standings[skill] = [ ]
191 try: puzzle = img['alt']
192 except KeyError: continue
194 if not puzzle in puzzles:
195 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
197 key = img.findParent('td')
199 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
201 valelem = key.findNextSibling('td')
203 skl.soupm(key, 'puzzle missing sibling "%s"'
206 valstr = soup_text(valelem)
207 match = re.match(valstr)
209 skl.soupm(key, ('puzzle "%s" unparseable'+
210 ' standing "%s"') % (puzzle, valstr))
212 standing = match.group(match.lastindex)
213 standings[puzzle].append(standing)
217 for puzzle in puzzles:
218 sl = standings[puzzle]
220 skl.msg('puzzle "%s" multiple standings %s' %
224 skl.msg('puzzle "%s" no standing found' % puzzle)
227 for i in range(0, len(standingvals)-1):
228 if standing == standingvals[i]:
229 self.standings[puzzle] = i
230 if not puzzle in self.standings:
231 skl.msg('puzzle "%s" unknown standing "%s"' %
234 all_standings_ok = True
235 for puzzle in puzzles:
236 if not puzzle in self.standings:
239 def _find_crewflag(self, cf, yoweb_re):
240 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
242 self.msg('zero or several %s id references found' % cf)
245 id_re = '\\b%sid\\=(\\w+)$' % cf
246 id_haystack = thing['href']
247 match = regexp.compile(id_re).search(id_haystack)
249 self.soupm(thing, ('incomprehensible %s id ref'+
250 ' (%s in %s)') % (cf, id_re, id_haystack))
252 name = soup_text(thing)
253 return (match.group(1), name)
256 return `(self.crew, self.flag, self.standings, self.msgs)`
258 class CrewInfo(SomethingSoupInfo):
259 # Public data members:
260 # ci.crew = [ ('Captain', ['Pirate', ...]),
261 # ('Senior Officer', [...]),
263 # pi.msgs = [ 'message describing problem with scrape' ]
265 def __init__(self, crewid, max_age=300):
266 SomethingSoupInfo.__init__(self,
267 'crew/info.wm?crewid=', crewid, max_age)
270 def _find_crew(self):
272 capts = self._soup.findAll('img',
273 src='/yoweb/images/crew-captain.png')
275 self.msg('crew members: no. of captain images != 1')
278 while not tbl.find('a', href=pirate_ref_re):
279 tbl = tbl.findParent('table')
281 self.msg('crew members: cannot find table')
283 current_rank_crew = None
284 crew_rank_re = regexp.compile('/yoweb/images/crew')
285 for row in tbl.contents:
286 # findAll(recurse=False)
287 if isinstance(row,basestring):
290 is_rank = row.find('img', attrs={'src': crew_rank_re})
292 rank = soup_text(row)
293 current_rank_crew = []
294 self.crew.append((rank, current_rank_crew))
296 for cell in row.findAll('a', href=pirate_ref_re):
297 if current_rank_crew is None:
298 self.soupm(cell, 'crew members: crew'
301 current_rank_crew.append(soup_text(cell))
304 return `(self.crew, self.msgs)`
306 class StandingsTable:
307 def __init__(self, use_puzzles=None, col_width=6):
308 if use_puzzles is None:
311 'Navigating','Battle Navigation',
313 ['Sailing','Rigging'],
320 self._puzzles = use_puzzles
322 self._cw = col_width-1
324 def _pline(self, pirate, puzstrs):
325 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
327 self.s += ' %-*.*s' % (self._cw,self._cw, v)
330 def _puzstr(self, pi, puzzle):
331 if not isinstance(puzzle,list): puzzle = [puzzle]
332 try: standing = max([pi.standings[p] for p in puzzle])
333 except KeyError: return '?'
334 if not standing: return ''
337 c1 = standingvals[standing][0]
338 if standing < 3: c1 = c1.lower() # 3 = Master
342 s += '*' * (standing / 2)
343 s += '+' * (standing % 2)
347 def puzn_redact(name):
348 if isinstance(name,list):
350 ["%.*s" % (self._cw/2, puzn_redact(n))
353 if spc < 0: return name
354 return name[0:min(4,spc)] + name[spc+1:]
355 self._pline('', map(puzn_redact, self._puzzles))
356 def literalline(self, line):
357 self.s += line + '\n'
358 def pirate_dummy(self, name, standingstring):
359 self._pline(name, standingstring * len(self._puzzles))
360 def pirate(self, pi):
361 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
362 self._pline(pi.name, puzstrs)
367 def do_pirate(pirates, bu):
369 for pirate in pirates:
370 info = PirateInfo(pirate)
371 print '%s: %s,' % (`pirate`, info)
374 def prep_crew_of(args, bu, max_age=300):
375 if len(args) != 1: bu('crew-of takes one pirate name')
376 pi = PirateInfo(args[0], max_age)
377 return CrewInfo(pi.crew[0], max_age)
379 def do_crew_of(args, bu):
380 ci = prep_crew_of(args, bu)
383 def do_standings_crew_of(args, bu):
384 ci = prep_crew_of(args, bu, 60)
385 tab = StandingsTable()
387 for (rank, members) in ci.crew:
388 if not members: continue
389 tab.literalline('%s:' % rank)
391 pi = PirateInfo(p, random.randint(900,1800))
405 def __init__(pa, pn, v, time, event):
409 pa.last_event = event
410 pa.last_chat_time = None
411 pa.last_chat_chan = None
416 if not pa.pi and not fetcher.need_wait(time.time()):
417 pa.pi = PirateInfo(pa.name, 3600)
420 class ChatLogTracker:
421 def __init__(self, myself_pi, logfn):
422 self._pl = {} # self._pl['Pirate'] =
423 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
424 # self._vl['Vessel']['#lastaboard']
425 self._v = None # self._v =
426 self._vessel = None # self._vl[self._vessel]
428 self._myself = myself_pi
429 self._need_redisplay = False
430 self._f = file(logfn)
432 self._progress = [0, os.fstat(self._f.fileno()).st_size]
435 self._need_redisplay = True
437 def _onboard_event(self,timestamp,pirate,event):
438 try: pa = self._pl[pirate]
439 except KeyError: pa = None
440 if pa is not None and pa.v is self._v:
441 pa.last_time = timestamp
442 pa.last_event = event
444 if pa is not None: del pa.v[pirate]
445 pa = PirateAboard(pirate, self._v, timestamp, event)
446 self._pl[pirate] = pa
448 self._v['#lastaboard'] = timestamp
452 def _trash_vessel(self, v):
454 if pn.startswith('#'): continue
458 def expire_garbage(self, timestamp):
459 for (vn,v) in list(self._vl.iteritems()):
460 la = v['#lastaboard']
461 if timestamp - la > opts.ship_reboard_clearout:
462 self._debug_line_disposition(timestamp,'',
464 self._trash_vessel(v)
467 def clear_vessel(self, timestamp):
468 if self._v is not None:
469 self._trash_vessel(self._v)
470 self._v = {'#lastaboard': timestamp}
471 self._vl[self._vessel] = self._v
473 def _debug_line_disposition(self,timestamp,l,m):
474 debug('CLT %13s %-30s %s' % (timestamp,m,l))
476 def chatline(self,l):
477 rm = lambda re: regexp.match(re,l)
478 d = lambda m: self._debug_line_disposition(timestamp,l,m)
481 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
483 self._date = m.groups()
484 return d('date '+`self._date`)
486 if self._date is None:
487 return d('date unset')
489 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
491 return d('no timestamp')
493 time_tuple = [int(x) for x in self._date + m.groups()]
494 time_tuple += (-1,-1,-1)
495 timestamp = time.mktime(time_tuple)
496 l = l[l.find(' ')+1:]
499 return self._onboard_event(timestamp, who, event)
500 def ob1(did): ob_x(m.group(1), did); return d(did)
501 def oba(did): return ob1('%s %s' % (did, m.group(2)))
503 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
505 pn = self._myself.name
506 self._vessel = m.group(1)
509 try: self._v = self._vl[self._vessel]
510 except KeyError: self._v = None; dm += ' new'
512 if self._v is not None: la = self._v['#lastaboard']
513 else: la = 0; dm += ' ?la'
515 if timestamp - la > opts.ship_reboard_clearout:
516 self.clear_vessel(timestamp)
519 ob_x(pn, 'we boarded')
520 self.expire_garbage(timestamp)
524 return d('no vessel')
526 m = rm('(\\w+) has come aboard\\.$')
527 if m: return ob1('boarded');
529 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
531 (who,what) = m.groups()
532 pa = ob_x(who,'ordered '+what)
533 if what == 'Gunning':
535 return d('duty order')
537 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
538 if m: oba('stopped'); return d('stopped')
542 try: pa = self._pl[who]
543 except KeyError: return d('chat mystery')
545 pa.last_chat_time = timestamp
546 pa.last_chat_chan = what
548 return d(what+' chat')
550 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
551 if m: return ob1('general order');
553 m = rm('(\\w+) says, "')
554 if m: return chat('public')
556 m = rm('(\\w+) tells ye, "')
557 if m: return chat('private')
559 m = rm('(\\w+) flag officer chats, "')
560 if m: return chat('flag officer')
562 m = rm('(\\w+) officer chats, "')
563 if m: return chat('officer')
565 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
567 pl = m.group(1).split(', ')
568 if not self._myself.name in pl:
569 return d('lost boarding battle')
571 if ' ' in pn: continue
572 ob_x(pn,'won boarding battle')
573 return d('won boarding battle')
575 m = rm('(\\w+) is eliminated\\!')
576 if m: return ob1('eliminated in fray');
578 m = rm('(\\w+) has left the vessel\.')
581 ob_x(who, 'disembarked')
584 return d('disembarked')
586 return d('not matched')
588 def _str_vessel(self, vn, v):
589 s = ' vessel %s\n' % vn
590 s += ' '*20 + "%-*s %13s\n" % (
591 max_pirate_namelen, '#lastaboard',
593 for pn in sorted(v.keys()):
594 if pn.startswith('#'): continue
597 assert self._pl[pn] == pa
598 s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
599 (' ','G')[pa.gunner],
600 max_pirate_namelen, pn,
601 pa.last_time, pa.last_event,
602 pa.last_chat_time, pa.last_chat_chan)
606 s = '''<ChatLogTracker
609 ''' % (self._myself.name, self._vessel)
610 assert ((self._v is None and self._vessel is None) or
611 (self._v is self._vl[self._vessel]))
612 if self._vessel is not None:
613 s += self._str_vessel(self._vessel, self._v)
614 for vn in sorted(self._vl.keys()):
615 if vn == self._vessel: continue
616 s += self._str_vessel(vn, self._vl[vn])
620 assert pa.v in self._vl.values()
624 def catchup(self, progress=None):
626 more = self._f.readline()
629 self._progress[0] += len(more)
630 if progress: progress.progress(*self._progress)
633 if self._lbuf.endswith('\n'):
634 self.chatline(self._lbuf.rstrip())
636 if progress: progress.caughtup()
639 rv = self._need_redisplay
640 self._need_redisplay = False
643 # returns our pirate name
644 return self._myself.name
646 # returns the vessel we're aboard or None
649 # returns a list of PirateAboard sorted by name
651 for pn in sorted(self._v.keys())
652 if not pn.startswith('#') ]
654 class ProgressPrintPercentage:
655 def __init__(self, f=sys.stdout): self._f = f
656 def progress(self,done,total):
657 self._f.write("scan chat logs %3d%%\r" % ((done*100) / total))
663 def prep_chat_log(args, bu,
664 progress=ProgressPrintPercentage(),
665 max_myself_age=3600):
666 if len(args) != 1: bu('this action takes only chat log filename')
668 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_chat-log-\\w+$'
669 match = regexp.match(logfn_re, logfn)
670 if not match: bu('chat log filename is not in default format')
671 (pirate, fetcher.ocean) = match.groups()
673 myself = PirateInfo(pirate,max_myself_age)
674 track = ChatLogTracker(myself, logfn)
677 track.catchup(progress)
680 return (myself, track)
682 def do_track_chat_log(args, bu):
683 (myself, track) = prep_chat_log(args, bu)
690 def do_ship_aid(args, bu):
691 if opts.ship_duty is None: opts.ship_duty = True
693 (myself, track) = prep_chat_log(args, bu)
700 sys.stdout.write("\n\n%s" % track.myname())
703 if vn is None: print " ...?"; return
705 print " on board the %s at %s\n" % (
706 vn, time.strftime("%Y-%m-%d %H:%M:%S"))
708 tbl = StandingsTable()
711 for pa in track.aboard():
712 pi = pa.pirate_info()
714 tbl.pirate_dummy(pa.name, rotate_nya[0])
720 rotate_nya = rotate_nya[1:2] + rotate_nya[0]
726 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
728 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
729 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
730 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
731 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
732 yoweb-scrape [--ocean OCEAN ...] ship-aid CHAT-LOG
735 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
736 help='select ocean OCEAN')
737 ao('--cache-dir', dest='cache_dir', metavar='DIR',
738 default='~/.yoweb-scrape-cache',
739 help='cache yoweb pages in DIR')
740 ao('-D','--debug', action='count', dest='debug', default=0,
741 help='enable debugging output')
742 ao('-q','--quiet', action='store_true', dest='quiet',
743 help='suppress warning output')
745 ao('--ship-duty', action='store_true', dest='ship_duty',
746 help='show ship duty station puzzles')
747 ao('--all-puzzles', action='store_false', dest='ship_duty',
748 help='show all puzzles, not just ship duty stations')
750 (opts,args) = pa.parse_args()
754 pa.error('need a mode argument')
757 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
758 try: mode_fn = globals()[mode_fn_name]
759 except KeyError: pa.error('unknown mode "%s"' % mode)
762 opts.min_max_age = 60
763 opts.expire_age = 3600
764 opts.ship_reboard_clearout = 3600
766 if opts.cache_dir.startswith('~/'):
767 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
769 fetcher = Fetcher(opts.ocean, opts.cache_dir)
771 mode_fn(args[1:], pa.error)