CommonService.py 31 KB

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