+ self._pline(' '+pi.name, puzstrs, extra)
+
+
+#---------- chat log parser ----------
+
+class PirateAboard:
+ # This is essentially a transparent, dumb, data class.
+ # pa.v may be None
+ # pa.name
+ # pa.last_time
+ # pa.last_event
+ # pa.gunner
+ # pa.last_chat_time
+ # pa.last_chat_chan
+ # pa.pi
+
+ # Also used for jobbing applicants:
+ # happens when expires (to "-")
+ # - disembark, leaves crew no
+ # aboard evidence of them being aboard no
+ # applied "has applied for the job" 120s, configurable
+ # ashore "has taken a job" 30min, configurable
+ # declined "declined the job offer" 30s, configurable
+ # invited "has been invited to job" 120s, configurable
+ #
+ # pa.jobber None, 'ashore', 'applied', 'invited', 'declined'
+ # pa.expires expiry time time
+
+ def __init__(pa, pn, v, time, event):
+ pa.name = pn
+ pa.v = v
+ pa.last_time = time
+ pa.last_event = event
+ pa.last_chat_time = None
+ pa.last_chat_chan = None
+ pa.gunner = False
+ pa.pi = None
+ pa.jobber = None
+ pa.expires = None
+
+ def pirate_info(pa):
+ now = time.time()
+ if pa.pi:
+ age = now - pa.pi_fetched
+ guide = random.randint(120,240)
+ if age <= guide:
+ return pa.pi
+ debug('PirateAboard refresh %d > %d %s' % (
+ age, guide, pa.name))
+ imaginary = [2,4]
+ else:
+ imaginary = [1]
+ wait = fetcher.need_wait(now, imaginary)
+ if wait:
+ debug('PirateAboard fetcher not ready %d' % wait)
+ return pa.pi
+ pa.pi = PirateInfo(pa.name, 600)
+ pa.pi_fetched = now
+ return pa.pi
+
+class ChatLogTracker:
+ # This is quite complex so we make it opaque. Use the
+ # official invokers, accessors etc.
+
+ def __init__(self, myself_pi, logfn):
+ self._pl = {} # self._pl['Pirate'] =
+ self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
+ # self._vl['Vessel']['#lastinfo']
+ # self._vl['Vessel']['#name']
+ # self._v = self._vl[self._vessel]
+ self._date = None
+ self._myself = myself_pi
+ self._lbuf = ''
+ self._f = file(logfn)
+ flen = os.fstat(self._f.fileno()).st_size
+ max_backlog = 500000
+ if flen > max_backlog:
+ startpos = flen - max_backlog
+ self._f.seek(startpos)
+ self._f.readline()
+ self._progress = [0, flen - self._f.tell()]
+ self._disembark_myself()
+ self._need_redisplay = False
+ self._lastvessel = None
+
+ def _disembark_myself(self):
+ self._v = None
+ self._vessel = None
+ self.force_redisplay()
+
+ def force_redisplay(self):
+ self._need_redisplay = True
+
+ def _vessel_updated(self, v, timestamp):
+ if v is None: return
+ v['#lastinfo'] = timestamp
+ self.force_redisplay()
+
+ def _onboard_event(self,v,timestamp,pirate,event,jobber=None):
+ pa = self._pl.get(pirate, None)
+ if pa is not None and pa.v is v:
+ pa.last_time = timestamp
+ pa.last_event = event
+ else:
+ if pa is not None and pa.v is not None:
+ del pa.v[pirate]
+ pa = PirateAboard(pirate, v, timestamp, event)
+ self._pl[pirate] = pa
+ if v is not None: v[pirate] = pa
+ pa.jobber = jobber
+
+ if jobber is None: timeout = None
+ else: timeout = getattr(opts, 'timeout_'+jobber)
+ if timeout is None: pa.expires = None
+ else: pa.expires = timestamp + timeout
+ self._vessel_updated(v, timestamp)
+ return pa
+
+ def _expire_jobbers(self, now):
+ for pa in self._pl.values():
+ if pa.expires is None: continue
+ if pa.expires >= now: continue
+ v = pa.v
+ del self._pl[pa.name]
+ if v is not None: del v[pa.name]
+ self.force_redisplay()
+
+ def _trash_vessel(self, v):
+ for pn in v:
+ if pn.startswith('#'): continue
+ del self._pl[pn]
+ vn = v['#name']
+ del self._vl[vn]
+ if v is self._v: self._disembark_myself()
+ self.force_redisplay()
+
+ def _vessel_stale(self, v, timestamp):
+ return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
+
+ def _vessel_check_expire(self, v, timestamp):
+ if not self._vessel_stale(v, timestamp):
+ return v
+ self._debug_line_disposition(timestamp,'',
+ 'stale-reset ' + v['#name'])
+ self._trash_vessel(v)
+ return None
+
+ def expire_garbage(self, timestamp):
+ for v in self._vl.values():
+ self._vessel_check_expire(v, timestamp)
+
+ def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
+ v = self._vl.get(vn, None)
+ if v is not None:
+ v = self._vessel_check_expire(v, timestamp)
+ if v is not None:
+ dml.append('found')
+ return v
+ if not create:
+ dml.append('no')
+ dml.append('new')
+ self._vl[vn] = v = { '#name': vn }
+ self._vessel_updated(v, timestamp)
+ return v
+
+ def _find_matching_vessel(self, pattern, timestamp, cmdr,
+ dml=[], create=False):
+ # use when a commander pirate `cmdr' specified a vessel
+ # by name `pattern' (either may be None)
+ # if create is true, will create the vessel
+ # record if an exact name is specified
+
+ if (pattern is not None and
+ not '*' in pattern
+ and len(pattern.split(' ')) == 2):
+ vn = pattern.title()
+ dml.append('exact')
+ return self._vessel_lookup(
+ vn, timestamp, dml=dml, create=create)
+
+ if pattern is None:
+ pattern_check = lambda vn: True
+ else:
+ re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
+ pattern_check = regexp.compile(re, regexp.I).match
+
+ tries = []
+
+ cmdr_pa = self._pl.get(cmdr, None)
+ if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
+
+ tries.append((self._v, 'here'))
+ tried_vns = []
+
+ for (v, dm) in tries:
+ if v is None: dml.append(dm+'?'); continue
+
+ vn = v['#name']
+ if not pattern_check(vn):
+ tried_vns.append(vn)
+ dml.append(dm+'#')
+ continue
+
+ dml.append(dm+'!')
+ return v
+
+ if pattern is not None and '*' in pattern:
+ search = [
+ (vn,v)
+ for (vn,v) in self._vl.iteritems()
+ if not self._vessel_stale(v, timestamp)
+ if pattern_check(vn)
+ ]
+ #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
+ # re,
+ # '/'.join(tried_vns),
+ # '/'.join([vn for (vn,v) in search])))
+
+ if len(search)==1:
+ dml.append('one')
+ return search[0][1]
+ elif search:
+ dml.append('many')
+ else:
+ dml.append('none')
+
+ def _debug_line_disposition(self,timestamp,l,m):
+ debug('CLT %13s %-40s %s' % (timestamp,m,l))
+
+ def _rm_crew_l(self,re,l):
+ m = regexp.match(re,l)
+ if m and m.group(2) == self._myself.crew[1]:
+ return m.group(1)
+ else:
+ return None
+
+ def chatline(self,l):
+ rm = lambda re: regexp.match(re,l)
+ d = lambda m: self._debug_line_disposition(timestamp,l,m)
+ rm_crew = lambda re: self._rm_crew_l(re,l)
+ timestamp = None
+
+ m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
+ if m:
+ self._date = [int(x) for x in m.groups()]
+ self._previous_timestamp = None
+ return d('date '+`self._date`)
+
+ if self._date is None:
+ return d('date unset')
+
+ m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
+ if not m:
+ return d('no timestamp')
+
+ while True:
+ time_tuple = (self._date +
+ [int(x) for x in m.groups()] +
+ [-1,-1,-1])
+ timestamp = time.mktime(time_tuple)
+ if timestamp >= self._previous_timestamp: break
+ self._date[2] += 1
+ self._debug_line_disposition(timestamp,'',
+ 'new date '+`self._date`)
+
+ self._previous_timestamp = timestamp
+
+ l = l[l.find(' ')+1:]
+
+ def ob_x(pirate,event):
+ return self._onboard_event(
+ self._v, timestamp, pirate, event)
+ def ob1(did): ob_x(m.group(1), did); return d(did)
+ def oba(did): return ob1('%s %s' % (did, m.group(2)))
+
+ def jb(pirate,jobber):
+ return self._onboard_event(
+ None, timestamp, pirate,
+ ("jobber %s" % jobber),
+ jobber=jobber
+ )
+
+ def disembark(v, timestamp, pirate, event):
+ self._onboard_event(
+ v, timestamp, pirate, 'leaving '+event)
+ del v[pirate]
+ del self._pl[pirate]
+
+ def disembark_me(why):
+ self._disembark_myself()
+ return d('disembark-me '+why)
+
+ m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
+ if m:
+ dm = ['boarding']
+ pn = self._myself.name
+ vn = m.group(1)
+ v = self._vessel_lookup(vn, timestamp, dm, create=True)
+ self._lastvessel = self._vessel = vn
+ self._v = v
+ ob_x(pn, 'we boarded')
+ self.expire_garbage(timestamp)
+ return d(' '.join(dm))
+
+ if self._v is None:
+ return d('no vessel')
+
+ m = rm('(\\w+) has come aboard\\.$')
+ if m: return ob1('boarded');
+
+ m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
+ if m:
+ (who,what) = m.groups()
+ pa = ob_x(who,'ord '+what)
+ if what == 'Gunning':
+ pa.gunner = True
+ return d('duty order')
+
+ m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
+ if m: oba('stopped'); return d("end")
+
+ def chat_core(speaker, chan):
+ try: pa = self._pl[speaker]
+ except KeyError: return 'mystery'
+ if pa.v is not None and pa.v is not self._v:
+ return 'elsewhere'
+ pa.last_chat_time = timestamp
+ pa.last_chat_chan = chan
+ self.force_redisplay()
+ return 'here'
+
+ def chat(chan):
+ speaker = m.group(1)
+ dm = chat_core(speaker, chan)
+ return d('chat %s %s' % (chan, dm))
+
+ def chat_metacmd(chan):
+ (cmdr, metacmd) = m.groups()
+ metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
+ m2 = regexp.match(
+ '/([adj]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
+ metacmd)
+ if not m2: return chat(chan)
+
+ (cmd, pattern, targets) = m2.groups()
+ dml = ['cmd', chan, cmd]
+
+ if cmd == 'a': each = self._onboard_event
+ elif cmd == 'd': each = disembark
+ else: each = lambda *l: self._onboard_event(*l,
+ **{'jobber':'applied'})
+
+ if cmdr == self._myself.name:
+ dml.append('self')
+ how = 'cmd: %s' % cmd
+ else:
+ dml.append('other')
+ how = 'cmd: %s %s' % (cmd,cmdr)
+
+ if cmd == 'j':
+ if pattern is not None:
+ return chat(chan)
+ v = None
+ else:
+ v = self._find_matching_vessel(
+ pattern, timestamp, cmdr,
+ dml, create=True)
+
+ if cmd == 'j' or v is not None:
+ targets = targets.strip().split(' ')
+ dml.append(`len(targets)`)
+ for target in targets:
+ each(v, timestamp, target.title(), how)
+ self._vessel_updated(v, timestamp)
+
+ dm = ' '.join(dml)
+ chat_core(cmdr, 'cmd '+chan)
+ return d(dm)
+
+ m = rm('(\\w+) (?:issued an order|ordered everyone) "')
+ if m: return ob1('general order');
+
+ m = rm('(\\w+) says, "')
+ if m: return chat('public')
+
+ m = rm('(\\w+) tells ye, "')
+ if m: return chat('private')
+
+ m = rm('Ye told (\\w+), "(.*)"$')
+ if m: return chat_metacmd('private')
+
+ m = rm('(\\w+) flag officer chats, "')
+ if m: return chat('flag officer')
+
+ m = rm('(\\w+) officer chats, "(.*)"$')
+ if m: return chat_metacmd('officer')
+
+ m = rm('Ye accepted the offer to job with ')
+ if m: return disembark_me('jobbing')
+
+ m = rm('Ye hop on the ferry and are whisked away ')
+ if m: return disembark_me('ferry')
+
+ m = rm('Whisking away to yer home on the magical winds')
+ if m: return disembark_me('home')