CommonService.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. # -*- coding: utf-8 -*-
  2. import base64
  3. import datetime
  4. import os
  5. import time
  6. import hashlib
  7. from pathlib import Path
  8. from random import Random
  9. import ipdb
  10. import requests
  11. import simplejson as json
  12. from boto3 import Session
  13. from django.core import serializers
  14. from django.utils import timezone
  15. from pyipip import IPIPDatabase
  16. import OpenSSL.crypto as ct
  17. from base64 import encodebytes
  18. from AnsjerPush.config import BASE_DIR, ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, PUSH_BUCKET
  19. from Model.models import iotdeviceInfoModel
  20. # 复用性且公用较高封装代码在这
  21. class CommonService:
  22. # 添加模糊搜索
  23. @staticmethod
  24. def get_kwargs(data={}):
  25. kwargs = {}
  26. for (k, v) in data.items():
  27. if v is not None and v != u'':
  28. kwargs[k + '__icontains'] = v
  29. return kwargs
  30. # 定义静态方法
  31. # 格式化query_set转dict
  32. @staticmethod
  33. def qs_to_dict(query_set):
  34. sqlJSON = serializers.serialize('json', query_set)
  35. sqlList = json.loads(sqlJSON)
  36. sqlDict = dict(zip(["datas"], [sqlList]))
  37. return sqlDict
  38. # 获取文件大小
  39. @staticmethod
  40. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  41. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  42. # path = Path() / 'D:/TestServer/123444.mp4'
  43. path = Path() / file_path
  44. size = path.stat().st_size
  45. mb_size = 0.0
  46. if suffix_type == 'MB':
  47. mb_size = size / 1024.0 / 1024.0
  48. if decimal_point != 0:
  49. mb_size = round(mb_size, decimal_point)
  50. return mb_size
  51. @staticmethod
  52. def get_param_flag(data=[]):
  53. # print(data)
  54. flag = True
  55. for v in data:
  56. if v is None:
  57. flag = False
  58. break
  59. return flag
  60. @staticmethod
  61. def get_ip_address(request):
  62. """
  63. 获取ip地址
  64. :param request:
  65. :return:
  66. """
  67. try:
  68. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  69. clientIP = real_ip.split(",")[0]
  70. except:
  71. try:
  72. clientIP = request.META['REMOTE_ADDR']
  73. except Exception as e:
  74. clientIP = ''
  75. return clientIP
  76. # @获取一天每个小时的datetime.datetime
  77. @staticmethod
  78. def getTimeDict(times):
  79. time_dict = {}
  80. t = 0
  81. for x in range(24):
  82. if x < 10:
  83. x = '0' + str(x)
  84. else:
  85. x = str(x)
  86. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  87. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  88. t += 1
  89. return time_dict
  90. # 根据ip获取地址
  91. @staticmethod
  92. def getAddr(ip):
  93. base_dir = BASE_DIR
  94. # ip数据库
  95. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  96. addr = db.lookup(ip)
  97. ts = addr.split('\t')[0]
  98. return ts
  99. # 通过ip检索ipip指定信息 lang为CN或EN
  100. @staticmethod
  101. def getIpIpInfo(ip, lang, update=False):
  102. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  103. db = ipdb.City(ipbd_dir)
  104. if update:
  105. from var_dump import var_dump
  106. var_dump('is_update')
  107. rr = db.reload(ipbd_dir)
  108. var_dump(rr)
  109. info = db.find_map(ip, lang)
  110. return info
  111. @staticmethod
  112. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  113. if μs == True:
  114. if getUser == True:
  115. timeID = str(round(time.time() * 1000000))
  116. userID = timeID + userPhone
  117. return userID
  118. else:
  119. if setOTAID == False:
  120. timeID = str(round(time.time() * 1000000))
  121. ID = userPhone + timeID
  122. return ID
  123. else:
  124. timeID = str(round(time.time() * 1000000))
  125. eID = '13800' + timeID + '138000'
  126. return eID
  127. else:
  128. if getUser == True:
  129. timeID = str(round(time.time() * 1000))
  130. userID = timeID + userPhone
  131. return userID
  132. else:
  133. if setOTAID == False:
  134. timeID = str(round(time.time() * 1000))
  135. ID = userPhone + timeID
  136. return ID
  137. else:
  138. timeID = str(round(time.time() * 1000))
  139. eID = '13800' + timeID + '138000'
  140. return eID
  141. # 生成随机数
  142. @staticmethod
  143. def RandomStr(randomlength=8, number=True):
  144. str = ''
  145. if number == False:
  146. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  147. 'tUuVvWwXxYyZz0123456789'
  148. else:
  149. characterSet = '0123456789'
  150. length = len(characterSet) - 1
  151. random = Random()
  152. for index in range(randomlength):
  153. str += characterSet[random.randint(0, length)]
  154. return str
  155. # 生成订单好
  156. @staticmethod
  157. def createOrderID():
  158. random_id = CommonService.RandomStr(6, True)
  159. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  160. print('orderID:')
  161. print(order_id)
  162. return order_id
  163. # qs转换list datetime处理
  164. @staticmethod
  165. def qs_to_list(qs):
  166. res = []
  167. # print(qs)
  168. for ps in qs:
  169. if 'add_time' in ps:
  170. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  171. if 'update_time' in ps:
  172. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  173. if 'end_time' in ps:
  174. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  175. if 'data_joined' in ps:
  176. if ps['data_joined']:
  177. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  178. else:
  179. ps['data_joined'] = ''
  180. res.append(ps)
  181. return res
  182. # 获取当前时间
  183. @staticmethod
  184. def get_now_time_str(n_time, tz, lang):
  185. print(n_time)
  186. print(tz)
  187. print(lang)
  188. try:
  189. tz = tz.replace(':', '.')
  190. n_time = int(n_time) + 3600 * float(tz)
  191. except:
  192. n_time = int(n_time)
  193. if lang == 'cn':
  194. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  195. else:
  196. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  197. @staticmethod
  198. def app_log_log(uid='None', tz='0'):
  199. file_path = '/'.join((BASE_DIR, 'static/app_log.log'))
  200. file = open(file_path, 'a+')
  201. file.write("uid:" + uid + "; " + "; tz:" + tz)
  202. file.write('\n')
  203. file.flush()
  204. file.close()
  205. @classmethod
  206. def upload_images(cls, file_dict, dir_path):
  207. """
  208. 上传图片到S3,并删除本地图片
  209. @param file_dict: S3图片路径
  210. @param dir_path: 本地图片路径
  211. @return: boolean
  212. """
  213. try:
  214. s3 = Session(
  215. aws_access_key_id=ACCESS_KEY_ID,
  216. aws_secret_access_key=SECRET_ACCESS_KEY,
  217. region_name=REGION_NAME
  218. ).resource('s3')
  219. for file_path, upload_path in file_dict.items():
  220. upload_data = open(file_path, 'rb')
  221. s3.Bucket(PUSH_BUCKET).put_object(Key=upload_path, Body=upload_data)
  222. # 删除图片
  223. cls.del_path(dir_path)
  224. cls.del_path(dir_path + '.jpg')
  225. return True
  226. except Exception as e:
  227. print(repr(e))
  228. return False
  229. @classmethod
  230. def del_path(cls, path):
  231. """
  232. 删除目录文件
  233. @param path: 文件路径
  234. @return: None
  235. """
  236. if not os.path.exists(path):
  237. return
  238. if os.path.isfile(path):
  239. os.remove(path)
  240. else:
  241. items = os.listdir(path)
  242. for f in items:
  243. c_path = os.path.join(path, f)
  244. if os.path.isdir(c_path):
  245. cls.del_path(c_path)
  246. else:
  247. os.remove(c_path)
  248. os.rmdir(path)
  249. @staticmethod
  250. def getMD5Sign(data, key):
  251. '''
  252. 魅族MD5签名
  253. '''
  254. dataList = []
  255. for k in sorted(data):
  256. dataList.append("%s=%s" % (k, data[k]))
  257. data = (''.join(dataList))
  258. data = data + key
  259. sign = hashlib.md5(data.encode(encoding="utf-8")).hexdigest()
  260. return sign
  261. @staticmethod
  262. def check_time_stamp_token(token, time_stamp):
  263. # 时间戳token校验
  264. if not all([token, time_stamp]):
  265. return False
  266. try:
  267. token = int(CommonService.decode_data(token))
  268. time_stamp = int(time_stamp)
  269. now_time = int(time.time())
  270. distance = now_time - time_stamp
  271. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  272. return False
  273. return True
  274. except Exception as e:
  275. print(e)
  276. return False
  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. @staticmethod
  294. def timestamp_to_str(timestamp):
  295. """
  296. 时间戳转时间字符串
  297. @param timestamp: 时间戳
  298. @return time_str: 时间字符串
  299. """
  300. struct_time = time.localtime(timestamp)
  301. time_str = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
  302. return time_str
  303. @staticmethod
  304. def req_publish_mqtt_msg(identification_code, topic_name, msg, qos=1):
  305. """
  306. 通用发布MQTT消息函数
  307. @param identification_code: 标识码
  308. @param topic_name: 主题名
  309. @param msg: 消息内容
  310. @param qos: mqtt qos等级
  311. @return: boolean
  312. """
  313. if not all([identification_code, topic_name]):
  314. return False
  315. if identification_code.endswith('11L'):
  316. thing_name = 'LC_' + identification_code
  317. else:
  318. thing_name = 'Ansjer_Device_' + identification_code
  319. try:
  320. # 获取数据组织将要请求的url
  321. iot = iotdeviceInfoModel.objects.filter(
  322. thing_name=thing_name).values(
  323. 'endpoint', 'token_iot_number')
  324. if not iot.exists():
  325. return False
  326. endpoint = iot[0]['endpoint']
  327. Token = iot[0]['token_iot_number']
  328. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  329. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  330. # post请求url发布MQTT消息
  331. url = 'https://{}/topics/{}?qos={}'.format(endpoint, topic_name, qos)
  332. authorizer_name = 'Ansjer_Iot_Auth'
  333. signature = CommonService.rsa_sign(Token) # Token签名
  334. headers = {
  335. 'x-amz-customauthorizer-name': authorizer_name,
  336. 'Token': Token,
  337. 'x-amz-customauthorizer-signature': signature}
  338. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  339. if r.status_code == 200:
  340. res = r.json()
  341. if res['message'] == 'OK':
  342. return True
  343. return False
  344. else:
  345. return False
  346. except Exception as e:
  347. return False
  348. @staticmethod
  349. def rsa_sign(Token):
  350. # 私钥签名Token
  351. if not Token:
  352. return ''
  353. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  354. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  355. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  356. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  357. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  358. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  359. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  360. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  361. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  362. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  363. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  364. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  365. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  366. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  367. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  368. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  369. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  370. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  371. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  372. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  373. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  374. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  375. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  376. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  377. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  378. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  379. -----END RSA PRIVATE KEY-----'''
  380. # 使用密钥文件方式
  381. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  382. # private_key_file = open(private_key_file_path, 'r')
  383. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  384. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  385. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  386. # print('signature:', signature)
  387. return signature