CommonService.py 29 KB

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