AdminManage.py 29 KB

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