-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
steemconnect.py
295 lines (246 loc) · 9.91 KB
/
steemconnect.py
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# This Python file uses the following encoding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
import json
try:
from urllib.parse import urlparse, urlencode, urljoin
except ImportError:
from urlparse import urlparse, urljoin
from urllib import urlencode
import requests
from .storage import configStorage as config
from six import PY2
from beem.instance import shared_steem_instance
from beem.amount import Amount
class SteemConnect(object):
""" SteemConnect
:param str scope: comma separated string with scopes
login,offline,vote,comment,delete_comment,comment_options,custom_json,claim_reward_balance
.. code-block:: python
# Run the login_app in examples and login with a account
from beem import Steem
from beem.steemconnect import SteemConnect
from beem.comment import Comment
sc2 = SteemConnect(client_id="beem.app")
steem = Steem(steemconnect=sc2)
steem.wallet.unlock("supersecret-passphrase")
post = Comment("author/permlink", steem_instance=steem)
post.upvote(voter="test") # replace "test" with your account
Examples for creating steemconnect v2 urls for broadcasting in browser:
.. testoutput::
from beem import Steem
from beem.account import Account
from beem.steemconnect import SteemConnect
from pprint import pprint
steem = Steem(nobroadcast=True, unsigned=True)
sc2 = SteemConnect(steem_instance=steem)
acc = Account("test", steem_instance=steem)
pprint(sc2.url_from_tx(acc.transfer("test1", 1, "STEEM", "test")))
.. testcode::
'https://v2.steemconnect.com/sign/transfer?from=test&to=test1&amount=1.000+STEEM&memo=test'
.. testoutput::
from beem import Steem
from beem.transactionbuilder import TransactionBuilder
from beembase import operations
from beem.steemconnect import SteemConnect
from pprint import pprint
stm = Steem()
tx = TransactionBuilder(steem_instance=stm)
op = operations.Transfer(**{"from": 'test',
"to": 'test1',
"amount": '1.000 STEEM',
"memo": 'test'})
tx.appendOps(op)
pprint(sc2.url_from_tx(tx)
.. testcode::
'https://v2.steemconnect.com/sign/transfer?from=test&to=test1&amount=1.000+STEEM&memo=test'
"""
def __init__(self, steem_instance=None, *args, **kwargs):
self.steem = steem_instance or shared_steem_instance()
self.access_token = None
self.get_refresh_token = kwargs.get("get_refresh_token", False)
self.hot_sign_redirect_uri = kwargs.get("hot_sign_redirect_uri", config["hot_sign_redirect_uri"])
if self.hot_sign_redirect_uri == "":
self.hot_sign_redirect_uri = None
self.client_id = kwargs.get("client_id", config["sc2_client_id"])
self.scope = kwargs.get("scope", "login")
self.oauth_base_url = kwargs.get("oauth_base_url", config["oauth_base_url"])
self.sc2_api_url = kwargs.get("sc2_api_url", config["sc2_api_url"])
@property
def headers(self):
return {'Authorization': self.access_token}
def get_login_url(self, redirect_uri, **kwargs):
""" Returns a login url for receiving token from steemconnect
"""
client_id = kwargs.get("client_id", self.client_id)
scope = kwargs.get("scope", self.scope)
get_refresh_token = kwargs.get("get_refresh_token", self.get_refresh_token)
params = {
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": scope,
}
if get_refresh_token:
params.update({
"response_type": "code",
})
if PY2:
return urljoin(
self.oauth_base_url,
"authorize?" + urlencode(params).replace('%2C', ','))
else:
return urljoin(
self.oauth_base_url,
"authorize?" + urlencode(params, safe=","))
def get_access_token(self, code):
post_data = {
"grant_type": "authorization_code",
"code": code,
"client_id": self.client_id,
"client_secret": self.steem.wallet.getTokenForAccountName(self.client_id),
}
r = requests.post(
urljoin(self.sc2_api_url, "oauth2/token/"),
data=post_data
)
return r.json()
def me(self, username=None):
""" Calls the me function from steemconnect
.. code-block:: python
from beem.steemconnect import SteemConnect
sc2 = SteemConnect()
sc2.steem.wallet.unlock("supersecret-passphrase")
sc2.me(username="test")
"""
if username:
self.set_username(username)
url = urljoin(self.sc2_api_url, "me/")
r = requests.post(url, headers=self.headers)
return r.json()
def set_access_token(self, access_token):
""" Is needed for broadcast() and me()
"""
self.access_token = access_token
def set_username(self, username, permission="posting"):
""" Set a username for the next broadcast() or me operation()
The necessary token is fetched from the wallet
"""
if permission != "posting":
self.access_token = None
return
self.access_token = self.steem.wallet.getTokenForAccountName(username)
def broadcast(self, operations, username=None):
""" Broadcast a operations
Sample operations:
.. code-block:: js
[
[
'vote', {
'voter': 'gandalf',
'author': 'gtg',
'permlink': 'steem-pressure-4-need-for-speed',
'weight': 10000
}
]
]
"""
url = urljoin(self.sc2_api_url, "broadcast/")
data = {
"operations": operations,
}
if username:
self.set_username(username)
headers = self.headers.copy()
headers.update({
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
})
r = requests.post(url, headers=headers, data=json.dumps(data))
try:
return r.json()
except ValueError:
return r.content
def refresh_access_token(self, code, scope):
post_data = {
"grant_type": "refresh_token",
"refresh_token": code,
"client_id": self.client_id,
"client_secret": self.steem.wallet.getTokenForAccountName(self.client_id),
"scope": scope,
}
r = requests.post(
urljoin(self.sc2_api_url, "oauth2/token/"),
data=post_data,
)
return r.json()
def revoke_token(self, access_token):
post_data = {
"access_token": access_token,
}
r = requests.post(
urljoin(self.sc2_api_url, "oauth2/token/revoke"),
data=post_data
)
return r.json()
def update_user_metadata(self, metadata):
put_data = {
"user_metadata": metadata,
}
r = requests.put(
urljoin(self.sc2_api_url, "me/"),
data=put_data, headers=self.headers)
return r.json()
def url_from_tx(self, tx, redirect_uri=None):
""" Creates a link for broadcasting an operation
:param dict tx: includes the operation, which should be broadcast
:param str redirect_uri: Redirects to this uri, when set
"""
if not isinstance(tx, dict):
tx = tx.json()
if "operations" not in tx or not tx["operations"]:
return ''
urls = []
operations = tx["operations"]
for op in operations:
operation = op[0]
params = op[1]
for key in params:
value = params[key]
if isinstance(value, list) and len(value) == 3:
try:
amount = Amount(value, steem_instance=self.steem)
params[key] = str(amount)
except:
amount = None
elif isinstance(value, bool):
if value:
params[key] = 1
else:
params[key] = 0
urls.append(self.create_hot_sign_url(operation, params, redirect_uri=redirect_uri))
if len(urls) == 1:
return urls[0]
else:
return urls
def create_hot_sign_url(self, operation, params, redirect_uri=None):
""" Creates a link for broadcasting an operation
:param str operation: operation name (e.g.: vote)
:param dict params: operation dict params
:param str redirect_uri: Redirects to this uri, when set
"""
if not isinstance(operation, str) or not isinstance(params, dict):
raise ValueError("Invalid Request.")
base_url = self.sc2_api_url.replace("/api", "")
if redirect_uri == "":
redirect_uri = None
if redirect_uri is None and self.hot_sign_redirect_uri is not None:
redirect_uri = self.hot_sign_redirect_uri
if redirect_uri is not None:
params.update({"redirect_uri": redirect_uri})
params = urlencode(params)
url = urljoin(base_url, "sign/%s" % operation)
url += "?" + params
return url