AdminManage.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. # -*- coding: utf-8 -*-
  2. import time
  3. import xlwt
  4. from django.db.models import Count,Q
  5. from django.http import HttpResponse
  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
  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
  19. import datetime, simplejson as json
  20. from Service.CommonService import CommonService
  21. from Object.RedisObject import RedisObject
  22. '''
  23. http://192.168.136.40:8077/adminManage/manage?operation=getAllDeviceArea&token=debug
  24. http://192.168.136.40:8077/adminManage/manage?operation=getAllUserName&token=debug
  25. http://192.168.136.40:8077/adminManage/manage?operation=getAllUID&token=debug
  26. http://127.0.0.1:8000/adminManage/manage?operation=getAllOnLine&token=stest
  27. http://127.0.0.1:8000/adminManage/manage?operation=getOnLine&token=stest
  28. '''
  29. class AdminManage(TemplateView):
  30. @method_decorator(csrf_exempt)
  31. def dispatch(self, *args, **kwargs):
  32. return super(AdminManage, self).dispatch(*args, **kwargs)
  33. def get(self, request, *args, **kwargs):
  34. request.encoding = 'utf-8'
  35. return self.validation(request_dict=request.GET)
  36. def post(self, request, *args, **kwargs):
  37. request.encoding = 'utf-8'
  38. return self.validation(request_dict=request.POST)
  39. def validation(self, request_dict, *args, **kwargs):
  40. response = ResponseObject()
  41. token = request_dict.get('token', None)
  42. tko = TokenObject(token)
  43. response.lang = tko.lang
  44. if tko.code != 0:
  45. return response.json(tko.code)
  46. userID = tko.userID
  47. operation = request_dict.get('operation', None)
  48. if userID is None or operation is None:
  49. return response.json(444, 'operation')
  50. if operation == 'resetUserPwd':
  51. return self.resetUserPwd(request_dict, userID, response)
  52. if operation == 'getAllOnLine':
  53. return self.getAllOnLine(userID, response)
  54. if operation == 'getOnLine':
  55. return self.getRedisOnline(userID, response)
  56. # return self.getOnLine(userID, response)
  57. if operation == 'getAllUserName':
  58. return self.getAllUserName(userID, response)
  59. if operation == 'getStatisAccess':
  60. return self.getStatisAccess(userID, request_dict, response)
  61. if operation == 'getAllUID':
  62. return self.getAllUID(userID, response)
  63. if operation == 'getAllDeviceArea':
  64. return self.getAllDeviceArea(userID, response)
  65. if operation == 'getUserBrand':
  66. return self.getUserBrand(userID, response)
  67. if operation == 'getAreaDeviceType':
  68. return self.getAreaDeviceType(userID, response)
  69. if operation == 'getDeviceType':
  70. return self.getDeviceType(userID, response)
  71. if operation == 'getAppFrequency':
  72. return self.getAppFrequency(userID, request_dict, response)
  73. if operation == 'getHistoryAppFrequency':
  74. return self.getAllAppFrequency(userID, response)
  75. if operation == 'downloadSubscribeEmail':
  76. return self.download_subscribe_email(userID, request_dict, response)
  77. def resetUserPwd(self, request_dict, userID, response):
  78. own_permission = ModelService.check_perm(userID=userID, permID=50)
  79. if not own_permission:
  80. return response.json(404)
  81. duserID = request_dict.get('duserID', None)
  82. userPwd = request_dict.get('userPwd', None)
  83. if not duserID:
  84. return response.json(444, 'duserID')
  85. UserValid = Device_User.objects.filter(userID=duserID)
  86. if UserValid:
  87. if userPwd is None:
  88. userPwd = '123456'
  89. is_update = UserValid.update(password=make_password(userPwd))
  90. if is_update:
  91. return response.json(0)
  92. else:
  93. return response.json(177)
  94. else:
  95. return response.json(104)
  96. def getAllUserName(self, userID, response):
  97. # 权限固定为30
  98. own_permission = ModelService.check_perm(userID=userID, permID=30)
  99. if own_permission is not True:
  100. return response.json(404)
  101. username_list = Device_User.objects.all().values_list('username', flat=True)
  102. if username_list:
  103. return response.json(0, {'username_list': list(username_list)})
  104. else:
  105. return response.json(0)
  106. # 获取全部用户的在线个数
  107. def getAllOnLine(self, userID, response):
  108. # 权限固定为30
  109. own_permission = ModelService.check_perm(userID=userID, permID=30)
  110. if own_permission is not True:
  111. return response.json(404)
  112. allonline = Device_User.objects.all().values('online')
  113. # 两个变量,分别是在线,离线
  114. onlinenum = 0
  115. noonlinenum = 0
  116. for q in allonline:
  117. if q['online'] == True:
  118. onlinenum += 1
  119. else:
  120. noonlinenum += 1
  121. print("在线人数:")
  122. print(onlinenum)
  123. return response.json(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})
  124. # 获取全部用户的在线人数
  125. def getOnLine(self, userID, response):
  126. # 权限固定为30
  127. own_permission = ModelService.check_perm(userID=userID, permID=30)
  128. if own_permission is True:
  129. online_list = Device_User.objects.all().values('online', 'last_login')
  130. # 两个变量,分别是在线,离线
  131. onlinenum = 0
  132. noonlinenum = 0
  133. for q in online_list:
  134. # print(q['last_login'] )
  135. # 最后访问时间加5分种
  136. dl_time = q['last_login'] + datetime.timedelta(minutes=OFF_LINE_TIME_DELTA)
  137. # print(dl_time)
  138. # 当前时间
  139. now_time = timezone.localtime(timezone.now())
  140. # print(now_time)
  141. # 如果当前时间大于最后访问的时间
  142. if now_time < dl_time:
  143. onlinenum += 1
  144. else:
  145. noonlinenum += 1
  146. print("在线人")
  147. print(onlinenum)
  148. return response.json(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})
  149. else:
  150. return response.json(404)
  151. # 获取全部用户的在线人数
  152. def getRedisOnline(self, userID, response):
  153. # 权限固定为30
  154. own_perm = ModelService.check_perm(userID, 30)
  155. if own_perm:
  156. count = int(Device_User.objects.count())
  157. redisObj = RedisObject(db=3)
  158. onlines = int(redisObj.get_size())
  159. print(onlines)
  160. return response.json(0, {"onlinenum": onlines, "no_onlinenum": count - onlines})
  161. else:
  162. return response.json(404)
  163. # 获取所有设备地区
  164. def getAllDeviceArea(self, userID, response):
  165. own_permission = ModelService.check_perm(userID=userID, permID=30)
  166. if own_permission is True:
  167. qs = Device_Info.objects.all().values('area', 'UID')
  168. uid_area_dict = {}
  169. for q in qs:
  170. if q['UID'] and q['area']:
  171. uid_area_dict[q['UID']] = q['area']
  172. if len(uid_area_dict):
  173. area_dict = {}
  174. for k, v in uid_area_dict.items():
  175. if v in area_dict:
  176. area_dict[v] += 1
  177. else:
  178. area_dict[v] = 1
  179. return response.json(0, {'area': area_dict})
  180. else:
  181. return response.json(0)
  182. else:
  183. return response.json(404)
  184. '''
  185. 统计一天访问量
  186. http://192.168.136.45:8077/adminManage/manage?token=test&operation=getStatisAccess&timestamp=1528773308
  187. '''
  188. def getStatisAccess(self, userID, request_dict, response):
  189. own_permission = ModelService.check_perm(userID=userID, permID=30)
  190. if own_permission is not True:
  191. return response.json(404)
  192. time_stamp = int(request_dict.get('timestamp', None))
  193. times = datetime.datetime.fromtimestamp(time_stamp)
  194. time_dict = CommonService.getTimeDict(times)
  195. res = {}
  196. for k, v in time_dict.items():
  197. start_date = time_dict[k]
  198. end_date = time_dict[k] + datetime.timedelta(hours=1)
  199. count = Access_Log.objects.filter(time__range=(start_date, end_date)).count()
  200. if count:
  201. res[k] = count
  202. else:
  203. res[k] = 0
  204. return response.json(0, {'count': res})
  205. def getAllUID(self, userID, response):
  206. own_permission = ModelService.check_perm(userID=userID, permID=30)
  207. if own_permission is not True:
  208. return response.json(404)
  209. uid_list = Device_Info.objects.all().values_list('UID', flat=True)
  210. res = {}
  211. if uid_list:
  212. res = {'count': uid_list.count(), 'uid_list': list(uid_list)}
  213. return response.json(0, res)
  214. def getUserBrand(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. # 手机型号统计
  219. print('手机型号统计:')
  220. ub_qs = User_Brand.objects.values('deviceSupplier', 'deviceModel').annotate(value=Count('id')).order_by()
  221. res = {
  222. 'value': 0,
  223. 'data': []
  224. }
  225. data = res['data']
  226. tmpDict = {}
  227. for ub in ub_qs:
  228. deviceSupplier = ub['deviceSupplier']
  229. if not tmpDict.__contains__(deviceSupplier):
  230. tmpDict[deviceSupplier] = {
  231. 'name': deviceSupplier,
  232. 'value': 0,
  233. 'children': []
  234. }
  235. item = tmpDict[deviceSupplier]
  236. item['value'] = item['value'] + ub['value']
  237. res['value'] = res['value'] + item['value']
  238. model = {
  239. 'name': ub['deviceModel'],
  240. 'value': ub['value']
  241. }
  242. item['children'].append(model)
  243. for k, v in tmpDict.items():
  244. data.append(v)
  245. print(res)
  246. return response.json(0, res)
  247. def getAreaDeviceType(self, userID, response):
  248. own_permission = ModelService.check_perm(userID=userID, permID=30)
  249. if own_permission is not True:
  250. return response.json(404)
  251. print('区域设备类型统计:')
  252. di_qs = Device_Info.objects.values('area', 'Type').annotate(value=Count('UID', distinct=True)).order_by()
  253. res = {
  254. 'quantity': 0,
  255. 'data': []
  256. }
  257. data = res['data']
  258. tmpDict = {}
  259. tmpDict['null'] = {
  260. 'area': '未知',
  261. 'quantity': 0,
  262. 'models': []
  263. }
  264. for di in di_qs:
  265. area = di['area']
  266. if area is None or area == '':
  267. area = 'null'
  268. if not tmpDict.__contains__(area):
  269. tmpDict[area] = {
  270. 'area': area,
  271. 'quantity': 0,
  272. 'models': []
  273. }
  274. item = tmpDict[area]
  275. item['quantity'] = item['quantity'] + di['value']
  276. res['quantity'] = res['quantity'] + item['quantity']
  277. device_model = None
  278. if DEVICE_TYPE.__contains__(di['Type']):
  279. device_model = DEVICE_TYPE[di['Type']]
  280. else:
  281. device_model = DEVICE_TYPE[0]
  282. model = {
  283. 'model': device_model,
  284. 'quantity': di['value']
  285. }
  286. item['models'].append(model)
  287. for k, v in tmpDict.items():
  288. data.append(v)
  289. return response.json(0, res)
  290. def getDeviceType(self, userID, response):
  291. own_permission = ModelService.check_perm(userID=userID, permID=30)
  292. if own_permission is not True:
  293. return response.json(404)
  294. # 设备类型统计
  295. di_qs = Device_Info.objects.values('Type').annotate(quantity=Count('UID', distinct=True)).order_by()
  296. # 设备型号统计
  297. us_qs = UidSetModel.objects.values('deviceModel').annotate(quantity=Count('id')).order_by()
  298. res = {
  299. 'type_data': {
  300. 'quantity': 0,
  301. 'data': []
  302. },
  303. 'model_data': {
  304. 'quantity': 0,
  305. 'data': []
  306. }
  307. }
  308. type_data = res['type_data']
  309. data = type_data['data']
  310. quantity = 0
  311. for di in di_qs:
  312. if DEVICE_TYPE.__contains__(di['Type']):
  313. device_model = DEVICE_TYPE[di['Type']]
  314. else:
  315. device_model = DEVICE_TYPE[0]
  316. di['Type'] = device_model
  317. quantity += di['quantity']
  318. data.append(di)
  319. type_data['quantity'] = quantity
  320. model_data = res['model_data']
  321. data = model_data['data']
  322. quantity = 0
  323. for us in us_qs:
  324. data.append(us)
  325. quantity += us['quantity']
  326. model_data['quantity'] = quantity
  327. return response.json(0, res)
  328. def getAppFrequency(self, userID, request_dict, response):
  329. own_permission = ModelService.check_perm(userID=userID, permID=30)
  330. if own_permission is not True:
  331. return response.json(404)
  332. # 当前的年份
  333. current_time = int(time.time())
  334. localtime = time.localtime(current_time)
  335. current_year = localtime.tm_year
  336. current_month = localtime.tm_mon
  337. start_year = end_year = current_year
  338. end_month = current_month
  339. start_month = 1
  340. result = []
  341. if end_month != 12:
  342. start_month = end_month + 1
  343. start_year = current_year - 1
  344. time_struct = [start_year, start_month, 0, 0, 0, 0, 0, 0, 0]
  345. key_formal = '{year}{month}'
  346. for i in range(12):
  347. result.append({
  348. 'date_time': key_formal.format(year=time_struct[0], month=str(time_struct[1]).zfill(2)),
  349. 'data': None
  350. })
  351. month = time_struct[1] + 1
  352. if month > 12:
  353. time_struct[0] = time_struct[0] + 1
  354. time_struct[1] = 1
  355. else:
  356. time_struct[1] = month
  357. #
  358. afs_qs = {}
  359. if start_year == end_year:
  360. afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month, month__lte=end_month).values().order_by('-year', 'month'))
  361. else:
  362. afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month).values().order_by('-year', 'month'))
  363. tmps_qs = list(AppFrequencyStatisticsModel.objects.filter(year=end_year, month__lte=end_month).values().order_by('-year', 'month'))
  364. for tmp in tmps_qs:
  365. afs_qs.append(tmp)
  366. tmp_dict = {}
  367. for afs in afs_qs:
  368. key = key_formal.format(year=afs['year'], month=str(afs['month']).zfill(2))
  369. tmp_dict[key] = json.loads(afs['data'])
  370. for res in result:
  371. if tmp_dict.__contains__(res['date_time']):
  372. res['data'] = tmp_dict[res['date_time']]
  373. print(result)
  374. return response.json(0, result)
  375. def getAllAppFrequency(self, userID, response):
  376. own_permission = ModelService.check_perm(userID=userID, permID=30)
  377. if own_permission is not True:
  378. return response.json(404)
  379. # 取出请求年份的统计好的数据
  380. print('start')
  381. time_struct = time.localtime()
  382. current_year = time_struct.tm_year
  383. start_year = current_year - 5 + 1
  384. afs_qs = AppFrequencyYearStatisticsModel.objects.filter(year__gte=start_year, year__lt=current_year).order_by(
  385. '-year')
  386. if afs_qs.exists():
  387. afs_qs = afs_qs.values('id', 'data', 'num', 'year')
  388. res = []
  389. for afs in afs_qs:
  390. res.append({
  391. 'year': afs['year'],
  392. 'data': json.loads(afs['data'])
  393. })
  394. return response.json(0, res)
  395. else:
  396. return response.json(0, [])
  397. def download_subscribe_email(self, userID, request_dict, response):
  398. own_permission = ModelService.check_perm(userID=userID, permID=30)
  399. if own_permission is not True:
  400. return response.json(404)
  401. user_qs = Device_User.objects.filter(subscribe_email=1).values('userEmail')
  402. print(user_qs)
  403. response = HttpResponse(content_type='application/vnd.ms-excel')
  404. response['Content-Disposition'] = 'attachment; filename=Email' + time.strftime('-%Y-%m-%d-%H-%M-%S', time.localtime()) + '.xls'
  405. workbook = xlwt.Workbook(encoding='utf-8')
  406. sheet1 = workbook.add_sheet('Email Address')
  407. num = 1
  408. sheet1.write(0, 0, 'Email Address')
  409. for user in user_qs:
  410. email = user['userEmail']
  411. if email == '':
  412. continue
  413. sheet1.write(num, 0, email)
  414. num += 1
  415. workbook.save(response)
  416. return response
  417. @require_http_methods(["GET"])
  418. def getUserIds(request):
  419. token = request.GET.get('token', None)
  420. response = ResponseObject()
  421. tko = TokenObject(token)
  422. response.lang = tko.lang
  423. if tko.code != 0:
  424. return response.json(tko.code)
  425. userID = tko.userID
  426. own_perm = ModelService.check_perm(userID, 30)
  427. if own_perm is not True:
  428. return response.json(404)
  429. dn = Device_User.objects.all().values('userID', 'username')
  430. return response.json(0, {"datas": list(dn)})
  431. @csrf_exempt
  432. def search_user_by_content(request):
  433. if request.method == 'GET':
  434. request_dict = request.GET
  435. if request.method == 'POST':
  436. request_dict = request.POST
  437. token = request_dict.get('token', None)
  438. page = request_dict.get('page', None)
  439. line = request_dict.get('line', None)
  440. content = request_dict.get('content', None)
  441. rstime = request_dict.get('rstime', None)
  442. retime = request_dict.get('retime', None)
  443. response = ResponseObject()
  444. if page is not None and line is not None:
  445. page = int(page)
  446. line = int(line)
  447. else:
  448. return response.json(10, 'page,line is none')
  449. tko = TokenObject(token)
  450. response.lang = tko.lang
  451. if tko.code != 0:
  452. return response.json(tko.code)
  453. userID = tko.userID
  454. own_perm = ModelService.check_perm(userID=userID, permID=20)
  455. if own_perm is not True:
  456. return response.json(404)
  457. try:
  458. content = json.loads(content)
  459. search_kwargs = CommonService.get_kwargs(data=content)
  460. queryset = Device_User.objects.filter(**search_kwargs)
  461. except Exception as e:
  462. return response.json(444, repr(e))
  463. if rstime is not None and rstime != '' and retime is not None and retime != '':
  464. startt = datetime.datetime.fromtimestamp(int(rstime))
  465. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  466. endt = datetime.datetime.fromtimestamp(int(retime))
  467. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  468. queryset = queryset.filter(data_joined__range=(rstime, retime))
  469. elif rstime is not None and rstime != '':
  470. startt = datetime.datetime.fromtimestamp(int(rstime))
  471. rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")
  472. queryset = queryset.filter(data_joined__gte=rstime)
  473. elif retime is not None and retime != '':
  474. endt = datetime.datetime.fromtimestamp(int(retime))
  475. retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")
  476. queryset = queryset.filter(data_joined__lte=retime)
  477. if queryset.exists():
  478. count = queryset.count()
  479. res = queryset[(page - 1) * line:page * line]
  480. sqlDict = CommonService.qs_to_dict(res)
  481. for k, v in enumerate(sqlDict["datas"]):
  482. if len(v['fields']['role']) > 0:
  483. role_query_set = Role.objects.get(rid=v['fields']['role'][0])
  484. sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
  485. for val in res:
  486. if v['pk'] == val.userID:
  487. if sqlDict["datas"][k]['fields']['online'] is True:
  488. dl_time = val.last_login + datetime.timedelta(minutes=5)
  489. now_time = timezone.localtime(timezone.now())
  490. if now_time > dl_time:
  491. sqlDict["datas"][k]['fields']['online'] = False
  492. ue = UserExModel.objects.filter(userID=v['pk'])
  493. if ue.exists():
  494. sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
  495. else:
  496. sqlDict["datas"][k]['fields']['appBundleId'] = ''
  497. sqlDict['count'] = count
  498. return response.json(0, sqlDict)
  499. return response.json(0, {'datas': [], 'count': 0})