AdminManage.py 29 KB

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