djacobs / PyAPNs

Python library for interacting with the Apple Push Notification service (APNs)
http://pypi.python.org/pypi/apns/
MIT License
1.22k stars 376 forks source link

How about to fix alert string or alert.body ? #115

Closed rdandy closed 7 years ago

rdandy commented 9 years ago

Is this an idea for fixing long text ?

class Payload(object):
    """A class representing an APNs message payload"""
    def __init__(self, alert=None, badge=None, sound=None, category=None, custom={}, content_available=False, fix_oversize=False):
        super(Payload, self).__init__()
        self.alert = alert
        self.badge = badge
        self.sound = sound
        self.category = category
        self.custom = custom
        self.content_available = content_available
        self.fix_oversize = fix_oversize
        self._check_size()

    def _check_size(self):
        if len(self.json()) > MAX_PAYLOAD_LENGTH:
            # keep original value of alert string or alert.body
            # and set alert string or alert.body to empty string
            if self.fix_oversize:
                if isinstance(self.alert, PayloadAlert):
                    ori_text, self.alert.body = self.alert.body, ''
                else:
                    ori_text, self.alert = self.alert, ''
                payload_length = len(self.json())
                remain_length = int(MAX_PAYLOAD_LENGTH - payload_length) / 4   # for unicode
                if remain_length >= 4:
                    new_text = u'%s%s' % (ori_text[:remain_length - 4], u' ...')
                else:
                    new_text = ori_text

                if isinstance(self.alert, PayloadAlert):
                    self.alert.body = new_text
                else:
                    self.alert = new_text

        payload_length = len(self.json())
        if payload_length > MAX_PAYLOAD_LENGTH:
            raise PayloadTooLargeError(payload_length)
jimhorng commented 9 years ago

I think caller should trim message size to 256 bytes before calling pyapns, that's the way I did for my service, FYR.

rdandy commented 9 years ago

Yes, I understand caller should trim messages, or UI should check size for them, but I had a mission is to send push via API, and the message size depends on event content, so I try to cut message this way.... Thanks for your reply!