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):
93 ages = self._cache_scan(now)
95 debug('Fetcher ages ' + `ages`)
99 if age < min_age and age < 300:
100 debug('Fetcher morewait min=%d age=%d' %
102 need_wait = max(need_wait, min_age - age)
107 def _rate_limit_cache_clean(self, now):
108 need_wait = self.need_wait(now)
110 debug('Fetcher wait %d' % need_wait)
113 def fetch(self, url, max_age):
114 debug('Fetcher fetch %s' % url)
115 cache_corename = urllib.quote_plus(url)
116 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
117 try: f = file(cache_item, 'r')
118 except (OSError,IOError), oe:
119 if oe.errno != errno.ENOENT: raise
122 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
124 s = os.fstat(f.fileno())
125 age = now - s.st_mtime
127 debug('Fetcher stale %d < %d'% (max_age, age))
132 debug('Fetcher cached %d > %d' % (max_age, age))
135 debug('Fetcher fetch')
136 self._rate_limit_cache_clean(now)
138 stream = urllib2.urlopen(url)
140 cache_tmp = "%s/#%s~%d#" % (
141 self.cachedir, cache_corename, os.getpid())
142 f = file(cache_tmp, 'w')
145 os.rename(cache_tmp, cache_item)
146 debug('Fetcher stored')
149 def yoweb(self, kind, tail, max_age):
151 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
152 self.ocean, kind, tail)
153 return self.fetch(url, max_age)
155 #---------- logging assistance for troubled screenscrapers ----------
162 def soupm(self, obj, m):
163 self.msg(m + '; in ' + `obj`)
164 def needs_msgs(self, child_souplog):
165 self.msgs += child_souplog.msgs
166 child_souplog.msgs = [ ]
169 str = ''.join(obj.findAll(text=True))
172 class SomethingSoupInfo(SoupLog):
173 def __init__(self, kind, tail, max_age):
174 SoupLog.__init__(self)
175 html = fetcher.yoweb(kind, tail, max_age)
176 self._soup = BeautifulSoup(html,
177 convertEntities=BeautifulSoup.HTML_ENTITIES
180 #---------- scraper for pirate pages ----------
182 class PirateInfo(SomethingSoupInfo):
183 # Public data members:
184 # pi.standings = { 'Treasure Haul': 'Able' ... }
186 # pi.crew = (id, name)
187 # pi.flag = (id, name)
188 # pi.msgs = [ 'message describing problem with scrape' ]
190 def __init__(self, pirate, max_age=300):
191 SomethingSoupInfo.__init__(self,
192 'pirate.wm?target=', pirate, max_age)
194 self._find_standings()
195 self.crew = self._find_crewflag('crew',
196 '^/yoweb/crew/info\\.wm')
197 self.flag = self._find_crewflag('flag',
198 '^/yoweb/flag/info\\.wm')
200 def _find_standings(self):
201 imgs = self._soup.findAll('img',
202 src=regexp.compile('/yoweb/images/stat.*'))
204 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
208 for skill in puzzles:
209 standings[skill] = [ ]
214 try: puzzle = img['alt']
215 except KeyError: continue
217 if not puzzle in puzzles:
218 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
220 key = img.findParent('td')
222 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
224 valelem = key.findNextSibling('td')
226 skl.soupm(key, 'puzzle missing sibling "%s"'
229 valstr = soup_text(valelem)
230 match = re.match(valstr)
232 skl.soupm(key, ('puzzle "%s" unparseable'+
233 ' standing "%s"') % (puzzle, valstr))
235 standing = match.group(match.lastindex)
236 standings[puzzle].append(standing)
240 for puzzle in puzzles:
241 sl = standings[puzzle]
243 skl.msg('puzzle "%s" multiple standings %s' %
247 skl.msg('puzzle "%s" no standing found' % puzzle)
250 for i in range(0, len(standingvals)-1):
251 if standing == standingvals[i]:
252 self.standings[puzzle] = i
253 if not puzzle in self.standings:
254 skl.msg('puzzle "%s" unknown standing "%s"' %
257 all_standings_ok = True
258 for puzzle in puzzles:
259 if not puzzle in self.standings:
262 def _find_crewflag(self, cf, yoweb_re):
263 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
265 self.msg('zero or several %s id references found' % cf)
268 id_re = '\\b%sid\\=(\\w+)$' % cf
269 id_haystack = thing['href']
270 match = regexp.compile(id_re).search(id_haystack)
272 self.soupm(thing, ('incomprehensible %s id ref'+
273 ' (%s in %s)') % (cf, id_re, id_haystack))
275 name = soup_text(thing)
276 return (match.group(1), name)
279 return `(self.crew, self.flag, self.standings, self.msgs)`
281 #---------- scraper for crew pages ----------
283 class CrewInfo(SomethingSoupInfo):
284 # Public data members:
285 # ci.crew = [ ('Captain', ['Pirate', ...]),
286 # ('Senior Officer', [...]),
288 # pi.msgs = [ 'message describing problem with scrape' ]
290 def __init__(self, crewid, max_age=300):
291 SomethingSoupInfo.__init__(self,
292 'crew/info.wm?crewid=', crewid, max_age)
295 def _find_crew(self):
297 capts = self._soup.findAll('img',
298 src='/yoweb/images/crew-captain.png')
300 self.msg('crew members: no. of captain images != 1')
303 while not tbl.find('a', href=pirate_ref_re):
304 tbl = tbl.findParent('table')
306 self.msg('crew members: cannot find table')
308 current_rank_crew = None
309 crew_rank_re = regexp.compile('/yoweb/images/crew')
310 for row in tbl.contents:
311 # findAll(recurse=False)
312 if isinstance(row,basestring):
315 is_rank = row.find('img', attrs={'src': crew_rank_re})
317 rank = soup_text(row)
318 current_rank_crew = []
319 self.crew.append((rank, current_rank_crew))
321 for cell in row.findAll('a', href=pirate_ref_re):
322 if current_rank_crew is None:
323 self.soupm(cell, 'crew members: crew'
326 current_rank_crew.append(soup_text(cell))
329 return `(self.crew, self.msgs)`
331 #---------- pretty-printer for tables of pirate puzzle standings ----------
333 class StandingsTable:
334 def __init__(self, use_puzzles=None, col_width=6):
335 if use_puzzles is None:
338 'Navigating','Battle Navigation',
340 ['Sailing','Rigging'],
347 self._puzzles = use_puzzles
349 self._cw = col_width-1
351 def _pline(self, pirate, puzstrs, extra):
352 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
354 self.s += ' %-*.*s' % (self._cw,self._cw, v)
356 self.s += ' ' + extra
359 def _puzstr(self, pi, puzzle):
360 if not isinstance(puzzle,list): puzzle = [puzzle]
361 try: standing = max([pi.standings[p] for p in puzzle])
362 except KeyError: return '?'
363 if not standing: return ''
366 c1 = standingvals[standing][0]
367 if standing < 3: c1 = c1.lower() # 3 = Master
371 s += '*' * (standing / 2)
372 s += '+' * (standing % 2)
376 def puzn_redact(name):
377 if isinstance(name,list):
379 ["%.*s" % (self._cw/2, puzn_redact(n))
382 if spc < 0: return name
383 return name[0:min(4,spc)] + name[spc+1:]
384 self._pline('', map(puzn_redact, self._puzzles), None)
385 def literalline(self, line):
386 self.s += line + '\n'
387 def pirate_dummy(self, name, standingstring, extra=None):
388 self._pline(name, standingstring * len(self._puzzles), extra)
389 def pirate(self, pi, extra=None):
390 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
391 self._pline(pi.name, puzstrs, extra)
396 #---------- chat log parser ----------
399 # This is essentially a transparent, dumb, data class.
409 def __init__(pa, pn, v, time, event):
413 pa.last_event = event
414 pa.last_chat_time = None
415 pa.last_chat_chan = None
420 if not pa.pi and not fetcher.need_wait(time.time()):
421 pa.pi = PirateInfo(pa.name, 3600)
424 class ChatLogTracker:
425 # This is quite complex so we make it opaque. Use the
426 # official invokers, accessors etc.
428 def __init__(self, myself_pi, logfn):
429 self._pl = {} # self._pl['Pirate'] =
430 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
431 # self._vl['Vessel']['#lastinfo']
432 self._v = None # self._v =
433 self._vessel = None # self._vl[self._vessel]
435 self._myself = myself_pi
436 self._need_redisplay = False
437 self._f = file(logfn)
439 self._progress = [0, os.fstat(self._f.fileno()).st_size]
441 def force_redisplay(self):
442 self._need_redisplay = True
444 def _onboard_event(self,v,timestamp,pirate,event):
445 pa = self._pl.get(pirate, None)
446 if pa is not None and pa.v is v:
447 pa.last_time = timestamp
448 pa.last_event = event
450 if pa is not None: del pa.v[pirate]
451 pa = PirateAboard(pirate, v, timestamp, event)
452 self._pl[pirate] = pa
454 v['#lastinfo'] = timestamp
455 self.force_redisplay()
458 def _trash_vessel(self, v):
460 if pn.startswith('#'): continue
462 self.force_redisplay()
464 def expire_garbage(self, timestamp):
465 for (vn,v) in list(self._vl.iteritems()):
467 if timestamp - la > opts.ship_reboard_clearout:
468 self._debug_line_disposition(timestamp,'',
470 self._trash_vessel(v)
473 def _create_vessel(self, vn, timestamp):
474 self._vl[vn] = v = { '#lastinfo': timestamp }
477 def _update_vessel_lookup(self, vn, timestamp, dml):
478 v = self._vl.get(vn, None)
481 v = self._create_vessel(vn, timestamp)
482 elif timestamp - v['#lastinfo'] > opts.ship_reboard_clearout:
484 self._trash_vessel(v)
485 v = self._create_vessel(vn, timestamp)
487 dml.append('current')
490 def _debug_line_disposition(self,timestamp,l,m):
491 debug('CLT %13s %-30s %s' % (timestamp,m,l))
493 def chatline(self,l):
494 rm = lambda re: regexp.match(re,l)
495 d = lambda m: self._debug_line_disposition(timestamp,l,m)
498 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
500 self._date = [int(x) for x in m.groups()]
501 self._previous_timestamp = None
502 return d('date '+`self._date`)
504 if self._date is None:
505 return d('date unset')
507 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
509 return d('no timestamp')
512 time_tuple = (self._date +
513 [int(x) for x in m.groups()] +
515 timestamp = time.mktime(time_tuple)
516 if timestamp >= self._previous_timestamp: break
518 self._debug_line_disposition(timestamp,'',
519 'new date '+`self._date`)
521 self._previous_timestamp = timestamp
523 l = l[l.find(' ')+1:]
525 def ob_x(pirate,event):
526 return self._onboard_event(
527 self._v, timestamp, pirate, event)
528 def ob1(did): ob_x(m.group(1), did); return d(did)
529 def oba(did): return ob1('%s %s' % (did, m.group(2)))
531 def disembark(v, timestamp, pirate, event):
533 v, timestamp, pirate, 'leaving '+event)
537 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
540 pn = self._myself.name
541 self._vessel = vn = m.group(1)
542 self._v = self._update_vessel_lookup(vn, timestamp, dm)
544 ob_x(pn, 'we boarded')
545 self.expire_garbage(timestamp)
546 return d(' '.join(dm))
549 return d('no vessel')
551 m = rm('(\\w+) has come aboard\\.$')
552 if m: return ob1('boarded');
554 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
556 (who,what) = m.groups()
557 pa = ob_x(who,'ord '+what)
558 if what == 'Gunning':
560 return d('duty order')
562 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
563 if m: oba('stopped'); return d("end")
565 def chat_core(speaker, chan):
566 try: pa = self._pl[speaker]
567 except KeyError: return 'mystery'
568 if pa.v is not self._v: return 'elsewhere'
569 pa.last_chat_time = timestamp
570 pa.last_chat_chan = chan
571 self.force_redisplay()
576 dm = chat_core(speaker, chan)
577 return d('chat %s %s' % (chan, dm))
579 def chat_metacmd(chan):
580 (cmdr, metacmd) = m.groups()
581 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
583 '/([ad]) (?:([A-Za-z ]+)\\s*:)?([A-Za-z ]+)$',
585 if not m2: return chat(chan)
587 (cmd, vn, targets) = m2.groups()
588 dml = ['cmd', chan, cmd]
590 if cmd == 'a': each = self._onboard_event
591 else: each = disembark
593 if cmdr == self._myself.name:
595 how = 'manual: /%s' % cmd
598 how = '/%s %s' % (cmd,cmdr)
601 if vn is not None and len(vn.split(' ')) == 2:
602 v = self._update_vessel_lookup(
603 vn.title(), timestamp, dml)
604 elif self._v is None:
605 dml.append('no-current')
607 dml.append('current')
609 elif regexp.match('(?:.* )?%s$' % vn.title(),
614 dml.append('unk-abbrev')
617 targets = targets.strip().split(' ')
618 dml.append(`len(targets)`)
619 for target in targets:
620 each(v, timestamp, target.title(), how)
623 chat_core(cmdr, 'cmd '+chan)
626 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
627 if m: return ob1('general order');
629 m = rm('(\\w+) says, "')
630 if m: return chat('public')
632 m = rm('(\\w+) tells ye, "')
633 if m: return chat('private')
635 m = rm('Ye told (\\w+), "(.*)"$')
636 if m: return chat_metacmd('private')
638 m = rm('(\\w+) flag officer chats, "')
639 if m: return chat('flag officer')
641 m = rm('(\\w+) officer chats, "(.*)"$')
642 if m: return chat_metacmd('officer')
644 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
646 pl = m.group(1).split(', ')
647 if not self._myself.name in pl:
648 return d('lost boarding battle')
650 if ' ' in pn: continue
651 ob_x(pn,'won boarding battle')
652 return d('won boarding battle')
654 m = rm('(\\w+) is eliminated\\!')
655 if m: return ob1('eliminated in fray');
657 m = rm('(\\w+) has left the vessel\.')
660 disembark(self._v, timestamp, pirate, 'disembarked')
661 return d('disembarked')
663 return d('not matched')
665 def _str_vessel(self, vn, v):
666 s = ' vessel %s\n' % vn
667 s += ' '*20 + "%-*s %13s\n" % (
668 max_pirate_namelen, '#lastinfo',
670 for pn in sorted(v.keys()):
671 if pn.startswith('#'): continue
674 assert self._pl[pn] == pa
675 s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
676 (' ','G')[pa.gunner],
677 max_pirate_namelen, pn,
678 pa.last_time, pa.last_event,
679 pa.last_chat_time, pa.last_chat_chan)
683 s = '''<ChatLogTracker
686 ''' % (self._myself.name, self._vessel)
687 assert ((self._v is None and self._vessel is None) or
688 (self._v is self._vl[self._vessel]))
689 if self._vessel is not None:
690 s += self._str_vessel(self._vessel, self._v)
691 for vn in sorted(self._vl.keys()):
692 if vn == self._vessel: continue
693 s += self._str_vessel(vn, self._vl[vn])
697 assert pa.v in self._vl.values()
701 def catchup(self, progress=None):
703 more = self._f.readline()
706 self._progress[0] += len(more)
707 if progress: progress.progress(*self._progress)
710 if self._lbuf.endswith('\n'):
711 self.chatline(self._lbuf.rstrip())
714 debug(self.__str__())
715 if progress: progress.caughtup()
718 rv = self._need_redisplay
719 self._need_redisplay = False
722 # returns our pirate name
723 return self._myself.name
725 # returns the vessel we're aboard or None
728 # returns a list of PirateAboard sorted by name
729 if self._v is None: return []
731 for pn in sorted(self._v.keys())
732 if not pn.startswith('#') ]
734 #---------- implementations of actual operation modes ----------
736 def do_pirate(pirates, bu):
738 for pirate in pirates:
739 info = PirateInfo(pirate)
740 print '%s: %s,' % (`pirate`, info)
743 def prep_crew_of(args, bu, max_age=300):
744 if len(args) != 1: bu('crew-of takes one pirate name')
745 pi = PirateInfo(args[0], max_age)
746 if pi.crew is None: return None
747 return CrewInfo(pi.crew[0], max_age)
749 def do_crew_of(args, bu):
750 ci = prep_crew_of(args, bu)
753 def do_standings_crew_of(args, bu):
754 ci = prep_crew_of(args, bu, 60)
755 tab = StandingsTable()
757 for (rank, members) in ci.crew:
758 if not members: continue
759 tab.literalline('%s:' % rank)
761 pi = PirateInfo(p, random.randint(900,1800))
765 class ProgressPrintPercentage:
766 def __init__(self, f=sys.stdout):
768 def progress_string(self,done,total):
769 return "scan chat logs %3d%%\r" % ((done*100) / total)
770 def progress(self,*a):
771 self._f.write(self.progress_string(*a))
773 def show_init(self, pirate, ocean):
774 print >>self._f, 'Starting up, %s on the %s ocean' % (
780 #----- modes which use the chat log parser are quite complex -----
782 def prep_chat_log(args, bu,
783 progress=ProgressPrintPercentage(),
784 max_myself_age=3600):
785 if len(args) != 1: bu('this action takes only chat log filename')
787 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
788 match = regexp.match(logfn_re, logfn)
789 if not match: bu('chat log filename is not in expected format')
790 (pirate, ocean) = match.groups()
791 fetcher.default_ocean(ocean)
793 myself = PirateInfo(pirate,max_myself_age)
794 progress.show_init(pirate, fetcher.ocean)
795 track = ChatLogTracker(myself, logfn)
798 track.catchup(progress)
801 track.force_redisplay()
803 return (myself, track)
805 def do_track_chat_log(args, bu):
806 (myself, track) = prep_chat_log(args, bu)
813 #----- ship management aid -----
815 class Display_dumb(ProgressPrintPercentage):
817 ProgressPrintPercentage.__init__(self)
823 class Display_overwrite(ProgressPrintPercentage):
825 ProgressPrintPercentage.__init__(self)
827 null = file('/dev/null','w')
828 curses.setupterm(fd=null.fileno())
830 self._clear = curses.tigetstr('clear')
832 self._debug('missing clear!')
833 self.show = Display_dumb.show
836 self._t = {'el':'', 'ed':''}
837 if not self._init_sophisticated():
838 for k in self._t.keys(): self._t[k] = ''
839 self._t['ho'] = self._clear
841 def _debug(self,m): debug('display overwrite: '+m)
843 def _init_sophisticated(self):
844 for k in self._t.keys():
845 s = curses.tigetstr(k)
847 self._t['ho'] = curses.tigetstr('ho')
848 if not self._t['ho']:
849 cup = curses.tigetstr('cup')
850 self._t['ho'] = curses.tparm(cup,0,0)
851 missing = [k for k in self._t.keys() if not self._t[k]]
853 self.debug('missing '+(' '.join(missing)))
859 def wti(k): w(self._t[k])
863 for l in s.rstrip().split('\n'):
873 sys.stdout.write(self._clear)
877 def do_ship_aid(args, bu):
878 if opts.ship_duty is None: opts.ship_duty = True
880 displayer = globals()['Display_'+opts.display]()
883 (myself, track) = prep_chat_log(args, bu, progress=displayer)
886 if t is None: return ' ' * 22
887 return " %-4s %-16s" % (format_time_interval(now - t),e)
889 displayer.realstart()
895 s = "%s" % track.myname()
898 if vn is None: s += " not on a vessel?!"
899 else: s += " on board the %s" % vn
900 s += " at %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")
902 tbl = StandingsTable()
905 for pa in track.aboard():
906 pi = pa.pirate_info()
909 if pa.gunner: xs += 'G '
911 xs += timeevent(pa.last_time, pa.last_event)
912 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
915 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
923 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
925 #---------- main program ----------
931 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
933 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
934 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
935 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
936 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
937 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
939 display modes (for --display) apply to ship-aid:
940 --display=dumb just print new information, scrolling the screen
941 --display=overwrite use cursor motion, selective clear, etc. to redraw at top
944 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
945 help='select ocean OCEAN')
946 ao('--cache-dir', dest='cache_dir', metavar='DIR',
947 default='~/.yoweb-scrape-cache',
948 help='cache yoweb pages in DIR')
949 ao('-D','--debug', action='count', dest='debug', default=0,
950 help='enable debugging output')
951 ao('--debug-fd', type='int', dest='debug_fd',
952 help='write any debugging output to specified fd')
953 ao('-q','--quiet', action='store_true', dest='quiet',
954 help='suppress warning output')
955 ao('--display', action='store', dest='display',
956 type='choice', choices=['dumb','overwrite'],
957 help='how to display ship aid')
959 ao('--ship-duty', action='store_true', dest='ship_duty',
960 help='show ship duty station puzzles')
961 ao('--all-puzzles', action='store_false', dest='ship_duty',
962 help='show all puzzles, not just ship duty stations')
964 (opts,args) = pa.parse_args()
968 pa.error('need a mode argument')
970 if opts.debug_fd is not None:
971 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
973 opts.debug_file = sys.stdout
976 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
977 try: mode_fn = globals()[mode_fn_name]
978 except KeyError: pa.error('unknown mode "%s"' % mode)
981 opts.min_max_age = 60
982 opts.expire_age = 3600
983 opts.ship_reboard_clearout = 3600
985 if opts.cache_dir.startswith('~/'):
986 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
988 if opts.display is None:
989 if ((opts.debug > 0 and opts.debug_fd is None)
990 or not os.isatty(sys.stdout.fileno())):
991 opts.display = 'dumb'
993 opts.display = 'overwrite'
995 fetcher = Fetcher(opts.ocean, opts.cache_dir)
997 mode_fn(args[1:], pa.error)