DeviceDataController.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UserDataController.py
  4. @Time : 2022/8/16 10:44
  5. @Author : peng
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import datetime
  10. import requests
  11. from django.db.models import Count
  12. from django.views.generic.base import View
  13. from Model.models import Device_Info, CountryModel, VodHlsModel, UidSetModel, DeviceTypeModel
  14. from Service.CommonService import CommonService
  15. # 设备数据
  16. class DeviceDataView(View):
  17. def get(self, request, *args, **kwargs):
  18. request.encoding = 'utf-8'
  19. operation = kwargs.get('operation')
  20. return self.validation(request.GET, request, operation)
  21. def post(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. return self.validation(request.POST, request, operation)
  25. def validation(self, request_dict, request, operation):
  26. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  27. if token_code != 0:
  28. return response.json(token_code)
  29. if operation == 'type': # 统计设备类型
  30. return self.type_statistics(response)
  31. if operation == 'regional': # 设备地区分布
  32. return self.regional_statistics(response)
  33. if operation == 'addDevice': # 查询设备增长数据(数据有些许差异)
  34. return self.add_device(request_dict, response)
  35. if operation == 'active': # 设备活跃数据
  36. return self.device_active(request_dict, response)
  37. if operation == 'global/regional': # 全球设备分布
  38. return self.global_regional(request, request_dict, response)
  39. if operation == 'global/type': # 全球设备类型
  40. return self.golbal_type(request, request_dict, response)
  41. if operation == 'global/active': # 全球设备活跃分布
  42. return self.golbal_active(request, request_dict, response)
  43. if operation == 'global/addDevice': # 全球新增设备数据
  44. return self.golbal_add_device(request, request_dict, response)
  45. @classmethod
  46. def golbal_add_device(cls, request, request_dict, response):
  47. """
  48. 全球新增设备数据
  49. @param request:请求
  50. @param request_dict:请求参数
  51. @param response: 响应对象
  52. """
  53. url_list = CommonService.get_domain_name()
  54. try:
  55. headers = {
  56. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  57. }
  58. device_list = []
  59. device_count = 0
  60. type_list = []
  61. type_count = 0
  62. region_list = []
  63. region_count = 0
  64. order_list = []
  65. order_count = 0
  66. for url in url_list:
  67. url = url + request.path.replace('global/', '')
  68. res = requests.get(url=url, params=request_dict, headers=headers)
  69. result = res.json()
  70. if result['result_code'] == 0:
  71. for item in result['result']['addDevice']:
  72. flag = 0
  73. for each in device_list:
  74. if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
  75. each['count'] += item['count']
  76. device_count += item['count']
  77. flag = 1
  78. break
  79. if flag == 0:
  80. device_list.append(item)
  81. device_count += item['count']
  82. for item in device_list:
  83. item['rate'] = round(item['count'] / device_count * 100, 2)
  84. for item in result['result']['region']:
  85. flag = 0
  86. for each in region_list:
  87. if item['countryName'] == each['countryName']:
  88. each['count'] += item['count']
  89. region_count += item['count']
  90. flag = 1
  91. break
  92. if flag == 0:
  93. region_list.append(item)
  94. region_count += item['count']
  95. for item in region_list:
  96. item['rate'] = round(item['count'] / region_count * 100, 2)
  97. for item in result['result']['type']:
  98. flag = 0
  99. for each in type_list:
  100. if item['type'] == each['type']:
  101. each['count'] += item['count']
  102. type_count += item['count']
  103. flag = 1
  104. break
  105. if flag == 0:
  106. type_list.append(item)
  107. type_count += item['count']
  108. for item in type_list:
  109. item['rate'] = round(item['count'] / type_count * 100, 2)
  110. for item in result['result']['version']:
  111. flag = 0
  112. for each in order_list:
  113. if item['type'] == each['type']:
  114. each['count'] += item['count']
  115. order_count += item['count']
  116. flag = 1
  117. break
  118. if flag == 0:
  119. order_list.append(item)
  120. order_count += item['count']
  121. for item in order_list:
  122. item['rate'] = round(item['count'] / order_count * 100, 2)
  123. else:
  124. return response.json(result['result_code'])
  125. res = {
  126. 'device': device_list,
  127. 'type': type_list,
  128. 'region': CommonService.list_sort(region_list),
  129. 'version': order_list
  130. }
  131. return response.json(0, res)
  132. except Exception as e:
  133. print(e)
  134. return response.json(500, repr(e))
  135. @classmethod
  136. def golbal_active(cls, request, request_dict, response):
  137. """
  138. 全球设备活跃分布
  139. @param request:请求
  140. @param request_dict:请求参数
  141. @param response: 响应对象
  142. """
  143. url_list = CommonService.get_domain_name()
  144. try:
  145. headers = {
  146. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  147. }
  148. type_list = []
  149. type_count = 0
  150. region_list = []
  151. region_count = 0
  152. for url in url_list:
  153. url = url + request.path.replace('global/', '')
  154. res = requests.get(url=url, params=request_dict, headers=headers)
  155. result = res.json()
  156. if result['result_code'] == 0:
  157. for item in result['result']['vodHls']:
  158. flag = 0
  159. for each in type_list:
  160. if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
  161. each['count'] += item['count']
  162. type_count += item['count']
  163. flag = 1
  164. break
  165. if flag == 0:
  166. type_list.append(item)
  167. type_count += item['count']
  168. for item in type_list:
  169. item['rate'] = round(item['count'] / type_count * 100, 2)
  170. for item in result['result']['region']:
  171. flag = 0
  172. for each in region_list:
  173. if item['countryName'] == each['countryName']:
  174. each['count'] += item['count']
  175. region_count += item['count']
  176. flag = 1
  177. break
  178. if flag == 0:
  179. region_list.append(item)
  180. region_count += item['count']
  181. for item in region_list:
  182. item['rate'] = round(item['count'] / region_count * 100, 2)
  183. else:
  184. return response.json(result['result_code'])
  185. res = {
  186. 'device': type_list,
  187. 'region': CommonService.list_sort(region_list)
  188. }
  189. return response.json(0, res)
  190. except Exception as e:
  191. print(e)
  192. return response.json(500, repr(e))
  193. @classmethod
  194. def golbal_type(cls, request, request_dict, response):
  195. """
  196. 全球设备类型分布
  197. @param request:请求
  198. @param request_dict:请求参数
  199. @param response: 响应对象
  200. """
  201. url_list = CommonService.get_domain_name()
  202. try:
  203. headers = {
  204. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  205. }
  206. type_list = []
  207. type_count = 0
  208. for url in url_list:
  209. url = url + request.path.replace('global/', '')
  210. res = requests.get(url=url, params=request_dict, headers=headers)
  211. result = res.json()
  212. if result['result_code'] == 0:
  213. for item in result['result']['type']:
  214. flag = 0
  215. for each in type_list:
  216. if item['type'] == each['type']:
  217. each['count'] += item['count']
  218. type_count += item['count']
  219. flag = 1
  220. break
  221. if flag == 0:
  222. type_list.append(item)
  223. type_count += item['count']
  224. for item in type_list:
  225. item['rate'] = round(item['count'] / type_count * 100, 2)
  226. else:
  227. return response.json(result['result_code'])
  228. res = {
  229. 'type': CommonService.list_sort(type_list)
  230. }
  231. return response.json(0, res)
  232. except Exception as e:
  233. print(e)
  234. return response.json(500)
  235. @classmethod
  236. def global_regional(cls, request, request_dict, response):
  237. """
  238. 全球设备分布
  239. @param request:请求
  240. @param request_dict:请求参数
  241. @param response:响应对象
  242. @return:
  243. """
  244. url_list = CommonService.get_domain_name()
  245. try:
  246. headers = {
  247. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  248. }
  249. device_list = []
  250. device_count = 0
  251. region_list = []
  252. region_count = 0
  253. for url in url_list:
  254. url = url + request.path.replace('global/', '')
  255. res = requests.get(url=url, params=request_dict, headers=headers)
  256. result = res.json()
  257. if result['result_code'] == 0:
  258. # 处理地区
  259. for item in result['result']['countries']:
  260. flag = 0
  261. for each in device_list:
  262. if each['countryName'] == item['countryName']:
  263. each['count'] += int(item['count'])
  264. device_count += int(item['count'])
  265. flag = 1
  266. break
  267. if flag == 0:
  268. device_list.append(item)
  269. device_count += int(item['count'])
  270. for item in device_list:
  271. rate = round(item['count'] / device_count * 100, 2)
  272. item['rate'] = rate
  273. for item in result['result']['continent']:
  274. flag = 0
  275. for each in region_list:
  276. if each['continentName'] == item['continentName']:
  277. each['count'] += item['count']
  278. region_count += item['count']
  279. flag = 1
  280. break
  281. if flag == 0:
  282. region_list.append(item)
  283. region_count += item['count']
  284. for item in region_list:
  285. item['rate'] = round(item['count'] / region_count * 100, 2)
  286. else:
  287. return response.json(result['result_code'])
  288. res = {
  289. 'countries': CommonService.list_sort(device_list[:20]),
  290. 'continent': region_list
  291. }
  292. return response.json(0, res)
  293. except Exception as e:
  294. return response.json(500, repr(e))
  295. @classmethod
  296. def device_active(cls, request_dict, response):
  297. """
  298. 设备活跃数据
  299. @param request_dict:请求参数
  300. @request_dict starTime:开始时间
  301. @request_dict endTime:结束时间
  302. @param response:响应对象
  303. """
  304. start_time = request_dict.get('startTime', None) # 时间戳
  305. end_time = request_dict.get('endTime', None)
  306. unit_time = request_dict.get('timeUnit', None)
  307. if not all([start_time, end_time, unit_time]):
  308. return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
  309. s_time = datetime.datetime.fromtimestamp(int(start_time))
  310. e_time = datetime.datetime.fromtimestamp(int(end_time))
  311. time_list = CommonService.cutting_time(s_time, e_time, unit_time)
  312. try:
  313. vod_hls_model_qs = VodHlsModel.objects.filter(time__range=(start_time, end_time))
  314. if not vod_hls_model_qs.exists():
  315. return response.json(173)
  316. device_info = list(vod_hls_model_qs.values('uid').order_by('uid').distinct())
  317. device_info_list = [item[key] for item in device_info for key in item]
  318. count_all = len(device_info_list)
  319. res = {}
  320. vod_list = []
  321. region_list = []
  322. for item in time_list:
  323. vod_hls_qs = vod_hls_model_qs.filter(time__range=(item[0], item[1]))
  324. uid_qs = vod_hls_qs.values('uid').order_by('uid').distinct()
  325. uid_list = [item[key] for item in uid_qs for key in item]
  326. rate = round(uid_qs.count() / count_all * 100, 2)
  327. vod_dict = {
  328. 'count': uid_qs.count(),
  329. 'rate': rate,
  330. 'startTime': item[0],
  331. 'endTime': item[1]
  332. }
  333. vod_list.append(vod_dict)
  334. res['vodHls'] = vod_list
  335. type_country_qs = UidSetModel.objects.filter(uid__in=uid_list).values(
  336. 'tb_country').annotate(count=Count('tb_country')).order_by('-count')
  337. for type_country in type_country_qs:
  338. country_id = type_country['tb_country']
  339. country_name_qs = CountryModel.objects.filter(id=country_id).values('country_name')
  340. country_name = country_name_qs[0]['country_name'] if country_name_qs.exists() else '未知区域'
  341. rate = round(type_country['count'] / count_all * 100, 2)
  342. country_dict = {
  343. 'countryName': country_name,
  344. 'count': type_country['count'],
  345. 'rate': rate
  346. }
  347. region_list.append(country_dict)
  348. res['region'] = region_list
  349. return response.json(0, res)
  350. except Exception as e:
  351. print(e)
  352. return response.json(500)
  353. @classmethod
  354. def add_device(cls, request_dict, response):
  355. """
  356. 查询设备增长数据
  357. @param request_dict:请求参数
  358. @request_dict starTime:开始时间
  359. @request_dict endTime:结束时间
  360. @param response:响应对象
  361. """
  362. start_time = request_dict.get('startTime', None) # 时间戳
  363. end_time = request_dict.get('endTime', None)
  364. unit_time = request_dict.get('timeUnit', None)
  365. if not all([start_time, end_time, unit_time]):
  366. return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
  367. try:
  368. uid_set_qs = UidSetModel.objects.filter(addTime__range=(start_time, end_time))
  369. count_all = uid_set_qs.count()
  370. # 统计该时间段的设备数量(已去重)
  371. res = {
  372. 'addDevice': '',
  373. 'region': '',
  374. 'type': '',
  375. 'version': '',
  376. }
  377. info_list = []
  378. region_list = []
  379. type_list = []
  380. version_list = []
  381. start_time = datetime.datetime.fromtimestamp(int(start_time))
  382. end_time = datetime.datetime.fromtimestamp(int(end_time))
  383. time_list = CommonService.cutting_time(start_time, end_time, unit_time)
  384. for item in time_list:
  385. deivce_uid_qs = uid_set_qs.filter(addTime__range=(item[0], item[1]))
  386. uid_qs = deivce_uid_qs.values('uid')
  387. if uid_qs.exists():
  388. uid_list = [item[key] for item in uid_qs for key in item]
  389. count_part = deivce_uid_qs.count()
  390. rate = round(count_part / count_all * 100, 2)
  391. info_dict = {
  392. 'startTime': item[0],
  393. 'endTime': item[1],
  394. 'count': count_part,
  395. 'rate': rate
  396. }
  397. info_list.append(info_dict)
  398. res['addDevice'] = info_list
  399. # 统计地区设备数量
  400. device_info_country_qs = deivce_uid_qs.values('tb_country').annotate(
  401. count=Count('tb_country')).order_by(
  402. '-count')
  403. for item in device_info_country_qs:
  404. country_id = item['tb_country']
  405. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'id')
  406. country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
  407. country_qs = deivce_uid_qs.values('tb_country')
  408. total_list = [item[key] for item in country_qs for key in item]
  409. country_count = total_list.count(country_id)
  410. rate = round(country_count / count_part * 100, 2)
  411. country_dict = {
  412. 'countryName': country_name,
  413. 'count': country_count,
  414. 'rate': rate
  415. }
  416. region_list.append(country_dict)
  417. res['region'] = CommonService.list_sort(region_list)
  418. # 统计设备类型数量
  419. device_info_type_qs = Device_Info.objects.filter(UID__in=uid_list)
  420. device_type_qs = device_info_type_qs.values('Type').annotate(
  421. count=Count('Type', distinct=True)).order_by('-count').distinct()
  422. count = device_info_type_qs.count()
  423. name = '未知类型'
  424. count_remain = count_part - count
  425. rate = round(count_remain / count_part * 100, 2)
  426. type_list.append({
  427. 'name': name,
  428. 'count': count_remain,
  429. 'rate': rate
  430. })
  431. for device_type in device_type_qs:
  432. Type = device_type['Type']
  433. device_type_qs = DeviceTypeModel.objects.filter(type=Type).values('name')
  434. name = device_type_qs[0]['name'] if device_type_qs.exists() else '未知类型'
  435. type_qs = device_info_type_qs.values('Type')
  436. test_list = [item[key] for item in type_qs for key in item]
  437. type_count = test_list.count(Type)
  438. rate = round(type_count / count_part * 100, 2)
  439. type_list.append({
  440. 'name': name,
  441. 'count': type_count,
  442. 'rate': rate
  443. })
  444. res['type'] = CommonService.list_sort(type_list)
  445. # 云存版本数量
  446. res_part = {}
  447. cloud_qs = deivce_uid_qs.exclude(cloud_vod=2).values('cloud_vod').count()
  448. res_part['count'] = cloud_qs
  449. res_part['rate'] = round(cloud_qs / count_part * 100, 2)
  450. version_list.append(res_part)
  451. res['version'] = version_list
  452. else:
  453. info_dict = {
  454. 'startTime': item[0],
  455. 'endTime': item[1],
  456. 'count': 0,
  457. 'rate': 0.0
  458. }
  459. info_list.append(info_dict)
  460. res['addDevice'] = info_list
  461. return response.json(0, res)
  462. except Exception as e:
  463. print(e)
  464. return response.json(500, repr(e))
  465. @classmethod
  466. def regional_statistics(cls, response):
  467. """
  468. 统计地区设备数量
  469. @param response:响应对象
  470. """
  471. uid_set_qs = UidSetModel.objects.all()
  472. tb_country_qs = uid_set_qs.values('tb_country').annotate(
  473. count=Count('tb_country')).order_by('-count')
  474. uid_set = uid_set_qs.values('uid')
  475. count_all = uid_set.count()
  476. if not uid_set_qs.exists():
  477. return response.json(444)
  478. res = {}
  479. try:
  480. device_country_list = []
  481. continent_list = []
  482. for device_country in tb_country_qs:
  483. country_id = device_country['tb_country']
  484. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  485. if not country_qs.exists():
  486. name = '未知地区'
  487. else:
  488. name = country_qs[0]['country_name']
  489. count = uid_set_qs.filter(
  490. tb_country=device_country['tb_country']).values('uid').annotate(
  491. count=Count('uid', distinct=True)).order_by('-count').count()
  492. device_country_list.append({
  493. 'countryName': name,
  494. 'count': count
  495. })
  496. if country_qs.exists():
  497. flag = 0
  498. for each in continent_list:
  499. if country_qs[0]['region__name'] == each['continentName']:
  500. each['count'] += count
  501. flag = 1
  502. break
  503. if flag == 0:
  504. continent_list.append({
  505. 'continentName': country_qs[0]['region__name'],
  506. 'count': count
  507. })
  508. for item in continent_list:
  509. item['rate'] = round(item['count'] / count_all * 100, 2)
  510. res['countries'] = CommonService.list_sort(device_country_list)
  511. res['continent'] = CommonService.list_sort(continent_list)
  512. return response.json(0, res)
  513. except Exception as e:
  514. print(e)
  515. return response.json(500)
  516. @classmethod
  517. def type_statistics(cls, response):
  518. """
  519. 统计设备类型
  520. @param response:响应对象
  521. @return:
  522. """
  523. uid_set_qs = UidSetModel.objects.values('uid').order_by('uid')
  524. uid_list = [item[key] for item in uid_set_qs for key in item]
  525. device_info_qs = Device_Info.objects.filter(UID__in=uid_list)
  526. device_type_qs = device_info_qs.values('Type').annotate(count=Count('Type')).order_by('-count')
  527. count_all = len(uid_list)
  528. device_info_count = device_info_qs.count()
  529. # 查询不到(类型)的设备数量
  530. if not device_info_qs.exists():
  531. return response.json(444)
  532. res = {}
  533. try:
  534. device_info_list = []
  535. count = count_all - device_info_count
  536. name = '未知类型'
  537. rate = round(count / count_all * 100, 2)
  538. device_info_list.append({
  539. 'count': count,
  540. 'name': name,
  541. 'rate': rate
  542. })
  543. for device_info in device_type_qs:
  544. Type = device_info['Type']
  545. device_type_qs = DeviceTypeModel.objects.filter(type=Type).values('name')
  546. name = device_type_qs[0]['name'] if device_type_qs.exists() else '未知类型'
  547. count = device_info['count']
  548. rate = round(count / count_all * 100, 2)
  549. device_info_list.append({
  550. 'type': name,
  551. 'count': count,
  552. 'rate': rate
  553. })
  554. res['type'] = device_info_list
  555. return response.json(0, res)
  556. except Exception as e:
  557. print(e)
  558. return response.json(500)