AdminManage.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. # -*- coding: utf-8 -*-
  2. import time
  3. from datetime import date, timedelta, timezone as asj_timezone
  4. import boto3
  5. from django.db.models import Count,Q
  6. from django.views.decorators.csrf import csrf_exempt
  7. from django.views.generic import TemplateView
  8. from django.utils.decorators import method_decorator
  9. from django.contrib.auth.hashers import make_password # 对密码加密模块
  10. from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel, AppFrequencyYearStatisticsModel, \
  11. AppFrequencyStatisticsModel, EquipmentInfoExStatisticsModel, Equipment_Info
  12. from Service.ModelService import ModelService
  13. from django.utils import timezone
  14. from Model.models import Access_Log, Device_User
  15. from django.views.decorators.http import require_http_methods
  16. from Object.ResponseObject import ResponseObject
  17. from Object.TokenObject import TokenObject
  18. from Ansjer.config import OFF_LINE_TIME_DELTA, DEVICE_TYPE, AWS_SES_ACCESS_ID, AWS_SES_ACCESS_SECRET, \
  19. AWS_SES_ACCESS_REGION_WEST
  20. import datetime, simplejson as json
  21. from Service.CommonService import CommonService
  22. from Object.RedisObject import RedisObject
  23. '''
  24. http://192.168.136.40:8077/adminManage/manage?operation=getAllDeviceArea&token=debug
  25. http://192.168.136.40:8077/adminManage/manage?operation=getAllUserName&token=debug
  26. http://192.168.136.40:8077/adminManage/manage?operation=getAllUID&token=debug
  27. http://127.0.0.1:8000/adminManage/manage?operation=getAllOnLine&token=stest
  28. http://127.0.0.1:8000/adminManage/manage?operation=getOnLine&token=stest
  29. '''
  30. class AdminManage(TemplateView):
  31. @method_decorator(csrf_exempt)
  32. def dispatch(self, *args, **kwargs):
  33. return super(AdminManage, self).dispatch(*args, **kwargs)
  34. def get(self, request, *args, **kwargs):
  35. request.encoding = 'utf-8'
  36. return self.validation(request_dict=request.GET)
  37. def post(self, request, *args, **kwargs):
  38. request.encoding = 'utf-8'
  39. return self.validation(request_dict=request.POST)
  40. def validation(self, request_dict, *args, **kwargs):
  41. response = ResponseObject()
  42. token = request_dict.get('token', None)
  43. tko = TokenObject(token)
  44. response.lang = tko.lang
  45. if tko.code != 0:
  46. return response.json(tko.code)
  47. userID = tko.userID
  48. operation = request_dict.get('operation', None)
  49. if userID is None or operation is None:
  50. return response.json(444, 'operation')
  51. if operation == 'resetUserPwd':
  52. return self.resetUserPwd(request_dict, userID, response)
  53. if operation == 'getAllOnLine':
  54. return self.getAllOnLine(userID, response)
  55. if operation == 'getOnLine':
  56. return self.getRedisOnline(userID, response)
  57. # return self.getOnLine(userID, response)
  58. if operation == 'getAllUserName':
  59. return self.getAllUserName(userID, response)
  60. if operation == 'getStatisAccess':
  61. return self.getStatisAccess(userID, request_dict, response)
  62. if operation == 'getAllUID':
  63. return self.getAllUID(userID, response)
  64. if operation == 'getAllDeviceArea':
  65. return self.getAllDeviceArea(userID, response)
  66. if operation == 'getUserBrand':
  67. return self.getUserBrand(userID, response)
  68. if operation == 'getAreaDeviceType':
  69. return self.getAreaDeviceType(userID, response)
  70. if operation == 'getDeviceType':
  71. return self.getDeviceType(userID, response)
  72. if operation == 'getAppFrequency':
  73. return self.getAppFrequency(userID, request_dict, response)
  74. if operation == 'getHistoryAppFrequency':
  75. return self.getAllAppFrequency(userID, response)
  76. if operation == 'getPushStatistics':
  77. return self.query_push_by_level(userID, request_dict, response)
  78. if operation == 'getPushFailures':
  79. return self.query_failures_push(userID, request_dict, response)
  80. if operation == 'getPushServerCPUUsage':
  81. return self.query_push_server_cpu_usage(userID, request_dict, response)
  82. def resetUserPwd(self, request_dict, userID, response):
  83. own_permission = ModelService.check_perm(userID=userID, permID=50)
  84. if not own_permission:
  85. return response.json(404)
  86. duserID = request_dict.get('duserID', None)
  87. userPwd = request_dict.get('userPwd', None)
  88. if not duserID:
  89. return response.json(444, 'duserID')
  90. UserValid = Device_User.objects.filter(userID=duserID)
  91. if UserValid:
  92. if userPwd is None:
  93. userPwd = '123456'
  94. is_update = UserValid.update(password=make_password(userPwd))
  95. if is_update:
  96. return response.json(0)
  97. else:
  98. return response.json(177)
  99. else:
  100. return response.json(104)
  101. def getAllUserName(self, userID, response):
  102. # 权限固定为30
  103. own_permission = ModelService.check_perm(userID=userID, permID=30)
  104. if own_permission is not True:
  105. return response.json(404)
  106. username_list = Device_User.objects.all().values_list('username', flat=True)
  107. if username_list:
  108. return response.json(0, {'username_list': list(username_list)})
  109. else:
  110. return response.json(0)
  111. # 获取全部用户的在线个数
  112. def getAllOnLine(self, userID, response):
  113. # 权限固定为30
  114. own_permission = ModelService.check_perm(userID=userID, permID=30)
  115. if own_permission is not True:
  116. return response.json(404)
  117. allonline = Device_User.objects.all().values('online')
  118. # 两个变量,分别是在线,离线
  119. onlinenum = 0
  120. noonlinenum = 0
  121. for q in allonline:
  122. if q['online'] == True:
  123. onlinenum += 1
  124. else:
  125. noonlinenum += 1
  126. print("在线人数:")
  127. print(onlinenum)
  128. return response.json(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})
  129. # 获取全部用户的在线人数
  130. def getOnLine(self, userID, response):
  131. # 权限固定为30
  132. own_permission = ModelService.check_perm(userID=userID, permID=30)
  133. if own_permission is True:
  134. online_list = Device_User.objects.all().values('online', 'last_login')
  135. # 两个变量,分别是在线,离线
  136. onlinenum = 0
  137. noonlinenum = 0
  138. for q in online_list:
  139. # print(q['last_login'] )
  140. # 最后访问时间加5分种
  141. dl_time = q['last_login'] + datetime.timedelta(minutes=OFF_LINE_TIME_DELTA)
  142. # print(dl_time)
  143. # 当前时间
  144. now_time = timezone.localtime(timezone.now())
  145. # print(now_time)
  146. # 如果当前时间大于最后访问的时间
  147. if now_time < dl_time:
  148. onlinenum += 1
  149. else:
  150. noonlinenum += 1
  151. print("在线人")
  152. print(onlinenum)
  153. return response.json(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})
  154. else:
  155. return response.json(404)
  156. # 获取全部用户的在线人数
  157. def getRedisOnline(self, userID, response):
  158. # 权限固定为30
  159. own_perm = ModelService.check_perm(userID, 30)
  160. if own_perm:
  161. count = int(Device_User.objects.count())
  162. redisObj = RedisObject(db=3)
  163. onlines = int(redisObj.get_size())
  164. print(onlines)
  165. return response.json(0, {"onlinenum": onlines, "no_onlinenum": count - onlines})
  166. else:
  167. return response.json(404)
  168. # 获取所有设备地区
  169. def getAllDeviceArea(self, userID, response):
  170. own_permission = ModelService.check_perm(userID=userID, permID=30)
  171. if own_permission is True:
  172. qs = Device_Info.objects.all().values('area', 'UID')
  173. uid_area_dict = {}
  174. for q in qs:
  175. if q['UID'] and q['area']:
  176. uid_area_dict[q['UID']] = q['area']
  177. if len(uid_area_dict):
  178. area_dict = {}
  179. for k, v in uid_area_dict.items():
  180. if v in area_dict:
  181. area_dict[v] += 1
  182. else:
  183. area_dict[v] = 1
  184. return response.json(0, {'area': area_dict})
  185. else:
  186. return response.json(0)
  187. else:
  188. return response.json(404)
  189. '''
  190. 统计一天访问量
  191. http://192.168.136.45:8077/adminManage/manage?token=test&operation=getStatisAccess&timestamp=1528773308
  192. '''
  193. def getStatisAccess(self, userID, request_dict, response):
  194. own_permission = ModelService.check_perm(userID=userID, permID=30)
  195. if own_permission is not True:
  196. return response.json(404)
  197. time_stamp = int(request_dict.get('timestamp', None))
  198. times = datetime.datetime.fromtimestamp(time_stamp)
  199. time_dict = CommonService.getTimeDict(times)
  200. res = {}
  201. for k, v in time_dict.items():
  202. start_date = time_dict[k]
  203. end_date = time_dict[k] + datetime.timedelta(hours=1)
  204. count = Access_Log.objects.filter(time__range=(start_date, end_date)).count()
  205. if count:
  206. res[k] = count
  207. else:
  208. res[k] = 0
  209. return response.json(0, {'count': res})
  210. def getAllUID(self, userID, response):
  211. own_permission = ModelService.check_perm(userID=userID, permID=30)
  212. if own_permission is not True:
  213. return response.json(404)
  214. uid_list = Device_Info.objects.all().values_list('UID', flat=True)
  215. res = {}
  216. if uid_list:
  217. res = {'count': uid_list.count(), 'uid_list': list(uid_list)}
  218. return response.json(0, res)
  219. def getUserBrand(self, userID, response):
  220. own_permission = ModelService.check_perm(userID=userID, permID=30)
  221. if own_permission is not True:
  222. return response.json(404)
  223. # 手机型号统计
  224. print('手机型号统计:')
  225. ub_qs = User_Brand.objects.values('deviceSupplier', 'deviceModel').annotate(value=Count('id')).order_by()
  226. res = {
  227. 'value': 0,
  228. 'data': []
  229. }
  230. data = res['data']
  231. tmpDict = {}
  232. for ub in ub_qs:
  233. deviceSupplier = ub['deviceSupplier']
  234. if not tmpDict.__contains__(deviceSupplier):
  235. tmpDict[deviceSupplier] = {
  236. 'name': deviceSupplier,
  237. 'value': 0,
  238. 'children': []
  239. }
  240. item = tmpDict[deviceSupplier]
  241. item['value'] = item['value'] + ub['value']
  242. res['value'] = res['value'] + item['value']
  243. model = {
  244. 'name': ub['deviceModel'],
  245. 'value': ub['value']
  246. }
  247. item['children'].append(model)
  248. for k, v in tmpDict.items():
  249. data.append(v)
  250. print(res)
  251. return response.json(0, res)
  252. def getAreaDeviceType(self, userID, response):
  253. own_permission = ModelService.check_perm(userID=userID, permID=30)
  254. if own_permission is not True:
  255. return response.json(404)
  256. print('区域设备类型统计:')
  257. di_qs = Device_Info.objects.values('area', 'Type').annotate(value=Count('UID', distinct=True)).order_by()
  258. res = {
  259. 'quantity': 0,
  260. 'data': []
  261. }
  262. data = res['data']
  263. tmpDict = {}
  264. tmpDict['null'] = {
  265. 'area': '未知',
  266. 'quantity': 0,
  267. 'models': []
  268. }
  269. for di in di_qs:
  270. area = di['area']
  271. if area is None or area == '':
  272. area = 'null'
  273. if not tmpDict.__contains__(area):
  274. tmpDict[area] = {
  275. 'area': area,
  276. 'quantity': 0,
  277. 'models': []
  278. }
  279. item = tmpDict[area]
  280. item['quantity'] = item['quantity'] + di['value']
  281. res['quantity'] = res['quantity'] + item['quantity']
  282. device_model = None
  283. if DEVICE_TYPE.__contains__(di['Type']):
  284. device_model = DEVICE_TYPE[di['Type']]
  285. else:
  286. device_model = DEVICE_TYPE[0]
  287. model = {
  288. 'model': device_model,
  289. 'quantity': di['value']
  290. }
  291. item['models'].append(model)
  292. for k, v in tmpDict.items():
  293. data.append(v)
  294. return response.json(0, res)
  295. def getDeviceType(self, userID, response):
  296. own_permission = ModelService.check_perm(userID=userID, permID=30)
  297. if own_permission is not True:
  298. return response.json(404)
  299. # 设备类型统计
  300. di_qs = Device_Info.objects.values('Type').annotate(quantity=Count('UID', distinct=True)).order_by()
  301. # 设备型号统计
  302. us_qs = UidSetModel.objects.values('deviceModel').annotate(quantity=Count('id')).order_by()
  303. res = {
  304. 'type_data': {
  305. 'quantity': 0,
  306. 'data': []
  307. },
  308. 'model_data': {
  309. 'quantity': 0,
  310. 'data': []
  311. }
  312. }
  313. type_data = res['type_data']
  314. data = type_data['data']
  315. quantity = 0
  316. for di in di_qs:
  317. if DEVICE_TYPE.__contains__(di['Type']):
  318. device_model = DEVICE_TYPE[di['Type']]
  319. else:
  320. device_model = DEVICE_TYPE[0]
  321. di['Type'] = device_model
  322. quantity += di['quantity']
  323. data.append(di)
  324. type_data['quantity'] = quantity
  325. model_data = res['model_data']
  326. data = model_data['data']
  327. quantity = 0
  328. for us in us_qs:
  329. data.append(us)
  330. quantity += us['quantity']
  331. model_data['quantity'] = quantity
  332. return response.json(0, res)
  333. def getAppFrequency(self, userID, request_dict, response):
  334. own_permission = ModelService.check_perm(userID=userID, permID=30)
  335. if own_permission is not True:
  336. return response.json(404)
  337. # 当前的年份
  338. current_time = int(time.time())
  339. localtime = time.localtime(current_time)
  340. current_year = localtime.tm_year
  341. current_month = localtime.tm_mon
  342. start_year = end_year = current_year
  343. end_month = current_month
  344. start_month = 1
  345. result = []
  346. if end_month != 12:
  347. start_month = end_month + 1
  348. start_year = current_year - 1
  349. time_struct = [start_year, start_month, 0, 0, 0, 0, 0, 0, 0]
  350. key_formal = '{year}{month}'
  351. for i in range(12):
  352. result.append({
  353. 'date_time': key_formal.format(year=time_struct[0], month=str(time_struct[1]).zfill(2)),
  354. 'data': None
  355. })
  356. month = time_struct[1] + 1
  357. if month > 12:
  358. time_struct[0] = time_struct[0] + 1
  359. time_struct[1] = 1
  360. else:
  361. time_struct[1] = month
  362. #
  363. afs_qs = {}
  364. if start_year == end_year:
  365. afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month, month__lte=end_month).values().order_by('-year', 'month'))
  366. else:
  367. afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month).values().order_by('-year', 'month'))
  368. tmps_qs = list(AppFrequencyStatisticsModel.objects.filter(year=end_year, month__lte=end_month).values().order_by('-year', 'month'))
  369. for tmp in tmps_qs:
  370. afs_qs.append(tmp)
  371. tmp_dict = {}
  372. for afs in afs_qs:
  373. key = key_formal.format(year=afs['year'], month=str(afs['month']).zfill(2))
  374. tmp_dict[key] = json.loads(afs['data'])
  375. for res in result:
  376. if tmp_dict.__contains__(res['date_time']):
  377. res['data'] = tmp_dict[res['date_time']]
  378. print(result)
  379. return response.json(0, result)
  380. def getAllAppFrequency(self, userID, response):
  381. own_permission = ModelService.check_perm(userID=userID, permID=30)
  382. if own_permission is not True:
  383. return response.json(404)
  384. # 取出请求年份的统计好的数据
  385. print('start')
  386. time_struct = time.localtime()
  387. current_year = time_struct.tm_year
  388. start_year = current_year - 5 + 1
  389. afs_qs = AppFrequencyYearStatisticsModel.objects.filter(year__gte=start_year, year__lt=current_year).order_by(
  390. '-year')
  391. if afs_qs.exists():
  392. afs_qs = afs_qs.values('id', 'data', 'num', 'year')
  393. res = []
  394. for afs in afs_qs:
  395. res.append({
  396. 'year': afs['year'],
  397. 'data': json.loads(afs['data'])
  398. })
  399. return response.json(0, res)
  400. else:
  401. return response.json(0, [])
  402. def query_push_by_level(self, userID, request_dict, response):
  403. own_permission = ModelService.check_perm(userID=userID, permID=30)
  404. if own_permission is not True:
  405. return response.json(404)
  406. level = request_dict.get('level', None)
  407. print(level)
  408. if level is None:
  409. return response.json(444)
  410. level = int(level)
  411. if level < 0:
  412. return response.json(444)
  413. elif level < 3:
  414. return self.query_push_day_statistics(level, response)
  415. else:
  416. return response.json(404)
  417. def query_push_day_statistics(self, level, response):
  418. start_time = 0
  419. gmtime = time.gmtime(int(time.time()) + 28800)
  420. current_day = gmtime.tm_mday
  421. time_struct = [gmtime.tm_year, gmtime.tm_mon, current_day, 0, 0, 0, 0, 0, 0]
  422. current_time = int(time.mktime(tuple(time_struct))) - 28800
  423. count = 0
  424. if level == 0: # 七天
  425. start_time = current_time - 6 * 24 * 3600
  426. count = 6
  427. elif level == 1:
  428. start_time = current_time - 13 * 24 * 3600
  429. count = 13
  430. elif level == 2:
  431. start_time = current_time - 29 * 24 * 3600
  432. count = 29
  433. end_time = current_time
  434. eqx_qs = EquipmentInfoExStatisticsModel.objects.filter(statistics_date__gte=start_time, statistics_date__lte=end_time, date_type=0, push_type=-1).values()
  435. data = []
  436. for i in range(count + 1):
  437. data.append({
  438. 'date_time': int(start_time),
  439. 'data': None
  440. })
  441. start_time += (24 * 60 * 60)
  442. tmp_dict = {}
  443. successes = 0
  444. failures = 0
  445. for eqx in eqx_qs:
  446. successes += eqx['number_of_successes']
  447. failures += eqx['number_of_failures']
  448. tmp_dict[eqx['statistics_date']] = {
  449. 'number_of_successes': eqx['number_of_successes'],
  450. 'number_of_failures': eqx['number_of_failures'],
  451. 'total': (eqx['number_of_successes'] + eqx['number_of_failures'])
  452. }
  453. # 取出当前的推送数据
  454. start_time = current_time
  455. current_time = int(time.time())
  456. eq_qs = Equipment_Info.objects.filter(addTime__gte=start_time, addTime__lte=current_time)
  457. print(eq_qs.values())
  458. # 0:APNS推送,1:谷歌推送,2:极光推送
  459. tmp = {
  460. 'number_of_successes': 0,
  461. 'number_of_failures': 0,
  462. 'total': 0
  463. }
  464. for eq in eq_qs:
  465. if eq.push_server_status == 200:
  466. tmp['number_of_successes'] += 1
  467. successes += 1
  468. else:
  469. tmp['number_of_failures'] += 1
  470. failures += 1
  471. tmp['total'] += 1
  472. tmp_dict[current_time] = tmp
  473. for item in data:
  474. if tmp_dict.__contains__(item['date_time']):
  475. item['data'] = tmp_dict[item['date_time']]
  476. success_rate = round(successes / (successes + failures), 2)
  477. arrival_rate = success_rate
  478. res = {
  479. 'data': data,
  480. 'successes': successes,
  481. 'failures': failures,
  482. 'success_rate': success_rate,
  483. 'arrival_rate': arrival_rate
  484. }
  485. return response.json(0, res)
  486. # def query_push_month_statistics(self, level, response):
  487. # start_time = 0
  488. # end_time = 0
  489. # localtime = time.localtime()
  490. # current_month = localtime.tm_mon
  491. #
  492. # time_struct = [localtime.tm_year, current_month, 1, 0, 0, 0, 0, 0, 0]
  493. # current_time = int(time.mktime(tuple(time_struct)))
  494. # current_time = current_time - time.timezone - 8 * 60 * 60
  495. # count = 0
  496. # start_month = 0
  497. # if level == 3: # 6个月
  498. # start_month = current_month - 5
  499. # count = 5
  500. # elif level == 4:
  501. # start_month = current_month - 11
  502. # count = 10
  503. #
  504. #
  505. # return
  506. def query_failures_push(self, userID, request_dict, response):
  507. own_permission = ModelService.check_perm(userID=userID, permID=30)
  508. if own_permission is not True:
  509. return response.json(404)
  510. start_time = request_dict.get('start_time', None)
  511. end_time = request_dict.get('end_time', None)
  512. page = request_dict.get('page', None)
  513. line = request_dict.get('line', None)
  514. if not start_time or not end_time or not page or not line:
  515. return response.json(444)
  516. start_time = int(start_time)
  517. end_time = int(end_time)
  518. page = int(page)
  519. line = int(line)
  520. if page <= 0 or line < 0:
  521. return response.json(444, 'page, line')
  522. eq_qs = Equipment_Info.objects.filter(addTime__gte=start_time, addTime__lte=end_time)\
  523. .filter(~Q(push_server_status=200)).values('id', 'devUid', 'devNickName', 'Channel', 'alarm', 'eventType', 'eventTime', 'receiveTime', 'push_server_status', 'userID__username')
  524. if eq_qs.exists():
  525. count = eq_qs.count()
  526. eq_qs = eq_qs[(page-1)*line: page * line]
  527. return response.json(0, {'count': count, 'data': list(eq_qs)})
  528. else:
  529. return response.json(0, {'count': 0, 'data': []})
  530. def query_push_server_cpu_usage(self, userID, request_dict, response):
  531. own_permission = ModelService.check_perm(userID=userID, permID=30)
  532. if own_permission is not True:
  533. return response.json(404)
  534. start_time = request_dict.get('start_time', None)
  535. end_time = request_dict.get('end_time', None)
  536. tz = request_dict.get('tz', None)
  537. if start_time is None or end_time is None or tz is None:
  538. return response.json(444)
  539. date = datetime.datetime(2020, 9, 15)
  540. start_time = date.fromtimestamp((int(start_time)))
  541. end_time = date.fromtimestamp(int(end_time))
  542. tz = int(tz)
  543. cloudwatch = boto3.client('cloudwatch', region_name=AWS_SES_ACCESS_REGION_WEST, aws_access_key_id=AWS_SES_ACCESS_ID,
  544. aws_secret_access_key=AWS_SES_ACCESS_SECRET)
  545. try:
  546. result = cloudwatch.get_metric_statistics(Namespace='AWS/EC2', MetricName='CPUUtilization',
  547. StartTime=start_time,
  548. EndTime=end_time, Period=60,
  549. Statistics=['Average'],
  550. Dimensions=[
  551. {'Name': 'InstanceId', 'Value': 'i-0596e00c9af077027'}])
  552. datas = result['Datapoints']
  553. datas.sort(key=getCompareKey)
  554. result = []
  555. for data in datas:
  556. tmp = data
  557. utcdt = data['Timestamp']
  558. time1 = str(utcdt.astimezone(asj_timezone(timedelta(hours=int(-tz)))))
  559. tmp['Timestamp'] = time1[0:time1.find('+')]
  560. result.append(tmp)
  561. return response.json(0, result)
  562. except Exception as e:
  563. print(repr(e))
  564. return response.json(10, 'AWS Server Error')
  565. def getCompareKey(item):
  566. return item['Timestamp']
  567. @require_http_methods(["GET"])
  568. def getUserIds(request):
  569. token = request.GET.get('token', None)
  570. response = ResponseObject()
  571. tko = TokenObject(token)
  572. response.lang = tko.lang
  573. if tko.code != 0:
  574. return response.json(tko.code)
  575. userID = tko.userID
  576. own_perm = ModelService.check_perm(userID, 30)
  577. if own_perm is not True:
  578. return response.json(404)
  579. dn = Device_User.objects.all().values('userID', 'username')
  580. return response.json(0, {"datas": list(dn)})
  581. @csrf_exempt
  582. def search_user_by_content(request):
  583. if request.method == 'GET':
  584. request_dict = request.GET
  585. if request.method == 'POST':
  586. request_dict = request.POST
  587. token = request_dict.get('token', None)
  588. page = request_dict.get('page', None)
  589. line = request_dict.get('line', None)
  590. content = request_dict.get('content', None)
  591. rstime = request_dict.get('rstime', None)
  592. retime = request_dict.get('retime', None)
  593. response = ResponseObject()
  594. if page is not None and line is not None:
  595. page = int(page)
  596. line = int(line)
  597. else:
  598. return response.json(10, 'page,line is none')
  599. tko = TokenObject(token)
  600. response.lang = tko.lang
  601. if tko.code != 0:
  602. return response.json(tko.code)
  603. userID = tko.userID
  604. own_perm = ModelService.check_perm(userID=userID, permID=20)
  605. if own_perm is not True:
  606. return response.json(404)
  607. try:
  608. content = json.loads(content)
  609. search_kwargs = CommonService.get_kwargs(data=content)
  610. queryset = Device_User.objects.filter(**search_kwargs)
  611. except Exception as e:
  612. return response.json(444, repr(e))
  613. if rstime is not None and rstime != '' and retime is not None and retime != '':
  614. startt = datetime.datetime.fromtimestamp(int(rstime))
  615. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  616. endt = datetime.datetime.fromtimestamp(int(retime))
  617. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  618. queryset = queryset.filter(data_joined__range=(rstime, retime))
  619. elif rstime is not None and rstime != '':
  620. startt = datetime.datetime.fromtimestamp(int(rstime))
  621. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  622. queryset = queryset.filter(data_joined__gte=rstime)
  623. elif retime is not None and retime != '':
  624. endt = datetime.datetime.fromtimestamp(int(retime))
  625. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  626. queryset = queryset.filter(data_joined__lte=retime)
  627. if queryset.exists():
  628. count = queryset.count()
  629. res = queryset[(page - 1) * line:page * line]
  630. sqlDict = CommonService.qs_to_dict(res)
  631. for k, v in enumerate(sqlDict["datas"]):
  632. if len(v['fields']['role']) > 0:
  633. role_query_set = Role.objects.get(rid=v['fields']['role'][0])
  634. sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
  635. for val in res:
  636. if v['pk'] == val.userID:
  637. if sqlDict["datas"][k]['fields']['online'] is True:
  638. dl_time = val.last_login + datetime.timedelta(minutes=5)
  639. now_time = timezone.localtime(timezone.now())
  640. if now_time > dl_time:
  641. sqlDict["datas"][k]['fields']['online'] = False
  642. ue = UserExModel.objects.filter(userID=v['pk'])
  643. if ue.exists():
  644. sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
  645. else:
  646. sqlDict["datas"][k]['fields']['appBundleId'] = ''
  647. sqlDict['count'] = count
  648. return response.json(0, sqlDict)
  649. return response.json(0, {'datas': [], 'count': 0})