CommonService.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 simplejson as json
  11. from boto3 import Session
  12. from django.core import serializers
  13. from django.utils import timezone
  14. from pyipip import IPIPDatabase
  15. from AnsjerPush.config import BASE_DIR, REGION_NAME, PUSH_BUCKET, SYS_EVENT_TYPE_LIST, DATA_PUSH_EVENT_TYPE_LIST
  16. from Model.models import iotdeviceInfoModel, Device_User
  17. from django.conf import settings
  18. ACCESS_KEY_ID = settings.ACCESS_KEY_ID
  19. SECRET_ACCESS_KEY = settings.SECRET_ACCESS_KEY
  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. rr = db.reload(ipbd_dir)
  106. info = db.find_map(ip, lang)
  107. return info
  108. @staticmethod
  109. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  110. if μs == True:
  111. if getUser == True:
  112. timeID = str(round(time.time() * 1000000))
  113. userID = timeID + userPhone
  114. return userID
  115. else:
  116. if setOTAID == False:
  117. timeID = str(round(time.time() * 1000000))
  118. ID = userPhone + timeID
  119. return ID
  120. else:
  121. timeID = str(round(time.time() * 1000000))
  122. eID = '13800' + timeID + '138000'
  123. return eID
  124. else:
  125. if getUser == True:
  126. timeID = str(round(time.time() * 1000))
  127. userID = timeID + userPhone
  128. return userID
  129. else:
  130. if setOTAID == False:
  131. timeID = str(round(time.time() * 1000))
  132. ID = userPhone + timeID
  133. return ID
  134. else:
  135. timeID = str(round(time.time() * 1000))
  136. eID = '13800' + timeID + '138000'
  137. return eID
  138. # 生成随机数
  139. @staticmethod
  140. def RandomStr(randomlength=8, number=True):
  141. str = ''
  142. if number == False:
  143. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  144. 'tUuVvWwXxYyZz0123456789'
  145. else:
  146. characterSet = '0123456789'
  147. length = len(characterSet) - 1
  148. random = Random()
  149. for index in range(randomlength):
  150. str += characterSet[random.randint(0, length)]
  151. return str
  152. # 生成订单好
  153. @staticmethod
  154. def createOrderID():
  155. random_id = CommonService.RandomStr(6, True)
  156. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  157. print('orderID:')
  158. print(order_id)
  159. return order_id
  160. # qs转换list datetime处理
  161. @staticmethod
  162. def qs_to_list(qs):
  163. res = []
  164. # print(qs)
  165. for ps in qs:
  166. if 'add_time' in ps:
  167. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  168. if 'update_time' in ps:
  169. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  170. if 'end_time' in ps:
  171. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  172. if 'data_joined' in ps:
  173. if ps['data_joined']:
  174. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  175. else:
  176. ps['data_joined'] = ''
  177. res.append(ps)
  178. return res
  179. # 获取当前时间
  180. @staticmethod
  181. def get_now_time_str(n_time, tz, lang):
  182. print(n_time)
  183. print(tz)
  184. print(lang)
  185. try:
  186. tz = tz.replace(':', '.')
  187. n_time = int(n_time) + 3600 * float(tz)
  188. except:
  189. n_time = int(n_time)
  190. if lang == 'cn':
  191. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  192. else:
  193. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  194. @staticmethod
  195. def app_log_log(uid='None', tz='0'):
  196. file_path = '/'.join((BASE_DIR, 'static/app_log.log'))
  197. file = open(file_path, 'a+')
  198. file.write("uid:" + uid + "; " + "; tz:" + tz)
  199. file.write('\n')
  200. file.flush()
  201. file.close()
  202. @classmethod
  203. def upload_images(cls, file_dict, dir_path):
  204. """
  205. 上传图片到S3,并删除本地图片
  206. @param file_dict: S3图片路径
  207. @param dir_path: 本地图片路径
  208. @return: boolean
  209. """
  210. try:
  211. s3 = Session(
  212. aws_access_key_id=ACCESS_KEY_ID,
  213. aws_secret_access_key=SECRET_ACCESS_KEY,
  214. region_name=REGION_NAME
  215. ).resource('s3')
  216. for file_path, upload_path in file_dict.items():
  217. upload_data = open(file_path, 'rb')
  218. s3.Bucket(PUSH_BUCKET).put_object(Key=upload_path, Body=upload_data)
  219. # 删除图片
  220. cls.del_path(dir_path)
  221. cls.del_path(dir_path + '.jpg')
  222. return True
  223. except Exception as e:
  224. print(repr(e))
  225. return False
  226. @classmethod
  227. def del_path(cls, path):
  228. """
  229. 删除目录文件
  230. @param path: 文件路径
  231. @return: None
  232. """
  233. if not os.path.exists(path):
  234. return
  235. if os.path.isfile(path):
  236. os.remove(path)
  237. else:
  238. items = os.listdir(path)
  239. for f in items:
  240. c_path = os.path.join(path, f)
  241. if os.path.isdir(c_path):
  242. cls.del_path(c_path)
  243. else:
  244. os.remove(c_path)
  245. os.rmdir(path)
  246. @staticmethod
  247. def getMD5Sign(data, key):
  248. '''
  249. 魅族MD5签名
  250. '''
  251. dataList = []
  252. for k in sorted(data):
  253. dataList.append("%s=%s" % (k, data[k]))
  254. data = (''.join(dataList))
  255. data = data + key
  256. sign = hashlib.md5(data.encode(encoding="utf-8")).hexdigest()
  257. return sign
  258. @staticmethod
  259. def check_time_stamp_token(token, time_stamp):
  260. # 时间戳token校验
  261. if not all([token, time_stamp]):
  262. return False
  263. try:
  264. token = int(CommonService.decode_data(token))
  265. time_stamp = int(time_stamp)
  266. now_time = int(time.time())
  267. distance = now_time - time_stamp
  268. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  269. return False
  270. return True
  271. except Exception as e:
  272. print(e)
  273. return False
  274. @staticmethod
  275. def decode_data(content, start=1, end=4):
  276. """
  277. 数据解密
  278. @param content: 数据内容
  279. @param start: 起始长度
  280. @param end: 结束长度
  281. @return content: 解密的数据
  282. """
  283. if not content:
  284. return ''
  285. for i in range(start, end):
  286. content = base64.b64decode(content)
  287. content = content.decode('utf-8')
  288. content = content[i:-i]
  289. return content
  290. @staticmethod
  291. def timestamp_to_str(timestamp):
  292. """
  293. 时间戳转时间字符串
  294. @param timestamp: 时间戳
  295. @return time_str: 时间字符串
  296. """
  297. struct_time = time.localtime(timestamp)
  298. time_str = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
  299. return time_str
  300. @staticmethod
  301. def get_jump_type(event_type):
  302. """
  303. 获取跳转类型
  304. @param event_type: 事件类型
  305. @return event_type: 跳转类型,1:推送消息,2:系统消息,3:音视频通话消息
  306. """
  307. # 跳转类型,1:推送消息,2:系统消息,3:音视频通话消息
  308. jump_type = 1
  309. event_type = int(event_type)
  310. if event_type in SYS_EVENT_TYPE_LIST:
  311. jump_type = 2
  312. elif event_type in DATA_PUSH_EVENT_TYPE_LIST:
  313. jump_type = 3
  314. return jump_type