Test.py 12 KB

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