CronTaskController.py 70 KB

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