CommonService.py 10 KB

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