/
sns_push.clj
109 lines (98 loc) · 3.03 KB
/
sns_push.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
(ns nsfw.sns-push
(:require [nsfw.aws :as aws]
[nsfw.util :as nu])
(:import [com.amazonaws.services.sns AmazonSNSClient]
[com.amazonaws.services.sns.model
CreatePlatformApplicationRequest
CreatePlatformEndpointRequest
PublishRequest
PublishResult]
[com.amazonaws.services.sns.model
InvalidParameterException]))
(defn sns-client [access-key secret-key region-key]
(doto (AmazonSNSClient.
(aws/basic-credentials access-key secret-key))
(.setRegion (aws/region-key->region-obj region-key))))
(defn publish-request-obj [{:keys [message-structure
target-arn
payload]
:or {message-structure :json}}]
(doto (PublishRequest.)
(.setMessageStructure (name message-structure))
(.setTargetArn target-arn)
(.setMessage (nu/to-json payload))))
(defn create-ios-endpoint-arn
[{:keys [access-key
secret-key
region
application-arn]}
platform-token
& [{:keys [custom-data]}]]
(let [client (sns-client access-key secret-key region)
custom-data (or custom-data platform-token)
req (doto (CreatePlatformEndpointRequest.)
(.setCustomUserData custom-data)
(.setToken platform-token)
(.setPlatformApplicationArn application-arn))]
(try
[(.getEndpointArn
(.createPlatformEndpoint
client
req))]
(catch InvalidParameterException e
[nil {:message (.getMessage e)} e])
(catch Exception e
[nil {:message (.getMessage e)} e]))))
(defn format-push-payload [platform data]
{(name platform)
(nu/to-json data)})
(defn send-ios-push
[{:keys [access-key
secret-key
region
platform]}
endpoint-arn
push-payload]
(let [client (sns-client access-key secret-key region)
req (publish-request-obj
{:target-arn endpoint-arn
:payload
(format-push-payload
platform
{"aps" push-payload})})]
(try
[{:message-id (.getMessageId (.publish client req))
:endpoint-arn endpoint-arn}]
(catch InvalidParameterException e
[nil {:message (.getMessage e)} e])
(catch Exception e
[nil {:message (.getMessage e)} e]))))
(comment
(def push-creds
{:access-key ""
:secret-key ""
:region :us-west-2
:platform "APNS_SANDBOX"
:application-arn ""})
(prn
(create-ios-endpoint-arn push-creds
"push-key"))
(prn
(send-ios-push
push-creds
"endpoint-arn"
{:alert {:title "hello world"
:subtitle "subtitle"
:body "the quick brown fox"}}))
(prn
(send-ios-push
push-creds
"error-arn"
{:alert {:title "hello world"
:subtitle "subtitle"
:body "the quick brown fox"}}))
(prn
(send-ios-push
push-creds
"endpoint-arn"
nil)))