def init(self, args): Intercom.init(self,args) self.buffer_size=args.buffer_size self.packet_list=[] #initialize buffer and fill with silence for x in range(self.buffer_size): self.packet_list.append(numpy.zeros( (self.samples_per_chunk, self.bytes_per_sample), self.dtype)) self.silence=numpy.zeros( (self.samples_per_chunk, self.bytes_per_sample), self.dtype) self.packet_send=0 #Benchmark Variables self.cpu_load=0 self.cpu_max=0 self.cycle=0 #caculation cycle for average value #first index -1 for delaying start of playing self.packet_received=-1 #calc size of message example: s. per chunk = 1024 & channel=2 (1024*2) self.msgsize=(self.samples_per_chunk*self.number_of_channels) if __debug__: print("buffer_size={}".format(self.buffer_size))
def it_handles_no_error_type(self): payload = { 'errors': [ { 'code': 'unique_user_constraint', 'message': 'User already exists.' } ], 'request_id': '00000000-0000-0000-0000-000000000000', 'type': 'error.list' } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.MultipleMatchingUsersError): Intercom.get('/users') payload = { 'errors': [ { 'code': 'parameter_not_found', 'message': 'missing data parameter' } ], 'request_id': None, 'type': 'error.list' } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.BadRequestError): Intercom.get('/users')
def test_get_users_params(self): resp = Intercom.get_users() ok_('params' in resp) ok_('page' not in resp['params']) ok_('per_page' not in resp['params']) ok_('tag_id' not in resp['params']) ok_('tag_id' not in resp['params']) resp = Intercom.get_users(page=20) ok_('params' in resp) ok_('page' in resp['params']) eq_(resp['params']['page'], 20) resp = Intercom.get_users(per_page=10) ok_('params' in resp) ok_('per_page' in resp['params']) eq_(resp['params']['per_page'], 10) resp = Intercom.get_users(tag_id=100) ok_('params' in resp) ok_('tag_id' in resp['params']) eq_(resp['params']['tag_id'], 100) resp = Intercom.get_users(tag_name="starter") ok_('params' in resp) ok_('tag_name' in resp['params']) eq_(resp['params']['tag_name'], "starter")
def init(self, args): Intercom.init(self, args) self.chunks_to_buffer = args.chunks_to_buffer self.cells_in_buffer = self.chunks_to_buffer * 2 self._buffer = [self.generate_zero_chunk()] * self.cells_in_buffer self.packet_format = f"H{self.samples_per_chunk}h" if __debug__: print(f"chunks_to_buffer={self.chunks_to_buffer}")
def find(cls, **params): from intercom import Intercom collection = utils.resource_class_to_collection_name(cls) if 'id' in params: response = Intercom.get("/%s/%s" % (collection, params['id'])) else: response = Intercom.get("/%s" % (collection), **params) if response is None: raise HttpError('Http Error - No response entity returned') return cls(**response)
def deleteuserpayment(request): if request.is_ajax(): if request.method == 'POST': txtmessage = '' try: json_data = json.loads(request.body) if json_data['txtmessage']: txtmessage = json_data['txtmessage'] userpayment_id = json_data['userpayment_id'] registro = UserPayment.objects.get( user_payment_id=userpayment_id) registro.message = txtmessage registro.enabled = False registro.status = 'CA' registro.channel = 'X' registro.save() # Envio envento a intercom ep = Setting.get_var('intercom_endpoint') token = Setting.get_var('intercom_token') try: intercom = Intercom(ep, token) reply = intercom.submitEvent( registro.user.user_id, registro.user.email, "cancelled-sub", { "event_description": "recurrencia cancelada por el administrador" }) if not reply: registro.message = "Intercom error: cannot post the event" registro.save() except Exception as e: registro.message = "Intercom error: %s" % str(e) registro.save() return JsonResponse({'message': 'activado correctamente'}, status=200) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({ 'message': 'Metodo no permitido', 'data': '' }, status=500)
def save(self): from intercom import Intercom collection = utils.resource_class_to_collection_name(self.__class__) params = self.attributes if self.id_present and not self.posted_updates: # update response = Intercom.put('/%s/%s' % (collection, self.id), **params) else: # create params.update(self.identity_hash) response = Intercom.post('/%s' % (collection), **params) if response: return self.from_response(response)
def setUp(self): self.intercom = Intercom(file_path=file_path) self.intercom.customers = { '1': { "latitude": "53.339428", "name": "Christina McArdle", "longitude": "-6.257664" }, '2': { "latitude": "54.339428", "name": "Christina McArdle", "longitude": "-6.257664" } }
def expireuser(request): if request.is_ajax(): if request.method == 'GET': fecha = datetime.today() if request.method == 'POST': try: json_data = json.loads(request.body) user_id = json_data['user_id'] user = User.objects.get(user_id=user_id) fecha = datetime.today() d = timedelta(days=1) fecha -= d user.expiration = fecha user.save() # Envio envento a intercom ep = Setting.get_var('intercom_endpoint') token = Setting.get_var('intercom_token') try: intercom = Intercom(ep, token) metadata = { "event_description": "usuario expirado por el administrador", "expire_at": str(int(mktime(user.expiration.timetuple()))) } reply = intercom.submitEvent(user.user_id, user.email, "user_expired", metadata) except Exception as e: pass return JsonResponse( { 'message': 'Guardado correctamente', 'data': fecha }, status=200) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({ 'message': 'Metodo no permitido', 'data': '' }, status=500)
def init(self, args): Intercom.init(self, args) self.buffer_size = args.buffer_size self.packet_list = [] for x in range(self.buffer_size): self.packet_list.append([]) self.packet_send = 0 self.cpu_load = 0 self.cpu_max = 0 self.cycle = 0 self.packet_received = -1 #first index -1 for delaying play if __debug__: print("buffer_size={}".format(self.buffer_size))
def it_raises_a_multiple_matching_users_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'conflict', 'message': 'Two many cooks.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.MultipleMatchingUsersError): Intercom.get('/users')
def it_raises_a_service_unavailable_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'service_unavailable', 'message': 'Zzzzz.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ServiceUnavailableError): Intercom.get('/users')
def it_raises_rate_limit_exceeded(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'rate_limit_exceeded', 'message': 'Fair use please.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.RateLimitExceeded): Intercom.get('/users')
def it_raises_resource_not_found_by_type(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'not_found', 'message': 'Waaaaally?' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ResourceNotFound): Intercom.get('/users')
def create(cls, **params): from intercom import Intercom collection = utils.resource_class_to_collection_name(cls) response = Intercom.post("/%s/" % (collection), **params) if response: # may be empty if we received a 202 return cls(**response)
def reply(self, **reply_data): from intercom import Intercom collection = utils.resource_class_to_collection_name(self.__class__) url = "/%s/%s/reply" % (collection, self.id) reply_data['conversation_id'] = self.id response = Intercom.post(url, **reply_data) return self.from_response(response)
def add_args(self): parser = Intercom.add_args(self) parser.add_argument("-cb", "--chunks_to_buffer", help="Number of chunks to buffer", type=int, default=32) return parser
def it_raises_a_multiple_matching_users_error_when_receiving_a_conflict(self): # noqa payload = { 'type': 'error.list', 'errors': [ { 'code': 'conflict', 'message': 'Multiple existing users match this email address - must be more specific using user_id' # noqa } ] } # create bytes content content = json.dumps(payload).encode('utf-8') # create mock response resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(MultipleMatchingUsersError): Intercom.get('/users')
def it_raises_an_authentication_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'unauthorized', 'message': 'Your name\'s not down.' } ] } for code in ['unauthorized', 'forbidden']: payload['errors'][0]['type'] = code content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.AuthenticationError): Intercom.get('/users')
def it_raises_an_unexpected_untyped_error(self): payload = { 'type': 'error.list', 'errors': [ { 'message': 'UNIVAC' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp try: Intercom.get('/users') self.fail('UnexpectedError not raised.') except (UnexpectedError) as err: ok_("An unexpected error occured." in err.message) eq_(err.context['application_error_code'], None)
def parse_args(self): parser = Intercom.add_args(self) parser.add_argument("-bs", "--buffer_size", help="tamaño de buffer", type=int, default=4) parser.set_defaults(samples_per_chunk=1024) args = parser.parse_args() return args
def activateuser(request): if request.is_ajax(): if request.method == 'POST': try: json_data = json.loads(request.body) user_id = json_data['user_id'] days = json_data['days'] user = User.objects.get(user_id=user_id) # Sumar la cantidad de dias a hoy date = user.enable_for(days) # Envio evento a intercom ep = Setting.get_var('intercom_endpoint') token = Setting.get_var('intercom_token') try: intercom = Intercom(ep, token) metadata = { 'event_description': 'usuario activado por el administrador', 'expire_at': str(int(mktime(date.timetuple()))) } reply = intercom.submitEvent(user.user_id, user.email, 'user_activated', metadata) except Exception as e: pass return JsonResponse({'message': 'activado correctamente'}, status=200) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({ 'message': 'Metodo no permitido', 'data': '' }, status=500)
def it_raises_a_bad_request_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': None, 'message': 'email is required' } ] } for code in ['missing_parameter', 'parameter_invalid', 'bad_request']: payload['errors'][0]['type'] = code content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.BadRequestError): Intercom.get('/users')
def it_raises_a_multiple_matching_users_error_when_receiving_a_conflict( self): # noqa payload = { 'type': 'error.list', 'errors': [{ 'code': 'conflict', 'message': 'Multiple existing users match this email address - must be more specific using user_id' # noqa }] } # create bytes content content = json.dumps(payload).encode('utf-8') # create mock response resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(MultipleMatchingUsersError): Intercom.get('/users')
def test_update_user_valid(self): companies = [{ 'id':1, 'name':'Intercom', 'created_at': 1331764344}] resp = Intercom.update_user( email='*****@*****.**', custom_data={'age': '42'}, companies=companies) self.assertEqual(None, resp['user_id']) self.assertEqual('*****@*****.**', resp['email']) self.assertEqual('42', resp['custom_data']['age'])
def it_raises_an_unexpected_typed_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'hopper', 'message': 'The first compiler.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp try: Intercom.get('/users') self.fail('UnexpectedError not raised.') except (UnexpectedError) as err: ok_("The error of type 'hopper' is not recognized" in err.message) # noqa eq_(err.context['http_code'], 200) eq_(err.context['application_error_code'], 'hopper')
def init(self, args): Intercom.init(self,args) self.buffer_size=args.buffer_size self.packet_list=[] for x in range(self.buffer_size): self.packet_list.append([]) self.packet_send=0 #Benchmark Variables self.cpu_load=0 self.cpu_max=0 self.cycle=0 #caculation cycle for average value #first index -1 for delaying play self.packet_received=-1 #calc size of message example: s. per chunk = 1024 & channel=2 & Index = (1024*2)+1 self.msgsize=(self.samples_per_chunk*self.number_of_channels)+1 if __debug__: print("buffer_size={}".format(self.buffer_size))
class IntercomTest(unittest.TestCase): def setUp(self): self.intercom = Intercom(file_path=file_path) self.intercom.customers = { '1': { "latitude": "53.339428", "name": "Christina McArdle", "longitude": "-6.257664" }, '2': { "latitude": "54.339428", "name": "Christina McArdle", "longitude": "-6.257664" } } def test_0_km(self): customer = json.loads( '{"latitude": "53.339428", "user_id": 1, "name": "Christina McArdle", "longitude": "-6.257664"}' ) distance = self.intercom.calculate_distance(customer) self.assertEqual(distance, 0) def test_1_degree_south(self): customer = json.loads( '{"latitude": "52.339428", "user_id": 1, "name": "Christina McArdle", "longitude": "-6.257664"}' ) distance = self.intercom.calculate_distance(customer) self.assertEqual(distance, 111.19492664454764) def test_close_enough(self): self.intercom.is_it_close_enough() customers = self.intercom.customers.copy() customers['1']['close_enough'] = True customers['2']['close_enough'] = False self.assertDictEqual(self.intercom.customers, customers)
def load(self): from intercom import Intercom cls = self.__class__ collection = utils.resource_class_to_collection_name(cls) if hasattr(self, 'id'): response = Intercom.get("/%s/%s" % (collection, self.id)) else: raise Exception( "Cannot load %s as it does not have a valid id." % (cls)) if response is None: raise HttpError('Http Error - No response entity returned') return cls(**response)
def parse_args(self): parser = Intercom.add_args(self) #add buffer size argument for command line parser.add_argument("-bs", "--buffer_size", help="tamaño de buffer", type=int, default=4) #overwrite default chunk-size by 512 if no argument is given (system specific) parser.set_defaults(samples_per_chunk=512) args = parser.parse_args() return args
def load(self): from intercom import Intercom cls = self.__class__ collection = utils.resource_class_to_collection_name(cls) if hasattr(self, 'id'): response = Intercom.get("/%s/%s" % (collection, self.id)) else: raise Exception("Cannot load %s as it does not have a valid id." % (cls)) if response is None: raise HttpError('Http Error - No response entity returned') return cls(**response)
def _tag_collection(cls, collection_name, name, objects, untag=False): from intercom import Intercom collection = utils.resource_class_to_collection_name(cls) object_ids = [] for obj in objects: if not hasattr(obj, 'keys'): obj = {'id': obj} if untag: obj['untag'] = True object_ids.append(obj) params = { 'name': name, collection_name: object_ids, } response = Intercom.post("/%s" % (collection), **params) return cls(**response)
def _tag_collection( cls, collection_name, name, objects, untag=False): from intercom import Intercom collection = utils.resource_class_to_collection_name(cls) object_ids = [] for obj in objects: if not hasattr(obj, 'keys'): obj = {'id': obj} if untag: obj['untag'] = True object_ids.append(obj) params = { 'name': name, collection_name: object_ids, } response = Intercom.post("/%s" % (collection), **params) return cls(**response)
def get_page(self, url, params={}): # get a page of results from intercom import Intercom # if there is no url stop iterating if url is None: raise StopIteration response = Intercom.get(url, **params) if response is None: raise HttpError('Http Error - No response entity returned') collection = response[self.collection] # if there are no resources in the response stop iterating if collection is None: raise StopIteration # create the resource iterator self.resources = iter(collection) # grab the next page URL if one exists self.next_page = self.extract_next_link(response)
def test_update_user_valid(self): resp = Intercom.update_user(email="*****@*****.**", custom_data={"age": "42"}) self.assertEqual(None, resp["user_id"]) self.assertEqual("*****@*****.**", resp["email"]) self.assertEqual("42", resp["custom_data"]["age"])
def test_api_error(self): resp = Intercom.get_users()
def test_api_error_when_json_is_invalid(self): Intercom.get_users()
def test_get_users_valid(self): resp = Intercom.get_users() self.assertEqual(3, len(resp['users'])) self.assertEqual(3, resp['total_count']) self.assertEqual(1, resp['total_pages'])
def test_not_found(self): resp = Intercom.get_users()
def test_update_user_valid(self): resp = Intercom.update_user( email='*****@*****.**', custom_data={'age': '42'} ) self.assertEqual(None, resp['user_id']) self.assertEqual('*****@*****.**', resp['email']) self.assertEqual('42', resp['custom_data']['age'])
def test_get_users_identifiers(self): Intercom.create_user()
def test_get_user_identifiers(self): Intercom.get_user()
def test_get_user_valid(self): resp = Intercom.get_user(email='*****@*****.**') self.assertEqual(None, resp['user_id']) self.assertEqual('*****@*****.**', resp['email'])
def test_delete_valid(self): resp = Intercom.delete_user(email='*****@*****.**') self.assertEqual('*****@*****.**', resp['email'])
def delete(self): from intercom import Intercom collection = utils.resource_class_to_collection_name(self.__class__) Intercom.delete("/%s/%s/" % (collection, self.id)) return self
help="select sound device", type=str) tornado.options.define("sipid", default="sip:localhost", help="", type=str) tornado.options.parse_command_line() if tornado.options.options.config: if os.path.exists(tornado.options.options.config): tornado.options.parse_config_file(tornado.options.options.config) options = tornado.options.options if options.gpio_mode.lower() == "bcm": GPIO.setmode(GPIO.BCM) elif options.gpio_mode.lower() == "board": GPIO.setmode(GPIO.BOARD) intercom = Intercom( led_red_channel=options.led_red_channel, led_green_channel=options.led_green_channel, doors_channel=options.doors_channel, btn_call_channel=options.btn_call_channel, snd_dev_capture=options.snd_dev_capture, snd_dev_playback=options.snd_dev_playback ) intercom.selected_sipid = options.sipid app = NigmafonWebApp(intercom, options.allowed_users) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
def init(self, args): Intercom.init(self, args) #Inicializo el contador. self.index = 0 #Inicializo la cola de prioridad, tamaño bastante grande pero he respetado el que estaba en la clase padre. self.priorityQ = PriorityQueue(maxsize=100000)
def __callback_paymentez_proc(data, country): # Verifico el stoken if not __validate_stoken(data, country): body = {"status": "error", "message": "not authorized"} return HttpResponse(json.dumps(body), content_type="application/json", status=200) # Obtengo los valores segun la respuesta de Paymentez pr = paymentez_translator(data) # Obtengo el PaymentHistory con el dev_reference informado try: ph = PaymentHistory.objects.get( payment_id=data["transaction"]["dev_reference"]) except ObjectDoesNotExist: body = {"status": "error", "message": "invalid dev_refence"} return HttpResponse(json.dumps(body), content_type="application/json", status=200) # Verifico que este en Waiting Callback if ph.status == 'W' or (ph.status == 'A' and pr["ph_status"] == 'C'): # Seteo los valores de la UserPayment ph.user_payment.status = pr["up_status"] ph.user_payment.message = pr["up_message"] ph.user_payment.enabled = pr["up_recurrence"] if ph.user_payment.status == 'AC': # calcular next_payment_day ph.user_payment.payment_date = ph.user_payment.calc_payment_date() # Fija la fecha de expiration del usuario ph.user_payment.user.set_expiration(ph.user_payment.payment_date) if ph.user_payment.disc_counter > 0: ph.user_payment.disc_counter = ph.user_payment.disc_counter - 1 else: ph.user_payment.channel = 'C' ph.user_payment.save() # Seteo los valores del PaymentHistory ph.status = pr["ph_status"] ph.gateway_id = pr["ph_gatewayid"] ph.message = pr["ph_message"] ph.save() if pr["user_expire"]: ph.user_payment.user.expire() if pr["intercom"]["action"]: ep = Setting.get_var('intercom_endpoint') token = Setting.get_var('intercom_token') try: intercom = Intercom(ep, token) reply = intercom.submitEvent( ph.user_payment.user.user_id, ph.user_payment.user.email, pr["intercom"]["event"], paymentez_intercom_metadata(data['transaction'])) if not reply: ph.message = "%s - Intercom error: cannot post the event" % ( ph.message) ph.save() except Exception as e: ph.message = "%s - Intercom error: %s" % (ph.message, str(e)) ph.save() else: body = { "status": "error", "message": "ignoring callback: PH status %s" % ph.status } return HttpResponse(json.dumps(body), content_type="application/json", status=200) body = {'status': 'success', 'message': ''} return HttpResponse(json.dumps(body), content_type="application/json", status=200)