AdminManage.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. # -*- coding: utf-8 -*-
  2. import time
  3. from datetime import timedelta, timezone as asj_timezone
  4. import boto3
  5. import xlwt
  6. from django.db.models import Count, Q
  7. from django.http import HttpResponse
  8. from django.views.decorators.csrf import csrf_exempt
  9. from django.views.generic import TemplateView
  10. from django.utils.decorators import method_decorator
  11. from django.contrib.auth.hashers import make_password # 对密码加密模块
  12. from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel, AppFrequencyYearStatisticsModel, \
  13. AppFrequencyStatisticsModel, EquipmentInfoExStatisticsModel, Equipment_Info
  14. from Service.ModelService import ModelService
  15. from django.utils import timezone
  16. from Model.models import Access_Log, Device_User
  17. from django.views.decorators.http import require_http_methods
  18. from Object.ResponseObject import ResponseObject
  19. from Object.TokenObject import TokenObject
  20. from Ansjer.config import OFF_LINE_TIME_DELTA, DEVICE_TYPE, AWS_SES_ACCESS_REGION_WEST
  21. import datetime, simplejson as json
  22. from Service.CommonService import CommonService
  23. from Object.RedisObject import RedisObject
  24. from django.conf import settings
  25. AWS_ACCESS_KEY_ID = settings.AWS_ACCESS_KEY_ID
  26. AWS_SECRET_ACCESS_KEY = settings.AWS_SECRET_ACCESS_KEY
  27. class AdminManage(TemplateView):
  28. @method_decorator(csrf_exempt)
  29. def dispatch(self, *args, **kwargs):
  30. return super(AdminManage, self).dispatch(*args, **kwargs)
  31. def get(self, request, *args, **kwargs):
  32. request.encoding = 'utf-8'
  33. return self.validation(request_dict=request.GET)
  34. def post(self, request, *args, **kwargs):
  35. request.encoding = 'utf-8'
  36. return self.validation(request_dict=request.POST)
  37. def validation(self, request_dict, *args, **kwargs):
  38. response = ResponseObject()
  39. token = request_dict.get('token', None)
  40. tko = TokenObject(token)
  41. response.lang = tko.lang
  42. if tko.code != 0:
  43. return response.json(tko.code)
  44. userID = tko.userID
  45. operation = request_dict.get('operation', None)
  46. if userID is None or operation is None:
  47. return response.json(444, 'operation')
  48. if operation == 'resetUserPwd':
  49. return self.resetUserPwd(request_dict, userID, response)
  50. if operation == 'getAllOnLine':
  51. return self.getAllOnLine(userID, response)
  52. if operation == 'getOnLine':
  53. return self.getRedisOnline(userID, response)
  54. # return self.getOnLine(userID, response)
  55. if operation == 'getAllUserName':
  56. return self.getAllUserName(userID, response)
  57. if operation == 'getStatisAccess':
  58. return self.getStatisAccess(userID, request_dict, response)
  59. if operation == 'getAllUID':
  60. return self.getAllUID(userID, response)
  61. if operation == 'getAllDeviceArea':
  62. return self.getAllDeviceArea(userID, response)
  63. if operation == 'getUserBrand':
  64. return self.getUserBrand(userID, response)
  65. if operation == 'getAreaDeviceType':
  66. return self.getAreaDeviceType(userID, response)
  67. if operation == 'getDeviceType':
  68. return self.getDeviceType(userID, response)
  69. if operation == 'getAppFrequency':
  70. return self.getAppFrequency(userID, request_dict, response)
  71. if operation == 'getHistoryAppFrequency':
  72. return self.getAllAppFrequency(userID, response)
  73. if operation == 'getPushStatistics':
  74. return self.query_push_by_level(userID, request_dict, response)
  75. if operation == 'getPushFailures':
  76. return self.query_failures_push(userID, request_dict, response)
  77. if operation == 'getPushServerCPUUsage':
  78. return self.query_push_server_cpu_usage(userID, request_dict, response)
  79. if operation == 'downloadSubscribeEmail':
  80. return self.download_subscribe_email(userID, request_dict, response)
  81. def resetUserPwd(self, request_dict, userID, response):
  82. own_permission = ModelService.check_perm(userID=userID, permID=50)
  83. if not own_permission:
  84. return response.json(404)
  85. duserID = request_dict.get('duserID', None)
  86. userPwd = request_dict.get('userPwd', '123456')
  87. password_version = request_dict.get('pwdVersion', 'V1')
  88. if not duserID:
  89. return response.json(444, 'duserID')
  90. UserValid = Device_User.objects.filter(userID=duserID)
  91. if UserValid:
  92. if password_version == 'V1':
  93. userPwd = make_password(userPwd)
  94. is_update = UserValid.update(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()
  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(
  544. 'cloudwatch', region_name=AWS_SES_ACCESS_REGION_WEST, aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  545. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1])
  546. try:
  547. result = cloudwatch.get_metric_statistics(Namespace='AWS/EC2', MetricName='CPUUtilization',
  548. StartTime=start_time,
  549. EndTime=end_time, Period=60,
  550. Statistics=['Average'],
  551. Dimensions=[
  552. {'Name': 'InstanceId', 'Value': 'i-0596e00c9af077027'}])
  553. datas = result['Datapoints']
  554. datas.sort(key=getCompareKey)
  555. result = []
  556. for data in datas:
  557. tmp = data
  558. utcdt = data['Timestamp']
  559. time1 = str(utcdt.astimezone(asj_timezone(timedelta(hours=int(-tz)))))
  560. tmp['Timestamp'] = time1[0:time1.find('+')]
  561. result.append(tmp)
  562. return response.json(0, result)
  563. except Exception as e:
  564. print(repr(e))
  565. return response.json(10, 'AWS Server Error')
  566. def download_subscribe_email(self, userID, request_dict, response):
  567. own_permission = ModelService.check_perm(userID=userID, permID=30)
  568. if own_permission is not True:
  569. return response.json(404)
  570. user_qs = Device_User.objects.filter(subscribe_email=1).values('userEmail')
  571. print(user_qs)
  572. response = HttpResponse(content_type='application/vnd.ms-excel')
  573. response['Content-Disposition'] = 'attachment; filename=Email' + time.strftime('-%Y-%m-%d-%H-%M-%S', time.localtime()) + '.xls'
  574. workbook = xlwt.Workbook(encoding='utf-8')
  575. sheet1 = workbook.add_sheet('Email Address')
  576. num = 1
  577. sheet1.write(0, 0, 'Email Address')
  578. for user in user_qs:
  579. email = user['userEmail']
  580. if email == '':
  581. continue
  582. sheet1.write(num, 0, email)
  583. num += 1
  584. workbook.save(response)
  585. return response
  586. def getCompareKey(item):
  587. return item['Timestamp']
  588. @require_http_methods(["GET"])
  589. def getUserIds(request):
  590. token = request.GET.get('token', None)
  591. response = ResponseObject()
  592. tko = TokenObject(token)
  593. response.lang = tko.lang
  594. if tko.code != 0:
  595. return response.json(tko.code)
  596. userID = tko.userID
  597. own_perm = ModelService.check_perm(userID, 30)
  598. if own_perm is not True:
  599. return response.json(404)
  600. dn = Device_User.objects.all().values('userID', 'username')
  601. return response.json(0, {"datas": list(dn)})
  602. @csrf_exempt
  603. def search_user_by_content(request):
  604. if request.method == 'GET':
  605. request_dict = request.GET
  606. if request.method == 'POST':
  607. request_dict = request.POST
  608. token = request_dict.get('token', None)
  609. page = request_dict.get('page', None)
  610. line = request_dict.get('line', None)
  611. content = request_dict.get('content', None)
  612. rstime = request_dict.get('rstime', None)
  613. retime = request_dict.get('retime', None)
  614. response = ResponseObject()
  615. if page is not None and line is not None:
  616. page = int(page)
  617. line = int(line)
  618. else:
  619. return response.json(10, 'page,line is none')
  620. tko = TokenObject(token)
  621. response.lang = tko.lang
  622. if tko.code != 0:
  623. return response.json(tko.code)
  624. userID = tko.userID
  625. own_perm = ModelService.check_perm(userID=userID, permID=20)
  626. if own_perm is not True:
  627. return response.json(404)
  628. try:
  629. content = json.loads(content)
  630. search_kwargs = CommonService.get_kwargs(data=content)
  631. queryset = Device_User.objects.filter(**search_kwargs)
  632. except Exception as e:
  633. return response.json(444, repr(e))
  634. if rstime is not None and rstime != '' and retime is not None and retime != '':
  635. startt = datetime.datetime.fromtimestamp(int(rstime))
  636. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  637. endt = datetime.datetime.fromtimestamp(int(retime))
  638. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  639. queryset = queryset.filter(data_joined__range=(rstime, retime))
  640. elif rstime is not None and rstime != '':
  641. startt = datetime.datetime.fromtimestamp(int(rstime))
  642. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  643. queryset = queryset.filter(data_joined__gte=rstime)
  644. elif retime is not None and retime != '':
  645. endt = datetime.datetime.fromtimestamp(int(retime))
  646. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  647. queryset = queryset.filter(data_joined__lte=retime)
  648. if queryset.exists():
  649. count = queryset.count()
  650. res = queryset[(page - 1) * line:page * line]
  651. sqlDict = CommonService.qs_to_dict(res)
  652. for k, v in enumerate(sqlDict["datas"]):
  653. if len(v['fields']['role']) > 0:
  654. role_query_set = Role.objects.get(rid=v['fields']['role'][0])
  655. sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
  656. for val in res:
  657. if v['pk'] == val.userID:
  658. if sqlDict["datas"][k]['fields']['online'] is True:
  659. dl_time = val.last_login + datetime.timedelta(minutes=5)
  660. now_time = timezone.localtime(timezone.now())
  661. if now_time > dl_time:
  662. sqlDict["datas"][k]['fields']['online'] = False
  663. ue = UserExModel.objects.filter(userID=v['pk'])
  664. if ue.exists():
  665. sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
  666. else:
  667. sqlDict["datas"][k]['fields']['appBundleId'] = ''
  668. sqlDict['count'] = count
  669. return response.json(0, sqlDict)
  670. return response.json(0, {'datas': [], 'count': 0})