Exemple #1
0
    def create_callee(callee):
        """
		Create a callee entity if not exist. Else update date of first call
		:param callee: Callee instance
		:return: Callee instance
		"""
        try:
            # Get existing callee entity by its phone number
            exs_callee = Callee.objects.get(
                user_profile_id=callee.user_profile_id, sip=callee.sip)
            # check if existing callee first call date over current callee first call date
            # If true that means current call of callee was before existing and existing needs to be updated with new date
            if exs_callee.first_call_date.replace(tzinfo=pytz.utc).replace(
                    tzinfo=None) > callee.first_call_date:
                exs_callee.first_call_date = callee.first_call_date
                exs_callee.save()
            # Else just return existing callee
            return ServiceResponse(True, data=exs_callee)
        except ObjectDoesNotExist as e:
            # Create a new callee
            try:
                callee.save()
            except Exception as e:
                # Callee isn't created
                return ServiceResponse(False, data=callee, message=str(e))
            return ServiceResponse(True, data=callee)
Exemple #2
0
    def update_calls_list(params, user):
        """
		Update db table Calls
		:param params: ApiParams
		:param user: User
		:return:
		"""
        # get common stat
        stat_common_res = PBXDataService.get_common_stat(params, user)
        if not stat_common_res.is_success:
            return ServiceResponse(False,
                                   message=Code.UCLUNS,
                                   data={
                                       'params': params,
                                       'user_id': user.pk
                                   },
                                   status_code=stat_common_res.status_code)

        # get pbx stat
        stat_pbx_res = PBXDataService.get_pbx_stat(params, user)
        if not stat_pbx_res.is_success:
            return ServiceResponse(False,
                                   message=Code.UCLUNS,
                                   data={
                                       'params': params,
                                       'user_id': user.pk
                                   },
                                   status_code=stat_pbx_res.status_code)

        # group pbx stat
        stat_pbx_grouped = PBXDataService.group_stat_pbx(stat_pbx_res.data)

        parseed_calls = PBXDataService.parse_calls(stat_common_res.data,
                                                   stat_pbx_grouped,
                                                   user.userprofile)
        callbacks = PBXDataService.merge(stat_common_res.data, parseed_calls,
                                         user.userprofile)

        other_calls = PBXDataService.parse_other(
            filter(lambda x: not x.merged, stat_common_res.data),
            filter(lambda x: not x.merged, parseed_calls), user.userprofile)

        calls = callbacks + other_calls

        # Get existing calls stat
        user_stat = user.userprofile.call_set.filter(date__gte=params.start,
                                                     date__lte=params.end)

        # update calls table and return
        return PBXDataService.update_calls_list_by_type(
            user.userprofile,
            user_stat,
            filter(lambda x: x.call_type == 'incoming', calls),
            filter(lambda x: x.call_type == 'coming', calls),
            filter(lambda x: x.call_type == 'internal', calls),
        )
Exemple #3
0
	def create_profile(data):
		"""
		Creates a new user and userProfile
		:param data: NewUserForm data instance
		:return: ServiceResponse
		"""
		try:
			user = User.objects.create_user(username=data['userName'], email=data['userEmail'], password=data['userPassword'])
			user.save()
			user_profile = UserProfile.objects.create(profile_email=data['login'], profile_password=data['password'], uid=data['uid'], token=data['token'], user_key=data['userKey'], secret_key=data['secretKey'], user_id=user.id, customer_number=data['customerNumber'], profile_phone_number=data['profilePhoneNumber'])
			user_profile.save()
			widget = WidgetScript(user_profile=user_profile)
			widget.save()
			return ServiceResponse(True, data=user)
		except Exception as e:
			return ServiceResponse(False, e.message)
Exemple #4
0
    def create_call(call_record, userprofile):
        """
		Create call entity
		:param call_record: Call instance
		:param userprofile: UserProfile instance
		:return: Call instance
		"""
        if (isinstance(call_record.destination, str)
                or isinstance(call_record.destination,
                              unicode)) and 'w00e' in call_record.destination:
            call_record.destination = call_record.destination[4:]

        if (isinstance(call_record.sip, str) or isinstance(
                call_record.sip, unicode)) and 'w00e' in call_record.sip:
            call_record.sip = call_record.sip[4:]

        callee = Callee(sip=call_record.sip,
                        description=call_record.description,
                        first_call_date=call_record.date,
                        user_profile_id=userprofile.pk)
        # create Callee entity or ensure it exist
        result = DBService.create_callee(callee)

        if result.is_success:
            call = Call(call_id=call_record.call_id,
                        date=call_record.date,
                        destination=call_record.destination,
                        disposition=call_record.disposition,
                        bill_seconds=call_record.bill_seconds,
                        cost=call_record.cost,
                        bill_cost=call_record.bill_cost,
                        currency=call_record.currency,
                        user_profile=userprofile,
                        callee=result.data,
                        call_type=call_record.call_type)
            # create Call Instance
            try:
                call.save()
            except Exception as e:
                # Call isn't created
                return ServiceResponse(False, data=call, message=e.message)
            return ServiceResponse(True, data=call)
        # Callee isn't created
        return ServiceResponse(False, data=result.data, message=result.message)
Exemple #5
0
    def generate_mailbox_data():
        """
		Generate new mailbox data
		:return: ServiceResponse: {'login': <login>, 'password': <password>}
		"""
        login = CommonService.get_random_string(6, only_digits=True)
        password = ApiService.generate_email_password(login)
        return ServiceResponse(True, {
            'login': '******' % (login, settings.DOMAIN),
            'password': password
        })
Exemple #6
0
	def sign_in(request):
		"""
		Authenticate and Sign in user by login and password
		:param request: HTTP request
		:return: True if the user was singed in
		"""
		form = AuthUserForm(request.POST)
		if form.errors:
			return ServiceResponse(False, form.errors)
		auth_user = authenticate(username=form.data['username'], password=form.data['password'])
		if auth_user is not None:

			if not auth_user.is_superuser and (not auth_user.last_login or not auth_user.userprofile.sip):
				auth_user.userprofile.sip = PBXDataService.get_pbx_sip(auth_user)
				auth_user.userprofile.save()

			login(request, auth_user)

			return ServiceResponse(True, data=auth_user)
		return ServiceResponse(False, {'username': ['Invalidusernameorpassword'], 'password': ['Invalidusernameorpassword']})
Exemple #7
0
    def create_domain_mail(params):
        """
		Create new domain email.
		:param params: MailParameters instance
		:return: ServiceResponse, api response data: {'domain': 'name', 'login': '******', 'uid': 'uid, 'success': 'status'}
		"""
        request_string = '%s%s' % (settings.API_URLS['mail']['host'],
                                   settings.API_URLS['mail']['create_mail'])
        api_response = requests.post(
            request_string,
            params.get_params(),
            headers={'PddToken': settings.MAIL_A_TOKEN})
        return ServiceResponse(api_response.ok,
                               json.loads(api_response.content))
Exemple #8
0
    def get_common_stat(params, user):
        """
		Get statistics from api
		:param params: ApiParameters instance
		:param user: User instance
		:return: json type
		"""
        method = settings.API_URLS['api']['common_stat']
        api_response = requests.get(
            params.get_request_string(method),
            headers={
                'Authorization':
                '%s:%s' %
                (user.userprofile.user_key,
                 CommonService.get_sign(params, method, params.api_version,
                                        user.userprofile.secret_key))
            })
        if api_response.ok:
            return ServiceResponse(
                api_response.ok,
                [Call(s) for s in json.loads(api_response.content)['stats']])
        return ServiceResponse(api_response.ok,
                               status_code=api_response.status_code)
Exemple #9
0
    def get_url(reason):
        """
		Returns url to the api depending on reason
		:param reason: string
		:return: ServiceResponse
		"""
        result = ''
        status = True
        if reason == 'OAuthCode':
            result = '%s%s&client_id=%s' % (
                settings.API_URLS['oauth']['host'],
                settings.API_URLS['oauth']['authorize'], settings.O_AUTH_ID)
        else:
            status = not status
        return ServiceResponse(status, result)
Exemple #10
0
    def update_mailbox_params(login, **params):
        """
		Update mailbox params
		:param params: MailboxParameters instance; Set default params if value is None
		:return: ServiceResponse
		"""
        request_string = '%s%s' % (settings.API_URLS['mail']['host'],
                                   settings.API_URLS['mail']['update_mail'])
        if not params:
            params = MailboxParameters(login=login, params=params)
        api_response = requests.post(
            request_string,
            params.get_params(),
            headers={'PddToken': settings.MAIL_A_TOKEN})
        return ServiceResponse(api_response.ok,
                               json.loads(api_response.content))
Exemple #11
0
    def get_token(code):
        """
		Get OAuth token to api access
		Api response data: {'access_token': 'token', 'token_type': 'bearer', 'expires_in': 'time_in_seconds'}
		:param code: verifying code
		:return: ServiceResponse
		"""
        request_string = '%s%s' % (settings.API_URLS['oauth']['host'],
                                   settings.API_URLS['oauth']['token'])
        api_response = requests.post(
            request_string, {
                'grant_type': 'authorization_code',
                'code': code,
                'client_id': settings.O_AUTH_ID,
                'client_secret': settings.O_AUTH_SECRET
            },
            headers={'Content-type': 'application/x-www-form-urlencoded'})
        return ServiceResponse(api_response.ok,
                               json.loads(api_response.content))
Exemple #12
0
    def update_calls_list_by_type(userprofile, stat, *args):
        """
		Update calls table of each call type
		:param userprofile: user profile
		:param stat: existing stat
		:param args: calls lists
		:return:
		"""
        message = '{row_to_update} row(s) to be inserted. '
        update_errors = []
        total_rows_to_update = 0

        for arg in args:
            if len(arg) != 0:
                call_type = arg[0].call_type
                user_stat = stat.filter(call_type=call_type)

                row_to_update = len(arg) - len(user_stat)
                if row_to_update > 0:
                    total_rows_to_update += row_to_update

                    for a in arg:
                        # check if current call already exist
                        stat_record = stat.filter(call_id=a.call_id)

                        # save to db if not
                        if not stat_record:
                            result = DBService.create_call(a, userprofile)

                            if not result.is_success:
                                update_errors.append((
                                    result.data,
                                    result.message,
                                ))

        if len(update_errors) > 0:
            # Update calls list succeed with errors
            message = message.format(row_to_update=total_rows_to_update)
            message += Code.UCLSWE

        return ServiceResponse(True, data=update_errors, message=message)
Exemple #13
0
    def upload_file(self, file_instance, folder_name=None):
        """
		Upload file to Disk
		:param file_instance: file instance
		:param folder_name: folder name
		:return: File instance
		"""
        folder_name = self.create_folder(folder_name)
        if not folder_name:
            return None

        upload_link = self.__get_upload_link(file_instance.filename)
        if not upload_link:
            return None

        # upload file
        response = requests.put(upload_link, file_instance.content)
        if response.ok:
            return ServiceResponse(True, data=file_instance)

        logger.error(Code.UPLOAD_FILE_ERR,
                     data=json.loads(response.content),
                     status_code=response.status_code)
        return None