CronTaskController.py 78 KB

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