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 ----------
42 print >>opts.debug_file, m
46 opts.debug_file.flush()
49 def format_time_interval(ti):
50 if ti < 120: return '%d:%02d' % (ti / 60, ti % 60)
51 if ti < 7200: return '%2dm' % (ti / 60)
52 if ti < 86400: return '%dh' % (ti / 3600)
53 return '%dd' % (ti / 86400)
55 #---------- caching and rate-limiting data fetcher ----------
58 def __init__(self, ocean, cachedir):
59 debug('Fetcher init %s' % cachedir)
61 self.cachedir = cachedir
62 try: os.mkdir(cachedir)
63 except (OSError,IOError), oe:
64 if oe.errno != errno.EEXIST: raise
65 self._cache_scan(time.time())
67 def default_ocean(self, ocean='ice'):
68 if self.ocean is None:
71 def _cache_scan(self, now):
72 # returns list of ages, unsorted
74 debug('Fetcher scan_cache')
75 for leaf in os.listdir(self.cachedir):
76 if not leaf.startswith('#'): continue
77 path = self.cachedir + '/' + leaf
78 try: s = os.stat(path)
79 except (OSError,IOError), oe:
80 if oe.errno != errno.ENOENT: raise
82 age = now - s.st_mtime
83 if age > opts.expire_age:
84 debug('Fetcher expire %d %s' % (age, path))
86 except (OSError,IOError), oe:
87 if oe.errno != errno.ENOENT: raise
92 def need_wait(self, now, imaginary=[]):
93 ages = self._cache_scan(now)
96 debug('Fetcher ages ' + `ages`)
100 if age < min_age and age < 300:
101 debug('Fetcher morewait min=%d age=%d' %
103 need_wait = max(need_wait, min_age - age)
108 def _rate_limit_cache_clean(self, now):
109 need_wait = self.need_wait(now)
111 debug('Fetcher wait %d' % need_wait)
114 def fetch(self, url, max_age):
115 debug('Fetcher fetch %s' % url)
116 cache_corename = urllib.quote_plus(url)
117 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
118 try: f = file(cache_item, 'r')
119 except (OSError,IOError), oe:
120 if oe.errno != errno.ENOENT: raise
123 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
125 s = os.fstat(f.fileno())
126 age = now - s.st_mtime
128 debug('Fetcher stale %d < %d'% (max_age, age))
133 debug('Fetcher cached %d > %d' % (max_age, age))
136 debug('Fetcher fetch')
137 self._rate_limit_cache_clean(now)
139 stream = urllib2.urlopen(url)
141 cache_tmp = "%s/#%s~%d#" % (
142 self.cachedir, cache_corename, os.getpid())
143 f = file(cache_tmp, 'w')
146 os.rename(cache_tmp, cache_item)
147 debug('Fetcher stored')
150 def yoweb(self, kind, tail, max_age):
152 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
153 self.ocean, kind, tail)
154 return self.fetch(url, max_age)
156 #---------- logging assistance for troubled screenscrapers ----------
163 def soupm(self, obj, m):
164 self.msg(m + '; in ' + `obj`)
165 def needs_msgs(self, child_souplog):
166 self.msgs += child_souplog.msgs
167 child_souplog.msgs = [ ]
170 str = ''.join(obj.findAll(text=True))
173 class SomethingSoupInfo(SoupLog):
174 def __init__(self, kind, tail, max_age):
175 SoupLog.__init__(self)
176 html = fetcher.yoweb(kind, tail, max_age)
177 self._soup = BeautifulSoup(html,
178 convertEntities=BeautifulSoup.HTML_ENTITIES
181 #---------- scraper for pirate pages ----------
183 class PirateInfo(SomethingSoupInfo):
184 # Public data members:
185 # pi.standings = { 'Treasure Haul': 'Able' ... }
187 # pi.crew = (id, name)
188 # pi.flag = (id, name)
189 # pi.msgs = [ 'message describing problem with scrape' ]
191 def __init__(self, pirate, max_age=300):
192 SomethingSoupInfo.__init__(self,
193 'pirate.wm?target=', pirate, max_age)
195 self._find_standings()
196 self.crew = self._find_crewflag('crew',
197 '^/yoweb/crew/info\\.wm')
198 self.flag = self._find_crewflag('flag',
199 '^/yoweb/flag/info\\.wm')
201 def _find_standings(self):
202 imgs = self._soup.findAll('img',
203 src=regexp.compile('/yoweb/images/stat.*'))
205 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
209 for skill in puzzles:
210 standings[skill] = [ ]
215 try: puzzle = img['alt']
216 except KeyError: continue
218 if not puzzle in puzzles:
219 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
221 key = img.findParent('td')
223 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
225 valelem = key.findNextSibling('td')
227 skl.soupm(key, 'puzzle missing sibling "%s"'
230 valstr = soup_text(valelem)
231 match = re.match(valstr)
233 skl.soupm(key, ('puzzle "%s" unparseable'+
234 ' standing "%s"') % (puzzle, valstr))
236 standing = match.group(match.lastindex)
237 standings[puzzle].append(standing)
241 for puzzle in puzzles:
242 sl = standings[puzzle]
244 skl.msg('puzzle "%s" multiple standings %s' %
248 skl.msg('puzzle "%s" no standing found' % puzzle)
251 for i in range(0, len(standingvals)):
252 if standing == standingvals[i]:
253 self.standings[puzzle] = i
254 if not puzzle in self.standings:
255 skl.msg('puzzle "%s" unknown standing "%s"' %
258 all_standings_ok = True
259 for puzzle in puzzles:
260 if not puzzle in self.standings:
263 def _find_crewflag(self, cf, yoweb_re):
264 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
266 self.msg('zero or several %s id references found' % cf)
269 id_re = '\\b%sid\\=(\\w+)$' % cf
270 id_haystack = thing['href']
271 match = regexp.compile(id_re).search(id_haystack)
273 self.soupm(thing, ('incomprehensible %s id ref'+
274 ' (%s in %s)') % (cf, id_re, id_haystack))
276 name = soup_text(thing)
277 return (match.group(1), name)
280 return `(self.crew, self.flag, self.standings, self.msgs)`
282 #---------- scraper for crew pages ----------
284 class CrewInfo(SomethingSoupInfo):
285 # Public data members:
286 # ci.crew = [ ('Captain', ['Pirate', ...]),
287 # ('Senior Officer', [...]),
289 # pi.msgs = [ 'message describing problem with scrape' ]
291 def __init__(self, crewid, max_age=300):
292 SomethingSoupInfo.__init__(self,
293 'crew/info.wm?crewid=', crewid, max_age)
296 def _find_crew(self):
298 capts = self._soup.findAll('img',
299 src='/yoweb/images/crew-captain.png')
301 self.msg('crew members: no. of captain images != 1')
304 while not tbl.find('a', href=pirate_ref_re):
305 tbl = tbl.findParent('table')
307 self.msg('crew members: cannot find table')
309 current_rank_crew = None
310 crew_rank_re = regexp.compile('/yoweb/images/crew')
311 for row in tbl.contents:
312 # findAll(recurse=False)
313 if isinstance(row,basestring):
316 is_rank = row.find('img', attrs={'src': crew_rank_re})
318 rank = soup_text(row)
319 current_rank_crew = []
320 self.crew.append((rank, current_rank_crew))
322 for cell in row.findAll('a', href=pirate_ref_re):
323 if current_rank_crew is None:
324 self.soupm(cell, 'crew members: crew'
327 current_rank_crew.append(soup_text(cell))
330 return `(self.crew, self.msgs)`
332 #---------- pretty-printer for tables of pirate puzzle standings ----------
334 class StandingsTable:
335 def __init__(self, use_puzzles=None, col_width=6, gap_every=5):
336 if use_puzzles is None:
339 'Navigating','Battle Navigation',
341 ['Sailing','Rigging'],
348 self._puzzles = use_puzzles
350 self._cw = col_width-1
351 self._gap_every = gap_every
354 def _pline(self, pirate, puzstrs, extra):
355 if (self._linecount > 0
356 and self._gap_every is not None
357 and not (self._linecount % self._gap_every)):
359 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
361 self.s += ' %-*.*s' % (self._cw,self._cw, v)
363 self.s += ' ' + extra
367 def _puzstr(self, pi, puzzle):
368 if not isinstance(puzzle,list): puzzle = [puzzle]
369 try: standing = max([pi.standings[p] for p in puzzle])
370 except KeyError: return '?'
371 if not standing: return ''
374 c1 = standingvals[standing][0]
375 if standing < 3: c1 = c1.lower() # 3 = Master
379 s += '*' * (standing / 2)
380 s += '+' * (standing % 2)
384 def puzn_redact(name):
385 if isinstance(name,list):
387 ["%.*s" % (self._cw/2, puzn_redact(n))
390 if spc < 0: return name
391 return name[0:min(4,spc)] + name[spc+1:]
393 self._pline('', map(puzn_redact, self._puzzles), None)
395 def literalline(self, line):
396 self.s += line + '\n'
398 def pirate_dummy(self, name, standingstring, extra=None):
399 self._pline(name, standingstring * len(self._puzzles), extra)
400 def pirate(self, pi, extra=None):
401 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
402 self._pline(pi.name, puzstrs, extra)
407 #---------- chat log parser ----------
410 # This is essentially a transparent, dumb, data class.
420 def __init__(pa, pn, v, time, event):
424 pa.last_event = event
425 pa.last_chat_time = None
426 pa.last_chat_chan = None
433 age = now - pa.pi_fetched
434 guide = random.randint(120,240)
437 debug('PirateAboard refresh %d > %d %s' % (
438 age, guide, pa.name))
442 wait = fetcher.need_wait(now, imaginary)
444 debug('PirateAboard fetcher not ready %d' % wait)
446 pa.pi = PirateInfo(pa.name, 600)
450 class ChatLogTracker:
451 # This is quite complex so we make it opaque. Use the
452 # official invokers, accessors etc.
454 def __init__(self, myself_pi, logfn):
455 self._pl = {} # self._pl['Pirate'] =
456 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
457 # self._vl['Vessel']['#lastinfo']
458 # self._vl['Vessel']['#name']
459 # self._v = self._vl[self._vessel]
461 self._myself = myself_pi
462 self._f = file(logfn)
464 self._progress = [0, os.fstat(self._f.fileno()).st_size]
465 self._disembark_myself()
466 self._need_redisplay = False
467 self._lastvessel = None
469 def _disembark_myself(self):
472 self.force_redisplay()
474 def force_redisplay(self):
475 self._need_redisplay = True
477 def _vessel_updated(self, v, timestamp):
478 v['#lastinfo'] = timestamp
479 self.force_redisplay()
481 def _onboard_event(self,v,timestamp,pirate,event):
482 pa = self._pl.get(pirate, None)
483 if pa is not None and pa.v is v:
484 pa.last_time = timestamp
485 pa.last_event = event
487 if pa is not None: del pa.v[pirate]
488 pa = PirateAboard(pirate, v, timestamp, event)
489 self._pl[pirate] = pa
491 self._vessel_updated(v, timestamp)
494 def _trash_vessel(self, v):
496 if pn.startswith('#'): continue
500 if v is self._v: self._disembark_myself()
501 self.force_redisplay()
503 def _vessel_stale(self, v, timestamp):
504 return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
506 def _vessel_check_expire(self, v, timestamp):
507 if not self._vessel_stale(v, timestamp):
509 self._debug_line_disposition(timestamp,'',
510 'stale-reset ' + v['#name'])
511 self._trash_vessel(v)
514 def expire_garbage(self, timestamp):
515 for v in self._vl.values():
516 self._vessel_check_expire(v, timestamp)
518 def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
519 v = self._vl.get(vn, None)
521 v = self._vessel_check_expire(v, timestamp)
528 self._vl[vn] = v = { '#name': vn }
529 self._vessel_updated(v, timestamp)
532 def _find_matching_vessel(self, pattern, timestamp, cmdr,
533 dml=[], create=False):
534 # use when a commander pirate `cmdr' specified a vessel
535 # by name `pattern' (either may be None)
536 # if create is true, will create the vessel
537 # record if an exact name is specified
539 if (pattern is not None and
541 and len(pattern.split(' ')) == 2):
544 return self._vessel_lookup(
545 vn, timestamp, dml=dml, create=create)
548 pattern_check = lambda vn: True
550 re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
551 pattern_check = regexp.compile(re, regexp.I).match
555 cmdr_pa = self._pl.get(cmdr, None)
556 if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
558 tries.append((self._v, 'here'))
561 for (v, dm) in tries:
562 if v is None: dml.append(dm+'?'); continue
565 if not pattern_check(vn):
573 if pattern is not None and '*' in pattern:
576 for (vn,v) in self._vl.iteritems()
577 if not self._vessel_stale(v, timestamp)
580 #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
582 # '/'.join(tried_vns),
583 # '/'.join([vn for (vn,v) in search])))
593 def _debug_line_disposition(self,timestamp,l,m):
594 debug('CLT %13s %-40s %s' % (timestamp,m,l))
596 def chatline(self,l):
597 rm = lambda re: regexp.match(re,l)
598 d = lambda m: self._debug_line_disposition(timestamp,l,m)
601 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
603 self._date = [int(x) for x in m.groups()]
604 self._previous_timestamp = None
605 return d('date '+`self._date`)
607 if self._date is None:
608 return d('date unset')
610 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
612 return d('no timestamp')
615 time_tuple = (self._date +
616 [int(x) for x in m.groups()] +
618 timestamp = time.mktime(time_tuple)
619 if timestamp >= self._previous_timestamp: break
621 self._debug_line_disposition(timestamp,'',
622 'new date '+`self._date`)
624 self._previous_timestamp = timestamp
626 l = l[l.find(' ')+1:]
628 def ob_x(pirate,event):
629 return self._onboard_event(
630 self._v, timestamp, pirate, event)
631 def ob1(did): ob_x(m.group(1), did); return d(did)
632 def oba(did): return ob1('%s %s' % (did, m.group(2)))
634 def disembark(v, timestamp, pirate, event):
636 v, timestamp, pirate, 'leaving '+event)
640 def disembark_me(why):
641 self._disembark_myself()
642 return d('disembark-me '+why)
644 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
647 pn = self._myself.name
649 v = self._vessel_lookup(vn, timestamp, dm, create=True)
650 self._lastvessel = self._vessel = vn
652 ob_x(pn, 'we boarded')
653 self.expire_garbage(timestamp)
654 return d(' '.join(dm))
657 return d('no vessel')
659 m = rm('(\\w+) has come aboard\\.$')
660 if m: return ob1('boarded');
662 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
664 (who,what) = m.groups()
665 pa = ob_x(who,'ord '+what)
666 if what == 'Gunning':
668 return d('duty order')
670 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
671 if m: oba('stopped'); return d("end")
673 def chat_core(speaker, chan):
674 try: pa = self._pl[speaker]
675 except KeyError: return 'mystery'
676 if pa.v is not self._v: return 'elsewhere'
677 pa.last_chat_time = timestamp
678 pa.last_chat_chan = chan
679 self.force_redisplay()
684 dm = chat_core(speaker, chan)
685 return d('chat %s %s' % (chan, dm))
687 def chat_metacmd(chan):
688 (cmdr, metacmd) = m.groups()
689 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
691 '/([ad]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
693 if not m2: return chat(chan)
695 (cmd, pattern, targets) = m2.groups()
696 dml = ['cmd', chan, cmd]
698 if cmd == 'a': each = self._onboard_event
699 else: each = disembark
701 if cmdr == self._myself.name:
703 how = 'cmd: %s' % cmd
706 how = 'cmd: %s %s' % (cmd,cmdr)
708 v = self._find_matching_vessel(
709 pattern, timestamp, cmdr, dml, create=True)
712 targets = targets.strip().split(' ')
713 dml.append(`len(targets)`)
714 for target in targets:
715 each(v, timestamp, target.title(), how)
716 self._vessel_updated(v, timestamp)
719 chat_core(cmdr, 'cmd '+chan)
722 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
723 if m: return ob1('general order');
725 m = rm('(\\w+) says, "')
726 if m: return chat('public')
728 m = rm('(\\w+) tells ye, "')
729 if m: return chat('private')
731 m = rm('Ye told (\\w+), "(.*)"$')
732 if m: return chat_metacmd('private')
734 m = rm('(\\w+) flag officer chats, "')
735 if m: return chat('flag officer')
737 m = rm('(\\w+) officer chats, "(.*)"$')
738 if m: return chat_metacmd('officer')
740 m = rm('Ye accepted the offer to job with ')
741 if m: return disembark_me('jobbing')
743 m = rm('Ye hop on the ferry and are whisked away ')
744 if m: return disembark_me('ferry')
746 m = rm('Whisking away to yer home on the magical winds')
747 if m: return disembark_me('home')
749 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
751 pl = m.group(1).split(', ')
752 if not self._myself.name in pl:
753 return d('lost melee')
755 if ' ' in pn: continue
757 return d('won melee')
759 m = rm('(\\w+) is eliminated\\!')
760 if m: return ob1('eliminated in fray');
762 m = rm('(\\w+) has driven \w+ from the ship\\!')
763 if m: return ob1('boarder repelled');
765 m = rm('\w+ has bested (\\w+), and turns'+
766 ' to the rest of the ship\\.')
767 if m: return ob1('boarder unrepelled');
769 m = rm('(\\w+) has left the vessel\.')
772 disembark(self._v, timestamp, pirate, 'disembarked')
773 return d('disembarked')
775 return d('not-matched')
777 def _str_vessel(self, vn, v):
778 s = ' vessel %s\n' % vn
779 s += ' '*20 + "%-*s %13s\n" % (
780 max_pirate_namelen, '#lastinfo',
782 assert v['#name'] == vn
783 for pn in sorted(v.keys()):
784 if pn.startswith('#'): continue
787 assert self._pl[pn] == pa
788 s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
789 (' ','G')[pa.gunner],
790 max_pirate_namelen, pn,
791 pa.last_time, pa.last_event,
792 pa.last_chat_time, pa.last_chat_chan)
796 s = '''<ChatLogTracker
799 ''' % (self._myself.name, self._vessel)
800 assert ((self._v is None and self._vessel is None) or
801 (self._v is self._vl[self._vessel]))
802 if self._vessel is not None:
803 s += self._str_vessel(self._vessel, self._v)
804 for vn in sorted(self._vl.keys()):
805 if vn == self._vessel: continue
806 s += self._str_vessel(vn, self._vl[vn])
810 assert pa.v in self._vl.values()
814 def catchup(self, progress=None):
816 more = self._f.readline()
819 self._progress[0] += len(more)
820 if progress: progress.progress(*self._progress)
823 if self._lbuf.endswith('\n'):
824 self.chatline(self._lbuf.rstrip())
827 debug(self.__str__())
828 if progress: progress.caughtup()
831 rv = self._need_redisplay
832 self._need_redisplay = False
835 # returns our pirate name
836 return self._myself.name
837 def vesselname(self):
838 # returns the vessel name we're aboard or None
840 def lastvesselname(self):
841 # returns the last vessel name we were aboard or None
842 return self._lastvessel
843 def aboard(self, vesselname=True):
844 # returns a list of PirateAboard the vessel
845 # sorted by pirate name
846 # you can pass this None and you'll get []
847 # or True for the current vessel (which is the default)
848 if vesselname is True: v = self._v
849 else: v = self._vl.get(vesselname.title())
850 if v is None: return []
852 for pn in sorted(v.keys())
853 if not pn.startswith('#') ]
855 #---------- implementations of actual operation modes ----------
857 def do_pirate(pirates, bu):
859 for pirate in pirates:
860 info = PirateInfo(pirate)
861 print '%s: %s,' % (`pirate`, info)
864 def prep_crew_of(args, bu, max_age=300):
865 if len(args) != 1: bu('crew-of takes one pirate name')
866 pi = PirateInfo(args[0], max_age)
867 if pi.crew is None: return None
868 return CrewInfo(pi.crew[0], max_age)
870 def do_crew_of(args, bu):
871 ci = prep_crew_of(args, bu)
874 def do_standings_crew_of(args, bu):
875 ci = prep_crew_of(args, bu, 60)
876 tab = StandingsTable()
878 for (rank, members) in ci.crew:
879 if not members: continue
881 tab.literalline('%s:' % rank)
883 pi = PirateInfo(p, random.randint(900,1800))
887 class ProgressPrintPercentage:
888 def __init__(self, f=sys.stdout):
890 def progress_string(self,done,total):
891 return "scan chat logs %3d%%\r" % ((done*100) / total)
892 def progress(self,*a):
893 self._f.write(self.progress_string(*a))
895 def show_init(self, pirate, ocean):
896 print >>self._f, 'Starting up, %s on the %s ocean' % (
902 #----- modes which use the chat log parser are quite complex -----
904 def prep_chat_log(args, bu,
905 progress=ProgressPrintPercentage(),
906 max_myself_age=3600):
907 if len(args) != 1: bu('this action takes only chat log filename')
909 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
910 match = regexp.match(logfn_re, logfn)
911 if not match: bu('chat log filename is not in expected format')
912 (pirate, ocean) = match.groups()
913 fetcher.default_ocean(ocean)
915 progress.show_init(pirate, fetcher.ocean)
916 myself = PirateInfo(pirate,max_myself_age)
917 track = ChatLogTracker(myself, logfn)
920 track.catchup(progress)
923 track.force_redisplay()
925 return (myself, track)
927 def do_track_chat_log(args, bu):
928 (myself, track) = prep_chat_log(args, bu)
935 #----- ship management aid -----
937 class Display_dumb(ProgressPrintPercentage):
939 ProgressPrintPercentage.__init__(self)
945 class Display_overwrite(ProgressPrintPercentage):
947 ProgressPrintPercentage.__init__(self)
949 null = file('/dev/null','w')
950 curses.setupterm(fd=null.fileno())
952 self._clear = curses.tigetstr('clear')
954 self._debug('missing clear!')
955 self.show = Display_dumb.show
958 self._t = {'el':'', 'ed':''}
959 if not self._init_sophisticated():
960 for k in self._t.keys(): self._t[k] = ''
961 self._t['ho'] = self._clear
963 def _debug(self,m): debug('display overwrite: '+m)
965 def _init_sophisticated(self):
966 for k in self._t.keys():
967 s = curses.tigetstr(k)
969 self._t['ho'] = curses.tigetstr('ho')
970 if not self._t['ho']:
971 cup = curses.tigetstr('cup')
972 self._t['ho'] = curses.tparm(cup,0,0)
973 missing = [k for k in self._t.keys() if not self._t[k]]
975 self.debug('missing '+(' '.join(missing)))
981 def wti(k): w(self._t[k])
985 for l in s.rstrip().split('\n'):
995 sys.stdout.write(self._clear)
999 def do_ship_aid(args, bu):
1000 if opts.ship_duty is None: opts.ship_duty = True
1002 displayer = globals()['Display_'+opts.display]()
1005 (myself, track) = prep_chat_log(args, bu, progress=displayer)
1008 if t is None: return ' ' * 22
1009 return " %-4s %-16s" % (format_time_interval(now - t),e)
1011 displayer.realstart()
1014 vn = track.vesselname()
1015 if vn: return (vn, " on board the %s" % vn)
1016 vn = track.lastvesselname()
1017 if vn: return (vn, " ashore from the %s" % vn)
1018 return (None, " not on a vessel")
1020 displayer.show(track.myname() + find_vessel()[1] + '...')
1026 (vn, s) = find_vessel()
1027 s = track.myname() + s
1028 s += " at %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")
1030 tbl = StandingsTable()
1033 aboard = track.aboard(vn)
1036 pi = pa.pirate_info()
1039 if pa.gunner: xs += 'G '
1041 xs += timeevent(pa.last_time, pa.last_event)
1042 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
1045 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
1053 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
1055 #---------- main program ----------
1058 global opts, fetcher
1061 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
1063 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
1064 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
1065 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
1066 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
1067 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
1069 display modes (for --display) apply to ship-aid:
1070 --display=dumb just print new information, scrolling the screen
1071 --display=overwrite use cursor motion, selective clear, etc. to redraw at top
1074 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
1075 help='select ocean OCEAN')
1076 ao('--cache-dir', dest='cache_dir', metavar='DIR',
1077 default='~/.yoweb-scrape-cache',
1078 help='cache yoweb pages in DIR')
1079 ao('-D','--debug', action='count', dest='debug', default=0,
1080 help='enable debugging output')
1081 ao('--debug-fd', type='int', dest='debug_fd',
1082 help='write any debugging output to specified fd')
1083 ao('-q','--quiet', action='store_true', dest='quiet',
1084 help='suppress warning output')
1085 ao('--display', action='store', dest='display',
1086 type='choice', choices=['dumb','overwrite'],
1087 help='how to display ship aid')
1089 ao('--ship-duty', action='store_true', dest='ship_duty',
1090 help='show ship duty station puzzles')
1091 ao('--all-puzzles', action='store_false', dest='ship_duty',
1092 help='show all puzzles, not just ship duty stations')
1094 ao('--min-cache-reuse', type='int', dest='min_max_age',
1095 metavar='SECONDS', default=60,
1096 help='always reuse cache yoweb data if no older than this')
1098 (opts,args) = pa.parse_args()
1102 pa.error('need a mode argument')
1104 if opts.debug_fd is not None:
1105 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
1107 opts.debug_file = sys.stdout
1110 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
1111 try: mode_fn = globals()[mode_fn_name]
1112 except KeyError: pa.error('unknown mode "%s"' % mode)
1115 opts.expire_age = max(3600, opts.min_max_age)
1117 opts.ship_reboard_clearout = 3600
1119 if opts.cache_dir.startswith('~/'):
1120 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
1122 if opts.display is None:
1123 if ((opts.debug > 0 and opts.debug_fd is None)
1124 or not os.isatty(sys.stdout.fileno())):
1125 opts.display = 'dumb'
1127 opts.display = 'overwrite'
1129 fetcher = Fetcher(opts.ocean, opts.cache_dir)
1131 mode_fn(args[1:], pa.error)