CommonService.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. # -*- coding: utf-8 -*-
  2. # 高复用性函数封装到CommonService类
  3. import base64
  4. import datetime
  5. import time
  6. from base64 import encodebytes
  7. from pathlib import Path
  8. from random import Random
  9. from dateutil.relativedelta import relativedelta
  10. import OpenSSL.crypto as ct
  11. import ipdb
  12. import requests
  13. import simplejson as json
  14. from django.core import serializers
  15. from django.utils import timezone
  16. from pyipip import IPIPDatabase
  17. from Ansjer.config import BASE_DIR, SERVER_DOMAIN_SSL, CONFIG_INFO, CONFIG_TEST, CONFIG_CN
  18. from Controller.CheckUserData import RandomStr
  19. from Model.models import iotdeviceInfoModel, Device_Info, CountryModel, RegionModel, UIDModel
  20. from Object.ResponseObject import ResponseObject
  21. from Object.TokenObject import TokenObject
  22. class CommonService:
  23. # 添加模糊搜索
  24. @staticmethod
  25. def get_kwargs(data=None):
  26. if data is None:
  27. data = {}
  28. kwargs = {}
  29. for (k, v) in data.items():
  30. if v is not None and v != u'':
  31. kwargs[k + '__icontains'] = v
  32. return kwargs
  33. # 定义静态方法
  34. # 格式化query_set转dict
  35. @staticmethod
  36. def qs_to_dict(query_set):
  37. sqlJSON = serializers.serialize('json', query_set)
  38. sqlList = json.loads(sqlJSON)
  39. sqlDict = dict(zip(["datas"], [sqlList]))
  40. return sqlDict
  41. # 格式化query_set转dict
  42. @staticmethod
  43. def request_dict_to_dict(request_dict):
  44. # 传参格式转换,键包含meta获取meta[]中的值,值'true'/'false'转为True,False
  45. key_list = []
  46. value_list = []
  47. for k, v in request_dict.items():
  48. key_list.append(k[k.index('[') + 1:k.index(']')] if 'meta' in k else k)
  49. if v == 'true':
  50. v = True
  51. elif v == 'false':
  52. v = False
  53. value_list.append(v)
  54. data_dict = dict(zip(key_list, value_list))
  55. print(data_dict)
  56. return data_dict
  57. # 获取文件大小
  58. @staticmethod
  59. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  60. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  61. # path = Path() / 'D:/TestServer/123444.mp4'
  62. path = Path() / file_path
  63. size = path.stat().st_size
  64. mb_size = 0.0
  65. if suffix_type == 'MB':
  66. mb_size = size / 1024.0 / 1024.0
  67. if decimal_point != 0:
  68. mb_size = round(mb_size, decimal_point)
  69. return mb_size
  70. @staticmethod
  71. def get_param_flag(data=None):
  72. # print(data)
  73. if data is None:
  74. data = []
  75. flag = True
  76. for v in data:
  77. if v is None:
  78. flag = False
  79. break
  80. return flag
  81. @staticmethod
  82. def get_ip_address(request):
  83. """
  84. 获取ip地址
  85. :param request:
  86. :return:
  87. """
  88. try:
  89. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  90. clientIP = real_ip.split(",")[0]
  91. except:
  92. try:
  93. clientIP = request.META['REMOTE_ADDR']
  94. except Exception as e:
  95. clientIP = ''
  96. return clientIP
  97. # @获取一天每个小时的datetime.datetime
  98. @staticmethod
  99. def getTimeDict(times):
  100. time_dict = {}
  101. t = 0
  102. for x in range(24):
  103. if x < 10:
  104. x = '0' + str(x)
  105. else:
  106. x = str(x)
  107. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  108. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  109. t += 1
  110. return time_dict
  111. # 根据ip获取地址
  112. @staticmethod
  113. def getAddr(ip):
  114. print('start_time=' + str(time.time()))
  115. base_dir = BASE_DIR
  116. # ip数据库
  117. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  118. addr = db.lookup(ip)
  119. # ModelService.add_tmp_log(addr)
  120. ts = addr.split('\t')[0]
  121. print('end_time=' + str(time.time()))
  122. return ts
  123. # 通过ip检索ipip指定信息 lang为CN或EN
  124. @staticmethod
  125. def getIpIpInfo(ip, lang, update=False):
  126. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  127. db = ipdb.City(ipbd_dir)
  128. if update:
  129. rr = db.reload(ipbd_dir)
  130. info = db.find_map(ip, lang)
  131. return info
  132. @staticmethod
  133. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  134. if μs == True:
  135. if getUser == True:
  136. timeID = str(round(time.time() * 1000000))
  137. userID = timeID + userPhone
  138. return userID
  139. else:
  140. if setOTAID == False:
  141. timeID = str(round(time.time() * 1000000))
  142. ID = userPhone + timeID
  143. return ID
  144. else:
  145. timeID = str(round(time.time() * 1000000))
  146. eID = '13800' + timeID + '138000'
  147. return eID
  148. else:
  149. if getUser == True:
  150. timeID = str(round(time.time() * 1000))
  151. userID = timeID + userPhone
  152. return userID
  153. else:
  154. if setOTAID == False:
  155. timeID = str(round(time.time() * 1000))
  156. ID = userPhone + timeID
  157. return ID
  158. else:
  159. timeID = str(round(time.time() * 1000))
  160. eID = '13800' + timeID + '138000'
  161. return eID
  162. # 生成随机数
  163. @staticmethod
  164. def RandomStr(randomlength=8, number=True):
  165. str = ''
  166. if number == False:
  167. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  168. 'tUuVvWwXxYyZz0123456789'
  169. else:
  170. characterSet = '0123456789'
  171. length = len(characterSet) - 1
  172. random = Random()
  173. for index in range(randomlength):
  174. str += characterSet[random.randint(0, length)]
  175. return str
  176. # 生成订单好
  177. @staticmethod
  178. def createOrderID():
  179. random_id = CommonService.RandomStr(6, True)
  180. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  181. print('orderID:')
  182. print(order_id)
  183. return order_id
  184. # qs转换list datetime处理
  185. @staticmethod
  186. def qs_to_list(qs):
  187. res = []
  188. # print(qs)
  189. for ps in qs:
  190. try:
  191. if 'time' in ps:
  192. ps['time'] = ps['time'].strftime("%Y-%m-%d %H:%M:%S")
  193. if 'add_time' in ps:
  194. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  195. if 'update_time' in ps:
  196. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  197. if 'end_time' in ps:
  198. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  199. if 'data_joined' in ps:
  200. if ps['data_joined']:
  201. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  202. else:
  203. ps['data_joined'] = ''
  204. if 'userID__data_joined' in ps:
  205. if ps['userID__data_joined']:
  206. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  207. else:
  208. ps['userID__data_joined'] = ''
  209. except Exception as e:
  210. pass
  211. res.append(ps)
  212. return res
  213. # 获取当前时间
  214. @staticmethod
  215. def get_now_time_str(n_time, tz, lang):
  216. print(n_time)
  217. print(tz)
  218. print(lang)
  219. n_time = int(n_time) + 3600 * float(tz)
  220. if lang == 'cn':
  221. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  222. else:
  223. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  224. # 生成随机数
  225. @staticmethod
  226. def encrypt_data(randomlength=8, number=False):
  227. str = ''
  228. if number == False:
  229. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  230. 'tUuVvWwXxYyZz0123456789'
  231. else:
  232. characterSet = '0123456789'
  233. length = len(characterSet) - 1
  234. random = Random()
  235. for index in range(randomlength):
  236. str += characterSet[random.randint(0, length)]
  237. return str
  238. @staticmethod
  239. def decode_data(content, start=1, end=4):
  240. if not content:
  241. return ''
  242. try:
  243. for i in range(start, end):
  244. if i == 1:
  245. content = base64.b64decode(content)
  246. content = content.decode('utf-8')
  247. content = content[1:-1]
  248. if i == 2:
  249. content = base64.b64decode(content)
  250. content = content.decode('utf-8')
  251. content = content[2:-2]
  252. if i == 3:
  253. content = base64.b64decode(content)
  254. content = content.decode('utf-8')
  255. content = content[3:-3]
  256. return content
  257. except Exception as e:
  258. print(e)
  259. return None
  260. @staticmethod
  261. def encode_data(content, start=1, end=4):
  262. if not content:
  263. return ''
  264. for i in range(start, end):
  265. if i == 1:
  266. content = RandomStr(3, False) + content + RandomStr(3, False)
  267. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  268. if i == 2:
  269. content = RandomStr(2, False) + str(content) + RandomStr(2, False)
  270. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  271. if i == 3:
  272. content = RandomStr(1, False) + str(content) + RandomStr(1, False)
  273. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  274. return content
  275. # 把格式化时间转换成时间戳
  276. @staticmethod
  277. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  278. if str_time:
  279. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  280. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  281. return int(result)
  282. return int(time.time())
  283. # 把时间戳转换成格式化
  284. @staticmethod
  285. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  286. if timestamp:
  287. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  288. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  289. return result
  290. else:
  291. return time.strptime(format)
  292. # 计算N个月后的时间戳
  293. @staticmethod
  294. def calcMonthLater(addMonth, unix_timestamp=None):
  295. if unix_timestamp:
  296. now_year = time.localtime(unix_timestamp).tm_year
  297. now_month = time.localtime(unix_timestamp).tm_mon
  298. now_day = time.localtime(unix_timestamp).tm_mday
  299. now_hour = time.localtime(unix_timestamp).tm_hour
  300. now_min = time.localtime(unix_timestamp).tm_min
  301. now_second = time.localtime(unix_timestamp).tm_sec
  302. else:
  303. now_year = datetime.datetime.now().year
  304. now_month = datetime.datetime.now().month
  305. now_day = datetime.datetime.now().day
  306. now_hour = datetime.datetime.now().hour
  307. now_min = datetime.datetime.now().minute
  308. now_second = datetime.datetime.now().second
  309. for add in range(addMonth):
  310. if now_month == 12:
  311. now_year += 1
  312. now_month = 1
  313. else:
  314. now_month += 1
  315. for is_format in range(4):
  316. try:
  317. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  318. .format(now_year=now_year, now_month=now_month, now_day=now_day, now_hour=now_hour,
  319. now_min=now_min, now_second=now_second)
  320. timestamps = CommonService.str_to_timestamp(date_format)
  321. except Exception as e:
  322. if str(e) == 'day is out of range for month':
  323. now_day = now_day - 1
  324. return timestamps
  325. @staticmethod
  326. def updateMac(mac: str):
  327. macArray = mac.split(':')
  328. macArray[0] = int(macArray[0], 16)
  329. macArray[1] = int(macArray[1], 16)
  330. macArray[2] = int(macArray[2], 16)
  331. first = int(macArray[5], 16)
  332. second = int(macArray[4], 16)
  333. three = int(macArray[3], 16)
  334. # print(macArray)
  335. # print(first)
  336. # print(second)
  337. # print(three)
  338. if first == 255 and second == 255 and three == 255:
  339. return None
  340. first += 1
  341. if first / 256 == 1:
  342. second += 1
  343. first = first % 256
  344. if second / 256 == 1:
  345. three += 1
  346. second = second % 256
  347. macArray[3] = three
  348. macArray[4] = second
  349. macArray[5] = first
  350. # print(macArray)
  351. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  352. # print(tmp)
  353. return tmp.upper()
  354. @staticmethod
  355. def decode_data(content, start=1, end=4):
  356. if not content:
  357. return ''
  358. try:
  359. for i in range(start, end):
  360. if i == 1:
  361. content = base64.b64decode(content)
  362. content = content.decode('utf-8')
  363. content = content[1:-1]
  364. if i == 2:
  365. content = base64.b64decode(content)
  366. content = content.decode('utf-8')
  367. content = content[2:-2]
  368. if i == 3:
  369. content = base64.b64decode(content)
  370. content = content.decode('utf-8')
  371. content = content[3:-3]
  372. print(content)
  373. return content
  374. except Exception as e:
  375. print(e)
  376. return None
  377. @staticmethod
  378. def encode_data(content, start=1, end=4):
  379. if not content:
  380. return ''
  381. for i in range(start, end):
  382. if i == 1:
  383. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  384. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  385. if i == 2:
  386. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  387. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  388. if i == 3:
  389. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  390. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  391. return content
  392. @staticmethod
  393. def encode_data_without_salt(content):
  394. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  395. @staticmethod
  396. def check_time_stamp_token(token, time_stamp):
  397. # 时间戳token校验
  398. if not all([token, time_stamp]):
  399. return False
  400. try:
  401. token = int(CommonService.decode_data(token))
  402. time_stamp = int(time_stamp)
  403. now_time = int(time.time())
  404. distance = now_time - time_stamp
  405. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  406. return False
  407. return True
  408. except Exception as e:
  409. print(e)
  410. return False
  411. @staticmethod
  412. def check_time_stamp_token_without_distance(time_stamp_token, time_stamp):
  413. """
  414. 用于没有RTC设备的时间戳token校验
  415. @param time_stamp: 时间戳
  416. @param time_stamp_token: 时间戳token
  417. @return: boolean True/False
  418. """
  419. if not all([time_stamp_token, time_stamp]):
  420. return False
  421. try:
  422. token = CommonService.decode_data(time_stamp_token)
  423. if token != time_stamp:
  424. return False
  425. return True
  426. except Exception as e:
  427. print(e)
  428. return False
  429. @staticmethod
  430. def req_publish_mqtt_msg(identification_code, topic_name, msg, qos=1):
  431. """
  432. 通用发布MQTT消息函数
  433. @param identification_code: 标识码
  434. @param topic_name: 主题名
  435. @param msg: 消息内容
  436. @param qos: mqtt qos等级
  437. @return: boolean
  438. """
  439. if not all([identification_code, topic_name]):
  440. return False
  441. if identification_code.endswith('11L'):
  442. thing_name = 'LC_' + identification_code
  443. else:
  444. thing_name = 'Ansjer_Device_' + identification_code
  445. try:
  446. # 获取数据组织将要请求的url
  447. iot = iotdeviceInfoModel.objects.filter(
  448. thing_name=thing_name).values(
  449. 'endpoint', 'token_iot_number')
  450. if not iot.exists():
  451. return False
  452. endpoint = iot[0]['endpoint']
  453. Token = iot[0]['token_iot_number']
  454. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  455. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  456. # post请求url发布MQTT消息
  457. url = 'https://{}/topics/{}?qos={}'.format(endpoint, topic_name, qos)
  458. authorizer_name = 'Ansjer_Iot_Auth'
  459. signature = CommonService.rsa_sign(Token) # Token签名
  460. headers = {
  461. 'x-amz-customauthorizer-name': authorizer_name,
  462. 'Token': Token,
  463. 'x-amz-customauthorizer-signature': signature}
  464. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  465. if r.status_code == 200:
  466. res = r.json()
  467. if res['message'] == 'OK':
  468. return True
  469. return False
  470. else:
  471. return False
  472. except Exception as e:
  473. return False
  474. @staticmethod
  475. def rsa_sign(Token):
  476. # 私钥签名Token
  477. if not Token:
  478. return ''
  479. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  480. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  481. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  482. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  483. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  484. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  485. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  486. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  487. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  488. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  489. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  490. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  491. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  492. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  493. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  494. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  495. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  496. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  497. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  498. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  499. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  500. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  501. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  502. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  503. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  504. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  505. -----END RSA PRIVATE KEY-----'''
  506. # 使用密钥文件方式
  507. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  508. # private_key_file = open(private_key_file_path, 'r')
  509. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  510. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  511. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  512. # print('signature:', signature)
  513. return signature
  514. @staticmethod
  515. def get_payment_status_url(lang, payment_status):
  516. # 返回相应的支付状态url
  517. if lang == 'cn':
  518. file_name = 'success.html' if payment_status == 'success' else 'fail.html'
  519. else:
  520. file_name = 'en_success.html' if payment_status == 'success' else 'en_fail.html'
  521. pay_failed_url = "{}web/paid2/{}".format(SERVER_DOMAIN_SSL, file_name)
  522. return pay_failed_url
  523. # 根据uid查询序列号,存在则返回序列号,否则返uid
  524. @staticmethod
  525. def query_serial_with_uid(uid):
  526. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number')
  527. if device_info_qs.exists():
  528. serial_number = device_info_qs[0]['serial_number']
  529. if serial_number:
  530. return serial_number
  531. return uid
  532. # 根据序列号查询uid,存在则返回uid,否则返回序列号
  533. @staticmethod
  534. def query_uid_with_serial(serial_number):
  535. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('UID')
  536. if device_info_qs.exists():
  537. uid = device_info_qs[0]['UID']
  538. if uid:
  539. return uid
  540. return serial_number
  541. @staticmethod
  542. def get_full_serial_number(uid, serial_number, device_type):
  543. """
  544. 根据uid查询返回完整序列号
  545. @param uid: uid
  546. @param serial_number: 序列号
  547. @param device_type: 设备类型
  548. @return: full_serial_number
  549. """
  550. p2p_type = str(UIDModel.objects.filter(uid=uid).values('p2p_type')[0]['p2p_type'])
  551. # 设备类型转为16进制并补齐4位
  552. device_type = hex(device_type)[2:]
  553. device_type = (4 - len(device_type)) * '0' + device_type
  554. full_serial_number = serial_number + p2p_type + device_type
  555. return full_serial_number
  556. # 根据企业标识返回物品名
  557. @staticmethod
  558. def get_thing_name(company_mark, thing_name_suffix):
  559. if company_mark == '11A':
  560. return 'Ansjer_Device_' + thing_name_suffix
  561. elif company_mark == '11L':
  562. return 'LC_' + thing_name_suffix
  563. else:
  564. return thing_name_suffix
  565. @staticmethod
  566. def confirm_region_id(request):
  567. """
  568. 根据配置信息确定region_id
  569. @param request: 请求体
  570. @return: region_id
  571. """
  572. region_id = 3
  573. if CONFIG_INFO == CONFIG_TEST or CONFIG_INFO == CONFIG_CN:
  574. region_id = 1
  575. else: # 国外配置暂时通过ip确认
  576. ip = CommonService.get_ip_address(request)
  577. ipInfo = CommonService.getIpIpInfo(ip, 'CN')
  578. if ipInfo['country_code']:
  579. country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('region__id')
  580. if country_qs.exists():
  581. region_id = country_qs[0]['region__id']
  582. else: # 不存在默认返回美洲地区api
  583. region_qs = RegionModel.objects.filter(continent_code='NA').values("id")
  584. region_id = region_qs[0]['id']
  585. return region_id
  586. @staticmethod
  587. def verify_token_get_user_id(request_dict, request):
  588. """
  589. 认证token,获取user id
  590. @param request_dict: 请求参数
  591. @param request: 请求体
  592. @return: token_obj.code, token_obj.userID, response
  593. """
  594. try:
  595. token_obj = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  596. lang = request_dict.get('lang', None)
  597. response = ResponseObject(lang if lang else token_obj.lang)
  598. return token_obj.code, token_obj.userID, response
  599. except Exception as e:
  600. print(e)
  601. @staticmethod
  602. def cutting_time(start_time, end_time, time_unit):
  603. """
  604. 按时间单位切割时间段
  605. @param start_time: 开始时间
  606. @param end_time: 结束时间
  607. @param time_util: 时间单位
  608. @return: time_list 切割后的时间列表
  609. """
  610. time_list = []
  611. while True:
  612. if time_unit == 'day':
  613. temp_time = start_time + relativedelta(days=1)
  614. elif time_unit == 'week':
  615. temp_time = start_time + relativedelta(days=7)
  616. elif time_unit == 'month':
  617. temp_time = start_time + relativedelta(months=1)
  618. elif time_unit == 'quarter':
  619. temp_time = start_time + relativedelta(months=3)
  620. elif time_unit == 'year':
  621. temp_time = start_time + relativedelta(years=1)
  622. else:
  623. break
  624. if temp_time < end_time:
  625. time_list.append((start_time, temp_time))
  626. start_time = temp_time
  627. else:
  628. if (start_time, temp_time) not in time_list:
  629. time_list.append((start_time, end_time))
  630. break
  631. if not time_list:
  632. time_list = [(start_time, end_time)]
  633. return time_list