-
Notifications
You must be signed in to change notification settings - Fork 10
/
stock-manager.py
executable file
·257 lines (199 loc) · 7.35 KB
/
stock-manager.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
#!/usr/bin/env python3
import sys
import argparse
import datetime
import os
from filelock import FileLock
from helpers.jsonModule import *
from helpers.htmlModule import *
from core.assets import *
# Lock timeout is 5 minutes
lockTimeout = 5 * 60
executionIntervals = ['weekly', 'daily']
configFile = 'config/viewer.json'
recipientsFile = 'config/recipients.json'
# report file path
reportFile = 'output/report.md'
# Size of report file with no data or header data
reportFileEmptySize = 0
entries = []
recipients = []
dataIsChanged = False
recipientsIsChanged = False
# Html fetcher default data - configured for bankier.pl
defaultHtmlElement = 'div'
defaultHtmlElementClasses = 'box300 boxGrey border3 right'
# Locks creation
lockConfig = FileLock(configFile + '.lock', timeout=lockTimeout)
lockRecipents = FileLock(recipientsFile + '.lock', timeout=lockTimeout)
# Emergency ForceExit
def ForceExit(message, ErrorCode=1):
global lockRecipents
global lockConfig
print('(Stock-manager) %s\n' % (message))
lockRecipents.release()
lockConfig.release()
sys.exit(ErrorCode)
# Entry handling
def recipientsAdd(address):
global recipients
global recipientsIsChanged
recipients.append({'address': address})
recipientsIsChanged = True
def recipientsRemove(address):
global recipients
global recipientsIsChanged
try:
recipients.remove({'address': address})
recipientsIsChanged = True
except ValueError:
pass
# Entry handling
def entryAdd(arguments, url, element, classes):
global entries
entries.append({'arguments': arguments, 'url': url,
'htmlElement': element, 'htmlClasses': classes})
def entryRemove(arguments, url, element, classes):
global entries
try:
entries.remove({'arguments': arguments, 'url': url,
'htmlElement': element, 'htmlClasses': classes})
except ValueError:
pass
def entryPrint(entry):
print(entry)
def entryExecute(entry, interval):
# Execute stock-viewer
if (os.system('stock-viewer ' + entry['arguments'] + ' -g -r -ri ' + interval) != 0):
print('Entry %s execution failed!\n' % (entry['arguments']))
return False
# Use HTML fetcher to fetch additional data
if (entry['url'] != ''):
fetcher = htmlFetcher(
entry['url'], entry['htmlElement'], entry['htmlClasses'])
ReportsAppend(reportFile, fetcher.Process() + '\n')
return True
# Appends data to reports file
def ReportAssets(filepath):
with FileLock(filepath + '.lock', timeout=lockTimeout):
if os.path.isfile(filepath):
with open(filepath, 'a+') as f:
stockAssets.Report(f, 'zl')
# Appends data to reports file
def ReportsAppend(filepath, data):
with FileLock(filepath + '.lock', timeout=lockTimeout):
if os.path.isfile(filepath):
with open(filepath, 'a+') as f:
f.write(data)
# Save reports to file. Append text.
def ReportsClean(filepath):
global reportFileEmptySize
with FileLock(filepath + '.lock', timeout=lockTimeout):
os.system('rm -rf output/report.md*')
os.system('rm -rf output/*.svg')
# Create file for reports with header
with open(filepath, 'w') as f:
f.write("%s report from <span style='color:blue'>%s</span> - file '%s'.\n" %
(args.execute, datetime.datetime.now().strftime('%d.%m.%Y %H:%M'), configFile))
f.write('------------------\n')
f.write('\n')
f.close()
# update empty file size after creation and header write
reportFileEmptySize = os.path.getsize(reportFile)
# Save reports to file. Append text.
def ReportsIsAnyting(filepath):
if (os.path.isfile(filepath)) and (os.path.getsize(filepath) > reportFileEmptySize):
return True
return False
# Save reports to file. Append text.
def ReportsToHTML(filepath):
os.system('make -C output/ html')
def ReportsToPDF(filepath):
os.system('make -C output/ htmltopdf')
def ReportsMail(recipient, filepath):
# mail all reports
print('Mail %s to %s.' % (filepath, recipient))
currentDate = datetime.date.today()
# Send email with attamchents through mutt smtp
os.system("mutt -e 'set content_type=text/html' -s '[Stock] Report %s for %s' -a output/report.pdf -- %s < %s" %
(args.execute, currentDate.strftime('%d/%m/%Y'), recipient, filepath))
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--add', action='store_true',
required=False, help='Adds given')
parser.add_argument('-d', '--delete', action='store_true',
required=False, help='Remove')
parser.add_argument('-e', '--execute', type=str,
required=False, help='Execute')
parser.add_argument('-s', '--show', action='store_true',
required=False, help='Print')
parser.add_argument('-ar', '--addRecipient', type=str,
required=False, help='Add email recipient')
parser.add_argument('-an', '--arguments', type=str,
required=False, help='Arguments')
parser.add_argument('-au', '--url', type=str,
required=False, help='Bankier URL')
args = parser.parse_args()
# Assert
if (not args.add
and not args.execute
and not args.delete
and not args.addRecipient
and not args.show):
print('Missing event')
sys.exit(1)
# Assert of execution parameter
if (args.execute is None) or (args.execute not in executionIntervals):
print('Wrong or missing execution interval.')
sys.exit(1)
# Assert - get locks
lockConfig.acquire()
lockRecipents.acquire()
stockAssets = StockAssets()
ReportsClean(reportFile)
entries = jsonRead(configFile)
recipients = jsonRead(recipientsFile)
# 0. Adding entries
# #####################################################33
if (args.add):
entryRemove(args.arguments, args.url, defaultHtmlElement,
defaultHtmlElementClasses)
entryAdd(args.arguments, args.url, defaultHtmlElement,
defaultHtmlElementClasses)
dataIsChanged = True
if (args.addRecipient is not None):
recipientsRemove(args.addRecipient)
recipientsAdd(args.addRecipient)
# 1. Removing entries
# #####################################################33
if (args.delete):
entryRemove(args.arguments, args.url, defaultHtmlElement,
defaultHtmlElementClasses)
dataIsChanged = True
# 2. Checking entries
# #####################################################33
for i in range(len(entries)):
entry = entries[i]
if (args.show):
entryPrint(entry)
if (args.execute is not None):
if (entryExecute(entry, args.execute) is True):
ForceExit('Execution failed!')
# 4. Write entries if were changed
# #####################################################33
if (dataIsChanged is True):
jsonWrite(configFile, entries)
if (recipientsIsChanged is True):
jsonWrite(recipientsFile, recipients)
# 5. Finish execution
if (args.execute is not None):
# If report has something
if (ReportsIsAnyting(reportFile)):
# Report also assets
ReportAssets(reportFile)
# Generate HTML & PDF
ReportsToPDF(reportFile)
# Send emails to all recipients
for i in range(len(recipients)):
ReportsMail(recipients[i]['address'], reportFile + '.html')
lockRecipents.release()
lockConfig.release()