Beispiel #1
0
def add_call(customer_id):
    '''Check for logged in user. Check for valid customer id.
    Get customer object that matches the given customer id.
    Get the user_id of the currently logged-in user.
    Get the current date-time.
    Get the notes from the POST request.
    Use the above data to create a new Call object. Save it.
    Redirect to the /customers/<customer_id>/ page.'''
    if check_for_logged_in() == True:
        if check_for_valid_customer_id(customer_id) == True:
            customer_id = customer_id
            c = Customer.get(customer_id)

            auth = Auth()
            current_user = auth.get_current_user()
            user_id = current_user['user_id']

            current_dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            note = request.form.get('note')
            call_id = None

            new_call = Call(current_dt, note, call_id, customer_id, user_id)
            new_call.save()
            return redirect(url_for('show_customer', customer_id=customer_id))
        else:
            return redirect(url_for('show_customers'))
    else:
        return redirect(url_for('login'))
Beispiel #2
0
    def do_call(self, call_id):

        #If the call input is correct
        if call_id != '':

            call = Call(call_id)
            print("Call " + call_id + " received")

            #Adding call to the list of calls which are happening
            self.online_calls_list.addCall(call)

            #Flag to see if call is going to queue or not
            go_queue = True

            if self.call_queue.isEmpty():

                #Look for operator available
                op = self.searchOperator("available")
                if op is not None:

                    #Allocate call to operator
                    print("Call " + call_id + " ringing for operator " + op.ID)
                    self.operators.setCall(op.ID, call)
                    go_queue = False

            #If is going to queue
            if go_queue:
                print("Call " + call_id + " waiting in queue")
                call.setStatus("waiting")
                self.call_queue.enqueue(call)
        else:
            print('Must specify a call id ( Call <call_id>)')
Beispiel #3
0
def reply(connection, username, client_address):

    """ responsible for sending replies on behalf host machine """

    client_ip, port = client_address
    try:
        while True:
            data = connection.recv(1024)

            if data and 'dummie' in data:
                connection.sendall(username)
                break

            elif data and 'call' in data:

                call_obj = Call(vid_recv_port = 5009, vid_send_port = 5010)
                call_obj.start()

                print 'live chat started with'

                # videofeed.send_video_feed(client_ip)
    finally:
        # Clean up the connection
        if connection:
            connection.close()
 def register_incoming_call(self, call: Call) -> None:
     """ Register a Call <call> into this incoming call history
     """
     time = (call.get_bill_date()[0], call.get_bill_date()[1])
     if time in self.incoming_calls:
         self.incoming_calls[time].append(call)
     else:
         self.incoming_calls[time] = [call]
Beispiel #5
0
    def get_satisfied_seconds(self, call: Call) -> int:
        second = (call.get_end() - call.get_start()).second

        if second <= self.start:
            return self.start
        elif second <= self.end:
            return second - self.start
        else:
            return second - self.end
Beispiel #6
0
    def register_incoming_call(self, call: Call) -> None:
        """ Register a Call <call> into this incoming call history
        """
        if call.get_bill_date() not in self.incoming_calls:
            self.incoming_calls[call.get_bill_date()] = []
            self.incoming_calls[call.get_bill_date()].append(call)

        else:
            self.incoming_calls[call.get_bill_date()].append(call)
Beispiel #7
0
 def register_incoming_call(self, call: Call) -> None:
     """ Register a Call <call> into this incoming call history
     """
     month = call.get_bill_date()[0]
     year = call.get_bill_date()[1]
     try:
         self.incoming_calls[(month, year)].append(call)
     except KeyError:
         self.incoming_calls[(month, year)] = [call]
Beispiel #8
0
 def make_call(self, call: Call) -> None:
     """ Add the <call> to this phone line's callhistory, and bill it
     according to the contract for this phone line.
     If there is no bill for the current monthly billing cycle, then a new
     month must be <started> by advancing to the right month from <call>.
     """
     if self.get_bill(call.get_bill_date()[0], call.get_bill_date()[1]) \
             is None:
         self.new_month(call.get_bill_date()[0], call.get_bill_date()[1])
     self.callhistory.register_outgoing_call(call)
     self.contract.bill_call(call)
Beispiel #9
0
    def receive_call(self, call: Call) -> None:
        """ Add the <call> to this phone line's callhistory.
        Incoming calls are not billed under any contract.
        However, if there is no bill for the current monthly billing cycle,
        then a new month must be <started> by advancing to the right month from
        <call>.
        """
        self.callhistory.register_incoming_call(call)

        if call.get_bill_date() not in self.bills:
            self.bills[call.get_bill_date()] = Bill()
Beispiel #10
0
 def _make_call(self):
     if self.state == AudioState.DISCONNECT:
         # Initialize Call
         self.call = Call(self.acc, self.bud.cfg.uri, self)
         # Create paramter
         call_prm = pj.CallOpParam()
         # Enable audio
         call_prm.opt.audioCount = 1
         # Enable video
         call_prm.opt.videoCount = 1
         # Make call
         self.call.makeCall(self.bud.cfg.uri, call_prm)
Beispiel #11
0
 def incoming_call(self, prm):
     call = Call(self.acc, call_id=prm.callId)
     call_prm = pj.CallOpParam()
     # Ringing State
     call_prm.statusCode = pj.PJSIP_SC_RINGING
     call.answer(call_prm)
     # Set uri
     call.uri = call.getInfo().remoteUri
     iid = call.uri.split(':')[1].split('@')[0]
     if msg.askquestion('Incoming Call',
                        'Accept call from ' + iid + ' ?',
                        default=msg.YES):
         # If not exist current buddy, then create
         if iid not in self.buddy_list:
             # Initialize buddy
             bud = Buddy(self, iid)
             # Initialize configuration of buddy
             bud_cfg = pj.BuddyConfig()
             bud_cfg.uri = 'sip:' + iid + '@' + self.domain
             # Create buddy
             bud.cfg = bud_cfg
             bud.create(self.acc, bud.cfg)
             bud.subscribePresence(True)
             # Push into buddy_list
             self.buddy_list[iid] = bud
             self.update_buddy(bud)
         # If not exist current chat dialog, then create
         if iid not in self.chat_list:
             self.chat_list[iid] = Chat(self.acc, self.buddy_list[iid],
                                        self)
         # Inform the corresponding chat
         self.chat_list[iid].receive_call(call)
     else:
         call.hangup(call_prm)
Beispiel #12
0
    def make_call(self, call: Call) -> None:
        """ Add the <call> to this phone line's callhistory, and bill it
        according to the contract for this phone line.
        If there is no bill for the current monthly billing cycle, then a new
        month must be <started> by advancing to the right month from <call>.
        """
        self.callhistory.register_outgoing_call(call)

        if call.get_bill_date() not in self.bills:
            self.bills[call.get_bill_date()] = Bill()
            self.contract.bill_call(call)

        else:
            self.contract.bill_call(call)
Beispiel #13
0
    def test_sets_status(self):
        call = Call(self.callback_succeeds)
        call.join()
        self.assertEqual(call.status, Call.RESOLVED)

        call = Call(self.callback_rejects)
        call.join()
        self.assertEqual(call.status, Call.REJECTED)
Beispiel #14
0
    def call(self):
        vms = self.voicemails
        vms = vms.shuffled()
        num = 10

        print("Playing %d tattles.." % num)
        call = Call()
        path = call.write(vms[0:num])
        answered = call.execute(path)
        answered = True

        if answered:
            self.call_in(config.call_mins_after_answer)
        else:
            self.call_in(config.call_mins_after_no_answer)
Beispiel #15
0
    def test_all(self):
        calls = []
        for i in range(10):

            def func():
                _i = i
                time.sleep(2 + random.random())
                return _i

            calls.append(Call.from_function(func))
            time.sleep(.2)  # Wait before going to next iteration

        results = Call.all(calls).wait()
        for i in range(10):
            self.assertEqual(results[i], i)
    def __preprocess(self):
        """
        Preprocess the callset by filling the regions with no calls with EventType.NO_CALL events, thereby assigning
        an event to every single base.

        """

        for sample in self.sample_names:
            interval_to_call_map = OrderedDict()
            for contig in self.ref_dict.contigs:
                contig_interval = self.ref_dict.get_contig_interval_for_chrom_name(
                    contig)
                events_on_contig = self.sample_to_calls_map.get(
                    sample)._get_interval_tree(contig)
                if not events_on_contig:
                    continue

                result = events_on_contig.copy()
                # TODO make code aware of 1-based representation
                # TODO i.e. right now some events overlap by a single base
                # This hacky code fills potential gaps between calls that lie within interval with NO_CALL events
                result.addi(
                    contig_interval.start, contig_interval.end,
                    Call(interval=contig_interval,
                         sample=sample,
                         event_type=EventType.NO_CALL,
                         call_attributes={
                             "QS": 0,
                             "QA": 0
                         }))
                result.split_overlaps()
                for interval in events_on_contig.items():
                    result.remove_overlap(interval.begin, interval.end)
                for interval in events_on_contig.items():
                    result.addi(interval.begin, interval.end,
                                Call.deep_copy(interval.data))

                for t in sorted(result):
                    if t.end - t.begin == 1 and t.data.event_type == EventType.NO_CALL:
                        # intervaltree.split_overlaps will create single base regions which we want to discard
                        continue
                    call = Call.deep_copy(t.data)
                    if t.data.event_type == EventType.NO_CALL:
                        call.interval = Interval(contig, t.begin, t.end)
                    interval_to_call_map[Interval(contig, t.begin,
                                                  t.end)] = call
            self.sample_to_calls_map[sample] = FeatureCollection(
                interval_to_call_map)
Beispiel #17
0
 def register_outgoing_call(self, call: Call) -> None:
     """ Register a Call <call> into this outgoing call history
     """
     call_date = call.get_bill_date()
     if call_date not in self.outgoing_calls:
         self.outgoing_calls[call_date] = []
     self.outgoing_calls[call_date].append(call)
Beispiel #18
0
 def register_incoming_call(self, call: Call) -> None:
     """ Register a Call <call> into this incoming call history
     """
     k = call.get_bill_date()
     if self.incoming_calls.get(k, 0) == 0:
         self.incoming_calls[k] = []
     self.incoming_calls[k].append(call)
 def test_cancel_contract_positive_balance(self):
     """ Test that the balance is charged as the cancellation fee if the
     contract is cancelled while the balance is positive.
     """
     pc = PrepaidContract(datetime.date(2000, 9, 29), 10)
     pc.new_month(month=10, year=2000, bill=Bill())
     # make a call that costs $15
     c1 = Call(src_nr="123-4567",
               dst_nr="987-6543",
               calltime=datetime.datetime(year=2000,
                                          month=10,
                                          day=31,
                                          hour=20,
                                          minute=30,
                                          second=0),
               duration=ceil(15 / PREPAID_MINS_COST * 60),
               src_loc=(-79.45188229255568, 43.62186408875219),
               dst_loc=(-79.36866519485261, 43.680793196449336))
     pc.bill_call(c1)
     # since the call was very long, the balance should be positive now
     self.assertAlmostEqual(pc.balance, 5)
     cancel = pc.cancel_contract()
     # since the balance is positive, it should be billed, so the cost for
     # the month should be the balance
     self.assertAlmostEqual(cancel, pc.balance)
    def test_bill_call_partially_free(self, t1):
        """ Test that a call is billed correctly even if it is longer than the
        number of free minutes remaining for the month.

        E.g. if 10 free minutes are remaining for the month and a call lasts 11
        minutes, then 10 minutes should be counted as free and 1 minute should
        be billed normally.
        """
        t1_mins = ceil(t1 / 60)
        tc = TermContract(datetime.date(2000, 9, 29),
                          datetime.date(2007, 9, 29))
        tc.new_month(10, 2007, Bill())
        # make a call whose duration is longer than the number of free mins left
        c1 = Call(src_nr="123-4567",
                  dst_nr="987-6543",
                  calltime=datetime.datetime(year=2007,
                                             month=10,
                                             day=31,
                                             hour=20,
                                             minute=30,
                                             second=0),
                  duration=t1,
                  src_loc=(-79.45188229255568, 43.62186408875219),
                  dst_loc=(-79.36866519485261, 43.680793196449336))
        tc.bill_call(c1)
        # check that free mins have been maxed out
        self.assertEqual(tc.bill.free_min, TERM_MINS)
        # check that the rest of the call has been billed
        self.assertEqual(tc.bill.billed_min, t1_mins - TERM_MINS)
 def test_bill_call_not_free(self, t1):
     """ Test that a call is billed correctly if there are no free minutes
     remaining for the month.
     """
     t1_mins = ceil(t1 / 60)
     tc = TermContract(datetime.date(2000, 9, 29),
                       datetime.date(2007, 9, 29))
     bill = Bill()
     tc.new_month(month=10, year=2007, bill=bill)
     # max out free mins so that a new call must be billed
     tc.bill.add_free_minutes(TERM_MINS)
     c1 = Call(src_nr="123-4567",
               dst_nr="987-6543",
               calltime=datetime.datetime(year=2007,
                                          month=10,
                                          day=31,
                                          hour=20,
                                          minute=30,
                                          second=0),
               duration=t1,
               src_loc=(-79.45188229255568, 43.62186408875219),
               dst_loc=(-79.36866519485261, 43.680793196449336))
     tc.bill_call(c1)
     # check that the entire call has been billed
     self.assertAlmostEqual(tc.bill.get_cost() - TERM_MONTHLY_FEE,
                            t1_mins * TERM_MINS_COST)
    def read_in_callset(cls, **kwargs):
        assert "gcnv_segment_vcfs" in kwargs
        gcnv_segment_vcfs = kwargs["gcnv_segment_vcfs"]
        ref_dict = kwargs["reference_dictionary"]
        sample_to_calls_map = {}
        for vcf_file in gcnv_segment_vcfs:

            vcf_reader = vcf.Reader(open(vcf_file, 'r'))
            assert len(vcf_reader.samples) == 1
            sample_name = vcf_reader.samples[0]
            interval_to_call_map = OrderedDict()

            for record in vcf_reader:
                interval = Interval(record.CHROM, record.POS,
                                    record.INFO['END'])
                event_type = EventType.gcnv_genotype_to_event_type(
                    int(record.genotype(sample_name)['GT']))
                attributes = {
                    'QS': int(record.genotype(sample_name)['QS']),
                    'QA': int(record.genotype(sample_name)['QA']),
                    'NP': int(record.genotype(sample_name)['NP'])
                }
                call = Call(interval=interval,
                            sample=sample_name,
                            event_type=event_type,
                            call_attributes=attributes)
                interval_to_call_map[interval] = call

            sample_to_calls_map[sample_name] = FeatureCollection(
                interval_to_call_map)
        return cls(sample_to_calls_map, ref_dict)
Beispiel #23
0
    def dispatch_call(self, caller):
        '''Assign a call to an employee.

        If no employees are available, queue this call.
        '''
        call = Call(caller)
        self._dispatch_call(call)
Beispiel #24
0
def process_event_history(log: Dict[str, List[Dict]],
                          customer_list: List[Customer]) -> None:
    """ Process the calls from the <log> dictionary. The <customer_list>
    list contains all the customers that exist in the <log> dictionary.

    Construct Call objects from <log> and register the Call into the
    corresponding customer's call history.

    Hint: You must advance all customers to a new month using the new_month()
    function, everytime a new month is detected for the current event you are
    extracting.

    Preconditions:
    - All calls are ordered chronologically (based on the call's date and time),
    when retrieved from the dictionary <log>, as specified in the handout.
    - The <log> argument guarantees that there is no "gap" month with zero
    activity for ALL customers, as specified in the handout.
    - The <log> dictionary is in the correct format, as defined in the
    handout.
    - The <customer_list> already contains all the customers from the <log>.
    """
    # TODO: Implement this method. We are giving you the first few lines of code
    billing_date = datetime.datetime.strptime(log['events'][0]['time'],
                                              "%Y-%m-%d %H:%M:%S")
    billing_month = billing_date.month
    current_month = billing_month

    # start recording the bills from this date
    # Note: uncomment the following lines when you're ready to implement this
    #
    new_month(customer_list, billing_date.month, billing_date.year)
    initial = 1

    for event_data in log['events']:
        if event_data['type'] == 'call':
            src_nr = event_data['src_number']
            dst_nr = event_data['dst_number']
            calltime = datetime.datetime.strptime(event_data['time'], \
                                                  "%Y-%m-%d %H:%M:%S")
            duration = int(event_data['duration'])
            src_loc = event_data['src_loc']
            dst_loc = event_data['dst_loc']

            this_call = Call(src_nr, dst_nr, calltime, duration, src_loc, \
                             dst_loc)
            if initial == 1:
                new_month(customer_list, calltime.month, calltime.year)
                current_month = calltime.month
                initial = 0

            if calltime.month != current_month:
                new_month(customer_list, calltime.month, calltime.year)
                current_month = calltime.month

            src = find_customer_by_number(src_nr, customer_list)
            dst = find_customer_by_number(dst_nr, customer_list)

            src.make_call(this_call)
            dst.make_call(this_call)
Beispiel #25
0
    def get_satisfied_seconds(self, call: Call) -> int:
        second = 0

        call_start = call.get_start()
        call_end = call.get_end()

        call_start_date = call_start.date()
        call_end_date = call_end.date()

        while call_start_date < call_end_date:
            second += (
                min(datetime.combine(call_start_date, self.end), call_end) -
                max(datetime.combine(call_start_date, self.start),
                    call_start)).second
            call_start_date += timedelta(days=1)

        return second
Beispiel #26
0
def process_event_history(log: Dict[str, List[Dict]],
                          customer_list: List[Customer]) -> None:
    """ Process the calls from the <log> dictionary. The <customer_list>
    list contains all the customers that exist in the <log> dictionary.

    Construct Call objects from <log> and register the Call into the
    corresponding customer's call history.

    Hint: You must advance all customers to a new month using the new_month()
    function, everytime a new month is detected for the current event you are
    extracting.

    Preconditions:
    - All calls are ordered chronologically (based on the call's date and time),
    when retrieved from the dictionary <log>, as specified in the handout.
    - The <log> argument guarantees that there is no "gap" month with zero
    activity for ALL customers, as specified in the handout.
    - The <log> dictionary is in the correct format, as defined in the
    handout.
    - The <customer_list> already contains all the customers from the <log>.
    """

    billing_date = datetime.datetime.strptime(log['events'][0]['time'],
                                              "%Y-%m-%d %H:%M:%S")
    billing_month = billing_date.month

    # start recording the bills from this date
    # Note: uncomment the following lines when you're ready to implement this

    new_month(customer_list, billing_date.month, billing_date.year)

    for event_data in log['events']:

        if event_data['type'] == 'call':
            e = Call(
                event_data['src_number'], event_data['dst_number'],
                datetime.datetime.strptime(event_data['time'],
                                           "%Y-%m-%d %H:%M:%S"),
                event_data['duration'], event_data['src_loc'],
                event_data['dst_loc'])

            find_customer_by_number(event_data['src_number'],
                                    customer_list).make_call(e)

            find_customer_by_number(event_data['dst_number'],
                                    customer_list).receive_call(e)

        ############ ADVACNING NEW MONTH ############

        if datetime.datetime.strptime(event_data["time"], "%Y-%m-%d %H:%M:%S").\
                month != billing_month:
            billing_month = datetime.datetime.strptime\
                (event_data["time"], "%Y-%m-%d %H:%M:%S").month

            billing_year = datetime.datetime.strptime\
                (event_data["time"], "%Y-%m-%d %H:%M:%S").year

            new_month(customer_list, billing_month, billing_year)
 def start_call(self, request):
     lvn = request.params['from']
     number_insight_json = NCCOHelper.get_call_info(lvn)
     caller_name = number_insight_json.get("caller_name", "")
     call = Call(user_lvn=lvn, state=CallState.CHOOSE_ACTION, is_mobile=number_insight_json["original_carrier"]['network_type'] == "mobile")
     self.calls[request.params['conversation_uuid']] = call
     return NccoBuilder().customer_call_greeting(caller_name).with_input(
         self.domain + NCCOServer.NCCO_INPUT
     ).build()
Beispiel #28
0
def connect_host(connection_type, host='0.0.0.0', port=5098):

    """ handles all outgoing connections from the CLIENT to SERVER """

    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print 'connecting to %s port %s' % (host, port)
    # starts a connection with server
    sock.connect((host, port))
    # receives
    if connection_type == 'dummie':
        username = get_username(host, sock, connection_type)
        return username
    elif connection_type == 'call':
        sock.sendall(connection_type)
        # videofeed.receive_video_feed()
        call_obj = Call(client_ip = host, vid_recv_port = 5010, vid_send_port = 5009)
        call_obj.start()
Beispiel #29
0
 def register_incoming_call(self, call: Call) -> None:
     """ Register a Call <call> into this incoming call history
     """
     # TODO: Implement this method
     date = call.get_bill_date()
     if date not in self.incoming_calls:
         self.incoming_calls[date] = [call]
     else:
         self.incoming_calls[date].append(call)
Beispiel #30
0
    def init(self):
        """register on the network"""
        logger.info("Turn on antenna power")
        logger.info("Register on the network")
        self.emit('provider-modified', "Charlie Telecom")
        self.network_strength = 100
        yield tichy.Service.get('ConfigService').wait_initialized()
        self.config_service = tichy.Service.get("ConfigService")
        logger.info("got config service")
        self.values = self.config_service.get_items("call_forwarding")
        if self.values != None: self.values = dict(self.values)
        logger.info("realized values is none")
        self.SettingReason = tichy.settings.ListSetting(
            'Call Forwarding',
            'Reason',
            tichy.Text,
            value='unconditional',
            setter=self.ForwardingSetReason,
            options=[
                "unconditional", "mobile busy", "no reply", "not reachable",
                "all", "all conditional"
            ],
            model=tichy.List([
                ListSettingObject("unconditional", self.action),
                ListSettingObject("mobile busy", self.action),
                ListSettingObject("no reply", self.action),
                ListSettingObject("not reachable", self.action),
                ListSettingObject("all", self.action),
                ListSettingObject("all conditional", self.action)
            ]),
            ListLabel=[('title', 'name')])
        self.SettingChannels = tichy.settings.Setting(
            'Call Forwarding',
            'channels',
            tichy.Text,
            value=self.ForwardingGet('class'),
            setter=self.ForwardingSetClass,
            options=["voice", "data", "voice+data", "fax", "voice+data+fax"])
        self.SettingTargetNumber = tichy.settings.NumberSetting(
            'Call Forwarding',
            'Target Number',
            tichy.Text,
            value=self.ForwardingGet('number'),
            setter=self.ForwardingSetNumber)
        self.SettingTargetNumber = tichy.settings.NumberSetting(
            'Call Forwarding',
            'Timeout',
            tichy.Text,
            value=self.ForwardingGet('timeout'),
            setter=self.ForwardingSetTimeout)

        if len(self.logs) == 0:
            for i in range(3):
                call = Call('0049110', direction='out')
                self.logs.insert(0, call)
        yield None