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)-1):
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):
336 if use_puzzles is None:
339 'Navigating','Battle Navigation',
341 ['Sailing','Rigging'],
348 self._puzzles = use_puzzles
350 self._cw = col_width-1
352 def _pline(self, pirate, puzstrs, extra):
353 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
355 self.s += ' %-*.*s' % (self._cw,self._cw, v)
357 self.s += ' ' + extra
360 def _puzstr(self, pi, puzzle):
361 if not isinstance(puzzle,list): puzzle = [puzzle]
362 try: standing = max([pi.standings[p] for p in puzzle])
363 except KeyError: return '?'
364 if not standing: return ''
367 c1 = standingvals[standing][0]
368 if standing < 3: c1 = c1.lower() # 3 = Master
372 s += '*' * (standing / 2)
373 s += '+' * (standing % 2)
377 def puzn_redact(name):
378 if isinstance(name,list):
380 ["%.*s" % (self._cw/2, puzn_redact(n))
383 if spc < 0: return name
384 return name[0:min(4,spc)] + name[spc+1:]
385 self._pline('', map(puzn_redact, self._puzzles), None)
386 def literalline(self, line):
387 self.s += line + '\n'
388 def pirate_dummy(self, name, standingstring, extra=None):
389 self._pline(name, standingstring * len(self._puzzles), extra)
390 def pirate(self, pi, extra=None):
391 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
392 self._pline(pi.name, puzstrs, extra)
397 #---------- chat log parser ----------
400 # This is essentially a transparent, dumb, data class.
410 def __init__(pa, pn, v, time, event):
414 pa.last_event = event
415 pa.last_chat_time = None
416 pa.last_chat_chan = None
423 age = now - pa.pi_fetched
424 guide = random.randint(120,240)
427 debug('PirateAboard refresh %d > %d %s' % (
428 age, guide, pa.name))
432 wait = fetcher.need_wait(now, imaginary)
434 debug('PirateAboard fetcher not ready %d' % wait)
436 pa.pi = PirateInfo(pa.name, 600)
440 class ChatLogTracker:
441 # This is quite complex so we make it opaque. Use the
442 # official invokers, accessors etc.
444 def __init__(self, myself_pi, logfn):
445 self._pl = {} # self._pl['Pirate'] =
446 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
447 # self._vl['Vessel']['#lastinfo']
448 # self._vl['Vessel']['#name']
449 # self._v = self._vl[self._vessel]
451 self._myself = myself_pi
452 self._f = file(logfn)
454 self._progress = [0, os.fstat(self._f.fileno()).st_size]
455 self._disembark_myself()
456 self._need_redisplay = False
457 self._lastvessel = None
459 def _disembark_myself(self):
462 self.force_redisplay()
464 def force_redisplay(self):
465 self._need_redisplay = True
467 def _vessel_updated(self, v, timestamp):
468 v['#lastinfo'] = timestamp
469 self.force_redisplay()
471 def _onboard_event(self,v,timestamp,pirate,event):
472 pa = self._pl.get(pirate, None)
473 if pa is not None and pa.v is v:
474 pa.last_time = timestamp
475 pa.last_event = event
477 if pa is not None: del pa.v[pirate]
478 pa = PirateAboard(pirate, v, timestamp, event)
479 self._pl[pirate] = pa
481 self._vessel_updated(v, timestamp)
484 def _trash_vessel(self, v):
486 if pn.startswith('#'): continue
490 if v is self._v: self._disembark_myself()
491 self.force_redisplay()
493 def _vessel_stale(self, v, timestamp):
494 return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
496 def _vessel_check_expire(self, v, timestamp):
497 if not self._vessel_stale(v, timestamp):
499 self._debug_line_disposition(timestamp,'',
500 'stale-reset ' + v['#name'])
501 self._trash_vessel(v)
504 def expire_garbage(self, timestamp):
505 for v in self._vl.values():
506 self._vessel_check_expire(v, timestamp)
508 def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
509 v = self._vl.get(vn, None)
511 v = self._vessel_check_expire(v, timestamp)
518 self._vl[vn] = v = { '#name': vn }
519 self._vessel_updated(v, timestamp)
522 def _find_matching_vessel(self, pattern, timestamp, cmdr,
523 dml=[], create=False):
524 # use when a commander pirate `cmdr' specified a vessel
525 # by name `pattern' (either may be None)
526 # if create is true, will create the vessel
527 # record if an exact name is specified
529 if (pattern is not None and
531 and len(pattern.split(' ')) == 2):
534 return self._vessel_lookup(
535 vn, timestamp, dml=dml, create=create)
538 pattern_check = lambda vn: True
540 re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
541 pattern_check = regexp.compile(re, regexp.I).match
545 cmdr_pa = self._pl.get(cmdr, None)
546 if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
548 tries.append((self._v, 'here'))
551 for (v, dm) in tries:
552 if v is None: dml.append(dm+'?'); continue
555 if not pattern_check(vn):
563 if pattern is not None and '*' in pattern:
566 for (vn,v) in self._vl.iteritems()
567 if not self._vessel_stale(v, timestamp)
570 #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
572 # '/'.join(tried_vns),
573 # '/'.join([vn for (vn,v) in search])))
583 def _debug_line_disposition(self,timestamp,l,m):
584 debug('CLT %13s %-40s %s' % (timestamp,m,l))
586 def chatline(self,l):
587 rm = lambda re: regexp.match(re,l)
588 d = lambda m: self._debug_line_disposition(timestamp,l,m)
591 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
593 self._date = [int(x) for x in m.groups()]
594 self._previous_timestamp = None
595 return d('date '+`self._date`)
597 if self._date is None:
598 return d('date unset')
600 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
602 return d('no timestamp')
605 time_tuple = (self._date +
606 [int(x) for x in m.groups()] +
608 timestamp = time.mktime(time_tuple)
609 if timestamp >= self._previous_timestamp: break
611 self._debug_line_disposition(timestamp,'',
612 'new date '+`self._date`)
614 self._previous_timestamp = timestamp
616 l = l[l.find(' ')+1:]
618 def ob_x(pirate,event):
619 return self._onboard_event(
620 self._v, timestamp, pirate, event)
621 def ob1(did): ob_x(m.group(1), did); return d(did)
622 def oba(did): return ob1('%s %s' % (did, m.group(2)))
624 def disembark(v, timestamp, pirate, event):
626 v, timestamp, pirate, 'leaving '+event)
630 def disembark_me(why):
631 self._disembark_myself()
632 return d('disembark-me '+why)
634 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
637 pn = self._myself.name
639 v = self._vessel_lookup(vn, timestamp, dm, create=True)
640 self._lastvessel = self._vessel = vn
642 ob_x(pn, 'we boarded')
643 self.expire_garbage(timestamp)
644 return d(' '.join(dm))
647 return d('no vessel')
649 m = rm('(\\w+) has come aboard\\.$')
650 if m: return ob1('boarded');
652 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
654 (who,what) = m.groups()
655 pa = ob_x(who,'ord '+what)
656 if what == 'Gunning':
658 return d('duty order')
660 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
661 if m: oba('stopped'); return d("end")
663 def chat_core(speaker, chan):
664 try: pa = self._pl[speaker]
665 except KeyError: return 'mystery'
666 if pa.v is not self._v: return 'elsewhere'
667 pa.last_chat_time = timestamp
668 pa.last_chat_chan = chan
669 self.force_redisplay()
674 dm = chat_core(speaker, chan)
675 return d('chat %s %s' % (chan, dm))
677 def chat_metacmd(chan):
678 (cmdr, metacmd) = m.groups()
679 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
681 '/([ad]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
683 if not m2: return chat(chan)
685 (cmd, pattern, targets) = m2.groups()
686 dml = ['cmd', chan, cmd]
688 if cmd == 'a': each = self._onboard_event
689 else: each = disembark
691 if cmdr == self._myself.name:
693 how = 'cmd: %s' % cmd
696 how = 'cmd: %s %s' % (cmd,cmdr)
698 v = self._find_matching_vessel(
699 pattern, timestamp, cmdr, dml, create=True)
702 targets = targets.strip().split(' ')
703 dml.append(`len(targets)`)
704 for target in targets:
705 each(v, timestamp, target.title(), how)
706 self._vessel_updated(v, timestamp)
709 chat_core(cmdr, 'cmd '+chan)
712 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
713 if m: return ob1('general order');
715 m = rm('(\\w+) says, "')
716 if m: return chat('public')
718 m = rm('(\\w+) tells ye, "')
719 if m: return chat('private')
721 m = rm('Ye told (\\w+), "(.*)"$')
722 if m: return chat_metacmd('private')
724 m = rm('(\\w+) flag officer chats, "')
725 if m: return chat('flag officer')
727 m = rm('(\\w+) officer chats, "(.*)"$')
728 if m: return chat_metacmd('officer')
730 m = rm('Ye accepted the offer to job with ')
731 if m: return disembark_me('jobbing')
733 m = rm('Ye hop on the ferry and are whisked away ')
734 if m: return disembark_me('ferry')
736 m = rm('Whisking away to yer home on the magical winds')
737 if m: return disembark_me('home')
739 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
741 pl = m.group(1).split(', ')
742 if not self._myself.name in pl:
743 return d('lost melee')
745 if ' ' in pn: continue
747 return d('won melee')
749 m = rm('(\\w+) is eliminated\\!')
750 if m: return ob1('eliminated in fray');
752 m = rm('(\\w+) has driven \w+ from the ship\\!')
753 if m: return ob1('boarder repelled');
755 m = rm('\w+ has bested (\\w+), and turns'+
756 ' to the rest of the ship\\.')
757 if m: return ob1('boarder unrepelled');
759 m = rm('(\\w+) has left the vessel\.')
762 disembark(self._v, timestamp, pirate, 'disembarked')
763 return d('disembarked')
765 return d('not-matched')
767 def _str_vessel(self, vn, v):
768 s = ' vessel %s\n' % vn
769 s += ' '*20 + "%-*s %13s\n" % (
770 max_pirate_namelen, '#lastinfo',
772 assert v['#name'] == vn
773 for pn in sorted(v.keys()):
774 if pn.startswith('#'): continue
777 assert self._pl[pn] == pa
778 s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
779 (' ','G')[pa.gunner],
780 max_pirate_namelen, pn,
781 pa.last_time, pa.last_event,
782 pa.last_chat_time, pa.last_chat_chan)
786 s = '''<ChatLogTracker
789 ''' % (self._myself.name, self._vessel)
790 assert ((self._v is None and self._vessel is None) or
791 (self._v is self._vl[self._vessel]))
792 if self._vessel is not None:
793 s += self._str_vessel(self._vessel, self._v)
794 for vn in sorted(self._vl.keys()):
795 if vn == self._vessel: continue
796 s += self._str_vessel(vn, self._vl[vn])
800 assert pa.v in self._vl.values()
804 def catchup(self, progress=None):
806 more = self._f.readline()
809 self._progress[0] += len(more)
810 if progress: progress.progress(*self._progress)
813 if self._lbuf.endswith('\n'):
814 self.chatline(self._lbuf.rstrip())
817 debug(self.__str__())
818 if progress: progress.caughtup()
821 rv = self._need_redisplay
822 self._need_redisplay = False
825 # returns our pirate name
826 return self._myself.name
827 def vesselname(self):
828 # returns the vessel name we're aboard or None
830 def lastvesselname(self):
831 # returns the last vessel name we were aboard or None
832 return self._lastvessel
833 def aboard(self, vesselname=True):
834 # returns a list of PirateAboard the vessel
835 # sorted by pirate name
836 # you can pass this None and you'll get []
837 # or True for the current vessel (which is the default)
838 if vesselname is True: v = self._v
839 else: v = self._vl.get(vesselname.title())
840 if v is None: return []
842 for pn in sorted(v.keys())
843 if not pn.startswith('#') ]
845 #---------- implementations of actual operation modes ----------
847 def do_pirate(pirates, bu):
849 for pirate in pirates:
850 info = PirateInfo(pirate)
851 print '%s: %s,' % (`pirate`, info)
854 def prep_crew_of(args, bu, max_age=300):
855 if len(args) != 1: bu('crew-of takes one pirate name')
856 pi = PirateInfo(args[0], max_age)
857 if pi.crew is None: return None
858 return CrewInfo(pi.crew[0], max_age)
860 def do_crew_of(args, bu):
861 ci = prep_crew_of(args, bu)
864 def do_standings_crew_of(args, bu):
865 ci = prep_crew_of(args, bu, 60)
866 tab = StandingsTable()
868 for (rank, members) in ci.crew:
869 if not members: continue
870 tab.literalline('%s:' % rank)
872 pi = PirateInfo(p, random.randint(900,1800))
876 class ProgressPrintPercentage:
877 def __init__(self, f=sys.stdout):
879 def progress_string(self,done,total):
880 return "scan chat logs %3d%%\r" % ((done*100) / total)
881 def progress(self,*a):
882 self._f.write(self.progress_string(*a))
884 def show_init(self, pirate, ocean):
885 print >>self._f, 'Starting up, %s on the %s ocean' % (
891 #----- modes which use the chat log parser are quite complex -----
893 def prep_chat_log(args, bu,
894 progress=ProgressPrintPercentage(),
895 max_myself_age=3600):
896 if len(args) != 1: bu('this action takes only chat log filename')
898 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
899 match = regexp.match(logfn_re, logfn)
900 if not match: bu('chat log filename is not in expected format')
901 (pirate, ocean) = match.groups()
902 fetcher.default_ocean(ocean)
904 progress.show_init(pirate, fetcher.ocean)
905 myself = PirateInfo(pirate,max_myself_age)
906 track = ChatLogTracker(myself, logfn)
909 track.catchup(progress)
912 track.force_redisplay()
914 return (myself, track)
916 def do_track_chat_log(args, bu):
917 (myself, track) = prep_chat_log(args, bu)
924 #----- ship management aid -----
926 class Display_dumb(ProgressPrintPercentage):
928 ProgressPrintPercentage.__init__(self)
934 class Display_overwrite(ProgressPrintPercentage):
936 ProgressPrintPercentage.__init__(self)
938 null = file('/dev/null','w')
939 curses.setupterm(fd=null.fileno())
941 self._clear = curses.tigetstr('clear')
943 self._debug('missing clear!')
944 self.show = Display_dumb.show
947 self._t = {'el':'', 'ed':''}
948 if not self._init_sophisticated():
949 for k in self._t.keys(): self._t[k] = ''
950 self._t['ho'] = self._clear
952 def _debug(self,m): debug('display overwrite: '+m)
954 def _init_sophisticated(self):
955 for k in self._t.keys():
956 s = curses.tigetstr(k)
958 self._t['ho'] = curses.tigetstr('ho')
959 if not self._t['ho']:
960 cup = curses.tigetstr('cup')
961 self._t['ho'] = curses.tparm(cup,0,0)
962 missing = [k for k in self._t.keys() if not self._t[k]]
964 self.debug('missing '+(' '.join(missing)))
970 def wti(k): w(self._t[k])
974 for l in s.rstrip().split('\n'):
984 sys.stdout.write(self._clear)
988 def do_ship_aid(args, bu):
989 if opts.ship_duty is None: opts.ship_duty = True
991 displayer = globals()['Display_'+opts.display]()
994 (myself, track) = prep_chat_log(args, bu, progress=displayer)
997 if t is None: return ' ' * 22
998 return " %-4s %-16s" % (format_time_interval(now - t),e)
1000 displayer.realstart()
1003 vn = track.vesselname()
1004 if vn: return (vn, " on board the %s" % vn)
1005 vn = track.lastvesselname()
1006 if vn: return (vn, " ashore from the %s" % vn)
1007 return (None, " not on a vessel")
1009 displayer.show(track.myname() + find_vessel()[1] + '...')
1015 (vn, s) = find_vessel()
1016 s = track.myname() + s
1017 s += " at %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")
1019 tbl = StandingsTable()
1022 aboard = track.aboard(vn)
1025 pi = pa.pirate_info()
1028 if pa.gunner: xs += 'G '
1030 xs += timeevent(pa.last_time, pa.last_event)
1031 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
1034 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
1042 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
1044 #---------- main program ----------
1047 global opts, fetcher
1050 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
1052 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
1053 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
1054 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
1055 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
1056 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
1058 display modes (for --display) apply to ship-aid:
1059 --display=dumb just print new information, scrolling the screen
1060 --display=overwrite use cursor motion, selective clear, etc. to redraw at top
1063 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
1064 help='select ocean OCEAN')
1065 ao('--cache-dir', dest='cache_dir', metavar='DIR',
1066 default='~/.yoweb-scrape-cache',
1067 help='cache yoweb pages in DIR')
1068 ao('-D','--debug', action='count', dest='debug', default=0,
1069 help='enable debugging output')
1070 ao('--debug-fd', type='int', dest='debug_fd',
1071 help='write any debugging output to specified fd')
1072 ao('-q','--quiet', action='store_true', dest='quiet',
1073 help='suppress warning output')
1074 ao('--display', action='store', dest='display',
1075 type='choice', choices=['dumb','overwrite'],
1076 help='how to display ship aid')
1078 ao('--ship-duty', action='store_true', dest='ship_duty',
1079 help='show ship duty station puzzles')
1080 ao('--all-puzzles', action='store_false', dest='ship_duty',
1081 help='show all puzzles, not just ship duty stations')
1083 (opts,args) = pa.parse_args()
1087 pa.error('need a mode argument')
1089 if opts.debug_fd is not None:
1090 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
1092 opts.debug_file = sys.stdout
1095 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
1096 try: mode_fn = globals()[mode_fn_name]
1097 except KeyError: pa.error('unknown mode "%s"' % mode)
1100 opts.min_max_age = 60
1101 opts.expire_age = 3600
1102 opts.ship_reboard_clearout = 3600
1104 if opts.cache_dir.startswith('~/'):
1105 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
1107 if opts.display is None:
1108 if ((opts.debug > 0 and opts.debug_fd is None)
1109 or not os.isatty(sys.stdout.fileno())):
1110 opts.display = 'dumb'
1112 opts.display = 'overwrite'
1114 fetcher = Fetcher(opts.ocean, opts.cache_dir)
1116 mode_fn(args[1:], pa.error)