-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcron.py
578 lines (528 loc) · 21.6 KB
/
cron.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
__author__ = 'Monte'
"""
This module initializes the application's automated features that include sending of text messages and reminders to the
users.
"""
import sys
import math
import string
import datetime
import cPickle as Pickle
import serverManager
from appmanager import *
from threading import Thread
from contextlib import closing
from database import DatabaseManager
from messenger import Messenger
from security import Security
# Setting up important system configurations
class FileManager(object):
"""
Contains methods responsible for managing the crucial file components of the application
This files include:
allclients.dat
balance.dat
extensions.dat
expiry.dat
config.conf
etc.
"""
def __init__(self):
self.files = {
"clients": "allclients.dat",
"balance": "balance.dat",
"renewal": "expiry.dat",
"newinvoice": "renewal.dat",
"extension": "extensions.dat",
"birthday": "allclients.dat"
}
self.database = DatabaseManager()
self.report_file = "bin/report"
self.message_file = "bin/messages"
self.config_file = "bin/config.conf"
self.folders = ["bin"]
self.initializer()
self.configarations()
self.security = Security()
self.user = self.security.user
self.password = self.security.password
self.dialect = self.security.dialect
self.db = self.security.database
self.database.connect(dialect=self.dialect, user=self.user, passwd=self.password, database=self.db)
def initializer(self):
for name in self.folders:
if not os.path.exists(name):
os.mkdir(name)
for key, name in self.files.items():
name = "bin/" + name
if not os.path.exists(name):
msg = key + " file missing"
self.reporter((False, msg))
log.warning(msg)
else:
msg = key + " file found"
self.reporter(("server", msg))
def configarations(self):
"""
interval is the date differences that the messages should be sent.
status determines if the messages are to be sent or not
next means the next date general messages have to be sent
"""
config_types = {
'clients': {"interval": False, "status": False, "next": False},
'balance': {"interval": False, "status": False, "amount": 500},
'renewal': {"interval": [15, 5], "status": True},
'newinvoice': {"interval": [15, 5], "status": False},
'extension': {"interval": [15, 5], "status": False},
'birthday': {"status": True},
'cheque': {"interval": [15, 5], "status": True},
'connection': {'dialect': "mysql", 'database': "bima"},
}
if not os.path.exists(self.config_file):
with closing(open(self.config_file, "wb")) as fl:
Pickle.dump(config_types, fl)
log.info("Setting up system configurations")
if not os.path.exists(self.message_file):
self.initialize_messages()
def reporter(self, details):
"""
Manages a report file that has details on errors and ho the application
executes the most important steps.
The details parameter is either a Tuple or a list of Tuples.
The tuple has a type of message and the message itself. Error messages
are represented by a False object while the rest have there specific names
written out.
"""
if not os.path.exists(self.report_file):
with open(self.report_file, "wb") as fl:
Pickle.dump([], fl)
with closing(open(self.report_file, "rb")) as fl:
data = Pickle.load(fl)
with closing(open(self.report_file, "wb")) as fl:
if isinstance(details, tuple):
now = time.ctime()
type_ = details[0]
message = details[1]
data.append((now, type_, message))
elif isinstance(details, list):
for detail in details:
now = time.ctime()
type_ = detail[0]
message = detail
data.append((now, type_, message))
Pickle.dump(data, fl)
def report_reader(self):
"""Returns the content of the report file which can then be written in a logfile"""
if not os.path.exists(self.report_file):
return "File does not exist"
else:
with closing(open(self.report_file, "rb")) as fl:
data = Pickle.load(fl)
return data
def initialize_messages(self):
"""Creates the message file and initializes the default messages in it"""
balance = """Dear client,your outstanding insurance premium balance is Ksh $AMOUNT.Kindly
send your payments.For enquiries call 0714046604.Thanks for your support."""
renewal = """Dear client your $POLICY policy expires on $DATE. Kindly send us the renewal
instructions.For enquiries call 0714046604.Thank you"""
newinvoice = """Dear client. We have renewed your $POLICY policy. Kindly let us have your
payment of Ksh:$AMOUNT.For enquiries call 0714046604. Thank you."""
cheque = """Dear client kindly note that your $TYPE cheque no: $NUMBER ( &BANK ) of Ksh $AMOUNT id due for
banking on $DUE"""
general = ""
quick = ""
birthday = """Wishing you the very best as you celebrate your big day. Happy Birthday to you
from K-BIMA"""
default = {
"balance": balance,
"renewal": renewal,
"newinvoice": newinvoice,
"general": general,
"quicktxt": quick,
"birthday": birthday,
"cheque": cheque,
}
with closing(open(self.message_file, "wb")) as fl:
Pickle.dump(default, fl)
log.info("Setting up default message files and details")
log.debug("Setting up message database configurations")
for key, value in default.items():
data = (key, "server2", False, value, datetime.datetime.today())
self._add_message(data)
def _add_message(self, data):
database = DatabaseManager()
security = Security()
user = security.user
password = security.password
database.connect(dialect=self.dialect, user=user, passwd=password, database=self.db)
database.add_messages(data)
def read_message(self, type_):
"""Returns the message of the type given in the parameter"""
if not os.path.exists(self.message_file):
messages = self.initialize_messages()
else:
with closing(open(self.message_file)) as fl:
messages = Pickle.load(fl)
try:
message = messages[type_]
except KeyError:
return False
return message
def change_message(self, type_, message):
"""Changes the message specified in by the type parameter"""
with closing(open(self.message_file, "rb")) as fl:
data = Pickle.load(fl)
with closing(open(self.message_file, "wb")) as fl:
data[type_] = message
Pickle.dump(data, fl)
def read_file(self, name):
"""Returns the contents of the data files containing the client details eg the balance file"""
try:
file_name = "bin/" + self.files[name]
except KeyError:
return False, "Invalid file name request"
try:
with closing(open(file_name, "rb")) as fl:
data = Pickle.load(fl)
if isinstance(data, list):
return True, data
else:
print file_name, type(data)
return False, "The %s file has been corrupted" % name
except EOFError:
return False, "The %s file has been corrupted or cannot be found" % name
except IOError:
return False, "The %s file does not exists" % name
class MessageController(FileManager):
def __init__(self, database_controller):
FileManager.__init__(self)
self.now = datetime.datetime.now()
self.db = database_controller
def central_command(self):
with closing(open(self.config_file, "rb")) as fl:
config = Pickle.load(fl)
def message_creator(message_type, message_details, message_recipients, message_):
deltas = list()
try:
interval = message_details["interval"]
except KeyError:
interval = []
if interval:
for days in interval:
if not isinstance(days, int):
continue
time_delta = datetime.timedelta(days=days)
delta = self.now + time_delta
deltas.append(delta)
compiled_list = list()
if message_type == "renewal":
for recipient in message_recipients:
name, phone, policy, date = recipient['Name'], recipient['Phone'],\
recipient['Policy'], recipient['To']
try:
values = dict()
values['POLICY'] = policy
values['DATE'] = date.date()
except AttributeError:
continue
t = string.Template(message_)
for delta in deltas:
if delta.date() == date.date() and phone is not None:
phone = phone.replace(' ', "")
compiled = ([name, phone], t.substitute(values))
compiled_list.append(compiled)
elif message_type == "newinvoice":
for recipient in message_recipients:
phone, policy, amount = recipient['Phone'], recipient['Policy'],\
recipient['Amount']
name = recipient['Name']
amount = math.ceil(amount*100)/100
values = dict()
values['POLICY'] = policy
values['AMOUNT'] = amount
t = string.Template(message_)
if phone is not None:
phone = phone.replace(' ', "")
compiled = ([name, phone], t.substitute(values))
compiled_list.append(compiled)
elif message_type == "balance":
try:
balance = message_details["amount"]
if not isinstance(balance, int):
return
except KeyError:
self.reporter(("Error", "Minimum balance amount is not specified"))
return
for recipient in message_recipients:
phone, amount = recipient['Phone'], recipient['Amount']
amount = math.ceil(amount*100)/100
name = recipient['Name']
values = dict()
values['AMOUNT'] = amount
t = string.Template(message_)
if int(amount) > balance and phone is not None:
phone = phone.replace(' ', "")
compiled = ([name, phone], t.substitute(values))
compiled_list.append(compiled)
elif message_type == "check":
for recipient in message_recipients:
due_date, name, amount, phone = recipient['Due'], recipient['Name'],\
recipient['Amount'], recipient['Phone']
values = dict()
values['NAME'] = name
values['DUE'] = due_date
values['AMOUNT'] = amount
t = string.Template(message_)
if not isinstance(due_date, datetime):
continue
for delta in deltas:
if delta.date() == due_date.date() and phone is not None:
phone = phone.replace(' ', "")
compiled = ([name, phone], t.substitute(values))
compiled_list.append(compiled)
elif message_type == "birthday":
for recipient in message_recipients:
name, dob, phone = recipient['Name'], recipient['dob'], recipient['Phone']
if phone is not None and dob is not None:
if self.now.month == dob.date().month and self.now.day == dob.date().day:
phone = phone.replace(' ', "")
compiled = ([name, phone], message_)
compiled_list.append(compiled)
else:
print "Cannot find the type specified"
return compiled_list
for key, type_ in self.files.items():
message_type_ = config[key]
if not message_type_['status']:
self.reporter((key, "%s has been disabled"))
continue
with closing(open(self.message_file, "rb")) as fl:
messages = Pickle.load(fl)
try:
message = messages[key]
except KeyError:
self.reporter((False, "Controller cannot find %s messages" % key))
continue
try:
details = config[key]
except KeyError:
self.reporter((False, "Configurations for %s is missing" % key))
continue
get_recipients = self.read_file(key)
if get_recipients[0]:
recipients = get_recipients[1]
msg = "Collecting %s files" % key
log.debug(msg)
print >>sys.stdout , msg
if isinstance(message_creator(key, details, recipients, message), list):
complete_list = message_creator(key, details, recipients, message)
else:
msg = "Error in collecting %s details" % key
self.reporter(("Error", msg))
log.warning(msg)
print >>sys.stdout , msg
continue
for every_msg in complete_list:
inst = PhoneNumber(every_msg[0][1])
phn = inst.list_of_numbers()
if phn:
self.db.add_outbox([every_msg[0][0], phn[0], "waiting", every_msg[1], self.now])
else:
print "Cant get recipients for %s" % key
class PhoneNumber(object):
def __init__(self, phn):
self.phn = phn
def list_of_numbers(self):
if isinstance(self.phn, list):
return self.list_phoneno_formater(self.phn)
elif isinstance(self.phn, long):
return self.int_phoneno_formater(self.phn)
elif isinstance(self.phn, int):
return self.int_phoneno_formater(self.phn)
elif isinstance(self.phn, str):
return self.str_phoneno_formater(self.phn)
else:
return "Wrong format"
def list_phoneno_formater(self, the_list):
valid_list = []
for number in the_list:
if self.phone_no_validator(number) is not False:
valid_list.append(self.phone_no_validator(number))
if not valid_list:
return []
else:
return valid_list
def int_phoneno_formater(self, the_int):
valid_list = []
if self.phone_no_validator(the_int) is not False:
valid_list.append(self.phone_no_validator(the_int))
return valid_list
else:
return []
def str_phoneno_formater(self, the_str):
valid_list = []
the_str.replace(' ', "")
if self.phone_no_validator(the_str) is not False:
valid_list.append(self.phone_no_validator(the_str))
return valid_list
else:
return []
def phone_no_validator(self, phnno):
try:
phnno = str(phnno)
if phnno[0] != "+":
int(phnno)
except ValueError:
return False
phnno.replace(' ', "")
length = len(phnno)
if length < 9:
return False
elif length == 9:
if phnno[:1] == "0":
print phnno, "has less values"
return False
return "%s%s" % ("+254", phnno)
elif length == 10:
return "%s%s" % ("+254", phnno[1:])
elif length == 12:
if phnno[:3] == "254":
return "%s%s" % ("+", phnno)
else:
return False
elif length == 13:
if phnno[:4] == "+254":
return phnno
else:
return False
else:
return False
class Initializer:
def __init__(self):
self.nothing = ""
self.folder_handler()
def folder_handler(self):
folders = ["bin", "database"]
for folder in folders:
try:
os.mkdir(folder)
except OSError:
continue
def important_files(self):
self.nothing = ""
if os.path.exists("bin/details.txt"):
return
with closing(open("bin/details.txt", "w")) as fl:
fl.write(time.ctime())
return True
class Controller(object, Initializer):
def __init__(self):
self.now = datetime.datetime.today()
self.latter = datetime.timedelta(hours=24) + self.now
self.db = DatabaseManager()
self.sec = Security()
self.user = self.sec.user
self.password = self.sec.password
self.dialect = self.sec.dialect
self.database = self.sec.database
self.db.connect(dialect=self.dialect, user=self.user, passwd=self.password, database=self.database)
self.waiting_messages = list()
Initializer.__init__(self)
def daily_messenger(self):
"""
Manages the application clock
"""
seconds = 30
while True:
time.sleep(seconds)
if self.now.hour < 8:
hour = (8 - self.now.hour) + 24
elif self.now.hour > 8:
hour = (24 - self.now.hour)
else:
hour = 24
self.latter = datetime.timedelta(hours=hour) + self.now
seconds = hour * 60 * 60
self.now = datetime.datetime.now()
msg = "Daily Thread initiating messenger"
log.info(msg)
print >>sys.stdout, msg
if self.time_checker():
log.debug("Daily Thread system update")
message_controller = MessageController(self.db)
message_controller.central_command()
self.message_sender()
with closing(open("bin/details.txt", "w")) as fl:
fl.write(time.ctime())
def hourly_messenger(self):
while True:
time.sleep(3600)
collect_data()
self.message_collector()
msg = "Hourly Thread initiating messenger"
log.info(msg)
print >>sys.stdout , msg
self.message_sender()
def hustler(self):
daily_thread = Thread(target=self.daily_messenger, name="Daily Thread")
hourly_thread = Thread(target=self.hourly_messenger, name="Hourly Thread")
daily_thread.start()
hourly_thread.start()
def message_collector(self):
self.waiting_messages = list()
messages = self.db.get_outbox("waiting")
if isinstance(messages, list) and messages:
for message in messages:
inst = PhoneNumber(message["phone"])
phn = inst.list_of_numbers()
if phn:
message_tuple = (message["phone"], message["message"])
else:
continue
self.waiting_messages.append(message_tuple)
def time_checker(self):
if not os.path.exists("bin/details.txt"):
return True
with closing(open("bin/details.txt", "rb")) as fl:
start_date = fl.readline()
if start_date[:10] == time.ctime()[:10]:
print False, start_date[:10], time.ctime()[:10]
return False
else:
print True, start_date[:10], time.ctime()[:10]
return True
def message_sender(self):
self.message_collector()
msg = "%d messages waiting to be sent" % len(self.waiting_messages)
log.info(msg)
print >>sys.stdout, msg
sent_list = []
for message in self.waiting_messages:
sender = Messenger([message])
sender.check_config("smsleopard")
sent_msg = sender.send_sms()[0]
sent_list.extend(sent_msg)
msg = "%d sent messages" % len(sent_list)
log.info(msg)
for sent in sent_list:
self.db.update_outbox(sent)
def collect_data():
seconds = 0
while True:
time.sleep(seconds)
serverManager.runKlass(("admin", "passwd"))
seconds += 60
def main():
FileManager()
cont = Controller()
cont.hustler()
cont.db.add_server_log((cont.now, "Loop 1: Scrapping for messages"))
if __name__ == '__main__':
log.info("Starting off the system")
msg = "Starting off the system"
print >>sys.stdout , msg
thr1 = Thread(target=check_network_connection, name="Network Manager")
t = Thread(target=main, name="Main thread")
thr1.start()
t.start()
collect_data()