utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import string
  2. import random
  3. import requests
  4. import json
  5. import logging
  6. import time
  7. import hashlib
  8. import math
  9. from captcha.image import ImageCaptcha
  10. from io import BytesIO
  11. import base64
  12. from datetime import datetime, timedelta
  13. import calendar
  14. from smartfarming.models.user import Role, UserPurview
  15. from kedong.tools import RedisPool
  16. from kedong import settings
  17. logger = logging.getLogger("other")
  18. redis_pool = RedisPool().get_redis_pool(settings.redis_db["jiankong"])
  19. config = settings.CONFIG
  20. def perms_pc_app(type_id=1000, perms_lst=[], device_user=None):
  21. menu = "PC" if type_id == 1000 else "APP"
  22. parent_ids = []
  23. for p in perms_lst:
  24. # 先判断是否是父级菜单
  25. per_obj = UserPurview.objects.filter(id=int(p), menu=menu).first()
  26. if per_obj:
  27. if per_obj.parent_perm_id == 0:
  28. parent_ids.append(p)
  29. perm_lst = []
  30. for i in parent_ids:
  31. parent = UserPurview.objects.get(id=int(i), menu=menu)
  32. inner_parent = {
  33. "menu": parent.menu,
  34. "parent_perm_id": parent.parent_perm_id,
  35. "pur_id": parent.id,
  36. "purview_name": parent.purview_name,
  37. "url": parent.url
  38. }
  39. children_lst = []
  40. # 获取此父级菜单中所有的子菜单
  41. children = UserPurview.objects.filter(parent_perm_id=int(i), menu=menu)
  42. for child in children:
  43. if child.id in perms_lst:
  44. if device_user and device_user.real_name == "yunfei" and child.parent_perm_id == 1:
  45. children_lst.append(
  46. {
  47. "menu": child.menu,
  48. "parent_perm_id": child.parent_perm_id,
  49. "pur_id": child.id,
  50. "purview_name": child.purview_name,
  51. "url": child.url
  52. }
  53. )
  54. if child.purview_name == "用户管理":
  55. children_lst.append(
  56. {
  57. "menu": "PC",
  58. "parent_perm_id": 0,
  59. "pur_id": 38,
  60. "purview_name": "监控定位",
  61. "url": "0"
  62. }
  63. )
  64. children_lst.append(
  65. {
  66. "menu": "PC",
  67. "parent_perm_id": 0,
  68. "pur_id": 39,
  69. "purview_name": "APP信息",
  70. "url": "0"
  71. }
  72. )
  73. else:
  74. children_lst.append(
  75. {
  76. "menu": child.menu,
  77. "parent_perm_id": child.parent_perm_id,
  78. "pur_id": child.id,
  79. "purview_name": child.purview_name,
  80. "url": child.url
  81. }
  82. )
  83. if children_lst:
  84. inner_parent["children"] = children_lst
  85. perm_lst.append(inner_parent)
  86. return perm_lst
  87. def get_perm_list(device_user):
  88. id = device_user.role_id
  89. try:
  90. role = Role.objects.get(id=id)
  91. role_perm = role.role_perm
  92. perms_lst = [int(i) for i in role_perm.split(",")]
  93. pc_perm_lst = perms_pc_app(type_id=1000, perms_lst=perms_lst, device_user=device_user)
  94. app_perm_lst = perms_pc_app(type_id=2000, perms_lst=perms_lst)
  95. if pc_perm_lst and app_perm_lst:
  96. perm_lst = [
  97. {
  98. "menu": "",
  99. "parent_perm_id": 1000,
  100. "pur_id": 0,
  101. "purview_name": "登录PC端",
  102. "url": "",
  103. "children": pc_perm_lst
  104. },
  105. {
  106. "menu": "",
  107. "parent_perm_id": 2000,
  108. "pur_id": 00,
  109. "purview_name": "登录APP端",
  110. "url": "",
  111. "children": app_perm_lst
  112. }
  113. ]
  114. elif pc_perm_lst:
  115. perm_lst = [
  116. {
  117. "menu": "",
  118. "parent_perm_id": 1000,
  119. "pur_id": 0,
  120. "purview_name": "登录PC端",
  121. "url": "",
  122. "children": pc_perm_lst
  123. }
  124. ]
  125. elif app_perm_lst:
  126. perm_lst = [
  127. {
  128. "menu": "",
  129. "parent_perm_id": 2000,
  130. "pur_id": 00,
  131. "purview_name": "登录APP端",
  132. "url": "",
  133. "children": app_perm_lst
  134. }
  135. ]
  136. else:
  137. perm_lst = []
  138. mark = role.mark
  139. return perm_lst, mark
  140. except Exception as e:
  141. return [], ""
  142. def get_all_pers():
  143. role_perm = UserPurview.objects.all().values("id")
  144. perms_lst = []
  145. for i in role_perm:
  146. perms_lst.append(i.get("id"))
  147. pc_perm_lst = perms_pc_app(type_id=1000, perms_lst=perms_lst)
  148. app_perm_lst = perms_pc_app(type_id=2000, perms_lst=perms_lst)
  149. perm_lst = [
  150. {
  151. "menu": "",
  152. "parent_perm_id": 1000,
  153. "pur_id": 0,
  154. "purview_name": "登录PC端",
  155. "url": "",
  156. "children": pc_perm_lst
  157. },
  158. {
  159. "menu": "",
  160. "parent_perm_id": 2000,
  161. "pur_id": 0,
  162. "purview_name": "登录APP端",
  163. "url": "",
  164. "children": app_perm_lst
  165. }
  166. ]
  167. return perm_lst
  168. def get_captcha():
  169. """获取图片验证码
  170. return :
  171. 验证码字符串,验证码图片base64数据
  172. """
  173. chr_all = string.ascii_uppercase + string.digits
  174. chr_all = chr_all.replace('0', '').replace('1', '').replace('2', '').replace('O', '').replace('I', '')
  175. code_str = ''.join(random.sample(chr_all, 4))
  176. image = ImageCaptcha().generate_image(code_str)
  177. f = BytesIO()
  178. image.save(f, 'png')
  179. data = f.getvalue()
  180. f.close()
  181. encode_data = base64.b64encode(data)
  182. data = str(encode_data, encoding='utf-8')
  183. img_data = "data:image/jpeg;base64,{data}".format(data=data)
  184. return code_str, img_data
  185. def get_recent_month(num):
  186. # 获取最近N个月的时间戳
  187. end_time = datetime.now() # 结束时间,当前时间
  188. # 获取当前月份和年份
  189. current_month = end_time.month
  190. current_year = end_time.year
  191. # 计算开始时间
  192. start_month = current_month - num # 当前月份往前推N个月
  193. start_year = current_year
  194. if start_month <= 0: # 如果计算得到的月份为负数,则需要向前借位
  195. start_month += 12
  196. start_year -= 1
  197. # 获取开始时间所在月份的最后一天
  198. _, last_day = calendar.monthrange(start_year, start_month)
  199. start_time = datetime(start_year, start_month, last_day).timestamp()
  200. return start_time
  201. def get_addr_by_lag_lng(lat,lng):
  202. # 根据经纬度获取省市级
  203. is_success, province, city, district = False, "", "", ""
  204. try:
  205. # 使用腾讯接口
  206. url = "https://apis.map.qq.com/ws/geocoder/v1?location={},{}&get_poi=0&key=OA4BZ-FX43U-E5VV2-45M6S-C4HD3-NIFFI&output=json".format(lat,lng)
  207. requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
  208. s = requests.session()
  209. s.keep_alive = False # 关闭多余连接
  210. ret = s.get(url)
  211. rest = json.loads(ret.text)
  212. province = rest["result"]["ad_info"]["province"]
  213. city = rest["result"]["ad_info"]["city"]
  214. district = rest["result"]["ad_info"]["district"]
  215. is_success = True
  216. except Exception as e:
  217. logger.error(f"获取腾讯地理位置接口失败 {e.args}")
  218. if not is_success:
  219. try:
  220. # 使用百度接口
  221. url = "http://api.map.baidu.com/geocoder?location=%s,%s&output=json"%(lat,lng)
  222. requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
  223. s = requests.session()
  224. s.keep_alive = False # 关闭多余连接
  225. ret = s.get(url)
  226. addr = json.loads(ret.text)
  227. province = addr["result"]["addressComponent"]["province"]
  228. city = addr["result"]["addressComponent"]["city"]
  229. district = addr["result"]["addressComponent"]["district"]
  230. is_success = True
  231. except Exception as e:
  232. logger.error(f"获取百度地理位置接口失败 {e.args}")
  233. return is_success, province, city, district
  234. # 获取天气数据
  235. def get_address_by_lntlat(lng, lat):
  236. province, city, district = "", "", ""
  237. try:
  238. key = "78ce288400f4fc6d9458989875c833c2"
  239. adcode_url = "http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}&poitype=&radius=&" \
  240. "extensions=all&batch=false&roadlevel=0".format(key=key, lng=lng, lat=lat)
  241. res = requests.get(adcode_url)
  242. rsp = res.json()
  243. address_info = rsp['regeocode']['addressComponent']
  244. adcode = address_info['adcode']
  245. if adcode != "900000":
  246. province, city, district = address_info['province'], address_info['city'], address_info['district']
  247. if (not city) and district:
  248. city = district
  249. except Exception as e:
  250. pass
  251. return province, city, district
  252. # 获取天气相关信息
  253. def get_weather_info(lng=None, lat=None):
  254. data = {}
  255. if lng and lat:
  256. try:
  257. url = "http://114.115.147.140:8080/weather"
  258. res = requests.post(url, {"lat": lat, "lng": lng})
  259. result = res.json()
  260. if result['status'] == 'true':
  261. data = result['data']
  262. except Exception as e:
  263. pass
  264. return data
  265. def expire_time(times):
  266. data_time = datetime.datetime.now()
  267. cultivate_time_expire = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
  268. time1 = datetime.datetime.strptime(cultivate_time_expire,"%Y-%m-%d %H:%M:%S")
  269. num=(time1-data_time).days
  270. print("设备到期天数---",num)
  271. if int(num) <=7 and int(num) >= 0:
  272. print("即将到期")
  273. status = 2
  274. elif int(num) < 0:
  275. print("已到期")
  276. status = 1
  277. else:
  278. print("未到期")
  279. status = 0
  280. return status
  281. def get_center_lnglat(lnglats_list):
  282. x, y, z = 0, 0, 0
  283. length = len(lnglats_list)
  284. for n, a in lnglats_list:
  285. g, t = math.radians(float(n)), math.radians(float(a))
  286. x += math.cos(t) * math.cos(g)
  287. y += math.cos(t) * math.sin(g)
  288. z += math.sin(t)
  289. x = float(x / length)
  290. y = float(y / length)
  291. z = float(z / length)
  292. lng = round(math.degrees(math.atan2(y, x)), 4)
  293. lat = round(math.degrees(math.atan2(z, math.sqrt(x*x + y*y))), 4)
  294. return lng, lat
  295. def md5value(appSecret):
  296. """sign加密"""
  297. times = int(time.time())
  298. # 随机生成32位字符串
  299. nonce = ''.join(random.sample(string.ascii_letters + string.digits, 32))
  300. sign = "time:{},nonce:{},appSecret:{}".format(times, nonce, appSecret)
  301. input_name = hashlib.md5()
  302. input_name.update(sign.encode("utf-8"))
  303. sign = (input_name.hexdigest()).lower()
  304. return times,nonce,sign
  305. def deviceAccessToken(appId, appSecret):
  306. # 乐橙云账号秘钥
  307. # 先从redis 中获取token
  308. tokens = redis_pool.get(appId)
  309. if tokens and tokens !=None:
  310. redis_jk_data = eval(tokens)
  311. status = redis_jk_data.get("status",1)
  312. if status:
  313. # 查看到期时间
  314. expireTime = redis_pool.ttl(appId)
  315. # 设置到期时间 秒
  316. # redis_pool.expire('ttt', 10)
  317. redis_jk_data["result"]["data"]["expireTime"] = expireTime
  318. else:
  319. redis_jk_data = {"status":0}
  320. return redis_jk_data
  321. else:
  322. status = 0
  323. if not status:
  324. url = config.get("camera").get("lc_token")
  325. # 加密
  326. times,nonce,sign = md5value(appSecret)
  327. data = {
  328. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":times,"nonce":nonce},
  329. "id":nonce,
  330. "params":{}
  331. }
  332. token_data = requests.post(url,json=data, timeout=5)
  333. if token_data.status_code == 200:
  334. try:
  335. token_json_data = json.loads(token_data.text)
  336. expireTime = token_json_data["result"]["data"]["expireTime"]
  337. # status 1 代表获取token 成功 0失败
  338. token_json_data["status"] = 1
  339. except Exception as e:
  340. token_json_data = {"status":0}
  341. expireTime = 5
  342. else:
  343. token_json_data = {"status":0}
  344. expireTime = 5
  345. redis_pool.set(appId,str(token_json_data),expireTime)
  346. return token_json_data
  347. def device_config(appId,appSecret):
  348. # 配置项
  349. time,nonce,sign = md5value(appSecret)
  350. token_data = deviceAccessToken(appId, appSecret)
  351. if token_data.get("status","0"):
  352. token = token_data["result"]["data"]["accessToken"]
  353. else:
  354. token = ""
  355. return time,nonce,sign,token
  356. def controlMove(appId,appSecret,deviceId,operation,channelId="0"):
  357. # 云台控制接口
  358. url = config.get("camera").get("lc_controler")
  359. time,nonce,sign,token = device_config(appId, appSecret)
  360. if not token:
  361. return {"msg":"控制失败"}
  362. data = {
  363. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  364. "id":nonce,
  365. "params":{"token":token,"deviceId":deviceId,"channelId":channelId,"operation":operation,"duration":"1000"}
  366. }
  367. control_Move = requests.post(url,json=data)
  368. return control_Move.json()
  369. def bindDeviceLive(appId,appSecret,deviceId,channelId="0"):
  370. # 获取直播地址
  371. url = config.get("camera").get("lc_addr")
  372. time,nonce,sign,token = device_config(appId, appSecret)
  373. data = {
  374. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  375. "params":{"streamId":1,"deviceId":deviceId,"channelId":channelId,"token":token},
  376. "id":nonce
  377. }
  378. device_live_data = requests.post(url,json=data)
  379. return device_live_data.json()
  380. def getLive(appId,appSecret,deviceId,channelId="0"):
  381. # 查询监控地址 用于设备直播地址创建后再次查询使用
  382. url = config.get("camera").get("lc_stream")
  383. time,nonce,sign,token = device_config(appId, appSecret)
  384. data = {
  385. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  386. "params":{"deviceId":deviceId, "channelId":channelId,"token":token},
  387. "id":nonce
  388. }
  389. live_data = requests.post(url,json=data)
  390. return live_data.json()
  391. def modify_live_time(appId,appSecret,liveToken,start_time,end_time,period="everyday"):
  392. # 开启,修改直播计划时间
  393. # period 直播周期,always:永久,once:指定某天, everyday:每天
  394. url = config.get("camera").get("lc_modify_live_plan")
  395. time,nonce,sign,token = device_config(appId, appSecret)
  396. if not token:
  397. return {'result': {'msg': '获取token失败。', 'code': '1'}, 'id': 'rWfBFgohj7VwkxsqbM5p4JKDOtQNU2XA'}
  398. data = {
  399. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  400. "id":nonce,
  401. "params":{"token":token,"period":period,"liveToken":liveToken,"beginTime":start_time,"endTime": end_time}
  402. }
  403. if period == "always":
  404. del data["params"]["beginTime"]
  405. del data["params"]["endTime"]
  406. device_live_data = requests.post(url,json=data).json()
  407. return device_live_data
  408. def off_on_live(appId,appSecret,liveToken,status):
  409. # 关闭、开启当前直播
  410. url = config.get("camera").get("lc_modify_live_plan_status")
  411. time,nonce,sign,token = device_config(appId, appSecret)
  412. if not token:
  413. return {'result': {'msg': '获取token失败。', 'code': '1'}, 'id': 'rWfBFgohj7VwkxsqbM5p4JKDOtQNU2XA'}
  414. data = {
  415. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  416. "params":{"token":token,"liveToken":liveToken,"status":status},
  417. "id":nonce
  418. }
  419. device_live_data = requests.post(url,json=data).json()
  420. return device_live_data
  421. def setDeviceSnap(appId,appSecret,deviceId,channelId="0"):
  422. # 抓图接口
  423. url = config.get("camera").get("lc_device_snap_enhanced")
  424. # url = config.get("camera").get("lc_device_snap")
  425. time,nonce,sign,token = device_config(appId, appSecret)
  426. if not token:
  427. return {"msg": "抓图失败"}
  428. data = {
  429. "system":{"ver":"1.0", "appId":appId,"sign":sign,"time":time,"nonce":nonce},
  430. "params":{"deviceId":deviceId,"channelId":channelId,"token":token},
  431. "id":nonce
  432. }
  433. img_data = requests.post(url,json=data)
  434. result = img_data.json()
  435. if result.get("result").get("code") == "0":
  436. return result.get("result").get("data").get("url")
  437. def get_weather(ip):
  438. # 获取天气
  439. res = requests.get("https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=69334222&appsecret=2u4bHXHD&ext=")
  440. response = json.loads(res.text)
  441. return response.get("data")
  442. def getKitToken(appId,appSecret,deviceId,channelId="0"):
  443. # 获取录像回放所需要的token
  444. url = config.get("camera").get("lc_kit_token")
  445. time,nonce,sign,token = device_config(appId, appSecret)
  446. if not token:
  447. return {"result":{"code":"1"}}
  448. data = {
  449. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  450. "id":nonce,
  451. "params":{"type":0,"deviceId":deviceId,"channelId":channelId,"token":token}
  452. }
  453. like_token_data = requests.post(url,json=data)
  454. return like_token_data.json()
  455. def getRecord(appId,appSecret,deviceId,channelId="0"):
  456. url = config.get("camera").get("lc_local_record")
  457. time,nonce,sign,token = device_config(appId, appSecret)
  458. if not token:
  459. return {"result":{"code":"1"}}
  460. data = {
  461. "system":{"ver":"1.0","appId":appId,"sign":sign,"time":time,"nonce":nonce},
  462. "id":nonce,
  463. "params":{
  464. "deviceId":deviceId,
  465. "channelId":channelId,
  466. "token":token,
  467. "beginTime":"2023-07-19 00:00:00",
  468. "endTime": "2023-07-25 00:00:00",
  469. "type": "All",
  470. "count": 100
  471. }
  472. }
  473. record_token_data = requests.post(url,json=data)
  474. return record_token_data.json()
  475. if __name__ == "__main__":
  476. t = get_recent_month(1)
  477. print(t)