CommonService.py 27 KB

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