AdminManage.py 20 KB

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