CommonService.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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, ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, PUSH_BUCKET
  16. from Object.enums.EventTypeEnum import EventTypeEnumObj
  17. # 复用性且公用较高封装代码在这
  18. class CommonService:
  19. # 添加模糊搜索
  20. @staticmethod
  21. def get_kwargs(data={}):
  22. kwargs = {}
  23. for (k, v) in data.items():
  24. if v is not None and v != u'':
  25. kwargs[k + '__icontains'] = v
  26. return kwargs
  27. # 定义静态方法
  28. # 格式化query_set转dict
  29. @staticmethod
  30. def qs_to_dict(query_set):
  31. sqlJSON = serializers.serialize('json', query_set)
  32. sqlList = json.loads(sqlJSON)
  33. sqlDict = dict(zip(["datas"], [sqlList]))
  34. return sqlDict
  35. # 获取文件大小
  36. @staticmethod
  37. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  38. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  39. # path = Path() / 'D:/TestServer/123444.mp4'
  40. path = Path() / file_path
  41. size = path.stat().st_size
  42. mb_size = 0.0
  43. if suffix_type == 'MB':
  44. mb_size = size / 1024.0 / 1024.0
  45. if decimal_point != 0:
  46. mb_size = round(mb_size, decimal_point)
  47. return mb_size
  48. @staticmethod
  49. def get_param_flag(data=[]):
  50. # print(data)
  51. flag = True
  52. for v in data:
  53. if v is None:
  54. flag = False
  55. break
  56. return flag
  57. @staticmethod
  58. def get_ip_address(request):
  59. """
  60. 获取ip地址
  61. :param request:
  62. :return:
  63. """
  64. try:
  65. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  66. clientIP = real_ip.split(",")[0]
  67. except:
  68. try:
  69. clientIP = request.META['REMOTE_ADDR']
  70. except Exception as e:
  71. clientIP = ''
  72. return clientIP
  73. # @获取一天每个小时的datetime.datetime
  74. @staticmethod
  75. def getTimeDict(times):
  76. time_dict = {}
  77. t = 0
  78. for x in range(24):
  79. if x < 10:
  80. x = '0' + str(x)
  81. else:
  82. x = str(x)
  83. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  84. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  85. t += 1
  86. return time_dict
  87. # 根据ip获取地址
  88. @staticmethod
  89. def getAddr(ip):
  90. base_dir = BASE_DIR
  91. # ip数据库
  92. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  93. addr = db.lookup(ip)
  94. ts = addr.split('\t')[0]
  95. return ts
  96. # 通过ip检索ipip指定信息 lang为CN或EN
  97. @staticmethod
  98. def getIpIpInfo(ip, lang, update=False):
  99. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  100. db = ipdb.City(ipbd_dir)
  101. if update:
  102. rr = db.reload(ipbd_dir)
  103. info = db.find_map(ip, lang)
  104. return info
  105. @staticmethod
  106. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  107. if μs == True:
  108. if getUser == True:
  109. timeID = str(round(time.time() * 1000000))
  110. userID = timeID + userPhone
  111. return userID
  112. else:
  113. if setOTAID == False:
  114. timeID = str(round(time.time() * 1000000))
  115. ID = userPhone + timeID
  116. return ID
  117. else:
  118. timeID = str(round(time.time() * 1000000))
  119. eID = '13800' + timeID + '138000'
  120. return eID
  121. else:
  122. if getUser == True:
  123. timeID = str(round(time.time() * 1000))
  124. userID = timeID + userPhone
  125. return userID
  126. else:
  127. if setOTAID == False:
  128. timeID = str(round(time.time() * 1000))
  129. ID = userPhone + timeID
  130. return ID
  131. else:
  132. timeID = str(round(time.time() * 1000))
  133. eID = '13800' + timeID + '138000'
  134. return eID
  135. # 生成随机数
  136. @staticmethod
  137. def RandomStr(randomlength=8, number=True):
  138. str = ''
  139. if number == False:
  140. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  141. 'tUuVvWwXxYyZz0123456789'
  142. else:
  143. characterSet = '0123456789'
  144. length = len(characterSet) - 1
  145. random = Random()
  146. for index in range(randomlength):
  147. str += characterSet[random.randint(0, length)]
  148. return str
  149. # 生成订单好
  150. @staticmethod
  151. def createOrderID():
  152. random_id = CommonService.RandomStr(6, True)
  153. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  154. print('orderID:')
  155. print(order_id)
  156. return order_id
  157. # qs转换list datetime处理
  158. @staticmethod
  159. def qs_to_list(qs):
  160. res = []
  161. # print(qs)
  162. for ps in qs:
  163. if 'add_time' in ps:
  164. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  165. if 'update_time' in ps:
  166. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  167. if 'end_time' in ps:
  168. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  169. if 'data_joined' in ps:
  170. if ps['data_joined']:
  171. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  172. else:
  173. ps['data_joined'] = ''
  174. res.append(ps)
  175. return res
  176. # 获取当前时间
  177. @staticmethod
  178. def get_now_time_str(n_time, tz, lang):
  179. print(n_time)
  180. print(tz)
  181. print(lang)
  182. try:
  183. tz = tz.replace(':', '.')
  184. n_time = int(n_time) + 3600 * float(tz)
  185. except:
  186. n_time = int(n_time)
  187. if lang == 'cn':
  188. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  189. else:
  190. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  191. @staticmethod
  192. def app_log_log(uid='None', tz='0'):
  193. file_path = '/'.join((BASE_DIR, 'static/app_log.log'))
  194. file = open(file_path, 'a+')
  195. file.write("uid:" + uid + "; " + "; tz:" + tz)
  196. file.write('\n')
  197. file.flush()
  198. file.close()
  199. @classmethod
  200. def upload_images(cls, file_dict, dir_path):
  201. """
  202. 上传图片到S3,并删除本地图片
  203. @param file_dict: S3图片路径
  204. @param dir_path: 本地图片路径
  205. @return: boolean
  206. """
  207. try:
  208. s3 = Session(
  209. aws_access_key_id=ACCESS_KEY_ID,
  210. aws_secret_access_key=SECRET_ACCESS_KEY,
  211. region_name=REGION_NAME
  212. ).resource('s3')
  213. for file_path, upload_path in file_dict.items():
  214. upload_data = open(file_path, 'rb')
  215. s3.Bucket(PUSH_BUCKET).put_object(Key=upload_path, Body=upload_data)
  216. # 删除图片
  217. cls.del_path(dir_path)
  218. cls.del_path(dir_path + '.jpg')
  219. return True
  220. except Exception as e:
  221. print(repr(e))
  222. return False
  223. @classmethod
  224. def del_path(cls, path):
  225. """
  226. 删除目录文件
  227. @param path: 文件路径
  228. @return: None
  229. """
  230. if not os.path.exists(path):
  231. return
  232. if os.path.isfile(path):
  233. os.remove(path)
  234. else:
  235. items = os.listdir(path)
  236. for f in items:
  237. c_path = os.path.join(path, f)
  238. if os.path.isdir(c_path):
  239. cls.del_path(c_path)
  240. else:
  241. os.remove(c_path)
  242. os.rmdir(path)
  243. @staticmethod
  244. def getMD5Sign(data, key):
  245. '''
  246. 魅族MD5签名
  247. '''
  248. dataList = []
  249. for k in sorted(data):
  250. dataList.append("%s=%s" % (k, data[k]))
  251. data = (''.join(dataList))
  252. data = data + key
  253. sign = hashlib.md5(data.encode(encoding="utf-8")).hexdigest()
  254. return sign
  255. @staticmethod
  256. def check_time_stamp_token(token, time_stamp):
  257. # 时间戳token校验
  258. if not all([token, time_stamp]):
  259. return False
  260. try:
  261. token = int(CommonService.decode_data(token))
  262. time_stamp = int(time_stamp)
  263. now_time = int(time.time())
  264. distance = now_time - time_stamp
  265. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  266. return False
  267. return True
  268. except Exception as e:
  269. print(e)
  270. return False
  271. @staticmethod
  272. def decode_data(content, start=1, end=4):
  273. """
  274. 数据解密
  275. @param content: 数据内容
  276. @param start: 起始长度
  277. @param end: 结束长度
  278. @return content: 解密的数据
  279. """
  280. if not content:
  281. return ''
  282. for i in range(start, end):
  283. content = base64.b64decode(content)
  284. content = content.decode('utf-8')
  285. content = content[i:-i]
  286. return content
  287. @staticmethod
  288. def timestamp_to_str(timestamp):
  289. """
  290. 时间戳转时间字符串
  291. @param timestamp: 时间戳
  292. @return time_str: 时间字符串
  293. """
  294. struct_time = time.localtime(timestamp)
  295. time_str = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
  296. return time_str
  297. @staticmethod
  298. def get_jump_type(event_type):
  299. """
  300. 获取跳转类型
  301. @param event_type: 事件类型
  302. @return event_type: 跳转类型,1:推送消息,2:系统消息,3:音视频通话消息
  303. """
  304. # 跳转类型,1:推送消息,2:系统消息,3:音视频通话消息
  305. jump_type = 1
  306. event_type = int(event_type)
  307. if event_type in EventTypeEnumObj.SYS_MSG_EVENT_TYPE_LIST.value:
  308. jump_type = 2
  309. elif event_type in EventTypeEnumObj.DATA_PUSH_EVENT_TYPE_LIST.value:
  310. jump_type = 3
  311. return jump_type