CommonService.py 15 KB

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