-
Notifications
You must be signed in to change notification settings - Fork 2
/
ioServ.py
344 lines (268 loc) · 11.3 KB
/
ioServ.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
import os
import sys
from datetime import datetime, timedelta
from math import floor
from time import strftime
import guiType
loadOptions = True
defaultOptions = fileData = {"ioForm": "%H:%M:%S %d.%m.%Y", "pathTime": "./times/", "autoClockOut": "00:00:00",
"autoClockLim": "04:30:00", "usernameFile": "usernameFile.txt", "adminPass": "",
"seasons": {"Build": {"start": "00:00:00 06.01.2018", "end": "23:59:59 20.02.2018", "hoursPerWeek": 0},
"Competition": {"start": "00:00:00 21.03.2018", "end": "23:59:59 14.04.2018", "hoursPerWeek": 0}},
"positions": ["Student", "Mentor", "Adult", "Other"],
"teams": ["Programming", "Mechanical", "Media", "Woodworking", "Mentors", "Other"]}
try:
import rapidjson
except ImportError as e:
print("Please install the rapidjson library so the so the options file can be loaded.")
loadOptions = False
# if not os.path.isdir(opts["path"]): os.mkdir(opts["path"])
# open(opts["name.txt"], "a").close() # create name file if it doesnt exist
def loadOpts():
opts = {}
if loadOptions:
os.chdir(os.path.dirname(__file__))
if not os.path.exists("opts.json"):
generateDefaultOpts()
with open("opts.json") as optsFile: # load options
opts = rapidjson.load(optsFile)
return opts
else:
return defaultOptions
def generateDefaultOpts():
print("generated opts")
# BuildHrsRqd : 54
os.chdir(os.path.dirname(__file__))
with open("opts.json", "w") as optsFile:
rapidjson.dump(defaultOptions, optsFile, indent=2)
opts = loadOpts()
def signIO(n, c):
nameIO = n
timeIO = strftime(opts["ioForm"])
pathIO = opts["pathTime"] + nameIO.replace(" ", "") + ".txt"
msg, color = "Nothing", "black"
open(pathIO, "+a").close() # make file if it doesn"t exist
with open(pathIO, "+r") as f:
lines = [line.strip() for line in f]
inTimeFrame = False
if lines:
lim = [int(x) for x in opts["autoClockLim"].split(":")]
theNow = datetime.now()
theIOA = datetime.strptime(lines[-1][5:], opts["ioForm"])
theLIM = theIOA.replace(
hour=lim[0], minute=lim[1], second=lim[2], microsecond=0) + timedelta(days=1)
inTimeFrame = theIOA < theNow < theLIM
name1st = nameIO.split()[0] # first name
if lines and lines[-1][0] == "a" and c == "o" and inTimeFrame:
## RECOVERING AUTOCLOCKOUT ##
with open(pathIO, "w+") as f:
f.write("\n".join(lines[:-1]) + "\n" + c + " | " + timeIO + "\n")
msg, color = name1st + " signed out proper!", "green"
return msg, color
elif lines and lines[-1][0] == "a" and c == "i" and inTimeFrame:
## SIGNING IN WHEN SEMI CLOCKED OUT ##
msg, color = "Did you mean to sign out to recover hours, " + name1st + "?", "orange"
elif lines and ((lines[-1][0] in "i!" and c == "i") or (lines[-1][0] in "o@" and c == "o") or (lines[-1][0] == "a" and c == "o" and not inTimeFrame)):
## DOUBLE SIGN IN/OUT ##
color = "orange"
if c == "i":
msg = name1st + " is already signed in!"
c = "!"
elif c == "o":
if lines[-1][0] in "o@":
msg = name1st + " is already signed out!"
elif lines[-1][0] == "a":
msg = name1st + " was auto-signed out!"
c = "@"
# return msg,color
elif not lines and c == "o":
## NEVER SIGNED IN BEFORE ##
msg, color = name1st + " has never signed in!", "orange"
return msg, color
else:
## NORMAL SIGN IN ##
hrs = 0
inSeason = False
currentSeason = "Off"
timet = 0
for season in opts["seasons"]:
v = calcSeasonTime(nameIO, season)
inSeason, timet = v[0], v[1]
timet = min(int(timet // 3600), 999)
currentSeason = season
if inSeason:
break
else:
currentSeason = "Off"
timet = min(int(calcTotalTime(nameIO) // 3600), 999)
limit = "8"
if currentSeason + "Hrs/Wk" in opts:
limit = str(opts[currentSeason + "Hrs/Wk"])
# calculate total time in seconds then convert to hours (rounded 2 dec places)
hours = str(floor(hrs / 3600 * 100) / 100)
weekh = str(floor(calcWeekTime(nameIO.replace(" ", "")) /
3600 * 100) / 100) # calculate current week time
if c == "i":
msg, color = name1st + " signed in! " + hours + \
" hours.\n" + weekh + " of " + limit + " hours.", "Green"
elif c == "o":
msg, color = name1st + " signed out! " + hours + \
" hours.\n" + weekh + " of " + limit + " hours.", "Red"
with open(pathIO, "a+") as f:
f.write(c + " | " + timeIO + "\n")
return msg, color
def checkNameDB(n): # check for if a name exists already
for line in open(opts["usernameFile"]):
for item in line.split("|"):
if item.lower().replace(" ", "") == n.lower().replace(" ", ""):
return True
return False
def addNameDB(full, user, title="None", job="None"): # add a new name to the list
file = open(opts["usernameFile"], "a+")
file.write(" | ".join([full.title(), user.lower(), title, job]) + "\n")
file.close()
def sortUsernameList(): # alphebetize names
def findCapitals(s): # for generating usernames
letters = ""
for i in s:
if i.isupper():
letters += i
return letters
with open(opts["usernameFile"]) as u:
names = []
for l in u.readlines():
l = l.strip().split(" | ")
l[0] = l[0].title() # full name
if len(l) >= 2: # user key
l[1] = l[1].lower()
else:
l += [findCapitals(l[0]).lower()]
if len(l) < 3 or l[2] == "":
l += ["none"] # if no title listed
if len(l) < 4 or l[3] == "":
l += ["none"] # if no job listed
names += [" | ".join(l[:4]) + "\n"]
names.sort()
with open(opts["usernameFile"], "w") as f:
f.write("".join(names))
def calcTotalTime(n):
return calcUserTime(n)
def calcWeekTime(n):
dt = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
firstDayOfWeek = (dt - timedelta(days=dt.isoweekday())) # last sunday
lastDayOfWeek = (firstDayOfWeek + timedelta(days=7)) # next sunday
firstDayOfWeek = firstDayOfWeek.strftime(opts["ioForm"])
lastDayOfWeek = lastDayOfWeek.strftime(opts["ioForm"])
return calcUserTime(n, startIO=firstDayOfWeek, endIO=lastDayOfWeek)
def calcSeasonTime(name, season, ignoreCheck=False):
if not ignoreCheck and not (datetime.strptime(opts["seasons"][season]["start"], opts["ioForm"]) <= datetime.now() <= datetime.strptime(opts["seasons"][season]["end"], opts["ioForm"])):
return False, 0, 0
currentDate = datetime.now()
buildStart = datetime.strptime(
opts["seasons"][season]["start"], opts["ioForm"])
buildLeave = datetime.strptime(
opts["seasons"][season]["end"], opts["ioForm"])
buildDelta = currentDate - buildStart
daysSinceStart = max(buildDelta.days, 0)
totalTime = calcUserTime(
name, startIO=opts["seasons"][season]["start"], endIO=opts["seasons"][season]["end"])
return True, totalTime, daysSinceStart
def calcUserTime(name, startIO=None, endIO=None):
if len(name) > guiType.maxName:
name = name[:guiType.maxName]
filename = opts["pathTime"] + name.strip().replace(" ", "") + \
".txt" # generate filename
# ensure the file exists
try:
open(filename, "r").close()
except FileNotFoundError:
print(name + "'s file was not found!")
return 0
# should the times be between specific dates?
checkTimes = False
if startIO != None and endIO == None:
raise ValueError("startIO defined, but endIO not defined")
if startIO == None and endIO != None:
raise ValueError("endIO defined, but startIO not defined")
if startIO != None and endIO != None:
checkTimes = True
startIO = datetime.strptime(startIO, opts["ioForm"])
endIO = datetime.strptime(endIO, opts["ioForm"])
currentDate = datetime.now()
lastTime = datetime.now()
lastState = "n"
totalTime = 0
for line in open(filename, "r"):
line = line.strip().split(" | ")
if not line:
continue # if nothing on line, skip line
state = line[0]
linetime = line[1]
datatime = datetime.strptime(linetime, opts["ioForm"])
if state in "!@":
continue # ensure this isnt a double
if checkTimes and datatime < startIO:
continue # skip until in timeframe
if state == "i":
pass
elif state == "o":
if lastState == "i":
totalTime += (datatime - lastTime).total_seconds()
lastTime = datatime
lastState = state
if checkTimes and datatime > endIO:
break # if left timeframe then finish
else: # if finished with no breaks
# add current time if still signed in
if lastState == "i":
totalTime += (currentDate - lastTime).total_seconds()
return totalTime
def calcUserData(name):
userdata = name + "'s TimeData\n"
userdata += "Total Time: " + str(calcUserTime(name) // 3600)
for season in opts["seasons"]:
try:
if opts["seasons"][season]["start"] and opts["seasons"][season]["end"]:
userdata += "\n" + season + " Time: " + \
str(calcSeasonTime(name, season,
ignoreCheck=True)[1] // 3600)
except KeyError:
print("Season \"" + season + "\" does not exist in opts.txt! Please give it a " +
season + "Start and " + season + "Leave time value!")
return userdata
def mkfile(t): open(t, "a+").close() # make files if they dont exist
def loadUsers():
allusers = {}
for line in open(opts["usernameFile"], "r+"):
l = line.split(" | ") # name | username | title | jobs
allusers[l[2]] = (allusers[l[2]] or []) + []
def calcSlackTimeString():
names = []
seasontimes = {}
longestname = 0
currentSeason = "Off"
for line in open(opts["usernameFile"], "r+"):
name = line.strip().split(" | ")[0]
print(name)
names += [name]
longestname = max(len(name), longestname)
inSeason = False
timet = 0
days = 0
for season in opts["seasons"]:
inSeason, seasontimes[name], days = calcSeasonTime(name, season)
currentSeason = season
if inSeason:
break
else:
currentSeason = "Off"
seasontimes[name], days = calcWeekTime(name), 0
seasontimes[name] = int(seasontimes[name] // 3600)
topstr = "Name" + " " * (longestname - 4) + \
" - Season (" + currentSeason + ")\n\n"
for name in names:
totaltime = str(times[name])
seasontime = str(seasontimes[name])
topstr += name + " " * (longestname - len(name)) + " - " + \
" " * (5 - len(seasontime)) + str(seasontimes[name]) + "\n"
return "```" + topstr + "```"