AdminManage.py 20 KB

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