CommonService.py 27 KB

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