forked from stopipv/isdi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
266 lines (218 loc) · 6.79 KB
/
db.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
import sqlite3
from flask_sqlalchemy import SQLAlchemy
import config
from flask import g
from datetime import datetime as dt
import config
import os
import pandas as pd
DATABASE = config.SQL_DB_PATH.replace('sqlite:///', '').strip()
#CONSULTS_DATABASE = config.SQL_DB_CONSULT_PATH.replace('sqlite:///', '')
def today():
db = get_db()
t = dt.now()
today = t.strftime('%Y%m%d')
return today
def new_client_id():
last_client_id = query_db(
'select max(clientid) as cid from clients_notes '
'where created_at > datetime("now", "localtime", "start of day")',
one=True
)['cid']
d, t = today(), 0
# FIXME: won't parse if different ClientID.
if last_client_id:
d, t = last_client_id.rsplit('_', 1)
cid = '{}_{:03d}'.format(d, int(t) + 1)
print("new_client_id >>>> {}".format(cid))
return cid
def make_dicts(cursor, row):
return dict((cursor.description[idx][0], value)
for idx, value in enumerate(row))
def get_db():
db = getattr(g, '_database', None)
if db is None:
print("Creating new db connection {}".format(DATABASE))
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = make_dicts
return db
def init_db(app, sa, force=False):
with app.app_context():
if force or not os.path.exists(DATABASE):
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
#sa.create_all() # TODO replace in schema.sql
# TODO how to repopulate?
#if not os.path.exists(CONSULTS_DATABASE):
# sa.create_all()
# add with sqlachemy the new models stuff
# can it get the schema sql // make a table
else:
db = get_db()
def insert(query, args):
db = get_db()
cur = db.execute(query, args)
lrowid = cur.lastrowid
cur.close()
db.commit()
return lrowid
def insert_many(query, argss):
db = get_db()
cur = db.executemany(query, argss)
lrowid = cur.lastrowid
cur.close()
db.commit()
return lrowid
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
lrowid = cur.lastrowid
cur.close()
return (rv[0] if rv else None) if one else rv
def save_note(scanid, note):
insert("update scan_res set note=? where id=?",
args=(note, scanid))
return True
def create_scan(scan_d):
"""
@scanr must have following fields.
"""
print(scan_d)
return insert(
"insert into scan_res "
"(clientid, serial, device, device_model, device_version, device_manufacturer, last_full_charge, device_primary_user, is_rooted, rooted_reasons) "
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
args=(
scan_d['clientid'],
scan_d['serial'],
scan_d['device'],
scan_d['device_model'],
scan_d['device_version'],
scan_d['device_manufacturer'],
scan_d['last_full_charge'],
scan_d['device_primary_user'],
scan_d['is_rooted'],
scan_d['rooted_reasons']))
def update_appinfo(scanid, appid, remark, action):
return insert("update app_info set "
"remark=?, action_taken=? where scanid=? and appid=?",
args=(remark, action, scanid, appid),
) == 0
def update_app_deleteinfo(scanid, appid, remark):
return insert("update app_info set "
"remark=? here scanid=? and appid=?",
args=(remark, action, scanid, appid),
)
def update_mul_appinfo(args):
return insert_many("update app_info set "
"remark=? where scanid=? and appid=?",
args
)
def create_appinfo(scanid, appid, flags, remark='', action='<new>'):
"""
@scanr must have following fields.
"""
return insert(
"insert into app_info (scanid, appid, flags, remark, action_taken) "
"values (?,?,?,?,?)",
args=(scanid, appid, flags, remark, action)
)
def create_mult_appinfo(args):
"""
"""
return insert_many(
"insert into app_info (scanid, appid, flags, remark, action_taken) values (?,?,?,?,?)",
args)
def get_is_rooted(serial):
try:
d = query_db(
'select id, is_rooted, rooted_reasons from scan_res where serial=?',
args=(serial), one=False
)
if d:
d = d[0]
return d['is_rooted'], d['rooted_reasons']
except Exception as e:
return "<ROOTED_ERR>", "<ROOTED_ERR>"
def get_device_info(ser: str) -> dict:
d = query_db(
'select id,device,device_model,serial,device_primary_user from scan_res where serial=?',
args=(ser,), one=True
)
if d:
return d
else:
return {}
def get_client_devices_from_db(clientid: str) -> list:
# TODO: change 'select serial ...' to 'select device_model ...' (setup
# first)
d = query_db(
'select id,device,device_model,serial,device_primary_user from scan_res where serial like "HSN_%" group by serial',
# args=(clientid,),
one=False
)
print("<>get_client_devices_from_db<>", d)
if d:
return d
else:
return [{}]
def get_most_recent_scan_id(ser: str) -> int:
d = query_db(
"select max(id) as scanid from scan_res where serial=?",
args=(ser,), one=True
)
print(f"Get_most_recent_scanid: {d}")
return d['scanid']
def get_scan_res_from_db(scanid):
d = query_db(
'select * from scan_res where id=?',
args=(scanid,), one=True
)
return d
def get_app_info_from_db(scanid):
d = query_db(
'select * from app_info where scanid=?',
args=(scanid,), one=False
)
if d:
return d
else:
return []
def get_device_from_db(scanid):
d = query_db(
'select device from scan_res where id=?',
args=(scanid,), one=True)
if d:
return d['device']
else:
return ''
def get_serial_from_db(scanid):
d = query_db(
'select serial from scan_res where id=?',
args=(
scanid,
),
one=True)
if d:
return d['serial']
else:
return ''
def first_element_or_none(l):
if l and len(l) > 0:
return l[0]
def create_report(clientid):
"""
Creates a report for a clientid
"""
reportf = os.path.join(config.REPORT_PATH, clientid + '.csv')
d = pd.DataFrame(
query_db(
"select * from scan_res inner join app_info on "
"scan_res.id=app_info.scanid where scan_res.clientid=?",
args=(
clientid,
)))
d.to_csv(reportf, index=None)
return d