chiark / gitweb /
show gunning; bugfix to crew-of
[ypp-sc-tools.db-live.git] / yoweb-scrape
1 #!/usr/bin/python
2
3 import signal
4 signal.signal(signal.SIGINT, signal.SIG_DFL)
5
6 import os
7 import time
8 import urllib
9 import urllib2
10 import errno
11 import sys
12 import re as regexp
13 import random
14 from optparse import OptionParser
15
16 from BeautifulSoup import BeautifulSoup
17
18 opts = None
19
20
21 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
22         '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
23         '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
24         '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
25
26 standingvals = ('Able/Distinguished/Respected/Master'+
27                 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
28
29 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
30
31 max_pirate_namelen = 12
32
33
34 def debug(m):
35         if opts.debug > 0:
36                 print m
37
38 class Fetcher:
39         def __init__(self, ocean, cachedir):
40                 debug('Fetcher init %s' % cachedir)
41                 self.ocean = ocean
42                 self.cachedir = cachedir
43                 try: os.mkdir(cachedir)
44                 except (OSError,IOError), oe:
45                         if oe.errno != errno.EEXIST: raise
46                 self._cache_scan(time.time())
47
48         def _default_ocean(self):
49                 if self.ocean is None:
50                         self.ocean = 'ice'
51
52         def _cache_scan(self, now):
53                 # returns list of ages, unsorted
54                 ages = []
55                 debug('Fetcher   scan_cache')
56                 for leaf in os.listdir(self.cachedir):
57                         if not leaf.startswith('#'): continue
58                         path = self.cachedir + '/' + leaf
59                         try: s = os.stat(path)
60                         except (OSError,IOError), oe:
61                                 if oe.errno != errno.ENOENT: raise
62                                 continue
63                         age = now - s.st_mtime
64                         if age > opts.expire_age:
65                                 debug('Fetcher    expire %d %s' % (age, path))
66                                 try: os.remove(path)
67                                 except (OSError,IOError), oe:
68                                         if oe.errno != errno.ENOENT: raise
69                                 continue
70                         ages.append(age)
71                 return ages
72
73         def need_wait(self, now):
74                 ages = self._cache_scan(now)
75                 ages.sort()
76                 debug('Fetcher   ages ' + `ages`)
77                 min_age = 1
78                 need_wait = 0
79                 for age in ages:
80                         if age < min_age and age < 300:
81                                 debug('Fetcher   morewait min=%d age=%d' %
82                                         (min_age, age))
83                                 need_wait = max(need_wait, min_age - age)
84                         min_age += 3
85                         min_age *= 1.25
86                 return need_wait
87
88         def _rate_limit_cache_clean(self, now):
89                 need_wait = self.need_wait(now)
90                 if need_wait > 0:
91                         debug('Fetcher   wait %d' % need_wait)
92                         time.sleep(need_wait)
93
94         def fetch(self, url, max_age):
95                 debug('Fetcher fetch %s' % url)
96                 cache_corename = urllib.quote_plus(url)
97                 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
98                 try: f = file(cache_item, 'r')
99                 except (OSError,IOError), oe:
100                         if oe.errno != errno.ENOENT: raise
101                         f = None
102                 now = time.time()
103                 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
104                 if f is not None:
105                         s = os.fstat(f.fileno())
106                         age = now - s.st_mtime
107                         if age > max_age:
108                                 debug('Fetcher  stale %d < %d'% (max_age, age))
109                                 f = None
110                 if f is not None:
111                         data = f.read()
112                         f.close()
113                         debug('Fetcher  cached %d > %d' % (max_age, age))
114                         return data
115
116                 debug('Fetcher  fetch')
117                 self._rate_limit_cache_clean(now)
118
119                 stream = urllib2.urlopen(url)
120                 data = stream.read()
121                 cache_tmp = "%s/#%s~%d#" % (
122                         self.cachedir, cache_corename, os.getpid())
123                 f = file(cache_tmp, 'w')
124                 f.write(data)
125                 f.close()
126                 os.rename(cache_tmp, cache_item)
127                 debug('Fetcher  stored')
128                 return data
129
130         def yoweb(self, kind, tail, max_age):
131                 self._default_ocean()
132                 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
133                         self.ocean, kind, tail)
134                 return self.fetch(url, max_age)
135
136 class SoupLog:
137         def __init__(self):
138                 self.msgs = [ ]
139         def msg(self, m):
140                 self.msgs.append(m)
141         def soupm(self, obj, m):
142                 self.msg(m + '; in ' + `obj`)
143         def needs_msgs(self, child_souplog):
144                 self.msgs += child_souplog.msgs
145                 child_souplog.msgs = [ ]
146
147 def soup_text(obj):
148         str = ''.join(obj.findAll(text=True))
149         return str.strip()
150
151 class SomethingSoupInfo(SoupLog):
152         def __init__(self, kind, tail, max_age):
153                 SoupLog.__init__(self)
154                 html = fetcher.yoweb(kind, tail, max_age)
155                 self._soup = BeautifulSoup(html,
156                         convertEntities=BeautifulSoup.HTML_ENTITIES
157                         )
158
159 class PirateInfo(SomethingSoupInfo):
160         # Public data members:
161         #  pi.standings = { 'Treasure Haul': 'Able' ... }
162         #  pi.name = name
163         #  pi.crew = (id, name)
164         #  pi.flag = (id, name)
165         #  pi.msgs = [ 'message describing problem with scrape' ]
166                 
167         def __init__(self, pirate, max_age=300):
168                 SomethingSoupInfo.__init__(self,
169                         'pirate.wm?target=', pirate, max_age)
170                 self.name = pirate
171                 self._find_standings()
172                 self.crew = self._find_crewflag('crew',
173                         '^/yoweb/crew/info\\.wm')
174                 self.flag = self._find_crewflag('flag',
175                         '^/yoweb/flag/info\\.wm')
176
177         def _find_standings(self):
178                 imgs = self._soup.findAll('img',
179                         src=regexp.compile('/yoweb/images/stat.*'))
180                 re = regexp.compile(
181 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
182                         )
183                 standings = { }
184
185                 for skill in puzzles:
186                         standings[skill] = [ ]
187
188                 skl = SoupLog()
189
190                 for img in imgs:
191                         try: puzzle = img['alt']
192                         except KeyError: continue
193
194                         if not puzzle in puzzles:
195                                 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
196                                 continue
197                         key = img.findParent('td')
198                         if key is None:
199                                 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
200                                 continue
201                         valelem = key.findNextSibling('td')
202                         if valelem is None:
203                                 skl.soupm(key, 'puzzle missing sibling "%s"'
204                                         % puzzle)
205                                 continue
206                         valstr = soup_text(valelem)
207                         match = re.match(valstr)
208                         if match is None:
209                                 skl.soupm(key, ('puzzle "%s" unparseable'+
210                                         ' standing "%s"') % (puzzle, valstr))
211                                 continue
212                         standing = match.group(match.lastindex)
213                         standings[puzzle].append(standing)
214
215                 self.standings = { }
216
217                 for puzzle in puzzles:
218                         sl = standings[puzzle]
219                         if len(sl) > 1:
220                                 skl.msg('puzzle "%s" multiple standings %s' %
221                                                 (puzzle, `sl`))
222                                 continue
223                         if not sl:
224                                 skl.msg('puzzle "%s" no standing found' % puzzle)
225                                 continue
226                         standing = sl[0]
227                         for i in range(0, len(standingvals)-1):
228                                 if standing == standingvals[i]:
229                                         self.standings[puzzle] = i
230                         if not puzzle in self.standings:
231                                 skl.msg('puzzle "%s" unknown standing "%s"' %
232                                         (puzzle, standing))
233
234                 all_standings_ok = True
235                 for puzzle in puzzles:
236                         if not puzzle in self.standings:
237                                 self.needs_msgs(skl)
238
239         def _find_crewflag(self, cf, yoweb_re):
240                 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
241                 if len(things) != 1:
242                         self.msg('zero or several %s id references found' % cf)
243                         return None
244                 thing = things[0]
245                 id_re = '\\b%sid\\=(\\w+)$' % cf
246                 id_haystack = thing['href']
247                 match = regexp.compile(id_re).search(id_haystack)
248                 if match is None:
249                         self.soupm(thing, ('incomprehensible %s id ref'+
250                                 ' (%s in %s)') % (cf, id_re, id_haystack))
251                         return None
252                 name = soup_text(thing)
253                 return (match.group(1), name)
254
255         def __str__(self):
256                 return `(self.crew, self.flag, self.standings, self.msgs)`
257
258 class CrewInfo(SomethingSoupInfo):
259         # Public data members:
260         #  ci.crew = [ ('Captain',        ['Pirate', ...]),
261         #              ('Senior Officer', [...]),
262         #               ... ]
263         #  pi.msgs = [ 'message describing problem with scrape' ]
264
265         def __init__(self, crewid, max_age=300):
266                 SomethingSoupInfo.__init__(self,
267                         'crew/info.wm?crewid=', crewid, max_age)
268                 self._find_crew()
269
270         def _find_crew(self):
271                 self.crew = []
272                 capts = self._soup.findAll('img',
273                         src='/yoweb/images/crew-captain.png')
274                 if len(capts) != 1:
275                         self.msg('crew members: no. of captain images != 1')
276                         return
277                 tbl = capts[0]
278                 while not tbl.find('a', href=pirate_ref_re):
279                         tbl = tbl.findParent('table')
280                         if not tbl:
281                                 self.msg('crew members: cannot find table')
282                                 return
283                 current_rank_crew = None
284                 crew_rank_re = regexp.compile('/yoweb/images/crew')
285                 for row in tbl.contents:
286                         # findAll(recurse=False)
287                         if isinstance(row,basestring):
288                                 continue
289
290                         is_rank = row.find('img', attrs={'src': crew_rank_re})
291                         if is_rank:
292                                 rank = soup_text(row)
293                                 current_rank_crew = []
294                                 self.crew.append((rank, current_rank_crew))
295                                 continue
296                         for cell in row.findAll('a', href=pirate_ref_re):
297                                 if current_rank_crew is None:
298                                         self.soupm(cell, 'crew members: crew'
299                                                 ' before rank')
300                                         continue
301                                 current_rank_crew.append(soup_text(cell))
302
303         def __str__(self):
304                 return `(self.crew, self.msgs)`
305
306 class StandingsTable:
307         def __init__(self, use_puzzles=None, col_width=6):
308                 if use_puzzles is None:
309                         if opts.ship_duty:
310                                 use_puzzles=[
311                                         'Navigating','Battle Navigation',
312                                         'Gunning',
313                                         ['Sailing','Rigging'],
314                                         'Bilging',
315                                         'Carpentry',
316                                         'Treasure Haul'
317                                 ]
318                         else:
319                                 use_puzzles=puzzles
320                 self._puzzles = use_puzzles
321                 self.s = ''
322                 self._cw = col_width-1
323
324         def _pline(self, pirate, puzstrs, extra):
325                 self.s += ' %-*s' % (max(max_pirate_namelen, 14), pirate)
326                 for v in puzstrs:
327                         self.s += ' %-*.*s' % (self._cw,self._cw, v)
328                 if extra:
329                         self.s += ' ' + extra
330                 self.s += '\n'
331
332         def _puzstr(self, pi, puzzle):
333                 if not isinstance(puzzle,list): puzzle = [puzzle]
334                 try: standing = max([pi.standings[p] for p in puzzle])
335                 except KeyError: return '?'
336                 if not standing: return ''
337                 s = ''
338                 if self._cw > 4:
339                         c1 = standingvals[standing][0]
340                         if standing < 3: c1 = c1.lower() # 3 = Master
341                         s += `standing`
342                 if self._cw > 5:
343                         s += ' '
344                 s += '*' * (standing / 2)
345                 s += '+' * (standing % 2)
346                 return s
347
348         def headings(self):
349                 def puzn_redact(name):
350                         if isinstance(name,list):
351                                 return '/'.join(
352                                         ["%.*s" % (self._cw/2, puzn_redact(n))
353                                          for n in name])
354                         spc = name.find(' ')
355                         if spc < 0: return name
356                         return name[0:min(4,spc)] + name[spc+1:]
357                 self._pline('', map(puzn_redact, self._puzzles), None)
358         def literalline(self, line):
359                 self.s += line + '\n'
360         def pirate_dummy(self, name, standingstring, extra=None):
361                 self._pline(name, standingstring * len(self._puzzles), extra)
362         def pirate(self, pi, extra=None):
363                 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
364                 self._pline(pi.name, puzstrs, extra)
365
366         def results(self):
367                 return self.s
368
369 def do_pirate(pirates, bu):
370         print '{'
371         for pirate in pirates:
372                 info = PirateInfo(pirate)
373                 print '%s: %s,' % (`pirate`, info)
374         print '}'
375
376 def prep_crew_of(args, bu, max_age=300):
377         if len(args) != 1: bu('crew-of takes one pirate name')
378         pi = PirateInfo(args[0], max_age)
379         if pi.crew is None: return None
380         return CrewInfo(pi.crew[0], max_age)
381
382 def do_crew_of(args, bu):
383         ci = prep_crew_of(args, bu)
384         print ci
385
386 def do_standings_crew_of(args, bu):
387         ci = prep_crew_of(args, bu, 60)
388         tab = StandingsTable()
389         tab.headings()
390         for (rank, members) in ci.crew:
391                 if not members: continue
392                 tab.literalline('%s:' % rank)
393                 for p in members:
394                         pi = PirateInfo(p, random.randint(900,1800))
395                         tab.pirate(pi)
396         print tab.results()
397
398 class PirateAboard:
399         # pa.v
400         # pa.name
401         # pa.last_time
402         # pa.last_event
403         # pa.gunner
404         # pa.last_chat_time
405         # pa.last_chat_chan
406         # pa.pi
407
408         def __init__(pa, pn, v, time, event):
409                 pa.name = pn
410                 pa.v = v
411                 pa.last_time = time
412                 pa.last_event = event
413                 pa.last_chat_time = None
414                 pa.last_chat_chan = None
415                 pa.gunner = False
416                 pa.pi = None
417
418         def pirate_info(pa):
419                 if not pa.pi and not fetcher.need_wait(time.time()):
420                         pa.pi = PirateInfo(pa.name, 3600)
421                 return pa.pi
422
423 class ChatLogTracker:
424         def __init__(self, myself_pi, logfn):
425                 self._pl = {}   # self._pl['Pirate'] =
426                 self._vl = {}   #   self._vl['Vessel']['Pirate'] = PirateAboard
427                                 # self._vl['Vessel']['#lastaboard']
428                 self._v = None          # self._v =
429                 self._vessel = None     #       self._vl[self._vessel]
430                 self._date = None
431                 self._myself = myself_pi
432                 self._need_redisplay = False
433                 self._f = file(logfn)
434                 self._lbuf = ''
435                 self._progress = [0, os.fstat(self._f.fileno()).st_size]
436
437         def _refresh(self):
438                 self._need_redisplay = True
439
440         def _onboard_event(self,timestamp,pirate,event):
441                 try: pa = self._pl[pirate]
442                 except KeyError: pa = None
443                 if pa is not None and pa.v is self._v:
444                         pa.last_time = timestamp
445                         pa.last_event = event
446                 else:
447                         if pa is not None: del pa.v[pirate]
448                         pa = PirateAboard(pirate, self._v, timestamp, event)
449                         self._pl[pirate] = pa
450                         self._v[pirate] = pa
451                 self._v['#lastaboard'] = timestamp
452                 self._refresh()
453                 return pa
454
455         def _trash_vessel(self, v):
456                 for pn in v:
457                         if pn.startswith('#'): continue
458                         del self._pl[pn]
459                 self._refresh()
460
461         def expire_garbage(self, timestamp):
462                 for (vn,v) in list(self._vl.iteritems()):
463                         la = v['#lastaboard']
464                         if timestamp - la > opts.ship_reboard_clearout:
465                                 self._debug_line_disposition(timestamp,'',
466                                         'stale reset '+vn)
467                                 self._trash_vessel(v)
468                                 del self._vl[vn]
469
470         def clear_vessel(self, timestamp):
471                 if self._v is not None:
472                         self._trash_vessel(self._v)
473                 self._v = {'#lastaboard': timestamp}
474                 self._vl[self._vessel] = self._v
475
476         def _debug_line_disposition(self,timestamp,l,m):
477                 debug('CLT %13s %-30s %s' % (timestamp,m,l))
478
479         def chatline(self,l):
480                 rm = lambda re: regexp.match(re,l)
481                 d = lambda m: self._debug_line_disposition(timestamp,l,m)
482                 timestamp = None
483
484                 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
485                 if m:
486                         self._date = m.groups()
487                         return d('date '+`self._date`)
488
489                 if self._date is None:
490                         return d('date unset')
491
492                 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
493                 if not m:
494                         return d('no timestamp')
495
496                 time_tuple = [int(x) for x in self._date + m.groups()]
497                 time_tuple += (-1,-1,-1)
498                 timestamp = time.mktime(time_tuple)
499                 l = l[l.find(' ')+1:]
500
501                 def ob_x(who,event):
502                         return self._onboard_event(timestamp, who, event)
503                 def ob1(did): ob_x(m.group(1), did); return d(did)
504                 def oba(did): return ob1('%s %s' % (did, m.group(2)))
505
506                 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
507                 if m:
508                         pn = self._myself.name
509                         self._vessel = m.group(1)
510                         dm = 'boarding'
511
512                         try:             self._v = self._vl[self._vessel]
513                         except KeyError: self._v = None; dm += ' new'
514                         
515                         if self._v is not None:  la = self._v['#lastaboard']
516                         else:                    la = 0; dm += ' ?la'
517
518                         if timestamp - la > opts.ship_reboard_clearout:
519                                 self.clear_vessel(timestamp)
520                                 dm += ' stale'
521
522                         ob_x(pn, 'we boarded')
523                         self.expire_garbage(timestamp)
524                         return d(dm)
525
526                 if self._v is None:
527                         return d('no vessel')
528
529                 m = rm('(\\w+) has come aboard\\.$')
530                 if m: return ob1('boarded');
531
532                 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
533                 if m:
534                         (who,what) = m.groups()
535                         pa = ob_x(who,'ord '+what)
536                         if what == 'Gunning':
537                                 pa.gunner = True
538                         return d('duty order')
539
540                 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
541                 if m: oba('stopped'); return d("end")
542
543                 def chat(what):
544                         who = m.group(1)
545                         try: pa = self._pl[who]
546                         except KeyError: return d('chat mystery')
547                         if pa.v is self._v:
548                                 pa.last_chat_time = timestamp
549                                 pa.last_chat_chan = what
550                                 self._refresh()
551                                 return d(what+' chat')
552
553                 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
554                 if m: return ob1('general order');
555
556                 m = rm('(\\w+) says, "')
557                 if m: return chat('public')
558
559                 m = rm('(\\w+) tells ye, "')
560                 if m: return chat('private')
561
562                 m = rm('(\\w+) flag officer chats, "')
563                 if m: return chat('flag officer')
564
565                 m = rm('(\\w+) officer chats, "')
566                 if m: return chat('officer')
567
568                 m = rm('Game over\\.  Winners: ([A-Za-z, ]+)\\.$')
569                 if m:
570                         pl = m.group(1).split(', ')
571                         if not self._myself.name in pl:
572                                 return d('lost boarding battle')
573                         for pn in pl:
574                                 if ' ' in pn: continue
575                                 ob_x(pn,'won boarding battle')
576                         return d('won boarding battle')
577
578                 m = rm('(\\w+) is eliminated\\!')
579                 if m: return ob1('eliminated in fray');
580
581                 m = rm('(\\w+) has left the vessel\.')
582                 if m:
583                         who = m.group(1)
584                         ob_x(who, 'disembarked')
585                         del self._v[who]
586                         del self._pl[who]
587                         return d('disembarked')
588
589                 return d('not matched')
590
591         def _str_vessel(self, vn, v):
592                 s = ' vessel %s\n' % vn
593                 s += ' '*20 + "%-*s   %13s\n" % (
594                                 max_pirate_namelen, '#lastaboard',
595                                 v['#lastaboard'])
596                 for pn in sorted(v.keys()):
597                         if pn.startswith('#'): continue
598                         pa = v[pn]
599                         assert pa.v == v
600                         assert self._pl[pn] == pa
601                         s += ' '*20 + "%s %-*s %13s %-30s %13s %s\n" % (
602                                 (' ','G')[pa.gunner],
603                                 max_pirate_namelen, pn,
604                                 pa.last_time, pa.last_event,
605                                 pa.last_chat_time, pa.last_chat_chan)
606                 return s
607
608         def __str__(self):
609                 s = '''<ChatLogTracker
610  myself %s
611  vessel %s
612 '''                     % (self._myself.name, self._vessel)
613                 assert ((self._v is None and self._vessel is None) or
614                         (self._v is self._vl[self._vessel]))
615                 if self._vessel is not None:
616                         s += self._str_vessel(self._vessel, self._v)
617                 for vn in sorted(self._vl.keys()):
618                         if vn == self._vessel: continue
619                         s += self._str_vessel(vn, self._vl[vn])
620                 for p in self._pl:
621                         pa = self._pl[p]
622                         assert pa.v[p] is pa
623                         assert pa.v in self._vl.values()
624                 s += '>\n'
625                 return s
626
627         def catchup(self, progress=None):
628                 while True:
629                         more = self._f.readline()
630                         if not more: break
631
632                         self._progress[0] += len(more)
633                         if progress: progress.progress(*self._progress)
634
635                         self._lbuf += more
636                         if self._lbuf.endswith('\n'):
637                                 self.chatline(self._lbuf.rstrip())
638                                 self._lbuf = ''
639                 if progress: progress.caughtup()
640
641         def changed(self):
642                 rv = self._need_redisplay
643                 self._need_redisplay = False
644                 return rv
645         def myname(self):
646                 # returns our pirate name
647                 return self._myself.name
648         def vessel(self):
649                 # returns the vessel we're aboard or None
650                 return self._vessel
651         def aboard(self):
652                 # returns a list of PirateAboard sorted by name
653                 return [ self._v[pn]
654                          for pn in sorted(self._v.keys())
655                          if not pn.startswith('#') ]
656
657 class ProgressPrintPercentage:
658         def __init__(self, f=sys.stdout): self._f = f
659         def progress(self,done,total):
660                 self._f.write("scan chat logs %3d%%\r" % ((done*100) / total))
661                 self._f.flush()
662         def caughtup(self):
663                 self._f.write('                   \r')
664                 self._f.flush()
665
666 def prep_chat_log(args, bu,
667                 progress=ProgressPrintPercentage(),
668                 max_myself_age=3600):
669         if len(args) != 1: bu('this action takes only chat log filename')
670         logfn = args[0]
671         logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_chat-log-\\w+$'
672         match = regexp.match(logfn_re, logfn)
673         if not match: bu('chat log filename is not in default format')
674         (pirate, fetcher.ocean) = match.groups()
675         
676         myself = PirateInfo(pirate,max_myself_age)
677         track = ChatLogTracker(myself, logfn)
678
679         opts.debug -= 1
680         track.catchup(progress)
681         opts.debug += 1
682
683         return (myself, track)
684
685 def do_track_chat_log(args, bu):
686         (myself, track) = prep_chat_log(args, bu)
687         while True:
688                 track.catchup()
689                 if track.changed():
690                         print track
691                 time.sleep(1)
692
693 def format_time_interval(ti):
694         if ti < 120: return '%d:%02d' % (ti / 60, ti % 60)
695         if ti < 7200: return '%2dm' % (ti / 60)
696         if ti < 86400: return '%dh' % (ti / 3600)
697         return '%dd' % (ti / 86400)
698
699 def do_ship_aid(args, bu):
700         if opts.ship_duty is None: opts.ship_duty = True
701
702         (myself, track) = prep_chat_log(args, bu)
703
704         rotate_nya = '/-\\'
705
706         def timeevent(t,e):
707                 if t is None: return ' ' * 22
708                 return " %-4s %-16s" % (format_time_interval(now - t),e)
709
710         while True:
711                 track.catchup()
712                 now = time.time()
713
714                 s = "%s" % track.myname()
715
716                 vn = track.vessel()
717                 if vn is None: print s + " ...?"; return
718
719                 s += " on board the %s at %s\n" % (
720                         vn, time.strftime("%Y-%m-%d %H:%M:%S"))
721
722                 tbl = StandingsTable()
723                 tbl.headings()
724
725                 for pa in track.aboard():
726                         pi = pa.pirate_info()
727
728                         xs = ''
729                         if pa.gunner: xs += 'G '
730                         else: xs += '  '
731                         xs += timeevent(pa.last_time, pa.last_event)
732                         xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
733
734                         if pi is None:
735                                 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
736                         else:
737                                 tbl.pirate(pi, xs)
738
739                 s += tbl.results()
740
741                 print '\n\n', s;
742
743                 time.sleep(1)
744                 rotate_nya = rotate_nya[1:2] + rotate_nya[0]
745
746 def main():
747         global opts, fetcher
748
749         pa = OptionParser(
750 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
751 actions:
752  yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
753  yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
754  yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
755  yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
756  yoweb-scrape [--ocean OCEAN ...] ship-aid CHAT-LOG
757 ''')
758         ao = pa.add_option
759         ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
760                 help='select ocean OCEAN')
761         ao('--cache-dir', dest='cache_dir', metavar='DIR',
762                 default='~/.yoweb-scrape-cache',
763                 help='cache yoweb pages in DIR')
764         ao('-D','--debug', action='count', dest='debug', default=0,
765                 help='enable debugging output')
766         ao('-q','--quiet', action='store_true', dest='quiet',
767                 help='suppress warning output')
768
769         ao('--ship-duty', action='store_true', dest='ship_duty',
770                 help='show ship duty station puzzles')
771         ao('--all-puzzles', action='store_false', dest='ship_duty',
772                 help='show all puzzles, not just ship duty stations')
773
774         (opts,args) = pa.parse_args()
775         random.seed()
776
777         if len(args) < 1:
778                 pa.error('need a mode argument')
779
780         mode = args[0]
781         mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
782         try: mode_fn = globals()[mode_fn_name]
783         except KeyError: pa.error('unknown mode "%s"' % mode)
784
785         # fixed parameters
786         opts.min_max_age = 60
787         opts.expire_age = 3600
788         opts.ship_reboard_clearout = 3600
789
790         if opts.cache_dir.startswith('~/'):
791                 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
792
793         fetcher = Fetcher(opts.ocean, opts.cache_dir)
794
795         mode_fn(args[1:], pa.error)
796
797 main()