Test.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: Ansjer
  7. @software: PyCharm
  8. @DATE: 2018/5/22 13:58
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: Test.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. from django.views.generic.base import View
  15. import os
  16. '''
  17. http://192.168.136.40:8077/Test
  18. '''
  19. from Object.ResponseObject import ResponseObject
  20. from Ansjer.config import BASE_DIR
  21. import json
  22. from alipay import AliPay
  23. import time
  24. import apns2
  25. # 测试接口sdk
  26. class Test(View):
  27. def get(self, request, *args, **kwargs):
  28. request_dict = request.GET
  29. op = request_dict.get('op',None)
  30. if op:
  31. return self.do_get_aws_kinesis_vidoe()
  32. test_push_type = request_dict.get('test_push_type')
  33. if test_push_type == 'jpush':
  34. return self.jgPush(request)
  35. elif test_push_type == 'fcm':
  36. return self.do_fcm_push(request)
  37. elif test_push_type == 'apns':
  38. return self.do_apns(request.GET)
  39. return self.do_gcm_push(request)
  40. return self.do_alipay_query_status()
  41. def do_get_aws_kinesis_vidoe(self):
  42. import boto3
  43. REGION_NAME = 'us-east-1' # e.g
  44. import json
  45. sts = boto3.client(
  46. 'sts',
  47. aws_access_key_id='AKIA2E67UIMD45Y3HL53',
  48. aws_secret_access_key='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',
  49. region_name=REGION_NAME
  50. )
  51. Policy = {"Version": "2012-10-17",
  52. "Statement": [{"Effect": "Allow", "Action": "kinesisvideo:*", "Resource": [
  53. "arn:aws:kinesisvideo:us-east-1:697864307463:stream/wpy_stream/1573460250304"]}]}
  54. credentials = sts.get_federation_token(
  55. Name='chanjunkai@163.com', # or any unique text related to user
  56. Policy=json.dumps(Policy),
  57. DurationSeconds=3600,
  58. )
  59. print(credentials)
  60. access_key_id = credentials['Credentials']['AccessKeyId']
  61. session_token = credentials['Credentials']['SessionToken']
  62. secret_access_key = credentials['Credentials']['SecretAccessKey']
  63. response = ResponseObject()
  64. res = {
  65. 'access_key_id':access_key_id,
  66. 'secret_access_key':secret_access_key,
  67. 'session_token':session_token,
  68. }
  69. return response.json(0,res)
  70. def do_alipay_query_status(self):
  71. response = ResponseObject()
  72. # app_private_key_string = open(BASE_DIR + '/Ansjer/file/alipay/alipay_private_2048.pem').read()
  73. # alipay_public_key_string = open(BASE_DIR + '/Ansjer/file/alipay/alipay_public_2048.pem').read()
  74. app_private_key_string = open(BASE_DIR + '/Ansjer/file/alipay/zosi_alipay_private_2048.pem').read()
  75. alipay_public_key_string = open(BASE_DIR + '/Ansjer/file/alipay/zosi_alipay_public_2048.pem').read()
  76. alipay = AliPay(
  77. # appid="2016092200569234",
  78. appid="2019041663958142",
  79. app_notify_url=None, # the default notify path
  80. app_private_key_string=app_private_key_string,
  81. alipay_public_key_string=alipay_public_key_string,
  82. sign_type="RSA2", # RSA or RSA2
  83. debug=False # False by default
  84. )
  85. # check order status
  86. print("now sleep 3s")
  87. # time.sleep(3)
  88. result = alipay.api_alipay_trade_query(out_trade_no="20190424085757859937")
  89. if result.get("trade_status", "") == "TRADE_SUCCESS":
  90. paid = True
  91. print(paid)
  92. return response.json(0)
  93. else:
  94. print("not paid...")
  95. return response.json(404)
  96. def do_fcm_push(self, request):
  97. rg_id = request.GET.get('rg_id', '')
  98. serverKey = request.GET.get('serverKey', '')
  99. push_type = request.GET.get('push_type', None)
  100. # Send to single device.
  101. from pyfcm import FCMNotification
  102. # OR initialize with proxies
  103. # proxy_dict = {
  104. # "http": "http://127.0.0.1",
  105. # "https": "http://127.0.0.1",
  106. # }
  107. # push_service = FCMNotification(api_key="<api-key>", proxy_dict=proxy_dict)
  108. push_service = FCMNotification(api_key=serverKey)
  109. # Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging
  110. registration_id = rg_id
  111. message_title = "Zosi Smart(xxxx 007)"
  112. now_time = int(time.time())
  113. data = {"alert": "Motion ", "event_time": now_time, "event_type": "51", "msg": "",
  114. "received_at": now_time, "sound": "sound.aif", "uid": "98UXAA8BRPA35VAL111A", "zpush": "1"}
  115. # message_body = json.dumps(data)
  116. message_body = '警告:Motion Channel:1 日期:{tt}'.format(
  117. tt=str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
  118. print(message_body)
  119. from var_dump import var_dump
  120. if push_type == '1':
  121. var_dump('1111111')
  122. result = push_service.single_device_data_message(registration_id=registration_id, data_message=data)
  123. elif push_type == '2':
  124. var_dump('22222222')
  125. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  126. message_body=message_body, data_message=data)
  127. else:
  128. var_dump('333333')
  129. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  130. message_body=message_body)
  131. from var_dump import var_dump
  132. var_dump(result)
  133. response = ResponseObject()
  134. return response.json(0, result)
  135. def do_apns(self, request_dict):
  136. token_val = request_dict.get('token_val', None)
  137. pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-dev2.pem')
  138. # pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-loocamccloud.pem')
  139. print(pem_path)
  140. response = ResponseObject()
  141. try:
  142. n_time = int(time.time())
  143. cli = apns2.APNSClient(mode="dev", client_cert=pem_path,
  144. password='111111')
  145. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 51, "msg": "",
  146. "received_at": n_time, "sound": "sound.aif", "uid": 'XFDJUHUIOKJHYTGSFFDR', "zpush": "1", "channel": 1}
  147. alert = apns2.PayloadAlert(body='通道:1 uid:XFDJUHUIOKJHYTGSFFDR', title='ansjer')
  148. payload = apns2.Payload(alert=alert, custom=push_data)
  149. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  150. res = cli.push(n=n, device_token=token_val, topic='com.ansjer.loocamccloud')
  151. # assert res.status_code == 200, res.reason
  152. # assert res.apns_id
  153. if res.status_code == 200:
  154. return response.json(0)
  155. else:
  156. return response.json(404, res.reason)
  157. except Exception as e:
  158. return response.json(10, repr(e))
  159. def do_get_putOss_url(self, request_dict):
  160. import oss2
  161. obj_name = request_dict.get('obj_name', '')
  162. # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
  163. auth = oss2.Auth('LTAIyMkGfEdogyL9', '71uIjpsqVOmF7DAITRyRuc259jHOjO')
  164. # Endpoint以杭州为例,其它Region请按实际情况填写。
  165. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  166. # 设置此签名URL在60秒内有效。
  167. url = bucket.sign_url('PUT', obj_name, 7200)
  168. response = ResponseObject()
  169. return response.json(0, url)
  170. def do_gcm_push(self, request):
  171. import json
  172. import requests
  173. response = ResponseObject()
  174. rg_id = request.GET.get('rg_id', '')
  175. serverKey = request.GET.get('serverKey', '')
  176. if not rg_id or not serverKey:
  177. return response.json(444)
  178. now_time = int(time.time())
  179. data = {"alert": "Motion ", "event_time": now_time, "event_type": "51", "msg": "",
  180. "received_at": now_time, "sound": "sound.aif", "uid": "XFDJUHUIOKJHYTGSFFDR", "zpush": "1"}
  181. json_data = {
  182. "collapse_key": "WhatYouWant",
  183. "data": data,
  184. "delay_while_idle": False,
  185. "time_to_live": 3600,
  186. "registration_ids": [rg_id]
  187. }
  188. url = 'https://android.googleapis.com/gcm/send'
  189. data = json.dumps(json_data).encode('utf-8')
  190. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  191. req = requests.post(url, data, headers=headers)
  192. response = ResponseObject()
  193. return response.json(0)
  194. def jgPush(self, request):
  195. response = ResponseObject()
  196. devToken = request.GET.get('devToken', '')
  197. app_key = request.GET.get('app_key', '')
  198. master_secret = request.GET.get('master_secret', '')
  199. import jpush as jpush
  200. # 此处换成各自的app_key和master_secret
  201. _jpush = jpush.JPush(app_key, master_secret)
  202. push = _jpush.create_push()
  203. # if you set the logging level to "DEBUG",it will show the debug logging.
  204. _jpush.set_logging("DEBUG")
  205. # push.audience = jpush.all_
  206. n_time = int(time.time())
  207. event_type = 51
  208. push.audience = jpush.registration_id(devToken)
  209. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  210. "received_at": n_time, "sound": "sound.aif", "uid": 'xoxoxoxoxoxoxoxoxoxo', "zpush": "1"}
  211. android = jpush.android(alert="Hello, Android msg", priority=1, style=1, alert_type=1, big_text='ssssssssssssssssss',
  212. extras=push_data,title='fffff')
  213. push.notification = jpush.notification(android=android)
  214. push.platform = jpush.all_
  215. try:
  216. push.send()
  217. except Exception as e:
  218. print("Exception")
  219. return response.json(10, repr(e))
  220. return response.json(0)
  221. def post(self, request, *args, **kwargs):
  222. response = ResponseObject()
  223. data = request.POST.dict()
  224. signature = data["sign"]
  225. data.pop('sign')
  226. print(json.dumps(data))
  227. print(signature)
  228. # verify
  229. app_private_key_string = open(BASE_DIR + '/Controller/alipay_private_2048.pem').read()
  230. alipay_public_key_string = open(BASE_DIR + '/Controller/alipay_public_2048.pem').read()
  231. alipay = AliPay(
  232. appid="2016092200569234",
  233. app_notify_url=None, # the default notify path
  234. app_private_key_string=app_private_key_string,
  235. alipay_public_key_string=alipay_public_key_string,
  236. sign_type="RSA2", # RSA or RSA2
  237. debug=False # False by default
  238. )
  239. success = alipay.verify(data, signature)
  240. if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  241. print("trade succeed")
  242. return response.json(0, signature)
  243. # 修改 资源改变
  244. def put(self, request):
  245. response = ResponseObject()
  246. return response.json(0, '')
  247. # 修改 属性改变
  248. def PATCH(self, request):
  249. response = ResponseObject()
  250. return response.json(0)
  251. # 删除
  252. def delete(self, request):
  253. response = ResponseObject()
  254. return response.json(0)
  255. def validation(self, request_dict, *args, **kwargs):
  256. response = ResponseObject()
  257. return response.json(0)