Test.py 11 KB

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