CommonService.py 28 KB

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