def api_request_headers(self, channelish): if (isinstance(channelish, Channel)): config = channelish.config_json() else: config = channelish.config headers = TEMBA_HEADERS.copy() headers.update({ 'Accept': 'application/json', }) if 'api_token' in config: headers.update({ 'Authorization': 'Token %s' % (config['api_token'], ), }) else: authorization = config['authorization'] headers.update({ 'Authorization': '%s %s' % ( authorization['token_type'], authorization['access_token'], ) }) return headers
def deliver(self): from .v1.serializers import MsgCreateSerializer # create our post parameters post_data = json.loads(self.data) post_data['event'] = self.event post_data['relayer'] = self.channel.pk post_data['channel'] = self.channel.pk post_data['relayer_phone'] = self.channel.address # look up the endpoint for this channel result = dict(url=self.org.get_webhook_url(), data=urlencode(post_data, doseq=True)) if not self.org.get_webhook_url(): # pragma: no cover result['status_code'] = 0 result[ 'message'] = "No webhook registered for this org, ignoring event" self.status = FAILED self.next_attempt = None return result # get our org user user = self.org.get_user() # no user? we shouldn't be doing webhooks shtuff if not user: result['status_code'] = 0 result['message'] = "No active user for this org, ignoring event" self.status = FAILED self.next_attempt = None return result # make the request try: if not settings.SEND_WEBHOOKS: raise Exception( "!! Skipping WebHook send, SEND_WEBHOOKS set to False") # some hosts deny generic user agents, use Temba as our user agent headers = TEMBA_HEADERS.copy() # also include any user-defined headers headers.update(self.org.get_webhook_headers()) s = requests.Session() prepped = requests.Request('POST', self.org.get_webhook_url(), data=post_data, headers=headers).prepare() result['url'] = prepped.url result['request'] = prepped_request_to_str(prepped) r = s.send(prepped, timeout=5) result['status_code'] = r.status_code result['body'] = r.text.strip() r.raise_for_status() # any 200 code is ok by us self.status = COMPLETE result['message'] = "Event delivered successfully." # read our body if we have one if result['body']: try: data = r.json() serializer = MsgCreateSerializer(data=data, user=user, org=self.org) if serializer.is_valid(): result['serializer'] = serializer obj = serializer.object result[ 'message'] = "SMS message to %d recipient(s) with text: '%s'" % ( len(obj.contacts), obj.text) else: errors = serializer.errors result['message'] = "Event delivered successfully, ignoring response body, wrong format: %s" % \ ",".join("%s: %s" % (_, ",".join(errors[_])) for _ in errors.keys()) except Exception as e: # we were unable to make anything of the body, that's ok though because # get a 200, so just save our error for posterity result[ 'message'] = "Event delivered successfully, ignoring response body, not JSON: %s" % unicode( e) except Exception as e: # we had an error, log it self.status = ERRORED result['message'] = "Error when delivering event - %s" % unicode(e) # if we had an error of some kind, schedule a retry for five minutes from now self.try_count += 1 if self.status == ERRORED: if self.try_count < 3: self.next_attempt = timezone.now() + timedelta(minutes=5) else: self.next_attempt = None self.status = 'F' else: self.next_attempt = None return result
def deliver(self): from .serializers import MsgCreateSerializer # create our post parameters post_data = json.loads(self.data) post_data['event'] = self.event post_data['relayer'] = self.channel.pk post_data['channel'] = self.channel.pk post_data['relayer_phone'] = self.channel.address # look up the endpoint for this channel result = dict(url=self.org.get_webhook_url(), data=urlencode(post_data, doseq=True)) if not self.org.get_webhook_url(): # pragma: no cover result['status_code'] = 0 result['message'] = "No webhook registered for this org, ignoring event" self.status = FAILED self.next_attempt = None return result # get our org user user = self.org.get_user() # no user? we shouldn't be doing webhooks shtuff if not user: result['status_code'] = 0 result['message'] = "No active user for this org, ignoring event" self.status = FAILED self.next_attempt = None return result # make the request try: if not settings.SEND_WEBHOOKS: raise Exception("!! Skipping WebHook send, SEND_WEBHOOKS set to False") # some hosts deny generic user agents, use Temba as our user agent headers = TEMBA_HEADERS.copy() # also include any user-defined headers headers.update(self.org.get_webhook_headers()) s = requests.Session() prepped = requests.Request('POST', self.org.get_webhook_url(), data=post_data, headers=headers).prepare() result['url'] = prepped.url result['request'] = prepped_request_to_str(prepped) r = s.send(prepped) result['status_code'] = r.status_code result['body'] = r.text.strip() r.raise_for_status() # any 200 code is ok by us self.status = COMPLETE result['message'] = "Event delivered successfully." # read our body if we have one if result['body']: try: data = r.json() serializer = MsgCreateSerializer(data=data, user=user, org=self.org) if serializer.is_valid(): result['serializer'] = serializer obj = serializer.object result['message'] = "SMS message to %d recipient(s) with text: '%s'" % (len(obj.contacts), obj.text) else: errors = serializer.errors result['message'] = "Event delivered successfully, ignoring response body, wrong format: %s" % \ ",".join("%s: %s" % (_, ",".join(errors[_])) for _ in errors.keys()) except Exception as e: # we were unable to make anything of the body, that's ok though because # get a 200, so just save our error for posterity result['message'] = "Event delivered successfully, ignoring response body, not JSON: %s" % unicode(e) except Exception as e: # we had an error, log it self.status = ERRORED result['message'] = "Error when delivering event - %s" % unicode(e) # if we had an error of some kind, schedule a retry for five minutes from now self.try_count += 1 if self.status == ERRORED: if self.try_count < 3: self.next_attempt = timezone.now() + timedelta(minutes=5) else: self.next_attempt = None self.status = 'F' else: self.next_attempt = None return result