CronTaskController.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2022 #
  5. # @Time : 2022/4/1 11:27
  6. # @Author : ming
  7. # @Email : zhangdongming@asj6.wecom.work
  8. # @File : CronTaskController.py
  9. # @Software: PyCharm
  10. import datetime
  11. import threading
  12. import time
  13. import requests
  14. from django.db import connection, connections, transaction
  15. from django.db.models import Q, Sum, Count
  16. from django.views import View
  17. from Ansjer.config import USED_SERIAL_REDIS_LIST, UNUSED_SERIAL_REDIS_LIST, CONFIG_INFO, CONFIG_US, \
  18. RESET_REGION_ID_SERIAL_REDIS_LIST, LOGGER
  19. from Model.models import Device_User, Device_Info, UidSetModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
  20. VodHlsModel, ExperienceContextModel, AiService, VodHlsSummary, VideoPlaybackTimeModel, DeviceUserSummary, \
  21. CountryModel, DeviceTypeModel, OrdersSummary, DeviceInfoSummary, CompanySerialModel, \
  22. CloudLogModel, UidCloudStorageCount, UserExModel, DeviceDomainRegionModel, VodHlsTag, VodHlsTagType, IcloudService, \
  23. Store_Meal, Lang, VodBucketModel, UnicomComboOrderInfo, UnicomDeviceInfo
  24. from Object.RedisObject import RedisObject
  25. from Object.ResponseObject import ResponseObject
  26. from Object.utils import LocalDateTimeUtil
  27. from Service.CommonService import CommonService
  28. from Service.VodHlsService import SplitVodHlsObject
  29. from Object.UnicomObject import UnicomObjeect
  30. class CronDelDataView(View):
  31. def get(self, request, *args, **kwargs):
  32. request.encoding = 'utf-8'
  33. operation = kwargs.get('operation')
  34. return self.validation(request.GET, request, operation)
  35. def post(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. operation = kwargs.get('operation')
  38. return self.validation(request.POST, request, operation)
  39. def validation(self, request_dict, request, operation):
  40. response = ResponseObject()
  41. if operation == 'delAccessLog': # 定时删除访问接口数据
  42. return self.delAccessLog(response)
  43. elif operation == 'delPushInfo': # 定时删除推送数据
  44. return self.delPushInfo(response)
  45. elif operation == 'delVodHls': # 定时删除云存播放列表
  46. return self.delVodHls(response)
  47. elif operation == 'delCloudLog': # 定时删除云存接口数据
  48. return self.delCloudLog(response)
  49. elif operation == 'delTesterDevice': # 定时删除测试账号下的设备数据
  50. return self.delTesterDevice(response)
  51. elif operation == 'delAppLog': # 定时删除app日志
  52. return self.delAppLog(response)
  53. elif operation == 'UpdateConfiguration': # 定时更新配置
  54. return self.UpdateConfiguration(response)
  55. elif operation == 'cloud-log':
  56. return self.uid_cloud_storage_upload_count(response)
  57. elif operation == 'delDeviceLog': # 定时删除设备日志
  58. return self.del_device_log(response)
  59. else:
  60. return response.json(404)
  61. @staticmethod
  62. def UpdateConfiguration(response):
  63. """
  64. 定时更新配置
  65. @param response: 响应对象
  66. @return:
  67. """
  68. try:
  69. ucode_list = ['823C01552AA',
  70. '823C01550AA',
  71. '823C01550XA',
  72. '823C01850XA',
  73. '730201350AA',
  74. '730201350AA',
  75. '730201450AA',
  76. '730201450MA',
  77. '72V201252AA',
  78. '72V201253AA',
  79. '72V201353AA',
  80. '72V201354AA',
  81. '72V201355AA',
  82. '72V201254AA']
  83. UidSetModel.objects.filter(ucode__in=ucode_list, is_human=0).update(is_human=1)
  84. UidSetModel.objects.filter(ucode='72V201254AA', mobile_4g=0).update(mobile_4g=1)
  85. # 根据设备规格码定时更新默认算法类型类型
  86. ucode_list = ['823C01552AA', '823C01550AA', '823C01550XA', 'C18201550KA',
  87. '823C01550TA', '823C01550VA', '823C01850XA', 'C18201850KA',
  88. '823C01850TA', '823C01850VA']
  89. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=47)
  90. ucode_list = ['730201350AA', '730201450AA', '730201450MA', '730201450NA']
  91. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=7)
  92. # 根据设备规格码更新默认个性化语音值
  93. ucode_list = ['823C01552AA', '823C01550XA', 'C18201550KA', '823C01550TA',
  94. '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', '823C01850VA',
  95. '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA',
  96. '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA']
  97. UidSetModel.objects.filter(ucode__in=ucode_list, is_custom_voice=0).update(is_custom_voice=1)
  98. # 根据设备规格码更新is_ai
  99. ucode_list = ['823C01552AA', '823C01550XA', 'C18201550KA', '823C01550TA',
  100. '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', '823C01850VA',
  101. '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA',
  102. '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA']
  103. UidSetModel.objects.filter(ucode__in=ucode_list, is_ai=2).update(is_ai=1)
  104. return response.json(0)
  105. except Exception as e:
  106. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  107. @staticmethod
  108. def delAppLog(response):
  109. """
  110. 定时删除app日志
  111. @param response: 响应对象
  112. @return:
  113. """
  114. nowTime = int(time.time())
  115. try:
  116. cursor = connection.cursor()
  117. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  118. sql = 'DELETE FROM `app_log` WHERE add_time<{}'.format(month_ago_time)
  119. cursor.execute(sql)
  120. cursor.close()
  121. return response.json(0)
  122. except Exception as e:
  123. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  124. @staticmethod
  125. def uid_cloud_storage_upload_count(response):
  126. try:
  127. now_time = int(time.time())
  128. local_time = LocalDateTimeUtil.get_before_days_timestamp(now_time)
  129. format_str = '%Y-%m-%d'
  130. date_str = LocalDateTimeUtil.time_stamp_to_time(local_time, format_str)
  131. start_time, end_time = LocalDateTimeUtil.get_start_and_end_time(date_str, format_str)
  132. cs_uid_qs = UID_Bucket.objects.filter(addTime__gte=int(1669824000)).values('uid')
  133. if not cs_uid_qs.exists():
  134. return response.json(0)
  135. for item in cs_uid_qs:
  136. uid = item['uid']
  137. cloud_log_qs = CloudLogModel.objects.filter(uid=uid, operation=r'cloudstorage/storeplaylist',
  138. time__gte=start_time, time__lte=end_time)
  139. cloud_log_qs = cloud_log_qs.values('uid')[0:1]
  140. if not cloud_log_qs.exists():
  141. continue
  142. count_data = {'uid': uid, 'count': cloud_log_qs.count(), 'created_time': end_time,
  143. 'updated_time': end_time}
  144. UidCloudStorageCount.objects.create(**count_data)
  145. return response.json(0)
  146. except Exception as e:
  147. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  148. return response.json(500)
  149. @staticmethod
  150. def delAccessLog(response):
  151. try:
  152. cursor = connection.cursor()
  153. # 删除7天前的数据
  154. last_week = LocalDateTimeUtil.get_last_week()
  155. sql = 'DELETE FROM access_log WHERE time < %s limit %s'
  156. cursor.execute(sql, [last_week, 10000])
  157. # 关闭游标
  158. cursor.close()
  159. connection.close()
  160. return response.json(0)
  161. except Exception as e:
  162. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  163. @staticmethod
  164. def delPushInfo(response):
  165. now_time = int(time.time())
  166. cursor = connections['mysql02'].cursor()
  167. try:
  168. # 当前时间转日期
  169. local_date_now = str(datetime.datetime.fromtimestamp(int(now_time)).date())
  170. # 根据日期获取周几
  171. week_val = LocalDateTimeUtil.date_to_week(local_date_now)
  172. # 根据当前时间获取7天前时间戳
  173. expiration_time = LocalDateTimeUtil.get_before_days_timestamp(now_time, 7)
  174. # 每次删除条数
  175. size = 10000
  176. # 删除7天前的数据
  177. sql = "DELETE FROM equipment_info WHERE addTime<= %s LIMIT %s "
  178. for i in range(6):
  179. cursor.execute(sql, [expiration_time, size])
  180. if week_val == 1:
  181. sql = "DELETE FROM equipment_info_sunday WHERE add_time<= %s LIMIT %s "
  182. if week_val == 2:
  183. sql = "DELETE FROM equipment_info_monday WHERE add_time<= %s LIMIT %s "
  184. if week_val == 3:
  185. sql = "DELETE FROM equipment_info_tuesday WHERE add_time<= %s LIMIT %s "
  186. if week_val == 4:
  187. sql = "DELETE FROM equipment_info_wednesday WHERE add_time<= %s LIMIT %s "
  188. if week_val == 5:
  189. sql = "DELETE FROM equipment_info_thursday WHERE add_time<= %s LIMIT %s "
  190. if week_val == 6:
  191. sql = "DELETE FROM equipment_info_friday WHERE add_time<= %s LIMIT %s "
  192. if week_val == 7:
  193. sql = "DELETE FROM equipment_info_saturday WHERE add_time<= %s LIMIT %s "
  194. for i in range(5):
  195. cursor.execute(sql, [expiration_time, size])
  196. # 关闭游标
  197. cursor.close()
  198. return response.json(0)
  199. except Exception as e:
  200. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  201. @staticmethod
  202. def delVodHls(response):
  203. nowTime = int(time.time())
  204. try:
  205. CronDelDataView.del_vod_hls_tag()
  206. cursor = connection.cursor()
  207. month_ago_time = nowTime - 3 * 30 * 24 * 60 * 60 # 删除3个月前的数据
  208. sql = 'DELETE FROM `vod_hls` WHERE endTime<{} LIMIT 50000'.format(month_ago_time)
  209. cursor.execute(sql)
  210. cursor.close()
  211. # 删除vod_hls分表数据
  212. split_vod_hls_obj = SplitVodHlsObject()
  213. split_vod_hls_obj.del_vod_hls_data(end_time__lt=month_ago_time)
  214. return response.json(0)
  215. except Exception as e:
  216. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  217. @staticmethod
  218. def del_vod_hls_tag():
  219. """
  220. 删除AI标签记录
  221. """
  222. e_time = LocalDateTimeUtil.get_before_days_timestamp(int(time.time()), 30)
  223. VodHlsTagType.objects.filter(created_time__lt=e_time).delete()
  224. VodHlsTag.objects.filter(created_time__lt=e_time).delete()
  225. @staticmethod
  226. def delCloudLog(response):
  227. nowTime = int(time.time())
  228. cursor = connection.cursor()
  229. try:
  230. # 删除3个月前的数据
  231. sql = "DELETE FROM `cloud_log` WHERE time<={} LIMIT 50000".format(
  232. nowTime - 3 * 30 * 24 * 60 * 60)
  233. cursor.execute(sql)
  234. # 关闭游标
  235. cursor.close()
  236. return response.json(0)
  237. except Exception as e:
  238. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  239. @staticmethod
  240. def delTesterDevice(response):
  241. try:
  242. userID_list = [
  243. 'tech01@ansjer.com',
  244. 'tech02@ansjer.com',
  245. 'tech03@ansjer.com',
  246. 'tech04@ansjer.com',
  247. 'tech05@ansjer.com',
  248. 'tech06@ansjer.com',
  249. 'tech07@ansjer.com',
  250. 'tech08@ansjer.com',
  251. 'tech09@ansjer.com',
  252. 'tech10@ansjer.com',
  253. 'fix01@ansjer.com',
  254. 'fix02@ansjer.com',
  255. 'fix03@ansjer.com',
  256. 'fix04@ansjer.com',
  257. 'fix05@ansjer.com']
  258. device_user = Device_User.objects.filter(username__in=userID_list)
  259. device_info_qs = Device_Info.objects.filter(
  260. userID__in=device_user).values('UID')
  261. uid_list = []
  262. for device_info in device_info_qs:
  263. uid_list.append(device_info['UID'])
  264. with transaction.atomic():
  265. # 删除设备云存相关数据
  266. UidSetModel.objects.filter(uid__in=uid_list).delete()
  267. UID_Bucket.objects.filter(uid__in=uid_list).delete()
  268. Unused_Uid_Meal.objects.filter(uid__in=uid_list).delete()
  269. Order_Model.objects.filter(UID__in=uid_list).delete()
  270. StsCrdModel.objects.filter(uid__in=uid_list).delete()
  271. VodHlsModel.objects.filter(uid__in=uid_list).delete()
  272. # 删除vod_hls分表数据
  273. split_vod_hls_obj = SplitVodHlsObject()
  274. split_vod_hls_obj.del_vod_hls_data(uid__in=uid_list)
  275. ExperienceContextModel.objects.filter(uid__in=uid_list).delete()
  276. Device_Info.objects.filter(userID__in=device_user).delete()
  277. return response.json(0)
  278. except Exception as e:
  279. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  280. @staticmethod
  281. def del_device_log(response):
  282. """
  283. 定时删除设备日志
  284. @param response: 响应对象
  285. @return:
  286. """
  287. nowTime = int(time.time())
  288. try:
  289. cursor = connection.cursor()
  290. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  291. sql = 'DELETE FROM `device_log` WHERE unix_timestamp(add_time)<{}'.format(month_ago_time)
  292. cursor.execute(sql)
  293. cursor.close()
  294. return response.json(0)
  295. except Exception as e:
  296. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  297. class CronUpdateDataView(View):
  298. def get(self, request, *args, **kwargs):
  299. request.encoding = 'utf-8'
  300. operation = kwargs.get('operation')
  301. return self.validation(request.GET, request, operation)
  302. def post(self, request, *args, **kwargs):
  303. request.encoding = 'utf-8'
  304. operation = kwargs.get('operation')
  305. return self.validation(request.POST, request, operation)
  306. def validation(self, request_dict, request, operation):
  307. response = ResponseObject()
  308. if operation == 'updateUnusedUidBucket': # 定时更新过期云存关联的未使用套餐状态
  309. return self.updateUnusedUidBucket(response)
  310. elif operation == 'updateUnusedAiService': # 定时更新过期ai关联的未使用套餐状态
  311. return self.updateUnusedAiService(response)
  312. elif operation == 'updateIcloudService': # 定时更新过期云盘套餐使用状态
  313. return self.updateIcloudService(response)
  314. elif operation == 'reqUpdateSerialStatus': # 定时请求更新序列号状态
  315. return self.reqUpdateSerialStatus(response)
  316. elif operation == 'updateSerialStatus': # 更新序列号状态
  317. return self.updateSerialStatus(request_dict, response)
  318. elif operation == 'reset-region-id': # 重置地区id
  319. return self.reset_region_id(request_dict, response)
  320. elif operation == 'updateVodMeal': # 定时修改体验套餐有效期为1个月
  321. return self.update_vod_meal(request_dict, response)
  322. else:
  323. return response.json(404)
  324. @staticmethod
  325. def updateUnusedUidBucket(response):
  326. """
  327. 监控云存套餐过期修改状态
  328. @param response:
  329. @return:
  330. """
  331. # 定时更新已过期套餐修改状态为2
  332. now_time = int(time.time())
  333. expired_uid_bucket = UID_Bucket.objects.filter(endTime__lte=now_time)
  334. expired_uid_bucket = expired_uid_bucket.filter(~Q(use_status=2)).values('id')
  335. if expired_uid_bucket.exists():
  336. expired_uid_bucket.update(use_status=2)
  337. # 监控有未使用套餐则自动生效
  338. expired_uid_buckets = UID_Bucket.objects.filter(endTime__lte=now_time, has_unused=1).values("id", "uid")[0:1000]
  339. for expired_uid_bucket in expired_uid_buckets:
  340. unuseds = Unused_Uid_Meal.objects.filter(
  341. uid=expired_uid_bucket['uid']).values(
  342. "id",
  343. "uid",
  344. "channel",
  345. "addTime",
  346. "expire",
  347. "num",
  348. "bucket_id").order_by('addTime')
  349. if not unuseds.exists():
  350. continue
  351. unused = unuseds[0]
  352. try:
  353. with transaction.atomic():
  354. count_unused = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).count()
  355. has_unused = 1 if count_unused > 1 else 0
  356. end_time = CommonService.calcMonthLater(unused['expire'] * unused['num'])
  357. UID_Bucket.objects.filter(
  358. uid=expired_uid_bucket['uid']).update(
  359. channel=unused['channel'],
  360. endTime=end_time,
  361. bucket_id=unused['bucket_id'],
  362. updateTime=now_time,
  363. use_status=1,
  364. has_unused=has_unused)
  365. Unused_Uid_Meal.objects.filter(id=unused['id']).delete()
  366. StsCrdModel.objects.filter(uid=expired_uid_bucket['uid']).delete() # 删除sts记录
  367. except Exception as e:
  368. print(repr(e))
  369. continue
  370. return response.json(0)
  371. @staticmethod
  372. def updateUnusedAiService(response):
  373. now_time = int(time.time())
  374. ai_service_qs = AiService.objects.filter(
  375. endTime__lte=now_time,
  376. use_status=1).values(
  377. 'id',
  378. 'uid')[
  379. 0:200]
  380. for ai_service in ai_service_qs:
  381. try:
  382. with transaction.atomic():
  383. AiService.objects.filter(
  384. id=ai_service['id']).update(
  385. use_status=2) # 更新过期ai订单状态
  386. # 如果存在未使用套餐,更新为使用
  387. unused_ai_service = AiService.objects.filter(
  388. uid=ai_service['uid'],
  389. use_status=0).order_by('addTime')[
  390. :1].values(
  391. 'id',
  392. 'endTime')
  393. if unused_ai_service.exists():
  394. # 未使用套餐的endTime在购买的时候保存为有效时间
  395. effective_day = unused_ai_service[0]['endTime']
  396. endTime = now_time + effective_day
  397. AiService.objects.filter(
  398. id=unused_ai_service[0]['id']).update(
  399. use_status=1, endTime=endTime, updTime=now_time)
  400. except Exception:
  401. continue
  402. return response.json(0)
  403. @staticmethod
  404. def updateIcloudService(response):
  405. """
  406. 监控云盘套餐过期修改状态
  407. @param response:
  408. @return:
  409. """
  410. # 定时更新已过期套餐修改状态为2
  411. now_time = int(time.time())
  412. try:
  413. IcloudService.objects.filter(Q(end_time__lte=now_time), ~Q(end_time=0),
  414. ~Q(use_status=1)).update(use_status=1)
  415. return response.json(0)
  416. except Exception as e:
  417. return response.json(500)
  418. @classmethod
  419. def reqUpdateSerialStatus(cls, response):
  420. redis_obj = RedisObject()
  421. # 更新已使用序列号其他服务器的状态
  422. used_serial_redis_list = redis_obj.lrange(USED_SERIAL_REDIS_LIST, 0, -1) # 读取redis已使用序列号
  423. if used_serial_redis_list:
  424. LOGGER.info('---请求更新已使用序列号列表---used_serial_redis_list:{}'.format(used_serial_redis_list))
  425. used_serial_redis_list = [str(i, 'utf-8') for i in used_serial_redis_list]
  426. cls.do_request_function(used_serial_redis_list, 3)
  427. # 更新未使用序列号其他服务器的状态
  428. unused_serial_redis_list = redis_obj.lrange(UNUSED_SERIAL_REDIS_LIST, 0, -1) # 读取redis未使用序列号
  429. if unused_serial_redis_list:
  430. LOGGER.info('---请求更新未使用序列号列表---unused_serial_redis_list:{}'.format(unused_serial_redis_list))
  431. unused_serial_redis_list = [str(i, 'utf-8') for i in unused_serial_redis_list]
  432. cls.do_request_function(unused_serial_redis_list, 1)
  433. # 重置地区id
  434. reset_region_id_serial_redis_list = redis_obj.lrange(RESET_REGION_ID_SERIAL_REDIS_LIST, 0, -1) # 读取redis未使用序列号
  435. if reset_region_id_serial_redis_list:
  436. LOGGER.info('---请求重置地区id的序列号列表---:{}'.format(reset_region_id_serial_redis_list))
  437. reset_region_id_serial_redis_list = [str(i, 'utf-8') for i in reset_region_id_serial_redis_list]
  438. cls.do_request_reset_region_id(reset_region_id_serial_redis_list)
  439. return response.json(0)
  440. @staticmethod
  441. def do_request_function(serial_redis_list, status):
  442. """
  443. 请求更新序列号状态
  444. @param serial_redis_list: 序列号redis列表
  445. @param status: 状态, 1: 未使用, 3: 已占用
  446. """
  447. data = {
  448. 'serial_redis_list': str(serial_redis_list),
  449. 'status': status
  450. }
  451. # 确认域名列表
  452. orders_domain_name_list = CommonService.get_orders_domain_name_list()
  453. redis_obj = RedisObject()
  454. LOGGER.info('---请求更新序列号线程---data:{},orders_domain_name_list:{}'.format(data, orders_domain_name_list))
  455. try:
  456. requests_failed_flag = False # 请求失败标志位
  457. for domain_name in orders_domain_name_list:
  458. url = '{}cron/update/updateSerialStatus'.format(domain_name)
  459. response = requests.post(url=url, data=data, timeout=5)
  460. LOGGER.info('---请求更新序列号响应时间---:{}'.format(response.elapsed.total_seconds()))
  461. result = response.json()
  462. if result['result_code'] != 0: # 请求失败标志位置位
  463. requests_failed_flag = True
  464. break
  465. # 状态为未使用,重置美洲服的地区id
  466. if status == 1: # 美洲服直接更新
  467. if CONFIG_INFO == CONFIG_US:
  468. DeviceDomainRegionModel.objects.filter(~Q(region_id=0), serial_number__in=serial_redis_list). \
  469. update(region_id=0)
  470. else: # 其他服请求到美洲服更新
  471. req_url = 'https://www.dvema.com/cron/update/reset-region-id'
  472. req_data = {
  473. 'serial_redis_list': str(serial_redis_list)
  474. }
  475. response = requests.post(url=req_url, data=req_data, timeout=5)
  476. LOGGER.info('---请求重置地区id响应时间---:{}'.format(response.elapsed.total_seconds()))
  477. result = response.json()
  478. if result['result_code'] != 0: # 请求失败标志位置位
  479. requests_failed_flag = True
  480. break
  481. if not requests_failed_flag: # 请求成功删除redis序列号
  482. if status == 1:
  483. for i in serial_redis_list:
  484. redis_obj.lrem(UNUSED_SERIAL_REDIS_LIST, 0, i)
  485. elif status == 3:
  486. for i in serial_redis_list:
  487. redis_obj.lrem(USED_SERIAL_REDIS_LIST, 0, i)
  488. except Exception as e:
  489. LOGGER.info('---更新序列号状态异常---:{}'.format(repr(e)))
  490. @staticmethod
  491. def do_request_reset_region_id(reset_region_id_serial_redis_list):
  492. """
  493. 请求重置地区id
  494. @param reset_region_id_serial_redis_list: 序列号redis列表
  495. """
  496. redis_obj = RedisObject()
  497. requests_failed_flag = False # 请求失败标志位
  498. data = {
  499. 'serial_redis_list': str(reset_region_id_serial_redis_list),
  500. }
  501. url = 'https://www.dvema.com/cron/update/reset-region-id'
  502. try:
  503. response = requests.post(url=url, data=data, timeout=5)
  504. result = response.json()
  505. if result['result_code'] != 0: # 请求失败标志位置位
  506. requests_failed_flag = True
  507. if not requests_failed_flag: # 请求成功删除redis序列号
  508. for serial in reset_region_id_serial_redis_list:
  509. redis_obj.lrem(RESET_REGION_ID_SERIAL_REDIS_LIST, 0, serial)
  510. except Exception as e:
  511. LOGGER.info('---请求重置地区id异常---:{}'.format(repr(e)))
  512. @staticmethod
  513. def updateSerialStatus(request_dict, response):
  514. """
  515. 更新序列号状态
  516. @param request_dict: 请求参数
  517. @request_dict serial_redis_list: 序列号redis列表
  518. @request_dict status: 状态, 1: 未使用, 3: 已占用
  519. @param response: 响应对象
  520. """
  521. serial_redis_list = request_dict.get('serial_redis_list', None)
  522. status = request_dict.get('status', None)
  523. LOGGER.info('---更新序列号状态参数---serial_redis_list:{},status:{}'.format(serial_redis_list, status))
  524. if not all([serial_redis_list, status]):
  525. return response.json(444)
  526. now_time = int(time.time())
  527. try:
  528. serial_redis_list = eval(serial_redis_list)
  529. CompanySerialModel.objects.filter(serial_number__in=serial_redis_list).update(status=int(status),
  530. update_time=now_time)
  531. return response.json(0)
  532. except Exception as e:
  533. LOGGER.info('---更新序列号状态异常---:{}'.format(repr(e)))
  534. return response.json(500)
  535. @staticmethod
  536. def reset_region_id(request_dict, response):
  537. """
  538. 重置地区id
  539. @param request_dict: 请求参数
  540. @request_dict serial_redis_list: 序列号redis列表
  541. @param response: 响应对象
  542. """
  543. serial_redis_list = request_dict.get('serial_redis_list', None)
  544. LOGGER.info('---重置地区id参数---serial_redis_list:{}'.format(serial_redis_list))
  545. if not serial_redis_list:
  546. return response.json(444)
  547. try:
  548. serial_redis_list = eval(serial_redis_list)
  549. DeviceDomainRegionModel.objects.filter(serial_number__in=serial_redis_list).update(region_id=0)
  550. return response.json(0)
  551. except Exception as e:
  552. LOGGER.info('---重置地区id异常---:{}'.format(repr(e)))
  553. return response.json(500)
  554. @staticmethod
  555. def update_vod_meal(request_dict, response):
  556. """
  557. 定时修改体验套餐有效期为1个月
  558. @param request_dict: 请求参数
  559. @param response: 响应对象
  560. """
  561. try:
  562. Store_Meal.objects.filter(is_show=0, expire=12, pixel_level=0).update(price='39.99',
  563. virtual_price='56.6',
  564. sort=1)
  565. Store_Meal.objects.filter(is_show=0, cycle_config_id=1, pixel_level=0).update(price='3.65',
  566. virtual_price='5.66',
  567. sort=2)
  568. Store_Meal.objects.filter(id=12).update(price='3.99', virtual_price='5.66', sort=3)
  569. Store_Meal.objects.filter(id__in=(16, 17, 18)).update(is_show=0)
  570. return response.json(0)
  571. except Exception as e:
  572. LOGGER.info('---修改云存套餐内容异常---:{}'.format(repr(e)))
  573. return response.json(500)
  574. class CronCollectDataView(View):
  575. def get(self, request, *args, **kwargs):
  576. request.encoding = 'utf-8'
  577. operation = kwargs.get('operation')
  578. return self.validation(request.GET, request, operation)
  579. def post(self, request, *args, **kwargs):
  580. request.encoding = 'utf-8'
  581. operation = kwargs.get('operation')
  582. return self.validation(request.POST, request, operation)
  583. def validation(self, request_dict, request, operation):
  584. response = ResponseObject()
  585. if operation == 'collectPlayBack': # 定时保存云存视频回放
  586. return self.collect_play_back(response)
  587. elif operation == 'collectDeviceUser': # 定时保存用户数据
  588. return self.collect_device_user(response)
  589. elif operation == 'collectOrder': # 定时保存订单数据
  590. return self.collect_order(response)
  591. elif operation == 'collectIcloudOrder': # 定时保存云盘订单数据
  592. return self.collect_icloud_order(response)
  593. elif operation == 'collectDeviceInfo': # 定时保存设备数据
  594. return self.collect_device_info(response)
  595. elif operation == 'collectFlowInfo': # 定时保存设备数据
  596. return self.collect_flow_info(response)
  597. else:
  598. return response.json(404)
  599. @staticmethod
  600. def collect_play_back(response):
  601. try:
  602. now_time = int(time.time())
  603. today = datetime.datetime.today()
  604. start_time = datetime.datetime(today.year, today.month, today.day)
  605. end_time = start_time + datetime.timedelta(days=1)
  606. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  607. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  608. this_month_str = datetime.datetime(today.year, today.month, 1)
  609. this_month_stamp = CommonService.str_to_timestamp(this_month_str.strftime('%Y-%m-%d %H:%M:%S'))
  610. video_play_back_time_qs = VideoPlaybackTimeModel.objects.filter(startTime__gte=start_time,
  611. startTime__lt=end_time,
  612. playMode='cloud').values('uid').annotate(
  613. play_duration=Sum('duration'), play_frequency=Count('uid'))
  614. with transaction.atomic():
  615. for item in video_play_back_time_qs:
  616. vod_hls_summary_qs = VodHlsSummary.objects.filter(uid=item['uid'], time=this_month_stamp)
  617. if vod_hls_summary_qs.exists():
  618. vod_hls_summary = vod_hls_summary_qs.first()
  619. vod_hls_summary.play_duration += item['play_duration']
  620. vod_hls_summary.play_frequency += 1
  621. vod_hls_summary.updated_time = now_time
  622. vod_hls_summary.save()
  623. else:
  624. VodHlsSummary.objects.create(uid=item['uid'], time=this_month_stamp, created_time=now_time,
  625. play_duration=item['play_duration'], play_frequency=1,
  626. updated_time=now_time)
  627. return response.json(0)
  628. except Exception as e:
  629. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  630. @staticmethod
  631. def collect_device_user(response):
  632. try:
  633. created_time = int(time.time())
  634. today = datetime.datetime.today()
  635. start_time = datetime.datetime(today.year, today.month, today.day)
  636. end_time = start_time + datetime.timedelta(days=1)
  637. increase_user_qs = Device_User.objects.filter(data_joined__year=today.year, data_joined__month=today.month,
  638. data_joined__day=today.day).values('region_country')
  639. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  640. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  641. active_user_qs = UserExModel.objects.filter(updTime__gte=start_time, updTime__lt=end_time).values(
  642. 'userID__region_country')
  643. country_qs = CountryModel.objects.all().values('id', 'region__name', 'country_name')
  644. country_dict = {}
  645. continent_dict = {}
  646. for item in country_qs:
  647. country_dict[item['id']] = item['country_name']
  648. continent_dict[item['country_name']] = item['region__name']
  649. with transaction.atomic():
  650. if increase_user_qs.exists():
  651. increase_user_count = increase_user_qs.count()
  652. increase_user_country_list = increase_user_qs.values('region_country').annotate(
  653. count=Count('region_country')).order_by('count')
  654. increase_user_country_dict = {}
  655. increase_user_continent_dict = {}
  656. for item in increase_user_country_list:
  657. country_name = country_dict.get(item['region_country'], '未知国家')
  658. continent_name = continent_dict.get(country_name, '未知大洲')
  659. increase_user_country_dict[country_name] = item['count']
  660. if continent_name not in increase_user_continent_dict:
  661. increase_user_continent_dict[continent_name] = 0
  662. increase_user_continent_dict[continent_name] += item['count']
  663. DeviceUserSummary.objects.create(time=start_time, count=increase_user_count,
  664. country=increase_user_country_dict, created_time=created_time,
  665. continent=increase_user_continent_dict)
  666. if active_user_qs.exists():
  667. active_user_count = active_user_qs.count()
  668. active_user_country_list = active_user_qs.values('userID__region_country').annotate(
  669. count=Count('userID__region_country')).order_by('count')
  670. active_user_country_dict = {}
  671. active_user_continent_dict = {}
  672. for item in active_user_country_list:
  673. country_name = country_dict.get(item['userID__region_country'], '未知国家')
  674. continent_name = continent_dict.get(country_name, '未知大洲')
  675. active_user_country_dict[country_name] = item['count']
  676. if continent_name not in active_user_continent_dict:
  677. active_user_continent_dict[continent_name] = 0
  678. active_user_continent_dict[continent_name] += item['count']
  679. DeviceUserSummary.objects.create(time=start_time, query_type=1, count=active_user_count,
  680. country=active_user_country_dict, created_time=created_time,
  681. continent=active_user_continent_dict)
  682. return response.json(0)
  683. except Exception as e:
  684. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  685. @staticmethod
  686. def collect_order(response):
  687. try:
  688. created_time = int(time.time())
  689. today = datetime.datetime.today()
  690. start_time = datetime.datetime(today.year, today.month, today.day)
  691. end_time = start_time + datetime.timedelta(days=1)
  692. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  693. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  694. order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time,
  695. status=1).values('UID', 'order_type',
  696. 'store_meal_name', 'price',
  697. 'addTime', 'currency').order_by(
  698. 'addTime')
  699. uid_list = []
  700. all_order_qs = Order_Model.objects.filter(addTime__lt=start_time, status=1).values('UID')
  701. for item in all_order_qs:
  702. if item['UID'] not in uid_list:
  703. uid_list.append(item['UID'])
  704. # 国家表数据
  705. country_qs = CountryModel.objects.values('id', 'country_name')
  706. country_dict = {}
  707. for item in country_qs:
  708. country_dict[item['id']] = item['country_name']
  709. # 设备类型数据
  710. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  711. device_type_dict = {}
  712. for item in device_type_qs:
  713. device_type_dict[item['type']] = item['name']
  714. with transaction.atomic():
  715. for item in order_qs:
  716. is_pay = 0
  717. price = float(item['price'])
  718. currency = item['currency']
  719. uid_set_qs = UidSetModel.objects.filter(uid=item['UID']).values('tb_country')
  720. country_id = uid_set_qs[0]['tb_country'] if uid_set_qs.exists() else 0
  721. country_name = country_dict.get(country_id, '未知国家')
  722. order_type = item['order_type']
  723. if order_type == '4' or order_type == 4:
  724. continue
  725. device_info_qs = Device_Info.objects.filter(UID=item['UID']).values('Type')
  726. device_type_id = device_info_qs[0]['Type'] if device_info_qs.exists() else 0
  727. device_type_name = device_type_dict.get(device_type_id, '未知设备')
  728. store_meal_name = item['store_meal_name']
  729. add_time_stamp = item['addTime']
  730. add_time_str = datetime.datetime.fromtimestamp(int(add_time_stamp))
  731. add_time_str = datetime.datetime(add_time_str.year, add_time_str.month, add_time_str.day)
  732. add_time_stamp = CommonService.str_to_timestamp(add_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  733. if price == 0:
  734. is_pay = 1
  735. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=1,
  736. service_type=order_type)
  737. else:
  738. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=0,
  739. service_type=order_type)
  740. if item['UID'] not in uid_list:
  741. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=2,
  742. service_type=order_type)
  743. query_type = 2
  744. else:
  745. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=3,
  746. service_type=order_type)
  747. query_type = 3
  748. if pay_order_summary_qs.exists():
  749. pay_order_summary = pay_order_summary_qs.first()
  750. pay_order_summary.count += 1
  751. temp_total = eval(pay_order_summary.total)
  752. if currency not in temp_total:
  753. temp_total[currency] = price
  754. else:
  755. temp_total[currency] = round(temp_total[currency] + price, 2)
  756. pay_order_summary.total = temp_total
  757. country_temp_dict = eval(pay_order_summary.country)
  758. if country_name in country_temp_dict:
  759. country_temp_dict[country_name]['数量'] += 1
  760. if currency not in country_temp_dict[country_name]:
  761. country_temp_dict[country_name][currency] = price
  762. else:
  763. country_temp_dict[country_name][currency] = round(
  764. country_temp_dict[country_name][currency] + price, 2)
  765. else:
  766. country_temp_dict[country_name] = {'数量': 1, currency: price}
  767. pay_order_summary.country = country_temp_dict
  768. device_type_temp_dict = eval(pay_order_summary.device_type)
  769. if device_type_name in device_type_temp_dict:
  770. device_type_temp_dict[device_type_name]['数量'] += 1
  771. if currency not in device_type_temp_dict[device_type_name]:
  772. device_type_temp_dict[device_type_name][currency] = price
  773. else:
  774. device_type_temp_dict[device_type_name][currency] = round(
  775. device_type_temp_dict[device_type_name][currency] + price, 2)
  776. else:
  777. device_type_temp_dict[device_type_name] = {'数量': 1, currency: price}
  778. pay_order_summary.device_type = device_type_temp_dict
  779. store_meal_temp_dict = eval(pay_order_summary.store_meal)
  780. if store_meal_name in store_meal_temp_dict:
  781. store_meal_temp_dict[store_meal_name]['数量'] += 1
  782. if currency not in store_meal_temp_dict[store_meal_name]:
  783. store_meal_temp_dict[store_meal_name][currency] = price
  784. else:
  785. store_meal_temp_dict[store_meal_name][currency] = round(
  786. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  787. else:
  788. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  789. pay_order_summary.store_meal = store_meal_temp_dict
  790. pay_order_summary.save()
  791. else:
  792. final_total = {currency: price}
  793. country_temp_dict = {
  794. country_name: {
  795. '数量': 1,
  796. currency: price
  797. }
  798. }
  799. device_type_temp_dict = {
  800. device_type_name: {
  801. '数量': 1,
  802. currency: price
  803. }
  804. }
  805. store_meal_temp_dict = {
  806. store_meal_name: {
  807. '数量': 1,
  808. currency: price
  809. }
  810. }
  811. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=query_type,
  812. service_type=order_type, total=final_total,
  813. country=country_temp_dict, created_time=created_time,
  814. device_type=device_type_temp_dict,
  815. store_meal=store_meal_temp_dict)
  816. if order_summary_qs.exists():
  817. order_summary = order_summary_qs.first()
  818. order_summary.count += 1
  819. temp_total = eval(order_summary.total)
  820. if currency not in temp_total:
  821. temp_total[currency] = price
  822. else:
  823. temp_total[currency] = round(temp_total[currency] + price, 2)
  824. order_summary.total = temp_total
  825. country_temp_dict = eval(order_summary.country)
  826. if country_name in country_temp_dict:
  827. if is_pay == 0:
  828. country_temp_dict[country_name]['数量'] += 1
  829. if currency not in country_temp_dict[country_name]:
  830. country_temp_dict[country_name][currency] = price
  831. else:
  832. country_temp_dict[country_name][currency] = round(
  833. country_temp_dict[country_name][currency] + price, 2)
  834. else:
  835. country_temp_dict[country_name] += 1
  836. else:
  837. if is_pay == 0:
  838. country_temp_dict[country_name] = {'数量': 1, currency: price}
  839. else:
  840. country_temp_dict[country_name] = 1
  841. order_summary.country = country_temp_dict
  842. device_type_temp_dict = eval(order_summary.device_type)
  843. if device_type_name in device_type_temp_dict:
  844. if is_pay == 0:
  845. device_type_temp_dict[device_type_name]['数量'] += 1
  846. if currency not in device_type_temp_dict[device_type_name]:
  847. device_type_temp_dict[device_type_name][currency] = price
  848. else:
  849. device_type_temp_dict[device_type_name][currency] = round(
  850. device_type_temp_dict[device_type_name][currency] + price, 2)
  851. else:
  852. device_type_temp_dict[device_type_name] += 1
  853. else:
  854. if is_pay == 0:
  855. device_type_temp_dict[device_type_name] = {'数量': 1, currency: price}
  856. else:
  857. device_type_temp_dict[device_type_name] = 1
  858. order_summary.device_type = device_type_temp_dict
  859. store_meal_temp_dict = eval(order_summary.store_meal)
  860. if store_meal_name in store_meal_temp_dict:
  861. if is_pay == 0:
  862. store_meal_temp_dict[store_meal_name]['数量'] += 1
  863. if currency not in store_meal_temp_dict[store_meal_name]:
  864. store_meal_temp_dict[store_meal_name][currency] = price
  865. else:
  866. store_meal_temp_dict[store_meal_name][currency] = round(
  867. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  868. else:
  869. store_meal_temp_dict[store_meal_name] += 1
  870. else:
  871. if is_pay == 0:
  872. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  873. else:
  874. store_meal_temp_dict[store_meal_name] = 1
  875. order_summary.store_meal = store_meal_temp_dict
  876. order_summary.save()
  877. else:
  878. final_total = {currency: price}
  879. if is_pay == 0:
  880. country_temp_dict = {
  881. country_name: {
  882. '数量': 1,
  883. currency: price
  884. }
  885. }
  886. device_type_temp_dict = {
  887. device_type_name: {
  888. '数量': 1,
  889. currency: price
  890. }
  891. }
  892. store_meal_temp_dict = {
  893. store_meal_name: {
  894. '数量': 1,
  895. currency: price
  896. }
  897. }
  898. else:
  899. device_type_temp_dict = {
  900. device_type_name: 1
  901. }
  902. store_meal_temp_dict = {
  903. store_meal_name: 1
  904. }
  905. country_temp_dict = {
  906. country_name: 1
  907. }
  908. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=is_pay,
  909. service_type=order_type, total=final_total,
  910. country=country_temp_dict, created_time=created_time,
  911. device_type=device_type_temp_dict, store_meal=store_meal_temp_dict)
  912. return response.json(0)
  913. except Exception as e:
  914. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  915. @staticmethod
  916. def collect_icloud_order(response):
  917. try:
  918. order_type = 4
  919. created_time = int(time.time())
  920. today = datetime.datetime.today()
  921. start_time = datetime.datetime(today.year, today.month, today.day)
  922. end_time = start_time + datetime.timedelta(days=1)
  923. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  924. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  925. order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time, order_type=order_type,
  926. status=1).values('userID',
  927. 'store_meal_name', 'price',
  928. 'addTime', 'currency').order_by(
  929. 'addTime')
  930. user_list = []
  931. all_order_qs = Order_Model.objects.filter(addTime__lt=start_time, status=1, order_type=order_type).values(
  932. 'userID')
  933. for item in all_order_qs:
  934. if item['userID'] not in user_list:
  935. user_list.append(item['userID'])
  936. # 国家表数据
  937. country_qs = CountryModel.objects.values('id', 'country_name')
  938. country_dict = {}
  939. for item in country_qs:
  940. country_dict[item['id']] = item['country_name']
  941. with transaction.atomic():
  942. for item in order_qs:
  943. price = float(item['price'])
  944. currency = item['currency']
  945. user_qs = Device_User.objects.filter(userID=item['userID']).values('region_country')
  946. country_id = user_qs[0]['region_country'] if user_qs.exists() else 0
  947. country_name = country_dict.get(country_id, '未知国家')
  948. store_meal_name = item['store_meal_name']
  949. add_time_stamp = item['addTime']
  950. add_time_str = datetime.datetime.fromtimestamp(int(add_time_stamp))
  951. add_time_str = datetime.datetime(add_time_str.year, add_time_str.month, add_time_str.day)
  952. add_time_stamp = CommonService.str_to_timestamp(add_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  953. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=0,
  954. service_type=order_type)
  955. if item['userID'] not in user_list:
  956. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=2,
  957. service_type=order_type)
  958. query_type = 2
  959. else:
  960. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=3,
  961. service_type=order_type)
  962. query_type = 3
  963. if pay_order_summary_qs.exists():
  964. pay_order_summary = pay_order_summary_qs.first()
  965. pay_order_summary.count += 1
  966. temp_total = eval(pay_order_summary.total)
  967. if currency not in temp_total:
  968. temp_total[currency] = price
  969. else:
  970. temp_total[currency] = round(temp_total[currency] + price, 2)
  971. pay_order_summary.total = temp_total
  972. country_temp_dict = eval(pay_order_summary.country)
  973. if country_name in country_temp_dict:
  974. country_temp_dict[country_name]['数量'] += 1
  975. if currency not in country_temp_dict[country_name]:
  976. country_temp_dict[country_name][currency] = price
  977. else:
  978. country_temp_dict[country_name][currency] = round(
  979. country_temp_dict[country_name][currency] + price, 2)
  980. else:
  981. country_temp_dict[country_name] = {'数量': 1, currency: price}
  982. pay_order_summary.country = country_temp_dict
  983. store_meal_temp_dict = eval(pay_order_summary.store_meal)
  984. if store_meal_name in store_meal_temp_dict:
  985. store_meal_temp_dict[store_meal_name]['数量'] += 1
  986. if currency not in store_meal_temp_dict[store_meal_name]:
  987. store_meal_temp_dict[store_meal_name][currency] = price
  988. else:
  989. store_meal_temp_dict[store_meal_name][currency] = round(
  990. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  991. else:
  992. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  993. pay_order_summary.store_meal = store_meal_temp_dict
  994. pay_order_summary.save()
  995. else:
  996. final_total = {currency: price}
  997. country_temp_dict = {
  998. country_name: {
  999. '数量': 1,
  1000. currency: price
  1001. }
  1002. }
  1003. store_meal_temp_dict = {
  1004. store_meal_name: {
  1005. '数量': 1,
  1006. currency: price
  1007. }
  1008. }
  1009. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=query_type,
  1010. service_type=order_type, total=final_total,
  1011. country=country_temp_dict, created_time=created_time,
  1012. device_type={},
  1013. store_meal=store_meal_temp_dict)
  1014. if order_summary_qs.exists():
  1015. order_summary = order_summary_qs.first()
  1016. order_summary.count += 1
  1017. temp_total = eval(order_summary.total)
  1018. if currency not in temp_total:
  1019. temp_total[currency] = price
  1020. else:
  1021. temp_total[currency] = round(temp_total[currency] + price, 2)
  1022. order_summary.total = temp_total
  1023. country_temp_dict = eval(order_summary.country)
  1024. if country_name in country_temp_dict:
  1025. country_temp_dict[country_name]['数量'] += 1
  1026. if currency not in country_temp_dict[country_name]:
  1027. country_temp_dict[country_name][currency] = price
  1028. else:
  1029. country_temp_dict[country_name][currency] = round(
  1030. country_temp_dict[country_name][currency] + price, 2)
  1031. else:
  1032. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1033. order_summary.country = country_temp_dict
  1034. store_meal_temp_dict = eval(order_summary.store_meal)
  1035. if store_meal_name in store_meal_temp_dict:
  1036. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1037. if currency not in store_meal_temp_dict[store_meal_name]:
  1038. store_meal_temp_dict[store_meal_name][currency] = price
  1039. else:
  1040. store_meal_temp_dict[store_meal_name][currency] = round(
  1041. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1042. else:
  1043. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1044. order_summary.store_meal = store_meal_temp_dict
  1045. order_summary.save()
  1046. else:
  1047. final_total = {currency: price}
  1048. country_temp_dict = {
  1049. country_name: {
  1050. '数量': 1,
  1051. currency: price
  1052. }
  1053. }
  1054. store_meal_temp_dict = {
  1055. store_meal_name: {
  1056. '数量': 1,
  1057. currency: price
  1058. }
  1059. }
  1060. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=0,
  1061. service_type=order_type, total=final_total,
  1062. country=country_temp_dict, created_time=created_time,
  1063. device_type={}, store_meal=store_meal_temp_dict)
  1064. return response.json(0)
  1065. except Exception as e:
  1066. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1067. @staticmethod
  1068. def collect_device_info(response):
  1069. try:
  1070. created_time = int(time.time())
  1071. today = datetime.datetime.today()
  1072. start_time = datetime.datetime(today.year, today.month, today.day)
  1073. end_time = start_time + datetime.timedelta(days=1)
  1074. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1075. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1076. increase_device_qs = UidSetModel.objects.filter(addTime__gte=start_time, addTime__lt=end_time).values(
  1077. 'tb_country',
  1078. 'uid',
  1079. 'device_type',
  1080. 'cloud_vod',
  1081. 'is_ai',
  1082. 'mobile_4g',
  1083. 'addTime')
  1084. video_play_back_time_qs = VideoPlaybackTimeModel.objects.filter(startTime__gte=start_time,
  1085. startTime__lt=end_time).values('uid')
  1086. active_device_qs = UidSetModel.objects.filter(uid__in=video_play_back_time_qs).values('tb_country',
  1087. 'addTime',
  1088. 'device_type',
  1089. 'cloud_vod',
  1090. 'is_ai',
  1091. 'mobile_4g',
  1092. 'uid')
  1093. increase_device_count = increase_device_qs.count()
  1094. active_device_count = active_device_qs.count()
  1095. # 国家表数据
  1096. country_qs = CountryModel.objects.values('id', 'country_name', 'region__name')
  1097. country_dict = {}
  1098. continent_dict = {}
  1099. for item in country_qs:
  1100. country_dict[item['id']] = item['country_name']
  1101. continent_dict[item['country_name']] = item['region__name']
  1102. # 设备类型数据
  1103. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  1104. device_type_dict = {}
  1105. for item in device_type_qs:
  1106. device_type_dict[item['type']] = item['name']
  1107. with transaction.atomic():
  1108. if increase_device_qs.exists():
  1109. # 国家大洲设备数据
  1110. increase_device_country_list = increase_device_qs.values('tb_country').annotate(
  1111. count=Count('tb_country')).order_by('count')
  1112. increase_device_country_dict = {}
  1113. increase_device_continent_dict = {}
  1114. for item in increase_device_country_list:
  1115. country_name = country_dict.get(item['tb_country'], '未知国家')
  1116. continent_name = continent_dict.get(country_name, '未知大洲')
  1117. increase_device_country_dict[country_name] = item['count']
  1118. if continent_name not in increase_device_continent_dict:
  1119. increase_device_continent_dict[continent_name] = 0
  1120. increase_device_continent_dict[continent_name] += item['count']
  1121. # 设备类型数据
  1122. increase_device_type_list = increase_device_qs.values('device_type').annotate(
  1123. count=Count('device_type')).order_by('count')
  1124. increase_device_type_dict = {}
  1125. for item in increase_device_type_list:
  1126. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1127. increase_device_type_dict[type_name] = item['count']
  1128. # 云存设备类型数据
  1129. increase_device_vod_list = increase_device_qs.filter(~Q(cloud_vod=2)).values(
  1130. 'device_type').annotate(
  1131. count=Count('device_type')).order_by('count')
  1132. increase_device_vod_dict = {}
  1133. for item in increase_device_vod_list:
  1134. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1135. increase_device_vod_dict[type_name] = item['count']
  1136. # AI设备类型数据
  1137. increase_device_ai_list = increase_device_qs.filter(~Q(is_ai=2)).values('device_type').annotate(
  1138. count=Count('device_type')).order_by('count')
  1139. increase_device_ai_dict = {}
  1140. for item in increase_device_ai_list:
  1141. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1142. increase_device_ai_dict[type_name] = item['count']
  1143. # 联通设备类型数据
  1144. increase_device_unicom_list = increase_device_qs.filter(~Q(mobile_4g=2)).values(
  1145. 'device_type').annotate(
  1146. count=Count('device_type')).order_by('count')
  1147. increase_device_unicom_dict = {}
  1148. for item in increase_device_unicom_list:
  1149. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1150. increase_device_unicom_dict[type_name] = item['count']
  1151. DeviceInfoSummary.objects.create(time=start_time, count=increase_device_count,
  1152. query_type=0, created_time=created_time,
  1153. country=increase_device_country_dict,
  1154. continent=increase_device_continent_dict,
  1155. vod_service=increase_device_vod_dict,
  1156. ai_service=increase_device_ai_dict,
  1157. unicom_service=increase_device_unicom_dict,
  1158. device_type=increase_device_type_dict)
  1159. if active_device_qs.exists():
  1160. # 国家大洲设备数据
  1161. active_device_country_list = active_device_qs.values('tb_country').annotate(
  1162. count=Count('tb_country')).order_by('count')
  1163. active_device_country_dict = {}
  1164. active_device_continent_dict = {}
  1165. for item in active_device_country_list:
  1166. country_name = country_dict.get(item['tb_country'], '未知国家')
  1167. continent_name = continent_dict.get(country_name, '未知大洲')
  1168. active_device_country_dict[country_name] = item['count']
  1169. if continent_name not in active_device_continent_dict:
  1170. active_device_continent_dict[continent_name] = 0
  1171. active_device_continent_dict[continent_name] += item['count']
  1172. # 设备类型数据
  1173. active_device_type_list = active_device_qs.values('device_type').annotate(
  1174. count=Count('device_type')).order_by('count')
  1175. active_device_type_dict = {}
  1176. for item in active_device_type_list:
  1177. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1178. active_device_type_dict[type_name] = item['count']
  1179. # 云存设备类型数据
  1180. active_device_vod_list = active_device_qs.filter(~Q(cloud_vod=2)).values('device_type').annotate(
  1181. count=Count('device_type')).order_by('count')
  1182. active_device_vod_dict = {}
  1183. for item in active_device_vod_list:
  1184. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1185. active_device_vod_dict[type_name] = item['count']
  1186. # AI设备类型数据
  1187. active_device_ai_list = active_device_qs.filter(~Q(is_ai=2)).values('device_type').annotate(
  1188. count=Count('device_type')).order_by('count')
  1189. active_device_ai_dict = {}
  1190. for item in active_device_ai_list:
  1191. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1192. active_device_ai_dict[type_name] = item['count']
  1193. # 联通设备类型数据
  1194. active_device_unicom_list = active_device_qs.filter(~Q(mobile_4g=2)).values('device_type').annotate(
  1195. count=Count('device_type')).order_by('count')
  1196. active_device_unicom_dict = {}
  1197. for item in active_device_unicom_list:
  1198. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1199. active_device_unicom_dict[type_name] = item['count']
  1200. DeviceInfoSummary.objects.create(time=start_time, count=active_device_count,
  1201. query_type=1, created_time=created_time,
  1202. country=active_device_country_dict,
  1203. continent=active_device_continent_dict,
  1204. vod_service=active_device_vod_dict,
  1205. ai_service=active_device_ai_dict,
  1206. unicom_service=active_device_unicom_dict,
  1207. device_type=active_device_type_dict)
  1208. return response.json(0)
  1209. except Exception as e:
  1210. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1211. @staticmethod
  1212. def collect_flow_info(response):
  1213. try:
  1214. unicom_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('iccid').distinct().order_by('iccid')
  1215. asy = threading.Thread(target=CronCollectDataView.thread_collect_flow, args=(unicom_qs,))
  1216. asy.start()
  1217. return response.json(0)
  1218. except Exception as e:
  1219. return response.json(500, repr(e))
  1220. @staticmethod
  1221. def thread_collect_flow(qs):
  1222. try:
  1223. unicom_api = UnicomObjeect()
  1224. redis_obj = RedisObject()
  1225. for item in qs:
  1226. res = unicom_api.query_device_usage_history(**item)
  1227. if res.status_code == 200:
  1228. res_json = res.json()
  1229. if res_json['code'] == 0:
  1230. redis_dict = {}
  1231. for data in res_json['data']['deviceUsageHistory']:
  1232. year = data.get('year', None)
  1233. month = data.get('month', None)
  1234. flow = data.get('flowTotalUsage', None)
  1235. if not all([year, month, flow]):
  1236. continue
  1237. file = str(year) + '-' + str(month)
  1238. redis_dict[file] = flow
  1239. key = 'monthly_flow_' + item['iccid']
  1240. if redis_dict:
  1241. redis_obj.set_hash_data(key, redis_dict)
  1242. except Exception as e:
  1243. LOGGER.info('统计联通流量失败,时间为:{}'.format(int(time.time())))