CronTaskController.py 77 KB

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