CommonService.py 31 KB

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