summaryrefslogtreecommitdiff
path: root/omegle.py
blob: 42f9f77d97307290a90cd523ab3b55f1e60a491e (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
import sys
import httplib
import urllib
import time
import json
import logging
from threading import Thread, Lock

class Timer(Thread):
	def __init__(self,func,interval=0.50):
		Thread.__init__(self)
		self.func = func
		self.interval = interval

		self.running = False

	def run(self):
		self.running = True
		while self.running:
			self.func()
			time.sleep(self.interval)

	def stop(self):
		self.running = False


class OmegleChat(object):
	headers = {
		"Host" : "omegle.com",
		"Content-type": "application/x-www-form-urlencoded; charset=utf-8",
		"Accept": "application/json"
	}

	def __init__(self,poll_interval=0.5):
		self.conn = httplib.HTTPConnection('www.omegle.com')
#		self.conn.set_debuglevel(1)

		self.conn_lock = Lock()

		self.timer = Timer(self.events, poll_interval)

		self.logger = logging.getLogger(__name__ + self.__class__.__name__)

	def start(self):
		self.conn_lock.acquire()
		self.conn.request("POST", "/start", {}, OmegleChat.headers)
		self.conn_lock.release()
		r=self.conn.getresponse()
		body=r.read()
		id=body.split("\"")
		if id.__len__() == 3:
			self.id = id[1]
			self.logger.info("Connected id=%s" % self.id)
		else:
			self.logger.error("Bad response: %s" % body)
			raise Exception("Bad response: %s" % body)
		#Poll events
		self.timer.start()

	def disconnect(self):
		self.timer.stop()

		self.conn_lock.acquire()
		self.conn.request("POST",
			"/disconnect",
			urllib.urlencode({'id' : self.id}),
			OmegleChat.headers)
		r = self.conn.getresponse()
		self.conn_lock.release()
		body = r.read()
		if body != "win":
			raise Exception("/disconnect; Bad response: %s" % body)

	def events(self):
		conn = httplib.HTTPConnection('www.omegle.com')
		conn.request("POST", 
			"/events", 
			urllib.urlencode({'id' : self.id}),
			OmegleChat.headers)
		r=conn.getresponse()
		body=r.read()
		self.dispatch_event(conn,body)
		conn.close()

	def send(self,msg):
		msg = unicode(msg)
		self.conn_lock.acquire()
		self.conn.request("POST",
			"/send",
			urllib.urlencode({'id':self.id,'msg':msg}),
			OmegleChat.headers)
		r=self.conn.getresponse()
		self.conn_lock.release()
		body = r.read()
		if body != "win":
			self.logger.error("/send; Bad response %s" % body)
			raise Exception("/send; Bad response %s" % body)

	def typing(self):
		self.conn_lock.acquire()
		self.conn.request("POST",
			"/typing",
			urllib.urlencode({'id':self.id}),
			OmegleChat.headers)
		r=self.conn.getresponse()
		self.conn_lock.release()
		body = r.read()
		if body != "win":
			self.logger.error("/typing; Bad response %s" % body)
			raise Exception("/typing; Bad response %s" % body)

	def stopped_typing(self):
		self.conn_lock.acquire()
		self.conn.request("POST",
			"/stoppedtyping",
			urllib.urlencode({'id':self.id}),
			OmegleChat.headers)
		r=self.conn.getresponse()
		self.conn_lock.release()
		body = r.read()
		if body != "win":
			self.logger.error("/stoppedtyping; Bad response %s" % body)
			raise Exception("/stoppedtyping; Bad response %s" % body)



	def dispatch_event(self,conn,body):
		try:
			data_set=json.read(unicode(body))
			if not data_set:
				self.logger.debug("event: no data received")
				return
			for data in data_set:
				if data[0] == "typing":
					self.on_typing()
				elif data[0] == "gotMessage" and data.__len__() == 2:
					self.on_message(data[1])
				elif data[0] == "connected":
					self.on_connect()
				elif data[0] == "strangerDisconnected":
					self.timer.stop()
					self.on_disconnect()
				elif data[0] == "stoppedTyping":
					self.on_stopped_typing()
				elif data[0] == "waiting":
					pass #unhandled
				else:
					self.logger.error("Unknown JSON Data: %s" % body)
		except json.ReadException:
			self.logger.error("Json ReadException. Body: %s" % body)

	def on_message(self,message):
		self.logger.info("<<< %s" % message)
	def on_connect(self):
		self.logger.info("Connection confirmed")
	def on_typing(self):
		self.logger.info("Stranger is typing")
	def on_stopped_typing(self):
		self.logger.info("Stranger stopped typing")
	def on_disconnect(self):
		self.logger.info("Stranger Disconnectet")


if __name__ == "__main__":
	logging.basicConfig(level=logging.INFO)
	print "Lets chat. Type \"quit\" to disconnect"
	chat = OmegleChat()
	chat.start()
	while 1==1:
		try:
			cmd=sys.stdin.readline().strip()
		except KeyboardInterrupt:
			chat.disconnect()
			break
		if cmd=="quit":
			chat.disconnect()
			break
		else:
			print ">>> %s" % cmd
			chat.send(cmd)