forked from sudheesh001/loklak_api_python
-
Notifications
You must be signed in to change notification settings - Fork 26
/
loklak.py
502 lines (439 loc) · 19 KB
/
loklak.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#!/usr/bin/env python
# encoding: utf-8
"""The module that handles the main interface of loklak."""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import json
import re
import requests
from xmljson import badgerfish as bf
import lxml.etree as et
from json import dumps
import csv
class Loklak(object):
"""The fields for the Loklak object.
Additionaly, it contains methods that can be used for accessing
the Loklak API services like geocode, markdown, etc.
"""
baseUrl = 'http://api.loklak.org/'
baseUrlSusi = 'https://api.susi.ai/'
name = None
followers = None
following = None
query = None
since = None
until = None
source = None
count = None
fields = None
from_user = None
fields = None
limit = None
action = None
data = {}
def __init__(self, baseUrl='http://api.loklak.org/'):
"""Loklak class constructor.
Args:
baseUrl (str): Base URL for accessing the APIs (default=http://api.loklak.org/).
"""
baseUrl = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', baseUrl)
try:
if baseUrl[0]:
if baseUrl[0] != 'http://api.loklak.org/':
url_test = self.hello()
if url_test['status'] == 'ok':
self.baseUrl = baseUrl[0]
else:
self.baseUrl = baseUrl[0]
except IndexError:
pass
def getBaseUrl(self):
"""Return the string value of baseUrl."""
return self.baseUrl
def status(self, status_application='api/status.json'):
"""Retrieve a json response about the status of the server."""
url_to_give = self.baseUrl + status_application
return_to_user = requests.get(url_to_give)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return json.dumps(return_to_user)
def xmlToJson(self, xmlData = None):
"""Convert XML to JSON as the service."""
jsonData = '[]'
if xmlData:
jsonData = dumps(bf.data(et.fromstring(xmlData)))
return jsonData
def csvToJson(self, csvData = None, fieldnamesList = None):
"""Convert CSV to JSON as the service."""
jsonData = ''
if csvData:
data = csv.DictReader( csvData, fieldnames = fieldnamesList)
jsonData = json.dumps( [ row for row in data ] )
return out
def hello(self):
"""Retrieve a json response about the basic status of the server."""
hello_application = 'api/hello.json'
url_to_give = self.baseUrl+hello_application
return_to_user = requests.get(url_to_give)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return json.dumps(return_to_user)
def geocode(self, places=None):
"""Provide geocoding of place names to location coordinates.
Args:
places (list): A list of place names.
Examples:
>>> l.geocode(['Barcelona'])
{u'locations': {u'Barcelona': {u'country': u'Spain',
u'country_code': u'ES',
u'location':[2.15898974899153,
41.38879005861875],
...
Returns:
json: The geocoding results based on the given place(s) name.
"""
geo_application = 'api/geocode.json'
url_to_give = self.baseUrl+geo_application
params = {}
params['places'] = places
return_to_user = requests.get(url_to_give, params=params)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return json.dumps(return_to_user)
def get_map(self, latitude, longitude, width=500, height=500,
zoom=8, text=""):
"""Visualize map using Loklak service.
Args:
latitude (float): Latitude value.
longtitude (float): Longitude value.
width (int): Width (default=500).
height (int): Height (default=500).
zoom (int): Zoom value (default=8).
text (str): Value of text like Hello.
Returns:
bytes: An encoded map image.
"""
map_application = 'vis/map.png'
params = {'text': text, 'mlat': latitude, 'mlon': longitude,
'width': width, 'height': height, 'zoom': zoom}
return_to_user = requests.get(self.baseUrl + map_application,
params=params, stream=True)
if return_to_user.status_code == 200:
return return_to_user.raw.read()
else:
return ''
def get_markdown(self, text, color_text="000000", color_bg="ffffff",
padding="10", uppercase="true"):
"""Provide an image with text on it.
Args:
text (str): Text to be printed, markdown possible.
color_text: 6-character hex code for the color.
color_bg: 6-character hex code for the color.
padding: Space around text.
uppercase: <true|false> by default true. If true the text is printed UPPERCASE.
Returns:
bytes: An encoded image.
"""
map_application = 'vis/markdown.png'
params = {'text': text, 'color_text': color_text, 'color_background': color_bg,
'padding': padding, 'uppercase': uppercase}
return_to_user = requests.get(self.baseUrl + map_application,
params=params, stream=True)
if return_to_user.status_code == 200:
return return_to_user.raw.read()
else:
return ''
def peers(self):
"""Retrieve the peers of a user."""
peers_application = 'api/peers.json'
url_to_give = self.baseUrl+peers_application
return_to_user = requests.get(url_to_give)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return json.dumps(return_to_user)
def push(self, data=None):
"""Push servlet for twitter like messages.
Note:
The API of this function has a restrictions
which only localhost clients are granted.
Args:
data: A search result object.
Returns:
json: Status about the message is pushed or not.
"""
push_application = 'api/push.json'
url_to_give = self.baseUrl + push_application
headers = {
'User-Agent': ('Mozilla/5.0 (Android 4.4; Mobile; rv:41.0)'
' Gecko/41.0 Firefox/41.0'),
'From': 'info@loklak.org'
}
if data:
self.data = data
params = {}
params['data'] = json.dumps(self.data)
return_to_user = requests.post(url_to_give, data=params)
if return_to_user:
return return_to_user.json()
else:
return_to_user = {}
return_to_user['error'] = ('Something went wrong,'
' looks like the query is wrong.')
return json.dumps(return_to_user)
else:
return_to_user = {}
return_to_user['error'] = ('Something went wrong,'
' looks like the data is not correct.')
return json.dumps(return_to_user)
def user(self, name=None, followers=None, following=None):
"""Retrieve Twitter user information.
Args:
name (str): Twitter screen name of the user.
followers (int): Followers of the user.
following (int): Accounts the user is following.
Returns:
json: User information, including who they are following, and who follows them.
"""
user_application = 'api/user.json'
url_to_give = self.baseUrl+user_application
self.name = name
self.followers = followers
self.following = following
if name:
params = {}
params['screen_name'] = self.name
if followers is not None:
params['followers'] = self.followers
if following is not None:
params['following'] = self.following
return_to_user = requests.get(url_to_give, params=params)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return json.dumps(return_to_user)
else:
return_to_user = {}
return_to_user['error'] = ('No user name given to query. Please'
' check and try again')
return json.dumps(return_to_user)
def settings(self):
"""Retrieve the settings of the application.
Note:
The API of this function has a restrictions
which only localhost clients are granted.
Returns:
json: The settings of the application.
"""
settings_application = 'api/settings.json'
url_to_give = self.baseUrl + settings_application
return_to_user = requests.get(url_to_give)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return_to_user['error'] = ('This API has access restrictions:'
' only localhost clients are granted.')
return json.dumps(return_to_user)
def search(self, query=None, since=None, until=None, from_user=None, count=None):
"""Handle the searching.
Args:
query (str): Query term.
since (str): Only messages after the date (including the date), <date>=yyyy-MM-dd or yyyy-MM-dd_HH:mm.
until (str): Only messages before the date (excluding the date), <date>=yyyy-MM-dd or yyyy-MM-dd_HH:mm.
from_user (str): Only messages published by the user.
count (int): The wanted number of results.
Returns:
json: Search results from API.
"""
search_application = 'api/search.json'
url_to_give = self.baseUrl+search_application
self.query = query
self.since = since
self.until = until
self.from_user = from_user
self.count = count
if query:
params = {}
params['query'] = self.query
if since:
params['query'] = params['query'] + ' since:'+self.since
if until:
params['query'] = params['query'] + ' until:'+self.until
if from_user:
params['query'] = params['query'] + ' from:'+self.from_user
if count:
params['count'] = self.count
return_to_user = requests.get(url_to_give, params=params)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return_to_user['error'] = ('Something went wrong, looks like'
' the server is down.')
return json.dumps(return_to_user)
else:
return_to_user = {}
return_to_user['error'] = ('No Query string has been'
' given to query for an account')
return json.dumps(return_to_user)
def suggest(self, query=None, count=None, order=None, orderby=None,since=None, until=None):
"""Retrieve a list of queries based on the given criteria.
Args:
query (str): To get a list of queries which match; to get all latest: leave query empty.
count (int): Number of queries.
order (str): Possible values: desc, asc; default: desc.
orderby (str): A field name of the query index schema, i.e. retrieval_next or query_count.
since (str): Left bound for a query time.
until (str): Right bound for a query time.
Returns:
json: A list of queries in the given order.
"""
suggest_application = 'api/suggest.json'
url_to_give = self.baseUrl+suggest_application
params = {}
if query:
params['query'] = query
if count:
params['count'] = count
if order:
params['order'] = order
if since:
params['since'] = since
if until:
params['until'] = until
print(params)
return_to_user = requests.get(url_to_give, params=params)
print(return_to_user.url)
if return_to_user.status_code == 200:
return return_to_user.json()
else :
return_to_user = {}
return_to_user['error'] = ('Something went wrong,'
' looks like the server is down.')
return json.dumps(return_to_user)
def aggregations(self, query=None, since=None, until=None,
fields=None, limit=6, count=0):
"""Give the aggregations of the application.
Args:
query (str): Query term.
since (str): Only messages after the date (including the date), <date>=yyyy-MM-dd or yyyy-MM-dd_HH:mm.
until (str): Only messages before the date (excluding the date), <date>=yyyy-MM-dd or yyyy-MM-dd_HH:mm.
fields (str): Aggregation fields for search facets, like "created_at,mentions".
limit (int): A limitation of number of facets for each aggregation.
count (int): The wanted number of results.
Returns:
json: Aggregations of the application.
"""
aggregations_application = 'api/search.json'
url_to_give = self.baseUrl+aggregations_application
self.query = query
self.since = since
self.until = until
self.fields = fields
self.limit = limit
self.count = count
if query:
params = {}
params['query'] = self.query
if since:
params['query'] = params['query']+' since:'+self.since
if until:
params['query'] = params['query']+' until:'+self.until
if fields:
if isinstance(fields, list):
params['fields'] = ','.join(self.fields)
else:
params['fields'] = self.fields
params['count'] = self.count
params['source'] = 'cache'
return_to_user = requests.get(url_to_give, params=params)
if return_to_user.status_code == 200:
return return_to_user
else:
return_to_user = {}
return_to_user['error'] = ('Something went wrong,'
' looks like the server is down.')
return json.dumps(return_to_user)
else:
return_to_user = {}
return_to_user['error'] = ('No Query string has been given to run '
'query for aggregations')
return json.dumps(return_to_user)
def account(self, name=None, action=None, data=None):
"""Provide the storage and retrieval of the user account data.
Note:
The API of this function has a restrictions which only localhost
clients are granted. If you want to retrieve the user account
information, just fill the 'name' argument, and do not fill any
args.
If you want to store one or more account objects, fill the
'action' argument with "update" then submit that object
(these objects) inside the 'data' argument.
The data object must have this following form:
{
"screen_name" : "test", // primary key for the user
"source_type" : "TWITTER", // the application which created the token, by default "TWITTER"
"oauth_token" : "abc", // the oauth token
"oauth_token_secret" : "def", // the oauth token_secret
"authentication_first" : "2015-06-07T09:39:22.341Z", // optional
"authentication_latest" : "2015-06-07T09:39:22.341Z", // optional
"apps" : {"wall" : {"type" : "horizontal"}} // any json
}
Args:
name (str): Twitter screen name of the user.
action (str): Proper values are either <empty> or 'update'.
data (str): An object to store (if you set action=update, you must submit this data object).
Returns:
json: Information about user's account if the 'action' argument is empty (retrieving).
"""
account_application = 'account.json'
url_to_give = 'http://localhost:9000/api/'+account_application
self.name = name
self.data = data
self.action = action
# Simple GET Query
headers = {
'User-Agent': ('Mozilla/5.0 (Android 4.4; Mobile; rv:41.0)'
' Gecko/41.0 Firefox/41.0'),
'From': 'info@loklak.org'
}
if name:
params = {}
params['screen_name'] = self.name
return_to_user = requests.get(url_to_give, params=params,
headers=headers)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return_to_user['error'] = ('Something went wrong,'
' looks like the query is wrong.')
return json.dumps(return_to_user)
# if action = update and data is provided, then make request
elif self.action == 'update' and data:
params = {}
params['action'] = self.action
params['data'] = self.data
return_to_user = requests.post(url_to_give,
params=params, headers=headers)
if return_to_user.status_code == 200:
return return_to_user.json()
else:
return_to_user = {}
return_to_user['error'] = ('Something went wrong,'
' looks like the query is wrong.')
return json.dumps(return_to_user)
else:
return_to_user = {}
return_to_user['error'] = ('No Query string has been given'
' given to query for an account')
return json.dumps(return_to_user)