2 # This is part of ypp-sc-tools, a set of third-party tools for assisting
3 # players of Yohoho Puzzle Pirates.
5 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
21 # are used without permission. This program is not endorsed or
22 # sponsored by Three Rings.
25 yoweb-scrape is part of ypp-sc-tools Copyright (C) 2009 Ian Jackson
26 This program comes with ABSOLUTELY NO WARRANTY; this is free software,
27 and you are welcome to redistribute it under certain conditions.
28 For details, read the top of the yoweb-scrape file.
31 #---------- setup ----------
34 signal.signal(signal.SIGINT, signal.SIG_DFL)
47 from optparse import OptionParser
48 from StringIO import StringIO
50 from BeautifulSoup import BeautifulSoup
54 #---------- YPP parameters and arrays ----------
56 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
57 '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
58 '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
59 '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
63 ['Sailing','Rigging'],
68 duty_puzzles = ([ 'Navigating', 'Battle Navigation' ] +
72 standingvals = ('Able/Proficient/Distinguished/Respected/Master'+
73 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
74 standing_limit = len(standingvals)
76 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
78 max_pirate_namelen = 12
81 #---------- general utilities ----------
85 print >>opts.debug_file, m
89 opts.debug_file.flush()
95 def format_time_interval(ti):
96 if ti < 120: return '%d:%02d' % (ti / 60, ti % 60)
97 if ti < 7200: return '%2dm' % (ti / 60)
98 if ti < 86400: return '%dh' % (ti / 3600)
99 return '%dd' % (ti / 86400)
101 #---------- caching and rate-limiting data fetcher ----------
104 def __init__(self, ocean, cachedir):
105 debug('Fetcher init %s' % cachedir)
107 self.cachedir = cachedir
108 try: os.mkdir(cachedir)
109 except (OSError,IOError), oe:
110 if oe.errno != errno.EEXIST: raise
111 self._cache_scan(time.time())
113 def default_ocean(self, ocean='ice'):
114 if self.ocean is None:
117 def _cache_scan(self, now):
118 # returns list of ages, unsorted
120 debug('Fetcher scan_cache')
121 for leaf in os.listdir(self.cachedir):
122 if not leaf.startswith('#'): continue
123 path = self.cachedir + '/' + leaf
124 try: s = os.stat(path)
125 except (OSError,IOError), oe:
126 if oe.errno != errno.ENOENT: raise
128 age = now - s.st_mtime
129 if age > opts.expire_age:
130 debug('Fetcher expire %d %s' % (age, path))
132 except (OSError,IOError), oe:
133 if oe.errno != errno.ENOENT: raise
138 def need_wait(self, now, imaginary=[]):
139 ages = self._cache_scan(now)
142 debug('Fetcher ages ' + `ages`)
146 if age < min_age and age <= 5:
147 debug('Fetcher morewait min=%d age=%d' %
149 need_wait = max(need_wait, min_age - age)
154 def _rate_limit_cache_clean(self, now):
155 need_wait = self.need_wait(now)
157 debug('Fetcher wait %d' % need_wait)
160 def fetch(self, url, max_age):
161 debug('Fetcher fetch %s' % url)
162 cache_corename = urllib.quote_plus(url)
163 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
164 try: f = file(cache_item, 'r')
165 except (OSError,IOError), oe:
166 if oe.errno != errno.ENOENT: raise
169 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
171 s = os.fstat(f.fileno())
172 age = now - s.st_mtime
174 debug('Fetcher stale %d < %d'% (max_age, age))
179 debug('Fetcher cached %d > %d' % (max_age, age))
182 debug('Fetcher fetch')
183 self._rate_limit_cache_clean(now)
185 stream = urllib2.urlopen(url)
187 cache_tmp = "%s/#%s~%d#" % (
188 self.cachedir, cache_corename, os.getpid())
189 f = file(cache_tmp, 'w')
192 os.rename(cache_tmp, cache_item)
193 debug('Fetcher stored')
196 def yoweb(self, kind, tail, max_age):
198 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
199 self.ocean, kind, tail)
200 return self.fetch(url, max_age)
202 #---------- logging assistance for troubled screenscrapers ----------
209 def soupm(self, obj, m):
210 self.msg(m + '; in ' + `obj`)
211 def needs_msgs(self, child_souplog):
212 self.msgs += child_souplog.msgs
213 child_souplog.msgs = [ ]
216 str = ''.join(obj.findAll(text=True))
219 class SomethingSoupInfo(SoupLog):
220 def __init__(self, kind, tail, max_age):
221 SoupLog.__init__(self)
222 html = fetcher.yoweb(kind, tail, max_age)
223 self._soup = BeautifulSoup(html,
224 convertEntities=BeautifulSoup.HTML_ENTITIES
227 #---------- scraper for pirate pages ----------
229 class PirateInfo(SomethingSoupInfo):
230 # Public data members:
231 # pi.standings = { 'Treasure Haul': 'Able' ... }
233 # pi.crew = (id, name)
234 # pi.flag = (id, name)
235 # pi.msgs = [ 'message describing problem with scrape' ]
237 def __init__(self, pirate, max_age=300):
238 SomethingSoupInfo.__init__(self,
239 'pirate.wm?target=', pirate, max_age)
241 self._find_standings()
242 self.crew = self._find_crewflag('crew',
243 '^/yoweb/crew/info\\.wm')
244 self.flag = self._find_crewflag('flag',
245 '^/yoweb/flag/info\\.wm')
247 def _find_standings(self):
248 imgs = self._soup.findAll('img',
249 src=regexp.compile('/yoweb/images/stat.*'))
251 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
255 for skill in puzzles:
256 standings[skill] = [ ]
261 try: puzzle = img['alt']
262 except KeyError: continue
264 if not puzzle in puzzles:
265 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
267 key = img.findParent('td')
269 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
271 valelem = key.findNextSibling('td')
273 skl.soupm(key, 'puzzle missing sibling "%s"'
276 valstr = soup_text(valelem)
277 match = re.match(valstr)
279 skl.soupm(key, ('puzzle "%s" unparseable'+
280 ' standing "%s"') % (puzzle, valstr))
282 standing = match.group(match.lastindex)
283 standings[puzzle].append(standing)
287 for puzzle in puzzles:
288 sl = standings[puzzle]
290 skl.msg('puzzle "%s" multiple standings %s' %
294 skl.msg('puzzle "%s" no standing found' % puzzle)
297 for i in range(0, standing_limit):
298 if standing == standingvals[i]:
299 self.standings[puzzle] = i
300 if not puzzle in self.standings:
301 skl.msg('puzzle "%s" unknown standing "%s"' %
304 all_standings_ok = True
305 for puzzle in puzzles:
306 if not puzzle in self.standings:
309 def _find_crewflag(self, cf, yoweb_re):
310 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
312 self.msg('zero or several %s id references found' % cf)
315 id_re = '\\b%sid\\=(\\w+)$' % cf
316 id_haystack = thing['href']
317 match = regexp.compile(id_re).search(id_haystack)
319 self.soupm(thing, ('incomprehensible %s id ref'+
320 ' (%s in %s)') % (cf, id_re, id_haystack))
322 name = soup_text(thing)
323 return (match.group(1), name)
326 return `(self.crew, self.flag, self.standings, self.msgs)`
328 #---------- scraper for crew pages ----------
330 class CrewInfo(SomethingSoupInfo):
331 # Public data members:
332 # ci.crew = [ ('Captain', ['Pirate', ...]),
333 # ('Senior Officer', [...]),
335 # pi.msgs = [ 'message describing problem with scrape' ]
337 def __init__(self, crewid, max_age=300):
338 SomethingSoupInfo.__init__(self,
339 'crew/info.wm?crewid=', crewid, max_age)
342 def _find_crew(self):
344 capts = self._soup.findAll('img',
345 src='/yoweb/images/crew-captain.png')
347 self.msg('crew members: no. of captain images != 1')
350 while not tbl.find('a', href=pirate_ref_re):
351 tbl = tbl.findParent('table')
353 self.msg('crew members: cannot find table')
355 current_rank_crew = None
356 crew_rank_re = regexp.compile('/yoweb/images/crew')
357 for row in tbl.contents:
358 # findAll(recurse=False)
359 if isinstance(row,basestring):
362 is_rank = row.find('img', attrs={'src': crew_rank_re})
364 rank = soup_text(row)
365 current_rank_crew = []
366 self.crew.append((rank, current_rank_crew))
368 for cell in row.findAll('a', href=pirate_ref_re):
369 if current_rank_crew is None:
370 self.soupm(cell, 'crew members: crew'
373 current_rank_crew.append(soup_text(cell))
376 return `(self.crew, self.msgs)`
378 #---------- pretty-printer for tables of pirate puzzle standings ----------
380 class StandingsTable:
381 def __init__(self, f, use_puzzles=None, col_width=6, gap_every=5):
382 if use_puzzles is None:
384 use_puzzles=duty_puzzles
387 self._puzzles = use_puzzles
389 self._cw = col_width-1
390 self._gap_every = gap_every
394 def _nl(self): self._o('\n')
396 def _pline(self, pirate, puzstrs, extra):
397 if (self._linecount > 0
398 and self._gap_every is not None
399 and not (self._linecount % self._gap_every)):
401 self._o(' %-*s' % (max(max_pirate_namelen, 14), pirate))
403 self._o(' %-*.*s' % (self._cw,self._cw, v))
409 def _puzstr(self, pi, puzzle):
410 if not isinstance(puzzle,list): puzzle = [puzzle]
411 try: standing = max([pi.standings[p] for p in puzzle])
412 except KeyError: return '?'
413 if not standing: return ''
416 c1 = standingvals[standing][0]
417 if standing < 3: c1 = c1.lower() # 3 = Master
421 s += '*' * (standing / 2)
422 s += '+' * (standing % 2)
425 def headings(self, lhs='', rhs=None):
426 def puzn_redact(name):
427 if isinstance(name,list):
429 ["%.*s" % (self._cw/2, puzn_redact(n))
432 if spc < 0: return name
433 return name[0:min(4,spc)] + name[spc+1:]
435 self._pline(lhs, map(puzn_redact, self._puzzles), rhs)
437 def literalline(self, line):
441 def pirate_dummy(self, name, standingstring, extra=None):
442 self._pline(name, standingstring * len(self._puzzles), extra)
443 def pirate(self, pi, extra=None):
444 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
445 self._pline(pi.name, puzstrs, extra)
448 #---------- chat log parser ----------
451 # This is essentially a transparent, dumb, data class.
461 def __init__(pa, pn, v, time, event):
465 pa.last_event = event
466 pa.last_chat_time = None
467 pa.last_chat_chan = None
474 age = now - pa.pi_fetched
475 guide = random.randint(120,240)
478 debug('PirateAboard refresh %d > %d %s' % (
479 age, guide, pa.name))
483 wait = fetcher.need_wait(now, imaginary)
485 debug('PirateAboard fetcher not ready %d' % wait)
487 pa.pi = PirateInfo(pa.name, 600)
491 class ChatLogTracker:
492 # This is quite complex so we make it opaque. Use the
493 # official invokers, accessors etc.
495 def __init__(self, myself_pi, logfn):
496 self._pl = {} # self._pl['Pirate'] =
497 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
498 # self._vl['Vessel']['#lastinfo']
499 # self._vl['Vessel']['#name']
500 # self._v = self._vl[self._vessel]
502 self._myself = myself_pi
503 self._f = file(logfn)
505 self._progress = [0, os.fstat(self._f.fileno()).st_size]
506 self._disembark_myself()
507 self._need_redisplay = False
508 self._lastvessel = None
510 def _disembark_myself(self):
513 self.force_redisplay()
515 def force_redisplay(self):
516 self._need_redisplay = True
518 def _vessel_updated(self, v, timestamp):
519 v['#lastinfo'] = timestamp
520 self.force_redisplay()
522 def _onboard_event(self,v,timestamp,pirate,event):
523 pa = self._pl.get(pirate, None)
524 if pa is not None and pa.v is v:
525 pa.last_time = timestamp
526 pa.last_event = event
528 if pa is not None: del pa.v[pirate]
529 pa = PirateAboard(pirate, v, timestamp, event)
530 self._pl[pirate] = pa
532 self._vessel_updated(v, timestamp)
535 def _trash_vessel(self, v):
537 if pn.startswith('#'): continue
541 if v is self._v: self._disembark_myself()
542 self.force_redisplay()
544 def _vessel_stale(self, v, timestamp):
545 return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
547 def _vessel_check_expire(self, v, timestamp):
548 if not self._vessel_stale(v, timestamp):
550 self._debug_line_disposition(timestamp,'',
551 'stale-reset ' + v['#name'])
552 self._trash_vessel(v)
555 def expire_garbage(self, timestamp):
556 for v in self._vl.values():
557 self._vessel_check_expire(v, timestamp)
559 def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
560 v = self._vl.get(vn, None)
562 v = self._vessel_check_expire(v, timestamp)
569 self._vl[vn] = v = { '#name': vn }
570 self._vessel_updated(v, timestamp)
573 def _find_matching_vessel(self, pattern, timestamp, cmdr,
574 dml=[], create=False):
575 # use when a commander pirate `cmdr' specified a vessel
576 # by name `pattern' (either may be None)
577 # if create is true, will create the vessel
578 # record if an exact name is specified
580 if (pattern is not None and
582 and len(pattern.split(' ')) == 2):
585 return self._vessel_lookup(
586 vn, timestamp, dml=dml, create=create)
589 pattern_check = lambda vn: True
591 re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
592 pattern_check = regexp.compile(re, regexp.I).match
596 cmdr_pa = self._pl.get(cmdr, None)
597 if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
599 tries.append((self._v, 'here'))
602 for (v, dm) in tries:
603 if v is None: dml.append(dm+'?'); continue
606 if not pattern_check(vn):
614 if pattern is not None and '*' in pattern:
617 for (vn,v) in self._vl.iteritems()
618 if not self._vessel_stale(v, timestamp)
621 #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
623 # '/'.join(tried_vns),
624 # '/'.join([vn for (vn,v) in search])))
634 def _debug_line_disposition(self,timestamp,l,m):
635 debug('CLT %13s %-40s %s' % (timestamp,m,l))
637 def chatline(self,l):
638 rm = lambda re: regexp.match(re,l)
639 d = lambda m: self._debug_line_disposition(timestamp,l,m)
642 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
644 self._date = [int(x) for x in m.groups()]
645 self._previous_timestamp = None
646 return d('date '+`self._date`)
648 if self._date is None:
649 return d('date unset')
651 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
653 return d('no timestamp')
656 time_tuple = (self._date +
657 [int(x) for x in m.groups()] +
659 timestamp = time.mktime(time_tuple)
660 if timestamp >= self._previous_timestamp: break
662 self._debug_line_disposition(timestamp,'',
663 'new date '+`self._date`)
665 self._previous_timestamp = timestamp
667 l = l[l.find(' ')+1:]
669 def ob_x(pirate,event):
670 return self._onboard_event(
671 self._v, timestamp, pirate, event)
672 def ob1(did): ob_x(m.group(1), did); return d(did)
673 def oba(did): return ob1('%s %s' % (did, m.group(2)))
675 def disembark(v, timestamp, pirate, event):
677 v, timestamp, pirate, 'leaving '+event)
681 def disembark_me(why):
682 self._disembark_myself()
683 return d('disembark-me '+why)
685 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
688 pn = self._myself.name
690 v = self._vessel_lookup(vn, timestamp, dm, create=True)
691 self._lastvessel = self._vessel = vn
693 ob_x(pn, 'we boarded')
694 self.expire_garbage(timestamp)
695 return d(' '.join(dm))
698 return d('no vessel')
700 m = rm('(\\w+) has come aboard\\.$')
701 if m: return ob1('boarded');
703 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
705 (who,what) = m.groups()
706 pa = ob_x(who,'ord '+what)
707 if what == 'Gunning':
709 return d('duty order')
711 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
712 if m: oba('stopped'); return d("end")
714 def chat_core(speaker, chan):
715 try: pa = self._pl[speaker]
716 except KeyError: return 'mystery'
717 if pa.v is not self._v: return 'elsewhere'
718 pa.last_chat_time = timestamp
719 pa.last_chat_chan = chan
720 self.force_redisplay()
725 dm = chat_core(speaker, chan)
726 return d('chat %s %s' % (chan, dm))
728 def chat_metacmd(chan):
729 (cmdr, metacmd) = m.groups()
730 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
732 '/([ad]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
734 if not m2: return chat(chan)
736 (cmd, pattern, targets) = m2.groups()
737 dml = ['cmd', chan, cmd]
739 if cmd == 'a': each = self._onboard_event
740 else: each = disembark
742 if cmdr == self._myself.name:
744 how = 'cmd: %s' % cmd
747 how = 'cmd: %s %s' % (cmd,cmdr)
749 v = self._find_matching_vessel(
750 pattern, timestamp, cmdr, dml, create=True)
753 targets = targets.strip().split(' ')
754 dml.append(`len(targets)`)
755 for target in targets:
756 each(v, timestamp, target.title(), how)
757 self._vessel_updated(v, timestamp)
760 chat_core(cmdr, 'cmd '+chan)
763 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
764 if m: return ob1('general order');
766 m = rm('(\\w+) says, "')
767 if m: return chat('public')
769 m = rm('(\\w+) tells ye, "')
770 if m: return chat('private')
772 m = rm('Ye told (\\w+), "(.*)"$')
773 if m: return chat_metacmd('private')
775 m = rm('(\\w+) flag officer chats, "')
776 if m: return chat('flag officer')
778 m = rm('(\\w+) officer chats, "(.*)"$')
779 if m: return chat_metacmd('officer')
781 m = rm('Ye accepted the offer to job with ')
782 if m: return disembark_me('jobbing')
784 m = rm('Ye hop on the ferry and are whisked away ')
785 if m: return disembark_me('ferry')
787 m = rm('Whisking away to yer home on the magical winds')
788 if m: return disembark_me('home')
790 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
792 pl = m.group(1).split(', ')
793 if not self._myself.name in pl:
794 return d('lost melee')
796 if ' ' in pn: continue
798 return d('won melee')
800 m = rm('(\\w+) is eliminated\\!')
801 if m: return ob1('eliminated in fray');
803 m = rm('(\\w+) has driven \w+ from the ship\\!')
804 if m: return ob1('boarder repelled');
806 m = rm('\w+ has bested (\\w+), and turns'+
807 ' to the rest of the ship\\.')
808 if m: return ob1('boarder unrepelled');
810 m = rm('(\\w+) has left the vessel\.')
813 disembark(self._v, timestamp, pirate, 'disembarked')
814 return d('disembarked')
816 return d('not-matched')
818 def _str_vessel(self, vn, v):
819 s = ' vessel %s\n' % vn
820 s += ' '*20 + "%-*s %13s\n" % (
821 max_pirate_namelen, '#lastinfo',
823 assert v['#name'] == vn
824 for pn in sorted(v.keys()):
825 if pn.startswith('#'): continue
828 assert self._pl[pn] == pa
829 s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
830 (' ','G')[pa.gunner],
831 max_pirate_namelen, pn,
832 pa.last_time, pa.last_event,
833 pa.last_chat_time, pa.last_chat_chan)
837 s = '''<ChatLogTracker
840 ''' % (self._myself.name, self._vessel)
841 assert ((self._v is None and self._vessel is None) or
842 (self._v is self._vl[self._vessel]))
843 if self._vessel is not None:
844 s += self._str_vessel(self._vessel, self._v)
845 for vn in sorted(self._vl.keys()):
846 if vn == self._vessel: continue
847 s += self._str_vessel(vn, self._vl[vn])
851 assert pa.v in self._vl.values()
855 def catchup(self, progress=None):
857 more = self._f.readline()
860 self._progress[0] += len(more)
861 if progress: progress.progress(*self._progress)
864 if self._lbuf.endswith('\n'):
865 self.chatline(self._lbuf.rstrip())
868 debug(self.__str__())
869 if progress: progress.caughtup()
872 rv = self._need_redisplay
873 self._need_redisplay = False
876 # returns our pirate name
877 return self._myself.name
878 def vesselname(self):
879 # returns the vessel name we're aboard or None
881 def lastvesselname(self):
882 # returns the last vessel name we were aboard or None
883 return self._lastvessel
884 def aboard(self, vesselname=True):
885 # returns a list of PirateAboard the vessel
886 # sorted by pirate name
887 # you can pass this None and you'll get []
888 # or True for the current vessel (which is the default)
889 # the returned value is a fresh list of persistent
890 # PirateAboard objects
891 if vesselname is True: v = self._v
892 else: v = self._vl.get(vesselname.title())
893 if v is None: return []
895 for pn in sorted(v.keys())
896 if not pn.startswith('#') ]
898 #---------- implementations of actual operation modes ----------
900 def do_pirate(pirates, bu):
902 for pirate in pirates:
903 info = PirateInfo(pirate)
904 print '%s: %s,' % (`pirate`, info)
907 def prep_crew_of(args, bu, max_age=300):
908 if len(args) != 1: bu('crew-of takes one pirate name')
909 pi = PirateInfo(args[0], max_age)
910 if pi.crew is None: return None
911 return CrewInfo(pi.crew[0], max_age)
913 def do_crew_of(args, bu):
914 ci = prep_crew_of(args, bu)
917 def do_standings_crew_of(args, bu):
918 ci = prep_crew_of(args, bu, 60)
919 tab = StandingsTable(sys.stdout)
921 for (rank, members) in ci.crew:
922 if not members: continue
924 tab.literalline('%s:' % rank)
926 pi = PirateInfo(p, random.randint(900,1800))
929 class ProgressPrintPercentage:
930 def __init__(self, f=sys.stdout):
932 def progress_string(self,done,total):
933 return "scan chat logs %3d%%\r" % ((done*100) / total)
934 def progress(self,*a):
935 self._f.write(self.progress_string(*a))
937 def show_init(self, pirate, ocean):
938 print >>self._f, 'Starting up, %s on the %s ocean' % (
944 #----- modes which use the chat log parser are quite complex -----
946 def prep_chat_log(args, bu,
947 progress=ProgressPrintPercentage(),
948 max_myself_age=3600):
949 if len(args) != 1: bu('this action takes only chat log filename')
951 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
952 match = regexp.match(logfn_re, logfn)
953 if not match: bu('chat log filename is not in expected format')
954 (pirate, ocean) = match.groups()
955 fetcher.default_ocean(ocean)
957 progress.show_init(pirate, fetcher.ocean)
958 myself = PirateInfo(pirate,max_myself_age)
959 track = ChatLogTracker(myself, logfn)
962 track.catchup(progress)
965 track.force_redisplay()
967 return (myself, track)
969 def do_track_chat_log(args, bu):
970 (myself, track) = prep_chat_log(args, bu)
977 #----- ship management aid -----
979 class Display_dumb(ProgressPrintPercentage):
981 ProgressPrintPercentage.__init__(self)
987 class Display_overwrite(ProgressPrintPercentage):
989 ProgressPrintPercentage.__init__(self)
991 null = file('/dev/null','w')
992 curses.setupterm(fd=null.fileno())
994 self._clear = curses.tigetstr('clear')
996 self._debug('missing clear!')
997 self.show = Display_dumb.show
1000 self._t = {'el':'', 'ed':''}
1001 if not self._init_sophisticated():
1002 for k in self._t.keys(): self._t[k] = ''
1003 self._t['ho'] = self._clear
1005 def _debug(self,m): debug('display overwrite: '+m)
1007 def _init_sophisticated(self):
1008 for k in self._t.keys():
1009 s = curses.tigetstr(k)
1011 self._t['ho'] = curses.tigetstr('ho')
1012 if not self._t['ho']:
1013 cup = curses.tigetstr('cup')
1014 self._t['ho'] = curses.tparm(cup,0,0)
1015 missing = [k for k in self._t.keys() if not self._t[k]]
1017 self.debug('missing '+(' '.join(missing)))
1022 w = sys.stdout.write
1023 def wti(k): w(self._t[k])
1027 for l in s.rstrip().split('\n'):
1036 def realstart(self):
1037 sys.stdout.write(self._clear)
1041 def do_ship_aid(args, bu):
1042 if opts.ship_duty is None: opts.ship_duty = True
1044 displayer = globals()['Display_'+opts.display]()
1046 (myself, track) = prep_chat_log(args, bu, progress=displayer)
1048 displayer.realstart()
1050 if os.isatty(0): kr_create = KeystrokeReader
1051 else: kr_create = DummyKeystrokeReader
1054 kreader = kr_create(0, 10)
1055 ship_aid_core(myself, track, displayer, kreader)
1060 class KeyBasedSorter:
1061 def compar_key_pa(self, pa):
1062 pi = pa.pirate_info()
1063 if pi is None: return None
1064 return self.compar_key(pi)
1065 def lsort_pa(self, l):
1066 l.sort(key = self.compar_key_pa)
1068 class NameSorter(KeyBasedSorter):
1069 def compar_key(self, pi): return pi.name
1070 def desc(self): return 'name'
1072 class SkillSorter(NameSorter):
1073 def __init__(self, relevant):
1074 self._want = frozenset(relevant.split('/'))
1076 for p in core_duty_puzzles:
1077 if isinstance(p,basestring): self._avoid.add(p)
1078 else: self._avoid |= set(p)
1079 self._avoid -= self._want
1080 self._desc = '%s' % relevant
1082 def desc(self): return self._desc
1084 def compar_key(self, pi):
1086 pi.standings.get(puz,-1)
1087 for puz in self._want
1090 -pi.standings.get(puz,standing_limit)
1091 for puz in self._avoid
1094 def negate(x): return -x
1095 debug('compar_key %s bw=%s ba=%s' % (pi.name, `best_want`,
1097 return (-best_want, map(negate, best_avoid), pi.name)
1099 def ship_aid_core(myself, track, displayer, kreader):
1102 vn = track.vesselname()
1103 if vn: return (vn, " on board the %s" % vn)
1104 vn = track.lastvesselname()
1105 if vn: return (vn, " ashore from the %s" % vn)
1106 return (None, " not on a vessel")
1109 if t is None: return ' ' * 22
1110 return " %-4s %-16s" % (format_time_interval(now - t),e)
1112 displayer.show(track.myname() + find_vessel()[1] + '...')
1122 (vn, s) = find_vessel()
1123 s = track.myname() + s
1124 s += " at %s" % time.strftime("%Y-%m-%d %H:%M:%S")
1128 aboard = track.aboard(vn)
1129 sort.lsort_pa(aboard)
1132 tbl = StandingsTable(tbl_s)
1134 if track.vesselname(): howmany = ' %d aboard' % len(aboard)
1137 tbl.headings(howmany, ' sorted by '+sort.desc())
1140 pi = pa.pirate_info()
1143 if pa.gunner: xs += 'G '
1145 xs += timeevent(pa.last_time, pa.last_event)
1146 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
1149 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
1153 s += tbl_s.getvalue()
1159 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
1163 elif k == 'g': sort = SkillSorter('Gunning')
1164 elif k == 'c': sort = SkillSorter('Carpentry')
1165 elif k == 's': sort = SkillSorter('Sailing/Rigging')
1166 elif k == 'b': sort = SkillSorter('Bilging')
1167 elif k == 'n': sort = SkillSorter('Navigating')
1168 elif k == 'd': sort = SkillSorter('Battle Navigation')
1169 elif k == 't': sort = SkillSorter('Treasure Haul')
1170 elif k == 'a': sort = NameSorter()
1171 else: pass # unknown key command
1173 #---------- individual keystroke input ----------
1175 class DummyKeystrokeReader:
1176 def __init__(self,fd,timeout_dummy): pass
1177 def stop(self): pass
1178 def getch(self): sleep(1); return None
1179 def info(self): return ' [noninteractive]'
1181 class KeystrokeReader(DummyKeystrokeReader):
1182 def __init__(self, fd, timeout_decisec=0):
1184 self._saved = termios.tcgetattr(fd)
1185 a = termios.tcgetattr(fd)
1186 a[3] &= ~(termios.ECHO | termios.ECHONL |
1187 termios.ICANON | termios.IEXTEN)
1188 a[6][termios.VMIN] = 0
1189 a[6][termios.VTIME] = timeout_decisec
1190 termios.tcsetattr(fd, termios.TCSANOW, a)
1192 termios.tcsetattr(self._fd, termios.TCSANOW, self._saved)
1195 byte = os.read(self._fd, 1)
1196 if not len(byte): return None
1201 #---------- main program ----------
1204 global opts, fetcher
1207 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
1209 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
1210 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
1211 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
1212 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
1213 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
1215 display modes (for --display) apply to ship-aid:
1216 --display=dumb just print new information, scrolling the screen
1217 --display=overwrite use cursor motion, selective clear, etc. to redraw at top''')
1219 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
1220 help='select ocean OCEAN')
1221 ao('--cache-dir', dest='cache_dir', metavar='DIR',
1222 default='~/.yoweb-scrape-cache',
1223 help='cache yoweb pages in DIR')
1224 ao('-D','--debug', action='count', dest='debug', default=0,
1225 help='enable debugging output')
1226 ao('--debug-fd', type='int', dest='debug_fd',
1227 help='write any debugging output to specified fd')
1228 ao('-q','--quiet', action='store_true', dest='quiet',
1229 help='suppress warning output')
1230 ao('--display', action='store', dest='display',
1231 type='choice', choices=['dumb','overwrite'],
1232 help='how to display ship aid')
1234 ao('--ship-duty', action='store_true', dest='ship_duty',
1235 help='show ship duty station puzzles')
1236 ao('--all-puzzles', action='store_false', dest='ship_duty',
1237 help='show all puzzles, not just ship duty stations')
1239 ao('--min-cache-reuse', type='int', dest='min_max_age',
1240 metavar='SECONDS', default=60,
1241 help='always reuse cache yoweb data if no older than this')
1243 (opts,args) = pa.parse_args()
1247 print >>sys.stderr, copyright_info
1248 pa.error('need a mode argument')
1250 if opts.debug_fd is not None:
1251 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
1253 opts.debug_file = sys.stdout
1256 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
1257 try: mode_fn = globals()[mode_fn_name]
1258 except KeyError: pa.error('unknown mode "%s"' % mode)
1261 opts.expire_age = max(3600, opts.min_max_age)
1263 opts.ship_reboard_clearout = 3600
1265 if opts.cache_dir.startswith('~/'):
1266 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
1268 if opts.display is None:
1269 if ((opts.debug > 0 and opts.debug_fd is None)
1270 or not os.isatty(sys.stdout.fileno())):
1271 opts.display = 'dumb'
1273 opts.display = 'overwrite'
1275 fetcher = Fetcher(opts.ocean, opts.cache_dir)
1277 mode_fn(args[1:], pa.error)