def get_call_cost(user, to): """ Get the cost of the call :param to: target phone number :return: """ method = settings.API_URLS['api']['call_cost'] # WARNING: Creates ApiParams with {start} and {end} params. Needs to be refactored params = ApiParams({'number': to}) url = params.get_request_string(method) response = requests.get( url, headers={ 'Authorization': '%s:%s' % (user.userprofile.user_key, CommonService.get_sign(params, method, params.api_version, user.userprofile.secret_key)) }) content = response.content if response.ok: return json.loads(content)['info'] logger = LogService() logger.error(Code.GET_CALL_COST_ERR, data=json.loads(content), status_code=response.status_code) return None
def create_subscr_transaction(user, params): """ Creates new Subscribe transaction :param user: current user :param params: transaction params :return: SubscribeTransaction instance """ try: subscr = SubscribeTransaction( transact_id=params['label'], receiver=params['receiver'], form_comments=params['form_comment'], short_dest=params['short_dest'], quickpay_form=params['quickpay_form'], targets=params['targets'], sum=params['sum'], payment_type=params['paymentType'], duration=params['duration'], expiration_date=None, user_profile=user.userprofile, status=TransactionStatus.objects.get(pk=1)) subscr.save() return subscr except Exception as e: logger = LogService() logger.error(Code.CREATE_SUBSCR_TRANSACTION_ERR, props=params, message=str(e)) return None
def convert_to_mp3(file_instance, target_format='mp3', delete_source=True): """ Convert audio file to mp3 :param file_instance: source file instance :param target_format: format to convert :param delete_source: flag to delete source instance after convert succeed :return: File instance """ try: audio_mp3 = File(filename=file_instance.filename.replace( '.wav', '.' + target_format), path=file_instance.path.replace( '.wav', '.' + target_format)) audio_mp3.content = AudioSegment.from_wav( file_instance.path).export(audio_mp3.path, format=target_format, bitrate='16k') if delete_source: CommonService.delete_temp_file(file_instance.filename) return audio_mp3 except Exception as e: logger = LogService() logger.error(Code.CONVERT_TO_MP3_ERR, message=str(e)) return None
def get_pbx_sip(user): """ Get sip number :param user: user :return: sip """ method = settings.API_URLS['api']['sip'] # WARNING: Creates ApiParams with {start} and {end} params. Needs to be refactored params = ApiParams() url = params.get_request_string(method) response = requests.get( url, headers={ 'Authorization': '%s:%s' % (user.userprofile.user_key, CommonService.get_sign(params, method, params.api_version, user.userprofile.secret_key)) }) content = response.content if response.ok: sips = json.loads(content)['sips'] sip = int( filter(lambda s: s['display_name'] == 'SIP', sips)[0]['id']) return sip logger = LogService() logger.error(Code.SIP_GETTING_ERR, data=json.loads(content), status_code=response.status_code) return None
def get_pbx_account_balance(user): """ Get current user account balance :param user: user instance :return: {float} current balance """ host = settings.API_URLS['api']['host'] api_version = settings.API_URLS['api']['api_version'] method = settings.API_URLS['api']['balance'] url = '{host}{api_version}{method}'.format(host=host, api_version=api_version, method=method) response = requests.get( url, headers={ 'Authorization': '%s:%s' % (user.userprofile.user_key, CommonService.get_sign({}, method, api_version, user.userprofile.secret_key)) }) content = response.content if response.ok: return json.loads(content)['balance'] logger = LogService() logger.error(Code.GET_BALANCE_ERR, data=json.loads(content), status_code=response.status_code) return None
def create_incoming_info(caller_id, called_did, call_start, script_guid): """ Creates incoming info :param caller_id: :param called_did: :param call_start: :param script_guid: :return: """ incoming_info = None try: expiration_date = call_start + datetime.timedelta(minutes=2) incoming_info = IncomingInfo(caller_id=caller_id, call_start=call_start, called_did=called_did, expiration_date=expiration_date, script_id=script_guid) incoming_info.save() return incoming_info except Exception as e: logger = LogService() logger.error(Code.INCOMING_INFO_ERR, data=incoming_info, message=str(e)) return None
def get_call(**kwargs): """ Get Call entity by prop names :param kwargs: prop names :return: Call entity """ try: return Call.objects.get(**kwargs) except Exception as e: logger = LogService() logger.error(Code.GET_CALL_ERR, props=kwargs, message=str(e)) return None
def delete_temp_file(filename): """ Delete temp file from the filesystem :param filename: name of the file :return: """ try: os.remove( os.path.join(settings.BASE_DIR, settings.TEMP_DIR) + filename) except Exception as e: logger = LogService() logger.warning(Code.WRITE_TEMP_FILE_ERR, message=str(e), file_path=filename)
def load_call_record_file(call, user): """ Load audio, convert, upload to disk and update db with filename :param call: Call instance :param user: current user :return: File instance """ # get audio call_audio = PBXDataService.get_audio(call.call_id, user) if not call_audio: return None # # # convert audio # # write temp file # path = CommonService.write_temp_file(call_audio) # if not path: # return None # # call_audio.path = path # # # convert wav to mp3 # # call_audio_mp3 = CommonService.convert_to_mp3(call_audio) # if not call_audio_mp3: # return None call_audio_mp3 = call_audio # upload new file to Disk disk_service = DiskService(user.userprofile.token) result = disk_service.upload_file(call_audio_mp3) if not result.is_success: return None filename = call_audio_mp3.filename # delete mp3 file form filesystem and save to db CommonService.delete_temp_file(filename) try: call.record_filename = filename call.save() except Exception as e: logger = LogService() logger.error(Code.UPDATE_CALL_ERR, message=str(e), call_id=call.pk, filename=filename) return None return filename
def get_audio(call_id, user): """ Check user mailbox to find the record :param call_id: id of the call :param user: current logged user :return: filename """ username = user.userprofile.profile_email password = user.userprofile.profile_password imap_server = 'imap.yandex.ru' header_start = 'audio/wav; name="' call_audio = None try: # connect to mailbox mailbox = imaplib.IMAP4_SSL(imap_server) mailbox.login(username, password) mailbox.select('INBOX') for msg_id in range(len(mailbox.search(None, 'ALL')[1][0].split()), 0, -1): message = email.message_from_string( mailbox.fetch(msg_id, '(RFC822)')[1][0][1]) for part in message.get_payload(): if isinstance(part, email.message.Message): header = filter( lambda x: x.startswith(header_start) and x.find( call_id) > 0, part.values()) if header and len(header) > 0: filename = header[0].strip(header_start) call_audio = File(part.get_payload(decode=True), filename) break if call_audio: break mailbox.logout() except Exception as e: logger = LogService() logger.error(Code.GET_AUDIO_ERR, message=str(e), call_id=call_id, username=user.username) return None return call_audio
def write_temp_file(file_instance): """ Write the file to the filesystem :param file_instance: File instance :return: path to the file """ folder_path = os.path.join(settings.BASE_DIR, settings.TEMP_DIR) file_path = '%s%s' % (folder_path, file_instance.filename) try: if not os.path.exists(folder_path): os.makedirs(folder_path) open(file_path, 'wb').write(file_instance.content) return file_path except Exception as e: logger = LogService() logger.error(Code.WRITE_TEMP_FILE_ERR, message=str(e), file_path=file_path) return None
def register_callback(user_profile, caller, destination): """ Register callback in database :param user_profile: user's profile instance :param caller: callback caller :param destination: callback destination :return: """ callback = None try: callback = RegisteredCallback(caller=caller, destination=destination, user_profile=user_profile) callback.save() return callback except Exception as e: logger = LogService() logger.error(Code.REGISTER_CALLBACK_ERR, data=callback, message=str(e)) return None
def create_profile_request_transact(profile_request): """ Create a new profile request transaction :param profile_request: ProfileRequest instance :return: created ProfileRequestTransaction instance """ profile_request_transact = None try: profile_request_transact = ProfileRequestTransaction( transact_id=profile_request.transact_id, creation_date=profile_request.creation_date, email=profile_request.email, username=profile_request.login, status=TransactionStatus.objects.get(pk=1)) profile_request_transact.save() return profile_request_transact except Exception as e: logger = LogService() logger.error(Code.CREATE_SUBSCR_TRANSACTION_ERR, data=profile_request_transact, message=str(e)) return None
def send(self, smtp='smtp.yandex.com', username='******', password='******'): """ Send email message :param smtp: server to send message :param username: server to send message :param password: server to send message :return: """ try: connection = SMTP_SSL(smtp) connection.set_debuglevel(False) connection.login(username, password) connection.sendmail(self.__sender, self.__destination, self.get_message()) connection.close() return True except Exception as e: logger = LogService() logger.error(Code.EMAIL_SEND_ERR, message=str(e)) return False
def request_callback(user, from_number, to_number): """ Request the callback :param user: user instance :param form: prom number :param to: to number :return: """ method = settings.API_URLS['api']['request_callback'] # WARNING: Creates ApiParams with {start} and {end} params. Needs to be refactored params = ApiParams({'from': from_number, 'to': to_number}) url = params.get_request_string(method) response = requests.get( url, headers={ 'Authorization': '%s:%s' % (user.userprofile.user_key, CommonService.get_sign(params, method, params.api_version, user.userprofile.secret_key)) }) content = response.content if response.ok: callback = DBService.register_callback(user.userprofile, from_number, to_number) if callback: return json.loads(content) logger = LogService() logger.error(Code.REQUEST_CALLBACK_ERR, data=json.loads(content), status_code=response.status_code) return None
def get_transact(transact_id): """ Get an existing transact by its id :param transact_id: transact_id :return: Transact instance """ try: from telephone.classes.view_models.SubscribeTransaction import SubscribeTransactionVM from telephone.classes.view_models.ProfileRequestTransaction import ProfileRequestTransactionVM try: return SubscribeTransactionVM( SubscribeTransaction.objects.get(transact_id=transact_id)) except ObjectDoesNotExist as e: return ProfileRequestTransactionVM( ProfileRequestTransaction.objects.get( transact_id=transact_id)) except Exception as e: logger = LogService() logger.error(Code.GET_TRANSACT_ERR, transact_id=transact_id, message=str(e)) return None
def __init__(self, transact): super(SubscribeTransactionVM, self).__init__() self.__transact = transact self.__logger = LogService()
import json import requests from telephone import settings from telephone.classes.File import File from telephone.classes.ServiceResponse import ServiceResponse from telephone.service_app.services.LogService import LogService, Code logger = LogService() class DiskService(): def __init__(self, token): self.__host_url = settings.API_URLS['disk']['host'] self.__file_download_link_url = settings.API_URLS['disk'][ 'file_download_link'] self.__file_upload_link_url = settings.API_URLS['disk'][ 'file_upload_link'] self.__files_info_url = settings.API_URLS['disk']['files_info'] self.__create_folder_url = settings.API_URLS['disk']['create_folder'] self.__token = token self.__headers = { 'Content-Type': 'application/json', 'Authorization': 'OAuth %s' % self.__token } self.__default_folder = settings.DISK_UPLOAD_FOLDER @property def default_folder(self): """
def __init__(self, transact): self.__transact = transact self.__logger = LogService()