summaryrefslogtreecommitdiffstats
path: root/Handler/SIPCall3.py
blob: 3a3fe15cfafdcdfd8cff02d08fcec896d2a1f6e5 (plain) (blame)
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
import sys
import pjsua as pj
import os
import re
import time
import MySQLdb
import subprocess
from time import sleep
from datetime import datetime

LOG_LEVEL=2
current_call = None
number=""
Stop = "False"

## -- Identify Server -- ##
lifeline = re.compile(r"(\d) received")
report = ("No response","Partial Response","Alive")
StatusPing=""

#make class connect to db
try:
    	mydb = MySQLdb.connect('localhost', 'root', 'randompasswordSQL','GSMTesting');  	
	db=mydb.cursor()
	print " _ _ _ _ _ _ _ _ _ _ _"
	print "_ _ _ _ _ _ _ _ _ _ _ _"
	print "Database connection establish"

except MySQLdb.Error, e:
	print "Error %d: %s" % (e.args[0],e.args[1])
	sys.exit(1)

#make it to be class

A=1,2,3
for host in A:
   ip = "132.230.4.8"
   pingaling = os.popen("ping -q -c2 "+ip,"r")

   while 1:
      line = pingaling.readline()
      if not line: break
      igot = re.findall(lifeline,line)
      if igot:
	       
	StatusPing= report[int(igot[0])]


###--- Ping -- Thread

# Logging callback
def log_cb(level, str, len):
    print str, "testingggggggg"


# Callback to receive events from account
class MyAccountCallback(pj.AccountCallback):

    def __init__(self, account=None):
        pj.AccountCallback.__init__(self, account)

    # Notification on incoming call##


        
# Callback to receive events from Call
class MyCallCallback(pj.CallCallback):
   
    def __init__(self, call=None):
        pj.CallCallback.__init__(self, call)

    # Notification when call state has changed
    def on_state(self):
        global current_call
        global Stop
	global Succes
	if self.call.info().state_text <> "DISCONNCTD":
		if self.call.info().state_text == "CONNECTING":
			print "CONNECTING CALL"
			#print "isine opo:", self.call.info().state_text
			print "CALL CONFIRMED and ESTABLISH", self.call.info().state_text
			sleep(5)
			current_call.hangup()
			Success = "True"
		else:
			sleep(1)
	#print ""

	if self.call.info().last_reason <> "":
		
		if self.call.info().last_reason == "Busy Here":
			
			print "Destination Number is Busy or offline"
			print ""
			Success = "True"
			

		#print self.call.info().state_text
        
        if self.call.info().state == pj.CallState.DISCONNECTED:
            current_call = None
            print 'Current call Disconnected'
	    Stop="True"
	    Success = "True"

# Function to make call should become class

class make_call(URI):
def make_call(uri):
    try:
        print "Making call to", uri
	cb=MyCallCallback()
        return acc.make_call(number, cb)
    except pj.Error, e:
        print "iki opo to yo Exception: " + str(e)
        return None
        

lib = pj.Lib()
lib.init()
lib.start()

if StatusPing <> "":

	if StatusPing == "Alive":
		print ""
		print "Checking Order from DB, hell yeah"
		try:
		 while True:		
			db.execute ("SELECT IDOrder, IDTester, SIPDesti, GSMDesti, GSM2Desti, Landline, GSMO2, Status FROM SIPTestOrder")
			rows = db.fetchall()
			

			for row in rows:	
				status=row[7]
				if status == "no":
					IDOrder=row[0]
					SIPTester=row[1]
					SIPDest=row[2]
					GSMDest1=row[3]
					GSMDest2=row[4]
					Landln=row[5]
					GSMO2=row[6]
					print "yes, I have something to do. I need to call", SIPDest, GSMDest1, GSMDest2, Landln, GSMO2

					db.execute ("SELECT Username, Password, Server, Status FROM SIPAccountInformation where IDSIP=%s",(SIPTester))
					Rows = db.fetchall()
					
					for Row in Rows:	
					   Server=Row[2]
					   Username=Row[0]
					   Password=Row[1]
							
					   try:
						print "I send my purpose to the server", Server, Username, Password
						lib.set_null_snd_dev()#
						sleep(1)
						transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
						acc_cfg = pj.AccountConfig(Server, Username, Password)	
						acc = lib.create_account(acc_cfg, cb=MyAccountCallback())

						if acc.info().reg_status < 700:
						   Regis_status= "OK"
						   print "heeeyyy She Accept me"
						   



						   if SIPDest <> "":
							IDTask=IDOrder
							SIPID=SIPDest
							Status = "N"
							db.execute ("insert into SIPReady (TaskID,SIPID,Status) value ('"+str(IDTask)+"','"+str(SIPID)+"','"+str(Status)+"')")
							command="--command=python IncomingCall2.py " +SIPDest #pindahin kebawah
							subprocess.Popen(args=["gnome-terminal", command])
							db.execute ("SELECT Number FROM SIPAccountInformation where IDSIP=%s",(SIPDest))
							Num = db.fetchall()

							for no in Num:
								number="sip:"+no[0]+"@132.230.4.8"
							stop="False"
					
							while stop <> "True":
								print "Waiting SIP Destination Ready to handle Incoming Call"
								db.execute ("SELECT Status FROM SIPReady where TaskID=%s",(IDOrder))
								Num = db.fetchall()

								for no in Num:
									if no[0] == "R":
										
								 	   try:
							   			current_call = acc.make_call(number, MyCallCallback())
							   			sleep(5)
										number=""
										if Success == "True":
										   report = "Succed"
										   db.execute ("insert into StatusConnection (TaskID,Caller,Receiver,Status) value ('"+str(IDTask)+"','"+str(SIPTester)+"','"+str(SIPDest)+"','"+str(report)+"')")
										else:
										   report = "Failed"
										   db.execute ("insert into StatusConnection (TaskID,Caller,Receiver,Status) value ('"+str(IDTask)+"','"+str(SIPTester)+"','"+str(SIPDest)+"','"+str(report)+"')")
										stop = "True"
										break#stop == "True"
										
							   #

									   except pj.Error, e:
							   			print "invalid SIP nummber", e

								sleep(2)
						   if GSMDest1 <> "":

							try:
							#call GSM, if error accour about invalid number
							   state="N"
							   time=""
							   db.execute ("insert into GSMReady (doID,recU,state) value ('"+str(IDOrder)+"','"+str(GSMDest1)+"','"+str(state)+"')")#still problemo
							   stop = "False"
							   while stop <> "True":
								db.execute ("SELECT state FROM GSMReady where doID=%s",(IDOrder))
								Num = db.fetchall()

								for rOw in Num:
								   if rOw[0]=="R":
								      number=GSMDest1
								      db.execute ("SELECT Number FROM SIPAccountInformation where IDSIP=%s",(GSMDest1))
								      Num = db.fetchall()
					
								      for nO in Num:
									   number="sip:"+nO[0]+"@132.230.4.8"
									   print "GSM Number", number
									   current_call = acc.make_call(number, MyCallCallback())
									   sleep(10)
									   stop = "True"
									   break
								      sleep(3)

								      number=""


						        except ValueError:
							  print "Invalid GSM1 Number", e

						   db.execute ("Update SIPTestOrder Set Status='ok' where IDOrder=%s",(IDOrder))
						   acc.delete()
						   acc = None
						else:
						   Regis_status= "Bad" 

								   

					   except ValueError:
						print "Register Error, Unknown Reason"


				else:
					sleep(2)
					print""
					
					print "The guy says Nothing to do. I'm going to sleep for 10 Seconds. Tschuss!!!"					
					sleep(2)
					print ""
					print "   hey, you miss me? I'm Back. Ready to check the Task in 2 seconds"
					sleep(2)
								
		except pj.Error, e:   
			print "hallo Exception: " + str(e)
			lib.destroy()
			lib = None

	if StatusPing == "Partial Response":
		print "Bad Connection"
	
	if StatusPing == "No response Response":
		print "Server not respon"