def get(self): """This method is called with a GET. Without parameter return a list of ongoin call of the User-Agent. With the token_call parameter set, this method return the specific call information. """ duration = 0 token_call = self.get_argument("token_call",None) call_info = Call() if token_call is not None: try: infos = call_info.getCallInfo(token_call,self._grant_token) if infos['stop'] is not None: stop = datetime.datetime.fromtimestamp(int(infos['stop'])).strftime('%d/%m/%Y %H:%M:%S') else: stop = "Call Ongoing" if infos['duration'] is None: #we need to calculate the duration netween the satrt to now duration = call_info.getDuration(infos['start']) else: duration = infos['duration'] user_info = dict( info= dict(duration=str(datetime.timedelta(seconds=duration)), number=infos['number'], token=infos['token'], start=datetime.datetime.fromtimestamp(int(infos['start'])).strftime('%d/%m/%Y %H:%M:%S'), end=stop), user = dict(username=infos['username']) ) self.set_status(200) self.write_result(user_info,"call") except ObjectDoesNotExist, e: raise tornado.web.HTTPError(409,"the token send is not correct")
def post(self): """Method POST to add a new call on ongoing status.""" try: call_app = Call() call_app.check_allowed_calls(self._grant_token,MAXIMUM_ONGOING_CALL) except RestMaxCallError, e: raise tornado.web.HTTPError(409,"maximum ongoin calls reached")
def put(self): """PUT method to udpate the status of the call, in this case is stop the call and actualize the end time and the duration""" token_call = self.get_argument("token_call") call_stop = Call() returned_call = call_stop.get(token=token_call) if returned_call['duration'] is None: call_stop.update(token_call) self.set_status(200) self.set_header("Location",DOMAIN_REST+"/call?token_call="+token_call) self.write("")
def action(): if request.form.get('open'): open_door() call = Call(open=True, user_id=current_user.get_id()) elif request.form.get('reject'): reject_knock() call = Call(open=False, user_id=current_user.get_id()) db.session.add(call) db.session.commit() return redirect(url_for('index'))
def test_model_creation(self): u1 = User() l1 = Lead() c1 = Call() d1 = Donation() p1 = Pass() cb1 = Callback() self.assertTrue(True)
def test_get_bill_24h13min_call(client, db): Call.create( id=1, source='99988526423', destination='9933468278', start_timestamp=datetime(2018, 2, 28, 21, 57, 13), end_timestamp=datetime(2018, 3, 1, 22, 10, 56), ) resp = client.get('/api/v1/calls/99988526423/2018/3') data = resp.json assert len(data['calls']) == 1 assert data['calls'][0] == { 'call_start_date': '2018-02-28', 'call_start_time': '21:57:13', 'destination': '9933468278', 'duration': '24h13min43s', 'price': 86.94 }
async def get_calls(request_model: RequestGetCalls) -> List[Call]: query = Call.all().prefetch_related('tags').order_by('-created_at') if request_model.offset: query = query.offset(request_model.offset) if request_model.limit: query = query.limit(request_model.limit) if not request_model.need_recall and request_model.state: query = query.filter(state=request_model.state) started_from = _get_dt(request_model.started_from) started_to = _get_dt(request_model.started_to) if started_from and started_to and started_from > started_to: started_to, started_from = started_from, started_to if started_from: query = query.filter(created_at__gte=started_from) if started_to: started_to = started_to.replace(hour=23, minute=59, second=59) query = query.filter(created_at__lte=started_to) if request_model.call_type: query = query.filter(call_type=request_model.call_type) number = request_model.number or '' num_len = len(number) if num_len > 4: number = number[1:] query = query.filter( Q(from_number__endswith=number, request_number__endswith=number, join_type='OR')) elif number: query = query.filter( Q(from_pin=number, request_pin=number, join_type='OR')) logger.info(f'request model: {request_model}', request_model=request_model.dict()) calls = await query logger.info(f'{query.sql()}', started_from=started_from, started_to=started_to) if request_model.need_recall: return CallsQueries.need_recalls(calls) return calls
def db_update(from_date, to_date, size=50): esi = ESIScraper(password='******') logger.info("scraper created...") esi._set_date_filters(fromdate=from_date, todate=to_date) count = esi.get_total_record_count() logger.info( 'loading %s call(s) to the database', count) esi.set_page_size(count=size) data = esi.read_call_history_data() esi.quit() if len(data) > 0: for item in data: call = Call( from_name=item.caller_id, caller_phone=item.caller_num, dialed_phone=item.dialed_num, answer_phone=item.answer_num, timestamp=item.timestamp, duration=item.duration.seconds ) call.save()
async def callback(self): async for call in Call.filter( state=CallState.END, record=None, integration_state=IntegrationState.END ): record = await find_call_record(call) if record: record.call = call await record.save() else: call.integration_state = IntegrationState.NOT_FOUNDED await call.save()
def test_create_call_2(client, db): now = datetime.now() data = { 'id': 1, 'call_id': 1, 'timestamp': f'{now.year}-{now.month}-{now.day}T22:45:15Z', 'type': 'end', } resp = client.post('/api/v1/calls', data=json.dumps(data), content_type='application/json') assert resp.status_code == 200 call = Call.get_by_id(1) assert call assert call.end_timestamp == datetime(now.year, now.month, now.day, 22, 45, 15) assert call.price is None assert call.start_timestamp is None data = { 'id': 2, 'call_id': 1, 'destination': '123456789', 'source': '12345678901', 'timestamp': f'{now.year}-{now.month}-{now.day}T21:45:25Z', 'type': 'start', } resp = client.post('/api/v1/calls', data=json.dumps(data), content_type='application/json') assert resp.status_code == 200 call = Call.get_by_id(1) assert call assert call.start_timestamp == datetime(now.year, now.month, now.day, 21, 45, 25) assert call.end_timestamp == datetime(now.year, now.month, now.day, 22, 45, 15) assert call.price is not None
def check_files_in_dir(): list_files = os.listdir(os.path.abspath('files')) if list_files: rate_gsm_for_minute = Rate.query.filter_by( type_connect='GSM').first().price_per_minute rate_cdma_for_minute = Rate.query.filter_by( type_connect='CDMA').first().price_per_minute rate_lte_for_minute = Rate.query.filter_by( type_connect='LTE').first().price_per_minute for file in list_files: if file[-4:] == 'json': with open(os.path.abspath('files') + '/' + file) as file_handler: line_list = file_handler.read().splitlines() number_in, number_target, timestamp_start_call, timestamp_end_call, type_connect = line_list dt_object_timestamp_start_call = datetime.fromtimestamp( float(timestamp_start_call)) dt_object_timestamp_end_call = datetime.fromtimestamp( float(timestamp_end_call)) count_minutes = ( dt_object_timestamp_end_call - dt_object_timestamp_start_call).seconds / 60 if type_connect == 'GSM': result_cost_call = int(count_minutes * rate_gsm_for_minute) elif type_connect == 'CDMA': result_cost_call = int(count_minutes * rate_cdma_for_minute) elif type_connect == 'LTE': result_cost_call = int(count_minutes * rate_lte_for_minute) else: result_cost_call = 0 add_call = Call(number_in=number_in, number_target=number_target, timestamp_start_call=timestamp_start_call, timestamp_end_call=timestamp_end_call, cost_call=result_cost_call) db.session.add(add_call) db.session.commit() os.remove(os.path.abspath('files') + '/' + file)
async def callback(self): query = Call.all().order_by('-created_at').annotate( records_count=Count('records') ).prefetch_related('records').filter( state=CallState.END, record_path=None, records_count__gte=1 ).limit(50) async for call in query: record = self._choice_record(call.records) record.converted = await convert_record(record.full_path, call.id) record.duration = await get_mp3_file_duration(record.converted) if record.converted: await record.save() call.record_path = record.converted await call.save()
def deploy(): """Run deployment tasks.""" if 'sqlite://' in app.config['SQLALCHEMY_DATABASE_URI']: path = Path(app.config['SQLALCHEMY_DATABASE_URI'][10:]) if path.is_file(): path.unlink() db.create_all() # insert sample data # this is part of olist's original requirements from app.models import Call source = '99988526423' destination = '9933468278' data = ( (70, datetime(2016, 2, 29, 12, 0, 0), datetime(2016, 2, 29, 14, 0, 0)), (71, datetime(2017, 12, 11, 15, 7, 13), datetime(2017, 12, 11, 15, 14, 56)), (72, datetime(2017, 12, 12, 22, 47, 56), datetime(2017, 12, 12, 22, 50, 56)), (73, datetime(2017, 12, 12, 21, 57, 13), datetime(2017, 12, 12, 22, 10, 56)), (74, datetime(2017, 12, 12, 4, 57, 13), datetime(2017, 12, 12, 6, 10, 56)), (75, datetime(2017, 12, 13, 21, 57, 13), datetime(2017, 12, 14, 22, 10, 56)), (76, datetime(2017, 12, 12, 15, 7, 58), datetime(2017, 12, 12, 15, 12, 56)), (77, datetime(2018, 2, 28, 21, 57, 13), datetime(2018, 3, 1, 22, 10, 56)), ) # bulk insert # ref: https://docs.sqlalchemy.org/en/latest/_modules/examples/performance/bulk_inserts.html db.session.add_all( Call(id=v[0], source=source, destination=destination, start_timestamp=v[1], end_timestamp=v[2]) for v in data) db.session.flush() db.session.commit()
def update_calls(session, issue_list): # Get a list of the intervention group's node ids nids = [int(i) for (i,) in session.query(RParticipant.nid).filter_by(ptype=1)] # We are only concerned with completed calls that belong to our sample group for r_call in session.query(RCall).filter(RCall.pnid.in_(nids)).filter(RCall.completed != None): # Find the Participant object for this call pid = session.query(RParticipant).filter_by(nid=r_call.pnid).first().pid participant = Participant.objects.get(pid=pid) # Check if this Call object is already in our database try: call = Call.objects.get(participant=participant, number=r_call.number) except Call.DoesNotExist: call = Call(participant=participant, number=r_call.number) # Update fields call.completed_date = datetime.datetime.strptime(r_call.completed, '%Y-%m-%dT%H:%M:%S').date() if r_call.goal_met: call.goal_met = True try: call.veg_servings = massage_number('veg_servings', r_call.veg_servings) except ValueError as ve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Vegetable Servings', 'reason': 'Value: %s' % r_call.veg_servings }) call.veg_servings = 0 except RequiredValueError as rve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Vegetable Servings', 'reason': rve.msg }) call.veg_servings = 0 try: call.fruit_servings = massage_number('fruit_servings', r_call.fruit_servings) except ValueError as ve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Fruit Servings', 'reason': 'Value: %s' % r_call.fruit_servings }) call.fruit_servings = 0 except RequiredValueError as rve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Fruit Servings', 'reason': rve.msg }) call.fruit_servings = 0 try: call.fiber_grams = massage_number('fiber_grams', r_call.fiber_grams) except ValueError as ve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Fiber Grams', 'reason': 'Value: %s' % r_call.fiber_grams }) call.fiber_grams = 0 except RequiredValueError as rve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Fiber Grams', 'reason': rve.msg }) call.fiber_grams = 0 try: call.fat_grams = massage_number('fat_grams', r_call.fat_grams) except ValueError as ve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Fat Grams', 'reason': 'Value: %s' % r_call.fat_grams }) call.fat_grams = 0 except RequiredValueError as rve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Fat Grams', 'reason': rve.msg }) call.fat_grams = 0 try: call.steps = massage_number('steps', r_call.steps) except ValueError as ve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Steps', 'reason': 'Value: %s' % r_call.steps }) call.steps = 0 except RequiredValueError as rve: issue_list.append({ 'participant': participant.pid, 'call_num': int(r_call.number), 'field': 'Call: Steps', 'reason': rve.msg }) call.steps = 0 call.save()
self.write_result({},"call") def post(self): """Method POST to add a new call on ongoing status.""" try: call_app = Call() call_app.check_allowed_calls(self._grant_token,MAXIMUM_ONGOING_CALL) except RestMaxCallError, e: raise tornado.web.HTTPError(409,"maximum ongoin calls reached") number = self.get_argument("number") grant_app = Grant() grant_id = grant_app.get(token=self._grant_token) call_start = Call() token_call = call_start.start_call(grant_id['id'],number) self.set_status(201) self.set_header("Location",DOMAIN_REST+"/call?token_call="+token_call) self.write("") def put(self): """PUT method to udpate the status of the call, in this case is stop the call and actualize the end time and the duration""" token_call = self.get_argument("token_call") call_stop = Call() returned_call = call_stop.get(token=token_call) if returned_call['duration'] is None: call_stop.update(token_call) self.set_status(200) self.set_header("Location",DOMAIN_REST+"/call?token_call="+token_call) self.write("")
def populate_calls(db): now = datetime.now() now_01 = datetime(now.year, now.month, 1) prev_month = previous_month(now) prev_prev_month = previous_month(prev_month) id = 0 # ---- Ligações do mês - 2 id += 1 date = prev_prev_month + timedelta(days=3, hours=5, minutes=50) Call.create( id=id, source='10987654321', destination='1122334455', start_timestamp=date, end_timestamp=date + timedelta(minutes=20, seconds=15), ) id += 1 date = prev_prev_month + timedelta( days=15, hours=12, minutes=30, seconds=30) Call.create( id=id, source='12345678901', destination='87654321', start_timestamp=date, end_timestamp=date + timedelta(minutes=20, seconds=15), ) id += 1 date = prev_prev_month + timedelta( days=16, hours=13, minutes=30, seconds=30) Call.create( id=id, source='23456789012', destination='3344556677', start_timestamp=date, end_timestamp=date + timedelta(minutes=20, seconds=15), ) # ---- Ligações do mês - 1 id += 1 date = prev_month - timedelta(minutes=30, seconds=30) Call.create( id=id, source='12345678901', destination='2233445566', start_timestamp=date, end_timestamp=date + timedelta(minutes=45, seconds=15), ) id += 1 date = prev_month + timedelta(days=15, hours=5, minutes=50) Call.create( id=id, source='12345678901', destination='2233445566', start_timestamp=date, end_timestamp=date + timedelta(minutes=20, seconds=15), ) id += 1 date = prev_month + timedelta(days=1, hours=12, minutes=30, seconds=30) Call.create( id=id, source='12345678901', destination='7890123456', start_timestamp=date, end_timestamp=date + timedelta(minutes=30, seconds=15), ) id += 1 date = prev_month + timedelta(days=16, hours=13, minutes=30, seconds=30) Call.create( id=id, source='23456789012', destination='3344556677', start_timestamp=date, end_timestamp=date + timedelta(minutes=20, seconds=15), ) # ---- Ligações do mês id += 1 date = now_01 - timedelta(minutes=30, seconds=30) Call.create( id=id, source='12345678901', destination='4455667788', start_timestamp=date, end_timestamp=date + timedelta(minutes=40, seconds=25), ) id += 1 date = now_01 + timedelta(hours=5, minutes=50) Call.create( id=id, source='33445566778', destination='7890123456', start_timestamp=date, end_timestamp=date + timedelta(minutes=25, seconds=15), ) id += 1 date = now_01 + timedelta(days=15, hours=12, minutes=30, seconds=30) Call.create( id=id, source='12345678901', destination='7890123456', start_timestamp=date, end_timestamp=date + timedelta(minutes=31, seconds=15), ) id += 1 date = now_01 + timedelta(days=16, hours=13, minutes=30, seconds=30) Call.create( id=id, source='23456789012', destination='3344556677', start_timestamp=date, end_timestamp=date + timedelta(minutes=22, seconds=29), )