CommonService.py 32 KB

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