CronTaskController.py 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  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 io
  12. import json
  13. import threading
  14. import time
  15. import zipfile
  16. import calendar
  17. import paypalrestsdk
  18. import requests
  19. import csv
  20. import math
  21. from django.db import connection, connections, transaction
  22. from django.db.models import Q, Sum, Count
  23. from django.views import View
  24. from Ansjer.config import USED_SERIAL_REDIS_LIST, UNUSED_SERIAL_REDIS_LIST, CONFIG_INFO, CONFIG_US, \
  25. RESET_REGION_ID_SERIAL_REDIS_LIST, LOGGER, PAYPAL_CRD, CONFIG_EUR, DETECT_PUSH_DOMAINS, ACCESS_KEY_ID, \
  26. SECRET_ACCESS_KEY, REGION_NAME, CONFIG_CN
  27. from Model.models import Device_User, Device_Info, UidSetModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
  28. VodHlsModel, ExperienceContextModel, AiService, VodHlsSummary, VideoPlaybackTimeModel, DeviceUserSummary, \
  29. CountryModel, DeviceTypeModel, OrdersSummary, DeviceInfoSummary, CompanySerialModel, \
  30. CloudLogModel, UidCloudStorageCount, UserExModel, DeviceDomainRegionModel, VodHlsTag, VodHlsTagType, IcloudService, \
  31. Store_Meal, Lang, VodBucketModel, UnicomComboOrderInfo, UnicomDeviceInfo, AbnormalOrder, DailyReconciliation, \
  32. CustomizedPush, UIDCompanySerialModel, UIDModel, LogModel, OperatingCosts, UidBucketStatistics, AppScannedSerial, \
  33. SerialUnbindUID, UidUserModel, UidPushModel, iotdeviceInfoModel, ExperienceAiModel
  34. from Object.AWS.AmazonS3Util import AmazonS3Util
  35. from Object.AWS.S3Email import S3Email
  36. from Object.RedisObject import RedisObject
  37. from Object.ResponseObject import ResponseObject
  38. from Object.utils import LocalDateTimeUtil
  39. from Service.CommonService import CommonService
  40. from Service.EquipmentInfoService import EQUIPMENT_INFO_MODEL_LIST, EquipmentInfoService
  41. from Service.VodHlsService import SplitVodHlsObject
  42. from Object.UnicomObject import UnicomObjeect
  43. from Object.WechatPayObject import WechatPayObject
  44. from Object.AliPayObject import AliPayObject
  45. from dateutil.relativedelta import relativedelta
  46. class CronDelDataView(View):
  47. def get(self, request, *args, **kwargs):
  48. request.encoding = 'utf-8'
  49. operation = kwargs.get('operation')
  50. return self.validation(request.GET, request, operation)
  51. def post(self, request, *args, **kwargs):
  52. request.encoding = 'utf-8'
  53. operation = kwargs.get('operation')
  54. return self.validation(request.POST, request, operation)
  55. def validation(self, request_dict, request, operation):
  56. response = ResponseObject()
  57. if operation == 'delAccessLog': # 定时删除访问接口数据
  58. return self.delAccessLog(response)
  59. elif operation == 'delPushInfo': # 定时删除推送数据
  60. return self.delPushInfo(response)
  61. elif operation == 'delPushInfoV2': # 定时删除推送数据V2
  62. return self.delPushInfoV2(response)
  63. elif operation == 'delSysMsg': # 定时删除系统消息数据
  64. return self.delSysMsg(response)
  65. elif operation == 'delVodHls': # 定时删除云存播放列表
  66. return self.delVodHls(response)
  67. elif operation == 'delCloudLog': # 定时删除云存接口数据
  68. return self.delCloudLog(response)
  69. elif operation == 'delTesterDevice': # 定时删除测试账号下的设备数据
  70. return self.delTesterDevice(response)
  71. elif operation == 'delAppLog': # 定时删除app日志
  72. return self.delAppLog(response)
  73. elif operation == 'delDeviceLog': # 定时删除设备日志
  74. return self.delDeviceLog(response)
  75. elif operation == 'UpdateConfiguration': # 定时更新配置
  76. return self.UpdateConfiguration(response)
  77. elif operation == 'cloud-log':
  78. return self.uid_cloud_storage_upload_count(response)
  79. elif operation == 'delDeviceLog': # 定时删除设备日志
  80. return self.del_device_log(response)
  81. elif operation == 'delCampaignsLogs':
  82. return self.del_campaigns_log(response)
  83. else:
  84. return response.json(404)
  85. @staticmethod
  86. def UpdateConfiguration(response):
  87. """
  88. 定时更新配置
  89. @param response: 响应对象
  90. @return:
  91. """
  92. try:
  93. ucode_list = ['823C01552AA',
  94. '823C01550AA',
  95. '823C01550XA',
  96. '823C01850XA',
  97. '730201350AA',
  98. '730201350AA',
  99. '730201450AA',
  100. '730201450MA',
  101. '72V201252AA',
  102. '72V201253AA',
  103. '72V201353AA',
  104. '72V201354AA',
  105. '72V201355AA',
  106. '72V201254AA',
  107. 'V82301850AA',
  108. 'V82301850XA',
  109. '72V201257AA', '72V201256AA']
  110. UidSetModel.objects.filter(ucode__in=ucode_list, is_human=0).update(is_human=1)
  111. ucode_list = ['72V201257AA', '72V201254AA'] # 4G规格码
  112. UidSetModel.objects.filter(ucode__in=ucode_list, mobile_4g=0).update(mobile_4g=1)
  113. # 根据设备规格码定时更新默认算法类型类型
  114. ucode_list = ['823C01552AA', '823C01550AA', '823C01550XA', 'C18201550KA',
  115. '823C01550TA', '823C01550VA', '823C01850XA', 'C18201850KA',
  116. '823C01850TA', '823C01850VA', 'C22501850VA']
  117. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=47)
  118. ucode_list = ['730201350AA', '730201450AA', '730201450MA', '730201450NA']
  119. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=7)
  120. ucode_list = ['V82301850AA', 'V82301850XA']
  121. UidSetModel.objects.filter(ucode__in=ucode_list, ai_type=0).update(ai_type=2031)
  122. # 根据设备规格码更新默认个性化语音值
  123. ucode_list = ['823C01552AA', '823C01550XA', 'C18201550KA', '823C01550TA',
  124. '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', '823C01850VA',
  125. '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA',
  126. '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA', 'C22501850VA',
  127. 'V82301850AA', 'V82301850XA', '72V201257AA', '72V201256AA']
  128. UidSetModel.objects.filter(ucode__in=ucode_list, is_custom_voice=0).update(is_custom_voice=1)
  129. # 根据设备规格码更新is_ai
  130. ucode_list = ['823C01552AA', '823C01550XA', 'C18201550KA', '823C01550TA',
  131. '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', '823C01850VA',
  132. '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA',
  133. '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA', 'C22501850VA',
  134. 'V82301850AA', 'V82301850XA', '72V201257AA', '72V201256AA', '730201350AA']
  135. UidSetModel.objects.filter(ucode__in=ucode_list, is_ai=2).update(is_ai=1)
  136. # 根据设备规格码更新alexa
  137. ucode_list = ['823C01552AA', '823C01550AA', '823C01550XA', '522001352AA',
  138. '823C01550TA', '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA',
  139. 'C22501850VA', 'V82301850AA', 'V82301850XA', '730201350AA', '72V201252AA',
  140. '72V201253AA', '72V201353AA', '72V201354AA', '72V201355AA', '72V201256AA']
  141. UidSetModel.objects.filter(ucode__in=ucode_list, is_alexa=0).update(is_alexa=1)
  142. # 根据ai类型和设备类型修改516 type
  143. uid_list = UidSetModel.objects.filter(ai_type=18563).values_list('uid')
  144. Device_Info.objects.filter(Type=10, UID__in=uid_list).update(Type=24)
  145. return response.json(0)
  146. except Exception as e:
  147. LOGGER.info('UpdateConfiguration异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  148. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  149. @staticmethod
  150. def delAppLog(response):
  151. """
  152. 定时删除app日志
  153. @param response: 响应对象
  154. @return:
  155. """
  156. nowTime = int(time.time())
  157. try:
  158. cursor = connection.cursor()
  159. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  160. sql = 'DELETE FROM `app_log` WHERE add_time<{}'.format(month_ago_time)
  161. cursor.execute(sql)
  162. cursor.close()
  163. return response.json(0)
  164. except Exception as e:
  165. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  166. @staticmethod
  167. def delDeviceLog(response):
  168. """
  169. 定时删除设备日志
  170. @param response: 响应对象
  171. @return:
  172. """
  173. nowTime = int(time.time())
  174. size = 5000
  175. try:
  176. cursor = connection.cursor()
  177. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  178. month_ago_time_str = CommonService.timestamp_to_str(month_ago_time)
  179. sql = "DELETE FROM `device_log` WHERE add_time<'{}' LIMIT {}".format(month_ago_time_str, size)
  180. cursor.execute(sql)
  181. cursor.close()
  182. return response.json(0)
  183. except Exception as e:
  184. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  185. @staticmethod
  186. def uid_cloud_storage_upload_count(response):
  187. try:
  188. now_time = int(time.time())
  189. local_time = LocalDateTimeUtil.get_before_days_timestamp(now_time)
  190. format_str = '%Y-%m-%d'
  191. date_str = LocalDateTimeUtil.time_stamp_to_time(local_time, format_str)
  192. start_time, end_time = LocalDateTimeUtil.get_start_and_end_time(date_str, format_str)
  193. cs_uid_qs = UID_Bucket.objects.filter(addTime__gte=int(1669824000)).values('uid')
  194. if not cs_uid_qs.exists():
  195. return response.json(0)
  196. for item in cs_uid_qs:
  197. uid = item['uid']
  198. cloud_log_qs = CloudLogModel.objects.filter(uid=uid, operation=r'cloudstorage/storeplaylist',
  199. time__gte=start_time, time__lte=end_time)
  200. cloud_log_qs = cloud_log_qs.values('uid')[0:1]
  201. if not cloud_log_qs.exists():
  202. continue
  203. count_data = {'uid': uid, 'count': cloud_log_qs.count(), 'created_time': end_time,
  204. 'updated_time': end_time}
  205. UidCloudStorageCount.objects.create(**count_data)
  206. return response.json(0)
  207. except Exception as e:
  208. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  209. return response.json(500)
  210. @staticmethod
  211. def delAccessLog(response):
  212. try:
  213. cursor = connection.cursor()
  214. # 删除7天前的数据
  215. last_week = LocalDateTimeUtil.get_last_week()
  216. sql = 'DELETE FROM access_log WHERE time < %s limit %s'
  217. cursor.execute(sql, [last_week, 10000])
  218. # 关闭游标
  219. cursor.close()
  220. connection.close()
  221. return response.json(0)
  222. except Exception as e:
  223. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  224. @classmethod
  225. def delPushInfo(cls, response):
  226. now_time = int(time.time())
  227. try:
  228. # 当前时间转日期
  229. local_date_now = str(datetime.datetime.fromtimestamp(int(now_time)).date())
  230. # 根据日期获取周几
  231. week_val = LocalDateTimeUtil.date_to_week(local_date_now)
  232. # 根据当前时间获取7天前时间戳
  233. expiration_time = LocalDateTimeUtil.get_before_days_timestamp(now_time, 7)
  234. # 异步删除推送消息
  235. kwargs = {
  236. 'week_val': week_val,
  237. 'expiration_time': expiration_time
  238. }
  239. del_push_info_thread = threading.Thread(
  240. target=cls.del_push_info_data,
  241. kwargs=kwargs)
  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(**kwargs):
  248. cursor = connections['mysql02'].cursor()
  249. # 获取删除星期列表
  250. week_val = kwargs['week_val']
  251. del_week_val_list = [i for i in range(1, 8)]
  252. # 移除当天和前后两天
  253. del_week_val_list.remove(week_val)
  254. if week_val == 1:
  255. pre_week_val = 7
  256. else:
  257. pre_week_val = week_val - 1
  258. del_week_val_list.remove(pre_week_val)
  259. if week_val == 7:
  260. nex_week_val = 1
  261. else:
  262. nex_week_val = week_val + 1
  263. del_week_val_list.remove(nex_week_val)
  264. expiration_time = kwargs['expiration_time']
  265. # 每次删除条数
  266. size = 5000
  267. # 删除7天前的数据
  268. sql = "DELETE FROM equipment_info WHERE addTime<= %s LIMIT %s "
  269. cursor.execute(sql, [expiration_time, size])
  270. for week_val in del_week_val_list:
  271. if week_val == 1:
  272. sql = "DELETE FROM equipment_info_monday WHERE add_time<= %s LIMIT %s "
  273. if week_val == 2:
  274. sql = "DELETE FROM equipment_info_tuesday WHERE add_time<= %s LIMIT %s "
  275. if week_val == 3:
  276. sql = "DELETE FROM equipment_info_wednesday WHERE add_time<= %s LIMIT %s "
  277. if week_val == 4:
  278. sql = "DELETE FROM equipment_info_thursday WHERE add_time<= %s LIMIT %s "
  279. if week_val == 5:
  280. sql = "DELETE FROM equipment_info_friday WHERE add_time<= %s LIMIT %s "
  281. if week_val == 6:
  282. sql = "DELETE FROM equipment_info_saturday WHERE add_time<= %s LIMIT %s "
  283. if week_val == 7:
  284. sql = "DELETE FROM equipment_info_sunday WHERE add_time<= %s LIMIT %s "
  285. cursor.execute(sql, [expiration_time, size])
  286. # 关闭游标
  287. cursor.close()
  288. @classmethod
  289. def delPushInfoV2(cls, response):
  290. try:
  291. del_push_info_thread = threading.Thread(
  292. target=cls.del_push_info_data_v2)
  293. del_push_info_thread.start()
  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 delSysMsg(response):
  299. try:
  300. cursor = connections['mysql02'].cursor()
  301. # 获取90天前时间戳
  302. now_time = int(time.time())
  303. expiration_time = LocalDateTimeUtil.get_before_days_timestamp(now_time, 90)
  304. # 每次删除条数
  305. size = 5000
  306. sql = "DELETE FROM sys_msg WHERE addTime< %s LIMIT %s "
  307. cursor.execute(sql, [expiration_time, size])
  308. # 关闭游标
  309. cursor.close()
  310. return response.json(0)
  311. except Exception as e:
  312. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  313. @staticmethod
  314. def del_push_info_data_v2():
  315. cursor = connections['mysql02'].cursor()
  316. # 获取7天前时间戳
  317. now_time = int(time.time())
  318. expiration_time = LocalDateTimeUtil.get_before_days_timestamp(now_time, 7)
  319. # 每次删除条数
  320. size = 5000
  321. for i in range(1, len(EQUIPMENT_INFO_MODEL_LIST) + 1):
  322. sql = "DELETE FROM equipment_info_{} WHERE add_time< %s LIMIT %s ".format(i)
  323. cursor.execute(sql, [expiration_time, size])
  324. # 关闭游标
  325. cursor.close()
  326. @staticmethod
  327. def delVodHls(response):
  328. nowTime = int(time.time())
  329. try:
  330. CronDelDataView.del_vod_hls_tag()
  331. cursor = connection.cursor()
  332. month_ago_time = nowTime - 3 * 30 * 24 * 60 * 60 # 删除3个月前的数据
  333. sql = 'DELETE FROM `vod_hls` WHERE endTime<{} LIMIT 50000'.format(month_ago_time)
  334. cursor.execute(sql)
  335. cursor.close()
  336. # 删除vod_hls分表数据
  337. split_vod_hls_obj = SplitVodHlsObject()
  338. split_vod_hls_obj.del_vod_hls_data(end_time__lt=month_ago_time)
  339. return response.json(0)
  340. except Exception as e:
  341. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  342. @staticmethod
  343. def del_vod_hls_tag():
  344. """
  345. 删除AI标签记录
  346. """
  347. e_time = LocalDateTimeUtil.get_before_days_timestamp(int(time.time()), 30)
  348. VodHlsTagType.objects.filter(created_time__lt=e_time).delete()
  349. VodHlsTag.objects.filter(created_time__lt=e_time).delete()
  350. @staticmethod
  351. def delCloudLog(response):
  352. nowTime = int(time.time())
  353. cursor = connection.cursor()
  354. try:
  355. # 删除3个月前的数据
  356. sql = "DELETE FROM `cloud_log` WHERE time<={} LIMIT 50000".format(
  357. nowTime - 3 * 30 * 24 * 60 * 60)
  358. cursor.execute(sql)
  359. # 关闭游标
  360. cursor.close()
  361. return response.json(0)
  362. except Exception as e:
  363. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  364. @staticmethod
  365. def delTesterDevice(response):
  366. try:
  367. userID_list = [
  368. 'tech01@ansjer.com',
  369. 'tech02@ansjer.com',
  370. 'tech03@ansjer.com',
  371. 'tech04@ansjer.com',
  372. 'tech05@ansjer.com',
  373. 'tech06@ansjer.com',
  374. 'tech07@ansjer.com',
  375. 'tech08@ansjer.com',
  376. 'tech09@ansjer.com',
  377. 'tech10@ansjer.com',
  378. 'fix01@ansjer.com',
  379. 'fix02@ansjer.com',
  380. 'fix03@ansjer.com',
  381. 'fix04@ansjer.com',
  382. 'fix05@ansjer.com']
  383. device_user = Device_User.objects.filter(username__in=userID_list)
  384. device_info_qs = Device_Info.objects.filter(
  385. userID__in=device_user).values('UID')
  386. uid_list = []
  387. for device_info in device_info_qs:
  388. uid_list.append(device_info['UID'])
  389. with transaction.atomic():
  390. # 删除设备云存相关数据
  391. UidSetModel.objects.filter(uid__in=uid_list).delete()
  392. UID_Bucket.objects.filter(uid__in=uid_list).delete()
  393. Unused_Uid_Meal.objects.filter(uid__in=uid_list).delete()
  394. # Order_Model.objects.filter(UID__in=uid_list).delete()
  395. StsCrdModel.objects.filter(uid__in=uid_list).delete()
  396. VodHlsModel.objects.filter(uid__in=uid_list).delete()
  397. # 删除vod_hls分表数据
  398. split_vod_hls_obj = SplitVodHlsObject()
  399. split_vod_hls_obj.del_vod_hls_data(uid__in=uid_list)
  400. ExperienceContextModel.objects.filter(uid__in=uid_list).delete()
  401. Device_Info.objects.filter(userID__in=device_user).delete()
  402. return response.json(0)
  403. except Exception as e:
  404. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  405. @staticmethod
  406. def del_device_log(response):
  407. """
  408. 定时删除设备日志
  409. @param response: 响应对象
  410. @return:
  411. """
  412. nowTime = int(time.time())
  413. try:
  414. cursor = connection.cursor()
  415. month_ago_time = nowTime - 30 * 24 * 60 * 60 # 保留近30天的数据
  416. sql = 'DELETE FROM `device_log` WHERE unix_timestamp(add_time)<{}'.format(month_ago_time)
  417. cursor.execute(sql)
  418. cursor.close()
  419. return response.json(0)
  420. except Exception as e:
  421. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  422. @staticmethod
  423. def del_campaigns_log(response):
  424. """
  425. 定时删除广告日志
  426. @param response: 响应对象
  427. @return:
  428. """
  429. nowTime = int(time.time())
  430. try:
  431. cursor = connection.cursor()
  432. month_ago_time = nowTime - 90 * 24 * 60 * 60 # 保留近90天的数据
  433. sql = f'DELETE FROM `open_screen_campaign` WHERE update_time<{month_ago_time}'
  434. cursor.execute(sql)
  435. cursor.close()
  436. return response.json(0)
  437. except Exception as e:
  438. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  439. class CronUpdateDataView(View):
  440. def get(self, request, *args, **kwargs):
  441. request.encoding = 'utf-8'
  442. operation = kwargs.get('operation')
  443. return self.validation(request.GET, request, operation)
  444. def post(self, request, *args, **kwargs):
  445. request.encoding = 'utf-8'
  446. operation = kwargs.get('operation')
  447. return self.validation(request.POST, request, operation)
  448. def validation(self, request_dict, request, operation):
  449. response = ResponseObject()
  450. if operation == 'updateUnusedUidBucket': # 定时更新过期云存关联的未使用套餐状态
  451. return self.updateUnusedUidBucket(response)
  452. elif operation == 'updateUnusedAiService': # 定时更新过期ai关联的未使用套餐状态
  453. return self.updateUnusedAiService(response)
  454. elif operation == 'updateIcloudService': # 定时更新过期云盘套餐使用状态
  455. return self.updateIcloudService(response)
  456. elif operation == 'reqUpdateSerialStatus': # 定时请求更新序列号状态
  457. return self.reqUpdateSerialStatus(response)
  458. elif operation == 'updateSerialStatus': # 更新序列号状态
  459. return self.updateSerialStatus(request_dict, response)
  460. elif operation == 'deleteUidData': # 清除uid数据
  461. return self.deleteUidData(request_dict, response)
  462. elif operation == 'reset-region-id': # 重置地区id
  463. return self.reset_region_id(request_dict, response)
  464. elif operation == 'updateVodMeal': # 定时修改体验套餐有效期为1个月
  465. return self.update_vod_meal(request_dict, response)
  466. elif operation == 'checkCustomizedPush': # 定时检查定制化推送,重新执行没有推送成功的请求
  467. return self.check_customized_push(response)
  468. else:
  469. return response.json(404)
  470. @staticmethod
  471. def updateUnusedUidBucket(response):
  472. """
  473. 监控云存套餐过期修改状态
  474. @param response:
  475. @return:
  476. """
  477. # 定时更新已过期套餐修改状态为2
  478. now_time = int(time.time())
  479. expired_uid_bucket = UID_Bucket.objects.filter(endTime__lte=now_time)
  480. expired_uid_bucket = expired_uid_bucket.filter(~Q(use_status=2)).values('id')
  481. if expired_uid_bucket.exists():
  482. expired_uid_bucket.update(use_status=2)
  483. # 监控有未使用套餐则自动生效
  484. expired_uid_buckets = UID_Bucket.objects.filter(endTime__lte=now_time, has_unused=1).values("id", "uid")[0:1000]
  485. for expired_uid_bucket in expired_uid_buckets:
  486. unuseds = Unused_Uid_Meal.objects.filter(
  487. uid=expired_uid_bucket['uid']).values(
  488. "id",
  489. "uid",
  490. "channel",
  491. "addTime",
  492. "expire",
  493. "is_ai",
  494. "bucket_id",
  495. "order_id").order_by('addTime')
  496. if not unuseds.exists():
  497. continue
  498. unused = unuseds[0]
  499. try:
  500. with transaction.atomic():
  501. count_unused = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).count()
  502. has_unused = 1 if count_unused > 1 else 0
  503. end_time = CommonService.calcMonthLater(unused['expire'])
  504. UID_Bucket.objects.filter(
  505. uid=expired_uid_bucket['uid']).update(
  506. channel=unused['channel'],
  507. endTime=end_time,
  508. bucket_id=unused['bucket_id'],
  509. updateTime=now_time,
  510. use_status=1,
  511. has_unused=has_unused,
  512. orderId=unused['order_id'])
  513. if unused['is_ai']:
  514. ai_service = AiService.objects.filter(uid=expired_uid_bucket['uid'], channel=unused['channel'])
  515. if ai_service.exists():
  516. ai_service.update(updTime=now_time, use_status=1, orders_id=unused['order_id'],
  517. endTime=end_time)
  518. else:
  519. AiService.objects.create(uid=expired_uid_bucket['uid'], channel=unused['channel'],
  520. detect_status=1, addTime=now_time, orders_id=unused['order_id'],
  521. updTime=now_time, endTime=end_time, use_status=1)
  522. Unused_Uid_Meal.objects.filter(id=unused['id']).delete()
  523. StsCrdModel.objects.filter(uid=expired_uid_bucket['uid']).delete() # 删除sts记录
  524. except Exception as e:
  525. print(repr(e))
  526. continue
  527. return response.json(0)
  528. @staticmethod
  529. def updateUnusedAiService(response):
  530. now_time = int(time.time())
  531. ai_service_qs = AiService.objects.filter(
  532. endTime__lte=now_time,
  533. use_status=1).values(
  534. 'id',
  535. 'uid')[
  536. 0:200]
  537. for ai_service in ai_service_qs:
  538. try:
  539. with transaction.atomic():
  540. AiService.objects.filter(
  541. id=ai_service['id']).update(
  542. use_status=2) # 更新过期ai订单状态
  543. # 如果存在未使用套餐,更新为使用
  544. unused_ai_service = AiService.objects.filter(
  545. uid=ai_service['uid'],
  546. use_status=0).order_by('addTime')[
  547. :1].values(
  548. 'id',
  549. 'endTime')
  550. if unused_ai_service.exists():
  551. # 未使用套餐的endTime在购买的时候保存为有效时间
  552. effective_day = unused_ai_service[0]['endTime']
  553. endTime = now_time + effective_day
  554. AiService.objects.filter(
  555. id=unused_ai_service[0]['id']).update(
  556. use_status=1, endTime=endTime, updTime=now_time)
  557. except Exception:
  558. continue
  559. return response.json(0)
  560. @staticmethod
  561. def updateIcloudService(response):
  562. """
  563. 监控云盘套餐过期修改状态
  564. @param response:
  565. @return:
  566. """
  567. # 定时更新已过期套餐修改状态为2
  568. now_time = int(time.time())
  569. try:
  570. IcloudService.objects.filter(Q(end_time__lte=now_time), ~Q(end_time=0),
  571. ~Q(use_status=1)).update(use_status=1)
  572. return response.json(0)
  573. except Exception as e:
  574. return response.json(500)
  575. @classmethod
  576. def reqUpdateSerialStatus(cls, response):
  577. redis_obj = RedisObject()
  578. # 更新已使用序列号其他服务器的状态
  579. used_serial_redis_list = redis_obj.lrange(USED_SERIAL_REDIS_LIST, 0, -1) # 读取redis已使用序列号
  580. if used_serial_redis_list:
  581. LOGGER.info('---请求更新已使用序列号列表---used_serial_redis_list:{}'.format(used_serial_redis_list))
  582. used_serial_redis_list = [str(i, 'utf-8') for i in used_serial_redis_list]
  583. cls.do_request_function(used_serial_redis_list, 3)
  584. # 更新未使用序列号其他服务器的状态
  585. unused_serial_redis_list = redis_obj.lrange(UNUSED_SERIAL_REDIS_LIST, 0, -1) # 读取redis未使用序列号
  586. if unused_serial_redis_list:
  587. LOGGER.info('---请求更新未使用序列号列表---unused_serial_redis_list:{}'.format(unused_serial_redis_list))
  588. unused_serial_redis_list = [str(i, 'utf-8') for i in unused_serial_redis_list]
  589. cls.do_request_function(unused_serial_redis_list, 1)
  590. # 重置地区id
  591. reset_region_id_serial_redis_list = redis_obj.lrange(RESET_REGION_ID_SERIAL_REDIS_LIST, 0, -1) # 读取redis未使用序列号
  592. if reset_region_id_serial_redis_list:
  593. LOGGER.info('---请求重置地区id的序列号列表---:{}'.format(reset_region_id_serial_redis_list))
  594. reset_region_id_serial_redis_list = [str(i, 'utf-8') for i in reset_region_id_serial_redis_list]
  595. cls.do_request_reset_region_id(reset_region_id_serial_redis_list)
  596. return response.json(0)
  597. @staticmethod
  598. def do_request_function(serial_redis_list, status):
  599. """
  600. 请求更新序列号状态
  601. @param serial_redis_list: 序列号redis列表
  602. @param status: 状态, 1: 未使用, 3: 已占用
  603. """
  604. data = {
  605. 'serial_redis_list': str(serial_redis_list),
  606. 'status': status
  607. }
  608. # 确认域名列表
  609. orders_domain_name_list = CommonService.get_orders_domain_name_list()
  610. redis_obj = RedisObject()
  611. LOGGER.info('---请求更新序列号线程---data:{},orders_domain_name_list:{}'.format(data, orders_domain_name_list))
  612. try:
  613. requests_failed_flag = False # 请求失败标志位
  614. for domain_name in orders_domain_name_list:
  615. url = '{}cron/update/updateSerialStatus'.format(domain_name)
  616. response = requests.post(url=url, data=data, timeout=5)
  617. LOGGER.info('---请求更新序列号响应时间---:{}'.format(response.elapsed.total_seconds()))
  618. result = response.json()
  619. if result['result_code'] != 0: # 请求失败标志位置位
  620. requests_failed_flag = True
  621. break
  622. # 状态为未使用,重置扫码记录和美洲服的地区id
  623. if status == 1:
  624. # 扫码记录
  625. AppScannedSerial.objects.filter(serial__in=serial_redis_list).delete()
  626. # 地区id
  627. # 美洲服直接更新
  628. if CONFIG_INFO == CONFIG_US:
  629. DeviceDomainRegionModel.objects.filter(~Q(region_id=0), serial_number__in=serial_redis_list). \
  630. update(region_id=0)
  631. # 其他服请求到美洲服更新
  632. else:
  633. req_url = 'https://www.dvema.com/cron/update/reset-region-id'
  634. req_data = {
  635. 'serial_redis_list': str(serial_redis_list)
  636. }
  637. response = requests.post(url=req_url, data=req_data, timeout=5)
  638. LOGGER.info('---请求重置地区id响应时间---:{}'.format(response.elapsed.total_seconds()))
  639. result = response.json()
  640. if result['result_code'] != 0: # 请求失败标志位置位
  641. requests_failed_flag = True
  642. break
  643. if not requests_failed_flag: # 请求成功删除redis序列号
  644. if status == 1:
  645. for i in serial_redis_list:
  646. redis_obj.lrem(UNUSED_SERIAL_REDIS_LIST, 0, i)
  647. elif status == 3:
  648. for i in serial_redis_list:
  649. redis_obj.lrem(USED_SERIAL_REDIS_LIST, 0, i)
  650. except Exception as e:
  651. LOGGER.info('---更新序列号状态异常---:{}'.format(repr(e)))
  652. @staticmethod
  653. def do_request_reset_region_id(reset_region_id_serial_redis_list):
  654. """
  655. 请求重置地区id
  656. @param reset_region_id_serial_redis_list: 序列号redis列表
  657. """
  658. redis_obj = RedisObject()
  659. requests_failed_flag = False # 请求失败标志位
  660. data = {
  661. 'serial_redis_list': str(reset_region_id_serial_redis_list),
  662. }
  663. url = 'https://www.dvema.com/cron/update/reset-region-id'
  664. try:
  665. response = requests.post(url=url, data=data, timeout=5)
  666. result = response.json()
  667. if result['result_code'] != 0: # 请求失败标志位置位
  668. requests_failed_flag = True
  669. if not requests_failed_flag: # 请求成功删除redis序列号
  670. for serial in reset_region_id_serial_redis_list:
  671. redis_obj.lrem(RESET_REGION_ID_SERIAL_REDIS_LIST, 0, serial)
  672. except Exception as e:
  673. LOGGER.info('---请求重置地区id异常---:{}'.format(repr(e)))
  674. @staticmethod
  675. def updateSerialStatus(request_dict, response):
  676. """
  677. 更新序列号状态
  678. @param request_dict: 请求参数
  679. @request_dict serial_redis_list: 序列号redis列表
  680. @request_dict status: 状态, 1: 未使用, 3: 已占用
  681. @param response: 响应对象
  682. """
  683. serial_redis_list = request_dict.get('serial_redis_list', None)
  684. status = request_dict.get('status', None)
  685. LOGGER.info('---更新序列号状态参数---serial_redis_list:{},status:{}'.format(serial_redis_list, status))
  686. if not all([serial_redis_list, status]):
  687. return response.json(444)
  688. now_time = int(time.time())
  689. try:
  690. serial_redis_list = eval(serial_redis_list)
  691. CompanySerialModel.objects.filter(serial_number__in=serial_redis_list).update(status=int(status),
  692. update_time=now_time)
  693. uid_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number__in=serial_redis_list)
  694. if uid_serial_qs:
  695. uid_list = list(uid_serial_qs.values_list('uid__uid', flat=True))
  696. serial_list = list(uid_serial_qs.values_list('company_serial__serial_number', flat=True))
  697. UIDModel.objects.filter(uid__in=uid_list).update(status=3, mac='', update_time=now_time)
  698. uid_serial_qs.delete()
  699. # 记录操作日志
  700. content = json.loads(json.dumps(request_dict))
  701. log = {
  702. 'ip': '127.0.0.1',
  703. 'user_id': 1,
  704. 'status': 200,
  705. 'time': now_time,
  706. 'content': json.dumps(content),
  707. 'url': 'cron/update/updateSerialStatus',
  708. 'operation': '序列号{}解绑uid: {}'.format(serial_list, uid_list),
  709. }
  710. LogModel.objects.create(**log)
  711. return response.json(0)
  712. except Exception as e:
  713. LOGGER.info('---更新序列号状态异常---:{}'.format(repr(e)))
  714. return response.json(500)
  715. @staticmethod
  716. def deleteUidData(request_dict, response):
  717. """
  718. 清除uid数据
  719. @param request_dict: 请求参数
  720. @request_dict serial_redis_list: 序列号redis列表
  721. @param response: 响应对象
  722. """
  723. serial_unbind_uid_qs = SerialUnbindUID.objects.filter(status=0).values('serial', 'uid')
  724. # 没有需要清除的数据直接返回
  725. if not serial_unbind_uid_qs.exists():
  726. return response.json(0)
  727. # 获取序列号,uid列表
  728. serial_list, uid_list = [], []
  729. for serial_unbind_uid in serial_unbind_uid_qs:
  730. serial_list.append(serial_unbind_uid['serial'])
  731. uid_list.append(serial_unbind_uid['uid'])
  732. now_time = int(time.time())
  733. redis_obj = RedisObject()
  734. try:
  735. with transaction.atomic():
  736. # 更新序列号解绑uid表状态
  737. serial_unbind_uid_qs.update(status=1, updated_time=now_time)
  738. # 更新序列号状态
  739. CompanySerialModel.objects.filter(serial_number__in=serial_list).update(status=1, update_time=now_time)
  740. UIDCompanySerialModel.objects.filter(company_serial__serial_number__in=serial_list).delete()
  741. # 删除设备相关数据,参考后台的设备重置删除的数据
  742. Device_Info.objects.filter(UID__in=uid_list).delete()
  743. UidSetModel.objects.filter(uid__in=uid_list).delete()
  744. UidUserModel.objects.filter(UID__in=uid_list).delete()
  745. UidPushModel.objects.filter(uid_set__uid__in=uid_list).delete()
  746. iotdeviceInfoModel.objects.filter(serial_number__in=serial_list).delete()
  747. # 删除推送消息
  748. EquipmentInfoService.delete_all_equipment_info(device_uid__in=uid_list)
  749. # 重置设备云存
  750. UID_Bucket.objects.filter(uid__in=uid_list).delete()
  751. Unused_Uid_Meal.objects.filter(uid__in=uid_list).delete()
  752. # Order_Model.objects.filter(UID__in=uid_list).delete()
  753. StsCrdModel.objects.filter(uid__in=uid_list).delete()
  754. VodHlsModel.objects.filter(uid__in=uid_list).delete()
  755. # 删除vod_hls分表数据
  756. split_vod_hls_obj = SplitVodHlsObject()
  757. split_vod_hls_obj.del_vod_hls_data(uid__in=uid_list)
  758. ExperienceContextModel.objects.filter(uid__in=uid_list).delete()
  759. # 重置AI
  760. ExperienceAiModel.objects.filter(uid__in=uid_list).delete()
  761. AiService.objects.filter(uid__in=uid_list).delete()
  762. # 写入未使用序列号redis列表
  763. redis_obj.rpush_list(UNUSED_SERIAL_REDIS_LIST, serial_list)
  764. # 重置region_id,不为美洲服,则写入redis列表
  765. if CONFIG_INFO == CONFIG_US:
  766. DeviceDomainRegionModel.objects.filter(serial_number__in=serial_list).update(region_id=0)
  767. else:
  768. redis_obj.rpush_list(RESET_REGION_ID_SERIAL_REDIS_LIST, serial_list)
  769. # 重置已使用的uid的使用状态为未使用,更新时间
  770. UIDModel.objects.filter(uid__in=uid_list, status=2).update(status=0, mac='', update_time=now_time)
  771. # 重置扫码记录
  772. AppScannedSerial.objects.filter(serial__in=serial_list).delete()
  773. # 记录操作日志
  774. end_time = int(time.time())
  775. log = {
  776. 'user_id': 1,
  777. 'status': 200,
  778. 'time': now_time,
  779. 'url': 'cron/update/deleteUidData',
  780. 'operation': '已解绑序列号{}清除uid{}成功,执行时间{}秒'.format(serial_list, uid_list, end_time-now_time)
  781. }
  782. LogModel.objects.create(**log)
  783. return response.json(0)
  784. except Exception as e:
  785. # 记录操作日志
  786. log = {
  787. 'user_id': 1,
  788. 'status': 200,
  789. 'time': now_time,
  790. 'url': 'cron/update/deleteUidData',
  791. 'operation': '已解绑序列号{}清除uid{}异常:{}'.format(serial_list, uid_list, repr(e))
  792. }
  793. LogModel.objects.create(**log)
  794. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  795. @staticmethod
  796. def reset_region_id(request_dict, response):
  797. """
  798. 重置地区id
  799. @param request_dict: 请求参数
  800. @request_dict serial_redis_list: 序列号redis列表
  801. @param response: 响应对象
  802. """
  803. serial_redis_list = request_dict.get('serial_redis_list', None)
  804. LOGGER.info('---重置地区id参数---serial_redis_list:{}'.format(serial_redis_list))
  805. if not serial_redis_list:
  806. return response.json(444)
  807. try:
  808. serial_redis_list = eval(serial_redis_list)
  809. DeviceDomainRegionModel.objects.filter(serial_number__in=serial_redis_list).update(region_id=0)
  810. return response.json(0)
  811. except Exception as e:
  812. LOGGER.info('---重置地区id异常---:{}'.format(repr(e)))
  813. return response.json(500)
  814. @staticmethod
  815. def update_vod_meal(request_dict, response):
  816. """
  817. 定时修改体验套餐有效期为1个月
  818. @param request_dict: 请求参数
  819. @param response: 响应对象
  820. """
  821. try:
  822. Store_Meal.objects.filter(is_show=0, expire=12, pixel_level=0).update(price='39.99',
  823. virtual_price='56.6',
  824. sort=1)
  825. Store_Meal.objects.filter(is_show=0, cycle_config_id=1, pixel_level=0).update(price='3.65',
  826. virtual_price='5.66',
  827. sort=2)
  828. Store_Meal.objects.filter(id=12).update(price='3.99', virtual_price='5.66', sort=3)
  829. Store_Meal.objects.filter(id__in=(16, 17, 18)).update(is_show=0)
  830. return response.json(0)
  831. except Exception as e:
  832. LOGGER.info('---修改云存套餐内容异常---:{}'.format(repr(e)))
  833. return response.json(500)
  834. @staticmethod
  835. def check_customized_push(response):
  836. try:
  837. now_time = int(time.time())
  838. # 查询推送时间小于当前时间且推送状态为待推送的数据
  839. customized_push_qs = CustomizedPush.objects.filter(push_timestamp__lt=now_time, push_satus=0).values('id')
  840. if customized_push_qs.exists():
  841. for customized_push in customized_push_qs:
  842. customized_push_id = customized_push['id']
  843. data = {'customized_push_id': customized_push_id}
  844. url = DETECT_PUSH_DOMAINS + 'customized_push/start'
  845. req = requests.post(url=url, data=data, timeout=8)
  846. return response.json(0)
  847. except Exception as e:
  848. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  849. class CronCollectDataView(View):
  850. def get(self, request, *args, **kwargs):
  851. request.encoding = 'utf-8'
  852. operation = kwargs.get('operation')
  853. return self.validation(request.GET, request, operation)
  854. def post(self, request, *args, **kwargs):
  855. request.encoding = 'utf-8'
  856. operation = kwargs.get('operation')
  857. return self.validation(request.POST, request, operation)
  858. def validation(self, request_dict, request, operation):
  859. response = ResponseObject()
  860. if operation == 'collectPlayBack': # 定时保存云存视频回放
  861. return self.collect_play_back(response)
  862. elif operation == 'collectDeviceUser': # 定时保存用户数据
  863. return self.collect_device_user(response)
  864. elif operation == 'collectActivityUser': # 定时保存用户数据
  865. return self.collect_activity_user(response)
  866. elif operation == 'collectOrder': # 定时保存订单数据
  867. return self.collect_order(response)
  868. elif operation == 'collectIcloudOrder': # 定时保存云盘订单数据
  869. return self.collect_icloud_order(response)
  870. elif operation == 'collectDeviceInfo': # 定时保存设备数据
  871. return self.collect_device_info(response)
  872. elif operation == 'collectFlowInfo': # 定时保存设备数据
  873. return self.collect_flow_info(response)
  874. elif operation == 'collectOperatingCosts': # 定时运营成本
  875. return self.collect_operating_costs(response)
  876. elif operation == 'collectObjSize': # 定时设备s3存储量
  877. return self.collect_obj_size(response)
  878. elif operation == 'checkRequest': # 定时检查各个服的https请求
  879. return self.check_request(response)
  880. else:
  881. return response.json(404)
  882. @staticmethod
  883. def collect_play_back(response):
  884. try:
  885. now_time = int(time.time())
  886. today = datetime.datetime.today()
  887. start_time = datetime.datetime(today.year, today.month, today.day)
  888. end_time = start_time + datetime.timedelta(days=1)
  889. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  890. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  891. this_month_str = datetime.datetime(today.year, today.month, 1)
  892. this_month_stamp = CommonService.str_to_timestamp(this_month_str.strftime('%Y-%m-%d %H:%M:%S'))
  893. video_play_back_time_qs = VideoPlaybackTimeModel.objects.filter(startTime__gte=start_time,
  894. startTime__lt=end_time,
  895. playMode='cloud').values('uid').annotate(
  896. play_duration=Sum('duration'), play_frequency=Count('uid'))
  897. with transaction.atomic():
  898. for item in video_play_back_time_qs:
  899. vod_hls_summary_qs = VodHlsSummary.objects.filter(uid=item['uid'], time=this_month_stamp)
  900. if vod_hls_summary_qs.exists():
  901. vod_hls_summary = vod_hls_summary_qs.first()
  902. vod_hls_summary.play_duration += item['play_duration']
  903. vod_hls_summary.play_frequency += 1
  904. vod_hls_summary.updated_time = now_time
  905. vod_hls_summary.save()
  906. else:
  907. VodHlsSummary.objects.create(uid=item['uid'], time=this_month_stamp, created_time=now_time,
  908. play_duration=item['play_duration'], play_frequency=1,
  909. updated_time=now_time)
  910. return response.json(0)
  911. except Exception as e:
  912. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  913. @staticmethod
  914. def collect_device_user(response):
  915. try:
  916. created_time = int(time.time())
  917. today = datetime.datetime.today()
  918. start_time = datetime.datetime(today.year, today.month, today.day)
  919. end_time = start_time + datetime.timedelta(days=1)
  920. increase_user_qs = Device_User.objects.filter(data_joined__year=today.year, data_joined__month=today.month,
  921. data_joined__day=today.day).values('region_country')
  922. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  923. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  924. active_user_qs = UserExModel.objects.filter(updTime__gte=start_time, updTime__lt=end_time).values(
  925. 'userID__region_country')
  926. country_qs = CountryModel.objects.all().values('id', 'region__name', 'country_name')
  927. country_dict = {}
  928. continent_dict = {}
  929. for item in country_qs:
  930. country_dict[item['id']] = item['country_name']
  931. continent_dict[item['country_name']] = item['region__name']
  932. with transaction.atomic():
  933. if increase_user_qs.exists():
  934. increase_user_count = increase_user_qs.count()
  935. increase_user_country_list = increase_user_qs.values('region_country').annotate(
  936. count=Count('region_country')).order_by('count')
  937. increase_user_country_dict = {}
  938. increase_user_continent_dict = {}
  939. for item in increase_user_country_list:
  940. country_name = country_dict.get(item['region_country'], '未知国家')
  941. continent_name = continent_dict.get(country_name, '未知大洲')
  942. increase_user_country_dict[country_name] = item['count']
  943. if continent_name not in increase_user_continent_dict:
  944. increase_user_continent_dict[continent_name] = 0
  945. increase_user_continent_dict[continent_name] += item['count']
  946. DeviceUserSummary.objects.create(time=start_time, count=increase_user_count,
  947. country=increase_user_country_dict, created_time=created_time,
  948. continent=increase_user_continent_dict)
  949. if active_user_qs.exists():
  950. active_user_count = active_user_qs.count()
  951. active_user_country_list = active_user_qs.values('userID__region_country').annotate(
  952. count=Count('userID__region_country')).order_by('count')
  953. active_user_country_dict = {}
  954. active_user_continent_dict = {}
  955. for item in active_user_country_list:
  956. country_name = country_dict.get(item['userID__region_country'], '未知国家')
  957. continent_name = continent_dict.get(country_name, '未知大洲')
  958. active_user_country_dict[country_name] = item['count']
  959. if continent_name not in active_user_continent_dict:
  960. active_user_continent_dict[continent_name] = 0
  961. active_user_continent_dict[continent_name] += item['count']
  962. user_qs = DeviceUserSummary.objects.filter(time=start_time, query_type=1)
  963. if user_qs.exists():
  964. user_qs.update(count=active_user_count, country=active_user_country_dict,
  965. continent=active_user_continent_dict)
  966. else:
  967. DeviceUserSummary.objects.create(time=start_time, query_type=1, count=active_user_count,
  968. country=active_user_country_dict, created_time=created_time,
  969. continent=active_user_continent_dict)
  970. return response.json(0)
  971. except Exception as e:
  972. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  973. @staticmethod
  974. def collect_order(response):
  975. try:
  976. created_time = int(time.time())
  977. today = datetime.datetime.today()
  978. start_time = datetime.datetime(today.year, today.month, today.day)
  979. end_time = start_time + datetime.timedelta(days=1)
  980. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  981. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  982. order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time,
  983. status=1).values('UID', 'order_type',
  984. 'store_meal_name', 'price',
  985. 'addTime', 'currency').order_by(
  986. 'addTime')
  987. uid_list = []
  988. all_order_qs = Order_Model.objects.filter(addTime__lt=start_time, status=1).values('UID')
  989. for item in all_order_qs:
  990. if item['UID'] not in uid_list:
  991. uid_list.append(item['UID'])
  992. # 国家表数据
  993. country_qs = CountryModel.objects.values('id', 'country_name')
  994. country_dict = {}
  995. for item in country_qs:
  996. country_dict[item['id']] = item['country_name']
  997. # 设备类型数据
  998. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  999. device_type_dict = {}
  1000. for item in device_type_qs:
  1001. device_type_dict[item['type']] = item['name']
  1002. with transaction.atomic():
  1003. for item in order_qs:
  1004. is_pay = 0
  1005. price = float(item['price'])
  1006. currency = item['currency']
  1007. uid_set_qs = UidSetModel.objects.filter(uid=item['UID']).values('tb_country')
  1008. country_id = uid_set_qs[0]['tb_country'] if uid_set_qs.exists() else 0
  1009. country_name = country_dict.get(country_id, '未知国家')
  1010. order_type = item['order_type']
  1011. if order_type == '4' or order_type == 4:
  1012. continue
  1013. device_info_qs = Device_Info.objects.filter(UID=item['UID']).values('Type')
  1014. device_type_id = device_info_qs[0]['Type'] if device_info_qs.exists() else 0
  1015. device_type_name = device_type_dict.get(device_type_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. if price == 0:
  1022. is_pay = 1
  1023. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=1,
  1024. service_type=order_type)
  1025. else:
  1026. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=0,
  1027. service_type=order_type)
  1028. if item['UID'] not in uid_list:
  1029. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=2,
  1030. service_type=order_type)
  1031. query_type = 2
  1032. else:
  1033. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=3,
  1034. service_type=order_type)
  1035. query_type = 3
  1036. if pay_order_summary_qs.exists():
  1037. pay_order_summary = pay_order_summary_qs.first()
  1038. pay_order_summary.count += 1
  1039. temp_total = eval(pay_order_summary.total)
  1040. if currency not in temp_total:
  1041. temp_total[currency] = price
  1042. else:
  1043. temp_total[currency] = round(temp_total[currency] + price, 2)
  1044. pay_order_summary.total = temp_total
  1045. country_temp_dict = eval(pay_order_summary.country)
  1046. if country_name in country_temp_dict:
  1047. country_temp_dict[country_name]['数量'] += 1
  1048. if currency not in country_temp_dict[country_name]:
  1049. country_temp_dict[country_name][currency] = price
  1050. else:
  1051. country_temp_dict[country_name][currency] = round(
  1052. country_temp_dict[country_name][currency] + price, 2)
  1053. else:
  1054. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1055. pay_order_summary.country = country_temp_dict
  1056. device_type_temp_dict = eval(pay_order_summary.device_type)
  1057. if device_type_name in device_type_temp_dict:
  1058. device_type_temp_dict[device_type_name]['数量'] += 1
  1059. if currency not in device_type_temp_dict[device_type_name]:
  1060. device_type_temp_dict[device_type_name][currency] = price
  1061. else:
  1062. device_type_temp_dict[device_type_name][currency] = round(
  1063. device_type_temp_dict[device_type_name][currency] + price, 2)
  1064. else:
  1065. device_type_temp_dict[device_type_name] = {'数量': 1, currency: price}
  1066. pay_order_summary.device_type = device_type_temp_dict
  1067. store_meal_temp_dict = eval(pay_order_summary.store_meal)
  1068. if store_meal_name in store_meal_temp_dict:
  1069. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1070. if currency not in store_meal_temp_dict[store_meal_name]:
  1071. store_meal_temp_dict[store_meal_name][currency] = price
  1072. else:
  1073. store_meal_temp_dict[store_meal_name][currency] = round(
  1074. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1075. else:
  1076. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1077. pay_order_summary.store_meal = store_meal_temp_dict
  1078. pay_order_summary.save()
  1079. else:
  1080. final_total = {currency: price}
  1081. country_temp_dict = {
  1082. country_name: {
  1083. '数量': 1,
  1084. currency: price
  1085. }
  1086. }
  1087. device_type_temp_dict = {
  1088. device_type_name: {
  1089. '数量': 1,
  1090. currency: price
  1091. }
  1092. }
  1093. store_meal_temp_dict = {
  1094. store_meal_name: {
  1095. '数量': 1,
  1096. currency: price
  1097. }
  1098. }
  1099. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=query_type,
  1100. service_type=order_type, total=final_total,
  1101. country=country_temp_dict, created_time=created_time,
  1102. device_type=device_type_temp_dict,
  1103. store_meal=store_meal_temp_dict)
  1104. if order_summary_qs.exists():
  1105. order_summary = order_summary_qs.first()
  1106. order_summary.count += 1
  1107. temp_total = eval(order_summary.total)
  1108. if currency not in temp_total:
  1109. temp_total[currency] = price
  1110. else:
  1111. temp_total[currency] = round(temp_total[currency] + price, 2)
  1112. order_summary.total = temp_total
  1113. country_temp_dict = eval(order_summary.country)
  1114. if country_name in country_temp_dict:
  1115. if is_pay == 0:
  1116. country_temp_dict[country_name]['数量'] += 1
  1117. if currency not in country_temp_dict[country_name]:
  1118. country_temp_dict[country_name][currency] = price
  1119. else:
  1120. country_temp_dict[country_name][currency] = round(
  1121. country_temp_dict[country_name][currency] + price, 2)
  1122. else:
  1123. country_temp_dict[country_name] += 1
  1124. else:
  1125. if is_pay == 0:
  1126. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1127. else:
  1128. country_temp_dict[country_name] = 1
  1129. order_summary.country = country_temp_dict
  1130. device_type_temp_dict = eval(order_summary.device_type)
  1131. if device_type_name in device_type_temp_dict:
  1132. if is_pay == 0:
  1133. device_type_temp_dict[device_type_name]['数量'] += 1
  1134. if currency not in device_type_temp_dict[device_type_name]:
  1135. device_type_temp_dict[device_type_name][currency] = price
  1136. else:
  1137. device_type_temp_dict[device_type_name][currency] = round(
  1138. device_type_temp_dict[device_type_name][currency] + price, 2)
  1139. else:
  1140. device_type_temp_dict[device_type_name] += 1
  1141. else:
  1142. if is_pay == 0:
  1143. device_type_temp_dict[device_type_name] = {'数量': 1, currency: price}
  1144. else:
  1145. device_type_temp_dict[device_type_name] = 1
  1146. order_summary.device_type = device_type_temp_dict
  1147. store_meal_temp_dict = eval(order_summary.store_meal)
  1148. if store_meal_name in store_meal_temp_dict:
  1149. if is_pay == 0:
  1150. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1151. if currency not in store_meal_temp_dict[store_meal_name]:
  1152. store_meal_temp_dict[store_meal_name][currency] = price
  1153. else:
  1154. store_meal_temp_dict[store_meal_name][currency] = round(
  1155. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1156. else:
  1157. store_meal_temp_dict[store_meal_name] += 1
  1158. else:
  1159. if is_pay == 0:
  1160. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1161. else:
  1162. store_meal_temp_dict[store_meal_name] = 1
  1163. order_summary.store_meal = store_meal_temp_dict
  1164. order_summary.save()
  1165. else:
  1166. final_total = {currency: price}
  1167. if is_pay == 0:
  1168. country_temp_dict = {
  1169. country_name: {
  1170. '数量': 1,
  1171. currency: price
  1172. }
  1173. }
  1174. device_type_temp_dict = {
  1175. device_type_name: {
  1176. '数量': 1,
  1177. currency: price
  1178. }
  1179. }
  1180. store_meal_temp_dict = {
  1181. store_meal_name: {
  1182. '数量': 1,
  1183. currency: price
  1184. }
  1185. }
  1186. else:
  1187. device_type_temp_dict = {
  1188. device_type_name: 1
  1189. }
  1190. store_meal_temp_dict = {
  1191. store_meal_name: 1
  1192. }
  1193. country_temp_dict = {
  1194. country_name: 1
  1195. }
  1196. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=is_pay,
  1197. service_type=order_type, total=final_total,
  1198. country=country_temp_dict, created_time=created_time,
  1199. device_type=device_type_temp_dict, store_meal=store_meal_temp_dict)
  1200. return response.json(0)
  1201. except Exception as e:
  1202. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1203. @staticmethod
  1204. def collect_operating_costs(response):
  1205. try:
  1206. today = datetime.datetime.today()
  1207. end_time = datetime.datetime(today.year, today.month, today.day)
  1208. yesterday = end_time - datetime.timedelta(days=1)
  1209. start_time = datetime.datetime(yesterday.year, yesterday.month, 1)
  1210. start_time_stamp = int(start_time.timestamp())
  1211. end_time_stamp = int(end_time.timestamp())
  1212. thread = threading.Thread(target=CronCollectDataView.thread_collect_operating_costs,
  1213. args=(start_time_stamp, end_time_stamp, start_time, end_time))
  1214. thread.start() # 启动线程
  1215. return response.json(0)
  1216. except Exception as e:
  1217. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1218. @staticmethod
  1219. def thread_collect_operating_costs(start_time_stamp, end_time_stamp, start_time, end_time):
  1220. try:
  1221. create_time = int(time.time())
  1222. today_end_time = end_time_stamp + 86400
  1223. operating_costs_qs_1 = OperatingCosts.objects.filter(time=start_time_stamp).exclude(
  1224. created_time__gte=end_time_stamp, created_time__lt=today_end_time).values('order_id', 'end_time', 'uid')
  1225. operating_costs_qs_2 = OperatingCosts.objects.filter(time=start_time_stamp,
  1226. created_time__gte=end_time_stamp,
  1227. created_time__lt=today_end_time, start_time=0).values(
  1228. 'order_id', 'end_time', 'uid')
  1229. operating_costs_qs = operating_costs_qs_1.union(operating_costs_qs_2)
  1230. storage_univalence = 0.023 / 30
  1231. api_univalence = 0.005 / 1000
  1232. region = '国内' if CONFIG_INFO == CONFIG_CN else '国外'
  1233. country_qs = CountryModel.objects.values('id', 'country_name')
  1234. country_dict = {}
  1235. for item in country_qs:
  1236. country_dict[item['id']] = item['country_name']
  1237. for item in operating_costs_qs:
  1238. order_qs = Order_Model.objects.filter(orderID=item['order_id'], order_type__in=[0, 1]).values('price',
  1239. 'payTime',
  1240. 'rank__expire',
  1241. 'fee',
  1242. 'payType',
  1243. 'userID__region_country')
  1244. if order_qs.exists():
  1245. order = order_qs[0]
  1246. country_name = country_dict.get(order['userID__region_country'], '未知国家')
  1247. order_type = '云存'
  1248. expire = str(order_qs[0]['rank__expire']) + '个月'
  1249. price = float(order['price'])
  1250. if order['payType'] in [2, 3]:
  1251. fee = round(0.0054 * price, 2)
  1252. else:
  1253. fee = float(order['fee']) if order['fee'] else 0
  1254. order_start_time = int((datetime.datetime.fromtimestamp(item['end_time']) - relativedelta(
  1255. months=order['rank__expire'])).timestamp())
  1256. order_days = math.ceil((item['end_time'] - order_start_time) / 86400)
  1257. if item['end_time'] > end_time_stamp: # 订单结束时间大于统计时间
  1258. if order_start_time <= start_time_stamp: # 订单月初之前开始
  1259. settlement_days = (end_time - start_time).days # 当月结算天数=月初-月底
  1260. uid_bucket_statistics = UidBucketStatistics.objects.filter(time__gte=start_time_stamp,
  1261. time__lte=end_time_stamp,
  1262. uid=item['uid'])
  1263. elif order_start_time >= end_time_stamp: # 订单在统计时间之后开始
  1264. settlement_days = 1
  1265. uid_bucket_statistics = UidBucketStatistics.objects.filter(time__gte=end_time_stamp,
  1266. time__lt=order_start_time,
  1267. uid=item['uid'])
  1268. else: # 订单月初和统计时间之间开始
  1269. settlement_days = math.ceil((end_time_stamp - order_start_time) / 86400)
  1270. uid_bucket_statistics = UidBucketStatistics.objects.filter(time__gte=order_start_time,
  1271. time__lte=end_time_stamp,
  1272. uid=item['uid'])
  1273. remaining_usage_time = math.ceil((item['end_time'] - end_time_stamp) / 86400) # 剩余使用时间
  1274. else: # 订单结束时间小于统计时间
  1275. if order_start_time <= start_time_stamp:
  1276. settlement_days = math.ceil((item['end_time'] - start_time_stamp) / 86400)
  1277. uid_bucket_statistics = UidBucketStatistics.objects.filter(time__gte=start_time_stamp,
  1278. time__lt=item['end_time'],
  1279. uid=item['uid'])
  1280. else:
  1281. settlement_days = math.ceil((item['end_time'] - order_start_time) / 86400)
  1282. uid_bucket_statistics = UidBucketStatistics.objects.filter(time__gte=order_start_time,
  1283. time__lt=item['end_time'],
  1284. uid=item['uid'])
  1285. remaining_usage_time = 0
  1286. day_average_price = round(price / order_days, 2) # 收入分摊/天
  1287. month_average_price = round(day_average_price * settlement_days, 2) # 收入分摊/月
  1288. monthly_income = round((price - fee) / order_days * settlement_days, 2) # 当月结算收入
  1289. real_income = round(price - fee, 2)
  1290. result = uid_bucket_statistics.aggregate(size=Sum('storage_size'), api_count=Sum('api_count'))
  1291. actual_storage = round(result['size'], 2) if result['size'] else 0
  1292. actual_api = result['api_count'] if result['api_count'] else 0
  1293. storage_cost = actual_storage / 1024 * storage_univalence * settlement_days
  1294. api_cost = actual_api * api_univalence
  1295. if CONFIG_INFO == CONFIG_CN: # 国内要换算汇率
  1296. storage_cost = storage_cost * 7
  1297. api_cost = api_cost * 7
  1298. profit = round(monthly_income - storage_cost - api_cost, 2) # 利润=月结算金额-月成本
  1299. storage_cost = round(storage_cost, 2)
  1300. api_cost = round(api_cost, 2)
  1301. if monthly_income == 0.0:
  1302. profit_margin = 0
  1303. else:
  1304. profit_margin = round(profit / month_average_price, 2) # 利润率=利润/每月收入分摊
  1305. OperatingCosts.objects.filter(time=start_time_stamp, order_id=item['order_id'],
  1306. uid=item['uid']).update(day_average_price=day_average_price,
  1307. month_average_price=month_average_price,
  1308. monthly_income=monthly_income,
  1309. actual_storage=actual_storage,
  1310. settlement_days=settlement_days,
  1311. actual_api=actual_api, fee=fee,
  1312. created_time=create_time, region=region,
  1313. start_time=order_start_time,
  1314. remaining_usage_time=remaining_usage_time,
  1315. storage_cost=storage_cost, api_cost=api_cost,
  1316. profit=profit, profit_margin=profit_margin,
  1317. real_income=real_income, price=price,
  1318. country_name=country_name,
  1319. order_type=order_type, expire=expire)
  1320. print('结束')
  1321. except Exception as e:
  1322. LOGGER.info(
  1323. 'thread_collect_operating_costs接口异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno,
  1324. repr(e)))
  1325. @staticmethod
  1326. def collect_obj_size(response):
  1327. try:
  1328. today = datetime.datetime.today()
  1329. end_time = datetime.datetime(today.year, today.month, today.day)
  1330. start_time = end_time - datetime.timedelta(days=1)
  1331. first_date = datetime.datetime(start_time.year, start_time.month, 1)
  1332. start_time_stamp = int(start_time.timestamp())
  1333. end_time_stamp = int(end_time.timestamp())
  1334. first_date_stamp = int(first_date.timestamp())
  1335. thread = threading.Thread(target=CronCollectDataView.thread_collect_obj_size,
  1336. args=(start_time_stamp, end_time_stamp, first_date_stamp))
  1337. thread.start() # 启动线程
  1338. return response.json(0)
  1339. except Exception as e:
  1340. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1341. @staticmethod
  1342. def thread_collect_obj_size(start_time, end_time, first_date):
  1343. try:
  1344. creat_time = int(time.time())
  1345. uid_list = UidBucketStatistics.objects.filter(time=start_time).values_list('uid', flat=True)
  1346. uid_vod = UID_Bucket.objects.filter(Q(endTime__gte=start_time), ~Q(uid__in=uid_list)).values('uid',
  1347. 'bucket__bucket',
  1348. 'orderId',
  1349. 'channel',
  1350. 'endTime')
  1351. s3_obj = AmazonS3Util(ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME)
  1352. for item in uid_vod:
  1353. path = '{uid}/vod{channel}'.format(uid=item['uid'], channel=item['channel'])
  1354. s3_result = s3_obj.get_object_list(item['bucket__bucket'], path,
  1355. path + '/{}'.format(start_time), end_time)
  1356. actual_storage = 0
  1357. actual_api = 0
  1358. for obj in s3_result:
  1359. temp_time = int(obj['Key'].split('/')[2])
  1360. if temp_time < end_time:
  1361. actual_storage += obj['Size']
  1362. actual_api += 1
  1363. actual_storage = round(actual_storage / 1024 / 1024, 2)
  1364. with transaction.atomic():
  1365. if actual_api:
  1366. UidBucketStatistics.objects.create(uid=item['uid'], storage_size=actual_storage,
  1367. api_count=actual_api,
  1368. created_time=creat_time,
  1369. time=start_time)
  1370. operating_costs_qs = OperatingCosts.objects.filter(order_id=item['orderId'], uid=item['uid'],
  1371. time=first_date)
  1372. if not operating_costs_qs.exists():
  1373. OperatingCosts.objects.create(order_id=item['orderId'], uid=item['uid'],
  1374. created_time=creat_time, time=first_date,
  1375. end_time=item['endTime'])
  1376. print(actual_storage, actual_api)
  1377. print('结束')
  1378. except Exception as e:
  1379. print('error')
  1380. LOGGER.info('统计s3信息异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1381. @classmethod
  1382. def check_request(cls, response):
  1383. domain_name_list = [
  1384. 'test.zositechc.cn', 'test.push.zositechc.cn',
  1385. 'www.zositechc.cn', 'api.loocam2.cn', 'common.neutral2.cn', 'api.aiotserver.cn', 'push.zositechc.cn',
  1386. 'www.dvema.com', 'api.zositech2.com', 'api.loocam2.com', 'common.neutral2.com', '149.neutral2.com',
  1387. '365.neutral2.com', 'push.dvema.com',
  1388. 'www.zositeche.com', 'api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com',
  1389. 'push.zositeche.com',
  1390. 'www.zositech.xyz', 'smart.loocam2.com'
  1391. ]
  1392. for domain_name in domain_name_list:
  1393. thread = threading.Thread(target=cls.initial_request, args=(domain_name,))
  1394. thread.start()
  1395. return response.json(0)
  1396. @staticmethod
  1397. def initial_request(domain_name):
  1398. url = 'https://{}/init/health-check'.format(domain_name)
  1399. try:
  1400. requests.post(url=url, timeout=30)
  1401. except Exception as e:
  1402. email_content = 'https请求域名{}出现异常!error_msg:{}'.format(domain_name, repr(e))
  1403. S3Email().faEmail(email_content, 'servers@ansjer.com')
  1404. @staticmethod
  1405. def collect_icloud_order(response):
  1406. try:
  1407. order_type = 4
  1408. created_time = int(time.time())
  1409. today = datetime.datetime.today()
  1410. start_time = datetime.datetime(today.year, today.month, today.day)
  1411. end_time = start_time + datetime.timedelta(days=1)
  1412. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1413. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1414. order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time, order_type=order_type,
  1415. status=1).values('userID',
  1416. 'store_meal_name', 'price',
  1417. 'addTime', 'currency').order_by(
  1418. 'addTime')
  1419. user_list = []
  1420. all_order_qs = Order_Model.objects.filter(addTime__lt=start_time, status=1, order_type=order_type).values(
  1421. 'userID')
  1422. for item in all_order_qs:
  1423. if item['userID'] not in user_list:
  1424. user_list.append(item['userID'])
  1425. # 国家表数据
  1426. country_qs = CountryModel.objects.values('id', 'country_name')
  1427. country_dict = {}
  1428. for item in country_qs:
  1429. country_dict[item['id']] = item['country_name']
  1430. with transaction.atomic():
  1431. for item in order_qs:
  1432. price = float(item['price'])
  1433. currency = item['currency']
  1434. user_qs = Device_User.objects.filter(userID=item['userID']).values('region_country')
  1435. country_id = user_qs[0]['region_country'] if user_qs.exists() else 0
  1436. country_name = country_dict.get(country_id, '未知国家')
  1437. store_meal_name = item['store_meal_name']
  1438. add_time_stamp = item['addTime']
  1439. add_time_str = datetime.datetime.fromtimestamp(int(add_time_stamp))
  1440. add_time_str = datetime.datetime(add_time_str.year, add_time_str.month, add_time_str.day)
  1441. add_time_stamp = CommonService.str_to_timestamp(add_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  1442. order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=0,
  1443. service_type=order_type)
  1444. if item['userID'] not in user_list:
  1445. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=2,
  1446. service_type=order_type)
  1447. query_type = 2
  1448. else:
  1449. pay_order_summary_qs = OrdersSummary.objects.filter(time=add_time_stamp, query_type=3,
  1450. service_type=order_type)
  1451. query_type = 3
  1452. if pay_order_summary_qs.exists():
  1453. pay_order_summary = pay_order_summary_qs.first()
  1454. pay_order_summary.count += 1
  1455. temp_total = eval(pay_order_summary.total)
  1456. if currency not in temp_total:
  1457. temp_total[currency] = price
  1458. else:
  1459. temp_total[currency] = round(temp_total[currency] + price, 2)
  1460. pay_order_summary.total = temp_total
  1461. country_temp_dict = eval(pay_order_summary.country)
  1462. if country_name in country_temp_dict:
  1463. country_temp_dict[country_name]['数量'] += 1
  1464. if currency not in country_temp_dict[country_name]:
  1465. country_temp_dict[country_name][currency] = price
  1466. else:
  1467. country_temp_dict[country_name][currency] = round(
  1468. country_temp_dict[country_name][currency] + price, 2)
  1469. else:
  1470. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1471. pay_order_summary.country = country_temp_dict
  1472. store_meal_temp_dict = eval(pay_order_summary.store_meal)
  1473. if store_meal_name in store_meal_temp_dict:
  1474. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1475. if currency not in store_meal_temp_dict[store_meal_name]:
  1476. store_meal_temp_dict[store_meal_name][currency] = price
  1477. else:
  1478. store_meal_temp_dict[store_meal_name][currency] = round(
  1479. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1480. else:
  1481. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1482. pay_order_summary.store_meal = store_meal_temp_dict
  1483. pay_order_summary.save()
  1484. else:
  1485. final_total = {currency: price}
  1486. country_temp_dict = {
  1487. country_name: {
  1488. '数量': 1,
  1489. currency: price
  1490. }
  1491. }
  1492. store_meal_temp_dict = {
  1493. store_meal_name: {
  1494. '数量': 1,
  1495. currency: price
  1496. }
  1497. }
  1498. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=query_type,
  1499. service_type=order_type, total=final_total,
  1500. country=country_temp_dict, created_time=created_time,
  1501. device_type={},
  1502. store_meal=store_meal_temp_dict)
  1503. if order_summary_qs.exists():
  1504. order_summary = order_summary_qs.first()
  1505. order_summary.count += 1
  1506. temp_total = eval(order_summary.total)
  1507. if currency not in temp_total:
  1508. temp_total[currency] = price
  1509. else:
  1510. temp_total[currency] = round(temp_total[currency] + price, 2)
  1511. order_summary.total = temp_total
  1512. country_temp_dict = eval(order_summary.country)
  1513. if country_name in country_temp_dict:
  1514. country_temp_dict[country_name]['数量'] += 1
  1515. if currency not in country_temp_dict[country_name]:
  1516. country_temp_dict[country_name][currency] = price
  1517. else:
  1518. country_temp_dict[country_name][currency] = round(
  1519. country_temp_dict[country_name][currency] + price, 2)
  1520. else:
  1521. country_temp_dict[country_name] = {'数量': 1, currency: price}
  1522. order_summary.country = country_temp_dict
  1523. store_meal_temp_dict = eval(order_summary.store_meal)
  1524. if store_meal_name in store_meal_temp_dict:
  1525. store_meal_temp_dict[store_meal_name]['数量'] += 1
  1526. if currency not in store_meal_temp_dict[store_meal_name]:
  1527. store_meal_temp_dict[store_meal_name][currency] = price
  1528. else:
  1529. store_meal_temp_dict[store_meal_name][currency] = round(
  1530. store_meal_temp_dict[store_meal_name][currency] + price, 2)
  1531. else:
  1532. store_meal_temp_dict[store_meal_name] = {'数量': 1, currency: price}
  1533. order_summary.store_meal = store_meal_temp_dict
  1534. order_summary.save()
  1535. else:
  1536. final_total = {currency: price}
  1537. country_temp_dict = {
  1538. country_name: {
  1539. '数量': 1,
  1540. currency: price
  1541. }
  1542. }
  1543. store_meal_temp_dict = {
  1544. store_meal_name: {
  1545. '数量': 1,
  1546. currency: price
  1547. }
  1548. }
  1549. OrdersSummary.objects.create(time=add_time_stamp, count=1, query_type=0,
  1550. service_type=order_type, total=final_total,
  1551. country=country_temp_dict, created_time=created_time,
  1552. device_type={}, store_meal=store_meal_temp_dict)
  1553. return response.json(0)
  1554. except Exception as e:
  1555. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1556. @staticmethod
  1557. def collect_device_info(response):
  1558. try:
  1559. created_time = int(time.time())
  1560. today = datetime.datetime.today()
  1561. start_time = datetime.datetime(today.year, today.month, today.day)
  1562. end_time = start_time + datetime.timedelta(days=1)
  1563. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1564. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1565. increase_device_qs = UidSetModel.objects.filter(addTime__gte=start_time, addTime__lt=end_time).values(
  1566. 'tb_country',
  1567. 'uid',
  1568. 'device_type',
  1569. 'cloud_vod',
  1570. 'is_ai',
  1571. 'mobile_4g',
  1572. 'addTime')
  1573. video_play_back_time_qs = VideoPlaybackTimeModel.objects.filter(startTime__gte=start_time,
  1574. startTime__lt=end_time).values('uid')
  1575. active_device_qs = UidSetModel.objects.filter(uid__in=video_play_back_time_qs).values('tb_country',
  1576. 'addTime',
  1577. 'device_type',
  1578. 'cloud_vod',
  1579. 'is_ai',
  1580. 'mobile_4g',
  1581. 'uid')
  1582. increase_device_count = increase_device_qs.count()
  1583. active_device_count = active_device_qs.count()
  1584. # 国家表数据
  1585. country_qs = CountryModel.objects.values('id', 'country_name', 'region__name')
  1586. country_dict = {}
  1587. continent_dict = {}
  1588. for item in country_qs:
  1589. country_dict[item['id']] = item['country_name']
  1590. continent_dict[item['country_name']] = item['region__name']
  1591. # 设备类型数据
  1592. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  1593. device_type_dict = {}
  1594. for item in device_type_qs:
  1595. device_type_dict[item['type']] = item['name']
  1596. with transaction.atomic():
  1597. if increase_device_qs.exists():
  1598. # 国家大洲设备数据
  1599. increase_device_country_list = increase_device_qs.values('tb_country').annotate(
  1600. count=Count('tb_country')).order_by('count')
  1601. increase_device_country_dict = {}
  1602. increase_device_continent_dict = {}
  1603. for item in increase_device_country_list:
  1604. country_name = country_dict.get(item['tb_country'], '未知国家')
  1605. continent_name = continent_dict.get(country_name, '未知大洲')
  1606. increase_device_country_dict[country_name] = item['count']
  1607. if continent_name not in increase_device_continent_dict:
  1608. increase_device_continent_dict[continent_name] = 0
  1609. increase_device_continent_dict[continent_name] += item['count']
  1610. # 设备类型数据
  1611. increase_device_type_list = increase_device_qs.values('device_type').annotate(
  1612. count=Count('device_type')).order_by('count')
  1613. increase_device_type_dict = {}
  1614. for item in increase_device_type_list:
  1615. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1616. increase_device_type_dict[type_name] = item['count']
  1617. # 云存设备类型数据
  1618. increase_device_vod_list = increase_device_qs.filter(~Q(cloud_vod=2)).values(
  1619. 'device_type').annotate(
  1620. count=Count('device_type')).order_by('count')
  1621. increase_device_vod_dict = {}
  1622. for item in increase_device_vod_list:
  1623. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1624. increase_device_vod_dict[type_name] = item['count']
  1625. # AI设备类型数据
  1626. increase_device_ai_list = increase_device_qs.filter(~Q(is_ai=2)).values('device_type').annotate(
  1627. count=Count('device_type')).order_by('count')
  1628. increase_device_ai_dict = {}
  1629. for item in increase_device_ai_list:
  1630. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1631. increase_device_ai_dict[type_name] = item['count']
  1632. # 联通设备类型数据
  1633. increase_device_unicom_list = increase_device_qs.filter(~Q(mobile_4g=2)).values(
  1634. 'device_type').annotate(
  1635. count=Count('device_type')).order_by('count')
  1636. increase_device_unicom_dict = {}
  1637. for item in increase_device_unicom_list:
  1638. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1639. increase_device_unicom_dict[type_name] = item['count']
  1640. DeviceInfoSummary.objects.create(time=start_time, count=increase_device_count,
  1641. query_type=0, created_time=created_time,
  1642. country=increase_device_country_dict,
  1643. continent=increase_device_continent_dict,
  1644. vod_service=increase_device_vod_dict,
  1645. ai_service=increase_device_ai_dict,
  1646. unicom_service=increase_device_unicom_dict,
  1647. device_type=increase_device_type_dict)
  1648. if active_device_qs.exists():
  1649. # 国家大洲设备数据
  1650. active_device_country_list = active_device_qs.values('tb_country').annotate(
  1651. count=Count('tb_country')).order_by('count')
  1652. active_device_country_dict = {}
  1653. active_device_continent_dict = {}
  1654. for item in active_device_country_list:
  1655. country_name = country_dict.get(item['tb_country'], '未知国家')
  1656. continent_name = continent_dict.get(country_name, '未知大洲')
  1657. active_device_country_dict[country_name] = item['count']
  1658. if continent_name not in active_device_continent_dict:
  1659. active_device_continent_dict[continent_name] = 0
  1660. active_device_continent_dict[continent_name] += item['count']
  1661. # 设备类型数据
  1662. active_device_type_list = active_device_qs.values('device_type').annotate(
  1663. count=Count('device_type')).order_by('count')
  1664. active_device_type_dict = {}
  1665. for item in active_device_type_list:
  1666. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1667. active_device_type_dict[type_name] = item['count']
  1668. # 云存设备类型数据
  1669. active_device_vod_list = active_device_qs.filter(~Q(cloud_vod=2)).values('device_type').annotate(
  1670. count=Count('device_type')).order_by('count')
  1671. active_device_vod_dict = {}
  1672. for item in active_device_vod_list:
  1673. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1674. active_device_vod_dict[type_name] = item['count']
  1675. # AI设备类型数据
  1676. active_device_ai_list = active_device_qs.filter(~Q(is_ai=2)).values('device_type').annotate(
  1677. count=Count('device_type')).order_by('count')
  1678. active_device_ai_dict = {}
  1679. for item in active_device_ai_list:
  1680. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1681. active_device_ai_dict[type_name] = item['count']
  1682. # 联通设备类型数据
  1683. active_device_unicom_list = active_device_qs.filter(~Q(mobile_4g=2)).values('device_type').annotate(
  1684. count=Count('device_type')).order_by('count')
  1685. active_device_unicom_dict = {}
  1686. for item in active_device_unicom_list:
  1687. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1688. active_device_unicom_dict[type_name] = item['count']
  1689. DeviceInfoSummary.objects.create(time=start_time, count=active_device_count,
  1690. query_type=1, created_time=created_time,
  1691. country=active_device_country_dict,
  1692. continent=active_device_continent_dict,
  1693. vod_service=active_device_vod_dict,
  1694. ai_service=active_device_ai_dict,
  1695. unicom_service=active_device_unicom_dict,
  1696. device_type=active_device_type_dict)
  1697. return response.json(0)
  1698. except Exception as e:
  1699. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1700. @staticmethod
  1701. def collect_activity_user(response):
  1702. try:
  1703. created_time = int(time.time())
  1704. today = datetime.datetime.today()
  1705. start_time = datetime.datetime(today.year, today.month, today.day)
  1706. end_time = start_time + datetime.timedelta(days=1)
  1707. start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
  1708. end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
  1709. thread = threading.Thread(target=CronCollectDataView.thread_collect_activity_user,
  1710. args=(start_time, end_time, created_time))
  1711. thread.start() # 启动线程
  1712. return response.json(0)
  1713. except Exception as e:
  1714. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1715. @staticmethod
  1716. def thread_collect_activity_user(start_time, end_time, created_time):
  1717. try:
  1718. active_uid = UserExModel.objects.filter(updTime__gte=start_time, updTime__lt=end_time).values_list(
  1719. 'userID__device_info__UID', flat=True).distinct()
  1720. active_device_qs = UidSetModel.objects.filter(uid__in=active_uid).values('addTime', 'device_type', 'ucode')
  1721. # 设备类型数据
  1722. device_type_qs = DeviceTypeModel.objects.values('name', 'type')
  1723. device_type_dict = {}
  1724. for item in device_type_qs:
  1725. device_type_dict[item['type']] = item['name']
  1726. with transaction.atomic():
  1727. if active_device_qs.exists():
  1728. # 按设备设备类型
  1729. active_device_type_list = active_device_qs.values('device_type').annotate(
  1730. count=Count('device_type')).order_by('count')
  1731. active_device_type_dict = {}
  1732. for item in active_device_type_list:
  1733. type_name = device_type_dict.get(item['device_type'], '未知设备类型')
  1734. active_device_type_dict[type_name] = item['count']
  1735. # 按ucode分类
  1736. active_ucode_list = active_device_qs.values('ucode').annotate(count=Count('ucode')).order_by('count')
  1737. active_ucode_dict = {}
  1738. for item in active_ucode_list:
  1739. ucode = item['ucode']
  1740. if item['ucode'] == '':
  1741. ucode = '未知ucode'
  1742. active_ucode_dict[ucode] = item['count']
  1743. user_qs = DeviceUserSummary.objects.filter(time=start_time, query_type=1)
  1744. if user_qs.exists():
  1745. user_qs.update(device_type=active_device_type_dict, ucode=active_ucode_dict)
  1746. else:
  1747. DeviceUserSummary.objects.create(time=start_time, query_type=1, created_time=created_time,
  1748. device_type=active_device_type_dict, ucode=active_ucode_dict)
  1749. except Exception as e:
  1750. LOGGER.info(
  1751. 'thread_collect_activity_user接口异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno,
  1752. repr(e)))
  1753. @staticmethod
  1754. def collect_flow_info(response):
  1755. try:
  1756. unicom_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('iccid').distinct().order_by('iccid')
  1757. asy = threading.Thread(target=CronCollectDataView.thread_collect_flow, args=(unicom_qs,))
  1758. asy.start()
  1759. return response.json(0)
  1760. except Exception as e:
  1761. return response.json(500, repr(e))
  1762. @staticmethod
  1763. def thread_collect_flow(qs):
  1764. try:
  1765. unicom_api = UnicomObjeect()
  1766. redis_obj = RedisObject()
  1767. for item in qs:
  1768. res = unicom_api.query_device_usage_history(**item)
  1769. if res.status_code == 200:
  1770. res_json = res.json()
  1771. if res_json['code'] == 0:
  1772. redis_dict = {}
  1773. for data in res_json['data']['deviceUsageHistory']:
  1774. year = data.get('year', None)
  1775. month = data.get('month', None)
  1776. flow = data.get('flowTotalUsage', None)
  1777. if not all([year, month, flow]):
  1778. continue
  1779. file = str(year) + '-' + str(month)
  1780. redis_dict[file] = flow
  1781. key = 'monthly_flow_' + item['iccid']
  1782. if redis_dict:
  1783. redis_obj.set_hash_data(key, redis_dict)
  1784. except Exception as e:
  1785. LOGGER.info('统计联通流量失败,时间为:{}'.format(int(time.time())))
  1786. class CronComparedDataView(View):
  1787. def get(self, request, *args, **kwargs):
  1788. request.encoding = 'utf-8'
  1789. operation = kwargs.get('operation')
  1790. return self.validation(request.GET, request, operation)
  1791. def post(self, request, *args, **kwargs):
  1792. request.encoding = 'utf-8'
  1793. operation = kwargs.get('operation')
  1794. return self.validation(request.POST, request, operation)
  1795. def validation(self, request_dict, request, operation):
  1796. response = ResponseObject()
  1797. if operation == 'PaypalOrder': # 定时对比paypal订单
  1798. return self.compared_paypal_order(request_dict, response)
  1799. elif operation == 'WechatOrder': # 定时对比微信订单
  1800. return self.compared_wechat_order(response)
  1801. elif operation == 'AlipayOrder': # 定时对比阿里订单
  1802. return self.compared_alipay_order(response)
  1803. elif operation == 'AnsjerOrder': # 定时对比后台订单
  1804. return self.compared_ansjer_order(request_dict, response)
  1805. else:
  1806. return response.json(404)
  1807. @staticmethod
  1808. def compared_paypal_order(request_dict, response):
  1809. time_stamp = request_dict.get('time', None)
  1810. if time_stamp:
  1811. end_date = datetime.datetime.fromtimestamp(int(time_stamp))
  1812. start_date = end_date - datetime.timedelta(days=1)
  1813. else:
  1814. today = datetime.datetime.today()
  1815. start_date = today - datetime.timedelta(days=2)
  1816. start_date = datetime.datetime(start_date.year, start_date.month, start_date.day)
  1817. end_date = start_date + datetime.timedelta(days=1)
  1818. try:
  1819. zosi_paypal_api = paypalrestsdk.Api(PAYPAL_CRD['Zosi'])
  1820. vsees_paypal_api = paypalrestsdk.Api(PAYPAL_CRD['Vsees'])
  1821. paypal_url = 'v1/reporting/transactions?start_date={}-{}-{}T08:00:00-0800&end_date={}-{}-{}T08:00:00-0800&fields=all&page_size=500&page=1&transaction_status=S'.format(
  1822. start_date.year, start_date.month, start_date.day, end_date.year, end_date.month, end_date.day)
  1823. zosi_order_list = zosi_paypal_api.get(paypal_url)
  1824. vsees_order_list = vsees_paypal_api.get(paypal_url)
  1825. order_list = zosi_order_list['transaction_details'] + vsees_order_list['transaction_details']
  1826. # data = (
  1827. # ('start_date', '{}-{}-{}T08:00:00-0800'.format(start_date.year, start_date.month, start_date.day)),
  1828. # ('end_date', '{}-{}-{}T08:00:00-0800'.format(end_date.year, end_date.month, end_date.day)),
  1829. # ('fields', 'all'),
  1830. # ('page_size', '500'),
  1831. # ('page', '1'),
  1832. # ('transaction_status', 'S')
  1833. # )
  1834. # order_list = PayPalService(PAYPAL_CRD['client_id'], PAYPAL_CRD['client_secret']).get_transactions(data)
  1835. thread = threading.Thread(target=CronComparedDataView.thread_compared_paypal_order,
  1836. args=(order_list, end_date))
  1837. thread.start() # 启动线程
  1838. return response.json(0)
  1839. except Exception as e:
  1840. LOGGER.info('CronComparedDataView.compared_paypal_order, errLine:{}, errMsg:{}'.format(
  1841. e.__traceback__.tb_lineno, repr(e)))
  1842. return response.json(500)
  1843. @staticmethod
  1844. def thread_compared_paypal_order(order_list, start_time):
  1845. try:
  1846. now_time = int(time.time())
  1847. timestamp = int(start_time.timestamp())
  1848. count = 0
  1849. total = 0
  1850. more_order_list = []
  1851. for item in order_list:
  1852. if 'custom_field' in item['transaction_info'] and item['transaction_info']['custom_field'] == 'Shopify':
  1853. continue
  1854. count += 1
  1855. total += float(item['transaction_info']['transaction_amount']['value'])
  1856. trade_no = item['transaction_info']['transaction_id']
  1857. if item['transaction_info']['transaction_event_code'] in ['T1106', 'T1107', 'T1202']: # 付款退款
  1858. trade_no = item['transaction_info']['paypal_reference_id']
  1859. transaction_subject = item['transaction_info'].get('transaction_subject', '')
  1860. agreement_id = item['transaction_info'].get('paypal_reference_id', '')
  1861. refund_order = False
  1862. if item['transaction_info']['transaction_event_code'] in ['T1106', 'T1107', 'T1201', 'T0114', 'T1108']:
  1863. agreement_id = ''
  1864. if item['transaction_info']['transaction_event_code'] in ['T0114']:
  1865. transaction_subject = '争议费'
  1866. elif item['transaction_info']['transaction_event_code'] in ['T1108']:
  1867. transaction_subject = 'Fee reversal'
  1868. else:
  1869. refund_order = True
  1870. transaction_subject = '退款费'
  1871. more_order_list.append(trade_no)
  1872. pay_time = int(datetime.datetime.strptime(item['transaction_info']['transaction_updated_date'],
  1873. "%Y-%m-%dT%H:%M:%S%z").timestamp())
  1874. order_qs = Order_Model.objects.filter(trade_no=trade_no, payType=1)
  1875. if not order_qs.exists():
  1876. order_dict = {
  1877. 'trade_no': trade_no,
  1878. 'agreement_id': agreement_id,
  1879. 'pay_time': pay_time,
  1880. 'username': item['payer_info'].get('email_address', ''),
  1881. 'price': item['transaction_info']['transaction_amount']['value'],
  1882. 'pay_type': 1,
  1883. 'upd_time': now_time,
  1884. 'status': 0,
  1885. 'meal_name': transaction_subject
  1886. }
  1887. if agreement_id:
  1888. order_dict['pay_type'] = 0
  1889. order_dict['meal_name'] = 'paypal_cycle'
  1890. order_dict['order_id'] = transaction_subject
  1891. params = {'trade_no': trade_no, 'pay_time': pay_time, 'refund_order': refund_order}
  1892. response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
  1893. if response.status_code != 200:
  1894. # 如果响应失败,记录在数据库
  1895. abnormal_qs = AbnormalOrder.objects.filter(trade_no=trade_no)
  1896. if not abnormal_qs.exists():
  1897. AbnormalOrder.objects.create(**order_dict)
  1898. continue
  1899. result = response.json()
  1900. if result['result_code'] != 0 or not result['result']['is_exist']:
  1901. # 如果响应结果为空,记录在数据库
  1902. abnormal_qs = AbnormalOrder.objects.filter(trade_no=trade_no)
  1903. if not abnormal_qs.exists():
  1904. AbnormalOrder.objects.create(**order_dict)
  1905. more_order_list.append(trade_no)
  1906. else:
  1907. if not refund_order:
  1908. order_qs.update(payTime=pay_time)
  1909. total = round(total, 2)
  1910. daily_reconciliation = DailyReconciliation.objects.filter(time=timestamp)
  1911. if daily_reconciliation.exists():
  1912. if daily_reconciliation.first().order_ids:
  1913. old_order_list = daily_reconciliation.first().order_ids.split(',')
  1914. more_order_list = list(set(old_order_list) | set(more_order_list))
  1915. order_ids = ','.join(set(more_order_list))
  1916. daily_reconciliation.update(paypal_num=count, paypal_total=total, upd_time=now_time,
  1917. order_ids=order_ids)
  1918. else:
  1919. order_ids = ','.join(set(more_order_list))
  1920. DailyReconciliation.objects.create(paypal_num=count, paypal_total=total, time=timestamp,
  1921. order_ids=order_ids, creat_time=now_time, upd_time=now_time)
  1922. except Exception as e:
  1923. LOGGER.info('paypal每日对账异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1924. @staticmethod
  1925. def compared_wechat_order(response):
  1926. today = datetime.datetime.today()
  1927. start_date = today - datetime.timedelta(days=1)
  1928. start_date = start_date.strftime("%Y%m%d")
  1929. try:
  1930. order_list = WechatPayObject().download_bill(start_date)
  1931. thread = threading.Thread(target=CronComparedDataView.thread_compared_wechat_order,
  1932. args=(order_list,))
  1933. thread.start()
  1934. return response.json(0)
  1935. except Exception as e:
  1936. LOGGER.info('CronComparedDataView.compared_wechat_order, errLine:{}, errMsg:{}'.format(
  1937. e.__traceback__.tb_lineno, repr(e)))
  1938. return response.json(500)
  1939. @staticmethod
  1940. def thread_compared_wechat_order(order_list):
  1941. now_time = int(time.time())
  1942. for order in order_list:
  1943. if order['交易类型'] != '`APP':
  1944. continue
  1945. order_id = order['商户订单号'].replace('`', '')
  1946. order_qs = Order_Model.objects.filter(orderID=order_id)
  1947. if not order_qs.exists():
  1948. order_dict = {
  1949. 'trade_no': order['微信订单号'].replace('`', ''),
  1950. 'order_id': order_id,
  1951. 'pay_type': 3,
  1952. 'price': order['订单金额'].replace('`', ''),
  1953. 'pay_time': int(
  1954. datetime.datetime.strptime(order['\ufeff交易时间'], "`%Y-%m-%d %H:%M:%S").timestamp()),
  1955. 'upd_time': now_time,
  1956. 'meal_name': order['商品名称'].replace('`', ''),
  1957. }
  1958. AbnormalOrder.objects.create(**order_dict)
  1959. @staticmethod
  1960. def compared_alipay_order(response):
  1961. today = datetime.datetime.today()
  1962. start_date = today - datetime.timedelta(days=1)
  1963. start_date = start_date.strftime("%Y-%m-%d")
  1964. try:
  1965. ali_pay_obj = AliPayObject()
  1966. alipay = ali_pay_obj.conf()
  1967. result = alipay.server_api(
  1968. api_name='alipay.data.dataservice.bill.downloadurl.query',
  1969. biz_content={'bill_type': 'trade',
  1970. 'bill_date': start_date,
  1971. }
  1972. )
  1973. res = requests.get(result['bill_download_url'])
  1974. zip_file = res.content
  1975. zip_data = io.BytesIO(zip_file)
  1976. data = []
  1977. with zipfile.ZipFile(zip_data, 'r') as zip_ref:
  1978. for file in zip_ref.namelist():
  1979. if '汇总' not in file.encode('cp437').decode('gbk'):
  1980. with zip_ref.open(file) as f:
  1981. reader = csv.reader(io.TextIOWrapper(f, 'gbk'))
  1982. for row in reader:
  1983. data.append(row)
  1984. key_list = data[4]
  1985. orders = data[5:-4]
  1986. order_list = []
  1987. for item in orders:
  1988. order_list.append(dict(zip(key_list, item)))
  1989. thread = threading.Thread(target=CronComparedDataView.thread_compared_alipay_order,
  1990. args=(order_list,))
  1991. thread.start()
  1992. return response.json(0)
  1993. except Exception as e:
  1994. LOGGER.info('CronComparedDataView.compared_alipay_order, errLine:{}, errMsg:{}'.format(
  1995. e.__traceback__.tb_lineno, repr(e)))
  1996. return response.json(500)
  1997. @staticmethod
  1998. def thread_compared_alipay_order(order_list):
  1999. now_time = int(time.time())
  2000. for order in order_list:
  2001. order_id = order['商户订单号'].replace('\t', '')
  2002. if len(order_id) != 20:
  2003. continue
  2004. order_qs = Order_Model.objects.filter(orderID=order_id)
  2005. if not order_qs.exists():
  2006. order_dict = {
  2007. 'trade_no': order['支付宝交易号'].replace('\t', ''),
  2008. 'order_id': order_id,
  2009. 'pay_type': 2,
  2010. 'price': order['订单金额(元)'].replace('\t', ''),
  2011. 'pay_time': int(datetime.datetime.strptime(order['完成时间'], "%Y-%m-%d %H:%M:%S").timestamp()),
  2012. 'upd_time': now_time,
  2013. 'meal_name': order['商品名称'].replace('\t', ''),
  2014. 'username': order['对方账户'].replace('\t', ''),
  2015. }
  2016. AbnormalOrder.objects.create(**order_dict)
  2017. @staticmethod
  2018. def compared_ansjer_order(request_dict, response):
  2019. start_date_stamp = request_dict.get('time', None)
  2020. end_time = request_dict.get('end_time', None)
  2021. if start_date_stamp:
  2022. start_date = datetime.datetime.fromtimestamp(int(start_date_stamp))
  2023. end_date = start_date + datetime.timedelta(days=1)
  2024. end_date_stamp = int(end_date.timestamp())
  2025. else:
  2026. today = datetime.datetime.today()
  2027. start_date = today - datetime.timedelta(days=1)
  2028. start_date = datetime.datetime(start_date.year, start_date.month, start_date.day)
  2029. end_date = datetime.datetime(today.year, today.month, today.day)
  2030. start_date_stamp = int(start_date.timestamp())
  2031. end_date_stamp = int(end_date.timestamp())
  2032. try:
  2033. if end_time:
  2034. end_date_stamp = end_time
  2035. order_qs = Order_Model.objects.filter(status__in=[1, 5, 6], payType=1, payTime__gte=start_date_stamp,
  2036. payTime__lt=end_date_stamp).values('trade_no', 'orderID', 'UID',
  2037. 'userID__username',
  2038. 'userID__NickName', 'channel',
  2039. 'desc', 'payType',
  2040. 'price', 'status',
  2041. 'refunded_amount', 'addTime',
  2042. 'updTime', 'app_type')
  2043. if CONFIG_INFO == CONFIG_EUR:
  2044. return response.json(0, list(order_qs))
  2045. thread = threading.Thread(target=CronComparedDataView.thread_compared_ansjer_order,
  2046. args=(list(order_qs), start_date))
  2047. thread.start() # 启动线程
  2048. return response.json(0)
  2049. except Exception as e:
  2050. LOGGER.info('CronComparedDataView.compared_ansjer_order, errLine:{}, errMsg:{}'.format(
  2051. e.__traceback__.tb_lineno, repr(e)))
  2052. return response.json(500)
  2053. @staticmethod
  2054. def thread_compared_ansjer_order(order_list, start_time):
  2055. while True:
  2056. response = requests.get('https://www.zositeche.com/cron/compared/AnsjerOrder',
  2057. params={'time': int(start_time.timestamp())})
  2058. if response.status_code == 200:
  2059. result = response.json()
  2060. if result['result_code'] == 0:
  2061. eur_order_list = result['result']
  2062. break
  2063. try:
  2064. begin_date = start_time - datetime.timedelta(days=15)
  2065. end_date = start_time + datetime.timedelta(days=15)
  2066. start_timestamp = int(start_time.timestamp())
  2067. now_time = int(time.time())
  2068. more_order_list = []
  2069. total = 0
  2070. all_order_list = order_list + eur_order_list
  2071. count = len(all_order_list)
  2072. zosi_paypal_api = paypalrestsdk.Api(PAYPAL_CRD['Zosi'])
  2073. vsees_paypal_api = paypalrestsdk.Api(PAYPAL_CRD['Vsees'])
  2074. for index, order in enumerate(all_order_list):
  2075. total += float(order['price'])
  2076. if not order['trade_no']:
  2077. more_order_list.append(order['orderID'])
  2078. continue
  2079. if all_order_list.index(order) != index:
  2080. more_order_list.append(order['orderID'])
  2081. continue
  2082. paypal_url = 'v1/reporting/transactions?start_date={}-{}-{}T00:00:00-0000&end_date={}-{}-{}T00:00:00-0000&transaction_id={}&fields=all&page_size=100&page=1'.format(
  2083. begin_date.year, begin_date.month, begin_date.day, end_date.year, end_date.month, end_date.day,
  2084. order['trade_no'])
  2085. if order['app_type'] == 1:
  2086. paypal_order_list = zosi_paypal_api.get(paypal_url)
  2087. elif order['app_type'] == 2:
  2088. paypal_order_list = vsees_paypal_api.get(paypal_url)
  2089. else:
  2090. continue
  2091. if not paypal_order_list['transaction_details']:
  2092. more_order_list.append(order['orderID'])
  2093. total = round(total, 2)
  2094. daily_reconciliation = DailyReconciliation.objects.filter(time=start_timestamp)
  2095. if daily_reconciliation.exists():
  2096. if daily_reconciliation.first().order_ids:
  2097. old_order_list = daily_reconciliation.first().order_ids.split(',')
  2098. more_order_list = list(set(old_order_list) | set(more_order_list))
  2099. order_ids = ','.join(set(more_order_list))
  2100. daily_reconciliation.update(ansjer_total=total, ansjer_num=count, order_ids=order_ids,
  2101. upd_time=now_time)
  2102. else:
  2103. order_ids = ','.join(more_order_list)
  2104. DailyReconciliation.objects.create(order_ids=order_ids, ansjer_total=total, ansjer_num=count,
  2105. time=start_timestamp, creat_time=now_time, upd_time=now_time)
  2106. except Exception as e:
  2107. LOGGER.info('后台每日对账异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))