-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeviceShare.py
More file actions
336 lines (279 loc) · 13.2 KB
/
DeviceShare.py
File metadata and controls
336 lines (279 loc) · 13.2 KB
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
import logging
from datetime import datetime, timedelta
logger = logging.getLogger(__name__)
class SimpleDeviceShareBot:
"""Core logic for SimpleDeviceShare bot - Public showcase version."""
def __init__(self):
self.users = {} # user_id: {username, working_days, ...}
self.pending_users = {}
self.usages = {'last_reset_date': datetime.now().strftime('%Y-%m-%d'), 'user_usages': {}}
self.device_logs = [] # [{'user_id', 'action', 'timestamp'}]
self.device_status = {'location': 'base', 'user_id': None, 'taken_time': None}
self.reset_daily_usages_if_needed()
def reset_daily_usages_if_needed(self):
"""Reset daily usages if it's a new day"""
today = datetime.now().strftime('%Y-%m-%d')
if self.usages['last_reset_date'] != today:
self.usages = {'last_reset_date': today, 'user_usages': {}}
def can_user_use_device(self, user_id):
"""Check if user can request device usage"""
today = datetime.now().strftime('%Y-%m-%d')
user_usages = self.usages['user_usages'].get(user_id, [])
today_usages = [u for u in user_usages if u.get('date') == today]
return len(today_usages) < 2
def add_usage(self, user_id):
"""Add a usage for the user today"""
today = datetime.now().strftime('%Y-%m-%d')
if user_id not in self.usages['user_usages']:
self.usages['user_usages'][user_id] = []
self.usages['user_usages'][user_id].append({'date': today, 'timestamp': datetime.now().isoformat()})
def log_device_action(self, user_id, action):
"""Log device take/return actions"""
self.device_logs.append({'user_id': user_id, 'action': action, 'timestamp': datetime.now().isoformat()})
if action == 'take':
self.device_status = {'location': 'user', 'user_id': user_id, 'taken_time': datetime.now()}
elif action == 'return':
self.device_status = {'location': 'base', 'user_id': None, 'taken_time': None}
def get_device_location(self):
"""Get current device location as string"""
if self.device_status['location'] == 'base':
return 'At base'
else:
username = self.users.get(self.device_status['user_id'], {}).get('username', 'Unknown')
return f"With {username}"
def overdue_check(self):
"""Check if device is overdue (more than 2 hours)"""
if self.device_status['location'] == 'user' and self.device_status['taken_time']:
delta = datetime.now() - self.device_status['taken_time']
if delta > timedelta(hours=2):
return True, self.device_status['user_id'], self.device_status['taken_time']
return False, None, None
def end_of_day_reset(self):
"""Reset device to base and clear logs (called at end of day or Monday noon)"""
self.device_logs.clear()
self.device_status = {'location': 'base', 'user_id': None, 'taken_time': None}
def delete_profile(self, user_id):
"""Delete user profile"""
if user_id in self.users:
username = self.users[user_id]['username']
del self.users[user_id]
# Clean up usages
if user_id in self.usages.get('user_usages', {}):
del self.usages['user_usages'][user_id]
return username
return None
def get_user_stats(self, user_id):
"""Get user's usage statistics"""
if user_id not in self.users:
return None
today = datetime.now().strftime('%Y-%m-%d')
user_usages = self.usages.get('user_usages', {}).get(user_id, [])
today_usages = [u for u in user_usages if u.get('date') == today]
return {
'username': self.users[user_id]['username'],
'today_usages': len(today_usages),
'remaining': 2 - len(today_usages),
'total_usages': len(user_usages),
'working_days': self.users[user_id]['working_days']
}
def is_working_day(self, user_id):
"""Check if today is a working day for the user"""
if user_id not in self.users:
return False
today = datetime.now().weekday()
return today in self.users[user_id]['working_days']
# Admin user creation
def admin_add_user(self, user_id, username, working_days):
"""Add user directly by admin"""
self.users[user_id] = {
'username': username,
'working_days': working_days,
'registration_time': datetime.now().isoformat(),
'added_by_admin': True
}
# Registration (user-initiated)
def user_register(self, user_id, username, working_days):
"""Register user (pending admin approval)"""
self.pending_users[user_id] = {
'username': username,
'working_days': working_days,
'registration_time': datetime.now().isoformat()
}
def approve_user(self, user_id):
"""Approve pending user registration"""
if user_id in self.pending_users:
self.users[user_id] = self.pending_users[user_id]
self.users[user_id]['approved_time'] = datetime.now().isoformat()
del self.pending_users[user_id]
return True
return False
def deny_user(self, user_id):
"""Deny pending user registration"""
if user_id in self.pending_users:
del self.pending_users[user_id]
return True
return False
def get_admin_stats(self):
"""Get admin statistics"""
total_users = len(self.users)
pending_users = len(self.pending_users)
total_logs = len(self.device_logs)
# Count today's usages
today = datetime.now().strftime('%Y-%m-%d')
today_usages = 0
active_users_today = set()
for user_id, user_usages in self.usages.get('user_usages', {}).items():
for usage in user_usages:
if usage.get('date') == today:
today_usages += 1
active_users_today.add(user_id)
return {
'total_users': total_users,
'pending_users': pending_users,
'total_logs': total_logs,
'today_usages': today_usages,
'active_users_today': len(active_users_today),
'device_location': self.get_device_location()
}
def get_available_tokens(self, user_id):
"""Get list of available tokens from absent users"""
if user_id not in self.users:
return []
available_tokens = []
for other_user_id, other_user in self.users.items():
if other_user_id != user_id and not self.is_working_day(other_user_id):
# Check if this token is not already used today
if not self.is_token_used_today(other_user_id):
available_tokens.append({
'user_id': other_user_id,
'username': other_user['username'],
'working_days': other_user['working_days']
})
return available_tokens
def is_token_used_today(self, token_owner_id):
"""Check if a specific token is already used today"""
today = datetime.now().strftime('%Y-%m-%d')
for request_user_id, user_requests in self.usages.get('user_usages', {}).items():
for request in user_requests:
if request.get('date') == today and request.get('token_owner_id') == token_owner_id:
return True
return False
def use_token(self, requesting_user_id, token_owner_id):
"""Use a specific token from an absent user"""
if token_owner_id not in self.users:
return False, "Token owner not found"
# Check if requesting user is working today (can use tokens)
if not self.is_working_day(requesting_user_id):
return False, "You are absent today and cannot use tokens"
# Check if token owner is absent today (token is available)
if self.is_working_day(token_owner_id):
return False, "Token owner is working today, token not available"
if self.is_token_used_today(token_owner_id):
return False, "Token already used today"
# Add the token usage
today = datetime.now().strftime('%Y-%m-%d')
if requesting_user_id not in self.usages['user_usages']:
self.usages['user_usages'][requesting_user_id] = []
self.usages['user_usages'][requesting_user_id].append({
'date': today,
'timestamp': datetime.now().isoformat(),
'token_owner_id': token_owner_id,
'type': 'token_usage'
})
# Log the token usage
self.device_logs.append({
'user_id': requesting_user_id,
'action': 'use_token',
'token_owner_id': token_owner_id,
'timestamp': datetime.now().isoformat()
})
return True, "Token used successfully"
def get_random_available_token(self, user_id):
"""Get a random available token"""
available_tokens = self.get_available_tokens(user_id)
if available_tokens:
import random
return random.choice(available_tokens)
return None
def can_use_tokens(self, user_id):
"""Check if user can use any tokens (has available tokens)"""
return len(self.get_available_tokens(user_id)) > 0
# Admin token management methods
def admin_mark_token_used(self, token_owner_id, used_by_user_id=None):
"""Admin: Mark a specific token as used today"""
if token_owner_id not in self.users:
return False, "Token owner not found"
today = datetime.now().strftime('%Y-%m-%d')
# Check if token is already used
if self.is_token_used_today(token_owner_id):
return False, "Token already used today"
# Mark as used by admin
if used_by_user_id not in self.usages['user_usages']:
self.usages['user_usages'][used_by_user_id] = []
self.usages['user_usages'][used_by_user_id].append({
'date': today,
'timestamp': datetime.now().isoformat(),
'token_owner_id': token_owner_id,
'type': 'admin_marked_used'
})
# Log the admin action
self.device_logs.append({
'user_id': used_by_user_id or 'admin',
'action': 'admin_mark_token_used',
'token_owner_id': token_owner_id,
'timestamp': datetime.now().isoformat()
})
return True, "Token marked as used"
def admin_mark_token_expired(self, token_owner_id):
"""Admin: Mark a specific token as expired (reset for today)"""
if token_owner_id not in self.users:
return False, "Token owner not found"
today = datetime.now().strftime('%Y-%m-%d')
# Remove all usages of this token today
for user_id, user_usages in self.usages.get('user_usages', {}).items():
self.usages['user_usages'][user_id] = [
usage for usage in user_usages
if not (usage.get('date') == today and usage.get('token_owner_id') == token_owner_id)
]
# Log the admin action
self.device_logs.append({
'user_id': 'admin',
'action': 'admin_mark_token_expired',
'token_owner_id': token_owner_id,
'timestamp': datetime.now().isoformat()
})
return True, "Token expired and reset"
def admin_reset_token(self, token_owner_id):
"""Admin: Reset a specific token (remove all today's usages)"""
if token_owner_id not in self.users:
return False, "Token owner not found"
today = datetime.now().strftime('%Y-%m-%d')
# Remove all usages of this token today
for user_id, user_usages in self.usages.get('user_usages', {}).items():
self.usages['user_usages'][user_id] = [
usage for usage in user_usages
if not (usage.get('date') == today and usage.get('token_owner_id') == token_owner_id)
]
# Log the admin action
self.device_logs.append({
'user_id': 'admin',
'action': 'admin_reset_token',
'token_owner_id': token_owner_id,
'timestamp': datetime.now().isoformat()
})
return True, "Token reset successfully"
def admin_get_token_status(self):
"""Admin: Get status of all tokens for today"""
today = datetime.now().strftime('%Y-%m-%d')
token_status = {}
for user_id, user_data in self.users.items():
is_working = self.is_working_day(user_id)
is_used = self.is_token_used_today(user_id)
token_status[user_id] = {
'username': user_data['username'],
'working_today': is_working,
'available': not is_working and not is_used,
'used_today': is_used,
'working_days': user_data['working_days']
}
return token_status