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 _match_url_normalise(self, url):
135 without_scheme = regexp.sub('^[a-z]+://', '', url)
136 without_tail = regexp.sub('/.*', '', without_scheme)
139 def _cache_scan(self, now, match_url=None):
140 # returns list of ages, unsorted
141 if match_url is not None:
142 match_url = self._match_url_normalise(match_url)
144 debug('Fetcher scan_cache')
145 for leaf in os.listdir(self.cachedir):
146 if not leaf.startswith('#'): continue
147 if match_url is not None:
148 leaf_url = urllib.unquote_plus(leaf.strip('#'))
149 leaf_url = self._match_url_normalise(leaf_url)
150 if leaf_url != match_url:
152 path = self.cachedir + '/' + leaf
153 try: s = os.stat(path)
154 except (OSError,IOError), oe:
155 if oe.errno != errno.ENOENT: raise
157 age = now - s.st_mtime
158 if age > opts.expire_age:
159 debug('Fetcher expire %d %s' % (age, path))
161 except (OSError,IOError), oe:
162 if oe.errno != errno.ENOENT: raise
167 def need_wait(self, now, imaginary=[], next_url=None):
168 ages = self._cache_scan(now, match_url=next_url)
171 debug('Fetcher ages ' + `ages`)
175 if age < min_age and age <= 5:
176 debug('Fetcher morewait min=%d age=%d' %
178 need_wait = max(need_wait, min_age - age)
181 need_wait += random.random() - 0.5
184 def _rate_limit_cache_clean(self, now, next_url=None):
185 need_wait = self.need_wait(now, next_url=next_url)
187 debug('Fetcher wait %f' % need_wait)
190 def fetch(self, url, max_age):
191 debug('Fetcher fetch %s' % url)
192 cache_corename = urllib.quote_plus(url)
193 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
194 try: f = file(cache_item, 'r')
195 except (OSError,IOError), oe:
196 if oe.errno != errno.ENOENT: raise
199 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
201 s = os.fstat(f.fileno())
202 age = now - s.st_mtime
204 debug('Fetcher stale %d < %d'% (max_age, age))
209 debug('Fetcher cached %d > %d' % (max_age, age))
212 debug('Fetcher fetch')
213 self._rate_limit_cache_clean(now, next_url=url)
215 stream = urllib2.urlopen(url)
217 cache_tmp = "%s/#%s~%d#" % (
218 self.cachedir, cache_corename, os.getpid())
219 f = file(cache_tmp, 'w')
222 os.rename(cache_tmp, cache_item)
223 debug('Fetcher stored')
226 class Yoweb(Fetcher):
227 def __init__(self, ocean, cachedir):
228 debug('Yoweb init %s' % cachedir)
230 Fetcher.__init__(self, cachedir)
232 def default_ocean(self, ocean='ice'):
233 if self.ocean is None:
236 def yoweb(self, kind, tail, max_age):
239 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
240 self.ocean, kind, tail)
241 return self.fetch(url, max_age)
243 class Yppedia(Fetcher):
244 def __init__(self, cachedir):
245 debug('Yoweb init %s' % cachedir)
246 self.base = 'http://yppedia.puzzlepirates.com/'
247 self.localhtml = opts.localhtml
248 Fetcher.__init__(self, cachedir)
250 def __call__(self, rhs):
251 if self.localhtml is None:
252 url = self.base + rhs
253 debug('Yppedia retrieving YPP '+url);
254 return self.fetch(url, 3000)
256 return file(opts.localhtml + '/' + rhs, 'r')
258 #---------- logging assistance for troubled screenscrapers ----------
265 def soupm(self, obj, m):
266 self.msg(m + '; in ' + `obj`)
267 def needs_msgs(self, child_souplog):
268 self.msgs += child_souplog.msgs
269 child_souplog.msgs = [ ]
272 str = ''.join(obj.findAll(text=True))
275 class SomethingSoupInfo(SoupLog):
276 def __init__(self, kind, tail, max_age):
277 SoupLog.__init__(self)
278 html = fetcher.yoweb(kind, tail, max_age)
279 self._soup = make_soup(html)
281 #---------- scraper for pirate pages ----------
283 class PirateInfo(SomethingSoupInfo):
284 # Public data members:
285 # pi.standings = { 'Treasure Haul': 'Able' ... }
287 # pi.crew = (id, name)
288 # pi.flag = (id, name)
289 # pi.msgs = [ 'message describing problem with scrape' ]
291 def __init__(self, pirate, max_age=300):
292 SomethingSoupInfo.__init__(self,
293 'pirate.wm?target=', pirate, max_age)
295 self._find_standings()
296 self.crew = self._find_crewflag('crew',
297 '^/yoweb/crew/info\\.wm')
298 self.flag = self._find_crewflag('flag',
299 '^/yoweb/flag/info\\.wm')
301 def _find_standings(self):
302 imgs = self._soup.findAll('img',
303 src=regexp.compile('/yoweb/images/stat.*'))
305 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
309 for skill in puzzles:
310 standings[skill] = [ ]
315 try: puzzle = img['alt']
316 except KeyError: continue
318 if not puzzle in puzzles:
319 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
321 key = img.findParent('td')
323 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
325 valelem = key.findNextSibling('td')
327 skl.soupm(key, 'puzzle missing sibling "%s"'
330 valstr = soup_text(valelem)
331 match = re.match(valstr)
333 skl.soupm(key, ('puzzle "%s" unparseable'+
334 ' standing "%s"') % (puzzle, valstr))
336 standing = match.group(match.lastindex)
337 standings[puzzle].append(standing)
341 for puzzle in puzzles:
342 sl = standings[puzzle]
344 skl.msg('puzzle "%s" multiple standings %s' %
348 skl.msg('puzzle "%s" no standing found' % puzzle)
351 for i in range(0, standing_limit):
352 if standing == standingvals[i]:
353 self.standings[puzzle] = i
354 if not puzzle in self.standings:
355 skl.msg('puzzle "%s" unknown standing "%s"' %
358 all_standings_ok = True
359 for puzzle in puzzles:
360 if not puzzle in self.standings:
363 def _find_crewflag(self, cf, yoweb_re):
364 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
366 self.msg('zero or several %s id references found' % cf)
369 id_re = '\\b%sid\\=(\\w+)$' % cf
370 id_haystack = thing['href']
371 match = regexp.compile(id_re).search(id_haystack)
373 self.soupm(thing, ('incomprehensible %s id ref'+
374 ' (%s in %s)') % (cf, id_re, id_haystack))
376 name = soup_text(thing)
377 return (match.group(1), name)
380 return `(self.crew, self.flag, self.standings, self.msgs)`
382 #---------- scraper for crew pages ----------
384 class CrewInfo(SomethingSoupInfo):
385 # Public data members:
387 # ci.crew = [ ('Captain', ['Pirate', ...]),
388 # ('Senior Officer', [...]),
390 # pi.msgs = [ 'message describing problem with scrape' ]
392 def __init__(self, crewid, max_age=300):
394 SomethingSoupInfo.__init__(self,
395 'crew/info.wm?crewid=', crewid, max_age)
398 def _find_crew(self):
400 capts = self._soup.findAll('img',
401 src='/yoweb/images/crew-captain.png')
403 self.msg('crew members: no. of captain images != 1')
406 while not tbl.find('a', href=pirate_ref_re):
407 tbl = tbl.findParent('table')
409 self.msg('crew members: cannot find table')
411 current_rank_crew = None
412 crew_rank_re = regexp.compile('/yoweb/images/crew')
413 for row in tbl.contents:
414 # findAll(recurse=False)
415 if isinstance(row,basestring):
418 is_rank = row.find('img', attrs={'src': crew_rank_re})
420 rank = soup_text(row)
421 current_rank_crew = []
422 self.crew.append((rank, current_rank_crew))
424 for cell in row.findAll('a', href=pirate_ref_re):
425 if current_rank_crew is None:
426 self.soupm(cell, 'crew members: crew'
429 current_rank_crew.append(soup_text(cell))
432 return `(self.crew, self.msgs)`
434 class FlagRelation():
435 # Public data members (put there by hand by creater)
440 # other_declaring_min
441 # other_declaring_max
442 # where {this,other}_declaring{,_min,_max} are:
443 # -1 {this,other} is declaring war
444 # 0 {this,other} is not doing either
445 # +1 {this,other} is allying
447 return '<FlagRelation %s %d/%d..%d %s %s>' % (
448 self.yoweb_heading, self.this_declaring,
449 self.other_declaring_min, self.other_declaring_max,
450 self.other_flagname, self.other_flagid)
452 class FlagInfo(SomethingSoupInfo):
453 # Public data members (after init):
458 # relations[n] = FlagRelation
459 # relation_byname[otherflagname] = relations[some_n]
460 # relation_byid[otherflagname] = relations[some_n]
462 # islands[n] = (islandname, islandid)
464 def __init__(self, flagid, max_age=600):
466 SomethingSoupInfo.__init__(self,
467 'flag/info.wm?flagid=', flagid, max_age)
470 def _find_flag(self):
471 font2 = self._soup.find('font',{'size':'+2'})
472 self.name = font2.find('b').contents[0]
475 self.relation_byname = { }
476 self.relation_byid = { }
479 magnate = self._soup.find('img',{'src':
480 '/yoweb/images/repute-MAGNATE.png'})
481 warinfo = (magnate.findParent('table').findParent('tr').
482 findNextSibling('tr').findNext('td',{'align':'left'}))
485 print >>sys.stderr, 'WARNING: '+m
487 def wi_warn(head, waritem):
488 warn('unknown warmap item: %s: %s' %
489 (`head`, ``waritem``))
491 def wihelp_item(waritem, thing):
492 url = waritem.get('href', None)
494 return ('no url for '+thing,None,None)
495 m = regexp.search('\?'+thing+'id=(\d+)$', url)
496 if not m: return ('no '+thing+'id',None,None)
498 tname = waritem.string
500 return (thing+' name not just string',None,None)
501 return (None,tid,tname)
503 def wi_alwar(head, waritem, thisdecl, othermin, othermax):
504 (err,flagid,flagname) = wihelp_item(waritem,'flag')
506 rel = self.relation_byid.get(flagid, None)
507 if rel: return 'flag id twice!'
508 if flagname in self.relation_byname:
509 return 'flag name twice!'
511 rel.other_flagname = flagname
512 rel.other_flagid = flagid
513 rel.yoweb_heading = head
514 rel.this_declaring = thisdecl
515 rel.other_declaring_min = othermin
516 rel.other_declaring_max = othermax
517 self.relations.append(rel)
518 self.relation_byid[flagid] = rel
519 self.relation_byname[flagid] = rel
521 def wi_isle(head, waritem):
522 (err,isleid,islename) = wihelp_item(waritem,'island')
524 self.islands.append((isleid,islename))
527 'Allied with': (wi_alwar,+1,+1,+1),
528 'Declaring war against': (wi_alwar,-1, 0,+1),
529 'At war with': (wi_alwar,-1,-1,-1),
530 'Trying to form an alliance with': (wi_alwar,+1,-1,0),
531 'Islands controlled by this flag': (wi_isle,),
534 how = (wi_warn, None)
536 for waritem in warinfo.findAll(['font','a']):
537 if waritem is None: break
538 if waritem.name == 'font':
539 colour = waritem.get('color',None)
540 if colour.lstrip('#') != '958A5F':
541 warn('strange colour %s in %s' %
542 (colour,``waritem``))
544 head = waritem.string
546 warn('no head string in '+``waritem``)
548 head = regexp.sub('\\s+', ' ', head).strip()
549 head = head.rstrip(':')
550 how = (head,) + warmap.get(head, (wi_warn,))
552 assert(waritem.name == 'a')
554 debug('WARHOW %s(%s, waritem, *%s)' %
555 (how[1], `how[0]`, `how[2:]`))
556 bad = how[1](how[0], waritem, *how[2:])
558 warn('bad waritem %s: %s: %s' % (`how[0]`,
562 return `(self.name, self.islands, self.relations)`
564 #---------- scraper for ocean info incl. embargoes etc. ----------
566 class IslandBasicInfo():
567 # Public data attributes:
570 # Public data attributes maybe set by caller:
572 def __init__(self, ocean, islename):
576 def q(x): return urllib.quote(x.replace(' ','_'))
577 url_rhs = q(self.name) + '_(' + q(self.ocean) + ')'
578 return yppedia(url_rhs)
580 return `(self.ocean, self.name)`
582 class IslandExtendedInfo(IslandBasicInfo):
583 # Public data attributes (inherited):
586 # Public data attributes (additional):
590 def __init__(self, ocean, islename):
591 IslandBasicInfo.__init__(self, ocean, islename)
593 self.yoweb_url = None
594 self._collect_yoweb()
595 self._collect_flagid()
597 def _collect_yoweb(self):
598 debug('IEI COLLECT YOWEB '+`self.name`)
600 self.yoweb_url = None
602 soup = make_soup(self.yppedia())
603 content = soup.find('div', attrs = {'id': 'content'})
604 yoweb_re = regexp.compile('^http://\w+\.puzzlepirates\.com/'+
605 'yoweb/island/info\.wm\?islandid=(\d+)$')
606 a = soup.find('a', attrs = { 'href': yoweb_re })
608 debug('IEI COLLECT YOWEB '+`self.name`+' NONE')
611 debug('IEI COLLECT YOWEB '+`self.name`+' GOT '+``a``)
612 self.yoweb_url = a['href']
613 m = yoweb_re.search(self.yoweb_url)
614 self.islandid = m.group(1)
616 def _collect_flagid(self):
620 debug('IEI COLLECT FLAGID '+`self.name`+' URL '+`yo`)
621 if yo is None: return None
622 dataf = fetcher.fetch(yo, 1800)
623 soup = make_soup(dataf)
624 ruler_re = regexp.compile(
625 '/yoweb/flag/info\.wm\?flagid=(\d+)$')
626 ruler = soup.find('a', attrs = { 'href': ruler_re })
628 debug('IEI COLLECT FLAGID '+`self.name`+' NONE')
630 debug('IEI COLLECT FLAGID '+`self.name`+' GOT '+``ruler``)
631 m = ruler_re.search(ruler['href'])
632 self.flagid = m.group(1)
635 return `(self.ocean, self.islandid, self.name,
636 self.yoweb_url, self.flagid)`
638 class IslandFlagInfo(IslandExtendedInfo):
639 # Public data attributes (inherited):
645 # Public data attributes (additional):
647 def __init__(self, ocean, islename):
648 IslandExtendedInfo.__init__(self, ocean, islename)
652 def _collect_flag(self):
653 if self.flagid is None: return
654 self.flag = FlagInfo(self.flagid, 1800)
657 return IslandExtendedInfo.__str__(self) + '; ' + str(self.flag)
659 class NullProgressReporter():
660 def doing(self, msg): pass
663 class TypewriterProgressReporter():
667 self._doing(m + '...')
671 less = self._l - len(m)
673 self._write(' ' * less)
674 self._write('\b' * less)
684 # Public data attributes:
685 # oi.islands[islename] = IslandInfo(...)
686 # oi.arches[archname][islename] = IslandInfo(...)
687 def __init__(self, isleclass=IslandBasicInfo):
688 self.isleclass = isleclass
689 self.ocean = fetcher.ocean.lower().capitalize()
691 progressreporter.doing('fetching ocean info')
693 cmdl = ['./yppedia-ocean-scraper']
694 if opts.localhtml is not None:
695 cmdl += ['--local-html-dir',opts.localhtml]
697 debug('OceanInfo collect running ' + `cmdl`)
698 oscraper = subprocess.Popen(
700 stdout = subprocess.PIPE,
701 cwd = yppsc_dir()+'/yarrg',
702 shell=False, stderr=None,
704 h = oscraper.stdout.readline()
705 debug('OceanInfo collect h '+`h`)
706 assert(regexp.match('^ocean ', h))
707 arch_re = regexp.compile('^ (\S.*)')
708 island_re = regexp.compile('^ (\S.*)')
711 assert(oscraper.returncode == 0)
718 progressreporter.doing('parsing ocean info')
720 for l in oscraper.stdout:
721 debug('OceanInfo collect l '+`l`)
723 m = island_re.match(l)
725 assert(archname is not None)
726 islename = m.group(1)
727 isles.append((archname, islename))
731 archname = m.group(1)
732 assert(archname not in self.arches)
733 self.arches[archname] = { }
737 for i in xrange(0, len(isles)-1):
738 (archname, islename) = isles[i]
739 progressreporter.doing(
740 'fetching isle info %2d/%d (%s: %s)'
741 % (i, len(isles), archname, islename))
742 isle = self.isleclass(self.ocean, islename)
744 self.islands[islename] = isle
745 self.arches[archname][islename] = isle
748 return `(self.islands, self.arches)`
750 #---------- pretty-printer for tables of pirate puzzle standings ----------
752 class StandingsTable:
753 def __init__(self, f, use_puzzles=None, col_width=6, gap_every=5):
754 if use_puzzles is None:
756 use_puzzles=duty_puzzles
759 self._puzzles = use_puzzles
761 self._cw = col_width-1
762 self._gap_every = gap_every
766 def _nl(self): self._o('\n')
768 def _pline(self, lhs, puzstrs, extra):
769 if (self._linecount > 0
770 and self._gap_every is not None
771 and not (self._linecount % self._gap_every)):
773 self._o('%-*s' % (max(max_pirate_namelen+1, 15), lhs))
775 self._o(' %-*.*s' % (self._cw,self._cw, v))
781 def _puzstr(self, pi, puzzle):
782 if not isinstance(puzzle,list): puzzle = [puzzle]
783 try: standing = max([pi.standings[p] for p in puzzle])
784 except KeyError: return '?'
785 if not standing: return ''
788 c1 = standingvals[standing][0]
789 if standing < 3: c1 = c1.lower() # 3 = Master
793 s += '*' * (standing / 2)
794 s += '+' * (standing % 2)
797 def headings(self, lhs='', rhs=None):
798 def puzn_redact(name):
799 if isinstance(name,list):
801 ["%.*s" % (self._cw/2, puzn_redact(n))
804 if spc < 0: return name
805 return name[0:min(4,spc)] + name[spc+1:]
807 self._pline(lhs, map(puzn_redact, self._puzzles), rhs)
809 def literalline(self, line):
813 def pirate_dummy(self, name, standingstring, extra=None):
814 standings = standingstring * len(self._puzzles)
815 self._pline(' '+name, standings, extra)
816 def pirate(self, pi, extra=None):
817 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
818 self._pline(' '+pi.name, puzstrs, extra)
821 #---------- chat log parser ----------
824 # This is essentially a transparent, dumb, data class.
834 # Also used for jobbing applicants:
835 # happens when expires (to "-")
836 # - disembark, leaves crew no
837 # aboard evidence of them being aboard no
838 # applied "has applied for the job" 120s, configurable
839 # ashore "has taken a job" 30min, configurable
840 # declined "declined the job offer" 30s, configurable
841 # invited "has been invited to job" 120s, configurable
843 # pa.jobber None, 'ashore', 'applied', 'invited', 'declined'
844 # pa.expires expiry time time
846 def __init__(pa, pn, v, time, event):
850 pa.last_event = event
851 pa.last_chat_time = None
852 pa.last_chat_chan = None
861 age = now - pa.pi_fetched
862 guide = random.randint(120,240)
865 debug('PirateAboard refresh %d > %d %s' % (
866 age, guide, pa.name))
870 wait = fetcher.need_wait(now, imaginary)
872 debug('PirateAboard fetcher not ready %d' % wait)
874 pa.pi = PirateInfo(pa.name, 600)
878 class ChatLogTracker:
879 # This is quite complex so we make it opaque. Use the
880 # official invokers, accessors etc.
882 def __init__(self, myself_pi, logfn):
883 self._pl = {} # self._pl['Pirate'] =
884 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
885 # self._vl['Vessel']['#lastinfo']
886 # self._vl['Vessel']['#name']
887 # self._v = self._vl[self._vessel]
889 self._myself = myself_pi
891 self._f = file(logfn)
892 flen = os.fstat(self._f.fileno()).st_size
894 if flen > max_backlog:
895 startpos = flen - max_backlog
896 self._f.seek(startpos)
898 self._progress = [0, flen - self._f.tell()]
899 self._disembark_myself()
900 self._need_redisplay = False
901 self._lastvessel = None
903 def _disembark_myself(self):
906 self.force_redisplay()
908 def force_redisplay(self):
909 self._need_redisplay = True
911 def _vessel_updated(self, v, timestamp):
913 v['#lastinfo'] = timestamp
914 self.force_redisplay()
916 def _onboard_event(self,v,timestamp,pirate,event,jobber=None):
917 pa = self._pl.get(pirate, None)
918 if pa is not None and pa.v is v:
919 pa.last_time = timestamp
920 pa.last_event = event
922 if pa is not None and pa.v is not None:
924 pa = PirateAboard(pirate, v, timestamp, event)
925 self._pl[pirate] = pa
926 if v is not None: v[pirate] = pa
929 if jobber is None: timeout = None
930 else: timeout = getattr(opts, 'timeout_'+jobber)
931 if timeout is None: pa.expires = None
932 else: pa.expires = timestamp + timeout
933 self._vessel_updated(v, timestamp)
936 def _expire_jobbers(self, now):
937 for pa in self._pl.values():
938 if pa.expires is None: continue
939 if pa.expires >= now: continue
941 del self._pl[pa.name]
942 if v is not None: del v[pa.name]
943 self.force_redisplay()
945 def _trash_vessel(self, v):
947 if pn.startswith('#'): continue
951 if v is self._v: self._disembark_myself()
952 self.force_redisplay()
954 def _vessel_stale(self, v, timestamp):
955 return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
957 def _vessel_check_expire(self, v, timestamp):
958 if not self._vessel_stale(v, timestamp):
960 self._debug_line_disposition(timestamp,'',
961 'stale-reset ' + v['#name'])
962 self._trash_vessel(v)
965 def expire_garbage(self, timestamp):
966 for v in self._vl.values():
967 self._vessel_check_expire(v, timestamp)
969 def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
970 v = self._vl.get(vn, None)
972 v = self._vessel_check_expire(v, timestamp)
979 self._vl[vn] = v = { '#name': vn }
980 self._vessel_updated(v, timestamp)
983 def _find_matching_vessel(self, pattern, timestamp, cmdr,
984 dml=[], create=False):
985 # use when a commander pirate `cmdr' specified a vessel
986 # by name `pattern' (either may be None)
987 # if create is true, will create the vessel
988 # record if an exact name is specified
990 if (pattern is not None and
992 and len(pattern.split(' ')) == 2):
995 return self._vessel_lookup(
996 vn, timestamp, dml=dml, create=create)
999 pattern_check = lambda vn: True
1001 re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
1002 pattern_check = regexp.compile(re, regexp.I).match
1006 cmdr_pa = self._pl.get(cmdr, None)
1007 if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
1009 tries.append((self._v, 'here'))
1012 for (v, dm) in tries:
1013 if v is None: dml.append(dm+'?'); continue
1016 if not pattern_check(vn):
1017 tried_vns.append(vn)
1024 if pattern is not None and '*' in pattern:
1027 for (vn,v) in self._vl.iteritems()
1028 if not self._vessel_stale(v, timestamp)
1029 if pattern_check(vn)
1031 #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
1033 # '/'.join(tried_vns),
1034 # '/'.join([vn for (vn,v) in search])))
1044 def _debug_line_disposition(self,timestamp,l,m):
1045 debug('CLT %13s %-40s %s' % (timestamp,m,l))
1047 def _rm_crew_l(self,re,l):
1048 m = regexp.match(re,l)
1049 if m and m.group(2) == self._myself.crew[1]:
1054 def local_command(self, metacmd):
1055 # returns None if all went well, or problem message
1056 return self._command(self._myself.name, metacmd,
1057 "local", time.time(),
1058 (lambda m: debug('CMD %s' % metacmd)))
1060 def _command(self, cmdr, metacmd, chan, timestamp, d):
1061 # returns None if all went well, or problem message
1062 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
1064 '/([adj]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
1066 if not m2: return "unknown syntax or command"
1068 (cmd, pattern, targets) = m2.groups()
1069 dml = ['cmd', chan, cmd]
1071 if cmd == 'a': each = self._onboard_event
1072 elif cmd == 'd': each = disembark
1073 else: each = lambda *l: self._onboard_event(*l,
1074 **{'jobber':'applied'})
1076 if cmdr == self._myself.name:
1078 how = 'cmd: %s' % cmd
1081 how = 'cmd: %s %s' % (cmd,cmdr)
1084 if pattern is not None:
1085 return "/j command does not take a vessel"
1088 v = self._find_matching_vessel(
1089 pattern, timestamp, cmdr,
1092 if cmd == 'j' or v is not None:
1093 targets = targets.strip().split(' ')
1094 dml.append(`len(targets)`)
1095 for target in targets:
1096 each(v, timestamp, target.title(), how)
1097 self._vessel_updated(v, timestamp)
1104 def chatline(self,l):
1105 rm = lambda re: regexp.match(re,l)
1106 d = lambda m: self._debug_line_disposition(timestamp,l,m)
1107 rm_crew = lambda re: self._rm_crew_l(re,l)
1110 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
1112 self._date = [int(x) for x in m.groups()]
1113 self._previous_timestamp = None
1114 return d('date '+`self._date`)
1116 if self._date is None:
1117 return d('date unset')
1119 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
1121 return d('no timestamp')
1124 time_tuple = (self._date +
1125 [int(x) for x in m.groups()] +
1127 timestamp = time.mktime(time_tuple)
1128 if timestamp >= self._previous_timestamp: break
1130 self._debug_line_disposition(timestamp,'',
1131 'new date '+`self._date`)
1133 self._previous_timestamp = timestamp
1135 l = l[l.find(' ')+1:]
1137 def ob_x(pirate,event):
1138 return self._onboard_event(
1139 self._v, timestamp, pirate, event)
1140 def ob1(did): ob_x(m.group(1), did); return d(did)
1141 def oba(did): return ob1('%s %s' % (did, m.group(2)))
1143 def jb(pirate,jobber):
1144 return self._onboard_event(
1145 None, timestamp, pirate,
1146 ("jobber %s" % jobber),
1150 def disembark(v, timestamp, pirate, event):
1151 self._onboard_event(
1152 v, timestamp, pirate, 'leaving '+event)
1154 del self._pl[pirate]
1156 def disembark_me(why):
1157 self._disembark_myself()
1158 return d('disembark-me '+why)
1160 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
1163 pn = self._myself.name
1165 v = self._vessel_lookup(vn, timestamp, dm, create=True)
1166 self._lastvessel = self._vessel = vn
1168 ob_x(pn, 'we boarded')
1169 self.expire_garbage(timestamp)
1170 return d(' '.join(dm))
1173 return d('no vessel')
1175 m = rm('(\\w+) has come aboard\\.$')
1176 if m: return ob1('boarded');
1178 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
1180 (who,what) = m.groups()
1181 pa = ob_x(who,'ord '+what)
1182 if what == 'Gunning':
1184 return d('duty order')
1186 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
1187 if m: oba('stopped'); return d("end")
1189 def chat_core(speaker, chan):
1190 try: pa = self._pl[speaker]
1191 except KeyError: return 'mystery'
1192 if pa.v is not None and pa.v is not self._v:
1194 pa.last_chat_time = timestamp
1195 pa.last_chat_chan = chan
1196 self.force_redisplay()
1200 speaker = m.group(1)
1201 dm = chat_core(speaker, chan)
1202 return d('chat %s %s' % (chan, dm))
1204 def chat_metacmd(chan):
1205 (cmdr, metacmd) = m.groups()
1206 whynot = self._command(
1207 cmdr, metacmd, chan, timestamp, d)
1208 if whynot is not None:
1211 chat_core(cmdr, 'cmd '+chan)
1213 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
1214 if m: return ob1('general order');
1216 m = rm('(\\w+) says, "')
1217 if m: return chat('public')
1219 m = rm('(\\w+) tells ye, "')
1220 if m: return chat('private')
1222 m = rm('Ye told (\\w+), "(.*)"$')
1223 if m: return chat_metacmd('private')
1225 m = rm('(\\w+) flag officer chats, "')
1226 if m: return chat('flag officer')
1228 m = rm('(\\w+) officer chats, "(.*)"$')
1229 if m: return chat_metacmd('officer')
1231 m = rm('Ye accepted the offer to job with ')
1232 if m: return disembark_me('jobbing')
1234 m = rm('Ye hop on the ferry and are whisked away ')
1235 if m: return disembark_me('ferry')
1237 m = rm('Whisking away to yer home on the magical winds')
1238 if m: return disembark_me('home')
1240 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
1242 pl = m.group(1).split(', ')
1243 if not self._myself.name in pl:
1244 return d('lost melee')
1246 if ' ' in pn: continue
1247 ob_x(pn,'won melee')
1248 return d('won melee')
1250 m = rm('(\\w+) is eliminated\\!')
1251 if m: return ob1('eliminated in fray');
1253 m = rm('(\\w+) has driven \w+ from the ship\\!')
1254 if m: return ob1('boarder repelled');
1256 m = rm('\w+ has bested (\\w+), and turns'+
1257 ' to the rest of the ship\\.')
1258 if m: return ob1('boarder unrepelled');
1260 pirate = rm_crew("(\\w+) has taken a job with '(.*)'\\.")
1261 if pirate: return jb(pirate, 'ashore')
1263 pirate = rm_crew("(\\w+) has left '(.*)'\\.")
1265 disembark(self._v, timestamp, pirate, 'left crew')
1266 return d('left crew')
1268 m = rm('(\w+) has applied for the posted job\.')
1269 if m: return jb(m.group(1), 'applied')
1271 pirate= rm_crew("(\\w+) has been invited to job for '(.*)'\\.")
1272 if pirate: return jb(pirate, 'invited')
1274 pirate = rm_crew("(\\w+) declined the job offer for '(.*)'\\.")
1275 if pirate: return jb(pirate, 'declined')
1277 m = rm('(\\w+) has left the vessel\.')
1280 disembark(self._v, timestamp, pirate, 'disembarked')
1281 return d('disembarked')
1283 return d('not-matched')
1285 def _str_pa(self, pn, pa):
1286 assert self._pl[pn] == pa
1287 s = ' '*20 + "%s %-*s %13s %-30s %13s %-20s %13s" % (
1288 (' ','G')[pa.gunner],
1289 max_pirate_namelen, pn,
1290 pa.last_time, pa.last_event,
1291 pa.last_chat_time, pa.last_chat_chan,
1293 if pa.expires is not None:
1294 s += " %-5d" % (pa.expires - pa.last_time)
1298 def _str_vessel(self, vn, v):
1299 s = ' vessel %s\n' % vn
1300 s += ' '*20 + "%-*s %13s\n" % (
1301 max_pirate_namelen, '#lastinfo',
1303 assert v['#name'] == vn
1304 for pn in sorted(v.keys()):
1305 if pn.startswith('#'): continue
1308 s += self._str_pa(pn,pa)
1312 s = '''<ChatLogTracker
1315 ''' % (self._myself.name, self._vessel)
1316 assert ((self._v is None and self._vessel is None) or
1317 (self._v is self._vl[self._vessel]))
1318 if self._vessel is not None:
1319 s += self._str_vessel(self._vessel, self._v)
1320 for vn in sorted(self._vl.keys()):
1321 if vn == self._vessel: continue
1322 s += self._str_vessel(vn, self._vl[vn])
1326 if pa.v is not None:
1327 assert pa.v[p] is pa
1328 assert pa.v in self._vl.values()
1330 s += self._str_pa(pa.name, pa)
1334 def catchup(self, progress=None):
1336 more = self._f.readline()
1339 self._progress[0] += len(more)
1340 if progress: progress.progress(*self._progress)
1343 if self._lbuf.endswith('\n'):
1344 self.chatline(self._lbuf.rstrip())
1347 debug(self.__str__())
1348 self._expire_jobbers(time.time())
1350 if progress: progress.caughtup()
1353 rv = self._need_redisplay
1354 self._need_redisplay = False
1357 # returns our pirate name
1358 return self._myself.name
1359 def vesselname(self):
1360 # returns the vessel name we're aboard or None
1362 def lastvesselname(self):
1363 # returns the last vessel name we were aboard or None
1364 return self._lastvessel
1365 def aboard(self, vesselname=True):
1366 # returns a list of PirateAboard the vessel
1367 # sorted by pirate name
1368 # you can pass this None and you'll get []
1369 # or True for the current vessel (which is the default)
1370 # the returned value is a fresh list of persistent
1371 # PirateAboard objects
1372 if vesselname is True: v = self._v
1373 else: v = self._vl.get(vesselname.title())
1374 if v is None: return []
1376 for pn in sorted(v.keys())
1377 if not pn.startswith('#') ]
1379 # returns a the jobbers' PirateAboards,
1380 # sorted by jobber class and reverse of expiry time
1382 for pa in self._pl.values()
1383 if pa.jobber is not None
1386 return (pa.jobber, -pa.expires)
1387 l.sort(key = compar_key)
1390 #---------- implementations of actual operation modes ----------
1392 def do_pirate(pirates, bu):
1394 for pirate in pirates:
1395 info = PirateInfo(pirate)
1396 print '%s: %s,' % (`pirate`, info)
1399 def prep_crewflag_of(args, bu, max_age, selector, constructor):
1400 if len(args) != 1: bu('crew-of etc. take one pirate name')
1401 pi = PirateInfo(args[0], max_age)
1403 if cf is None: return None
1404 return constructor(cf[0], max_age)
1406 def prep_crew_of(args, bu, max_age=300):
1407 return prep_crewflag_of(args, bu, max_age,
1408 (lambda pi: pi.crew), CrewInfo)
1410 def prep_flag_of(args, bu, max_age=300):
1411 return prep_crewflag_of(args, bu, max_age,
1412 (lambda pi: pi.flag), FlagInfo)
1414 def do_crew_of(args, bu):
1415 ci = prep_crew_of(args, bu)
1418 def do_flag_of(args, bu):
1419 fi = prep_flag_of(args, bu)
1422 def do_standings_crew_of(args, bu):
1423 ci = prep_crew_of(args, bu, 60)
1424 tab = StandingsTable(sys.stdout)
1426 for (rank, members) in ci.crew:
1427 if not members: continue
1429 tab.literalline('%s:' % rank)
1431 pi = PirateInfo(p, random.randint(900,1800))
1434 def do_ocean(args, bu):
1435 if (len(args)): bu('ocean takes no further arguments')
1436 fetcher.default_ocean()
1437 oi = OceanInfo(IslandFlagInfo)
1439 for islename in sorted(oi.islands.keys()):
1440 isle = oi.islands[islename]
1443 def do_embargoes(args, bu):
1444 if (len(args)): bu('ocean takes no further arguments')
1445 fetcher.default_ocean()
1446 oi = OceanInfo(IslandFlagInfo)
1447 wr = sys.stdout.write
1448 print ('EMBARGOES: Island | Owning flag'+
1449 ' | Embargoed flags')
1451 def getflname(isle):
1452 if isle.islandid is None: return 'uncolonisable'
1453 if isle.flag is None: return 'uncolonised'
1454 return isle.flag.name
1456 progressreporter.stop()
1458 for archname in sorted(oi.arches.keys()):
1459 print 'ARCHIPELAGO: ',archname
1460 for islename in sorted(oi.arches[archname].keys()):
1461 isle = oi.islands[islename]
1462 wr(' %-20s | ' % isle.name)
1463 flname = getflname(isle)
1464 wr('%-30s | ' % flname)
1466 if flag is None: print ''; continue
1468 for rel in flag.relations:
1469 if rel.this_declaring >= 0: continue
1471 wr(rel.other_flagname)
1475 def do_embargoes_flag_of(args, bu):
1476 progressreporter.doing('fetching flag info')
1477 fi = prep_flag_of(args, bu)
1479 progressreporter.stop()
1480 print 'Pirate is not in a flag.'
1483 oi = OceanInfo(IslandFlagInfo)
1485 progressreporter.stop()
1489 for islename in sorted(oi.islands.keys()):
1490 isle = oi.islands[islename]
1492 if flag is None: continue
1493 for rel in flag.relations:
1494 if rel.this_declaring >= 0: continue
1495 if rel.other_flagid != fi.flagid: continue
1496 if not any: print 'EMBARGOED:'
1498 print " %-30s (%s)" % (islename, flag.name)
1500 print 'No embargoes.'
1506 def do_war_flag_of(args, bu):
1507 fi = prep_flag_of(args, bu)
1512 for certain in [True, False]:
1514 for rel in fi.relations:
1515 if rel.this_declaring >= 0: continue
1516 if (rel.other_declaring_max < 0) != certain: continue
1518 if certain: m = 'SINKING PvP'
1519 else: m = 'RISK OF SINKING PvP'
1520 print '%s (%s):' % (m, rel.yoweb_heading)
1523 print " ", rel.other_flagname
1525 print 'No sinking PvP.'
1527 #----- modes which use the chat log parser are quite complex -----
1529 class ProgressPrintPercentage:
1530 def __init__(self, f=sys.stdout):
1532 def progress_string(self,done,total):
1533 return "scan chat logs %3d%%\r" % ((done*100) / total)
1534 def progress(self,*a):
1535 self._f.write(self.progress_string(*a))
1537 def show_init(self, pirate, ocean):
1538 print >>self._f, 'Starting up, %s on the %s ocean' % (
1541 self._f.write(' \r')
1544 def prep_chat_log(args, bu,
1545 progress=ProgressPrintPercentage(),
1546 max_myself_age=3600):
1547 if len(args) != 1: bu('this action takes only chat log filename')
1549 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
1550 match = regexp.match(logfn_re, logfn)
1551 if not match: bu('chat log filename is not in expected format')
1552 (pirate, ocean) = match.groups()
1553 fetcher.default_ocean(ocean)
1555 progress.show_init(pirate, fetcher.ocean)
1556 myself = PirateInfo(pirate,max_myself_age)
1557 track = ChatLogTracker(myself, logfn)
1560 track.catchup(progress)
1563 track.force_redisplay()
1565 return (myself, track)
1567 def do_track_chat_log(args, bu):
1568 (myself, track) = prep_chat_log(args, bu)
1573 sleep(0.5 + 0.5 * random.random())
1575 #----- ship management aid -----
1577 class Display_dumb(ProgressPrintPercentage):
1579 ProgressPrintPercentage.__init__(self)
1582 def realstart(self):
1585 class Display_overwrite(ProgressPrintPercentage):
1587 ProgressPrintPercentage.__init__(self)
1589 null = file('/dev/null','w')
1590 curses.setupterm(fd=null.fileno())
1592 self._clear = curses.tigetstr('clear')
1594 self._debug('missing clear!')
1595 self.show = Display_dumb.show
1598 self._t = {'el':'', 'ed':''}
1599 if not self._init_sophisticated():
1600 for k in self._t.keys(): self._t[k] = ''
1601 self._t['ho'] = self._clear
1603 def _debug(self,m): debug('display overwrite: '+m)
1605 def _init_sophisticated(self):
1606 for k in self._t.keys():
1607 s = curses.tigetstr(k)
1609 self._t['ho'] = curses.tigetstr('ho')
1610 if not self._t['ho']:
1611 cup = curses.tigetstr('cup')
1612 self._t['ho'] = curses.tparm(cup,0,0)
1613 missing = [k for k in self._t.keys() if not self._t[k]]
1615 self.debug('missing '+(' '.join(missing)))
1620 w = sys.stdout.write
1621 def wti(k): w(self._t[k])
1625 for l in s.rstrip().split('\n'):
1634 def realstart(self):
1635 sys.stdout.write(self._clear)
1639 def do_ship_aid(args, bu):
1640 if opts.ship_duty is None: opts.ship_duty = True
1642 displayer = globals()['Display_'+opts.display]()
1644 (myself, track) = prep_chat_log(args, bu, progress=displayer)
1646 displayer.realstart()
1648 if os.isatty(0): kr_create = KeystrokeReader
1649 else: kr_create = DummyKeystrokeReader
1652 kreader = kr_create(0, 10)
1653 ship_aid_core(myself, track, displayer, kreader)
1658 class KeyBasedSorter:
1659 def compar_key_pa(self, pa):
1660 pi = pa.pirate_info()
1661 if pi is None: return None
1662 return self.compar_key(pi)
1663 def lsort_pa(self, l):
1664 l.sort(key = self.compar_key_pa)
1666 class NameSorter(KeyBasedSorter):
1667 def compar_key(self, pi): return pi.name
1668 def desc(self): return 'name'
1670 class SkillSorter(NameSorter):
1671 def __init__(self, relevant):
1672 self._want = frozenset(relevant.split('/'))
1674 for p in core_duty_puzzles:
1675 if isinstance(p,basestring): self._avoid.add(p)
1676 else: self._avoid |= set(p)
1677 self._avoid -= self._want
1678 self._desc = '%s' % relevant
1680 def desc(self): return self._desc
1682 def compar_key(self, pi):
1684 pi.standings.get(puz,-1)
1685 for puz in self._want
1688 -pi.standings.get(puz,standing_limit)
1689 for puz in self._avoid
1692 def negate(x): return -x
1693 debug('compar_key %s bw=%s ba=%s' % (pi.name, `best_want`,
1695 return (-best_want, map(negate, best_avoid), pi.name)
1697 def ship_aid_core(myself, track, displayer, kreader):
1700 vn = track.vesselname()
1701 if vn: return (vn, " on board the %s" % vn)
1702 vn = track.lastvesselname()
1703 if vn: return (vn, " ashore from the %s" % vn)
1704 return (None, " not on a vessel")
1707 if t is None: return ' ' * 22
1708 return " %-4s %-16s" % (format_time_interval(now - t),e)
1710 displayer.show(track.myname() + find_vessel()[1] + '...')
1723 (vn, vs) = find_vessel()
1726 if cliexec is not None:
1728 elif clierr is not None:
1729 s += 'Error: '+clierr
1730 elif clicmd is not None:
1733 s = track.myname() + vs
1734 s += " at %s" % time.strftime("%Y-%m-%d %H:%M:%S")
1739 tbl = StandingsTable(tbl_s)
1741 aboard = track.aboard(vn)
1742 sort.lsort_pa(aboard)
1744 jobbers = track.jobbers()
1746 if track.vesselname(): howmany = 'aboard: %2d' % len(aboard)
1749 tbl.headings(howmany, ' sorted by '+sort.desc())
1753 for pa in aboard + jobbers:
1754 if pa.jobber != last_jobber:
1755 last_jobber = pa.jobber
1757 tbl.literalline('jobbers '+last_jobber)
1759 pi = pa.pirate_info()
1762 if pa.gunner: xs += 'G '
1764 xs += timeevent(pa.last_time, pa.last_event)
1765 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
1768 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
1772 s += tbl_s.getvalue()
1776 if cliexec is not None:
1777 clierr = track.local_command("/"+cliexec.strip())
1783 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
1786 if clierr is not None:
1790 if clicmd is not None:
1791 if k == '\r' or k == '\n':
1794 elif k == '\e' and clicmd != "":
1798 elif k == '\b' or k == '\177':
1799 clicmd = clicmd[ 0 : len(clicmd)-1 ]
1805 elif k == 'g': sort = SkillSorter('Gunning')
1806 elif k == 'c': sort = SkillSorter('Carpentry')
1807 elif k == 's': sort = SkillSorter('Sailing/Rigging')
1808 elif k == 'b': sort = SkillSorter('Bilging')
1809 elif k == 'n': sort = SkillSorter('Navigating')
1810 elif k == 'd': sort = SkillSorter('Battle Navigation')
1811 elif k == 't': sort = SkillSorter('Treasure Haul')
1812 elif k == 'a': sort = NameSorter()
1813 elif k == '/': clicmdbase = ""; clicmd = clicmdbase
1814 elif k == '+': clicmdbase = "a "; clicmd = clicmdbase
1815 else: pass # unknown key command
1817 #---------- individual keystroke input ----------
1819 class DummyKeystrokeReader:
1820 def __init__(self,fd,timeout_dummy): pass
1821 def stop(self): pass
1822 def getch(self): sleep(1); return None
1823 def info(self): return ' [noninteractive]'
1825 class KeystrokeReader(DummyKeystrokeReader):
1826 def __init__(self, fd, timeout_decisec=0):
1828 self._saved = termios.tcgetattr(fd)
1829 a = termios.tcgetattr(fd)
1830 a[3] &= ~(termios.ECHO | termios.ECHONL |
1831 termios.ICANON | termios.IEXTEN)
1832 a[6][termios.VMIN] = 0
1833 a[6][termios.VTIME] = timeout_decisec
1834 termios.tcsetattr(fd, termios.TCSANOW, a)
1836 termios.tcsetattr(self._fd, termios.TCSANOW, self._saved)
1839 byte = os.read(self._fd, 1)
1840 if not len(byte): return None
1845 #---------- main program ----------
1848 global opts, fetcher, yppedia, progressreporter
1851 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
1853 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
1854 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
1855 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
1856 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
1857 yoweb-scrape [--ocean OCEAN ...] ocean|embargoes
1858 yoweb-scrape [--ocean OCEAN ...] war-flag-of|embargoes-flag-of PIRATE
1859 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
1861 display modes (for --display) apply to ship-aid:
1862 --display=dumb just print new information, scrolling the screen
1863 --display=overwrite use cursor motion, selective clear, etc. to redraw at top''')
1865 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
1866 help='select ocean OCEAN')
1867 ao('--cache-dir', dest='cache_dir', metavar='DIR',
1868 default='~/.yoweb-scrape-cache',
1869 help='cache yoweb pages in DIR')
1870 ao('-D','--debug', action='count', dest='debug', default=0,
1871 help='enable debugging output')
1872 ao('--debug-fd', type='int', dest='debug_fd',
1873 help='write any debugging output to specified fd')
1874 ao('-q','--quiet', action='store_true', dest='quiet',
1875 help='suppress warning output')
1876 ao('--display', action='store', dest='display',
1877 type='choice', choices=['dumb','overwrite'],
1878 help='how to display ship aid')
1879 ao('--local-ypp-dir', action='store', dest='localhtml',
1880 help='get yppedia pages from local directory LOCALHTML'+
1881 ' instead of via HTTP')
1883 ao_jt = lambda wh, t: ao(
1884 '--timeout-sa-'+wh, action='store', dest='timeout_'+wh,
1885 default=t, help=('set timeout for expiring %s jobbers' % wh))
1886 ao_jt('applied', 120)
1887 ao_jt('invited', 120)
1888 ao_jt('declined', 30)
1889 ao_jt('ashore', 1800)
1891 ao('--ship-duty', action='store_true', dest='ship_duty',
1892 help='show ship duty station puzzles')
1893 ao('--all-puzzles', action='store_false', dest='ship_duty',
1894 help='show all puzzles, not just ship duty stations')
1896 ao('--min-cache-reuse', type='int', dest='min_max_age',
1897 metavar='SECONDS', default=60,
1898 help='always reuse cache yoweb data if no older than this')
1900 (opts,args) = pa.parse_args()
1904 print >>sys.stderr, copyright_info
1905 pa.error('need a mode argument')
1907 if opts.debug_fd is not None:
1908 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
1910 opts.debug_file = sys.stdout
1913 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
1914 try: mode_fn = globals()[mode_fn_name]
1915 except KeyError: pa.error('unknown mode "%s"' % mode)
1918 opts.expire_age = max(3600, opts.min_max_age)
1920 opts.ship_reboard_clearout = 3600
1922 if opts.cache_dir.startswith('~/'):
1923 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
1925 if opts.display is None:
1926 if ((opts.debug > 0 and opts.debug_fd is None)
1927 or not os.isatty(sys.stdout.fileno())):
1928 opts.display = 'dumb'
1930 opts.display = 'overwrite'
1932 fetcher = Yoweb(opts.ocean, opts.cache_dir)
1933 yppedia = Yppedia(opts.cache_dir)
1935 if opts.debug or not os.isatty(0):
1936 progressreporter = NullProgressReporter()
1938 progressreporter = TypewriterProgressReporter()
1940 mode_fn(args[1:], pa.error)