Test.py 12 KB

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