CommonService.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. @staticmethod
  311. def get_date_from_timestamp(timestamp, timezone_offset):
  312. # 创建时区对象
  313. tz = datetime.timezone(datetime.timedelta(hours=timezone_offset))
  314. # 使用时间戳创建 datetime 对象
  315. dt = datetime.datetime.fromtimestamp(timestamp, tz)
  316. # 格式化成 '%Y-%m-%d'
  317. formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S')
  318. return formatted_date
  319. # 计算N个月后的时间戳
  320. @staticmethod
  321. def calcMonthLater(addMonth, unix_timestamp=None):
  322. if unix_timestamp:
  323. now_year = time.localtime(unix_timestamp).tm_year
  324. now_month = time.localtime(unix_timestamp).tm_mon
  325. now_day = time.localtime(unix_timestamp).tm_mday
  326. now_hour = time.localtime(unix_timestamp).tm_hour
  327. now_min = time.localtime(unix_timestamp).tm_min
  328. now_second = time.localtime(unix_timestamp).tm_sec
  329. else:
  330. now_year = datetime.datetime.now().year
  331. now_month = datetime.datetime.now().month
  332. now_day = datetime.datetime.now().day
  333. now_hour = datetime.datetime.now().hour
  334. now_min = datetime.datetime.now().minute
  335. now_second = datetime.datetime.now().second
  336. for add in range(addMonth):
  337. if now_month == 12:
  338. now_year += 1
  339. now_month = 1
  340. else:
  341. now_month += 1
  342. timestamps = 0
  343. for is_format in range(4):
  344. try:
  345. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  346. .format(now_year=now_year, now_month=now_month, now_day=now_day, now_hour=now_hour,
  347. now_min=now_min, now_second=now_second)
  348. timestamps = CommonService.str_to_timestamp(date_format)
  349. except Exception as e:
  350. if str(e) == 'day is out of range for month':
  351. now_day = now_day - 1
  352. return timestamps
  353. @staticmethod
  354. def updateMac(mac: str):
  355. macArray = mac.split(':')
  356. macArray[0] = int(macArray[0], 16)
  357. macArray[1] = int(macArray[1], 16)
  358. macArray[2] = int(macArray[2], 16)
  359. first = int(macArray[5], 16)
  360. second = int(macArray[4], 16)
  361. three = int(macArray[3], 16)
  362. if first == 255 and second == 255 and three == 255:
  363. return None
  364. first += 1
  365. if first / 256 == 1:
  366. second += 1
  367. first = first % 256
  368. if second / 256 == 1:
  369. three += 1
  370. second = second % 256
  371. macArray[3] = three
  372. macArray[4] = second
  373. macArray[5] = first
  374. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  375. return tmp.upper()
  376. @staticmethod
  377. def encode_data_without_salt(content):
  378. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  379. @staticmethod
  380. def check_time_stamp_token(token, time_stamp):
  381. # 时间戳token校验
  382. if not all([token, time_stamp]):
  383. return False
  384. try:
  385. token = int(CommonService.decode_data(token))
  386. time_stamp = int(time_stamp)
  387. now_time = int(time.time())
  388. distance = now_time - time_stamp
  389. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  390. return False
  391. return True
  392. except Exception as e:
  393. print(e)
  394. return False
  395. @staticmethod
  396. def check_time_stamp_token_without_distance(time_stamp_token, time_stamp):
  397. """
  398. 用于没有RTC设备的时间戳token校验
  399. @param time_stamp: 时间戳
  400. @param time_stamp_token: 时间戳token
  401. @return: boolean True/False
  402. """
  403. if not all([time_stamp_token, time_stamp]):
  404. return False
  405. try:
  406. token = CommonService.decode_data(time_stamp_token)
  407. if token != time_stamp:
  408. return False
  409. return True
  410. except Exception as e:
  411. print(e)
  412. return False
  413. @staticmethod
  414. def req_publish_mqtt_msg(identification_code, topic_name, msg, qos=1):
  415. """
  416. 通用发布MQTT消息函数
  417. @param identification_code: 标识码
  418. @param topic_name: 主题名
  419. @param msg: 消息内容
  420. @param qos: mqtt qos等级
  421. @return: boolean
  422. """
  423. if not all([identification_code, topic_name]):
  424. return False
  425. if identification_code.endswith('11L'):
  426. thing_name = 'LC_' + identification_code
  427. else:
  428. thing_name = 'Ansjer_Device_' + identification_code
  429. try:
  430. # 获取数据组织将要请求的url
  431. iot = iotdeviceInfoModel.objects.filter(
  432. thing_name=thing_name).values(
  433. 'endpoint', 'token_iot_number')
  434. if not iot.exists():
  435. return False
  436. endpoint = iot[0]['endpoint']
  437. Token = iot[0]['token_iot_number']
  438. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  439. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  440. # post请求url发布MQTT消息
  441. url = 'https://{}/topics/{}?qos={}'.format(endpoint, topic_name, qos)
  442. authorizer_name = 'Ansjer_Iot_Auth'
  443. signature = CommonService.rsa_sign(Token) # Token签名
  444. headers = {
  445. 'x-amz-customauthorizer-name': authorizer_name,
  446. 'Token': Token,
  447. 'x-amz-customauthorizer-signature': signature}
  448. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  449. if r.status_code == 200:
  450. res = r.json()
  451. if res['message'] == 'OK':
  452. return True
  453. return False
  454. else:
  455. return False
  456. except Exception as e:
  457. return False
  458. @staticmethod
  459. def rsa_sign(Token):
  460. # 私钥签名Token
  461. if not Token:
  462. return ''
  463. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  464. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  465. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  466. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  467. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  468. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  469. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  470. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  471. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  472. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  473. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  474. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  475. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  476. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  477. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  478. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  479. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  480. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  481. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  482. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  483. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  484. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  485. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  486. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  487. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  488. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  489. -----END RSA PRIVATE KEY-----'''
  490. # 使用密钥文件方式
  491. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  492. # private_key_file = open(private_key_file_path, 'r')
  493. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  494. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  495. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  496. # print('signature:', signature)
  497. return signature
  498. @staticmethod
  499. def get_payment_status_url(lang, payment_status):
  500. # 返回相应的支付状态url
  501. if lang == 'cn':
  502. file_name = 'success.html' if payment_status == 'success' else 'fail.html'
  503. else:
  504. file_name = 'en_success.html' if payment_status == 'success' else 'en_fail.html'
  505. pay_failed_url = "{}web/paid2/{}".format(SERVER_DOMAIN_SSL, file_name)
  506. return pay_failed_url
  507. # 根据uid查询序列号,存在则返回序列号,否则返uid
  508. @staticmethod
  509. def query_serial_with_uid(uid):
  510. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number')
  511. if device_info_qs.exists():
  512. serial_number = device_info_qs[0]['serial_number']
  513. if serial_number:
  514. return serial_number
  515. return uid
  516. # 根据序列号查询uid,存在则返回uid,否则返回序列号
  517. @staticmethod
  518. def query_uid_with_serial(serial_number):
  519. device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('UID')
  520. if device_info_qs.exists():
  521. uid = device_info_qs[0]['UID']
  522. if uid:
  523. return uid
  524. return serial_number
  525. @staticmethod
  526. def get_full_serial_number(uid, serial_number, device_type):
  527. """
  528. 根据uid查询返回完整序列号
  529. @param uid: uid
  530. @param serial_number: 9位序列号
  531. @param device_type: 设备类型
  532. @return: full_serial_number
  533. """
  534. p2p_type = str(UIDModel.objects.filter(uid=uid).values('p2p_type')[0]['p2p_type'])
  535. # 设备类型转为16进制并补齐4位
  536. device_type = hex(device_type)[2:]
  537. device_type = (4 - len(device_type)) * '0' + device_type
  538. full_serial_number = serial_number + p2p_type + device_type
  539. return full_serial_number
  540. # 根据企业标识返回物品名
  541. @staticmethod
  542. def get_thing_name(company_mark, thing_name_suffix):
  543. if company_mark == '11A':
  544. return 'Ansjer_Device_' + thing_name_suffix
  545. elif company_mark == '11L':
  546. return 'LC_' + thing_name_suffix
  547. else:
  548. return thing_name_suffix
  549. @staticmethod
  550. def confirm_region_id(region_country=0):
  551. """
  552. 根据配置信息和国家确定region_id
  553. @param region_country: 用户国家id
  554. @return: region_id
  555. """
  556. region_id = 3
  557. if CONFIG_INFO == CONFIG_US: # 美洲
  558. # 中东地区国家id
  559. if region_country in ME_COUNTRY_ID_LIST:
  560. region_id = 6
  561. # 东亚地区国家id
  562. elif region_country in EA_COUNTRY_ID_LIST:
  563. region_id = 2
  564. elif CONFIG_INFO == CONFIG_EUR: # 欧洲
  565. region_id = 4
  566. elif CONFIG_INFO == CONFIG_CN: # 中国
  567. region_id = 1
  568. elif CONFIG_INFO == CONFIG_TEST: # 测试
  569. region_id = 5
  570. return region_id
  571. @staticmethod
  572. def verify_token_get_user_id(request_dict, request):
  573. """
  574. 认证token,获取user id
  575. @param request_dict: 请求参数
  576. @param request: 请求体
  577. @return: token_obj.code, token_obj.userID, response
  578. """
  579. try:
  580. token_obj = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  581. lang = request_dict.get('lang', None)
  582. response = ResponseObject(lang if lang else token_obj.lang)
  583. return token_obj.code, token_obj.userID, response
  584. except Exception as e:
  585. print(e)
  586. return 309, None, None
  587. @staticmethod
  588. def cutting_time(start_time, end_time, time_unit):
  589. """
  590. 按时间单位切割时间段
  591. @param start_time: 开始时间
  592. @param end_time: 结束时间
  593. @param time_unit: 时间单位
  594. @return: time_list 切割后的时间列表
  595. """
  596. time_list = []
  597. while True:
  598. if time_unit == 'day':
  599. temp_time = start_time + relativedelta(days=1)
  600. elif time_unit == 'week':
  601. temp_time = start_time + relativedelta(days=7)
  602. elif time_unit == 'month':
  603. temp_time = start_time + relativedelta(months=1)
  604. elif time_unit == 'quarter':
  605. temp_time = start_time + relativedelta(months=3)
  606. elif time_unit == 'year':
  607. temp_time = start_time + relativedelta(years=1)
  608. else:
  609. break
  610. if temp_time < end_time:
  611. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  612. CommonService.str_to_timestamp(temp_time.strftime('%Y-%m-%d %H:%M:%S')))
  613. time_list.append(time_tuple)
  614. start_time = temp_time
  615. else:
  616. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  617. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  618. if time_tuple not in time_list:
  619. time_list.append(time_tuple)
  620. break
  621. if not time_list:
  622. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  623. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  624. time_list = [time_tuple]
  625. return time_list
  626. @staticmethod
  627. def cutting_time_stamp(start_time, end_time):
  628. """
  629. 按天切割时间段
  630. @param start_time: 开始时间
  631. @param end_time: 结束时间
  632. @return: time_list 切割后的时间列表
  633. """
  634. time_list = []
  635. while True:
  636. mid_time = datetime.datetime(start_time.year, start_time.month, start_time.day) + relativedelta(days=1)
  637. if mid_time < end_time:
  638. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  639. CommonService.str_to_timestamp(mid_time.strftime('%Y-%m-%d %H:%M:%S')))
  640. time_list.append(time_tuple)
  641. start_time = mid_time
  642. else:
  643. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  644. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  645. if time_tuple not in time_list:
  646. time_list.append(time_tuple)
  647. break
  648. if not time_list:
  649. time_tuple = (CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S')),
  650. CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S')))
  651. time_list = [time_tuple]
  652. return time_list
  653. @staticmethod
  654. def get_domain_name():
  655. """
  656. 获取域名
  657. @return: domain_name_list 域名列表
  658. """
  659. if CONFIG_INFO == CONFIG_TEST:
  660. domain_name_list = [SERVER_DOMAIN_TEST[:-1]]
  661. elif CONFIG_INFO == CONFIG_CN or CONFIG_INFO == CONFIG_US or CONFIG_INFO == CONFIG_EUR:
  662. domain_name_list = [SERVER_DOMAIN_US[:-1], SERVER_DOMAIN_CN[:-1], SERVER_DOMAIN_EUR[:-1]]
  663. else:
  664. domain_name_list = []
  665. return domain_name_list
  666. @staticmethod
  667. def get_orders_domain_name_list():
  668. """
  669. 获取其他服务器域名列表
  670. @return: orders_domain_name_list 其他服务器域名列表
  671. """
  672. orders_domain_name_list = SERVER_DOMAIN_LIST
  673. if CONFIG_INFO == CONFIG_TEST:
  674. orders_domain_name_list = [SERVER_DOMAIN_CN, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR]
  675. elif CONFIG_INFO == CONFIG_CN:
  676. orders_domain_name_list = [SERVER_DOMAIN_TEST, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR]
  677. elif CONFIG_INFO == CONFIG_US:
  678. orders_domain_name_list = [SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_EUR]
  679. elif CONFIG_INFO == CONFIG_EUR:
  680. orders_domain_name_list = [SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_US]
  681. return orders_domain_name_list
  682. @staticmethod
  683. def list_sort(e):
  684. """
  685. 列表排序
  686. @param e: 列表元素
  687. """
  688. return sorted(e, key=lambda item: -item['count'])
  689. @staticmethod
  690. def list_sort_v2(e, order_by):
  691. """
  692. 列表排序
  693. @param e: 列表元素
  694. @param order_by: 排序对象
  695. """
  696. return sorted(e, key=lambda item: item[order_by], reverse=True)
  697. @staticmethod
  698. def Package_Type(order_type, content):
  699. """
  700. 套餐类型
  701. """
  702. if order_type == 0:
  703. content = content + '(' + '云存' + ')'
  704. return content
  705. elif order_type == 1:
  706. content = content + '(' + 'AI' + ')'
  707. return content
  708. elif order_type == 2:
  709. pass
  710. elif order_type == 4:
  711. content = content + '(' + '云盘' + ')'
  712. return content
  713. @staticmethod
  714. def is_cloud_device(ucode, device_type):
  715. """
  716. 设备是否支持云存
  717. @param ucode: 设备版本
  718. @param device_type: 设备类型
  719. """
  720. if len(ucode) > 4:
  721. number = ucode[-4]
  722. else:
  723. return False
  724. device_type_qs = AppDeviceType.objects.filter(type=device_type).values('model')
  725. model = device_type_qs[0]['model'] if device_type_qs.exists() else ''
  726. # 判断设备是否为ipc设备和是否支持云存
  727. if model == 2 and number in ['4', '5']:
  728. return True
  729. return False
  730. @staticmethod
  731. def negative_number_judgment(number_list):
  732. """
  733. 判断正负数
  734. @param number_list: float或int类型列表
  735. """
  736. if any(i < 0 for i in number_list):
  737. return False
  738. else:
  739. return True
  740. @staticmethod
  741. def check_password(password1, password2):
  742. """
  743. 比较密码
  744. @param 返回True or False
  745. """
  746. return constant_time_compare(password1, password2)
  747. @staticmethod
  748. def compare_version_number(version_number, version_number_list):
  749. """
  750. 比对版本号大小
  751. @param version_number: 版本号
  752. @param version_number_list: 版本号列表
  753. """
  754. version_list = []
  755. input_version = LooseVersion(version_number)
  756. for version in version_number_list:
  757. version = LooseVersion(version)
  758. if input_version >= version:
  759. version_list.append(version)
  760. else:
  761. continue
  762. return version_list
  763. @staticmethod
  764. def convert_to_timestamp(timezone_offset, time_string):
  765. """
  766. 时间字符串转为时间戳
  767. @param timezone_offset: 时区
  768. @param time_string: 时间字符串
  769. @return: timestamp
  770. """
  771. datetime_obj = datetime.datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')
  772. # 创建一个表示指定时区的timedelta对象
  773. utc_offset = datetime.timedelta(hours=timezone_offset)
  774. # 调整时区
  775. datetime_obj = datetime_obj - utc_offset
  776. # datetime.datetime对象 -> str
  777. time_str_utc = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
  778. timestamp = calendar.timegm(time.strptime(time_str_utc, '%Y-%m-%d %H:%M:%S'))
  779. return timestamp
  780. @staticmethod
  781. def get_uid_by_serial_number(serial_number):
  782. """
  783. 根据序列号获取绑定uid
  784. @param serial_number: 9位序列号
  785. @return: uid信息
  786. """
  787. c_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number=serial_number[0:6])
  788. if not c_serial_qs.exists():
  789. return serial_number
  790. c_serial_info = c_serial_qs.values('uid__uid')
  791. return c_serial_info[0]['uid__uid']
  792. @staticmethod
  793. def get_serial_number_by_uid(uid):
  794. """
  795. 根据序列号获取绑定uid
  796. @param uid: uid
  797. @return: uid信息
  798. """
  799. c_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=uid)
  800. if not c_serial_qs.exists():
  801. return uid
  802. c_serial_qs = c_serial_qs.annotate(mark=F('company_serial__company__mark'),
  803. serial_number=F('company_serial__serial_number'))
  804. c_serial_info = c_serial_qs.values('mark', 'serial_number')
  805. return c_serial_info[0]['serial_number'] + c_serial_info[0]['mark']
  806. @staticmethod
  807. def get_user_tz(user_id):
  808. """
  809. 获取用户时区
  810. @param user_id: 用户id
  811. @return: tz
  812. """
  813. # 从gateway_push表查询时区
  814. gateway_push_qs = GatewayPush.objects.filter(user_id=user_id).order_by('-id').first()
  815. if gateway_push_qs is None:
  816. tz = 0.00
  817. else:
  818. # 截掉.00然后转为浮点型
  819. tz = float(gateway_push_qs.tz[:-3])
  820. return tz
  821. @staticmethod
  822. def update_alexa_events(data_list):
  823. """
  824. 请求Alexa服务器更新事件网关
  825. 邮件提醒捕获的异常
  826. @param data_list: 数据列表
  827. @return:
  828. """
  829. try:
  830. data_list = json.dumps(data_list)
  831. data = {'data_list': data_list}
  832. url = ALEXA_DOMAIN + 'deviceStatus/addOrUpdateV2'
  833. requests.post(url, data=data, timeout=30)
  834. except Exception as e:
  835. S3Email().faEmail(
  836. '请求Alexa服务器更新事件网关异常:error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)),
  837. 'servers@ansjer.com')
  838. pass