AdminManage.py 16 KB

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