def validate(self, attrs): """ Validate sms campaign form """ request = self.context['request'] if request.method == 'POST': name_count = SMSCampaign.objects.filter(name=attrs.get('name'), user=request.user).count() if name_count != 0: raise serializers.ValidationError("The SMS Campaign name duplicated!") if not user_dialer_setting(request.user): raise serializers.ValidationError("Your settings are not configured properly, Please contact the administrator.") if check_sms_dialer_setting(request, check_for="smscampaign"): raise serializers.ValidationError("Too many sms campaigns. Max allowed %s" % dialer_setting_limit(request, limit_for="smscampaign")) frequency = attrs.get('frequency') if frequency: if check_sms_dialer_setting(request, check_for="smsfrequency", field_value=int(frequency)): raise serializers.ValidationError("Frequency limit of %s exceeded." % dialer_setting_limit(request, limit_for="smsfrequency")) maxretry = attrs.get('maxretry') if maxretry: if check_sms_dialer_setting(request, check_for="smsretry", field_value=int(maxretry)): raise serializers.ValidationError("Retries limit of %s exceeded." % dialer_setting_limit(request, limit_for="smsretry")) return attrs
def clean(self): cleaned_data = self.cleaned_data frequency = cleaned_data.get('frequency') maxretry = cleaned_data.get('maxretry') phonebook = cleaned_data.get('phonebook') if not phonebook: msg = _('you must select at least one phonebook') self._errors['phonebook'] = ErrorList([msg]) del self.cleaned_data['phonebook'] sms_dialer_set = user_dialer_setting(self.user) if sms_dialer_set: if frequency > sms_dialer_set.sms_max_frequency: msg = _('Maximum Frequency limit of %d exceeded.' % sms_dialer_set.sms_max_frequency) self._errors['frequency'] = ErrorList([msg]) del self.cleaned_data['frequency'] if maxretry > sms_dialer_set.sms_maxretry: msg = _('Maximum Retries limit of %d exceeded.' % sms_dialer_set.sms_maxretry) self._errors['maxretry'] = ErrorList([msg]) del self.cleaned_data['maxretry'] return cleaned_data
def clean(self): cleaned_data = self.cleaned_data ds_user = cleaned_data.get("ds_user") frequency = cleaned_data.get('frequency') callmaxduration = cleaned_data.get('callmaxduration') maxretry = cleaned_data.get('maxretry') calltimeout = cleaned_data.get('calltimeout') dialer_set = user_dialer_setting(User.objects.get(username=ds_user)) if dialer_set: if frequency > dialer_set.max_frequency: msg = _('maximum frequency limit of %d exceeded.' % dialer_set.max_frequency) self._errors['frequency'] = ErrorList([msg]) del self.cleaned_data['frequency'] if callmaxduration > dialer_set.callmaxduration: msg = _('maximum duration limit of %d exceeded.' % dialer_set.callmaxduration) self._errors['callmaxduration'] = ErrorList([msg]) del self.cleaned_data['callmaxduration'] if maxretry > dialer_set.maxretry: msg = _('maximum retries limit of %d exceeded.' % dialer_set.maxretry) self._errors['maxretry'] = ErrorList([msg]) del self.cleaned_data['maxretry'] if calltimeout > dialer_set.max_calltimeout: msg = _('maximum timeout limit of %d exceeded.' % dialer_set.max_calltimeout) self._errors['calltimeout'] = ErrorList([msg]) del self.cleaned_data['calltimeout'] return cleaned_data
def clean(self): cleaned_data = self.cleaned_data ds_user = cleaned_data.get("ds_user") frequency = cleaned_data.get('frequency') callmaxduration = cleaned_data.get('callmaxduration') maxretry = cleaned_data.get('maxretry') calltimeout = cleaned_data.get('calltimeout') dialer_set = user_dialer_setting(ds_user) if dialer_set: if frequency > dialer_set.max_frequency: msg = _('Maximum Frequency limit of %d exceeded.'\ % dialer_set.max_frequency) self._errors['frequency'] = ErrorList([msg]) del self.cleaned_data['frequency'] if callmaxduration > dialer_set.callmaxduration: msg = _('Maximum Duration limit of %d exceeded.'\ % dialer_set.callmaxduration) self._errors['callmaxduration'] = ErrorList([msg]) del self.cleaned_data['callmaxduration'] if maxretry > dialer_set.maxretry: msg = _('Maximum Retries limit of %d exceeded.' \ % dialer_set.maxretry) self._errors['maxretry'] = ErrorList([msg]) del self.cleaned_data['maxretry'] if calltimeout > dialer_set.max_calltimeout: msg = _('Maximum Timeout limit of %d exceeded.'\ % dialer_set.max_calltimeout) self._errors['calltimeout'] = ErrorList([msg]) del self.cleaned_data['calltimeout'] return cleaned_data
def campaign_add(request): """Add a new campaign for the logged in user **Attributes**: * ``form`` - CampaignForm * ``template`` - frontend/campaign/change.html **Logic Description**: * Before adding a campaign, check dialer setting limit if applicable to the user. * Add the new campaign which will belong to the logged in user via CampaignForm & get redirected to campaign list """ # If dialer setting is not attached with user, redirect to campaign list if not user_dialer_setting(request.user): request.session['error_msg'] = \ _("in order to add a campaign, you need to have your settings configured properly, please contact the admin.") return HttpResponseRedirect("/campaign/") # Check dialer setting limit if request.user and request.method != 'POST': # check Max Number of running campaign if check_dialer_setting(request, check_for="campaign"): msg = _("you have too many campaigns. Max allowed %(limit)s") \ % {'limit': dialer_setting_limit(request, limit_for="campaign")} request.session['msg'] = msg # campaign limit reached frontend_send_notification(request, NOTIFICATION_NAME.campaign_limit_reached) return HttpResponseRedirect("/campaign/") form = CampaignForm(request.user) # Add campaign if request.method == 'POST': form = CampaignForm(request.user, request.POST) if form.is_valid(): obj = form.save(commit=False) contenttype = get_content_type(form.cleaned_data['content_object']) obj.content_type = contenttype['object_type'] obj.object_id = contenttype['object_id'] obj.user = request.user obj.save() form.save_m2m() request.session["msg"] = _('"%(name)s" added.') %\ {'name': request.POST['name']} return HttpResponseRedirect('/campaign/') template = 'frontend/campaign/change.html' data = { 'module': current_view(request), 'form': form, 'action': 'add', 'AMD': settings.AMD, } return render_to_response(template, data, context_instance=RequestContext(request))
def clean(self): cleaned_data = self.cleaned_data ds_user = cleaned_data.get("ds_user") frequency = cleaned_data.get("frequency") maxretry = cleaned_data.get("maxretry") phonebook = cleaned_data.get("phonebook") if not phonebook: msg = _("you must select at least one phonebook") self._errors["phonebook"] = ErrorList([msg]) del self.cleaned_data["phonebook"] sms_dialer_set = user_dialer_setting(ds_user) if sms_dialer_set: if frequency > sms_dialer_set.sms_max_frequency: msg = _("Maximum Frequency limit of %d exceeded." % sms_dialer_set.sms_max_frequency) self._errors["frequency"] = ErrorList([msg]) del self.cleaned_data["frequency"] if maxretry > sms_dialer_set.sms_maxretry: msg = _("Maximum Retries limit of %d exceeded." % sms_dialer_set.sms_maxretry) self._errors["maxretry"] = ErrorList([msg]) del self.cleaned_data["maxretry"] return cleaned_data
def sms_campaign_add(request): """Add a new sms campaign for the logged in user **Attributes**: * ``form`` - SMSCampaignForm * ``template`` - frontend/sms_campaign/change.html **Logic Description**: * Before adding a sms campaign, check dialer setting limit if applicable to the user. * Add the new sms campaign which will belong to the logged in user via SMSCampaignForm & get redirected to sms campaign list """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): request.session['error_msg'] = \ _("in order to add a sms campaign, you need to have your \ settings configured properly, please contact the admin.") return HttpResponseRedirect(redirect_url_to_smscampaign_list) # Check dialer setting limit if request.user and request.method != 'POST': # check Max Number of running campaign if check_sms_dialer_setting(request, check_for="smscampaign"): msg = _("you have too many sms campaigns. Max allowed %(limit)s")\ % {'limit': dialer_setting_limit(request, limit_for="smscampaign")} request.session['msg'] = msg # sms campaign limit reached frontend_send_notification( request, SMS_NOTIFICATION_NAME.sms_campaign_limit_reached) return HttpResponseRedirect(redirect_url_to_smscampaign_list) form = SMSCampaignForm(request.user) # Add sms campaign if request.method == 'POST': form = SMSCampaignForm(request.user, request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = User.objects.get(username=request.user) obj.save() form.save_m2m() request.session["msg"] = _('"%(name)s" is added.') %\ {'name': request.POST['name']} return HttpResponseRedirect(redirect_url_to_smscampaign_list) template = 'frontend/sms_campaign/change.html' data = { 'form': form, 'action': 'add', 'dialer_setting_msg': user_dialer_setting_msg(request.user), } return render_to_response( template, data, context_instance=RequestContext(request))
def get_sms_maxretry(sms_campaign): """ If SMS Campaign's maxretry is 0 then we should use SMS Dialer Setting sms_maxretry """ if sms_campaign.maxretry is None or not sms_campaign.maxretry >= 0: sms_dialer_set = user_dialer_setting(sms_campaign.user) maxretry = int(sms_dialer_set.sms_maxretry) else: maxretry = int(sms_campaign.maxretry) return maxretry
def sms_campaign_add(request): """Add a new sms campaign for the logged in user **Attributes**: * ``form`` - SMSCampaignForm * ``template`` - mod_sms/change.html **Logic Description**: * Before adding a sms campaign, check dialer setting limit if applicable to the user. * Add the new sms campaign which will belong to the logged in user via SMSCampaignForm & get redirected to sms campaign list """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): request.session['error_msg'] = \ _("in order to add a sms campaign, you need to have your \ settings configured properly, please contact the admin." ) return HttpResponseRedirect(redirect_url_to_smscampaign_list) # Check dialer setting limit if request.user and request.method != 'POST': # check Max Number of running campaign if check_sms_dialer_setting(request, check_for="smscampaign"): msg = _("you have too many sms campaigns. Max allowed %(limit)s")\ % {'limit': dialer_setting_limit(request, limit_for="smscampaign")} request.session['msg'] = msg # sms campaign limit reached frontend_send_notification( request, SMS_NOTIFICATION_NAME.sms_campaign_limit_reached) return HttpResponseRedirect(redirect_url_to_smscampaign_list) form = SMSCampaignForm(request.user, request.POST or None) # Add sms campaign if form.is_valid(): obj = form.save(commit=False) obj.user = User.objects.get(username=request.user) obj.stoppeddate = obj.expirationdate obj.save() form.save_m2m() request.session["msg"] = _('"%(name)s" is added.') % { 'name': request.POST['name'] } return HttpResponseRedirect(redirect_url_to_smscampaign_list) data = { 'form': form, 'action': 'add', } return render_to_response('mod_sms/change.html', data, context_instance=RequestContext(request))
def run(self, **kwargs): logger = init_call_retry.get_logger() logger.info("TASK :: init_call_retry") try: # get callrequest which are failed callreq_retry_list = Callrequest.objects.filter(status=2, call_type=1) for callreq in callreq_retry_list: try: # Call type => Retry Done = 3 callreq.call_type = 3 callreq.save() campaign_obj = Campaign.objects.get(id=callreq.campaign_id) if campaign_obj: if callreq.num_attempt >= campaign_obj.maxretry: logger.error("Not allowed retry") break dialer_set = user_dialer_setting(callreq.user) if dialer_set: if callreq.num_attempt >= dialer_set.maxretry: logger.error("Not allowed retry") break except: # Call type => Can Not Retry = 2 callreq.call_type = 2 callreq.save() logger.error("Can't find dialer setting for user of the campaign : %s" \ % callreq.campaign_id) break # TODO : Review Logic # Crete new callrequest, Assign parent_callrequest, Change callrequest_type # & num_attempt obj = Callrequest(request_uuid=uuid1(), parent_callrequest_id=callreq.id, call_type=1, num_attempt=callreq.num_attempt+1, user=callreq.user, campaign_id=callreq.campaign_id, aleg_gateway_id=callreq.aleg_gateway_id, content_type=callreq.content_type, object_id=callreq.object_id, phone_number=callreq.phone_number) obj.save() # TODO : perform retry init_callrequest.delay(obj.id, obj.campaign_id) except: logger.error("Can't find failed callrequest") return False return True
def sms_campaign_duplicate(request, id): """ Duplicate sms campaign via DuplicateSMSCampaignForm **Attributes**: * ``id`` - Selected sms campaign object * ``form`` - DuplicateSMSCampaignForm * ``template`` - mod_sms/sms_campaign_duplicate.html """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect(redirect_url_to_smscampaign_list) form = DuplicateSMSCampaignForm(request.user, request.POST or None) request.session['error_msg'] = '' if request.method == 'POST': if form.is_valid(): sms_campaign_obj = SMSCampaign.objects.get(pk=id) sms_campaign_obj.pk = None sms_campaign_obj.campaign_code = request.POST.get('campaign_code') sms_campaign_obj.name = request.POST.get('name') sms_campaign_obj.status = SMS_CAMPAIGN_STATUS.PAUSE sms_campaign_obj.startingdate = datetime.utcnow().replace( tzinfo=utc) sms_campaign_obj.expirationdate = datetime.utcnow().replace( tzinfo=utc) + relativedelta(days=+1) sms_campaign_obj.stoppeddate = datetime.utcnow().replace( tzinfo=utc) + relativedelta(days=+1) sms_campaign_obj.imported_phonebook = '' sms_campaign_obj.totalcontact = 0 sms_campaign_obj.save() # Many to many field for pb in request.POST.getlist('phonebook'): sms_campaign_obj.phonebook.add(pb) return HttpResponseRedirect(redirect_url_to_smscampaign_list) else: request.session['error_msg'] = True data = { 'sms_campaign_id': id, 'form': form, 'err_msg': request.session.get('error_msg'), } request.session['error_msg'] = '' return render_to_response('mod_sms/sms_campaign_duplicate.html', data, context_instance=RequestContext(request))
def sms_campaign_duplicate(request, id): """ Duplicate sms campaign via DuplicateSMSCampaignForm **Attributes**: * ``id`` - Selected sms campaign object * ``form`` - DuplicateSMSCampaignForm * ``template`` - frontend/sms_campaign/sms_campaign_duplicate.html """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect(redirect_url_to_smscampaign_list) form = DuplicateSMSCampaignForm(request.user) request.session['error_msg'] = '' if request.method == 'POST': form = DuplicateSMSCampaignForm(request.user, request.POST) if form.is_valid(): sms_campaign_obj = SMSCampaign.objects.get(pk=id) sms_campaign_obj.pk = None sms_campaign_obj.campaign_code = request.POST.get('campaign_code') sms_campaign_obj.name = request.POST.get('name') sms_campaign_obj.status = SMS_CAMPAIGN_STATUS.PAUSE sms_campaign_obj.startingdate = datetime.utcnow().replace(tzinfo=utc) sms_campaign_obj.expirationdate = datetime.utcnow().replace(tzinfo=utc) + relativedelta(days=+1) sms_campaign_obj.imported_phonebook = '' sms_campaign_obj.totalcontact = 0 sms_campaign_obj.save() # Many to many field for pb in request.POST.getlist('phonebook'): sms_campaign_obj.phonebook.add(pb) return HttpResponseRedirect(redirect_url_to_smscampaign_list) else: request.session['error_msg'] = True else: request.session['error_msg'] = '' template = 'frontend/sms_campaign/sms_campaign_duplicate.html' data = { 'sms_campaign_id': id, 'form': form, 'err_msg': request.session.get('error_msg'), } request.session['error_msg'] = '' return render_to_response( template, data, context_instance=RequestContext(request))
def sms_campaign_change(request, object_id): """Update/Delete sms campaign for the logged in user **Attributes**: * ``object_id`` - Selected campaign object * ``form`` - SMSCampaignForm * ``template`` - frontend/sms_campaign/change.html **Logic Description**: * Update/delete selected sms campaign from the sms campaign list via SMSCampaignForm & get redirected to the sms campaign list """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect(redirect_url_to_smscampaign_list) sms_campaign = get_object_or_404(SMSCampaign, pk=object_id, user=request.user) form = SMSCampaignForm(request.user, instance=sms_campaign) if request.method == 'POST': # Delete sms campaign if request.POST.get('delete'): sms_campaign_del(request, object_id) return HttpResponseRedirect(redirect_url_to_smscampaign_list) else: # Update sms campaign form = SMSCampaignForm( request.user, request.POST, instance=sms_campaign) if form.is_valid(): obj = form.save() obj.save() request.session["msg"] = _('"%(name)s" is updated.') \ % {'name': request.POST['name']} return HttpResponseRedirect(redirect_url_to_smscampaign_list) template = 'frontend/sms_campaign/change.html' data = { 'form': form, 'action': 'update', 'dialer_setting_msg': user_dialer_setting_msg(request.user), } return render_to_response( template, data, context_instance=RequestContext(request))
def sms_campaign_change(request, object_id): """Update/Delete sms campaign for the logged in user **Attributes**: * ``object_id`` - Selected campaign object * ``form`` - SMSCampaignForm * ``template`` - mod_sms/change.html **Logic Description**: * Update/delete selected sms campaign from the sms campaign list via SMSCampaignForm & get redirected to the sms campaign list """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect(redirect_url_to_smscampaign_list) sms_campaign = get_object_or_404(SMSCampaign, pk=object_id, user=request.user) form = SMSCampaignForm(request.user, request.POST or None, instance=sms_campaign) if form.is_valid(): # Delete sms campaign if request.POST.get('delete'): sms_campaign_del(request, object_id) return HttpResponseRedirect(redirect_url_to_smscampaign_list) else: # Update sms campaign obj = form.save() obj.save() request.session["msg"] = _('"%(name)s" is updated.') % { 'name': request.POST['name'] } return HttpResponseRedirect(redirect_url_to_smscampaign_list) data = { 'form': form, 'action': 'update', } return render_to_response('mod_sms/change.html', data, context_instance=RequestContext(request))
def validate(self, attrs): """ Validate campaign form """ request = self.context['request'] if request.method == 'POST': name_count = Campaign.objects.filter(name=attrs.get('name'), user=request.user).count() if name_count != 0: raise serializers.ValidationError("The Campaign name duplicated!") if not user_dialer_setting(request.user): raise serializers.ValidationError("Your system settings are not configured properly.") if check_dialer_setting(request, check_for="campaign"): raise serializers.ValidationError("Too many campaigns. Max allowed %s" % dialer_setting_limit(request, limit_for="campaign")) frequency = attrs.get('frequency') if frequency: if check_dialer_setting(request, check_for="frequency", field_value=int(frequency)): raise serializers.ValidationError("Frequency limit of %s exceeded." % dialer_setting_limit(request, limit_for="frequency")) callmaxduration = attrs.get('callmaxduration') if callmaxduration: if check_dialer_setting(request, check_for="duration", field_value=int(callmaxduration)): raise serializers.ValidationError("Duration limit of %s exceeded." % dialer_setting_limit(request, limit_for="duration")) maxretry = attrs.get('maxretry') if maxretry: if check_dialer_setting(request, check_for="retry", field_value=int(maxretry)): raise serializers.ValidationError("Retries limit of %s exceeded." % dialer_setting_limit(request, limit_for="retry")) calltimeout = attrs.get('calltimeout') if calltimeout: if check_dialer_setting(request, check_for="timeout", field_value=int(calltimeout)): raise serializers.ValidationError("Timeout limit of %s exceeded." % dialer_setting_limit(request, limit_for="timeout")) return attrs
def sms_campaign_text_message(request, object_id): """ Get sms campaign's text message **Attributes**: * ``object_id`` - Selected sms campaign object * ``template`` - mod_sms/sms_campaign_text_message.html """ # If dialer setting is not attached with user, redirect to sms campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect(redirect_url_to_smscampaign_list) sms_campaign = get_object_or_404(SMSCampaign, pk=object_id, user=request.user) data = { 'sms_campaign': sms_campaign, } request.session['error_msg'] = '' return render_to_response('mod_sms/sms_campaign_text_message.html', data, context_instance=RequestContext(request))
def clean(self): cleaned_data = self.cleaned_data frequency = cleaned_data.get('frequency') callmaxduration = cleaned_data.get('callmaxduration') maxretry = cleaned_data.get('maxretry') calltimeout = cleaned_data.get('calltimeout') phonebook = cleaned_data.get('phonebook') if not phonebook: msg = _('you must select at least one phonebook') self._errors['phonebook'] = ErrorList([msg]) del self.cleaned_data['phonebook'] dialer_set = user_dialer_setting(self.user) if dialer_set: if frequency > dialer_set.max_frequency: msg = _('maximum frequency limit of %d exceeded.' % dialer_set.max_frequency) self._errors['frequency'] = ErrorList([msg]) del self.cleaned_data['frequency'] if callmaxduration > dialer_set.callmaxduration: msg = _('maximum duration limit of %d exceeded.' % dialer_set.callmaxduration) self._errors['callmaxduration'] = ErrorList([msg]) del self.cleaned_data['callmaxduration'] if maxretry > dialer_set.maxretry: msg = _('maximum retries limit of %d exceeded.' % dialer_set.maxretry) self._errors['maxretry'] = ErrorList([msg]) del self.cleaned_data['maxretry'] if calltimeout > dialer_set.max_calltimeout: msg = _('maximum timeout limit of %d exceeded.' % dialer_set.max_calltimeout) self._errors['calltimeout'] = ErrorList([msg]) del self.cleaned_data['calltimeout'] return cleaned_data
def is_valid(self, bundle, request=None): errors = {} if not bundle.data: return {'__all__': 'Please enter data'} startingdate = bundle.data.get('startingdate') expirationdate = bundle.data.get('expirationdate') if bundle.request.method == 'POST': startingdate = get_value_if_none(startingdate, time.time()) # expires in 90 days expirationdate = get_value_if_none(expirationdate, time.time() + 86400 * 90) #Startdate and expirationdate are UTC -> convert to localtime startingdate = float(startingdate) - time.altzone expirationdate = float(expirationdate) - time.altzone bundle.data['startingdate'] = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(startingdate)) bundle.data['expirationdate'] = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(expirationdate)) if bundle.request.method == 'PUT': if startingdate: bundle.data['startingdate'] = time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate))) if expirationdate: bundle.data['expirationdate'] = time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate))) if not user_dialer_setting(bundle.request.user): errors['user_dialer_setting'] = ['Your settings are not configured properly, Please contact the administrator.'] if check_dialer_setting(request, check_for="campaign"): errors['chk_campaign'] = ["Too many campaigns. Max allowed %s" % dialer_setting_limit(bundle.request, limit_for="campaign")] frequency = bundle.data.get('frequency') if frequency: if check_dialer_setting(bundle.request, check_for="frequency", field_value=int(frequency)): errors['chk_frequency'] = ["Frequency limit of %s exceeded." % dialer_setting_limit(request, limit_for="frequency")] callmaxduration = bundle.data.get('callmaxduration') if callmaxduration: if check_dialer_setting(bundle.request, check_for="duration", field_value=int(callmaxduration)): errors['chk_duration'] = ["Duration limit of %s exceeded." % dialer_setting_limit(bundle.request, limit_for="duration")] maxretry = bundle.data.get('maxretry') if maxretry: if check_dialer_setting(bundle.request, check_for="retry", field_value=int(maxretry)): errors['chk_duration'] = ["Retries limit of %s exceeded." % dialer_setting_limit(bundle.request, limit_for="retry")] calltimeout = bundle.data.get('calltimeout') if calltimeout: if check_dialer_setting(request, check_for="timeout", field_value=int(calltimeout)): errors['chk_timeout'] = ["Timeout limit of %s exceeded." % dialer_setting_limit(request, limit_for="timeout")] aleg_gateway_id = bundle.data.get('aleg_gateway') if aleg_gateway_id: try: Gateway.objects.get(id=aleg_gateway_id) bundle.data['aleg_gateway'] = '/api/v1/gateway/%s/' % aleg_gateway_id except: errors['chk_gateway'] = ["The Gateway ID doesn't exist!"] content_type = bundle.data.get('content_type') if content_type == 'survey_template': try: content_type_id = ContentType.objects.get(model=str(content_type)).id bundle.data['content_type'] = '/api/v1/contenttype/%s/' % content_type_id except: errors['chk_content_type'] = ["The ContentType doesn't exist!"] else: errors['chk_content_type'] = ["Entered wrong option. Please enter 'survey_template' !"] object_id = bundle.data.get('object_id') if object_id: try: bundle.data['object_id'] = int(object_id) except: errors['chk_object_id'] = ["object_id must be digit"] else: errors['chk_object_id'] = ["App Object ID doesn't exist!"] if bundle.request.method == 'POST': name_count = Campaign.objects.filter(name=bundle.data.get('name'), user=bundle.request.user).count() if (name_count != 0): errors['chk_campaign_name'] = ["The Campaign name duplicated!"] # Voicemail setting is not enabled by default if settings.AMD: voicemail = bundle.data.get('voicemail') if voicemail: bundle.data['voicemail'] = voicemail amd_behavior = bundle.data.get('amd_behavior') audiofile_id = bundle.data.get('voicemail_audiofile') if audiofile_id: try: AudioFile.objects.get(id=audiofile_id) bundle.data['voicemail_audiofile'] = '/api/v1/audiofile/%s/' % audiofile_id except: errors['voicemail_audiofile'] = ["The audiofile ID doesn't exist!"] else: errors['voicemail'] = ["voicemail not enabled!"] if errors: raise BadRequest(errors) return errors
def campaign_add(request): """Add a new campaign for the logged in user **Attributes**: * ``form`` - CampaignForm * ``template`` - frontend/campaign/change.html **Logic Description**: * Before adding a campaign, check dialer setting limit if applicable to the user. * Add the new campaign which will belong to the logged in user via CampaignForm & get redirected to campaign list """ # If dialer setting is not attached with user, redirect to campaign list if not user_dialer_setting(request.user): request.session['error_msg'] = \ _("in order to add a campaign, you need to have your settings configured properly, please contact the admin.") return HttpResponseRedirect("/campaign/") # Check dialer setting limit if request.user and request.method != 'POST': # check Max Number of running campaign if check_dialer_setting(request, check_for="campaign"): msg = _("you have too many campaigns. Max allowed %(limit)s") \ % {'limit': dialer_setting_limit(request, limit_for="campaign")} request.session['msg'] = msg # campaign limit reached frontend_send_notification( request, NOTIFICATION_NAME.campaign_limit_reached) return HttpResponseRedirect("/campaign/") form = CampaignForm(request.user) # Add campaign if request.method == 'POST': form = CampaignForm(request.user, request.POST) if form.is_valid(): obj = form.save(commit=False) contenttype = get_content_type(form.cleaned_data['content_object']) obj.content_type = contenttype['object_type'] obj.object_id = contenttype['object_id'] obj.user = request.user obj.save() form.save_m2m() request.session["msg"] = _('"%(name)s" added.') %\ {'name': request.POST['name']} return HttpResponseRedirect('/campaign/') template = 'frontend/campaign/change.html' data = { 'module': current_view(request), 'form': form, 'action': 'add', 'AMD': settings.AMD, } return render_to_response(template, data, context_instance=RequestContext(request))
def campaign_change(request, object_id): """Update/Delete campaign for the logged in user **Attributes**: * ``object_id`` - Selected campaign object * ``form`` - CampaignForm * ``template`` - frontend/campaign/change.html **Logic Description**: * Update/delete selected campaign from the campaign list via CampaignForm & get redirected to the campaign list """ # If dialer setting is not attached with user, redirect to campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect("/campaign/") campaign = get_object_or_404(Campaign, pk=object_id, user=request.user) content_object = "type:%s-id:%s" % \ (campaign.content_type_id, campaign.object_id) form = CampaignForm(request.user, instance=campaign, initial={'content_object': content_object}) if campaign.status == CAMPAIGN_STATUS.START: request.session['info_msg'] =\ _('the campaign is started, you can only edit Dialer settings and Campaign schedule') if request.method == 'POST': # Delete campaign if request.POST.get('delete'): return HttpResponseRedirect('/campaign/del/%s/' % object_id) else: # Update campaign form = CampaignForm(request.user, request.POST, instance=campaign) if form.is_valid(): form.save() obj = form.save(commit=False) selected_content_object = form.cleaned_data['content_object'] if not selected_content_object: selected_content_object = form.cleaned_data[ 'selected_content_object'] # while campaign status is running if campaign.status == CAMPAIGN_STATUS.START: if request.POST.get('selected_phonebook'): selected_phonebook = str(request.POST.get('selected_phonebook'))\ .split(',') obj.phonebook = Phonebook.objects\ .filter(id__in=selected_phonebook) contenttype = get_content_type(selected_content_object) obj.content_type = contenttype['object_type'] obj.object_id = contenttype['object_id'] obj.save() request.session["msg"] = _('"%(name)s" is updated.') \ % {'name': request.POST['name']} request.session['error_msg'] = '' return HttpResponseRedirect('/campaign/') template = 'frontend/campaign/change.html' data = { 'module': current_view(request), 'form': form, 'action': 'update', 'error_msg': request.session.get('error_msg'), 'info_msg': request.session.get('info_msg'), 'AMD': settings.AMD, } request.session['error_msg'] = '' request.session['info_msg'] = '' return render_to_response(template, data, context_instance=RequestContext(request))
def campaign_change(request, object_id): """Update/Delete campaign for the logged in user **Attributes**: * ``object_id`` - Selected campaign object * ``form`` - CampaignForm * ``template`` - frontend/campaign/change.html **Logic Description**: * Update/delete selected campaign from the campaign list via CampaignForm & get redirected to the campaign list """ # If dialer setting is not attached with user, redirect to campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect("/campaign/") campaign = get_object_or_404(Campaign, pk=object_id, user=request.user) content_object = "type:%s-id:%s" % \ (campaign.content_type_id, campaign.object_id) form = CampaignForm(request.user, instance=campaign, initial={'content_object': content_object}) if campaign.status == CAMPAIGN_STATUS.START: request.session['info_msg'] =\ _('the campaign is started, you can only edit Dialer settings and Campaign schedule') if request.method == 'POST': # Delete campaign if request.POST.get('delete'): return HttpResponseRedirect('/campaign/del/%s/' % object_id) else: # Update campaign form = CampaignForm(request.user, request.POST, instance=campaign) if form.is_valid(): form.save() obj = form.save(commit=False) selected_content_object = form.cleaned_data['content_object'] if not selected_content_object: selected_content_object = form.cleaned_data['selected_content_object'] # while campaign status is running if campaign.status == CAMPAIGN_STATUS.START: if request.POST.get('selected_phonebook'): selected_phonebook = str(request.POST.get('selected_phonebook'))\ .split(',') obj.phonebook = Phonebook.objects\ .filter(id__in=selected_phonebook) contenttype = get_content_type(selected_content_object) obj.content_type = contenttype['object_type'] obj.object_id = contenttype['object_id'] obj.save() request.session["msg"] = _('"%(name)s" is updated.') \ % {'name': request.POST['name']} request.session['error_msg'] = '' return HttpResponseRedirect('/campaign/') template = 'frontend/campaign/change.html' data = { 'module': current_view(request), 'form': form, 'action': 'update', 'error_msg': request.session.get('error_msg'), 'info_msg': request.session.get('info_msg'), 'AMD': settings.AMD, } request.session['error_msg'] = '' request.session['info_msg'] = '' return render_to_response(template, data, context_instance=RequestContext(request))
def check_campaign_pendingcall(campaign_id): """This will execute the outbound calls in the campaign **Attributes**: * ``campaign_id`` - Campaign ID """ logger = check_campaign_pendingcall.get_logger() logger.info("TASK :: check_campaign_pendingcall = %s" % str(campaign_id)) try: obj_campaign = Campaign.objects.get(id=campaign_id) except: logger.error('Can\'t find this campaign') return False #TODO: Control the Speed #if there is many task pending we should slow down frequency = obj_campaign.frequency # default 10 calls per minutes dialer_set = user_dialer_setting(obj_campaign.user) # default call_type call_type = 1 # Check campaign's maxretry if obj_campaign.maxretry == 0: call_type = 2 # Check user's dialer setting maxretry if dialer_set: if dialer_set.maxretry == 0: call_type = 2 # check frequency to control the Speed #if dialer_set.frequency: # frequency = 20 #Speed #check if the other tasks send for this campaign finished to be ran #Get the subscriber of this campaign # get_pending_subscriber get Max 1000 records list_subscriber = obj_campaign.get_pending_subscriber_update( frequency, 6 # Update to In Process ) if list_subscriber: logger.debug("Number of subscriber found : %d" % len(list_subscriber)) try: no_subscriber = list_subscriber.count() except AttributeError: no_subscriber = 0 if no_subscriber == 0: logger.info("No Subscriber to proceed on this campaign") return False #find how to dispatch them in the current minutes time_to_wait = 60.0 / no_subscriber count = 0 for elem_camp_subscriber in list_subscriber: """Loop on Subscriber and start the initcall task""" count = count + 1 logger.info("Add CallRequest for Subscriber (%s) & wait (%s) " % (str(elem_camp_subscriber.id), str(time_to_wait))) #Check if the contact is authorized if not obj_campaign.is_authorized_contact( elem_camp_subscriber.contact.contact): logger.error("Error : Contact not authorized") elem_camp_subscriber.status = 7 # Update to Not Authorized elem_camp_subscriber.save() return True #Create a Callrequest Instance to track the call task new_callrequest = Callrequest(status=1, # PENDING call_type=call_type, call_time=datetime.now(), timeout=obj_campaign.calltimeout, callerid=obj_campaign.callerid, phone_number=elem_camp_subscriber.contact.contact, campaign=obj_campaign, aleg_gateway=obj_campaign.aleg_gateway, content_type=obj_campaign.content_type, object_id=obj_campaign.object_id, user=obj_campaign.user, extra_data=obj_campaign.extra_data, timelimit=obj_campaign.callmaxduration, campaign_subscriber=elem_camp_subscriber) new_callrequest.save() #Todo Check if it's a good practice / implement a PID algorithm second_towait = ceil(count * time_to_wait) launch_date = datetime.now() + timedelta(seconds=second_towait) logger.info("Init CallRequest at %s" % \ (launch_date.strftime("%b %d %Y %I:%M:%S"))) init_callrequest.apply_async( args=[new_callrequest.id, obj_campaign.id], eta=launch_date)
def create(self, request=None, **kwargs): """POST method of Hangupcall API""" logger.debug('Hangupcall API authentication called!') auth_result = self._meta.authentication.is_authenticated(request) if not auth_result is True: raise ImmediateHttpResponse(response=http.HttpUnauthorized()) auth_result = self._meta.authorization.is_authorized(request, object) errors = self._meta.validation.is_valid(request) if not errors: opt_request_uuid = request.POST.get('RequestUUID') opt_hangup_cause = request.POST.get('HangupCause') try: callrequest = Callrequest.objects.get( request_uuid=opt_request_uuid) except: logger.debug('Hangupcall Error cannot find the Callrequest!') try: obj_subscriber = CampaignSubscriber.objects.get( id=callrequest.campaign_subscriber.id) if opt_hangup_cause == 'NORMAL_CLEARING': obj_subscriber.status = 5 # Complete else: obj_subscriber.status = 4 # Fail obj_subscriber.save() except: logger.debug('Hangupcall Error cannot find the ' 'Campaignsubscriber!') # 2 / FAILURE ; 3 / RETRY ; 4 / SUCCESS if opt_hangup_cause == 'NORMAL_CLEARING': callrequest.status = 4 # Success else: callrequest.status = 2 # Failure callrequest.hangup_cause = opt_hangup_cause #save callrequest & campaignsubscriber callrequest.save() data = {} for element in CDR_VARIABLES: if not request.POST.get('variable_%s' % element): data[element] = None else: data[element] = request.POST.get('variable_%s' % element) from_plivo = request.POST.get('From') to_plivo = request.POST.get('To') create_voipcall(obj_callrequest=callrequest, plivo_request_uuid=opt_request_uuid, data=data, data_prefix='', leg='a', hangup_cause=opt_hangup_cause, from_plivo=from_plivo, to_plivo=to_plivo) object_list = [{'result': 'OK'}] logger.debug('Hangupcall API : Result 200!') obj = CustomXmlEmitter() #We will manage the retry directly from the API if opt_hangup_cause != 'NORMAL_CLEARING'\ and callrequest.call_type == 1: # Allow retry #Update to Retry Done callrequest.call_type = 3 callrequest.save() dialer_set = user_dialer_setting(callrequest.user) if callrequest.num_attempt >= callrequest.campaign.maxretry\ or callrequest.num_attempt >= dialer_set.maxretry: logger.error("Not allowed retry - Maxretry (%d)" %\ callrequest.campaign.maxretry) else: #Allowed Retry # TODO : Review Logic # Create new callrequest, Assign parent_callrequest, # Change callrequest_type & num_attempt new_callrequest = Callrequest( request_uuid=uuid1(), parent_callrequest_id=callrequest.id, call_type=1, num_attempt=callrequest.num_attempt + 1, user=callrequest.user, campaign_id=callrequest.campaign_id, aleg_gateway_id=callrequest.aleg_gateway_id, content_type=callrequest.content_type, object_id=callrequest.object_id, phone_number=callrequest.phone_number) new_callrequest.save() #Todo Check if it's a good practice #implement a PID algorithm second_towait = callrequest.campaign.intervalretry launch_date = datetime.now() + \ timedelta(seconds=second_towait) logger.info("Init Retry CallRequest at %s" %\ (launch_date.strftime("%b %d %Y %I:%M:%S"))) init_callrequest.apply_async( args=[new_callrequest.id, callrequest.campaign.id], eta=launch_date) return self.create_response(request, obj.render(request, object_list)) else: if len(errors): if request: desired_format = self.determine_format(request) else: desired_format = self._meta.default_format serialized = self.serialize(request, errors, desired_format) response = http.HttpBadRequest(content=serialized, content_type=desired_format) raise ImmediateHttpResponse(response=response)
def campaign_change(request, object_id): """Update/Delete campaign for the logged in user **Attributes**: * ``object_id`` - Selected campaign object * ``form`` - CampaignForm * ``template`` - frontend/campaign/change.html **Logic Description**: * Update/delete selected campaign from the campaign list via CampaignForm & get redirected to the campaign list """ # If dialer setting is not attached with user, redirect to campaign list if not user_dialer_setting(request.user): return HttpResponseRedirect("/campaign/") campaign = get_object_or_404(Campaign, pk=object_id, user=request.user) content_object = "type:%s-id:%s" % (campaign.content_type_id, campaign.object_id) form = CampaignForm(request.user, instance=campaign, initial={"content_object": content_object}) if campaign.status == CAMPAIGN_STATUS.START: request.session["info_msg"] = _( "the campaign is started, you can only edit Dialer settings and Campaign schedule" ) if request.method == "POST": # Delete campaign if request.POST.get("delete"): return HttpResponseRedirect("/campaign/del/%s/" % object_id) else: # Update campaign form = CampaignForm(request.user, request.POST, instance=campaign) if form.is_valid(): form.save() obj = form.save(commit=False) selected_content_object = form.cleaned_data["content_object"] if not selected_content_object: selected_content_object = form.cleaned_data["selected_content_object"] # while campaign status is running if campaign.status == CAMPAIGN_STATUS.START: if request.POST.get("selected_phonebook"): selected_phonebook = str(request.POST.get("selected_phonebook")).split(",") obj.phonebook = Phonebook.objects.filter(id__in=selected_phonebook) contenttype = get_content_type(selected_content_object) obj.content_type = contenttype["object_type"] obj.object_id = contenttype["object_id"] obj.save() request.session["msg"] = _('the campaign "%(name)s" is updated.') % {"name": request.POST["name"]} request.session["error_msg"] = "" return HttpResponseRedirect("/campaign/") template = "frontend/campaign/change.html" data = { "form": form, "action": "update", "error_msg": request.session.get("error_msg"), "info_msg": request.session.get("info_msg"), "AMD": settings.AMD, } request.session["error_msg"] = "" request.session["info_msg"] = "" return render_to_response(template, data, context_instance=RequestContext(request))
def check_campaign_pendingcall(campaign_id): """This will execute the outbound calls in the campaign **Attributes**: * ``campaign_id`` - Campaign ID """ logger = check_campaign_pendingcall.get_logger() logger.info("TASK :: check_campaign_pendingcall = %s" % str(campaign_id)) try: obj_campaign = Campaign.objects.get(id=campaign_id) except: logger.error('Can\'t find this campaign') return False #TODO: Control the Speed #if there is many task pending we should slow down frequency = obj_campaign.frequency # default 10 calls per minutes dialer_set = user_dialer_setting(obj_campaign.user) # default call_type call_type = 1 # Check campaign's maxretry if obj_campaign.maxretry == 0: call_type = 2 # Check user's dialer setting maxretry if dialer_set: if dialer_set.maxretry == 0: call_type = 2 # check frequency to control the Speed #if dialer_set.frequency: # frequency = 20 #Speed #check if the other tasks send for this campaign finished to be ran #Get the subscriber of this campaign # get_pending_subscriber get Max 1000 records list_subscriber = obj_campaign.get_pending_subscriber_update( frequency, 6 # Update to In Process ) if list_subscriber: logger.debug("Number of subscriber found : %d" % len(list_subscriber)) try: no_subscriber = list_subscriber.count() except AttributeError: no_subscriber = 0 if no_subscriber == 0: logger.info("No Subscriber to proceed on this campaign") return False #find how to dispatch them in the current minutes time_to_wait = 60.0 / no_subscriber count = 0 for elem_camp_subscriber in list_subscriber: """Loop on Subscriber and start the initcall task""" count = count + 1 logger.info("Add CallRequest for Subscriber (%s) & wait (%s) " % (str(elem_camp_subscriber.id), str(time_to_wait))) #Check if the contact is authorized if not obj_campaign.is_authorized_contact( elem_camp_subscriber.contact.contact): logger.error("Error : Contact not authorized") elem_camp_subscriber.status = 7 # Update to Not Authorized elem_camp_subscriber.save() return True #Create a Callrequest Instance to track the call task new_callrequest = Callrequest( status=1, # PENDING call_type=call_type, call_time=datetime.now(), timeout=obj_campaign.calltimeout, callerid=obj_campaign.callerid, phone_number=elem_camp_subscriber.contact.contact, campaign=obj_campaign, aleg_gateway=obj_campaign.aleg_gateway, content_type=obj_campaign.content_type, object_id=obj_campaign.object_id, user=obj_campaign.user, extra_data=obj_campaign.extra_data, timelimit=obj_campaign.callmaxduration, campaign_subscriber=elem_camp_subscriber) new_callrequest.save() #Todo Check if it's a good practice / implement a PID algorithm second_towait = ceil(count * time_to_wait) launch_date = datetime.now() + timedelta(seconds=second_towait) logger.info("Init CallRequest at %s" % \ (launch_date.strftime("%b %d %Y %I:%M:%S"))) init_callrequest.apply_async( args=[new_callrequest.id, obj_campaign.id], eta=launch_date)
def is_valid(self, bundle, request=None): errors = {} if not bundle.data: return {'__all__': 'Please enter data'} startingdate = bundle.data.get('startingdate') expirationdate = bundle.data.get('expirationdate') if bundle.request.method == 'POST': startingdate = get_value_if_none(startingdate, time.time()) # expires in 90 days expirationdate = get_value_if_none(expirationdate, time.time() + 86400 * 90) #Startdate and expirationdate are UTC -> convert to localtime startingdate = float(startingdate) - time.altzone expirationdate = float(expirationdate) - time.altzone bundle.data['startingdate'] = time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime(startingdate)) bundle.data['expirationdate'] = time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime(expirationdate)) if bundle.request.method == 'PUT': if startingdate: bundle.data['startingdate'] = time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate))) if expirationdate: bundle.data['expirationdate'] = time.strftime( '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate))) if not user_dialer_setting(bundle.request.user): errors['user_dialer_setting'] = [ 'Your settings are not configured properly, Please contact the administrator.' ] if check_dialer_setting(request, check_for="campaign"): errors['chk_campaign'] = [ "Too many campaigns. Max allowed %s" % dialer_setting_limit(bundle.request, limit_for="campaign") ] frequency = bundle.data.get('frequency') if frequency: if check_dialer_setting(bundle.request, check_for="frequency", field_value=int(frequency)): errors['chk_frequency'] = [ "Frequency limit of %s exceeded." % dialer_setting_limit(request, limit_for="frequency") ] callmaxduration = bundle.data.get('callmaxduration') if callmaxduration: if check_dialer_setting(bundle.request, check_for="duration", field_value=int(callmaxduration)): errors['chk_duration'] = [ "Duration limit of %s exceeded." % dialer_setting_limit(bundle.request, limit_for="duration") ] maxretry = bundle.data.get('maxretry') if maxretry: if check_dialer_setting(bundle.request, check_for="retry", field_value=int(maxretry)): errors['chk_duration'] = [ "Retries limit of %s exceeded." % dialer_setting_limit(bundle.request, limit_for="retry") ] calltimeout = bundle.data.get('calltimeout') if calltimeout: if check_dialer_setting(request, check_for="timeout", field_value=int(calltimeout)): errors['chk_timeout'] = [ "Timeout limit of %s exceeded." % dialer_setting_limit(request, limit_for="timeout") ] aleg_gateway_id = bundle.data.get('aleg_gateway') if aleg_gateway_id: try: Gateway.objects.get(id=aleg_gateway_id) bundle.data[ 'aleg_gateway'] = '/api/v1/gateway/%s/' % aleg_gateway_id except: errors['chk_gateway'] = ["The Gateway ID doesn't exist!"] content_type = bundle.data.get('content_type') if content_type == 'survey_template': try: content_type_id = ContentType.objects.get( model=str(content_type)).id bundle.data[ 'content_type'] = '/api/v1/contenttype/%s/' % content_type_id except: errors['chk_content_type'] = ["The ContentType doesn't exist!"] else: errors['chk_content_type'] = [ "Entered wrong option. Please enter 'survey_template' !" ] object_id = bundle.data.get('object_id') if object_id: try: bundle.data['object_id'] = int(object_id) except: errors['chk_object_id'] = ["object_id must be digit"] else: errors['chk_object_id'] = ["App Object ID doesn't exist!"] if bundle.request.method == 'POST': name_count = Campaign.objects.filter( name=bundle.data.get('name'), user=bundle.request.user).count() if (name_count != 0): errors['chk_campaign_name'] = ["The Campaign name duplicated!"] # Voicemail setting is not enabled by default if settings.AMD: voicemail = bundle.data.get('voicemail') if voicemail: bundle.data['voicemail'] = voicemail amd_behavior = bundle.data.get('amd_behavior') audiofile_id = bundle.data.get('voicemail_audiofile') if audiofile_id: try: AudioFile.objects.get(id=audiofile_id) bundle.data[ 'voicemail_audiofile'] = '/api/v1/audiofile/%s/' % audiofile_id except: errors['voicemail_audiofile'] = [ "The audiofile ID doesn't exist!" ] else: errors['voicemail'] = ["voicemail not enabled!"] if errors: raise BadRequest(errors) return errors
def create(self, request=None, **kwargs): """POST method of Hangupcall API""" logger.debug('Hangupcall API authentication called!') auth_result = self._meta.authentication.is_authenticated(request) if not auth_result is True: raise ImmediateHttpResponse(response=http.HttpUnauthorized()) auth_result = self._meta.authorization.is_authorized(request, object) errors = self._meta.validation.is_valid(request) if not errors: opt_request_uuid = request.POST.get('RequestUUID') opt_hangup_cause = request.POST.get('HangupCause') try: callrequest = Callrequest.objects.get( request_uuid=opt_request_uuid) except: logger.debug('Hangupcall Error cannot find the Callrequest!') try: obj_subscriber = CampaignSubscriber.objects.get( id=callrequest.campaign_subscriber.id) if opt_hangup_cause == 'NORMAL_CLEARING': obj_subscriber.status = 5 # Complete else: obj_subscriber.status = 4 # Fail obj_subscriber.save() except: logger.debug('Hangupcall Error cannot find the ' 'Campaignsubscriber!') # 2 / FAILURE ; 3 / RETRY ; 4 / SUCCESS if opt_hangup_cause == 'NORMAL_CLEARING': callrequest.status = 4 # Success else: callrequest.status = 2 # Failure callrequest.hangup_cause = opt_hangup_cause #save callrequest & campaignsubscriber callrequest.save() data = {} for element in CDR_VARIABLES: if not request.POST.get('variable_%s' % element): data[element] = None else: data[element] = request.POST.get('variable_%s' % element) from_plivo = request.POST.get('From') to_plivo = request.POST.get('To') create_voipcall(obj_callrequest=callrequest, plivo_request_uuid=opt_request_uuid, data=data, data_prefix='', leg='a', hangup_cause=opt_hangup_cause, from_plivo=from_plivo, to_plivo=to_plivo) object_list = [{'result': 'OK'}] logger.debug('Hangupcall API : Result 200!') obj = CustomXmlEmitter() #We will manage the retry directly from the API if opt_hangup_cause != 'NORMAL_CLEARING'\ and callrequest.call_type == 1: # Allow retry #Update to Retry Done callrequest.call_type = 3 callrequest.save() dialer_set = user_dialer_setting(callrequest.user) if callrequest.num_attempt >= callrequest.campaign.maxretry\ or callrequest.num_attempt >= dialer_set.maxretry: logger.error("Not allowed retry - Maxretry (%d)" %\ callrequest.campaign.maxretry) else: #Allowed Retry # TODO : Review Logic # Create new callrequest, Assign parent_callrequest, # Change callrequest_type & num_attempt new_callrequest = Callrequest( request_uuid=uuid1(), parent_callrequest_id=callrequest.id, call_type=1, num_attempt=callrequest.num_attempt + 1, user=callrequest.user, campaign_id=callrequest.campaign_id, aleg_gateway_id=callrequest.aleg_gateway_id, content_type=callrequest.content_type, object_id=callrequest.object_id, phone_number=callrequest.phone_number) new_callrequest.save() #Todo Check if it's a good practice #implement a PID algorithm second_towait = callrequest.campaign.intervalretry launch_date = datetime.now() + \ timedelta(seconds=second_towait) logger.info("Init Retry CallRequest at %s" %\ (launch_date.strftime("%b %d %Y %I:%M:%S"))) init_callrequest.apply_async( args=[new_callrequest.id, callrequest.campaign.id], eta=launch_date) return self.create_response(request, obj.render(request, object_list)) else: if len(errors): if request: desired_format = self.determine_format(request) else: desired_format = self._meta.default_format serialized = self.serialize(request, errors, desired_format) response = http.HttpBadRequest( content=serialized, content_type=desired_format) raise ImmediateHttpResponse(response=response)