Exemplo n.º 1
0
    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
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
	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
Exemplo n.º 5
0
    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
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
    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
Exemplo n.º 8
0
	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
Exemplo n.º 9
0
	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)
Exemplo n.º 10
0
    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
Exemplo n.º 11
0
	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
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
	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
Exemplo n.º 15
0
	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
Exemplo n.º 16
0
	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
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
    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
Exemplo n.º 19
0
	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
Exemplo n.º 20
0
	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
Exemplo n.º 21
0
	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
Exemplo n.º 22
0
	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
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
	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
Exemplo n.º 25
0
	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
Exemplo n.º 26
0
	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
Exemplo n.º 27
0
    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
Exemplo n.º 28
0
    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
Exemplo n.º 29
0
	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
Exemplo n.º 30
0
    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
Exemplo n.º 31
0
    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
Exemplo n.º 32
0
	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
Exemplo n.º 33
0
 def __init__(self, transact):
     super(SubscribeTransactionVM, self).__init__()
     self.__transact = transact
     self.__logger = LogService()
Exemplo n.º 34
0
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):
        """
class SubscribeTransactionVM(TransactAction):
	def __init__(self, transact):
		super(SubscribeTransactionVM, self).__init__()
		self.__transact = transact
		self.__logger = LogService()

	def archive(self, **kwargs):
		"""
		Execute to archive transaction
		:return: transact
		"""
		self.__transact.is_archive = not self.__transact.is_archive
		return self.__save()

	def confirm(self, **kwargs):
		"""
		Execute confirm transaction
		:return: transact
		"""
		self.__transact.status_id = 2
		self.__transact.expiration_date = CommonService.add_months(datetime.datetime.now(), self.__transact.duration)
		return self.__save(self.__extend_subscription)

	def cancel(self, **kwargs):
		"""
		Change transact status to cancel
		:return: transact
		"""
		self.__transact.status_id = 3
		return self.__save()

	def __extend_subscription(self, *args):
		"""
		Extend profile subscription and send e-mail
		:param args:
		"""
		ProfileService.extend_subscription(self.__transact.user_profile, self.__transact.duration)

		message = MailMessage(settings.INFO_EMAIL, 'Продление подписки', 'mail_tmpl_subscribe_extended.html', {
			'username': self.__transact.user_profile.user.username,
			'expiration_date': self.__transact.user_profile.date_subscribe_ended
		}, self.__transact.user_profile.user.email)
		message.send()

	def __save(self, on_success=None):
		"""
		Save entity changes
		:param on_success: callback on successful changes
		:return: True if saving executed success or False if exception has been raised
		"""
		try:
			self.__transact.save()
			if on_success and hasattr(on_success, '__call__'):
				on_success(self.__transact)
			return True
		except Exception as e:
			self.__logger.error(Code.SAVE_ENTITY_ERR, action=inspect.stack()[1][3], transact_id=self.__transact.transact_id, message=str(e))
			return False

	@property
	def transact_id(self):
		"""
		Getter of __transact_id
		:return: transact_id value
		"""
		return self.__transact.transact_id

	@property
	def sum(self):
		"""
		Getter of __sum
		:return: sum value
		"""
		return self.__transact.sum

	@property
	def payment_type(self):
		"""
		Getter of __payment_type
		:return: payment_type value
		"""
		return self.__transact.payment_type

	@property
	def duration(self):
		"""
		Getter of __duration
		:return: duration value
		"""
		return '{value} мес'.format(value=self.__transact.duration)

	@property
	def username(self):
		"""
		Getter of __username
		:return: username value
		"""
		return self.__transact.user_profile.user.username

	@property
	def creation_date(self):
		"""
		Getter of __creation_date
		:return: creation_date value
		"""
		return self.__transact.creation_date

	@property
	def status_id(self):
		"""
		Getter of __status_id
		:return: status_id value
		"""
		return self.__transact.status_id

	@property
	def status_value(self):
		"""
		Getter of __status_value
		:return: status_value value
		"""
		return self.__transact.status.value

	@property
	def is_archive(self):
		"""
		Getter of __is_archive
		:return: is_archive value
		"""
		return self.__transact.is_archive
Exemplo n.º 36
0
class SubscribeTransactionVM(TransactAction):
    def __init__(self, transact):
        super(SubscribeTransactionVM, self).__init__()
        self.__transact = transact
        self.__logger = LogService()

    def archive(self, **kwargs):
        """
		Execute to archive transaction
		:return: transact
		"""
        self.__transact.is_archive = not self.__transact.is_archive
        return self.__save()

    def confirm(self, **kwargs):
        """
		Execute confirm transaction
		:return: transact
		"""
        self.__transact.status_id = 2
        self.__transact.expiration_date = CommonService.add_months(
            datetime.datetime.now(), self.__transact.duration)
        return self.__save(self.__extend_subscription)

    def cancel(self, **kwargs):
        """
		Change transact status to cancel
		:return: transact
		"""
        self.__transact.status_id = 3
        return self.__save()

    def __extend_subscription(self, *args):
        """
		Extend profile subscription and send e-mail
		:param args:
		"""
        ProfileService.extend_subscription(self.__transact.user_profile,
                                           self.__transact.duration)

        message = MailMessage(
            settings.INFO_EMAIL, 'Продление подписки',
            'mail_tmpl_subscribe_extended.html', {
                'username':
                self.__transact.user_profile.user.username,
                'expiration_date':
                self.__transact.user_profile.date_subscribe_ended
            }, self.__transact.user_profile.user.email)
        message.send()

    def __save(self, on_success=None):
        """
		Save entity changes
		:param on_success: callback on successful changes
		:return: True if saving executed success or False if exception has been raised
		"""
        try:
            self.__transact.save()
            if on_success and hasattr(on_success, '__call__'):
                on_success(self.__transact)
            return True
        except Exception as e:
            self.__logger.error(Code.SAVE_ENTITY_ERR,
                                action=inspect.stack()[1][3],
                                transact_id=self.__transact.transact_id,
                                message=str(e))
            return False

    @property
    def transact_id(self):
        """
		Getter of __transact_id
		:return: transact_id value
		"""
        return self.__transact.transact_id

    @property
    def sum(self):
        """
		Getter of __sum
		:return: sum value
		"""
        return self.__transact.sum

    @property
    def payment_type(self):
        """
		Getter of __payment_type
		:return: payment_type value
		"""
        return self.__transact.payment_type

    @property
    def duration(self):
        """
		Getter of __duration
		:return: duration value
		"""
        return '{value} мес'.format(value=self.__transact.duration)

    @property
    def username(self):
        """
		Getter of __username
		:return: username value
		"""
        return self.__transact.user_profile.user.username

    @property
    def creation_date(self):
        """
		Getter of __creation_date
		:return: creation_date value
		"""
        return self.__transact.creation_date

    @property
    def status_id(self):
        """
		Getter of __status_id
		:return: status_id value
		"""
        return self.__transact.status_id

    @property
    def status_value(self):
        """
		Getter of __status_value
		:return: status_value value
		"""
        return self.__transact.status.value

    @property
    def is_archive(self):
        """
		Getter of __is_archive
		:return: is_archive value
		"""
        return self.__transact.is_archive
	def __init__(self, transact):
		super(SubscribeTransactionVM, self).__init__()
		self.__transact = transact
		self.__logger = LogService()
Exemplo n.º 38
0
class ProfileRequestTransactionVM(TransactAction):
    def __init__(self, transact):
        self.__transact = transact
        self.__logger = LogService()

    def cancel(self, **kwargs):
        """
		Change transact status to cancel
		:return: transact
		"""
        self.__transact.status_id = 3
        return self.__save()

    def confirm(self, **kwargs):
        """
		Execute confirm transaction
		:return: transact
		"""
        self.__transact.status_id = 2
        return self.__save()

    def archive(self, **kwargs):
        """
		Archive method isn't support by profileRequestTransaction model
		:param kwargs:
		"""
        raise NotImplementedError('This method isn\'t implemented')

    def __save(self, on_success=None):
        """
		Save entity changes
		:param on_success: callback on successful changes
		:return: True if saving executed success or False if exception has been raised
		"""
        try:
            self.__transact.save()
            if on_success and hasattr(on_success, '__call__'):
                on_success(self.__transact)
            return True
        except Exception as e:
            self.__logger.error(Code.SAVE_ENTITY_ERR,
                                action=inspect.stack()[1][3],
                                transact_id=self.__transact.transact_id,
                                message=str(e))
            return False

    @property
    def transact_id(self):
        """
		Getter of __transact_id
		:return: transact_id value
		"""
        return self.__transact.transact_id

    @property
    def creation_date(self):
        """
		Getter of __creation_date
		:return: creation_date value
		"""
        return self.__transact.creation_date

    @property
    def email(self):
        """
		Getter of __email
		:return: email value
		"""
        return self.__transact.email

    @property
    def username(self):
        """
		Getter of __username
		:return: username value
		"""
        return self.__transact.username

    @property
    def status_id(self):
        """
		Getter of __status_id
		:return: status_id value
		"""
        return self.__transact.status_id

    @property
    def status_value(self):
        """
		Getter of __status_value
		:return: status_value value
		"""
        return self.__transact.status.value
Exemplo n.º 39
0
 def __init__(self, transact):
     self.__transact = transact
     self.__logger = LogService()
class ProfileRequestTransactionVM(TransactAction):
	def __init__(self, transact):
		self.__transact = transact
		self.__logger = LogService()

	def cancel(self, **kwargs):
		"""
		Change transact status to cancel
		:return: transact
		"""
		self.__transact.status_id = 3
		return self.__save()

	def confirm(self, **kwargs):
		"""
		Execute confirm transaction
		:return: transact
		"""
		self.__transact.status_id = 2
		return self.__save()

	def archive(self, **kwargs):
		"""
		Archive method isn't support by profileRequestTransaction model
		:param kwargs:
		"""
		raise NotImplementedError('This method isn\'t implemented')

	def __save(self, on_success=None):
		"""
		Save entity changes
		:param on_success: callback on successful changes
		:return: True if saving executed success or False if exception has been raised
		"""
		try:
			self.__transact.save()
			if on_success and hasattr(on_success, '__call__'):
				on_success(self.__transact)
			return True
		except Exception as e:
			self.__logger.error(Code.SAVE_ENTITY_ERR, action=inspect.stack()[1][3], transact_id=self.__transact.transact_id, message=str(e))
			return False

	@property
	def transact_id(self):
		"""
		Getter of __transact_id
		:return: transact_id value
		"""
		return self.__transact.transact_id

	@property
	def creation_date(self):
		"""
		Getter of __creation_date
		:return: creation_date value
		"""
		return self.__transact.creation_date

	@property
	def email(self):
		"""
		Getter of __email
		:return: email value
		"""
		return self.__transact.email

	@property
	def username(self):
		"""
		Getter of __username
		:return: username value
		"""
		return self.__transact.username

	@property
	def status_id(self):
		"""
		Getter of __status_id
		:return: status_id value
		"""
		return self.__transact.status_id

	@property
	def status_value(self):
		"""
		Getter of __status_value
		:return: status_value value
		"""
		return self.__transact.status.value
	def __init__(self, transact):
		self.__transact = transact
		self.__logger = LogService()