CommonService.py 15 KB

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