Skip to content

Commit df3aead

Browse files
committed
added support for creating redirect urls
1 parent 8289710 commit df3aead

6 files changed

Lines changed: 92 additions & 17 deletions

File tree

‎CHANGELOG‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@
77
* Add support for add_to_many batch operation
88

99

10+
2.3.3
11+
=====
12+
:release-date: 2015-10-07
13+
:by: Thierry Schellenbach
14+
15+
* Added support for creating redirect urls
16+
17+
1018
2.3.0
1119
=====
1220
:release-date: 2015-06-11

‎stream/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
__copyright__ = 'Copyright 2014, Thierry Schellenbach'
66
__credits__ = ['Thierry Schellenbach, mellowmorning.com, @tschellenbach']
77
__license__ = 'BSD'
8-
__version__ = '2.3.2'
8+
__version__ = '2.3.3'
99
__maintainer__ = 'Thierry Schellenbach'
1010
__email__ = 'thierryschellenbach@gmail.com'
1111
__status__ = 'Production'

‎stream/client.py‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
from datetime import datetime
2-
from requests.adapters import HTTPAdapter
3-
from stream import exceptions, serializer
4-
from stream.signing import sign
5-
from stream.signing import jwt_scope_token
2+
import json
63
import logging
74
import os
5+
6+
from httpsig.requests_auth import HTTPSignatureAuth
7+
import jwt
88
import requests
9+
from requests.adapters import HTTPAdapter
10+
from stream import exceptions, serializer
11+
from stream.signing import sign
912
from stream.utils import validate_feed_slug, validate_user_id
10-
from httpsig.requests_auth import HTTPSignatureAuth
13+
from requests import Request
1114

1215

1316
logger = logging.getLogger(__name__)
@@ -55,6 +58,8 @@ def __init__(self, api_key, api_secret, app_id, version='v1.0', timeout=6.0, bas
5558
self.base_url = base_url
5659
elif location is not None:
5760
self.base_url = 'https://%s-api.getstream.io/api/' % location
61+
62+
self.base_analytics_url = 'https://analytics.getstream.io/analytics/'
5863

5964
self.session = requests.Session()
6065
# TODO: turn this back on after we verify it doesnt retry on slower requests
@@ -131,8 +136,21 @@ def _make_signed_request(self, method_name, relative_url, params=None, data=None
131136
response.url, headers, data)
132137
return self._parse_response(response)
133138

134-
def create_feed_jwt_token(self, feed, resource, action):
135-
return jwt_scope_token(self.api_secret, feed.feed_together, resource, action)
139+
def create_jwt_token(self, resource, action, feed_id=None, user_id=None):
140+
'''
141+
Setup the payload for the given resource, action, feed or user
142+
and encode it using jwt
143+
'''
144+
payload = {
145+
'action': action,
146+
'resource': resource
147+
}
148+
if feed_id is not None:
149+
payload['feed_id'] = feed_id
150+
if user_id is not None:
151+
payload['user_id'] = user_id
152+
print payload
153+
return jwt.encode(payload, self.api_secret)
136154

137155
def _make_request(self, method, relative_url, signature, params=None, data=None):
138156
params = params or {}
@@ -217,3 +235,24 @@ def follow_many(self, follows):
217235
218236
'''
219237
self._make_signed_request('post', 'follow_many/', data=follows)
238+
239+
def create_redirect_url(self, target_url, user_id, events):
240+
'''
241+
Creates a redirect url for tracking the given events in the context
242+
of an email using Stream's analytics platform. Learn more at
243+
getstream.io/personalization
244+
'''
245+
# generate the JWT token
246+
auth_token = self.create_jwt_token('redirect_and_track', '*', user_id=user_id)
247+
# setup the params
248+
params = dict(auth_type='jwt', authorization=auth_token, url=target_url)
249+
params['api_key'] = self.api_key
250+
params['events'] = json.dumps(events)
251+
url = self.base_analytics_url + 'redirect/'
252+
# we get the url from the prepare request, this skips issues with
253+
# python's urlencode implementation
254+
request = Request('GET', url, params=params)
255+
prepared_request = request.prepare()
256+
# validate the target url is valid
257+
Request('GET', target_url).prepare()
258+
return prepared_request.url

‎stream/feed.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def create_scope_token(self, resource, action):
2626
'''
2727
creates the JWT token to perform an action on a owned resource
2828
'''
29-
return self.client.create_feed_jwt_token(self, resource, action)
29+
return self.client.create_jwt_token(resource, action, feed_id=self.feed_together)
3030

3131
def get_readonly_token(self):
3232
'''

‎stream/signing.py‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,3 @@ def sign(api_secret, feed_id):
2626
token = urlsafe_digest.decode('ascii')
2727
return token
2828

29-
def jwt_scope_token(api_secret, feed_id, resource, action):
30-
payload = {
31-
'action': action,
32-
'feed_id': feed_id,
33-
'resource': resource
34-
}
35-
return jwt.encode(payload, api_secret)

‎stream/tests.py‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
import os
99
import datetime
1010
from stream import serializer
11-
from requests.exceptions import ConnectionError
11+
from requests.exceptions import ConnectionError, MissingSchema
12+
from urlparse import urlparse
1213

1314

1415
def connect_debug():
@@ -619,3 +620,37 @@ def test_add_to_many(self):
619620
for feed in feeds:
620621
feed = self.c.feed(*feed.split(':'))
621622
self.assertEqual(feed.get()['results'][0]['custom'], 'data')
623+
624+
def test_create_email_redirect(self):
625+
expected_parts = ['https://analytics.getstream.io/analytics/redirect/',
626+
'auth_type=jwt',
627+
'url=http%3A%2F%2Fgoogle.com%2F%3Fa%3Db%26c%3Dd',
628+
'api_key=ahj2ndz7gsan',
629+
'authorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY3Rpb24iOiIqIiwidXNlcl9pZCI6InRvbW1hc28iLCJyZXNvdXJjZSI6InJlZGlyZWN0X2FuZF90cmFjayJ9.pQ2cBmC7l0WGP9LP7RrvLEbtrw8YWcFtjOqSfoSr2s0',
630+
'events=%5B%7B%22foreign_ids%22%3A+%5B%22tweet%3A1%22%2C+%22tweet%3A2%22%2C+%22tweet%3A3%22%2C+%22tweet%3A4%22%2C+%22tweet%3A5%22%5D%2C+%22feed_id%22%3A+%22user%3Aglobal%22%2C+%22user_id%22%3A+%22tommaso%22%2C+%22location%22%3A+%22email%22%7D%2C+%7B%22user_id%22%3A+%22tommaso%22%2C+%22label%22%3A+%22click%22%2C+%22feed_id%22%3A+%22user%3Aglobal%22%2C+%22location%22%3A+%22email%22%2C+%22position%22%3A+3%2C+%22foreign_id%22%3A+%22tweet%3A1%22%7D%5D',
631+
]
632+
engagement = {'foreign_id': 'tweet:1', 'label': 'click', 'position': 3, 'user_id': 'tommaso', 'location': 'email', 'feed_id': 'user:global'}
633+
impression = {'foreign_ids': ['tweet:1', 'tweet:2', 'tweet:3', 'tweet:4', 'tweet:5'], 'user_id':
634+
'tommaso', 'location': 'email', 'feed_id': 'user:global'}
635+
events = [impression, engagement]
636+
target_url = 'http://google.com/?a=b&c=d'
637+
user_id = 'tommaso'
638+
redirect_url = self.c.create_redirect_url(target_url, user_id, events)
639+
640+
for part in expected_parts:
641+
if part not in redirect_url:
642+
raise ValueError('didnt find %s in url \n %s' % (part, redirect_url))
643+
644+
def test_email_redirect_invalid_target(self):
645+
engagement = {'foreign_id': 'tweet:1', 'label': 'click', 'position': 3, 'user_id': 'tommaso', 'location': 'email', 'feed_id': 'user:global'}
646+
impression = {'foreign_ids': ['tweet:1', 'tweet:2', 'tweet:3', 'tweet:4', 'tweet:5'], 'user_id':
647+
'tommaso', 'location': 'email', 'feed_id': 'user:global'}
648+
events = [impression, engagement]
649+
# no protocol specified, this should raise an error
650+
target_url = 'google.com'
651+
user_id = 'tommaso'
652+
create_redirect = lambda : self.c.create_redirect_url(target_url, user_id, events)
653+
self.assertRaises(MissingSchema, create_redirect)
654+
655+
656+

0 commit comments

Comments
 (0)