aboutsummaryrefslogtreecommitdiffstats
path: root/python/examples/dev-console.py
blob: adade8fe70cf93791d6289c979651db364484985 (plain)
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
## www.pubnub.com - PubNub Real-time push service in the cloud. 
# coding=utf8

## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/

## -----------------------------------
## PubNub 3.1 Real-time Push Cloud API
## -----------------------------------

import sys
sys.path.append('../')
sys.path.append('../../')
from Pubnub import Pubnub

from optparse import OptionParser


parser = OptionParser()

parser.add_option("--publish-key",
                  dest="publish_key", default="demo",
                  help="Publish Key ( default : 'demo' )")

parser.add_option("--subscribe-key",
                  dest="subscribe_key", default="demo",
                  help="Subscribe Key ( default : 'demo' )")

parser.add_option("--secret-key",
                  dest="secret_key", default="demo",
                  help="Secret Key ( default : 'demo' )")

parser.add_option("--cipher-key",
                  dest="cipher_key", default="",
                  help="Cipher Key")

parser.add_option("--auth-key",
                  dest="auth_key", default=None,
                  help="Auth Key")

parser.add_option("--origin",
                  dest="origin", default="pubsub.pubnub.com",
                  help="Origin ( default: pubsub.pubnub.com )")

parser.add_option("--ssl-on",
                  action="store_false", dest="ssl", default=False,
                  help="SSL")

parser.add_option("--uuid",
                  dest="uuid", default=None,
                  help="UUID")

(options, args) = parser.parse_args()

print(options)

pubnub = Pubnub(options.publish_key, options.subscribe_key, options.secret_key, options.cipher_key, options.auth_key, options.ssl, options.origin, options.uuid)


class color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

from datetime import datetime

def print_ok(msg, channel=None):
    chstr = color.PURPLE + "[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + color.END
    chstr += color.CYAN + "[Channel : " + channel + "] " if channel is not None else "" + color.END
    try:
        print(chstr + color.GREEN +  str(msg) + color.END)
    except Exception as e:
        print(msg)

def print_error(msg, channel=None):
    chstr = color.PURPLE + "[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + color.END
    chstr += color.CYAN + "[Channel : " + channel + "] " if channel is not None else "" + color.END
    try:
        print( chstr + color.RED + color.BOLD +str(msg) + color.END)
    except:
        print(msg)

import threading

def kill_all_threads():
    for thread in threading.enumerate():
        if thread.isAlive():
            try:
                thread._Thread__stop()
            except Exception as e:
                pass
                #print(e)
                #thread.exit()
                #print(str(thread.getName()) + ' could not be terminated')

def get_input(message, t=None):
    while True:
        try:
            try:
                command = raw_input(message)
            except NameError:
                command = input(message)
            except KeyboardInterrupt:
                return None

            command = command.strip()

            if command is None or len(command) == 0:
                raise ValueError

            if t is not None and t == bool:
                if command in ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"]:
                    return True
                else:
                    return False
            if t is not None:
                command = t(command)
            else:
                command = eval("'" + command + "'")

            return command
        except ValueError:
            print_error("Invalid input : " + command)



def _publish_command_handler():

    channel = get_input("[PUBLISH] Enter Channel Name ", str)
    if channel is None:
        return
    while True:
        message = get_input("[PUBLISH] Enter Message ( QUIT or CTRL-C for exit from publish mode ) ")
        if message == 'QUIT' or message == 'quit' or message == None:
            return  
        def _callback(r):
            print_ok(r)
        def _error(r):
            print_error(r)
        pubnub.publish({
            'channel' : channel,
            'message' : message,
            'callback' : _callback,
            'error'   : _error
        })


def _subscribe_command_handler():
    channel = get_input("[SUBSCRIBE] Enter Channel Name ", str)
    def _callback(r):
        print_ok(r, channel)
    def _error(r):
        print_error(r, channel)
    pubnub.subscribe({
        'channel' : channel,
        'callback' : _callback,
        'error'   : _error
    })

def _unsubscribe_command_handler():
    channel = get_input("[UNSUBSCRIBE] Enter Channel Name ", str)
    def _callback(r):
        print_ok(r)
    def _error(r):
        print_error(r)
    pubnub.unsubscribe({
        'channel' : channel,
        'callback' : _callback,
        'error'   : _error
    })    

def _grant_command_handler():
    def _callback(r):
        print_ok(r)
    def _error(r):
        print_error(r)
    channel = get_input("[GRANT] Enter Channel Name ", str)
    auth_key = get_input("[GRANT] Enter Auth Key ", str)
    ttl = get_input("[GRANT] Enter ttl ", int)
    read = get_input("[GRANT] Read ? ", bool)
    write = get_input("[GRANT] Write ? ", bool)
    pubnub.grant(channel, auth_key,read,write,ttl, _callback)

def _revoke_command_handler():
    def _callback(r):
        print_ok(r)
    def _error(r):
        print_error(r)
    channel = get_input("[REVOKE] Enter Channel Name ", str)
    auth_key = get_input("[REVOKE] Enter Auth Key ", str)
    ttl = get_input("[REVOKE] Enter ttl ", int)

    pubnub.revoke(channel, auth_key, ttl, _callback)

def _audit_command_handler():
    def _callback(r):
        print_ok(r)
    def _error(r):
        print_error(r)
    channel = get_input("[AUDIT] Enter Channel Name ", str)
    auth_key = get_input("[AUDIT] Enter Auth Key ", str)
    pubnub.audit(channel, auth_key, _callback)

def _history_command_handler():
    def _callback(r):
        print_ok(r)
    def _error(r):
        print_error(r)
    channel = get_input("[HISTORY] Enter Channel Name ", str)
    count = get_input("[HISTORY] Enter Count ", int)

    pubnub.history({
        'channel' : channel,
        'count'   : count,
        'callback' : _callback,
        'error'   : _error
    })


def _here_now_command_handler():
    def _callback(r):
        print_ok(r)
    def _error(r):
        print_error(r)
    channel = get_input("[HERE NOW] Enter Channel Name ", str)

    pubnub.here_now({
        'channel' : channel,
        'callback' : _callback,
        'error'   : _error
    })




commands = []
commands.append({"command" : "publish", "handler" : _publish_command_handler})
commands.append({"command" : "subscribe", "handler" : _subscribe_command_handler})
commands.append({"command" : "unsubscribe", "handler" : _unsubscribe_command_handler})
commands.append({"command" : "here_now", "handler" : _here_now_command_handler})
commands.append({"command" : "history", "handler" : _history_command_handler})
commands.append({"command" : "grant", "handler" : _grant_command_handler})
commands.append({"command" : "revoke", "handler" : _revoke_command_handler})
commands.append({"command" : "audit", "handler" : _audit_command_handler})

# last command is quit. add new commands before this line
commands.append({"command" : "QUIT"})

def get_help():
    help = ""
    help += "Channels currently subscribed to : "
    help += str(pubnub.get_channel_array())
    help += "\n"
    for i,v in enumerate(commands):
        help += "Enter " + str(i) + " for " + v['command'] + "\n"
    return help

            
while True:
    command = get_input(color.BLUE + get_help(), int)
    if command == len(commands) - 1 or command is None:
        kill_all_threads()
        break
    if command >= len(commands):
        print_error("Invalid input " + str(command))
        continue

    commands[command]['handler']()

#pubnub.start()