forked from jerub/nrds-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KosLookupExe.py
343 lines (300 loc) · 10.5 KB
/
KosLookupExe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import cgi
import ctypes
import datetime
import io
from optparse import OptionParser
import os
import shutil
import sys
import tempfile
import time
import urllib
import urllib2
import webbrowser
import wx
import wx.html
import zipfile
try:
import winsound
except ImportError:
winsound = None
try:
from scikits.audiolab.pysndfile.matapi import oggread
from scikits.audiolab import wavread, play
except ImportError:
play = None
import ChatKosLookup
MINUS_TAG = u'[\u2212]' # Unicode MINUS SIGN
# Cargo-culted from:
# http://stackoverflow.com/questions/3927259/how-do-you-get-the-exact-path-to-my-documents
def GetMyDocumentsDir():
shell32 = ctypes.windll.shell32
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH + 1)
if shell32.SHGetSpecialFolderPathW(None, buf, 0x5, False):
return buf.value
return None
def GetEveLogsDir():
if options.chat_dir:
return options.chat_dir
home = GetMyDocumentsDir()
if not home:
return None
if os.path.isdir(os.path.join(home, 'EVE', 'logs', 'Chatlogs')):
return os.path.join(home, 'EVE', 'logs', 'Chatlogs')
if os.path.isdir(os.path.join(home, 'CCP', 'EVE', 'logs', 'Chatlogs')):
return os.path.join(home, 'CCP', 'EVE', 'logs', 'Chatlogs')
return None
class wxHTML(wx.html.HtmlWindow):
def OnLinkClicked(self, link):
webbrowser.open(link.GetHref())
class MainFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.UpdateIcon()
self.UpdateTitle()
self.checker = ChatKosLookup.KosChecker()
self.tailer = ChatKosLookup.DirectoryTailer(GetEveLogsDir())
self.labels = []
self.html = wxHTML(self, style=wx.html.HW_SCROLLBAR_NEVER)
self.status_bar = self.CreateStatusBar(1)
self.status_bar.PushStatusText("Starting...")
self.SetSize((300, 800))
self.SetBackgroundColour('white')
self.recent_lines = []
self.CreateMenu()
self.UpdateLabels()
self.KosCheckerPoll()
self.CheckArgs()
self.Show()
def CreateMenu(self):
file_menu = wx.Menu()
help_menu = wx.Menu()
reset_id = wx.NewId()
update_id = wx.NewId()
help_menu.Append(wx.ID_ABOUT, "About")
file_menu.Append(reset_id, "Reset")
file_menu.Append(update_id, "Update")
file_menu.Append(wx.ID_EXIT, "Exit")
menu_bar = wx.MenuBar()
menu_bar.Append(file_menu, "File")
menu_bar.Append(help_menu, "Help")
self.SetMenuBar(menu_bar)
self.Bind(wx.EVT_MENU, self.OnReset, id=reset_id)
self.Bind(wx.EVT_MENU, self.OnUpdate, id=update_id)
self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
def UpdateIcon(self):
"""
If running from py2exe, then the icon is implicitly obtained from the .exe
file, but when running from source, this method pulls it in from the
directory containing the python modules.
"""
if sys.argv[0].endswith('.exe'):
try:
loc = wx.IconLocation(sys.argv[0], 0)
self.SetIcon(wx.IconFromLocation(loc))
return
except:
pass
try:
icon_path = os.path.join(os.path.dirname(__file__), 'icon.ico')
except NameError:
# __file__ does not exist
return
if os.path.exists(icon_path):
self.SetIcon(wx.Icon(icon_path, wx.BITMAP_TYPE_ICO))
def KosCheckerPoll(self):
play_sound = False
action = False
self.status_bar.PushStatusText("Checking for KOS pilots")
for entry in iter(self.tailer.poll, None):
action = True
if entry.linekey in self.recent_lines:
continue
self.recent_lines.append(entry.linekey)
self.status_bar.PushStatusText("KOS Checking {} pilots".format(
len(entry.pilots)))
kos, not_kos, error = self.checker.koscheck_logentry(entry.pilots)
self.status_bar.PopStatusText()
new_labels = []
if entry.comment:
new_labels.append(entry.comment)
if kos or not_kos:
new_labels.append('KOS: {} Not KOS: {}'.format(len(kos), len(not_kos)))
if kos:
play_sound = True
new_labels.extend(
[(u'<font color="red">{minus} <a href="{kospath}">{pilot}</a> ({reason})</font>'.format(
minus=MINUS_TAG,
kospath="http://kos.cva-eve.org/?q=" + urllib.quote(p),
pilot=cgi.escape(p),
reason=cgi.escape(reason)))
for (p, reason) in kos])
if not_kos:
if kos:
new_labels.append('')
new_labels.extend([('<font color="blue">[+] {}</font>'.format(p)) for p in not_kos])
if error:
new_labels.append('Error: {}'.format(len(error)))
new_labels.extend(error)
if new_labels:
new_labels.append('<hr>')
self.labels = new_labels + self.labels
self.labels = self.labels[:100]
self.status_bar.PopStatusText()
if play_sound:
self.PlayKosAlertSound()
if action:
self.recent_lines = self.recent_lines[-100:]
self.UpdateLabels()
wx.FutureCall(1000, self.KosCheckerPoll)
def PlayKosAlertSound(self):
global winsound
if winsound:
try:
winsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
except:
# such as when there's no SystemQuestion sound, reported by some users.
winsound = False
elif play and options.sound_file:
data = None
if options.sound_file.endswith("ogg"):
data, fs, _ = oggread(options.sound_file)
elif options.sound_file.endswith("wav"):
data, fs, _ = wavread(options.sound_file)
if data is not None:
play(data.T, fs)
def UpdateLabels(self):
self.status_bar.PopStatusText()
last_update = self.tailer.last_update()
if last_update:
status = "Last update: {}".format(
datetime.datetime.fromtimestamp(last_update
).strftime("%Y-%m-%d %H:%M:%S"))
else:
status = "No logs found"
self.status_bar.PushStatusText(status)
self.html.SetPage('<br>'.join(self.labels))
def UpdateTitle(self):
self.SetLabel("Kill On Sight")
def OnReset(self, event):
logs_dir = GetEveLogsDir()
self.tailer = ChatKosLookup.DirectoryTailer(logs_dir)
last_update = self.tailer.last_update()
self.labels = []
self.labels.append('Checking logs in {}'.format(logs_dir))
if last_update:
minutes_ago = int((time.time() - last_update) / 60)
last_update = datetime.datetime.fromtimestamp(last_update
).strftime("%Y-%m-%d %H:%M:%S")
self.labels.append(
'Reset Complete: reading {} log files'.format(
len(self.tailer.watchers)))
self.labels.append('last update: {}, {} minutes ago'.format(
last_update, minutes_ago))
else:
self.labels.append(
'Reset Complete, no log files found')
self.UpdateLabels()
def OnAbout(self, event):
dlg = wx.MessageDialog(
self,
"KOS Lookup\nSee http://nrds.eu/\n"
"Version: 0.8b2",
'About',
wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def OnExit(self, event):
self.Close()
def CheckArgs(self):
if not zipfile.is_zipfile(sys.executable):
return
if '/updated' in sys.argv:
for x in range(10):
try:
if os.path.exists(sys.argv[2]):
os.unlink(sys.argv[2])
except OSError:
time.sleep(.1)
dlg = wx.MessageDialog(self, "Updates Complete", 'KosUpdater', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return
if '/update' in sys.argv:
realname = sys.argv[2]
while 1:
try:
shutil.copy(sys.executable, sys.argv[2])
break
except WindowsError as e:
time.sleep(.05)
wx.Execute("{} /updated {}".format(realname, sys.executable))
sys.exit()
return
def OnUpdate(self, event):
if not zipfile.is_zipfile(sys.executable):
return
files = self.CheckForUpdate()
with zipfile.PyZipFile(sys.executable, 'r') as z:
namelist = set(z.namelist())
edit = False
for filename, contents in list(files):
if filename not in namelist:
edit = True
elif z.read(filename) != contents:
edit = True
else:
files.remove((filename, contents))
if not edit:
dlg = wx.MessageDialog(self, "No Updates Found", 'KosUpdater', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return
with tempfile.NamedTemporaryFile(suffix='.exe', delete=False) as tmpfile:
shutil.copy(sys.executable, tmpfile.name)
with zipfile.PyZipFile(tmpfile.name, 'a', compression=zipfile.ZIP_DEFLATED) as z:
for zinfo in list(z.filelist):
for name, contents in files:
if zinfo.filename.startswith(name):
z.filelist.remove(zinfo)
for filename, contents in files:
if filename not in namelist or z.read(filename) != contents:
z.writestr(filename, contents)
wx.Execute("{} /update {}".format(tmpfile.name, sys.executable))
sys.exit()
def CheckForUpdate(self):
"""
Will attempt to download the latest update from http://www.nrds.eu/
The update is served from http://www.nrds.eu/download/update.zip and
contains one or more python files, which will replace the files inside the
py2exe release.
"""
try:
f = urllib2.urlopen('http://www.nrds.eu/downloads/update.zip')
update_zip = io.BytesIO(f.read())
z = zipfile.ZipFile(update_zip, 'r')
except Exception as e:
dlg = wx.MessageDialog(
self, 'Error retreiving update: {}'.format(e),
'KosUpdater', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return []
return [(filename, z.read(filename)) for filename in z.namelist()]
def main():
app = wx.App(redirect=False)
frame = MainFrame(None, -1, 'KOS Checker')
app.MainLoop()
def GetOptionsParser():
p = OptionParser()
p.add_option("-c", "--chat", dest="chat_dir", default="",
help="EVE chat log directory", metavar="chatlogs")
p.add_option("-s", "--sound", dest="sound_file", default="",
help="Sound file path for the KOS alert (wav or ogg)",
metavar="soundfile")
return p
if __name__ == '__main__':
p = GetOptionsParser()
(options, _) = p.parse_args()
main()