CommonService.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. import base64
  2. import datetime
  3. import ipdb
  4. import time
  5. from base64 import encodebytes
  6. from pathlib import Path
  7. from random import Random
  8. from distutils.version import LooseVersion
  9. import OpenSSL.crypto as ct
  10. import requests
  11. import simplejson as json
  12. from dateutil.relativedelta import relativedelta
  13. from django.core import serializers
  14. from django.utils import timezone
  15. from pyipip import IPIPDatabase
  16. from Ansjer.config import BASE_DIR, SERVER_DOMAIN_SSL, CONFIG_INFO, CONFIG_TEST, CONFIG_CN, SERVER_DOMAIN_TEST, \
  17. SERVER_DOMAIN_CN, SERVER_DOMAIN_US, CONFIG_US, CONFIG_EUR, SERVER_DOMAIN_LIST, SERVER_DOMAIN_EUR
  18. from Controller.CheckUserData import RandomStr
  19. from Model.models import iotdeviceInfoModel, Device_Info, 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. # 添加模糊搜索
  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. @staticmethod
  35. def qs_to_dict(query_set):
  36. # 格式化query_set转dict
  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 encode_data(content, start=1, end=4):
  240. """
  241. 数据加密
  242. @param content: 数据内容
  243. @param start: 起始长度
  244. @param end: 结束长度
  245. @return content: 加密的数据
  246. """
  247. if not content:
  248. return ''
  249. for i in range(start, end):
  250. length = end - i
  251. content = RandomStr(length, False) + content + RandomStr(length, False)
  252. content = base64.b64encode(str(content).encode('utf-8')).decode('utf8')
  253. return content
  254. @staticmethod
  255. def decode_data(content, start=1, end=4):
  256. """
  257. 数据解密
  258. @param content: 数据内容
  259. @param start: 起始长度
  260. @param end: 结束长度
  261. @return content: 解密的数据
  262. """
  263. if not content:
  264. return ''
  265. for i in range(start, end):
  266. content = base64.b64decode(content)
  267. content = content.decode('utf-8')
  268. content = content[i:-i]
  269. return content
  270. # 把格式化时间转换成时间戳
  271. @staticmethod
  272. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  273. if str_time:
  274. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  275. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  276. return int(result)
  277. return int(time.time())
  278. # 把时间戳转换成格式化
  279. @staticmethod
  280. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  281. if timestamp:
  282. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  283. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  284. return result
  285. else:
  286. return time.strptime(format)
  287. # 计算N个月后的时间戳
  288. @staticmethod
  289. def calcMonthLater(addMonth, unix_timestamp=None):
  290. if unix_timestamp:
  291. now_year = time.localtime(unix_timestamp).tm_year
  292. now_month = time.localtime(unix_timestamp).tm_mon
  293. now_day = time.localtime(unix_timestamp).tm_mday
  294. now_hour = time.localtime(unix_timestamp).tm_hour
  295. now_min = time.localtime(unix_timestamp).tm_min
  296. now_second = time.localtime(unix_timestamp).tm_sec
  297. else:
  298. now_year = datetime.datetime.now().year
  299. now_month = datetime.datetime.now().month
  300. now_day = datetime.datetime.now().day
  301. now_hour = datetime.datetime.now().hour
  302. now_min = datetime.datetime.now().minute
  303. now_second = datetime.datetime.now().second
  304. for add in range(addMonth):
  305. if now_month == 12:
  306. now_year += 1
  307. now_month = 1
  308. else:
  309. now_month += 1
  310. timestamps = 0
  311. for is_format in range(4):
  312. try:
  313. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  314. .format(now_year=now_year, now_month=now_month, now_day=now_day, now_hour=now_hour,
  315. now_min=now_min, now_second=now_second)
  316. timestamps = CommonService.str_to_timestamp(date_format)
  317. except Exception as e:
  318. if str(e) == 'day is out of range for month':
  319. now_day = now_day - 1
  320. return timestamps
  321. @staticmethod
  322. def updateMac(mac: str):
  323. macArray = mac.split(':')
  324. macArray[0] = int(macArray[0], 16)
  325. macArray[1] = int(macArray[1], 16)
  326. macArray[2] = int(macArray[2], 16)
  327. first = int(macArray[5], 16)
  328. second = int(macArray[4], 16)
  329. three = int(macArray[3], 16)
  330. if first == 255 and second == 255 and three == 255:
  331. return None
  332. first += 1
  333. if first / 256 == 1:
  334. second += 1
  335. first = first % 256
  336. if second / 256 == 1:
  337. three += 1
  338. second = second % 256
  339. macArray[3] = three
  340. macArray[4] = second
  341. macArray[5] = first
  342. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  343. return tmp.upper()
  344. @staticmethod
  345. def encode_data_without_salt(content):
  346. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  347. @staticmethod
  348. def check_time_stamp_token(token, time_stamp):
  349. # 时间戳token校验
  350. if not all([token, time_stamp]):
  351. return False
  352. try:
  353. token = int(CommonService.decode_data(token))
  354. time_stamp = int(time_stamp)
  355. now_time = int(time.time())
  356. distance = now_time - time_stamp
  357. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  358. return False
  359. return True
  360. except Exception as e:
  361. print(e)
  362. return False
  363. @staticmethod
  364. def check_time_stamp_token_without_distance(time_stamp_token, time_stamp):
  365. """
  366. 用于没有RTC设备的时间戳token校验
  367. @param time_stamp: 时间戳
  368. @param time_stamp_token: 时间戳token
  369. @return: boolean True/False
  370. """
  371. if not all([time_stamp_token, time_stamp]):
  372. return False
  373. try:
  374. token = CommonService.decode_data(time_stamp_token)
  375. if token != time_stamp:
  376. return False
  377. return True
  378. except Exception as e:
  379. print(e)
  380. return False
  381. @staticmethod
  382. def req_publish_mqtt_msg(identification_code, topic_name, msg, qos=1):
  383. """
  384. 通用发布MQTT消息函数
  385. @param identification_code: 标识码
  386. @param topic_name: 主题名
  387. @param msg: 消息内容
  388. @param qos: mqtt qos等级
  389. @return: boolean
  390. """
  391. if not all([identification_code, topic_name]):
  392. return False
  393. if identification_code.endswith('11L'):
  394. thing_name = 'LC_' + identification_code
  395. else:
  396. thing_name = 'Ansjer_Device_' + identification_code
  397. try:
  398. # 获取数据组织将要请求的url
  399. iot = iotdeviceInfoModel.objects.filter(
  400. thing_name=thing_name).values(
  401. 'endpoint', 'token_iot_number')
  402. if not iot.exists():
  403. return False
  404. endpoint = iot[0]['endpoint']
  405. Token = iot[0]['token_iot_number']
  406. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  407. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  408. # post请求url发布MQTT消息
  409. url = 'https://{}/topics/{}?qos={}'.format(endpoint, topic_name, qos)
  410. authorizer_name = 'Ansjer_Iot_Auth'
  411. signature = CommonService.rsa_sign(Token) # Token签名
  412. headers = {
  413. 'x-amz-customauthorizer-name': authorizer_name,
  414. 'Token': Token,
  415. 'x-amz-customauthorizer-signature': signature}
  416. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  417. if r.status_code == 200:
  418. res = r.json()
  419. if res['message'] == 'OK':
  420. return True
  421. return False
  422. else:
  423. return False
  424. except Exception as e:
  425. return False
  426. @staticmethod
  427. def rsa_sign(Token):
  428. # 私钥签名Token
  429. if not Token:
  430. return ''
  431. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  432. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  433. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  434. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  435. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  436. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  437. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  438. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  439. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  440. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  441. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  442. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  443. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  444. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  445. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  446. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  447. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  448. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  449. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  450. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  451. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  452. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  453. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  454. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  455. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  456. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  457. -----END RSA PRIVATE KEY-----'''
  458. # 使用密钥文件方式
  459. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  460. # private_key_file = open(private_key_file_path, 'r')
  461. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  462. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  463. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  464. # print('signature:', signature)
  465. return signature
  466. @staticmethod
  467. def get_payment_status_url(lang, payment_status):
  468. # 返回相应的支付状态url
  469. if lang == 'cn':
  470. file_name = 'success.html' if payment_status == 'success' else 'fail.html'
  471. else:
  472. file_name = 'en_success.html' if payment_status == 'success' else 'en_fail.html'
  473. pay_failed_url = "{}web/paid2/{}".format(SERVER_DOMAIN_SSL, file_name)
  474. return pay_failed_url
  475. # 根据uid查询序列号,存在则返回序列号,否则返uid
  476. @staticmethod
  477. def query_serial_with_uid(uid):
  478. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number')
  479. if device_info_qs.exists():
  480. serial_number = device_info_qs[0]['serial_number']
  481. if serial_number:
  482. return serial_number
  483. return uid
  484. # 根据序列号查询uid,存在则返回uid,否则返回序列号
  485. @staticmethod
  486. def query_uid_with_serial(serial_number):
  487. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('UID')
  488. if device_info_qs.exists():
  489. uid = device_info_qs[0]['UID']
  490. if uid:
  491. return uid
  492. return serial_number
  493. @staticmethod
  494. def get_full_serial_number(uid, serial_number, device_type):
  495. """
  496. 根据uid查询返回完整序列号
  497. @param uid: uid
  498. @param serial_number: 序列号
  499. @param device_type: 设备类型
  500. @return: full_serial_number
  501. """
  502. p2p_type = str(UIDModel.objects.filter(uid=uid).values('p2p_type')[0]['p2p_type'])
  503. # 设备类型转为16进制并补齐4位
  504. device_type = hex(device_type)[2:]
  505. device_type = (4 - len(device_type)) * '0' + device_type
  506. full_serial_number = serial_number + p2p_type + device_type
  507. return full_serial_number
  508. # 根据企业标识返回物品名
  509. @staticmethod
  510. def get_thing_name(company_mark, thing_name_suffix):
  511. if company_mark == '11A':
  512. return 'Ansjer_Device_' + thing_name_suffix
  513. elif company_mark == '11L':
  514. return 'LC_' + thing_name_suffix
  515. else:
  516. return thing_name_suffix
  517. @staticmethod
  518. def confirm_region_id():
  519. """
  520. 根据配置信息确定region_id
  521. @return: region_id
  522. """
  523. region_id = 3
  524. if CONFIG_INFO == CONFIG_US: # 美洲
  525. region_id = 3
  526. elif CONFIG_INFO == CONFIG_EUR: # 欧洲
  527. region_id = 4
  528. elif CONFIG_INFO == CONFIG_CN: # 中国
  529. region_id = 1
  530. elif CONFIG_INFO == CONFIG_TEST: # 测试
  531. region_id = 5
  532. return region_id
  533. @staticmethod
  534. def verify_token_get_user_id(request_dict, request):
  535. """
  536. 认证token,获取user id
  537. @param request_dict: 请求参数
  538. @param request: 请求体
  539. @return: token_obj.code, token_obj.userID, response
  540. """
  541. try:
  542. token_obj = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  543. lang = request_dict.get('lang', None)
  544. response = ResponseObject(lang if lang else token_obj.lang)
  545. return token_obj.code, token_obj.userID, response
  546. except Exception as e:
  547. print(e)
  548. return 309, None, None
  549. @staticmethod
  550. def cutting_time(start_time, end_time, time_unit):
  551. """
  552. 按时间单位切割时间段
  553. @param start_time: 开始时间
  554. @param end_time: 结束时间
  555. @param time_unit: 时间单位
  556. @return: time_list 切割后的时间列表
  557. """
  558. time_list = []
  559. while True:
  560. if time_unit == 'day':
  561. temp_time = start_time + relativedelta(days=1)
  562. elif time_unit == 'week':
  563. temp_time = start_time + relativedelta(days=7)
  564. elif time_unit == 'month':
  565. temp_time = start_time + relativedelta(months=1)
  566. elif time_unit == 'quarter':
  567. temp_time = start_time + relativedelta(months=3)
  568. elif time_unit == 'year':
  569. temp_time = start_time + relativedelta(years=1)
  570. else:
  571. break
  572. if temp_time < end_time:
  573. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  574. CommonService.str_to_timestamp(temp_time.strftime('%Y-%m-%d %H:%M:%S')))
  575. time_list.append(time_tuple)
  576. start_time = temp_time
  577. else:
  578. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  579. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  580. if time_tuple not in time_list:
  581. time_list.append(time_tuple)
  582. break
  583. if not time_list:
  584. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  585. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  586. time_list = [time_tuple]
  587. return time_list
  588. @staticmethod
  589. def cutting_time_stamp(start_time, end_time):
  590. """
  591. 按天切割时间段
  592. @param start_time: 开始时间
  593. @param end_time: 结束时间
  594. @return: time_list 切割后的时间列表
  595. """
  596. time_list = []
  597. while True:
  598. mid_time = datetime.datetime(start_time.year, start_time.month, start_time.day)+relativedelta(days=1)
  599. if mid_time < end_time:
  600. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  601. CommonService.str_to_timestamp(mid_time.strftime('%Y-%m-%d %H:%M:%S')))
  602. time_list.append(time_tuple)
  603. start_time = mid_time
  604. else:
  605. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  606. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  607. if time_tuple not in time_list:
  608. time_list.append(time_tuple)
  609. break
  610. if not time_list:
  611. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  612. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  613. time_list = [time_tuple]
  614. return time_list
  615. @staticmethod
  616. def get_domain_name():
  617. """
  618. 获取域名
  619. @return: domain_name_list 域名列表
  620. """
  621. if CONFIG_INFO == CONFIG_TEST:
  622. domain_name_list = [SERVER_DOMAIN_TEST[:-1]]
  623. elif CONFIG_INFO == CONFIG_CN or CONFIG_INFO == CONFIG_US or CONFIG_INFO == CONFIG_EUR:
  624. domain_name_list = [SERVER_DOMAIN_US[:-1], SERVER_DOMAIN_CN[:-1], SERVER_DOMAIN_EUR[:-1]]
  625. else:
  626. domain_name_list = []
  627. return domain_name_list
  628. @staticmethod
  629. def get_orders_domain_name_list():
  630. """
  631. 获取其他服务器域名列表
  632. @return: orders_domain_name_list 其他服务器域名列表
  633. """
  634. orders_domain_name_list = SERVER_DOMAIN_LIST
  635. if CONFIG_INFO == CONFIG_TEST:
  636. orders_domain_name_list = [SERVER_DOMAIN_CN, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR]
  637. elif CONFIG_INFO == CONFIG_CN:
  638. orders_domain_name_list = [SERVER_DOMAIN_TEST, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR]
  639. elif CONFIG_INFO == CONFIG_US:
  640. orders_domain_name_list = [SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_EUR]
  641. elif CONFIG_INFO == CONFIG_EUR:
  642. orders_domain_name_list = [SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_US]
  643. return orders_domain_name_list
  644. @staticmethod
  645. def list_sort(e):
  646. """
  647. 列表排序
  648. @param e: 列表元素
  649. """
  650. return sorted(e, key=lambda item: -item['count'])
  651. @staticmethod
  652. def Package_Type(order_type, content):
  653. """
  654. 套餐类型
  655. """
  656. if order_type == 0:
  657. content = content + '(' + '云存' + ')'
  658. return content
  659. elif order_type == 1:
  660. content = content + '(' + 'AI' + ')'
  661. return content
  662. elif order_type == 2:
  663. pass
  664. @staticmethod
  665. def negative_number_judgment(number_list):
  666. """
  667. 判断正负数
  668. @param number_list: float或int类型列表
  669. """
  670. if any(i < 0 for i in number_list):
  671. return False
  672. else:
  673. return True
  674. @staticmethod
  675. def compare_version_number(version_number, version_number_list):
  676. """
  677. 比对版本号大小
  678. @param version_number: 版本号
  679. @param version_number_list: 版本号列表
  680. """
  681. version_list = []
  682. input_version = LooseVersion(version_number)
  683. for version in version_number_list:
  684. version = LooseVersion(version)
  685. if input_version >= version:
  686. version_list.append(version)
  687. else:
  688. continue
  689. return version_list