-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.py
325 lines (273 loc) · 9.94 KB
/
app.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
# -*- coding: utf-8 -*-
import os
import objc
import rumps
import subprocess
import threading
import sys
from Cocoa import NSObject
from rumps import MenuItem
from Foundation import NSLog, NSMakeRect
from AppKit import (
NSApp,
NSWindow,
NSTitledWindowMask,
NSClosableWindowMask,
NSBackingStoreBuffered,
NSScreenSaverWindowLevel,
)
from safety.safety import check
from safety.util import (
read_requirements,
Package as SafetyPackage,
RequirementFile as SafetyRequirementFile
)
from preference import PreferenceController, PreferenceSetting
__version__ = "0.1"
# icons come bundled with the binary
try:
ROOT = sys._MEIPASS
except AttributeError:
ROOT = os.path.dirname(os.path.realpath(__file__))
LAUNCH_TEMPLATE_FILE = 'launch.template.plist'
BUNDLE_ID = 'com.safetyapp.menubar'
DEAMON_TEMPLATE_FILE = 'deamon.template.sh'
DEAMON_FILE = 'deamon.sh'
DEBUG = True
if DEBUG:
def log(message):
NSLog(message)
else:
def log(_):
pass
class UIHelper(NSObject):
'''
A helper to interact with UI, eg UI update
'''
def initWithApp_(self, app):
'''
Init Helper with rumps app instance
interpret as Objc selector: initWithApp:
'''
self = objc.super(UIHelper, self).init()
if self is None:
return None
self._app = app
self.add = 0
return self
def updateMenuItem_(self, menu_item):
'''
Update the menu item
:param menu_item The menu item to be added to menu
'''
separator_key = 'separator_1'
if separator_key not in self._app.menu.keys():
# Add separator
self._app.menu.insert_before('Preferences', rumps.separator)
if menu_item.key not in self._app.menu.keys():
# Add directory
self._app.menu.insert_before(separator_key, menu_item)
else:
self._app.menu.update(menu_item)
class ICONS:
GRAY = os.path.join(ROOT, 'icons/gray.png')
GREEN = os.path.join(ROOT, 'icons/green.png')
RED = os.path.join(ROOT, 'icons/red.png')
class RequirementFile(object):
def __init__(self, project, path, requirements):
self.project = project
self.path = path
self.menu_item = MenuItem(
self.path,
key=path,
callback=self.clicked,
icon=ICONS.GRAY,
)
self.requirements = requirements
def clicked(self, sender):
subprocess.call(['open', self.path])
def check(self):
vulns = check(self.requirements)
if vulns:
self.menu_item.icon = ICONS.RED
else:
self.menu_item.icon = ICONS.GREEN
return vulns
class Project(object):
def __init__(self, app, path):
self.app = app
self.path = path
self.name = path.split("/")[-1]
self.insecure = None
self.menu_item = MenuItem(
self.path,
callback=self.clicked,
key=self.path,
icon=ICONS.GRAY,
)
self.requirement_files = None
self.ui_helper = UIHelper.alloc().initWithApp_(app)
NSApp.activateIgnoringOtherApps_(True)
@property
def is_valid(self):
return self.requirement_files is not None and self.requirement_files
@property
def needs_check(self):
return self.insecure is None
def find_requirement_files(self):
def is_likely_a_requirement(path):
if "req" in path:
if path.endswith(".txt") or path.endswith(".pip"):
return True
return False
def parse(file_name):
reqs = []
try:
with open(file_name) as fh:
for item in read_requirements(fh):
if isinstance(item, SafetyPackage):
reqs.append(item)
elif isinstance(item, SafetyRequirementFile):
for other_file in parse(item.path):
yield other_file
if reqs:
yield RequirementFile(
project=self,
requirements=reqs,
path=file_name
)
except:
pass
for item in os.listdir(self.path):
full_path = os.path.join(self.path, item)
if os.path.isdir(full_path):
for item_deep in os.listdir(full_path):
full_path_deep = os.path.join(full_path, item_deep)
if os.path.isfile(full_path_deep) and is_likely_a_requirement(full_path_deep):
for req_file in parse(full_path_deep):
yield req_file
elif os.path.isfile(full_path) and is_likely_a_requirement(full_path):
for req_file in parse(full_path):
yield req_file
def check(self):
if self.requirement_files is None:
self.requirement_files = list(self.find_requirement_files())
insecure = False
for req in self.requirement_files:
vulns = req.check()
if vulns:
insecure = True
self.insecure = insecure
if insecure:
self.menu_item.icon = ICONS.RED
else:
self.menu_item.icon = ICONS.GREEN
def add(self):
self.menu_item.update(
[r.menu_item for r in self.requirement_files]
)
# self.app.menu.update(self.menu_item)
self.ui_helper.pyobjc_performSelectorOnMainThread_withObject_('updateMenuItem:', self.menu_item)
def clicked(self, sender):
subprocess.call(['open', self.path])
def __eq__(self, other):
if isinstance(other, Project):
return self.path == other.path
return super(Project, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
class PyupStatusBarApp(rumps.App):
def __init__(self):
super(PyupStatusBarApp, self).__init__(
name="pyup",
)
self.projects = []
# Load the settings from file
self.reloadSettings()
@rumps.clicked('Preferences')
def preferences(self, _):
if 'prefController' not in self.__dict__:
# Initialize preference window
rect = NSMakeRect(0, 0, 500, 500)
window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
rect,
NSTitledWindowMask | NSClosableWindowMask,
NSBackingStoreBuffered,
False)
window.setTitle_('Preference')
window.center()
self.prefController = PreferenceController.alloc().initWithWindow_(window)
self.prefController.window().makeKeyWindow()
# self.prefController.window().setLevel_(NSFloatingWindowLevel)
self.prefController.window().orderFront_(self)
self.prefController.setSettingChangedCallback_withArgs_(self.reloadSettings, [])
if not self.prefController.window().isVisible():
self.prefController.window().makeKeyAndOrderFront_(self)
def sync(self):
log('Sync Thread {} is about to run...'.format(threading.current_thread().name))
if self.icon is None:
self.icon = ICONS.GRAY
try:
insecure = False
for path in self.settings['paths']:
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isdir(full_path):
project = Project(self, full_path)
log("have {}".format(full_path))
if project not in self.projects:
self.projects.append(project)
if project.needs_check:
project.check()
if project.is_valid:
project.add()
if project.insecure:
insecure = True
if insecure:
self.icon = ICONS.RED
else:
self.icon = ICONS.GREEN
log('Sync Thread {} run finished.'.format(threading.current_thread().name))
except:
import traceback
traceback.print_exc()
@rumps.timer(60 * 60) # run every hour
def refresh(self, _):
t = threading.Thread(target=self.sync, name='SyncThread')
t.start()
def reloadSettings(self, *args):
settings = PreferenceSetting.loadPathSettings()
self.settings = {
'paths': tuple(settings['paths']),
'depth': 1,
'key': str(settings['api_key']),
'startup': settings['startup'],
}
log('Setting is reloaed')
# Change the startup setting
self.startupLaunchSetup(self.settings['startup'])
def startupLaunchSetup(self, enable):
home = os.path.expanduser("~")
script_dir = os.path.dirname(os.path.realpath(__file__))
launch_dir = os.path.join(home, 'Library/LaunchAgents')
if enable:
# Setup startup launch
with open(LAUNCH_TEMPLATE_FILE, 'rb') as f:
with open('{}/{}.plist'.format(launch_dir, BUNDLE_ID), 'w') as w:
content = f.read().format(dir=script_dir, deamon=DEAMON_FILE)
w.write(content)
# Create deamon script file
with open(DEAMON_TEMPLATE_FILE, 'rb') as f:
with open(DEAMON_FILE, 'wb') as w:
content = f.read().format(dir=script_dir)
w.write(content)
else:
# Disable startup launch
try:
os.remove('{}/{}.plist'.format(launch_dir, BUNDLE_ID))
except OSError:
pass
if __name__ == "__main__":
PyupStatusBarApp().run(
debug=True
)