Example #1
0
 def get(self, API_VERSION, ACCOUNT_SID, *args):
     format = response.response_format(args[0])
     if 'GET' in self.AllowedMethods:
         InstanceSid = args[0].split('.')[0]
         Instance = self.InstanceModel.filter('Sid =', InstanceSid).filter(
             'AccountSid = ', ACCOUNT_SID).get()
         if Instance is not None:
             response_data = Instance.get_dict()
             response_data['ApiVersion'] = API_VERSION
             response_data['Uri'] = self.request.path
             self.response.out.write(
                 response.format_response(
                     response.add_nodes(self, response_data, format),
                     format))
         else:
             self.response.out.write(
                 response.format_response(
                     errors.rest_error_response(
                         400, "The requested resource was not found",
                         format), format))
     else:
         self.response.out.write(
             response.format_response(
                 errors.rest_error_response(
                     405, "The requested method is not allowed", format,
                     20004, 'http://www.twilio.com/docs/errors/20004'),
                 format))
Example #2
0
	def get(self,API_VERSION,ACCOUNT_SID, *args):
		format = response.response_format( args[0] )
		if 'GET' in self.AllowedMethods:
			InstanceSid = args[0].split('.')[0]
			Instance = self.InstanceModel.filter('Sid =',InstanceSid).filter('AccountSid = ',ACCOUNT_SID).get()
			if Instance is not None:
				response_data = Instance.get_dict()
				response_data['ApiVersion'] = API_VERSION
				response_data['Uri'] = self.request.path
				self.response.out.write(response.format_response(response.add_nodes(self,response_data,format),format))
			else:
				self.response.out.write(response.format_response(errors.rest_error_response(400,"The requested resource was not found",format),format))
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))
Example #3
0
 def post(self, API_VERSION, ACCOUNT_SID, *args):
     format = response.response_format(args[0])
     if 'POST' in self.AllowedMethods:
         InstanceSid = args[0].split('.')[0]
         Instance = self.InstanceModel.filter('Sid =', InstanceSid).filter(
             'AccountSid = ', ACCOUNT_SID).get()
         if Instance is not None:
             #update stuff according to allowed rules
             #get all arguments passed in
             for argument in self.request.arguments():
                 #if we are allowed to alter that argument
                 if argument in self.AllowedProperties['Post']:
                     #validate that a valid value was passed in
                     if self.InstanceHelper.validate(
                             self, Instance, argument,
                             self.request.get(argument)):
                         #set it to a valid argument value
                         setattr(
                             Instance, argument,
                             self.InstanceHelper.sanitize(
                                 self, Instance, argument,
                                 self.request.get(argument)))
             Instance.put()
             InstanceHandler.get(self, API_VERSION, ACCOUNT_SID, *args)
     else:
         self.response.out.write(
             response.format_response(
                 errors.rest_error_response(
                     405, "The requested method is not allowed", format,
                     20004, 'http://www.twilio.com/docs/errors/20004'),
                 format))
Example #4
0
	def post(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format(self.request.path.split('/')[-1])
		if parameters.required(['From','To','Body'],self.request):
			Message = messages.Message.new(
										To = self.request.get('To'),
										From = self.request.get('From'),
										Body = self.request.get('Body'),
										AccountSid = ACCOUNT_SID,
										Direction = 'outbound-api',
										Status = 'queued'
									)
			if self.request.get('StatusCallback',None) is not None:
				Message.StatusCallback = self.request.get('StatusCallback')
			response_data = Message.get_dict()
			self.response.out.write(response.format_response(response.add_nodes(self,response_data,format),format))
			Message.put()
			#DO SOME THINGS DEPENDING ON ACCOUNT SETTINGS
			#DEFAULT WILL BE TO SEND MESSAGE, CHARGE FOR IT AND UPDATE WHEN SENT
			Message.send()
			#make sure put happens before callback happens
			if Message.StatusCallback is not None:
				taskqueue.Queue('StatusCallbacks').add(taskqueue.Task(url='/Callbacks/SMS', params = {'SmsSid':Message.Sid}))
		else:
			#This should either specify a twilio code either 21603 or 21604
			self.response.out.write(response.format_response(errors.rest_error_response(400,"Missing Parameters",format),format))
Example #5
0
	def post(self,API_VERSION,ACCOUNT_SID,*args):
		"""
		From	The phone number to use as the caller id. Format with a '+' and country code e.g., +16175551212 (E.164 format). Must be a Twilio number or a valid outgoing caller id for your account.
		To	The number to call formatted with a '+' and country code e.g., +16175551212 (E.164 format). Twilio will also accept unformatted US numbers e.g., (415) 555-1212, 415-555-1212.
		Url	The fully qualified URL that should be consulted when the call connects. Just like when you set a URL for your inbound calls.

		Method	The HTTP method Twilio should use when requesting the required Url parameter's value above. Defaults to POST.
		FallbackUrl	A URL that Twilio will request if an error occurs requesting or executing the TwiML at Url.
		FallbackMethod	The HTTP method that Twilio should use to request the FallbackUrl. Must be either GET or POST. Defaults to POST.
		StatusCallback	A URL that Twilio will request when the call ends to notify your app.
		StatusCallbackMethod	The HTTP method Twilio should use when requesting the above URL. Defaults to POST.
		SendDigits	A string of keys to dial after connecting to the number. Valid digits in the string include: any digit (0-9), '#' and '*'. For example, if you connected to a company phone number, and wanted to dial extension 1234 and then the pound key, use SendDigits=1234#. Remember to URL-encode this string, since the '#' character has special meaning in a URL.
		IfMachine	Tell Twilio to try and determine if a machine (like voicemail) or a human has answered the call. Possible values are Continue and Hangup. See the answering machines section below for more info.
		Timeout	The integer number of seconds that Twilio should allow the phone to ring before assuming there is no answer. Default is 60 seconds, the maximum is 999 seconds. Note, you could set this to a low value, such as 15, to hangup before reaching an answering machine or voicemail. Also see the answering machine section for other solutions.
		"""
		format = response.response_format(self.request.path.split('/')[-1])
		if parameters.required(['From','To','Url'],self.request):
			Phone_Number = phone_numbers.Phone_Number.all().filter('PhoneNumber = ',self.request.get('From')).filter('AccountSid =',ACCOUNT_SID).get()
			if Phone_Number is not None:
				Call = calls.Call.new(From = self.request.get('From'),To = self.request.get('To'),PhoneNumberSid = Phone_Number.Sid, AccountSid = ACCOUNT_SID,Status = 'queued',Direction = 'outgoing-api')
				Call.put()
				response_data = Call.get_dict()
				#has been queueud so lets ring
				Call.ring()
				#ringing, what should we do? connect and read twiml and parse, fail, busy signal or no answer
				#default is to connect, read twiml and do some things i guess
				Call.connect()

				if self.request.get('StatusCallback',None) is not None:
					StatusCallback = self.request.get('StatusCallback')
					StatusCallbackMethod = self.request.get('StatusCallbackMethod','POST').upper()
					if StatusCallbackMethod not in ['GET','POST']:
						StatusCallbackMethod = 'POST'
				elif Phone_Number.StatusCallback is not None:
					StatusCallback = Phone_Number.StatusCallback
					StatusCallbackMethod = Phone_Number.StatusCallbackMethod
				if self.request.get('StatusCallback',None) is not None or Phone_Number.StatusCallback is not None:
					Call.disconnect(StatusCallback,StatusCallbackMethod)
				self.response.out.write(response.format_response(response.add_nodes(self,response_data,format),format))
			else:
				self.response.out.write(response.format_response(errors.rest_error_response(404,"Resource not found",format),format))				
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(400,"Missing Parameters",format),format))
Example #6
0
	def authorized_method(self,API_VERSION,ACCOUNT_SID,*args):
		format = response.response_format(self.request.path.split('/')[-1])
		#Memcache the account to speed things up alittle
		#PREMATURE OPTIMIZATION!
		Account = memcache.get('ACCOUNT_SID')
		if Account is None:
			Account = accounts.Account.all().filter('Sid = ',ACCOUNT_SID).get()
			if Account is not None:
				memcache.set(ACCOUNT_SID,db.model_to_protobuf(Account).Encode())
		else:
			Account = db.model_from_protobuf(entity_pb.EntityProto(Account))
			#convert back from proto model

		if Account is not None:
			authstring = base64.encodestring(Account.Sid+':'+Account.AuthToken).replace('\n','')
			if 'Authorization' in self.request.headers:#hasattr(self.request.headers,'Authorization'):
				request_auth = self.request.headers['Authorization'].split(' ')
				if request_auth[0] == 'Basic' and request_auth[1]==authstring:
					self.data = {'Account' : Account}
					return method(self,API_VERSION,ACCOUNT_SID,*args)
				else:
					logging.info('Basic Authorization Failed')
					self.response.out.write(response.format_response(errors.rest_error_response(401,"Unauthorized",format),format))
			else:
				#should return a tuple of components, but documentation doesnt explain how to retrieve username & password
				parsed_url = urlparse.urlparse(self.request.url)
				netloc = parsed_url.netloc
				net_split = netloc.rsplit('@',1)
				if len(net_split) == 2:
					auth_info = net_split[0]
					auth_split = auth_info.split(':')
					if auth_split[0] == ACCOUNT_SID and auth_split[1] == Account.AuthToken:
						self.data = {'Account' : Account}
						return method(self,API_VERSION,ACCOUNT_SID,*args)
					else:
						self.response.out.write(response.format_response(errors.rest_error_response(401,"Authorization Required",format,20004),format))
				else:
					self.response.out.write(response.format_response(errors.rest_error_response(401,"Authorization Required",format,20004),format))
					
		else:
			logging.info('No account exists')
			self.response.out.write(response.format_response(errors.rest_error_response(400,"No Account Found",format),format))
Example #7
0
 def delete(self, API_VERSION, ACCOUNT_SID, *args):
     format = response.response_format(self.request.path.split('/')[-1])
     if 'DELETE' in self.AllowedMethods:
         pass
     else:
         self.response.out.write(
             response.format_response(
                 errors.rest_error_response(
                     405, "The requested method is not allowed", format,
                     20004, 'http://www.twilio.com/docs/errors/20004'),
                 format))
Example #8
0
 def put(self, API_VERSION, ACCOUNT_SID, *args):
     format = response.response_format(args[0])
     if 'PUT' in self.AllowedMethods:
         pass
     else:
         self.response.out.write(
             response.format_response(
                 errors.rest_error_response(
                     405, "The requested method is not allowed", format,
                     20004, 'http://www.twilio.com/docs/errors/20004'),
                 format))
Example #9
0
	def delete(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format( args[0] )
		if 'DELETE' in self.AllowedMethods:
			format = response.response_format( args[0] )
			InstanceSid = args[0].split('.')[0]
			Instance = self.InstanceModel.filter('Sid = ',InstanceSid).get()
			if Instance is not None:
				db.delete(Instance)
				self.response.set_status(204)
			else:
				self.error(400)
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))
Example #10
0
 def delete(self, API_VERSION, ACCOUNT_SID, *args):
     format = response.response_format(args[0])
     if 'DELETE' in self.AllowedMethods:
         format = response.response_format(args[0])
         InstanceSid = args[0].split('.')[0]
         Instance = self.InstanceModel.filter('Sid = ', InstanceSid).get()
         if Instance is not None:
             db.delete(Instance)
             self.response.set_status(204)
         else:
             self.error(400)
     else:
         self.response.out.write(
             response.format_response(
                 errors.rest_error_response(
                     405, "The requested method is not allowed", format,
                     20004, 'http://www.twilio.com/docs/errors/20004'),
                 format))
Example #11
0
	def post(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format( args[0] )
		if 'POST' in self.AllowedMethods:
			InstanceSid = args[0].split('.')[0]
			Instance = self.InstanceModel.filter('Sid =',InstanceSid).filter('AccountSid = ',ACCOUNT_SID).get()
			if Instance is not None:
				#update stuff according to allowed rules
				#get all arguments passed in
				for argument in self.request.arguments():
					#if we are allowed to alter that argument
					if argument in self.AllowedProperties['Post']:
						#validate that a valid value was passed in
						if self.InstanceHelper.validate(self,Instance, argument,self.request.get(argument)):
							#set it to a valid argument value
							setattr(Instance,argument,self.InstanceHelper.sanitize(self, Instance, argument, self.request.get(argument)))
				Instance.put()
				InstanceHandler.get(self,API_VERSION,ACCOUNT_SID,*args)
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))
Example #12
0
                "previouspageuri":
                uris.PrevUri(Page, PageSize, ListCount, self.request.path),
                "lastpageuri":
                uris.LastUri(Page, PageSize, ListCount, self.request.path),
                self.ListName: []
            }
            for instance in ListInstance:
                response_data[self.ListName].append(
                    {self.InstanceModelName: instance.get_dict()})
            self.response.out.write(
                response.format_response(response_data, format))
        else:
            self.response.out.write(
                response.format_response(
                    errors.rest_error_response(
                        405, "The requested method is not allowed", format,
                        20004, 'http://www.twilio.com/docs/errors/20004'),
                    format))

    #Unlikely this will be used ever
    @authorization.authorize_request
    def post(self, API_VERSION, ACCOUNT_SID, *args):
        format = response.response_format(self.request.path.split('/')[-1])
        if 'POST' in self.AllowedMethods:
            pass
        else:
            self.response.out.write(
                response.format_response(
                    errors.rest_error_response(
                        405, "The requested method is not allowed", format,
                        20004, 'http://www.twilio.com/docs/errors/20004'),
Example #13
0
    def authorized_method(self, API_VERSION, ACCOUNT_SID, *args):
        format = response.response_format(self.request.path.split('/')[-1])
        #Memcache the account to speed things up alittle
        #PREMATURE OPTIMIZATION!
        Account = memcache.get('ACCOUNT_SID')
        if Account is None:
            Account = accounts.Account.all().filter('Sid = ',
                                                    ACCOUNT_SID).get()
            if Account is not None:
                memcache.set(ACCOUNT_SID,
                             db.model_to_protobuf(Account).Encode())
        else:
            Account = db.model_from_protobuf(entity_pb.EntityProto(Account))
            #convert back from proto model

        if Account is not None:
            authstring = base64.encodestring(Account.Sid + ':' +
                                             Account.AuthToken).replace(
                                                 '\n', '')
            if 'Authorization' in self.request.headers:  #hasattr(self.request.headers,'Authorization'):
                request_auth = self.request.headers['Authorization'].split(' ')
                if request_auth[0] == 'Basic' and request_auth[1] == authstring:
                    self.data = {'Account': Account}
                    return method(self, API_VERSION, ACCOUNT_SID, *args)
                else:
                    logging.info('Basic Authorization Failed')
                    self.response.out.write(
                        response.format_response(
                            errors.rest_error_response(401, "Unauthorized",
                                                       format), format))
            else:
                #should return a tuple of components, but documentation doesnt explain how to retrieve username & password
                parsed_url = urlparse.urlparse(self.request.url)
                netloc = parsed_url.netloc
                net_split = netloc.rsplit('@', 1)
                if len(net_split) == 2:
                    auth_info = net_split[0]
                    auth_split = auth_info.split(':')
                    if auth_split[0] == ACCOUNT_SID and auth_split[
                            1] == Account.AuthToken:
                        self.data = {'Account': Account}
                        return method(self, API_VERSION, ACCOUNT_SID, *args)
                    else:
                        self.response.out.write(
                            response.format_response(
                                errors.rest_error_response(
                                    401, "Authorization Required", format,
                                    20004), format))
                else:
                    self.response.out.write(
                        response.format_response(
                            errors.rest_error_response(
                                401, "Authorization Required", format, 20004),
                            format))

        else:
            logging.info('No account exists')
            self.response.out.write(
                response.format_response(
                    errors.rest_error_response(400, "No Account Found",
                                               format), format))
Example #14
0
	def delete(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format(self.request.path.split('/')[-1])
		if 'DELETE' in self.AllowedMethods:
			pass
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))
Example #15
0
							"total": ListCount,
							"pagesize": PageSize,
							"numpages": int(math.ceil(float(ListCount)/PageSize)),
							"page":Page,
							"uri": uris.CurUri(self.request.path,self.request.query_string),
							"firstpageuri": uris.FirstUri(Page,PageSize,ListCount,self.request.path),
							"nextpageuri": uris.NextUri(Page,PageSize,ListCount,self.request.path),
							"previouspageuri": uris.PrevUri(Page,PageSize,ListCount,self.request.path),
							"lastpageuri": uris.LastUri(Page,PageSize,ListCount,self.request.path),
							self.ListName:[]
							}
			for instance in ListInstance:
				response_data[self.ListName].append({self.InstanceModelName : instance.get_dict()})
			self.response.out.write(response.format_response(response_data,format))
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))

	#Unlikely this will be used ever
	@authorization.authorize_request
	def post(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format(self.request.path.split('/')[-1])
		if 'POST' in self.AllowedMethods:
			pass
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))

	#Unlikely this will be used ever
	@authorization.authorize_request
	def put(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format(self.request.path.split('/')[-1])
		if 'PUT' in self.AllowedMethods:
Example #16
0
    def post(self, API_VERSION, ACCOUNT_SID, *args):
        """
		From	The phone number to use as the caller id. Format with a '+' and country code e.g., +16175551212 (E.164 format). Must be a Twilio number or a valid outgoing caller id for your account.
		To	The number to call formatted with a '+' and country code e.g., +16175551212 (E.164 format). Twilio will also accept unformatted US numbers e.g., (415) 555-1212, 415-555-1212.
		Url	The fully qualified URL that should be consulted when the call connects. Just like when you set a URL for your inbound calls.

		Method	The HTTP method Twilio should use when requesting the required Url parameter's value above. Defaults to POST.
		FallbackUrl	A URL that Twilio will request if an error occurs requesting or executing the TwiML at Url.
		FallbackMethod	The HTTP method that Twilio should use to request the FallbackUrl. Must be either GET or POST. Defaults to POST.
		StatusCallback	A URL that Twilio will request when the call ends to notify your app.
		StatusCallbackMethod	The HTTP method Twilio should use when requesting the above URL. Defaults to POST.
		SendDigits	A string of keys to dial after connecting to the number. Valid digits in the string include: any digit (0-9), '#' and '*'. For example, if you connected to a company phone number, and wanted to dial extension 1234 and then the pound key, use SendDigits=1234#. Remember to URL-encode this string, since the '#' character has special meaning in a URL.
		IfMachine	Tell Twilio to try and determine if a machine (like voicemail) or a human has answered the call. Possible values are Continue and Hangup. See the answering machines section below for more info.
		Timeout	The integer number of seconds that Twilio should allow the phone to ring before assuming there is no answer. Default is 60 seconds, the maximum is 999 seconds. Note, you could set this to a low value, such as 15, to hangup before reaching an answering machine or voicemail. Also see the answering machine section for other solutions.
		"""
        format = response.response_format(self.request.path.split('/')[-1])
        if parameters.required(['From', 'To', 'Url'], self.request):
            Phone_Number = phone_numbers.Phone_Number.all().filter(
                'PhoneNumber = ',
                self.request.get('From')).filter('AccountSid =',
                                                 ACCOUNT_SID).get()
            if Phone_Number is not None:
                Call = calls.Call.new(From=self.request.get('From'),
                                      To=self.request.get('To'),
                                      PhoneNumberSid=Phone_Number.Sid,
                                      AccountSid=ACCOUNT_SID,
                                      Status='queued',
                                      Direction='outgoing-api')
                Call.put()
                response_data = Call.get_dict()
                #has been queueud so lets ring
                Call.ring()
                #ringing, what should we do? connect and read twiml and parse, fail, busy signal or no answer
                #default is to connect, read twiml and do some things i guess
                Call.connect()

                if self.request.get('StatusCallback', None) is not None:
                    StatusCallback = self.request.get('StatusCallback')
                    StatusCallbackMethod = self.request.get(
                        'StatusCallbackMethod', 'POST').upper()
                    if StatusCallbackMethod not in ['GET', 'POST']:
                        StatusCallbackMethod = 'POST'
                elif Phone_Number.StatusCallback is not None:
                    StatusCallback = Phone_Number.StatusCallback
                    StatusCallbackMethod = Phone_Number.StatusCallbackMethod
                if self.request.get(
                        'StatusCallback', None
                ) is not None or Phone_Number.StatusCallback is not None:
                    Call.disconnect(StatusCallback, StatusCallbackMethod)
                self.response.out.write(
                    response.format_response(
                        response.add_nodes(self, response_data, format),
                        format))
            else:
                self.response.out.write(
                    response.format_response(
                        errors.rest_error_response(404, "Resource not found",
                                                   format), format))
        else:
            self.response.out.write(
                response.format_response(
                    errors.rest_error_response(400, "Missing Parameters",
                                               format), format))
Example #17
0
	def put(self, API_VERSION, ACCOUNT_SID, *args):
		format = response.response_format( args[0] )
		if 'PUT' in self.AllowedMethods:
			pass
		else:
			self.response.out.write(response.format_response(errors.rest_error_response(405,"The requested method is not allowed",format,20004,'http://www.twilio.com/docs/errors/20004'),format))