CommonService.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. # -*- coding: utf-8 -*-
  2. # 高复用性函数封装到CommonService类
  3. import base64
  4. import datetime
  5. import time
  6. from pathlib import Path
  7. from random import Random
  8. import ipdb
  9. import simplejson as json
  10. from django.core import serializers
  11. from django.http import HttpResponseRedirect
  12. from django.utils import timezone
  13. from pyipip import IPIPDatabase
  14. from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET, SERVER_DOMAIN_SSL
  15. import OpenSSL.crypto as ct
  16. from base64 import encodebytes
  17. from Controller.CheckUserData import RandomStr
  18. from Service.ModelService import ModelService
  19. class CommonService:
  20. # 添加模糊搜索
  21. @staticmethod
  22. def get_kwargs(data={}):
  23. kwargs = {}
  24. for (k, v) in data.items():
  25. if v is not None and v != u'':
  26. kwargs[k + '__icontains'] = v
  27. return kwargs
  28. # 定义静态方法
  29. # 格式化query_set转dict
  30. @staticmethod
  31. def qs_to_dict(query_set):
  32. sqlJSON = serializers.serialize('json', query_set)
  33. sqlList = json.loads(sqlJSON)
  34. sqlDict = dict(zip(["datas"], [sqlList]))
  35. return sqlDict
  36. # 格式化query_set转dict
  37. @staticmethod
  38. def request_dict_to_dict(request_dict):
  39. # 传参格式转换,键包含meta获取meta[]中的值,值'true'/'false'转为True,False
  40. key_list = []
  41. value_list = []
  42. for k, v in request_dict.items():
  43. key_list.append(k[k.index('[')+1:k.index(']')] if 'meta' in k else k)
  44. if v == 'true':
  45. v = True
  46. elif v == 'false':
  47. v = False
  48. value_list.append(v)
  49. data_dict = dict(zip(key_list, value_list))
  50. print(data_dict)
  51. return data_dict
  52. # 获取文件大小
  53. @staticmethod
  54. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  55. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  56. # path = Path() / 'D:/TestServer/123444.mp4'
  57. path = Path() / file_path
  58. size = path.stat().st_size
  59. mb_size = 0.0
  60. if suffix_type == 'MB':
  61. mb_size = size / 1024.0 / 1024.0
  62. if decimal_point != 0:
  63. mb_size = round(mb_size, decimal_point)
  64. return mb_size
  65. @staticmethod
  66. def get_param_flag(data=[]):
  67. # print(data)
  68. flag = True
  69. for v in data:
  70. if v is None:
  71. flag = False
  72. break
  73. return flag
  74. @staticmethod
  75. def get_ip_address(request):
  76. """
  77. 获取ip地址
  78. :param request:
  79. :return:
  80. """
  81. try:
  82. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  83. clientIP = real_ip.split(",")[0]
  84. except:
  85. try:
  86. clientIP = request.META['REMOTE_ADDR']
  87. except Exception as e:
  88. clientIP = ''
  89. return clientIP
  90. # @获取一天每个小时的datetime.datetime
  91. @staticmethod
  92. def getTimeDict(times):
  93. time_dict = {}
  94. t = 0
  95. for x in range(24):
  96. if x < 10:
  97. x = '0' + str(x)
  98. else:
  99. x = str(x)
  100. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  101. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  102. t += 1
  103. return time_dict
  104. # 根据ip获取地址
  105. @staticmethod
  106. def getAddr(ip):
  107. print('start_time=' + str(time.time()))
  108. base_dir = BASE_DIR
  109. # ip数据库
  110. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  111. addr = db.lookup(ip)
  112. # ModelService.add_tmp_log(addr)
  113. ts = addr.split('\t')[0]
  114. print('end_time=' + str(time.time()))
  115. return ts
  116. # 通过ip检索ipip指定信息 lang为CN或EN
  117. @staticmethod
  118. def getIpIpInfo(ip, lang, update=False):
  119. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  120. db = ipdb.City(ipbd_dir)
  121. if update:
  122. rr = db.reload(ipbd_dir)
  123. info = db.find_map(ip, lang)
  124. return info
  125. @staticmethod
  126. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  127. if μs == True:
  128. if getUser == True:
  129. timeID = str(round(time.time() * 1000000))
  130. userID = timeID + userPhone
  131. return userID
  132. else:
  133. if setOTAID == False:
  134. timeID = str(round(time.time() * 1000000))
  135. ID = userPhone + timeID
  136. return ID
  137. else:
  138. timeID = str(round(time.time() * 1000000))
  139. eID = '13800' + timeID + '138000'
  140. return eID
  141. else:
  142. if getUser == True:
  143. timeID = str(round(time.time() * 1000))
  144. userID = timeID + userPhone
  145. return userID
  146. else:
  147. if setOTAID == False:
  148. timeID = str(round(time.time() * 1000))
  149. ID = userPhone + timeID
  150. return ID
  151. else:
  152. timeID = str(round(time.time() * 1000))
  153. eID = '13800' + timeID + '138000'
  154. return eID
  155. # 生成随机数
  156. @staticmethod
  157. def RandomStr(randomlength=8, number=True):
  158. str = ''
  159. if number == False:
  160. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  161. 'tUuVvWwXxYyZz0123456789'
  162. else:
  163. characterSet = '0123456789'
  164. length = len(characterSet) - 1
  165. random = Random()
  166. for index in range(randomlength):
  167. str += characterSet[random.randint(0, length)]
  168. return str
  169. # 生成订单好
  170. @staticmethod
  171. def createOrderID():
  172. random_id = CommonService.RandomStr(6, True)
  173. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  174. print('orderID:')
  175. print(order_id)
  176. return order_id
  177. # qs转换list datetime处理
  178. @staticmethod
  179. def qs_to_list(qs):
  180. res = []
  181. # print(qs)
  182. for ps in qs:
  183. try:
  184. if 'time' in ps:
  185. ps['time'] = ps['time'].strftime("%Y-%m-%d %H:%M:%S")
  186. if 'add_time' in ps:
  187. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  188. if 'update_time' in ps:
  189. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  190. if 'end_time' in ps:
  191. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  192. if 'data_joined' in ps:
  193. if ps['data_joined']:
  194. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  195. else:
  196. ps['data_joined'] = ''
  197. if 'userID__data_joined' in ps:
  198. if ps['userID__data_joined']:
  199. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  200. else:
  201. ps['userID__data_joined'] = ''
  202. except Exception as e:
  203. pass
  204. res.append(ps)
  205. return res
  206. # 获取当前时间
  207. @staticmethod
  208. def get_now_time_str(n_time, tz, lang):
  209. print(n_time)
  210. print(tz)
  211. print(lang)
  212. n_time = int(n_time) + 3600 * float(tz)
  213. if lang == 'cn':
  214. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  215. else:
  216. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  217. # 生成随机数
  218. @staticmethod
  219. def encrypt_data(randomlength=8, number=False):
  220. str = ''
  221. if number == False:
  222. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  223. 'tUuVvWwXxYyZz0123456789'
  224. else:
  225. characterSet = '0123456789'
  226. length = len(characterSet) - 1
  227. random = Random()
  228. for index in range(randomlength):
  229. str += characterSet[random.randint(0, length)]
  230. return str
  231. @staticmethod
  232. def decode_data(content, start=1, end=4):
  233. if not content:
  234. return ''
  235. try:
  236. for i in range(start, end):
  237. if i == 1:
  238. content = base64.b64decode(content)
  239. content = content.decode('utf-8')
  240. content = content[1:-1]
  241. if i == 2:
  242. content = base64.b64decode(content)
  243. content = content.decode('utf-8')
  244. content = content[2:-2]
  245. if i == 3:
  246. content = base64.b64decode(content)
  247. content = content.decode('utf-8')
  248. content = content[3:-3]
  249. return content
  250. except Exception as e:
  251. print(e)
  252. return None
  253. @staticmethod
  254. def encode_data(content, start=1, end=4):
  255. if not content:
  256. return ''
  257. for i in range(start, end):
  258. if i == 1:
  259. content = RandomStr(3, False)+content+RandomStr(3, False)
  260. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  261. if i == 2:
  262. content = RandomStr(2, False)+str(content)+RandomStr(2, False)
  263. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  264. if i == 3:
  265. content = RandomStr(1, False)+str(content)+RandomStr(1, False)
  266. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  267. return content
  268. #把格式化时间转换成时间戳
  269. @staticmethod
  270. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  271. if str_time:
  272. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  273. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  274. return int(result)
  275. return int(time.time())
  276. # 把时间戳转换成格式化
  277. @staticmethod
  278. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  279. if timestamp:
  280. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  281. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  282. return result
  283. else:
  284. return time.strptime(format)
  285. #计算N个月后的时间戳
  286. @staticmethod
  287. def calcMonthLater(addMonth, unix_timestamp=None):
  288. if unix_timestamp:
  289. now_year = time.localtime(unix_timestamp).tm_year
  290. now_month = time.localtime(unix_timestamp).tm_mon
  291. now_day = time.localtime(unix_timestamp).tm_mday
  292. now_hour = time.localtime(unix_timestamp).tm_hour
  293. now_min = time.localtime(unix_timestamp).tm_min
  294. now_second = time.localtime(unix_timestamp).tm_sec
  295. else:
  296. now_year = datetime.datetime.now().year
  297. now_month = datetime.datetime.now().month
  298. now_day = datetime.datetime.now().day
  299. now_hour = datetime.datetime.now().hour
  300. now_min = datetime.datetime.now().minute
  301. now_second = datetime.datetime.now().second
  302. for add in range(addMonth):
  303. if now_month == 12:
  304. now_year += 1
  305. now_month = 1
  306. else:
  307. now_month += 1
  308. for is_format in range(4):
  309. try:
  310. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  311. .format(now_year=now_year,now_month=now_month,now_day=now_day,now_hour=now_hour,
  312. now_min=now_min,now_second=now_second)
  313. timestamps = CommonService.str_to_timestamp(date_format)
  314. except Exception as e:
  315. if str(e) == 'day is out of range for month':
  316. now_day = now_day - 1
  317. return timestamps
  318. @staticmethod
  319. def updateMac(mac: str):
  320. macArray = mac.split(':')
  321. macArray[0] = int(macArray[0], 16)
  322. macArray[1] = int(macArray[1], 16)
  323. macArray[2] = int(macArray[2], 16)
  324. first = int(macArray[5], 16)
  325. second = int(macArray[4], 16)
  326. three = int(macArray[3], 16)
  327. # print(macArray)
  328. # print(first)
  329. # print(second)
  330. # print(three)
  331. if first == 255 and second == 255 and three == 255:
  332. return None
  333. first += 1
  334. if first / 256 == 1:
  335. second += 1
  336. first = first % 256
  337. if second / 256 == 1:
  338. three += 1
  339. second = second % 256
  340. macArray[3] = three
  341. macArray[4] = second
  342. macArray[5] = first
  343. # print(macArray)
  344. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  345. # print(tmp)
  346. return tmp.upper()
  347. @staticmethod
  348. def decode_data(content, start=1, end=4):
  349. if not content:
  350. return ''
  351. try:
  352. for i in range(start, end):
  353. if i == 1:
  354. content = base64.b64decode(content)
  355. content = content.decode('utf-8')
  356. content = content[1:-1]
  357. if i == 2:
  358. content = base64.b64decode(content)
  359. content = content.decode('utf-8')
  360. content = content[2:-2]
  361. if i == 3:
  362. content = base64.b64decode(content)
  363. content = content.decode('utf-8')
  364. content = content[3:-3]
  365. print(content)
  366. return content
  367. except Exception as e:
  368. print(e)
  369. return None
  370. @staticmethod
  371. def encode_data(content, start=1, end=4):
  372. if not content:
  373. return ''
  374. for i in range(start, end):
  375. if i == 1:
  376. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  377. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  378. if i == 2:
  379. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  380. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  381. if i == 3:
  382. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  383. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  384. return content
  385. @staticmethod
  386. def encode_data_without_salt(content):
  387. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  388. @staticmethod
  389. def check_time_stamp_token(token, time_stamp):
  390. # 时间戳token校验
  391. if not all([token, time_stamp]):
  392. return False
  393. try:
  394. token = int(CommonService.decode_data(token))
  395. time_stamp = int(time_stamp)
  396. now_time = int(time.time())
  397. distance = now_time - time_stamp
  398. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  399. return False
  400. return True
  401. except Exception as e:
  402. print(e)
  403. return False
  404. @staticmethod
  405. def rsa_sign(Token):
  406. # 私钥签名Token
  407. if not Token:
  408. return ''
  409. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  410. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  411. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  412. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  413. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  414. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  415. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  416. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  417. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  418. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  419. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  420. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  421. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  422. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  423. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  424. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  425. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  426. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  427. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  428. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  429. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  430. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  431. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  432. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  433. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  434. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  435. -----END RSA PRIVATE KEY-----'''
  436. # 使用密钥文件方式
  437. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  438. # private_key_file = open(private_key_file_path, 'r')
  439. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  440. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  441. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  442. # print('signature:', signature)
  443. return signature
  444. @staticmethod
  445. def get_payment_status_url(lang, payment_status):
  446. # 返回相应的支付状态url
  447. if lang == 'cn':
  448. file_name = 'success.html' if payment_status == 'success' else 'fail.html'
  449. else:
  450. file_name = 'en_success.html' if payment_status == 'success' else 'en_fail.html'
  451. pay_failed_url = "{}web/paid2/{}".format(SERVER_DOMAIN_SSL, file_name)
  452. return pay_failed_url