3 #---------- setup ----------
6 signal.signal(signal.SIGINT, signal.SIG_DFL)
17 from optparse import OptionParser
19 from BeautifulSoup import BeautifulSoup
23 #---------- YPP parameters and arrays ----------
25 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
26 '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
27 '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
28 '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
30 standingvals = ('Able/Distinguished/Respected/Master'+
31 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
33 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
35 max_pirate_namelen = 12
38 #---------- general utilities ----------
44 def format_time_interval(ti):
45 if ti < 120: return '%d:%02d' % (ti / 60, ti % 60)
46 if ti < 7200: return '%2dm' % (ti / 60)
47 if ti < 86400: return '%dh' % (ti / 3600)
48 return '%dd' % (ti / 86400)
50 #---------- caching and rate-limiting data fetcher ----------
53 def __init__(self, ocean, cachedir):
54 debug('Fetcher init %s' % cachedir)
56 self.cachedir = cachedir
57 try: os.mkdir(cachedir)
58 except (OSError,IOError), oe:
59 if oe.errno != errno.EEXIST: raise
60 self._cache_scan(time.time())
62 def default_ocean(self, ocean='ice'):
63 if self.ocean is None:
66 def _cache_scan(self, now):
67 # returns list of ages, unsorted
69 debug('Fetcher scan_cache')
70 for leaf in os.listdir(self.cachedir):
71 if not leaf.startswith('#'): continue
72 path = self.cachedir + '/' + leaf
73 try: s = os.stat(path)
74 except (OSError,IOError), oe:
75 if oe.errno != errno.ENOENT: raise
77 age = now - s.st_mtime
78 if age > opts.expire_age:
79 debug('Fetcher expire %d %s' % (age, path))
81 except (OSError,IOError), oe:
82 if oe.errno != errno.ENOENT: raise
87 def need_wait(self, now):
88 ages = self._cache_scan(now)
90 debug('Fetcher ages ' + `ages`)
94 if age < min_age and age < 300:
95 debug('Fetcher morewait min=%d age=%d' %
97 need_wait = max(need_wait, min_age - age)
102 def _rate_limit_cache_clean(self, now):
103 need_wait = self.need_wait(now)
105 debug('Fetcher wait %d' % need_wait)
106 time.sleep(need_wait)
108 def fetch(self, url, max_age):
109 debug('Fetcher fetch %s' % url)
110 cache_corename = urllib.quote_plus(url)
111 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
112 try: f = file(cache_item, 'r')
113 except (OSError,IOError), oe:
114 if oe.errno != errno.ENOENT: raise
117 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
119 s = os.fstat(f.fileno())
120 age = now - s.st_mtime
122 debug('Fetcher stale %d < %d'% (max_age, age))
127 debug('Fetcher cached %d > %d' % (max_age, age))
130 debug('Fetcher fetch')
131 self._rate_limit_cache_clean(now)
133 stream = urllib2.urlopen(url)
135 cache_tmp = "%s/#%s~%d#" % (
136 self.cachedir, cache_corename, os.getpid())
137 f = file(cache_tmp, 'w')
140 os.rename(cache_tmp, cache_item)
141 debug('Fetcher stored')
144 def yoweb(self, kind, tail, max_age):
146 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
147 self.ocean, kind, tail)
148 return self.fetch(url, max_age)
150 #---------- logging assistance for troubled screenscrapers ----------
157 def soupm(self, obj, m):
158 self.msg(m + '; in ' + `obj`)
159 def needs_msgs(self, child_souplog):
160 self.msgs += child_souplog.msgs
161 child_souplog.msgs = [ ]
164 str = ''.join(obj.findAll(text=True))
167 class SomethingSoupInfo(SoupLog):
168 def __init__(self, kind, tail, max_age):
169 SoupLog.__init__(self)
170 html = fetcher.yoweb(kind, tail, max_age)
171 self._soup = BeautifulSoup(html,
172 convertEntities=BeautifulSoup.HTML_ENTITIES
175 #---------- scraper for pirate pages ----------
177 class PirateInfo(SomethingSoupInfo):
178 # Public data members:
179 # pi.standings = { 'Treasure Haul': 'Able' ... }
181 # pi.crew = (id, name)
182 # pi.flag = (id, name)
183 # pi.msgs = [ 'message describing problem with scrape' ]
185 def __init__(self, pirate, max_age=300):
186 SomethingSoupInfo.__init__(self,
187 'pirate.wm?target=', pirate, max_age)
189 self._find_standings()
190 self.crew = self._find_crewflag('crew',
191 '^/yoweb/crew/info\\.wm')
192 self.flag = self._find_crewflag('flag',
193 '^/yoweb/flag/info\\.wm')
195 def _find_standings(self):
196 imgs = self._soup.findAll('img',
197 src=regexp.compile('/yoweb/images/stat.*'))
199 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
203 for skill in puzzles:
204 standings[skill] = [ ]
209 try: puzzle = img['alt']
210 except KeyError: continue
212 if not puzzle in puzzles:
213 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
215 key = img.findParent('td')
217 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
219 valelem = key.findNextSibling('td')
221 skl.soupm(key, 'puzzle missing sibling "%s"'
224 valstr = soup_text(valelem)
225 match = re.match(valstr)
227 skl.soupm(key, ('puzzle "%s" unparseable'+
228 ' standing "%s"') % (puzzle, valstr))
230 standing = match.group(match.lastindex)
231 standings[puzzle].append(standing)
235 for puzzle in puzzles:
236 sl = standings[puzzle]
238 skl.msg('puzzle "%s" multiple standings %s' %
242 skl.msg('puzzle "%s" no standing found' % puzzle)
245 for i in range(0, len(standingvals)-1):
246 if standing == standingvals[i]:
247 self.standings[puzzle] = i
248 if not puzzle in self.standings:
249 skl.msg('puzzle "%s" unknown standing "%s"' %
252 all_standings_ok = True
253 for puzzle in puzzles:
254 if not puzzle in self.standings:
257 def _find_crewflag(self, cf, yoweb_re):
258 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
260 self.msg('zero or several %s id references found' % cf)
263 id_re = '\\b%sid\\=(\\w+)$' % cf
264 id_haystack = thing['href']
265 match = regexp.compile(id_re).search(id_haystack)
267 self.soupm(thing, ('incomprehensible %s id ref'+
268 ' (%s in %s)') % (cf, id_re, id_haystack))
270 name = soup_text(thing)
271 return (match.group(1), name)
274 return `(self.crew, self.flag, self.standings, self.msgs)`
276 #---------- scraper for crew pages ----------
278 class CrewInfo(SomethingSoupInfo):
279 # Public data members:
280 # ci.crew = [ ('Captain', ['Pirate', ...]),
281 # ('Senior Officer', [...]),
283 # pi.msgs = [ 'message describing problem with scrape' ]
285 def __init__(self, crewid, max_age=300):
286 SomethingSoupInfo.__init__(self,
287 'crew/info.wm?crewid=', crewid, max_age)
290 def _find_crew(self):
292 capts = self._soup.findAll('img',
293 src='/yoweb/images/crew-captain.png')
295 self.msg('crew members: no. of captain images != 1')
298 while not tbl.find('a', href=pirate_ref_re):
299 tbl = tbl.findParent('table')
301 self.msg('crew members: cannot find table')
303 current_rank_crew = None
304 crew_rank_re = regexp.compile('/yoweb/images/crew')
305 for row in tbl.contents:
306 # findAll(recurse=False)
307 if isinstance(row,basestring):
310 is_rank = row.find('img', attrs={'src': crew_rank_re})
312 rank = soup_text(row)
313 current_rank_crew = []
314 self.crew.append((rank, current_rank_crew))
316 for cell in row.findAll('a', href=pirate_ref_re):
317 if current_rank_crew is None:
318 self.soupm(cell, 'crew members: crew'
321 current_rank_crew.append(soup_text(cell))
324 return `(self.crew, self.msgs)`
326 #---------- pretty-printer for tables of pirate puzzle standings ----------
328 class StandingsTable:
329 def __init__(self, use_puzzles=None, col_width=6):
330 if use_puzzles is None:
333 'Navigating','Battle Navigation',
335 ['Sailing','Rigging'],
342 self._puzzles = use_puzzles
344 self._cw = col_width-1
346 def _pline(self, pirate, puzstrs, extra):
347 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
349 self.s += ' %-*.*s' % (self._cw,self._cw, v)
351 self.s += ' ' + extra
354 def _puzstr(self, pi, puzzle):
355 if not isinstance(puzzle,list): puzzle = [puzzle]
356 try: standing = max([pi.standings[p] for p in puzzle])
357 except KeyError: return '?'
358 if not standing: return ''
361 c1 = standingvals[standing][0]
362 if standing < 3: c1 = c1.lower() # 3 = Master
366 s += '*' * (standing / 2)
367 s += '+' * (standing % 2)
371 def puzn_redact(name):
372 if isinstance(name,list):
374 ["%.*s" % (self._cw/2, puzn_redact(n))
377 if spc < 0: return name
378 return name[0:min(4,spc)] + name[spc+1:]
379 self._pline('', map(puzn_redact, self._puzzles), None)
380 def literalline(self, line):
381 self.s += line + '\n'
382 def pirate_dummy(self, name, standingstring, extra=None):
383 self._pline(name, standingstring * len(self._puzzles), extra)
384 def pirate(self, pi, extra=None):
385 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
386 self._pline(pi.name, puzstrs, extra)
391 #---------- chat log parser ----------
394 # This is essentially a transparent, dumb, data class.
404 def __init__(pa, pn, v, time, event):
408 pa.last_event = event
409 pa.last_chat_time = None
410 pa.last_chat_chan = None
415 if not pa.pi and not fetcher.need_wait(time.time()):
416 pa.pi = PirateInfo(pa.name, 3600)
419 class ChatLogTracker:
420 # This is quite complex so we make it opaque. Use the
421 # official invokers, accessors etc.
423 def __init__(self, myself_pi, logfn):
424 self._pl = {} # self._pl['Pirate'] =
425 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
426 # self._vl['Vessel']['#lastaboard']
427 self._v = None # self._v =
428 self._vessel = None # self._vl[self._vessel]
430 self._myself = myself_pi
431 self._need_redisplay = False
432 self._f = file(logfn)
434 self._progress = [0, os.fstat(self._f.fileno()).st_size]
436 def force_redisplay(self):
437 self._need_redisplay = True
439 def _onboard_event(self,timestamp,pirate,event):
440 try: pa = self._pl[pirate]
441 except KeyError: pa = None
442 if pa is not None and pa.v is self._v:
443 pa.last_time = timestamp
444 pa.last_event = event
446 if pa is not None: del pa.v[pirate]
447 pa = PirateAboard(pirate, self._v, timestamp, event)
448 self._pl[pirate] = pa
450 self._v['#lastaboard'] = timestamp
451 self.force_redisplay()
454 def _trash_vessel(self, v):
456 if pn.startswith('#'): continue
458 self.force_redisplay()
460 def expire_garbage(self, timestamp):
461 for (vn,v) in list(self._vl.iteritems()):
462 la = v['#lastaboard']
463 if timestamp - la > opts.ship_reboard_clearout:
464 self._debug_line_disposition(timestamp,'',
466 self._trash_vessel(v)
469 def clear_vessel(self, timestamp):
470 if self._v is not None:
471 self._trash_vessel(self._v)
472 self._v = {'#lastaboard': timestamp}
473 self._vl[self._vessel] = self._v
475 def _debug_line_disposition(self,timestamp,l,m):
476 debug('CLT %13s %-30s %s' % (timestamp,m,l))
478 def chatline(self,l):
479 rm = lambda re: regexp.match(re,l)
480 d = lambda m: self._debug_line_disposition(timestamp,l,m)
483 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
485 self._date = [int(x) for x in m.groups()]
486 self._previous_timestamp = None
487 return d('date '+`self._date`)
489 if self._date is None:
490 return d('date unset')
492 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
494 return d('no timestamp')
497 time_tuple = (self._date +
498 [int(x) for x in m.groups()] +
500 timestamp = time.mktime(time_tuple)
501 if timestamp >= self._previous_timestamp: break
503 self._debug_line_disposition(timestamp,'',
504 'new date '+`self._date`)
506 self._previous_timestamp = timestamp
508 l = l[l.find(' ')+1:]
511 return self._onboard_event(timestamp, who, event)
512 def ob1(did): ob_x(m.group(1), did); return d(did)
513 def oba(did): return ob1('%s %s' % (did, m.group(2)))
515 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
517 pn = self._myself.name
518 self._vessel = m.group(1)
521 try: self._v = self._vl[self._vessel]
522 except KeyError: self._v = None; dm += ' new'
524 if self._v is not None: la = self._v['#lastaboard']
525 else: la = 0; dm += ' ?la'
527 if timestamp - la > opts.ship_reboard_clearout:
528 self.clear_vessel(timestamp)
531 ob_x(pn, 'we boarded')
532 self.expire_garbage(timestamp)
536 return d('no vessel')
538 m = rm('(\\w+) has come aboard\\.$')
539 if m: return ob1('boarded');
541 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
543 (who,what) = m.groups()
544 pa = ob_x(who,'ord '+what)
545 if what == 'Gunning':
547 return d('duty order')
549 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
550 if m: oba('stopped'); return d("end")
554 try: pa = self._pl[who]
555 except KeyError: return d('chat mystery')
557 pa.last_chat_time = timestamp
558 pa.last_chat_chan = what
559 self.force_redisplay()
560 return d(what+' chat')
562 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
563 if m: return ob1('general order');
565 m = rm('(\\w+) says, "')
566 if m: return chat('public')
568 m = rm('(\\w+) tells ye, "')
569 if m: return chat('private')
571 m = rm('(\\w+) flag officer chats, "')
572 if m: return chat('flag officer')
574 m = rm('(\\w+) officer chats, "')
575 if m: return chat('officer')
577 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
579 pl = m.group(1).split(', ')
580 if not self._myself.name in pl:
581 return d('lost boarding battle')
583 if ' ' in pn: continue
584 ob_x(pn,'won boarding battle')
585 return d('won boarding battle')
587 m = rm('(\\w+) is eliminated\\!')
588 if m: return ob1('eliminated in fray');
590 m = rm('(\\w+) has left the vessel\.')
593 ob_x(who, 'disembarked')
596 return d('disembarked')
598 return d('not matched')
600 def _str_vessel(self, vn, v):
601 s = ' vessel %s\n' % vn
602 s += ' '*20 + "%-*s %13s\n" % (
603 max_pirate_namelen, '#lastaboard',
605 for pn in sorted(v.keys()):
606 if pn.startswith('#'): continue
609 assert self._pl[pn] == pa
610 s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
611 (' ','G')[pa.gunner],
612 max_pirate_namelen, pn,
613 pa.last_time, pa.last_event,
614 pa.last_chat_time, pa.last_chat_chan)
618 s = '''<ChatLogTracker
621 ''' % (self._myself.name, self._vessel)
622 assert ((self._v is None and self._vessel is None) or
623 (self._v is self._vl[self._vessel]))
624 if self._vessel is not None:
625 s += self._str_vessel(self._vessel, self._v)
626 for vn in sorted(self._vl.keys()):
627 if vn == self._vessel: continue
628 s += self._str_vessel(vn, self._vl[vn])
632 assert pa.v in self._vl.values()
636 def catchup(self, progress=None):
638 more = self._f.readline()
641 self._progress[0] += len(more)
642 if progress: progress.progress(*self._progress)
645 if self._lbuf.endswith('\n'):
646 self.chatline(self._lbuf.rstrip())
648 if progress: progress.caughtup()
651 rv = self._need_redisplay
652 self._need_redisplay = False
655 # returns our pirate name
656 return self._myself.name
658 # returns the vessel we're aboard or None
661 # returns a list of PirateAboard sorted by name
662 if self._v is None: return []
664 for pn in sorted(self._v.keys())
665 if not pn.startswith('#') ]
667 #---------- implementations of actual operation modes ----------
669 def do_pirate(pirates, bu):
671 for pirate in pirates:
672 info = PirateInfo(pirate)
673 print '%s: %s,' % (`pirate`, info)
676 def prep_crew_of(args, bu, max_age=300):
677 if len(args) != 1: bu('crew-of takes one pirate name')
678 pi = PirateInfo(args[0], max_age)
679 if pi.crew is None: return None
680 return CrewInfo(pi.crew[0], max_age)
682 def do_crew_of(args, bu):
683 ci = prep_crew_of(args, bu)
686 def do_standings_crew_of(args, bu):
687 ci = prep_crew_of(args, bu, 60)
688 tab = StandingsTable()
690 for (rank, members) in ci.crew:
691 if not members: continue
692 tab.literalline('%s:' % rank)
694 pi = PirateInfo(p, random.randint(900,1800))
698 class ProgressPrintPercentage:
699 def __init__(self, f=sys.stdout):
701 def progress_string(self,done,total):
702 return "scan chat logs %3d%%\r" % ((done*100) / total)
703 def progress(self,*a):
704 self._f.write(self.progress_string(*a))
706 def show_init(self, pirate, ocean):
707 print >>self._f, 'Starting up, %s on the %s ocean' % (
713 #----- modes which use the chat log parser are quite complex -----
715 def prep_chat_log(args, bu,
716 progress=ProgressPrintPercentage(),
717 max_myself_age=3600):
718 if len(args) != 1: bu('this action takes only chat log filename')
720 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
721 match = regexp.match(logfn_re, logfn)
722 if not match: bu('chat log filename is not in expected format')
723 (pirate, ocean) = match.groups()
724 fetcher.default_ocean(ocean)
726 myself = PirateInfo(pirate,max_myself_age)
727 progress.show_init(pirate, fetcher.ocean)
728 track = ChatLogTracker(myself, logfn)
731 track.catchup(progress)
734 track.force_redisplay()
736 return (myself, track)
738 def do_track_chat_log(args, bu):
739 (myself, track) = prep_chat_log(args, bu)
746 #----- ship management aid -----
748 class Display_dumb(ProgressPrintPercentage):
750 ProgressPrintPercentage.__init__(self)
756 class Display_overwrite(ProgressPrintPercentage):
758 ProgressPrintPercentage.__init__(self)
760 null = file('/dev/null','w')
761 curses.setupterm(fd=null.fileno())
763 self._clear = curses.tigetstr('clear')
765 self._debug('missing clear!')
766 self.show = Display_dumb.show
769 self._t = {'el':'', 'ed':''}
770 if not self._init_sophisticated():
771 for k in self._t.keys(): self._t[k] = ''
772 self._t['ho'] = self._clear
774 def _debug(self,m): debug('display overwrite: '+m)
776 def _init_sophisticated(self):
777 for k in self._t.keys():
778 s = curses.tigetstr(k)
780 self._t['ho'] = curses.tigetstr('ho')
781 if not self._t['ho']:
782 cup = curses.tigetstr('cup')
783 self._t['ho'] = curses.tparm(cup,0,0)
784 missing = [k for k in self._t.keys() if not self._t[k]]
786 self.debug('missing '+(' '.join(missing)))
792 def wti(k): w(self._t[k])
796 for l in s.rstrip().split('\n'):
806 sys.stdout.write(self._clear)
810 def do_ship_aid(args, bu):
811 if opts.ship_duty is None: opts.ship_duty = True
813 displayer = globals()['Display_'+opts.display]()
816 (myself, track) = prep_chat_log(args, bu, progress=displayer)
819 if t is None: return ' ' * 22
820 return " %-4s %-16s" % (format_time_interval(now - t),e)
822 displayer.realstart()
828 s = "%s" % track.myname()
831 if vn is None: s += " not on a vessel?!"
832 else: s += " on board the %s" % vn
833 s += " at %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")
835 tbl = StandingsTable()
838 for pa in track.aboard():
839 pi = pa.pirate_info()
842 if pa.gunner: xs += 'G '
844 xs += timeevent(pa.last_time, pa.last_event)
845 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
848 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
856 rotate_nya = rotate_nya[1:2] + rotate_nya[0]
858 #---------- main program ----------
864 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
866 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
867 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
868 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
869 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
870 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
872 display modes (for --display) apply to ship-aid:
873 --display=dumb just print new information, scrolling the screen
874 --display=overwrite use cursor motion, selective clear, etc. to redraw at top
877 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
878 help='select ocean OCEAN')
879 ao('--cache-dir', dest='cache_dir', metavar='DIR',
880 default='~/.yoweb-scrape-cache',
881 help='cache yoweb pages in DIR')
882 ao('-D','--debug', action='count', dest='debug', default=0,
883 help='enable debugging output')
884 ao('--debug-fd', action='count', dest='debug_fd',
885 help='write any debugging output to specified fd')
886 ao('-q','--quiet', action='store_true', dest='quiet',
887 help='suppress warning output')
888 ao('--display', action='store', dest='display',
889 type='choice', choices=['dumb','overwrite'],
890 help='how to display ship aid')
892 ao('--ship-duty', action='store_true', dest='ship_duty',
893 help='show ship duty station puzzles')
894 ao('--all-puzzles', action='store_false', dest='ship_duty',
895 help='show all puzzles, not just ship duty stations')
897 (opts,args) = pa.parse_args()
901 pa.error('need a mode argument')
903 if opts.debug_fd is not None:
904 opts.debug_file = fdopen(opts.debug_fd, 'w')
907 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
908 try: mode_fn = globals()[mode_fn_name]
909 except KeyError: pa.error('unknown mode "%s"' % mode)
912 opts.min_max_age = 60
913 opts.expire_age = 3600
914 opts.ship_reboard_clearout = 3600
916 if opts.cache_dir.startswith('~/'):
917 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
919 if opts.display is None:
920 if ((opts.debug > 0 and opts.debug_fd is None)
921 or not os.isatty(sys.stdout.fileno())):
922 opts.display = 'dumb'
924 opts.display = 'overwrite'
926 fetcher = Fetcher(opts.ocean, opts.cache_dir)
928 mode_fn(args[1:], pa.error)