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)
49 from optparse import OptionParser
50 from StringIO import StringIO
52 from BeautifulSoup import BeautifulSoup
56 #---------- YPP parameters and arrays ----------
58 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
59 '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
60 '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
61 '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
65 ['Sailing','Rigging'],
70 duty_puzzles = ([ 'Navigating', 'Battle Navigation' ] +
74 standingvals = ('Able/Proficient/Distinguished/Respected/Master'+
75 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
76 standing_limit = len(standingvals)
78 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
80 max_pirate_namelen = 12
83 #---------- general utilities ----------
87 print >>opts.debug_file, m
91 opts.debug_file.flush()
97 def format_time_interval(ti):
98 if ti < 120: return '%d:%02d' % (ti / 60, ti % 60)
99 if ti < 7200: return '%2dm' % (ti / 60)
100 if ti < 86400: return '%dh' % (ti / 3600)
101 return '%dd' % (ti / 86400)
104 lib = os.getenv("YPPSC_YARRG_SRCBASE")
105 if lib is not None: return lib
107 lib = regexp.sub('/[^/]+$', '', lib)
108 os.environ["YPPSC_YARRG_SRCBASE"] = lib
111 soup_massage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
113 (regexp.compile('(\<td.*") ("center")'),
114 lambda m: m.group(1)+' align='+m.group(2))
117 def make_soup(*args, **kwargs):
118 return BeautifulSoup(*args,
119 convertEntities=BeautifulSoup.HTML_ENTITIES,
120 markupMassage=soup_massage,
123 #---------- caching and rate-limiting data fetcher ----------
126 def __init__(self, cachedir):
127 debug('Fetcher init %s' % cachedir)
128 self.cachedir = cachedir
129 try: os.mkdir(cachedir)
130 except (OSError,IOError), oe:
131 if oe.errno != errno.EEXIST: raise
132 self._cache_scan(time.time())
134 def _cache_scan(self, now):
135 # returns list of ages, unsorted
137 debug('Fetcher scan_cache')
138 for leaf in os.listdir(self.cachedir):
139 if not leaf.startswith('#'): continue
140 path = self.cachedir + '/' + leaf
141 try: s = os.stat(path)
142 except (OSError,IOError), oe:
143 if oe.errno != errno.ENOENT: raise
145 age = now - s.st_mtime
146 if age > opts.expire_age:
147 debug('Fetcher expire %d %s' % (age, path))
149 except (OSError,IOError), oe:
150 if oe.errno != errno.ENOENT: raise
155 def need_wait(self, now, imaginary=[]):
156 ages = self._cache_scan(now)
159 debug('Fetcher ages ' + `ages`)
163 if age < min_age and age <= 5:
164 debug('Fetcher morewait min=%d age=%d' %
166 need_wait = max(need_wait, min_age - age)
169 need_wait += random.random() - 0.5
172 def _rate_limit_cache_clean(self, now):
173 need_wait = self.need_wait(now)
175 debug('Fetcher wait %f' % need_wait)
178 def fetch(self, url, max_age):
179 debug('Fetcher fetch %s' % url)
180 cache_corename = urllib.quote_plus(url)
181 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
182 try: f = file(cache_item, 'r')
183 except (OSError,IOError), oe:
184 if oe.errno != errno.ENOENT: raise
187 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
189 s = os.fstat(f.fileno())
190 age = now - s.st_mtime
192 debug('Fetcher stale %d < %d'% (max_age, age))
197 debug('Fetcher cached %d > %d' % (max_age, age))
200 debug('Fetcher fetch')
201 self._rate_limit_cache_clean(now)
203 stream = urllib2.urlopen(url)
205 cache_tmp = "%s/#%s~%d#" % (
206 self.cachedir, cache_corename, os.getpid())
207 f = file(cache_tmp, 'w')
210 os.rename(cache_tmp, cache_item)
211 debug('Fetcher stored')
214 class Yoweb(Fetcher):
215 def __init__(self, ocean, cachedir):
216 debug('Yoweb init %s' % cachedir)
218 Fetcher.__init__(self, cachedir)
220 def default_ocean(self, ocean='ice'):
221 if self.ocean is None:
224 def yoweb(self, kind, tail, max_age):
227 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
228 self.ocean, kind, tail)
229 return self.fetch(url, max_age)
231 class Yppedia(Fetcher):
232 def __init__(self, cachedir):
233 debug('Yoweb init %s' % cachedir)
234 self.base = 'http://yppedia.puzzlepirates.com/'
235 self.localhtml = opts.localhtml
236 Fetcher.__init__(self, cachedir)
238 def __call__(self, rhs):
239 if self.localhtml is None:
240 url = self.base + rhs
241 debug('Yppedia retrieving YPP '+url);
242 return self.fetch(url, 3000)
244 return file(opts.localhtml + '/' + rhs, 'r')
246 #---------- logging assistance for troubled screenscrapers ----------
253 def soupm(self, obj, m):
254 self.msg(m + '; in ' + `obj`)
255 def needs_msgs(self, child_souplog):
256 self.msgs += child_souplog.msgs
257 child_souplog.msgs = [ ]
260 str = ''.join(obj.findAll(text=True))
263 class SomethingSoupInfo(SoupLog):
264 def __init__(self, kind, tail, max_age):
265 SoupLog.__init__(self)
266 html = fetcher.yoweb(kind, tail, max_age)
267 self._soup = make_soup(html)
269 #---------- scraper for pirate pages ----------
271 class PirateInfo(SomethingSoupInfo):
272 # Public data members:
273 # pi.standings = { 'Treasure Haul': 'Able' ... }
275 # pi.crew = (id, name)
276 # pi.flag = (id, name)
277 # pi.msgs = [ 'message describing problem with scrape' ]
279 def __init__(self, pirate, max_age=300):
280 SomethingSoupInfo.__init__(self,
281 'pirate.wm?target=', pirate, max_age)
283 self._find_standings()
284 self.crew = self._find_crewflag('crew',
285 '^/yoweb/crew/info\\.wm')
286 self.flag = self._find_crewflag('flag',
287 '^/yoweb/flag/info\\.wm')
289 def _find_standings(self):
290 imgs = self._soup.findAll('img',
291 src=regexp.compile('/yoweb/images/stat.*'))
293 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
297 for skill in puzzles:
298 standings[skill] = [ ]
303 try: puzzle = img['alt']
304 except KeyError: continue
306 if not puzzle in puzzles:
307 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
309 key = img.findParent('td')
311 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
313 valelem = key.findNextSibling('td')
315 skl.soupm(key, 'puzzle missing sibling "%s"'
318 valstr = soup_text(valelem)
319 match = re.match(valstr)
321 skl.soupm(key, ('puzzle "%s" unparseable'+
322 ' standing "%s"') % (puzzle, valstr))
324 standing = match.group(match.lastindex)
325 standings[puzzle].append(standing)
329 for puzzle in puzzles:
330 sl = standings[puzzle]
332 skl.msg('puzzle "%s" multiple standings %s' %
336 skl.msg('puzzle "%s" no standing found' % puzzle)
339 for i in range(0, standing_limit):
340 if standing == standingvals[i]:
341 self.standings[puzzle] = i
342 if not puzzle in self.standings:
343 skl.msg('puzzle "%s" unknown standing "%s"' %
346 all_standings_ok = True
347 for puzzle in puzzles:
348 if not puzzle in self.standings:
351 def _find_crewflag(self, cf, yoweb_re):
352 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
354 self.msg('zero or several %s id references found' % cf)
357 id_re = '\\b%sid\\=(\\w+)$' % cf
358 id_haystack = thing['href']
359 match = regexp.compile(id_re).search(id_haystack)
361 self.soupm(thing, ('incomprehensible %s id ref'+
362 ' (%s in %s)') % (cf, id_re, id_haystack))
364 name = soup_text(thing)
365 return (match.group(1), name)
368 return `(self.crew, self.flag, self.standings, self.msgs)`
370 #---------- scraper for crew pages ----------
372 class CrewInfo(SomethingSoupInfo):
373 # Public data members:
375 # ci.crew = [ ('Captain', ['Pirate', ...]),
376 # ('Senior Officer', [...]),
378 # pi.msgs = [ 'message describing problem with scrape' ]
380 def __init__(self, crewid, max_age=300):
382 SomethingSoupInfo.__init__(self,
383 'crew/info.wm?crewid=', crewid, max_age)
386 def _find_crew(self):
388 capts = self._soup.findAll('img',
389 src='/yoweb/images/crew-captain.png')
391 self.msg('crew members: no. of captain images != 1')
394 while not tbl.find('a', href=pirate_ref_re):
395 tbl = tbl.findParent('table')
397 self.msg('crew members: cannot find table')
399 current_rank_crew = None
400 crew_rank_re = regexp.compile('/yoweb/images/crew')
401 for row in tbl.contents:
402 # findAll(recurse=False)
403 if isinstance(row,basestring):
406 is_rank = row.find('img', attrs={'src': crew_rank_re})
408 rank = soup_text(row)
409 current_rank_crew = []
410 self.crew.append((rank, current_rank_crew))
412 for cell in row.findAll('a', href=pirate_ref_re):
413 if current_rank_crew is None:
414 self.soupm(cell, 'crew members: crew'
417 current_rank_crew.append(soup_text(cell))
420 return `(self.crew, self.msgs)`
422 class FlagRelation():
423 # Public data members (put there by hand by creater)
428 # other_declaring_min
429 # other_declaring_max
430 # where {this,other}_declaring{,_min,_max} are:
431 # -1 {this,other} is declaring war
432 # 0 {this,other} is not doing either
433 # +1 {this,other} is allying
435 return '<FlagRelation %s %d/%d..%d %s %s>' % (
436 self.yoweb_heading, self.this_declaring,
437 self.other_declaring_min, self.other_declaring_max,
438 self.other_flagname, self.other_flagid)
440 class FlagInfo(SomethingSoupInfo):
441 # Public data members (after init):
446 # relations[n] = FlagRelation
447 # relation_byname[otherflagname] = relations[some_n]
448 # relation_byid[otherflagname] = relations[some_n]
450 # islands[n] = (islandname, islandid)
452 def __init__(self, flagid, max_age=600):
454 SomethingSoupInfo.__init__(self,
455 'flag/info.wm?flagid=', flagid, max_age)
458 def _find_flag(self):
459 font2 = self._soup.find('font',{'size':'+2'})
460 self.name = font2.find('b').contents[0]
463 self.relation_byname = { }
464 self.relation_byid = { }
467 magnate = self._soup.find('img',{'src':
468 '/yoweb/images/repute-MAGNATE.png'})
469 warinfo = (magnate.findParent('table').findParent('tr').
470 findNextSibling('tr').findNext('td',{'align':'left'}))
473 print >>sys.stderr, 'WARNING: '+m
475 def wi_warn(head, waritem):
476 warn('unknown warmap item: %s: %s' %
477 (`head`, ``waritem``))
479 def wihelp_item(waritem, thing):
480 url = waritem.get('href', None)
482 return ('no url for '+thing,None,None)
483 m = regexp.search('\?'+thing+'id=(\d+)$', url)
484 if not m: return ('no '+thing+'id',None,None)
486 tname = waritem.string
488 return (thing+' name not just string',None,None)
489 return (None,tid,tname)
491 def wi_alwar(head, waritem, thisdecl, othermin, othermax):
492 (err,flagid,flagname) = wihelp_item(waritem,'flag')
494 rel = self.relation_byid.get(flagid, None)
495 if rel: return 'flag id twice!'
496 if flagname in self.relation_byname:
497 return 'flag name twice!'
499 rel.other_flagname = flagname
500 rel.other_flagid = flagid
501 rel.yoweb_heading = head
502 rel.this_declaring = thisdecl
503 rel.other_declaring_min = othermin
504 rel.other_declaring_max = othermax
505 self.relations.append(rel)
506 self.relation_byid[flagid] = rel
507 self.relation_byname[flagid] = rel
509 def wi_isle(head, waritem):
510 (err,isleid,islename) = wihelp_item(waritem,'island')
512 self.islands.append((isleid,islename))
515 'Allied with': (wi_alwar,+1,+1,+1),
516 'Declaring war against': (wi_alwar,-1, 0,+1),
517 'At war with': (wi_alwar,-1,-1,-1),
518 'Trying to form an alliance with': (wi_alwar,+1,-1,0),
519 'Islands controlled by this flag': (wi_isle,),
522 how = (wi_warn, None)
524 for waritem in warinfo.findAll(['font','a']):
525 if waritem is None: break
526 if waritem.name == 'font':
527 colour = waritem.get('color',None)
528 if colour.lstrip('#') != '958A5F':
529 warn('strange colour %s in %s' %
530 (colour,``waritem``))
532 head = waritem.string
534 warn('no head string in '+``waritem``)
536 head = regexp.sub('\\s+', ' ', head).strip()
537 head = head.rstrip(':')
538 how = (head,) + warmap.get(head, (wi_warn,))
540 assert(waritem.name == 'a')
542 debug('WARHOW %s(%s, waritem, *%s)' %
543 (how[1], `how[0]`, `how[2:]`))
544 bad = how[1](how[0], waritem, *how[2:])
546 warn('bad waritem %s: %s: %s' % (`how[0]`,
550 return `(self.name, self.islands, self.relations)`
552 #---------- scraper for ocean info incl. embargoes etc. ----------
554 class IslandBasicInfo():
555 # Public data attributes:
558 # Public data attributes maybe set by caller:
560 def __init__(self, ocean, islename):
564 def q(x): return urllib.quote(x.replace(' ','_'))
565 url_rhs = q(self.name) + '_(' + q(self.ocean) + ')'
566 return yppedia(url_rhs)
568 return `(self.ocean, self.name)`
570 class IslandExtendedInfo(IslandBasicInfo):
571 # Public data attributes (inherited):
574 # Public data attributes (additional):
578 def __init__(self, ocean, islename):
579 IslandBasicInfo.__init__(self, ocean, islename)
581 self.yoweb_url = None
582 self._collect_yoweb()
583 self._collect_flagid()
585 def _collect_yoweb(self):
586 debug('IEI COLLECT YOWEB '+`self.name`)
588 self.yoweb_url = None
590 soup = make_soup(self.yppedia())
591 content = soup.find('div', attrs = {'id': 'content'})
592 yoweb_re = regexp.compile('^http://\w+\.puzzlepirates\.com/'+
593 'yoweb/island/info\.wm\?islandid=(\d+)$')
594 a = soup.find('a', attrs = { 'href': yoweb_re })
596 debug('IEI COLLECT YOWEB '+`self.name`+' NONE')
599 debug('IEI COLLECT YOWEB '+`self.name`+' GOT '+``a``)
600 self.yoweb_url = a['href']
601 m = yoweb_re.search(self.yoweb_url)
602 self.islandid = m.group(1)
604 def _collect_flagid(self):
608 debug('IEI COLLECT FLAGID '+`self.name`+' URL '+`yo`)
609 if yo is None: return None
610 dataf = fetcher.fetch(yo, 1800)
611 soup = make_soup(dataf)
612 ruler_re = regexp.compile(
613 '/yoweb/flag/info\.wm\?flagid=(\d+)$')
614 ruler = soup.find('a', attrs = { 'href': ruler_re })
616 debug('IEI COLLECT FLAGID '+`self.name`+' NONE')
618 debug('IEI COLLECT FLAGID '+`self.name`+' GOT '+``ruler``)
619 m = ruler_re.search(ruler['href'])
620 self.flagid = m.group(1)
623 return `(self.ocean, self.islandid, self.name,
624 self.yoweb_url, self.flagid)`
626 class IslandFlagInfo(IslandExtendedInfo):
627 # Public data attributes (inherited):
633 # Public data attributes (additional):
635 def __init__(self, ocean, islename):
636 IslandExtendedInfo.__init__(self, ocean, islename)
640 def _collect_flag(self):
641 if self.flagid is None: return
642 self.flag = FlagInfo(self.flagid, 1800)
645 return IslandExtendedInfo.__str__(self) + '; ' + str(self.flag)
647 class NullProgressReporter():
648 def doing(self, msg): pass
651 class TypewriterProgressReporter():
655 self._doing(m + '...')
659 less = self._l - len(m)
661 self._write(' ' * less)
662 self._write('\b' * less)
672 # Public data attributes:
673 # oi.islands[islename] = IslandInfo(...)
674 # oi.arches[archname][islename] = IslandInfo(...)
675 def __init__(self, isleclass=IslandBasicInfo):
676 self.isleclass = isleclass
677 self.ocean = fetcher.ocean.lower().capitalize()
679 progressreporter.doing('fetching ocean info')
681 cmdl = ['./yppedia-ocean-scraper']
682 if opts.localhtml is not None:
683 cmdl += ['--local-html-dir',opts.localhtml]
685 debug('OceanInfo collect running ' + `cmdl`)
686 oscraper = subprocess.Popen(
688 stdout = subprocess.PIPE,
689 cwd = yppsc_dir()+'/yarrg',
690 shell=False, stderr=None,
692 h = oscraper.stdout.readline()
693 debug('OceanInfo collect h '+`h`)
694 assert(regexp.match('^ocean ', h))
695 arch_re = regexp.compile('^ (\S.*)')
696 island_re = regexp.compile('^ (\S.*)')
699 assert(oscraper.returncode == 0)
706 progressreporter.doing('parsing ocean info')
708 for l in oscraper.stdout:
709 debug('OceanInfo collect l '+`l`)
711 m = island_re.match(l)
713 assert(archname is not None)
714 islename = m.group(1)
715 isles.append((archname, islename))
719 archname = m.group(1)
720 assert(archname not in self.arches)
721 self.arches[archname] = { }
725 for i in xrange(0, len(isles)-1):
726 (archname, islename) = isles[i]
727 progressreporter.doing(
728 'fetching isle info %2d/%d (%s: %s)'
729 % (i, len(isles), archname, islename))
730 isle = self.isleclass(self.ocean, islename)
732 self.islands[islename] = isle
733 self.arches[archname][islename] = isle
736 return `(self.islands, self.arches)`
738 #---------- pretty-printer for tables of pirate puzzle standings ----------
740 class StandingsTable:
741 def __init__(self, f, use_puzzles=None, col_width=6, gap_every=5):
742 if use_puzzles is None:
744 use_puzzles=duty_puzzles
747 self._puzzles = use_puzzles
749 self._cw = col_width-1
750 self._gap_every = gap_every
754 def _nl(self): self._o('\n')
756 def _pline(self, lhs, puzstrs, extra):
757 if (self._linecount > 0
758 and self._gap_every is not None
759 and not (self._linecount % self._gap_every)):
761 self._o('%-*s' % (max(max_pirate_namelen+1, 15), lhs))
763 self._o(' %-*.*s' % (self._cw,self._cw, v))
769 def _puzstr(self, pi, puzzle):
770 if not isinstance(puzzle,list): puzzle = [puzzle]
771 try: standing = max([pi.standings[p] for p in puzzle])
772 except KeyError: return '?'
773 if not standing: return ''
776 c1 = standingvals[standing][0]
777 if standing < 3: c1 = c1.lower() # 3 = Master
781 s += '*' * (standing / 2)
782 s += '+' * (standing % 2)
785 def headings(self, lhs='', rhs=None):
786 def puzn_redact(name):
787 if isinstance(name,list):
789 ["%.*s" % (self._cw/2, puzn_redact(n))
792 if spc < 0: return name
793 return name[0:min(4,spc)] + name[spc+1:]
795 self._pline(lhs, map(puzn_redact, self._puzzles), rhs)
797 def literalline(self, line):
801 def pirate_dummy(self, name, standingstring, extra=None):
802 standings = standingstring * len(self._puzzles)
803 self._pline(' '+name, standings, extra)
804 def pirate(self, pi, extra=None):
805 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
806 self._pline(' '+pi.name, puzstrs, extra)
809 #---------- chat log parser ----------
812 # This is essentially a transparent, dumb, data class.
822 # Also used for jobbing applicants:
823 # happens when expires (to "-")
824 # - disembark, leaves crew no
825 # aboard evidence of them being aboard no
826 # applied "has applied for the job" 120s, configurable
827 # ashore "has taken a job" 30min, configurable
828 # declined "declined the job offer" 30s, configurable
829 # invited "has been invited to job" 120s, configurable
831 # pa.jobber None, 'ashore', 'applied', 'invited', 'declined'
832 # pa.expires expiry time time
834 def __init__(pa, pn, v, time, event):
838 pa.last_event = event
839 pa.last_chat_time = None
840 pa.last_chat_chan = None
849 age = now - pa.pi_fetched
850 guide = random.randint(120,240)
853 debug('PirateAboard refresh %d > %d %s' % (
854 age, guide, pa.name))
858 wait = fetcher.need_wait(now, imaginary)
860 debug('PirateAboard fetcher not ready %d' % wait)
862 pa.pi = PirateInfo(pa.name, 600)
866 class ChatLogTracker:
867 # This is quite complex so we make it opaque. Use the
868 # official invokers, accessors etc.
870 def __init__(self, myself_pi, logfn):
871 self._pl = {} # self._pl['Pirate'] =
872 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
873 # self._vl['Vessel']['#lastinfo']
874 # self._vl['Vessel']['#name']
875 # self._v = self._vl[self._vessel]
877 self._myself = myself_pi
879 self._f = file(logfn)
880 flen = os.fstat(self._f.fileno()).st_size
882 if flen > max_backlog:
883 startpos = flen - max_backlog
884 self._f.seek(startpos)
886 self._progress = [0, flen - self._f.tell()]
887 self._disembark_myself()
888 self._need_redisplay = False
889 self._lastvessel = None
891 def _disembark_myself(self):
894 self.force_redisplay()
896 def force_redisplay(self):
897 self._need_redisplay = True
899 def _vessel_updated(self, v, timestamp):
901 v['#lastinfo'] = timestamp
902 self.force_redisplay()
904 def _onboard_event(self,v,timestamp,pirate,event,jobber=None):
905 pa = self._pl.get(pirate, None)
906 if pa is not None and pa.v is v:
907 pa.last_time = timestamp
908 pa.last_event = event
910 if pa is not None and pa.v is not None:
912 pa = PirateAboard(pirate, v, timestamp, event)
913 self._pl[pirate] = pa
914 if v is not None: v[pirate] = pa
917 if jobber is None: timeout = None
918 else: timeout = getattr(opts, 'timeout_'+jobber)
919 if timeout is None: pa.expires = None
920 else: pa.expires = timestamp + timeout
921 self._vessel_updated(v, timestamp)
924 def _expire_jobbers(self, now):
925 for pa in self._pl.values():
926 if pa.expires is None: continue
927 if pa.expires >= now: continue
929 del self._pl[pa.name]
930 if v is not None: del v[pa.name]
931 self.force_redisplay()
933 def _trash_vessel(self, v):
935 if pn.startswith('#'): continue
939 if v is self._v: self._disembark_myself()
940 self.force_redisplay()
942 def _vessel_stale(self, v, timestamp):
943 return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
945 def _vessel_check_expire(self, v, timestamp):
946 if not self._vessel_stale(v, timestamp):
948 self._debug_line_disposition(timestamp,'',
949 'stale-reset ' + v['#name'])
950 self._trash_vessel(v)
953 def expire_garbage(self, timestamp):
954 for v in self._vl.values():
955 self._vessel_check_expire(v, timestamp)
957 def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
958 v = self._vl.get(vn, None)
960 v = self._vessel_check_expire(v, timestamp)
967 self._vl[vn] = v = { '#name': vn }
968 self._vessel_updated(v, timestamp)
971 def _find_matching_vessel(self, pattern, timestamp, cmdr,
972 dml=[], create=False):
973 # use when a commander pirate `cmdr' specified a vessel
974 # by name `pattern' (either may be None)
975 # if create is true, will create the vessel
976 # record if an exact name is specified
978 if (pattern is not None and
980 and len(pattern.split(' ')) == 2):
983 return self._vessel_lookup(
984 vn, timestamp, dml=dml, create=create)
987 pattern_check = lambda vn: True
989 re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
990 pattern_check = regexp.compile(re, regexp.I).match
994 cmdr_pa = self._pl.get(cmdr, None)
995 if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
997 tries.append((self._v, 'here'))
1000 for (v, dm) in tries:
1001 if v is None: dml.append(dm+'?'); continue
1004 if not pattern_check(vn):
1005 tried_vns.append(vn)
1012 if pattern is not None and '*' in pattern:
1015 for (vn,v) in self._vl.iteritems()
1016 if not self._vessel_stale(v, timestamp)
1017 if pattern_check(vn)
1019 #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
1021 # '/'.join(tried_vns),
1022 # '/'.join([vn for (vn,v) in search])))
1032 def _debug_line_disposition(self,timestamp,l,m):
1033 debug('CLT %13s %-40s %s' % (timestamp,m,l))
1035 def _rm_crew_l(self,re,l):
1036 m = regexp.match(re,l)
1037 if m and m.group(2) == self._myself.crew[1]:
1042 def local_command(self, metacmd):
1043 # returns None if all went well, or problem message
1044 return self._command(self._myself.name, metacmd,
1045 "local", time.time(),
1046 (lambda m: debug('CMD %s' % metacmd)))
1048 def _command(self, cmdr, metacmd, chan, timestamp, d):
1049 # returns None if all went well, or problem message
1050 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
1052 '/([adj]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
1054 if not m2: return "unknown syntax or command"
1056 (cmd, pattern, targets) = m2.groups()
1057 dml = ['cmd', chan, cmd]
1059 if cmd == 'a': each = self._onboard_event
1060 elif cmd == 'd': each = disembark
1061 else: each = lambda *l: self._onboard_event(*l,
1062 **{'jobber':'applied'})
1064 if cmdr == self._myself.name:
1066 how = 'cmd: %s' % cmd
1069 how = 'cmd: %s %s' % (cmd,cmdr)
1072 if pattern is not None:
1073 return "/j command does not take a vessel"
1076 v = self._find_matching_vessel(
1077 pattern, timestamp, cmdr,
1080 if cmd == 'j' or v is not None:
1081 targets = targets.strip().split(' ')
1082 dml.append(`len(targets)`)
1083 for target in targets:
1084 each(v, timestamp, target.title(), how)
1085 self._vessel_updated(v, timestamp)
1092 def chatline(self,l):
1093 rm = lambda re: regexp.match(re,l)
1094 d = lambda m: self._debug_line_disposition(timestamp,l,m)
1095 rm_crew = lambda re: self._rm_crew_l(re,l)
1098 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
1100 self._date = [int(x) for x in m.groups()]
1101 self._previous_timestamp = None
1102 return d('date '+`self._date`)
1104 if self._date is None:
1105 return d('date unset')
1107 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
1109 return d('no timestamp')
1112 time_tuple = (self._date +
1113 [int(x) for x in m.groups()] +
1115 timestamp = time.mktime(time_tuple)
1116 if timestamp >= self._previous_timestamp: break
1118 self._debug_line_disposition(timestamp,'',
1119 'new date '+`self._date`)
1121 self._previous_timestamp = timestamp
1123 l = l[l.find(' ')+1:]
1125 def ob_x(pirate,event):
1126 return self._onboard_event(
1127 self._v, timestamp, pirate, event)
1128 def ob1(did): ob_x(m.group(1), did); return d(did)
1129 def oba(did): return ob1('%s %s' % (did, m.group(2)))
1131 def jb(pirate,jobber):
1132 return self._onboard_event(
1133 None, timestamp, pirate,
1134 ("jobber %s" % jobber),
1138 def disembark(v, timestamp, pirate, event):
1139 self._onboard_event(
1140 v, timestamp, pirate, 'leaving '+event)
1142 del self._pl[pirate]
1144 def disembark_me(why):
1145 self._disembark_myself()
1146 return d('disembark-me '+why)
1148 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
1151 pn = self._myself.name
1153 v = self._vessel_lookup(vn, timestamp, dm, create=True)
1154 self._lastvessel = self._vessel = vn
1156 ob_x(pn, 'we boarded')
1157 self.expire_garbage(timestamp)
1158 return d(' '.join(dm))
1161 return d('no vessel')
1163 m = rm('(\\w+) has come aboard\\.$')
1164 if m: return ob1('boarded');
1166 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
1168 (who,what) = m.groups()
1169 pa = ob_x(who,'ord '+what)
1170 if what == 'Gunning':
1172 return d('duty order')
1174 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
1175 if m: oba('stopped'); return d("end")
1177 def chat_core(speaker, chan):
1178 try: pa = self._pl[speaker]
1179 except KeyError: return 'mystery'
1180 if pa.v is not None and pa.v is not self._v:
1182 pa.last_chat_time = timestamp
1183 pa.last_chat_chan = chan
1184 self.force_redisplay()
1188 speaker = m.group(1)
1189 dm = chat_core(speaker, chan)
1190 return d('chat %s %s' % (chan, dm))
1192 def chat_metacmd(chan):
1193 (cmdr, metacmd) = m.groups()
1194 whynot = self._command(
1195 cmdr, metacmd, chan, timestamp, d)
1196 if whynot is not None:
1199 chat_core(cmdr, 'cmd '+chan)
1201 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
1202 if m: return ob1('general order');
1204 m = rm('(\\w+) says, "')
1205 if m: return chat('public')
1207 m = rm('(\\w+) tells ye, "')
1208 if m: return chat('private')
1210 m = rm('Ye told (\\w+), "(.*)"$')
1211 if m: return chat_metacmd('private')
1213 m = rm('(\\w+) flag officer chats, "')
1214 if m: return chat('flag officer')
1216 m = rm('(\\w+) officer chats, "(.*)"$')
1217 if m: return chat_metacmd('officer')
1219 m = rm('Ye accepted the offer to job with ')
1220 if m: return disembark_me('jobbing')
1222 m = rm('Ye hop on the ferry and are whisked away ')
1223 if m: return disembark_me('ferry')
1225 m = rm('Whisking away to yer home on the magical winds')
1226 if m: return disembark_me('home')
1228 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
1230 pl = m.group(1).split(', ')
1231 if not self._myself.name in pl:
1232 return d('lost melee')
1234 if ' ' in pn: continue
1235 ob_x(pn,'won melee')
1236 return d('won melee')
1238 m = rm('(\\w+) is eliminated\\!')
1239 if m: return ob1('eliminated in fray');
1241 m = rm('(\\w+) has driven \w+ from the ship\\!')
1242 if m: return ob1('boarder repelled');
1244 m = rm('\w+ has bested (\\w+), and turns'+
1245 ' to the rest of the ship\\.')
1246 if m: return ob1('boarder unrepelled');
1248 pirate = rm_crew("(\\w+) has taken a job with '(.*)'\\.")
1249 if pirate: return jb(pirate, 'ashore')
1251 pirate = rm_crew("(\\w+) has left '(.*)'\\.")
1253 disembark(self._v, timestamp, pirate, 'left crew')
1254 return d('left crew')
1256 m = rm('(\w+) has applied for the posted job\.')
1257 if m: return jb(m.group(1), 'applied')
1259 pirate= rm_crew("(\\w+) has been invited to job for '(.*)'\\.")
1260 if pirate: return jb(pirate, 'invited')
1262 pirate = rm_crew("(\\w+) declined the job offer for '(.*)'\\.")
1263 if pirate: return jb(pirate, 'declined')
1265 m = rm('(\\w+) has left the vessel\.')
1268 disembark(self._v, timestamp, pirate, 'disembarked')
1269 return d('disembarked')
1271 return d('not-matched')
1273 def _str_pa(self, pn, pa):
1274 assert self._pl[pn] == pa
1275 s = ' '*20 + "%s %-*s %13s %-30s %13s %-20s %13s" % (
1276 (' ','G')[pa.gunner],
1277 max_pirate_namelen, pn,
1278 pa.last_time, pa.last_event,
1279 pa.last_chat_time, pa.last_chat_chan,
1281 if pa.expires is not None:
1282 s += " %-5d" % (pa.expires - pa.last_time)
1286 def _str_vessel(self, vn, v):
1287 s = ' vessel %s\n' % vn
1288 s += ' '*20 + "%-*s %13s\n" % (
1289 max_pirate_namelen, '#lastinfo',
1291 assert v['#name'] == vn
1292 for pn in sorted(v.keys()):
1293 if pn.startswith('#'): continue
1296 s += self._str_pa(pn,pa)
1300 s = '''<ChatLogTracker
1303 ''' % (self._myself.name, self._vessel)
1304 assert ((self._v is None and self._vessel is None) or
1305 (self._v is self._vl[self._vessel]))
1306 if self._vessel is not None:
1307 s += self._str_vessel(self._vessel, self._v)
1308 for vn in sorted(self._vl.keys()):
1309 if vn == self._vessel: continue
1310 s += self._str_vessel(vn, self._vl[vn])
1314 if pa.v is not None:
1315 assert pa.v[p] is pa
1316 assert pa.v in self._vl.values()
1318 s += self._str_pa(pa.name, pa)
1322 def catchup(self, progress=None):
1324 more = self._f.readline()
1327 self._progress[0] += len(more)
1328 if progress: progress.progress(*self._progress)
1331 if self._lbuf.endswith('\n'):
1332 self.chatline(self._lbuf.rstrip())
1335 debug(self.__str__())
1336 self._expire_jobbers(time.time())
1338 if progress: progress.caughtup()
1341 rv = self._need_redisplay
1342 self._need_redisplay = False
1345 # returns our pirate name
1346 return self._myself.name
1347 def vesselname(self):
1348 # returns the vessel name we're aboard or None
1350 def lastvesselname(self):
1351 # returns the last vessel name we were aboard or None
1352 return self._lastvessel
1353 def aboard(self, vesselname=True):
1354 # returns a list of PirateAboard the vessel
1355 # sorted by pirate name
1356 # you can pass this None and you'll get []
1357 # or True for the current vessel (which is the default)
1358 # the returned value is a fresh list of persistent
1359 # PirateAboard objects
1360 if vesselname is True: v = self._v
1361 else: v = self._vl.get(vesselname.title())
1362 if v is None: return []
1364 for pn in sorted(v.keys())
1365 if not pn.startswith('#') ]
1367 # returns a the jobbers' PirateAboards,
1368 # sorted by jobber class and reverse of expiry time
1370 for pa in self._pl.values()
1371 if pa.jobber is not None
1374 return (pa.jobber, -pa.expires)
1375 l.sort(key = compar_key)
1378 #---------- implementations of actual operation modes ----------
1380 def do_pirate(pirates, bu):
1382 for pirate in pirates:
1383 info = PirateInfo(pirate)
1384 print '%s: %s,' % (`pirate`, info)
1387 def prep_crewflag_of(args, bu, max_age, selector, constructor):
1388 if len(args) != 1: bu('crew-of etc. take one pirate name')
1389 pi = PirateInfo(args[0], max_age)
1391 if cf is None: return None
1392 return constructor(cf[0], max_age)
1394 def prep_crew_of(args, bu, max_age=300):
1395 return prep_crewflag_of(args, bu, max_age,
1396 (lambda pi: pi.crew), CrewInfo)
1398 def prep_flag_of(args, bu, max_age=300):
1399 return prep_crewflag_of(args, bu, max_age,
1400 (lambda pi: pi.flag), FlagInfo)
1402 def do_crew_of(args, bu):
1403 ci = prep_crew_of(args, bu)
1406 def do_flag_of(args, bu):
1407 fi = prep_flag_of(args, bu)
1410 def do_standings_crew_of(args, bu):
1411 ci = prep_crew_of(args, bu, 60)
1412 tab = StandingsTable(sys.stdout)
1414 for (rank, members) in ci.crew:
1415 if not members: continue
1417 tab.literalline('%s:' % rank)
1419 pi = PirateInfo(p, random.randint(900,1800))
1422 def do_ocean(args, bu):
1423 if (len(args)): bu('ocean takes no further arguments')
1424 fetcher.default_ocean()
1425 oi = OceanInfo(IslandFlagInfo)
1427 for islename in sorted(oi.islands.keys()):
1428 isle = oi.islands[islename]
1431 def do_embargoes(args, bu):
1432 if (len(args)): bu('ocean takes no further arguments')
1433 fetcher.default_ocean()
1434 oi = OceanInfo(IslandFlagInfo)
1435 wr = sys.stdout.write
1436 print ('EMBARGOES: Island | Owning flag'+
1437 ' | Embargoed flags')
1439 def getflname(isle):
1440 if isle.islandid is None: return 'uncolonisable'
1441 if isle.flag is None: return 'uncolonised'
1442 return isle.flag.name
1444 progressreporter.stop()
1446 for archname in sorted(oi.arches.keys()):
1447 print 'ARCHIPELAGO: ',archname
1448 for islename in sorted(oi.arches[archname].keys()):
1449 isle = oi.islands[islename]
1450 wr(' %-20s | ' % isle.name)
1451 flname = getflname(isle)
1452 wr('%-30s | ' % flname)
1454 if flag is None: print ''; continue
1456 for rel in flag.relations:
1457 if rel.this_declaring >= 0: continue
1459 wr(rel.other_flagname)
1463 def do_embargoes_flag_of(args, bu):
1464 progressreporter.doing('fetching flag info')
1465 fi = prep_flag_of(args, bu)
1467 progressreporter.stop()
1468 print 'Pirate is not in a flag.'
1471 oi = OceanInfo(IslandFlagInfo)
1473 progressreporter.stop()
1477 for islename in sorted(oi.islands.keys()):
1478 isle = oi.islands[islename]
1480 if flag is None: continue
1481 for rel in flag.relations:
1482 if rel.this_declaring >= 0: continue
1483 if rel.other_flagid != fi.flagid: continue
1484 if not any: print 'EMBARGOED:'
1486 print " %-30s (%s)" % (islename, flag.name)
1488 print 'No embargoes.'
1494 def do_war_flag_of(args, bu):
1495 fi = prep_flag_of(args, bu)
1500 for certain in [True, False]:
1502 for rel in fi.relations:
1503 if rel.this_declaring >= 0: continue
1504 if (rel.other_declaring_max < 0) != certain: continue
1506 if certain: m = 'SINKING PvP'
1507 else: m = 'RISK OF SINKING PvP'
1508 print '%s (%s):' % (m, rel.yoweb_heading)
1511 print " ", rel.other_flagname
1513 print 'No sinking PvP.'
1515 #----- modes which use the chat log parser are quite complex -----
1517 class ProgressPrintPercentage:
1518 def __init__(self, f=sys.stdout):
1520 def progress_string(self,done,total):
1521 return "scan chat logs %3d%%\r" % ((done*100) / total)
1522 def progress(self,*a):
1523 self._f.write(self.progress_string(*a))
1525 def show_init(self, pirate, ocean):
1526 print >>self._f, 'Starting up, %s on the %s ocean' % (
1529 self._f.write(' \r')
1532 def prep_chat_log(args, bu,
1533 progress=ProgressPrintPercentage(),
1534 max_myself_age=3600):
1535 if len(args) != 1: bu('this action takes only chat log filename')
1537 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
1538 match = regexp.match(logfn_re, logfn)
1539 if not match: bu('chat log filename is not in expected format')
1540 (pirate, ocean) = match.groups()
1541 fetcher.default_ocean(ocean)
1543 progress.show_init(pirate, fetcher.ocean)
1544 myself = PirateInfo(pirate,max_myself_age)
1545 track = ChatLogTracker(myself, logfn)
1548 track.catchup(progress)
1551 track.force_redisplay()
1553 return (myself, track)
1555 def do_track_chat_log(args, bu):
1556 (myself, track) = prep_chat_log(args, bu)
1561 sleep(0.5 + 0.5 * random.random())
1563 #----- ship management aid -----
1565 class Display_dumb(ProgressPrintPercentage):
1567 ProgressPrintPercentage.__init__(self)
1570 def realstart(self):
1573 class Display_overwrite(ProgressPrintPercentage):
1575 ProgressPrintPercentage.__init__(self)
1577 null = file('/dev/null','w')
1578 curses.setupterm(fd=null.fileno())
1580 self._clear = curses.tigetstr('clear')
1582 self._debug('missing clear!')
1583 self.show = Display_dumb.show
1586 self._t = {'el':'', 'ed':''}
1587 if not self._init_sophisticated():
1588 for k in self._t.keys(): self._t[k] = ''
1589 self._t['ho'] = self._clear
1591 def _debug(self,m): debug('display overwrite: '+m)
1593 def _init_sophisticated(self):
1594 for k in self._t.keys():
1595 s = curses.tigetstr(k)
1597 self._t['ho'] = curses.tigetstr('ho')
1598 if not self._t['ho']:
1599 cup = curses.tigetstr('cup')
1600 self._t['ho'] = curses.tparm(cup,0,0)
1601 missing = [k for k in self._t.keys() if not self._t[k]]
1603 self.debug('missing '+(' '.join(missing)))
1608 w = sys.stdout.write
1609 def wti(k): w(self._t[k])
1613 for l in s.rstrip().split('\n'):
1622 def realstart(self):
1623 sys.stdout.write(self._clear)
1627 def do_ship_aid(args, bu):
1628 if opts.ship_duty is None: opts.ship_duty = True
1630 displayer = globals()['Display_'+opts.display]()
1632 (myself, track) = prep_chat_log(args, bu, progress=displayer)
1634 displayer.realstart()
1636 if os.isatty(0): kr_create = KeystrokeReader
1637 else: kr_create = DummyKeystrokeReader
1640 kreader = kr_create(0, 10)
1641 ship_aid_core(myself, track, displayer, kreader)
1646 class KeyBasedSorter:
1647 def compar_key_pa(self, pa):
1648 pi = pa.pirate_info()
1649 if pi is None: return None
1650 return self.compar_key(pi)
1651 def lsort_pa(self, l):
1652 l.sort(key = self.compar_key_pa)
1654 class NameSorter(KeyBasedSorter):
1655 def compar_key(self, pi): return pi.name
1656 def desc(self): return 'name'
1658 class SkillSorter(NameSorter):
1659 def __init__(self, relevant):
1660 self._want = frozenset(relevant.split('/'))
1662 for p in core_duty_puzzles:
1663 if isinstance(p,basestring): self._avoid.add(p)
1664 else: self._avoid |= set(p)
1665 self._avoid -= self._want
1666 self._desc = '%s' % relevant
1668 def desc(self): return self._desc
1670 def compar_key(self, pi):
1672 pi.standings.get(puz,-1)
1673 for puz in self._want
1676 -pi.standings.get(puz,standing_limit)
1677 for puz in self._avoid
1680 def negate(x): return -x
1681 debug('compar_key %s bw=%s ba=%s' % (pi.name, `best_want`,
1683 return (-best_want, map(negate, best_avoid), pi.name)
1685 def ship_aid_core(myself, track, displayer, kreader):
1688 vn = track.vesselname()
1689 if vn: return (vn, " on board the %s" % vn)
1690 vn = track.lastvesselname()
1691 if vn: return (vn, " ashore from the %s" % vn)
1692 return (None, " not on a vessel")
1695 if t is None: return ' ' * 22
1696 return " %-4s %-16s" % (format_time_interval(now - t),e)
1698 displayer.show(track.myname() + find_vessel()[1] + '...')
1711 (vn, vs) = find_vessel()
1714 if cliexec is not None:
1716 elif clierr is not None:
1717 s += 'Error: '+clierr
1718 elif clicmd is not None:
1721 s = track.myname() + vs
1722 s += " at %s" % time.strftime("%Y-%m-%d %H:%M:%S")
1727 tbl = StandingsTable(tbl_s)
1729 aboard = track.aboard(vn)
1730 sort.lsort_pa(aboard)
1732 jobbers = track.jobbers()
1734 if track.vesselname(): howmany = 'aboard: %2d' % len(aboard)
1737 tbl.headings(howmany, ' sorted by '+sort.desc())
1741 for pa in aboard + jobbers:
1742 if pa.jobber != last_jobber:
1743 last_jobber = pa.jobber
1745 tbl.literalline('jobbers '+last_jobber)
1747 pi = pa.pirate_info()
1750 if pa.gunner: xs += 'G '
1752 xs += timeevent(pa.last_time, pa.last_event)
1753 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
1756 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
1760 s += tbl_s.getvalue()
1764 if cliexec is not None:
1765 clierr = track.local_command("/"+cliexec.strip())
1771 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
1774 if clierr is not None:
1778 if clicmd is not None:
1779 if k == '\r' or k == '\n':
1782 elif k == '\e' and clicmd != "":
1786 elif k == '\b' or k == '\177':
1787 clicmd = clicmd[ 0 : len(clicmd)-1 ]
1793 elif k == 'g': sort = SkillSorter('Gunning')
1794 elif k == 'c': sort = SkillSorter('Carpentry')
1795 elif k == 's': sort = SkillSorter('Sailing/Rigging')
1796 elif k == 'b': sort = SkillSorter('Bilging')
1797 elif k == 'n': sort = SkillSorter('Navigating')
1798 elif k == 'd': sort = SkillSorter('Battle Navigation')
1799 elif k == 't': sort = SkillSorter('Treasure Haul')
1800 elif k == 'a': sort = NameSorter()
1801 elif k == '/': clicmdbase = ""; clicmd = clicmdbase
1802 elif k == '+': clicmdbase = "a "; clicmd = clicmdbase
1803 else: pass # unknown key command
1805 #---------- individual keystroke input ----------
1807 class DummyKeystrokeReader:
1808 def __init__(self,fd,timeout_dummy): pass
1809 def stop(self): pass
1810 def getch(self): sleep(1); return None
1811 def info(self): return ' [noninteractive]'
1813 class KeystrokeReader(DummyKeystrokeReader):
1814 def __init__(self, fd, timeout_decisec=0):
1816 self._saved = termios.tcgetattr(fd)
1817 a = termios.tcgetattr(fd)
1818 a[3] &= ~(termios.ECHO | termios.ECHONL |
1819 termios.ICANON | termios.IEXTEN)
1820 a[6][termios.VMIN] = 0
1821 a[6][termios.VTIME] = timeout_decisec
1822 termios.tcsetattr(fd, termios.TCSANOW, a)
1824 termios.tcsetattr(self._fd, termios.TCSANOW, self._saved)
1827 byte = os.read(self._fd, 1)
1828 if not len(byte): return None
1833 #---------- main program ----------
1836 global opts, fetcher, yppedia, progressreporter
1839 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
1841 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
1842 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
1843 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
1844 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
1845 yoweb-scrape [--ocean OCEAN ...] ocean|embargoes
1846 yoweb-scrape [--ocean OCEAN ...] war-flag-of|embargoes-flag-of PIRATE
1847 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
1849 display modes (for --display) apply to ship-aid:
1850 --display=dumb just print new information, scrolling the screen
1851 --display=overwrite use cursor motion, selective clear, etc. to redraw at top''')
1853 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
1854 help='select ocean OCEAN')
1855 ao('--cache-dir', dest='cache_dir', metavar='DIR',
1856 default='~/.yoweb-scrape-cache',
1857 help='cache yoweb pages in DIR')
1858 ao('-D','--debug', action='count', dest='debug', default=0,
1859 help='enable debugging output')
1860 ao('--debug-fd', type='int', dest='debug_fd',
1861 help='write any debugging output to specified fd')
1862 ao('-q','--quiet', action='store_true', dest='quiet',
1863 help='suppress warning output')
1864 ao('--display', action='store', dest='display',
1865 type='choice', choices=['dumb','overwrite'],
1866 help='how to display ship aid')
1867 ao('--local-ypp-dir', action='store', dest='localhtml',
1868 help='get yppedia pages from local directory LOCALHTML'+
1869 ' instead of via HTTP')
1871 ao_jt = lambda wh, t: ao(
1872 '--timeout-sa-'+wh, action='store', dest='timeout_'+wh,
1873 default=t, help=('set timeout for expiring %s jobbers' % wh))
1874 ao_jt('applied', 120)
1875 ao_jt('invited', 120)
1876 ao_jt('declined', 30)
1877 ao_jt('ashore', 1800)
1879 ao('--ship-duty', action='store_true', dest='ship_duty',
1880 help='show ship duty station puzzles')
1881 ao('--all-puzzles', action='store_false', dest='ship_duty',
1882 help='show all puzzles, not just ship duty stations')
1884 ao('--min-cache-reuse', type='int', dest='min_max_age',
1885 metavar='SECONDS', default=60,
1886 help='always reuse cache yoweb data if no older than this')
1888 (opts,args) = pa.parse_args()
1892 print >>sys.stderr, copyright_info
1893 pa.error('need a mode argument')
1895 if opts.debug_fd is not None:
1896 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
1898 opts.debug_file = sys.stdout
1901 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
1902 try: mode_fn = globals()[mode_fn_name]
1903 except KeyError: pa.error('unknown mode "%s"' % mode)
1906 opts.expire_age = max(3600, opts.min_max_age)
1908 opts.ship_reboard_clearout = 3600
1910 if opts.cache_dir.startswith('~/'):
1911 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
1913 if opts.display is None:
1914 if ((opts.debug > 0 and opts.debug_fd is None)
1915 or not os.isatty(sys.stdout.fileno())):
1916 opts.display = 'dumb'
1918 opts.display = 'overwrite'
1920 fetcher = Yoweb(opts.ocean, opts.cache_dir)
1921 yppedia = Yppedia(opts.cache_dir)
1923 if opts.debug or not os.isatty(0):
1924 progressreporter = NullProgressReporter()
1926 progressreporter = TypewriterProgressReporter()
1928 mode_fn(args[1:], pa.error)