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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
|
## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2014-15 Stephen Blum
## http://www.pubnub.com/
## -----------------------------------
## PubNub 3.7.1 Real-time Push Cloud API
## -----------------------------------
try:
import json
except ImportError:
import simplejson as json
import time
import hashlib
import uuid as uuid_lib
import random
import sys
from base64 import urlsafe_b64encode
from base64 import encodestring, decodestring
import hmac
from Crypto.Cipher import AES
from Crypto.Hash import MD5
try:
from hashlib import sha256
digestmod = sha256
except ImportError:
import Crypto.Hash.SHA256 as digestmod
sha256 = digestmod.new
##### vanilla python imports #####
try:
from urllib.parse import quote
except ImportError:
from urllib2 import quote
try:
import urllib.request
except ImportError:
import urllib2
try:
import requests
from requests.adapters import HTTPAdapter
except ImportError:
pass
#import urllib
import socket
import sys
import threading
from threading import current_thread
try:
import urllib3.HTTPConnection
default_socket_options = urllib3.HTTPConnection.default_socket_options
except:
default_socket_options = []
default_socket_options += [
# Enable TCP keepalive
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
]
if sys.platform.startswith("linux"):
default_socket_options += [
# Send first keepalive packet 200 seconds after last data packet
(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 200),
# Resend keepalive packets every second, when unanswered
(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1),
# Close the socket after 5 unanswered keepalive packets
(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
]
elif sys.platform.startswith("darwin"):
# From /usr/include/netinet/tcp.h
# idle time used when SO_KEEPALIVE is enabled
socket.TCP_KEEPALIVE = socket.TCP_KEEPALIVE \
if hasattr(socket, 'TCP_KEEPALIVE') \
else 0x10
# interval between keepalives
socket.TCP_KEEPINTVL = socket.TCP_KEEPINTVL \
if hasattr(socket, 'TCP_KEEPINTVL') \
else 0x101
# number of keepalives before close
socket.TCP_KEEPCNT = socket.TCP_KEEPCNT \
if hasattr(socket, 'TCP_KEEPCNT') \
else 0x102
default_socket_options += [
# Send first keepalive packet 200 seconds after last data packet
(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, 200),
# Resend keepalive packets every second, when unanswered
(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1),
# Close the socket after 5 unanswered keepalive packets
(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
]
"""
# The Windows code is currently untested
elif sys.platform.startswith("win"):
import struct
from urllib3.connectionpool import HTTPConnectionPool, HTTPSConnectionPool
def patch_socket_keepalive(conn):
conn.sock.ioctl(socket.SIO_KEEPALIVE_VALS, (
# Enable TCP keepalive
1,
# Send first keepalive packet 200 seconds after last data packet
200,
# Resend keepalive packets every second, when unanswered
1
))
class PubnubHTTPConnectionPool(HTTPConnectionPool):
def _validate_conn(self, conn):
super(PubnubHTTPConnectionPool, self)._validate_conn(conn)
class PubnubHTTPSConnectionPool(HTTPSConnectionPool):
def _validate_conn(self, conn):
super(PubnubHTTPSConnectionPool, self)._validate_conn(conn)
import urllib3.poolmanager
urllib3.poolmanager.pool_classes_by_scheme = {
'http' : PubnubHTTPConnectionPool,
'https' : PubnubHTTPSConnectionPool
}
"""
##################################
##### Tornado imports and globals #####
try:
import tornado.httpclient
import tornado.ioloop
from tornado.stack_context import ExceptionStackContext
ioloop = tornado.ioloop.IOLoop.instance()
except ImportError:
pass
#######################################
##### Twisted imports and globals #####
try:
from twisted.web.client import getPage
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent, ContentDecoderAgent
from twisted.web.client import RedirectAgent, GzipDecoder
from twisted.web.client import HTTPConnectionPool
from twisted.web.http_headers import Headers
from twisted.internet.ssl import ClientContextFactory
from twisted.internet.task import LoopingCall
import twisted
from twisted.python.compat import (
_PY3, unicode, intToBytes, networkString, nativeString)
pnconn_pool = HTTPConnectionPool(reactor, persistent=True)
pnconn_pool.maxPersistentPerHost = 100000
pnconn_pool.cachedConnectionTimeout = 15
pnconn_pool.retryAutomatically = True
class WebClientContextFactory(ClientContextFactory):
def getContext(self, hostname, port):
return ClientContextFactory.getContext(self)
class PubNubPamResponse(Protocol):
def __init__(self, finished):
self.finished = finished
def dataReceived(self, bytes):
self.finished.callback(bytes)
class PubNubResponse(Protocol):
def __init__(self, finished):
self.finished = finished
def dataReceived(self, bytes):
self.finished.callback(bytes)
except ImportError:
pass
#######################################
def get_data_for_user(data):
try:
if 'message' in data and 'payload' in data:
return {'message': data['message'], 'payload': data['payload']}
else:
return data
except TypeError:
return data
class PubnubCrypto2():
def pad(self, msg, block_size=16):
padding = block_size - (len(msg) % block_size)
return msg + chr(padding) * padding
def depad(self, msg):
return msg[0:-ord(msg[-1])]
def getSecret(self, key):
return hashlib.sha256(key).hexdigest()
def encrypt(self, key, msg):
secret = self.getSecret(key)
Initial16bytes = '0123456789012345'
cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
enc = encodestring(cipher.encrypt(self.pad(msg)))
return enc
def decrypt(self, key, msg):
try:
secret = self.getSecret(key)
Initial16bytes = '0123456789012345'
cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
plain = self.depad(cipher.decrypt(decodestring(msg)))
except:
return msg
try:
return eval(plain)
except SyntaxError:
return plain
class PubnubCrypto3():
def pad(self, msg, block_size=16):
padding = block_size - (len(msg) % block_size)
return msg + (chr(padding) * padding).encode('utf-8')
def depad(self, msg):
return msg[0:-ord(msg[-1])]
def getSecret(self, key):
return hashlib.sha256(key.encode("utf-8")).hexdigest()
def encrypt(self, key, msg):
secret = self.getSecret(key)
Initial16bytes = '0123456789012345'
cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
return encodestring(
cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8')
def decrypt(self, key, msg):
secret = self.getSecret(key)
Initial16bytes = '0123456789012345'
cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
return (cipher.decrypt(
decodestring(msg.encode('utf-8')))).decode('utf-8')
class PubnubBase(object):
def __init__(
self,
publish_key,
subscribe_key,
secret_key=False,
cipher_key=False,
auth_key=None,
ssl_on=False,
origin='pubsub.pubnub.com',
uuid=None
):
"""Pubnub Class
Provides methods to communicate with Pubnub cloud
Attributes:
publish_key: Publish Key
subscribe_key: Subscribe Key
secret_key: Secret Key
cipher_key: Cipher Key
auth_key: Auth Key (used with Pubnub Access Manager i.e. PAM)
ssl: SSL enabled ?
origin: Origin
"""
self.origin = origin
self.version = '3.7.1'
self.limit = 1800
self.publish_key = publish_key
self.subscribe_key = subscribe_key
self.secret_key = secret_key
self.cipher_key = cipher_key
self.ssl = ssl_on
self.auth_key = auth_key
self.STATE = {}
if self.ssl:
self.origin = 'https://' + self.origin
else:
self.origin = 'http://' + self.origin
self.uuid = uuid or str(uuid_lib.uuid4())
if type(sys.version_info) is tuple:
self.python_version = 2
self.pc = PubnubCrypto2()
else:
if sys.version_info.major == 2:
self.python_version = 2
self.pc = PubnubCrypto2()
else:
self.python_version = 3
self.pc = PubnubCrypto3()
if not isinstance(self.uuid, str):
raise AttributeError("uuid must be a string")
def _pam_sign(self, msg):
sign = urlsafe_b64encode(hmac.new(
self.secret_key.encode("utf-8"),
msg.encode("utf-8"),
sha256
).digest())
return quote(sign, safe="")
def set_u(self, u=False):
self.u = u
def _pam_auth(self, query, apicode=0, callback=None, error=None):
if 'timestamp' not in query:
query['timestamp'] = int(time.time())
## Global Grant?
if 'auth' in query and not query['auth']:
del query['auth']
if 'channel' in query and not query['channel']:
del query['channel']
if 'channel-group' in query and not query['channel-group']:
del query['channel-group']
params = "&".join([
x + "=" + quote(
str(query[x]), safe=""
) for x in sorted(query)
])
sign_input = "{subkey}\n{pubkey}\n{apitype}\n{params}".format(
subkey=self.subscribe_key,
pubkey=self.publish_key,
apitype="audit" if (apicode) else "grant",
params=params
)
query['signature'] = self._pam_sign(sign_input)
return self._request({"urlcomponents": [
'v1', 'auth', "audit" if (apicode) else "grant",
'sub-key',
self.subscribe_key
], 'urlparams': query},
self._return_wrapped_callback(callback),
self._return_wrapped_callback(error))
def get_origin(self):
return self.origin
def set_auth_key(self, auth_key):
self.auth_key = auth_key
def get_auth_key(self):
return self.auth_key
def grant(self, channel=None, channel_group=None, auth_key=False, read=False,
write=False, manage=False, ttl=5, callback=None, error=None):
"""Method for granting permissions.
This function establishes subscribe and/or write permissions for
PubNub Access Manager (PAM) by setting the read or write attribute
to true. A grant with read or write set to false (or not included)
will revoke any previous grants with read or write set to true.
Permissions can be applied to any one of three levels:
1. Application level privileges are based on subscribe_key applying to all associated channels.
2. Channel level privileges are based on a combination of subscribe_key and channel name.
3. User level privileges are based on the combination of subscribe_key, channel and auth_key.
Args:
channel: (string) (optional)
Specifies channel name to grant permissions to.
If channel/channel_group is not specified, the grant applies to all
channels associated with the subscribe_key. If auth_key
is not specified, it is possible to grant permissions to
multiple channels simultaneously by specifying the channels
as a comma separated list.
channel_group: (string) (optional)
Specifies channel group name to grant permissions to.
If channel/channel_group is not specified, the grant applies to all
channels associated with the subscribe_key. If auth_key
is not specified, it is possible to grant permissions to
multiple channel groups simultaneously by specifying the channel groups
as a comma separated list.
auth_key: (string) (optional)
Specifies auth_key to grant permissions to.
It is possible to specify multiple auth_keys as comma
separated list in combination with a single channel name.
If auth_key is provided as the special-case value "null"
(or included in a comma-separated list, eg. "null,null,abc"),
a new auth_key will be generated and returned for each "null" value.
read: (boolean) (default: True)
Read permissions are granted by setting to True.
Read permissions are removed by setting to False.
write: (boolean) (default: True)
Write permissions are granted by setting to true.
Write permissions are removed by setting to false.
manage: (boolean) (default: True)
Manage permissions are granted by setting to true.
Manage permissions are removed by setting to false.
ttl: (int) (default: 1440 i.e 24 hrs)
Time in minutes for which granted permissions are valid.
Max is 525600 , Min is 1.
Setting ttl to 0 will apply the grant indefinitely.
callback: (function) (optional)
A callback method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado
error: (function) (optional)
An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Returns a dict in sync mode i.e. when callback argument is not given
The dict returned contains values with keys 'message' and 'payload'
Sample Response:
{
"message":"Success",
"payload":{
"ttl":5,
"auths":{
"my_ro_authkey":{"r":1,"w":0}
},
"subscribe_key":"my_subkey",
"level":"user",
"channel":"my_channel"
}
}
"""
return self._pam_auth({
'channel' : channel,
'channel-group' : channel_group,
'auth' : auth_key,
'r' : read and 1 or 0,
'w' : write and 1 or 0,
'm' : manage and 1 or 0,
'ttl' : ttl,
'pnsdk' : self.pnsdk
}, callback=callback, error=error)
def revoke(self, channel=None, channel_group=None, auth_key=None, ttl=1, callback=None, error=None):
"""Method for revoking permissions.
Args:
channel: (string) (optional)
Specifies channel name to revoke permissions to.
If channel/channel_group is not specified, the revoke applies to all
channels associated with the subscribe_key. If auth_key
is not specified, it is possible to grant permissions to
multiple channels simultaneously by specifying the channels
as a comma separated list.
channel_group: (string) (optional)
Specifies channel group name to revoke permissions to.
If channel/channel_group is not specified, the grant applies to all
channels associated with the subscribe_key. If auth_key
is not specified, it is possible to revoke permissions to
multiple channel groups simultaneously by specifying the channel groups
as a comma separated list.
auth_key: (string) (optional)
Specifies auth_key to revoke permissions to.
It is possible to specify multiple auth_keys as comma
separated list in combination with a single channel name.
If auth_key is provided as the special-case value "null"
(or included in a comma-separated list, eg. "null,null,abc"),
a new auth_key will be generated and returned for each "null" value.
ttl: (int) (default: 1440 i.e 24 hrs)
Time in minutes for which granted permissions are valid.
Max is 525600 , Min is 1.
Setting ttl to 0 will apply the grant indefinitely.
callback: (function) (optional)
A callback method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado
error: (function) (optional)
An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Returns a dict in sync mode i.e. when callback argument is not given
The dict returned contains values with keys 'message' and 'payload'
Sample Response:
{
"message":"Success",
"payload":{
"ttl":5,
"auths":{
"my_authkey":{"r":0,"w":0}
},
"subscribe_key":"my_subkey",
"level":"user",
"channel":"my_channel"
}
}
"""
return self._pam_auth({
'channel' : channel,
'channel-group' : channel_group,
'auth' : auth_key,
'r' : 0,
'w' : 0,
'ttl' : ttl,
'pnsdk' : self.pnsdk
}, callback=callback, error=error)
def audit(self, channel=None, channel_group=None, auth_key=None, callback=None, error=None):
"""Method for fetching permissions from pubnub servers.
This method provides a mechanism to reveal existing PubNub Access Manager attributes
for any combination of subscribe_key, channel and auth_key.
Args:
channel: (string) (optional)
Specifies channel name to return PAM
attributes optionally in combination with auth_key.
If channel/channel_group is not specified, results for all channels
associated with subscribe_key are returned.
If auth_key is not specified, it is possible to return
results for a comma separated list of channels.
channel_group: (string) (optional)
Specifies channel group name to return PAM
attributes optionally in combination with auth_key.
If channel/channel_group is not specified, results for all channels
associated with subscribe_key are returned.
If auth_key is not specified, it is possible to return
results for a comma separated list of channels.
auth_key: (string) (optional)
Specifies the auth_key to return PAM attributes for.
If only a single channel is specified, it is possible to return
results for a comma separated list of auth_keys.
callback: (function) (optional)
A callback method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado
error: (function) (optional)
An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Returns a dict in sync mode i.e. when callback argument is not given
The dict returned contains values with keys 'message' and 'payload'
Sample Response
{
"message":"Success",
"payload":{
"channels":{
"my_channel":{
"auths":{"my_ro_authkey":{"r":1,"w":0},
"my_rw_authkey":{"r":0,"w":1},
"my_admin_authkey":{"r":1,"w":1}
}
}
},
}
Usage:
pubnub.audit ('my_channel'); # Sync Mode
"""
return self._pam_auth({
'channel' : channel,
'channel-group' : channel_group,
'auth' : auth_key,
'pnsdk' : self.pnsdk
}, 1, callback=callback, error=error)
def encrypt(self, message):
"""Method for encrypting data.
This method takes plaintext as input and returns encrypted data.
This need not be called directly as enncryption/decryption is
taken care of transparently by Pubnub class if cipher key is
provided at time of initializing pubnub object
Args:
message: Message to be encrypted.
Returns:
Returns encrypted message if cipher key is set
"""
if self.cipher_key:
message = json.dumps(self.pc.encrypt(
self.cipher_key, json.dumps(message)).replace('\n', ''))
else:
message = json.dumps(message)
return message
def decrypt(self, message):
"""Method for decrypting data.
This method takes ciphertext as input and returns decrypted data.
This need not be called directly as enncryption/decryption is
taken care of transparently by Pubnub class if cipher key is
provided at time of initializing pubnub object
Args:
message: Message to be decrypted.
Returns:
Returns decrypted message if cipher key is set
"""
if self.cipher_key:
message = self.pc.decrypt(self.cipher_key, message)
return message
def _return_wrapped_callback(self, callback=None):
def _new_format_callback(response):
if 'payload' in response:
if (callback is not None):
callback_data = dict()
callback_data['payload'] = response['payload']
if 'message' in response:
callback_data['message'] = response['message']
callback(callback_data)
else:
if (callback is not None):
callback(response)
if (callback is not None):
return _new_format_callback
else:
return None
def leave_channel(self, channel, callback=None, error=None):
## Send leave
return self._request({"urlcomponents": [
'v2', 'presence',
'sub_key',
self.subscribe_key,
'channel',
channel,
'leave'
], 'urlparams': {'auth': self.auth_key, 'pnsdk' : self.pnsdk, "uuid": self.uuid,}},
callback=self._return_wrapped_callback(callback),
error=self._return_wrapped_callback(error))
def leave_group(self, channel_group, callback=None, error=None):
## Send leave
return self._request({"urlcomponents": [
'v2', 'presence',
'sub_key',
self.subscribe_key,
'channel',
',',
'leave'
], 'urlparams': {'auth': self.auth_key, 'pnsdk' : self.pnsdk, 'channel-group' : channel_group, "uuid": self.uuid,}},
callback=self._return_wrapped_callback(callback),
error=self._return_wrapped_callback(error))
def publish(self, channel, message, callback=None, error=None):
"""Publishes data on a channel.
The publish() method is used to send a message to all subscribers of a channel.
To publish a message you must first specify a valid publish_key at initialization.
A successfully published message is replicated across the PubNub Real-Time Network
and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by
setting ssl to True during initialization.
Published messages can also be encrypted with AES-256 simply by specifying a cipher_key
during initialization.
Args:
channel: (string)
Specifies channel name to publish messages to.
message: (string/int/double/dict/list)
Message to be published
callback: (optional)
A callback method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado
error: (optional)
An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado
Returns:
Sync Mode : list
Async Mode : None
The function returns the following formatted response:
[ Number, "Status", "Time Token"]
The output below demonstrates the response to a successful call:
[1,"Sent","13769558699541401"]
"""
message = self.encrypt(message)
## Send Message
return self._request({"urlcomponents": [
'publish',
self.publish_key,
self.subscribe_key,
'0',
channel,
'0',
message
], 'urlparams': {'auth': self.auth_key, 'pnsdk' : self.pnsdk}},
callback=self._return_wrapped_callback(callback),
error=self._return_wrapped_callback(error))
def presence(self, channel, callback, error=None):
"""Subscribe to presence events on a channel.
Only works in async mode
Args:
channel: Channel name ( string ) on which to listen for events
callback: A callback method should be passed as parameter.
If passed, the api works in async mode.
Required argument when working with twisted or tornado .
error: Optional variable. An error method can be passed as parameter.
If set, the api works in async mode.
Returns:
None
"""
return self.subscribe(channel+'-pnpres', callback=callback)
def presence_group(self, channel_group, callback, error=None):
"""Subscribe to presence events on a channel group.
Only works in async mode
Args:
channel_group: Channel group name ( string )
callback: A callback method should be passed to the method.
If passed, the api works in async mode.
Required argument when working with twisted or tornado .
error: Optional variable. An error method can be passed as parameter.
If passed, the api works in async mode.
Returns:
None
"""
return self.subscribe_group(channel_group+'-pnpres', callback=callback)
def here_now(self, channel, uuids=True, state=False, callback=None, error=None):
"""Get here now data.
You can obtain information about the current state of a channel including
a list of unique user-ids currently subscribed to the channel and the total
occupancy count of the channel by calling the here_now() function in your
application.
Args:
channel: (string) (optional)
Specifies the channel name to return occupancy results.
If channel is not provided, here_now will return data for all channels.
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Sync Mode: list
Async Mode: None
Response Format:
The here_now() method returns a list of uuid s currently subscribed to the channel.
uuids:["String","String", ... ,"String"] - List of UUIDs currently subscribed to the channel.
occupancy: Number - Total current occupancy of the channel.
Example Response:
{
occupancy: 4,
uuids: [
'123123234t234f34fq3dq',
'143r34f34t34fq34q34q3',
'23f34d3f4rq34r34rq23q',
'w34tcw45t45tcw435tww3',
]
}
"""
urlcomponents = [
'v2', 'presence',
'sub_key', self.subscribe_key
]
if (channel is not None and len(channel) > 0):
urlcomponents.append('channel')
urlcomponents.append(channel)
data = {'auth': self.auth_key, 'pnsdk' : self.pnsdk}
if state is True:
data['state'] = '1'
if uuids is False:
data['disable_uuids'] = '1'
## Get Presence Here Now
return self._request({"urlcomponents": urlcomponents,
'urlparams': data},
callback=self._return_wrapped_callback(callback),
error=self._return_wrapped_callback(error))
def history(self, channel, count=100, reverse=False,
start=None, end=None, include_token=False, callback=None, error=None):
"""This method fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited
history for all messages published to PubNub. Stored messages are replicated
across multiple availability zones in several geographical data center
locations. Stored messages can be encrypted with AES-256 message encryption
ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order,
for example you can:
Return messages in the order newest to oldest (default behavior).
Return messages in the order oldest to newest by setting reverse to true.
Page through results by providing a start or end time token.
Retrieve a "slice" of the time line by providing both a start and end time token.
Limit the number of messages to a specific quantity using the count parameter.
Args:
channel: (string)
Specifies channel to return history messages from
count: (int) (default: 100)
Specifies the number of historical messages to return
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
error: (optional)
An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Returns a list in sync mode i.e. when callback argument is not given
Sample Response:
[["Pub1","Pub2","Pub3","Pub4","Pub5"],13406746729185766,13406746845892666]
"""
params = dict()
params['count'] = count
params['reverse'] = reverse
params['start'] = start
params['end'] = end
params['auth_key'] = self.auth_key
params['pnsdk'] = self.pnsdk
params['include_token'] = 'true' if include_token else 'false'
## Get History
return self._request({'urlcomponents': [
'v2',
'history',
'sub-key',
self.subscribe_key,
'channel',
channel,
], 'urlparams': params},
callback=self._return_wrapped_callback(callback),
error=self._return_wrapped_callback(error))
def time(self, callback=None):
"""This function will return a 17 digit precision Unix epoch.
Args:
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Returns a 17 digit number in sync mode i.e. when callback argument is not given
Sample:
13769501243685161
"""
time = self._request({'urlcomponents': [
'time',
'0'
]}, callback)
if time is not None:
return time[0]
def _encode(self, request):
return [
"".join([' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and
hex(ord(ch)).replace('0x', '%').upper() or
ch for ch in list(bit)
]) for bit in request]
def getUrl(self, request):
if self.u is True and "urlparams" in request:
request['urlparams']['u'] = str(random.randint(1, 100000000000))
## Build URL
url = self.origin + '/' + "/".join([
"".join([' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and
hex(ord(ch)).replace('0x', '%').upper() or
ch for ch in list(bit)
]) for bit in request["urlcomponents"]])
if ("urlparams" in request):
url = url + '?' + "&".join([x + "=" + str(y) for x, y in request[
"urlparams"].items() if y is not None and len(str(y)) > 0])
return url
def _channel_registry(self, url=None, params=None, callback=None, error=None):
if (params is None):
params = dict()
urlcomponents = ['v1', 'channel-registration', 'sub-key', self.subscribe_key ]
if (url is not None):
urlcomponents += url
params['auth'] = self.auth_key
params['pnsdk'] = self.pnsdk
## Get History
return self._request({'urlcomponents': urlcomponents, 'urlparams': params},
callback=self._return_wrapped_callback(callback),
error=self._return_wrapped_callback(error))
def _channel_group(self, channel_group=None, channels=None, cloak=None,mode='add', callback=None, error=None):
params = dict()
url = []
namespace = None
if (channel_group is not None and len(channel_group) > 0):
ns_ch_a = channel_group.split(':')
if len(ns_ch_a) > 1:
namespace = None if ns_ch_a[0] == '*' else ns_ch_a[0]
channel_group = ns_ch_a[1]
else:
channel_group = ns_ch_a[0]
if (namespace is not None):
url.append('namespace')
url.append(self._encode(namespace))
url.append('channel-group')
if channel_group is not None and channel_group != '*':
url.append(channel_group)
if (channels is not None):
if (type(channels) is list):
channels = ','.join(channels)
params[mode] = channels
#params['cloak'] = 'true' if CLOAK is True else 'false'
else:
if mode == 'remove':
url.append('remove')
return self._channel_registry(url=url, params=params, callback=callback, error=error)
def channel_group_list_namespaces(self, callback=None, error=None):
"""Get list of namespaces.
You can obtain list of namespaces for the subscribe key associated with PubNub
object using this method.
Args:
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
Returns:
Sync Mode: dict
channel_group_list_namespaces method returns a dict which contains list of namespaces
in payload field
{
u'status': 200,
u'payload': {
u'sub_key': u'demo',
u'namespaces': [u'dev', u'foo']
},
u'service': u'channel-registry',
u'error': False
}
Async Mode: None (callback gets the response as parameter)
Response Format:
The callback passed to channel_group_list_namespaces gets the a dict containing list of namespaces
under payload field
{
u'payload': {
u'sub_key': u'demo',
u'namespaces': [u'dev', u'foo']
}
}
namespaces is the list of namespaces for the given subscribe key
"""
url = ['namespace']
return self._channel_registry(url=url, callback=callback, error=error)
def channel_group_remove_namespace(self, namespace, callback=None, error=None):
"""Remove a namespace.
A namespace can be deleted using this method.
Args:
namespace: (string) namespace to be deleted
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Sync Mode: dict
channel_group_remove_namespace method returns a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
Async Mode: None ( callback gets the response as parameter )
Response Format:
The callback passed to channel_group_list_namespaces gets the a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
"""
url = ['namespace', self._encode(namespace), 'remove']
return self._channel_registry(url=url, callback=callback, error=error)
def channel_group_list_groups(self, namespace=None, callback=None, error=None):
"""Get list of groups.
Using this method, list of groups for the subscribe key associated with PubNub
object, can be obtained. If namespace is provided, groups within the namespace
only are listed
Args:
namespace: (string) (optional) namespace
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Sync Mode: dict
channel_group_list_groups method returns a dict which contains list of groups
in payload field
{
u'status': 200,
u'payload': {"namespace": "dev", "groups": ["abcd"]},
u'service': u'channel-registry',
u'error': False
}
Async Mode: None ( callback gets the response as parameter )
Response Format:
The callback passed to channel_group_list_namespaces gets the a dict containing list of groups
under payload field
{
u'payload': {"namespace": "dev", "groups": ["abcd"]}
}
"""
if (namespace is not None and len(namespace) > 0):
channel_group = namespace + ':*'
else:
channel_group = '*:*'
return self._channel_group(channel_group=channel_group, callback=callback, error=error)
def channel_group_list_channels(self, channel_group, callback=None, error=None):
"""Get list of channels for a group.
Using this method, list of channels for a group, can be obtained.
Args:
channel_group: (string) (optional)
Channel Group name. It can also contain namespace.
If namespace is also specified, then the parameter
will be in format namespace:channel_group
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
Returns:
Sync Mode: dict
channel_group_list_channels method returns a dict which contains list of channels
in payload field
{
u'status': 200,
u'payload': {"channels": ["hi"], "group": "abcd"},
u'service': u'channel-registry',
u'error': False
}
Async Mode: None ( callback gets the response as parameter )
Response Format:
The callback passed to channel_group_list_channels gets the a dict containing list of channels
under payload field
{
u'payload': {"channels": ["hi"], "group": "abcd"}
}
"""
return self._channel_group(channel_group=channel_group, callback=callback, error=error)
def channel_group_add_channel(self, channel_group, channel, callback=None, error=None):
"""Add a channel to group.
A channel can be added to group using this method.
Args:
channel_group: (string)
Channel Group name. It can also contain namespace.
If namespace is also specified, then the parameter
will be in format namespace:channel_group
channel: (string)
Can be a channel name, a list of channel names,
or a comma separated list of channel names
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
Returns:
Sync Mode: dict
channel_group_add_channel method returns a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
Async Mode: None ( callback gets the response as parameter )
Response Format:
The callback passed to channel_group_add_channel gets the a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
"""
return self._channel_group(channel_group=channel_group, channels=channel, mode='add', callback=callback, error=error)
def channel_group_remove_channel(self, channel_group, channel, callback=None, error=None):
"""Remove channel.
A channel can be removed from a group method.
Args:
channel_group: (string)
Channel Group name. It can also contain namespace.
If namespace is also specified, then the parameter
will be in format namespace:channel_group
channel: (string)
Can be a channel name, a list of channel names,
or a comma separated list of channel names
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado .
Returns:
Sync Mode: dict
channel_group_remove_channel method returns a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
Async Mode: None ( callback gets the response as parameter )
Response Format:
The callback passed to channel_group_remove_channel gets the a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
"""
return self._channel_group(channel_group=channel_group, channels=channel, mode='remove', callback=callback, error=error)
def channel_group_remove_group(self, channel_group, callback=None, error=None):
"""Remove channel group.
A channel group can be removed using this method.
Args:
channel_group: (string)
Channel Group name. It can also contain namespace.
If namespace is also specified, then the parameter
will be in format namespace:channel_group
callback: (optional)
A callback method should be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
error: (optional)
Optional variable. An error method can be passed to the method.
If set, the api works in async mode.
Required argument when working with twisted or tornado.
Returns:
Sync Mode: dict
channel_group_remove_group method returns a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
Async Mode: None ( callback gets the response as parameter )
Response Format:
The callback passed to channel_group_remove_group gets the a dict indicating status of the request
{
u'status': 200,
u'message': 'OK',
u'service': u'channel-registry',
u'error': False
}
"""
return self._channel_group(channel_group=channel_group, mode='remove', callback=callback, error=error)
class EmptyLock():
def __enter__(self):
pass
def __exit__(self, a, b, c):
pass
empty_lock = EmptyLock()
class PubnubCoreAsync(PubnubBase):
def start(self):
pass
def stop(self):
pass
def __init__(
self,
publish_key,
subscribe_key,
secret_key=None,
cipher_key=None,
auth_key=None,
ssl_on=False,
origin='pubsub.pubnub.com',
uuid=None,
_tt_lock=empty_lock,
_channel_list_lock=empty_lock,
_channel_group_list_lock=empty_lock
):
super(PubnubCoreAsync, self).__init__(
publish_key=publish_key,
subscribe_key=subscribe_key,
secret_key=secret_key,
cipher_key=cipher_key,
auth_key=auth_key,
ssl_on=ssl_on,
origin=origin,
uuid=uuid
)
self.subscriptions = {}
self.subscription_groups = {}
self.timetoken = 0
self.last_timetoken = 0
self.accept_encoding = 'gzip'
self.SUB_RECEIVER = None
self._connect = None
self._tt_lock = _tt_lock
self._channel_list_lock = _channel_list_lock
self._channel_group_list_lock = _channel_group_list_lock
self._connect = lambda: None
self.u = None
def get_channel_list(self, channels):
channel = ''
first = True
with self._channel_list_lock:
for ch in channels:
if not channels[ch]['subscribed']:
continue
if not first:
channel += ','
else:
first = False
channel += ch
return channel
def get_channel_group_list(self, channel_groups):
channel_group = ''
first = True
with self._channel_group_list_lock:
for ch in channel_groups:
if not channel_groups[ch]['subscribed']:
continue
if not first:
channel_group += ','
else:
first = False
channel_group += ch
return channel_group
def get_channel_array(self):
"""Get List of currently subscribed channels
Returns:
Returns a list containing names of channels subscribed
Sample return value:
["a","b","c]
"""
channels = self.subscriptions
channel = []
with self._channel_list_lock:
for ch in channels:
if not channels[ch]['subscribed']:
continue
channel.append(ch)
return channel
def get_channel_group_array(self):
"""Get List of currently subscribed channel groups
Returns:
Returns a list containing names of channel groups subscribed
Sample return value:
["a","b","c]
"""
channel_groups = self.subscription_groups
channel_group = []
with self._channel_group_list_lock:
for ch in channel_groups:
if not channel_groups[ch]['subscribed']:
continue
channel_group.append(ch)
return channel_group
def each(l, func):
if func is None:
return
for i in l:
func(i)
def subscribe(self, channels, callback, state=None, error=None,
connect=None, disconnect=None, reconnect=None, sync=False):
"""Subscribe to data on a channel.
This function causes the client to create an open TCP socket to the
PubNub Real-Time Network and begin listening for messages on a specified channel.
To subscribe to a channel the client must send the appropriate subscribe_key at
initialization.
Only works in async mode
Args:
channel: (string/list)
Specifies the channel to subscribe to. It is possible to specify
multiple channels as a comma separated list or andarray.
callback: (function)
This callback is called on receiving a message from the channel.
state: (dict)
State to be set.
error: (function) (optional)
This callback is called on an error event
connect: (function) (optional)
This callback is called on a successful connection to the PubNub cloud
disconnect: (function) (optional)
This callback is called on client disconnect from the PubNub cloud
reconnect: (function) (optional)
This callback is called on successfully re-connecting to the PubNub cloud
Returns:
None
"""
return self._subscribe(channels=channels, callback=callback, state=state, error=error,
connect=connect, disconnect=disconnect, reconnect=reconnect, sync=sync)
def subscribe_group(self, channel_groups, callback, error=None,
connect=None, disconnect=None, reconnect=None, sync=False):
"""Subscribe to data on a channel group.
This function causes the client to create an open TCP socket to the
PubNub Real-Time Network and begin listening for messages on a specified channel.
To subscribe to a channel group the client must send the appropriate subscribe_key at
initialization.
Only works in async mode
Args:
channel_groups: (string/list)
Specifies the channel groups to subscribe to. It is possible to specify
multiple channel groups as a comma separated list or andarray.
callback: (function)
This callback is called on receiving a message from the channel.
error: (function) (optional)
This callback is called on an error event
connect: (function) (optional)
This callback is called on a successful connection to the PubNub cloud
disconnect: (function) (optional)
This callback is called on client disconnect from the PubNub cloud
reconnect: (function) (optional)
This callback is called on successfully re-connecting to the PubNub cloud
Returns:
None
"""
return self._subscribe(channel_groups=channel_groups, callback=callback, error=error,
connect=connect, disconnect=disconnect, reconnect=reconnect, sync=sync)
def _subscribe(self, channels=None, channel_groups=None, state=None, callback=None, error=None,
connect=None, disconnect=None, reconnect=None, sync=False):
with self._tt_lock:
self.last_timetoken = self.timetoken if self.timetoken != 0 \
else self.last_timetoken
self.timetoken = 0
if sync is True and self.subscribe_sync is not None:
self.subscribe_sync(args)
return
def _invoke(func, msg=None, channel=None, real_channel=None):
if func is not None:
if msg is not None and channel is not None and real_channel is not None:
try:
func(get_data_for_user(msg), channel, real_channel)
except:
func(get_data_for_user(msg), channel)
elif msg is not None and channel is not None:
func(get_data_for_user(msg), channel)
elif msg is not None:
func(get_data_for_user(msg))
else:
func()
def _invoke_connect():
if self._channel_list_lock:
with self._channel_list_lock:
for ch in self.subscriptions:
chobj = self.subscriptions[ch]
if chobj['connected'] is False:
chobj['connected'] = True
chobj['disconnected'] = False
_invoke(chobj['connect'], chobj['name'])
else:
if chobj['disconnected'] is True:
chobj['disconnected'] = False
_invoke(chobj['reconnect'], chobj['name'])
if self._channel_group_list_lock:
with self._channel_group_list_lock:
for ch in self.subscription_groups:
chobj = self.subscription_groups[ch]
if chobj['connected'] is False:
chobj['connected'] = True
chobj['disconnected'] = False
_invoke(chobj['connect'], chobj['name'])
else:
if chobj['disconnected'] is True:
chobj['disconnected'] = False
_invoke(chobj['reconnect'], chobj['name'])
def _invoke_disconnect():
if self._channel_list_lock:
with self._channel_list_lock:
for ch in self.subscriptions:
chobj = self.subscriptions[ch]
if chobj['connected'] is True:
if chobj['disconnected'] is False:
chobj['disconnected'] = True
_invoke(chobj['disconnect'], chobj['name'])
if self._channel_group_list_lock:
with self._channel_group_list_lock:
for ch in self.subscription_groups:
chobj = self.subscription_groups[ch]
if chobj['connected'] is True:
if chobj['disconnected'] is False:
chobj['disconnected'] = True
_invoke(chobj['disconnect'], chobj['name'])
def _invoke_error(channel_list=None, error=None):
if channel_list is None:
for ch in self.subscriptions:
chobj = self.subscriptions[ch]
_invoke(chobj['error'], error)
else:
for ch in channel_list:
chobj = self.subscriptions[ch]
_invoke(chobj['error'], error)
def _get_channel():
for ch in self.subscriptions:
chobj = self.subscriptions[ch]
if chobj['subscribed'] is True:
return chobj
if channels is not None:
channels = channels if isinstance(
channels, list) else channels.split(",")
for channel in channels:
## New Channel?
if len(channel) > 0 and \
(not channel in self.subscriptions or
self.subscriptions[channel]['subscribed'] is False):
with self._channel_list_lock:
self.subscriptions[channel] = {
'name': channel,
'first': False,
'connected': False,
'disconnected': True,
'subscribed': True,
'callback': callback,
'connect': connect,
'disconnect': disconnect,
'reconnect': reconnect,
'error': error
}
if state is not None:
if channel in self.STATE:
self.STATE[channel] = state[channel]
else:
self.STATE[channel] = state
if channel_groups is not None:
channel_groups = channel_groups if isinstance(
channel_groups, list) else channel_groups.split(",")
for channel_group in channel_groups:
## New Channel?
if len(channel_group) > 0 and \
(not channel_group in self.subscription_groups or
self.subscription_groups[channel_group]['subscribed'] is False):
with self._channel_group_list_lock:
self.subscription_groups[channel_group] = {
'name': channel_group,
'first': False,
'connected': False,
'disconnected': True,
'subscribed': True,
'callback': callback,
'connect': connect,
'disconnect': disconnect,
'reconnect': reconnect,
'error': error
}
'''
## return if already connected to channel
if channel in self.subscriptions and \
'connected' in self.subscriptions[channel] and \
self.subscriptions[channel]['connected'] is True:
_invoke(error, "Already Connected")
return
'''
## SUBSCRIPTION RECURSION
def _connect():
self._reset_offline()
def error_callback(response):
## ERROR ?
if not response or \
('message' in response and
response['message'] == 'Forbidden'):
_invoke_error(channel_list=response['payload'][
'channels'], error=response['message'])
self.timeout(1, _connect)
return
if 'message' in response:
_invoke_error(error=response['message'])
else:
_invoke_disconnect()
self.timetoken = 0
self.timeout(1, _connect)
def sub_callback(response):
## ERROR ?
if not response or \
('message' in response and
response['message'] == 'Forbidden'):
_invoke_error(channel_list=response['payload'][
'channels'], error=response['message'])
_connect()
return
_invoke_connect()
with self._tt_lock:
self.timetoken = \
self.last_timetoken if self.timetoken == 0 and \
self.last_timetoken != 0 else response[1]
if len(response) > 3:
channel_list = response[2].split(',')
channel_list_2 = response[3].split(',')
response_list = response[0]
for ch in enumerate(channel_list):
if ch[1] in self.subscription_groups or ch[1] in self.subscriptions:
try:
chobj = self.subscription_groups[ch[1]]
except KeyError as k:
chobj = self.subscriptions[ch[1]]
_invoke(chobj['callback'],
self.decrypt(response_list[ch[0]]),
chobj['name'].split('-pnpres')[0], channel_list_2[ch[0]].split('-pnpres')[0])
elif len(response) > 2:
channel_list = response[2].split(',')
response_list = response[0]
for ch in enumerate(channel_list):
if ch[1] in self.subscriptions:
chobj = self.subscriptions[ch[1]]
_invoke(chobj['callback'],
self.decrypt(response_list[ch[0]]),
chobj['name'].split('-pnpres')[0])
else:
response_list = response[0]
chobj = _get_channel()
for r in response_list:
if chobj:
_invoke(chobj['callback'], self.decrypt(r),
chobj['name'].split('-pnpres')[0])
_connect()
channel_list = self.get_channel_list(self.subscriptions)
channel_group_list = self.get_channel_group_list(self.subscription_groups)
if len(channel_list) <= 0 and len(channel_group_list) <= 0:
return
if len(channel_list) <= 0:
channel_list = ','
data = {"uuid": self.uuid, "auth": self.auth_key,
'pnsdk' : self.pnsdk, 'channel-group' : channel_group_list}
st = json.dumps(self.STATE)
if len(st) > 2:
data['state'] = quote(st,safe="")
## CONNECT TO PUBNUB SUBSCRIBE SERVERS
#try:
self.SUB_RECEIVER = self._request({"urlcomponents": [
'subscribe',
self.subscribe_key,
channel_list,
'0',
str(self.timetoken)
], "urlparams": data},
sub_callback,
error_callback,
single=True, timeout=320)
'''
except Exception as e:
print(e)
self.timeout(1, _connect)
return
'''
self._connect = _connect
## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES)
_connect()
def _reset_offline(self):
if self.SUB_RECEIVER is not None:
self.SUB_RECEIVER()
self.SUB_RECEIVER = None
def CONNECT(self):
self._reset_offline()
self._connect()
def unsubscribe(self, channel):
"""Unsubscribe from channel .
Only works in async mode
Args:
channel: Channel name ( string )
"""
if channel in self.subscriptions is False:
return False
## DISCONNECT
with self._channel_list_lock:
if channel in self.subscriptions:
self.subscriptions[channel]['connected'] = 0
self.subscriptions[channel]['subscribed'] = False
self.subscriptions[channel]['timetoken'] = 0
self.subscriptions[channel]['first'] = False
self.leave_channel(channel=channel)
# remove channel from STATE
STATE.pop(channel, None)
self.CONNECT()
def unsubscribe_group(self, channel_group):
"""Unsubscribe from channel group.
Only works in async mode
Args:
channel_group: Channel group name ( string )
"""
if channel_group in self.subscription_groups is False:
return False
## DISCONNECT
with self._channel_group_list_lock:
if channel_group in self.subscription_groups:
self.subscription_groups[channel_group]['connected'] = 0
self.subscription_groups[channel_group]['subscribed'] = False
self.subscription_groups[channel_group]['timetoken'] = 0
self.subscription_groups[channel_group]['first'] = False
self.leave_group(channel_group=channel_group)
self.CONNECT()
class PubnubCore(PubnubCoreAsync):
def __init__(
self,
publish_key,
subscribe_key,
secret_key=None,
cipher_key=None,
auth_key=None,
ssl_on=False,
origin='pubsub.pubnub.com',
uuid=None,
_tt_lock=None,
_channel_list_lock=None,
_channel_group_list_lock=None
):
super(PubnubCore, self).__init__(
publish_key=publish_key,
subscribe_key=subscribe_key,
secret_key=secret_key,
cipher_key=cipher_key,
auth_key=auth_key,
ssl_on=ssl_on,
origin=origin,
uuid=uuid,
_tt_lock=_tt_lock,
_channel_list_lock=_channel_list_lock,
_channel_group_list_lock=_channel_group_list_lock
)
self.subscriptions = {}
self.timetoken = 0
self.accept_encoding = 'gzip'
def subscribe_sync(self, channel, callback, timetoken=0):
"""
#**
#* Subscribe
#*
#* This is BLOCKING.
#* Listen for a message on a channel.
#*
#* @param array args with channel and callback.
#* @return false on fail, array on success.
#**
## Subscribe Example
def receive(message) :
print(message)
return True
pubnub.subscribe({
'channel' : 'hello_world',
'callback' : receive
})
"""
subscribe_key = self.subscribe_key
## Begin Subscribe
while True:
try:
## Wait for Message
response = self._request({"urlcomponents": [
'subscribe',
subscribe_key,
channel,
'0',
str(timetoken)
], "urlparams": {"uuid": self.uuid, 'pnsdk' : self.pnsdk}})
messages = response[0]
timetoken = response[1]
## If it was a timeout
if not len(messages):
continue
## Run user Callback and Reconnect if user permits.
for message in messages:
if not callback(self.decrypt(message)):
return
except Exception:
time.sleep(1)
return True
class HTTPClient:
def __init__(self, pubnub, url, urllib_func=None,
callback=None, error=None, id=None, timeout=5):
self.url = url
self.id = id
self.callback = callback
self.error = error
self.stop = False
self._urllib_func = urllib_func
self.timeout = timeout
self.pubnub = pubnub
def cancel(self):
self.stop = True
self.callback = None
self.error = None
def run(self):
def _invoke(func, data):
if func is not None:
func(get_data_for_user(data))
if self._urllib_func is None:
return
resp = self._urllib_func(self.url, timeout=self.timeout)
data = resp[0]
code = resp[1]
if self.stop is True:
return
if self.callback is None:
with self.pubnub.latest_sub_callback_lock:
if self.pubnub.latest_sub_callback['id'] != self.id:
return
else:
if self.pubnub.latest_sub_callback['callback'] is not None:
self.pubnub.latest_sub_callback['id'] = 0
try:
data = json.loads(data)
except ValueError as e:
_invoke(self.pubnub.latest_sub_callback['error'],
{'error': 'json decoding error'})
return
if code != 200:
_invoke(self.pubnub.latest_sub_callback['error'], data)
else:
_invoke(self.pubnub.latest_sub_callback['callback'], data)
else:
try:
data = json.loads(data)
except ValueError:
_invoke(self.error, {'error': 'json decoding error'})
return
if code != 200:
_invoke(self.error, data)
else:
_invoke(self.callback, data)
def _urllib_request_2(url, timeout=5):
try:
resp = urllib2.urlopen(url, timeout=timeout)
except urllib2.HTTPError as http_error:
resp = http_error
except urllib2.URLError as error:
msg = {"message": str(error.reason)}
return (json.dumps(msg), 0)
return (resp.read(), resp.code)
class PubnubHTTPAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
kwargs.setdefault('socket_options', default_socket_options)
super(PubnubHTTPAdapter, self).init_poolmanager(*args, **kwargs)
s = requests.Session()
#s.mount('http://', PubnubHTTPAdapter(max_retries=1))
#s.mount('https://', PubnubHTTPAdapter(max_retries=1))
#s.mount('http://pubsub.pubnub.com', HTTPAdapter(max_retries=1))
#s.mount('https://pubsub.pubnub.com', HTTPAdapter(max_retries=1))
def _requests_request(url, timeout=5):
try:
resp = s.get(url, timeout=timeout)
except requests.exceptions.HTTPError as http_error:
resp = http_error
except requests.exceptions.ConnectionError as error:
msg = str(error)
return (json.dumps(msg), 0)
except requests.exceptions.Timeout as error:
msg = str(error)
return (json.dumps(msg), 0)
return (resp.text, resp.status_code)
def _urllib_request_3(url, timeout=5):
try:
resp = urllib.request.urlopen(url, timeout=timeout)
except (urllib.request.HTTPError, urllib.request.URLError) as http_error:
resp = http_error
r = resp.read().decode("utf-8")
return (r, resp.code)
_urllib_request = None
# Pubnub
class Pubnub(PubnubCore):
def __init__(
self,
publish_key,
subscribe_key,
secret_key=None,
cipher_key=None,
auth_key=None,
ssl_on=False,
origin='pubsub.pubnub.com',
uuid=None,
pooling=True,
daemon=False,
pres_uuid=None,
azure=False
):
super(Pubnub, self).__init__(
publish_key=publish_key,
subscribe_key=subscribe_key,
secret_key=secret_key,
cipher_key=cipher_key,
auth_key=auth_key,
ssl_on=ssl_on,
origin=origin,
uuid=uuid or pres_uuid,
_tt_lock=threading.RLock(),
_channel_list_lock=threading.RLock(),
_channel_group_list_lock=threading.RLock()
)
global _urllib_request
if self.python_version == 2:
_urllib_request = _urllib_request_2
else:
_urllib_request = _urllib_request_3
if pooling is True:
_urllib_request = _requests_request
self.latest_sub_callback_lock = threading.RLock()
self.latest_sub_callback = {'id': None, 'callback': None}
self.pnsdk = 'PubNub-Python' + '/' + self.version
self.daemon = daemon
if azure is False:
s.mount('http://pubsub.pubnub.com', HTTPAdapter(max_retries=1))
s.mount('https://pubsub.pubnub.com', HTTPAdapter(max_retries=1))
else:
s.mount('http://', PubnubHTTPAdapter(max_retries=1))
s.mount('https://', PubnubHTTPAdapter(max_retries=1))
def timeout(self, interval, func):
def cb():
time.sleep(interval)
func()
thread = threading.Thread(target=cb)
thread.daemon = self.daemon
thread.start()
def _request_async(self, request, callback=None, error=None, single=False, timeout=5):
global _urllib_request
## Build URL
url = self.getUrl(request)
if single is True:
id = time.time()
client = HTTPClient(self, url=url, urllib_func=_urllib_request,
callback=None, error=None, id=id, timeout=timeout)
with self.latest_sub_callback_lock:
self.latest_sub_callback['id'] = id
self.latest_sub_callback['callback'] = callback
self.latest_sub_callback['error'] = error
else:
client = HTTPClient(self, url=url, urllib_func=_urllib_request,
callback=callback, error=error, timeout=timeout)
thread = threading.Thread(target=client.run)
thread.daemon = self.daemon
thread.start()
def abort():
client.cancel()
return abort
def _request_sync(self, request, timeout=5):
global _urllib_request
## Build URL
url = self.getUrl(request)
## Send Request Expecting JSONP Response
response = _urllib_request(url, timeout=timeout)
try:
resp_json = json.loads(response[0])
except ValueError:
return [0, "JSON Error"]
if response[1] != 200 and 'message' in resp_json and 'payload' in resp_json:
return {'message': resp_json['message'],
'payload': resp_json['payload']}
if response[1] == 0:
return [0, resp_json]
return resp_json
def _request(self, request, callback=None, error=None, single=False, timeout=5):
if callback is None:
return get_data_for_user(self._request_sync(request, timeout=timeout))
else:
self._request_async(request, callback, error, single=single, timeout=timeout)
# Pubnub Twisted
class PubnubTwisted(PubnubCoreAsync):
def start(self):
reactor.run()
def stop(self):
reactor.stop()
def timeout(self, delay, callback):
reactor.callLater(delay, callback)
def __init__(
self,
publish_key,
subscribe_key,
secret_key=None,
cipher_key=None,
auth_key=None,
ssl_on=False,
origin='pubsub.pubnub.com'
):
super(PubnubTwisted, self).__init__(
publish_key=publish_key,
subscribe_key=subscribe_key,
secret_key=secret_key,
cipher_key=cipher_key,
auth_key=auth_key,
ssl_on=ssl_on,
origin=origin,
)
self.headers = {}
self.headers['User-Agent'] = ['Python-Twisted']
self.headers['V'] = [self.version]
self.pnsdk = 'PubNub-Python-' + 'Twisted' + '/' + self.version
def _request(self, request, callback=None, error=None, single=False, timeout=5):
global pnconn_pool
def _invoke(func, data):
if func is not None:
func(get_data_for_user(data))
## Build URL
url = self.getUrl(request)
agent = ContentDecoderAgent(RedirectAgent(Agent(
reactor,
contextFactory=WebClientContextFactory(),
pool=self.ssl and None or pnconn_pool
)), [('gzip', GzipDecoder)])
try:
request = agent.request(
'GET', url, Headers(self.headers), None)
except TypeError as te:
request = agent.request(
'GET', url.encode(), Headers(self.headers), None)
if single is True:
id = time.time()
self.id = id
def received(response):
if not isinstance(response, twisted.web._newclient.Response):
_invoke(error, {"message": "Not Found"})
return
finished = Deferred()
if response.code in [401, 403]:
response.deliverBody(PubNubPamResponse(finished))
else:
response.deliverBody(PubNubResponse(finished))
return finished
def complete(data):
if single is True:
if id != self.id:
return None
try:
data = json.loads(data)
except ValueError as e:
try:
data = json.loads(data.decode("utf-8"))
except ValueError as e:
_invoke(error, {'error': 'json decode error'})
if 'error' in data and 'status' in data and 'status' != 200:
_invoke(error, data)
else:
_invoke(callback, data)
def abort():
pass
request.addCallback(received)
request.addCallback(complete)
return abort
# PubnubTornado
class PubnubTornado(PubnubCoreAsync):
def stop(self):
ioloop.stop()
def start(self):
ioloop.start()
def timeout(self, delay, callback):
ioloop.add_timeout(time.time() + float(delay), callback)
def __init__(
self,
publish_key,
subscribe_key,
secret_key=False,
cipher_key=False,
auth_key=False,
ssl_on=False,
origin='pubsub.pubnub.com'
):
super(PubnubTornado, self).__init__(
publish_key=publish_key,
subscribe_key=subscribe_key,
secret_key=secret_key,
cipher_key=cipher_key,
auth_key=auth_key,
ssl_on=ssl_on,
origin=origin,
)
self.headers = {}
self.headers['User-Agent'] = 'Python-Tornado'
self.headers['Accept-Encoding'] = self.accept_encoding
self.headers['V'] = self.version
self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000)
self.id = None
self.pnsdk = 'PubNub-Python-' + 'Tornado' + '/' + self.version
def _request(self, request, callback=None, error=None,
single=False, timeout=5, connect_timeout=5):
def _invoke(func, data):
if func is not None:
func(get_data_for_user(data))
url = self.getUrl(request)
request = tornado.httpclient.HTTPRequest(
url, 'GET',
self.headers,
connect_timeout=connect_timeout,
request_timeout=timeout)
if single is True:
id = time.time()
self.id = id
def responseCallback(response):
if single is True:
if not id == self.id:
return None
body = response._get_body()
if body is None:
return
def handle_exc(*args):
return True
if response.error is not None:
with ExceptionStackContext(handle_exc):
if response.code in [403, 401]:
response.rethrow()
else:
_invoke(error, {"message": response.reason})
return
try:
data = json.loads(body)
except TypeError as e:
try:
data = json.loads(body.decode("utf-8"))
except ValueError as ve:
_invoke(error, {'error': 'json decode error'})
if 'error' in data and 'status' in data and 'status' != 200:
_invoke(error, data)
else:
_invoke(callback, data)
self.http.fetch(
request=request,
callback=responseCallback
)
def abort():
pass
return abort
|