Giter Club home page Giter Club logo

pyapns's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyapns's Issues

Python2.6 SSL write error

File "/var/www/apns-proxy-server/lib/python2.6/site-packages/apns.py", line 526, in send_notification_multiple
    return self.write(frame.get_frame())
  File "/var/www/apns-proxy-server/lib/python2.6/site-packages/apns.py", line 260, in write
    return self._connection().write(string)
  File "/usr/lib64/python2.6/ssl.py", line 148, in write
    return self._sslobj.write(data)
TypeError: write() argument 1 must be string or read-only buffer, not bytearray

Max Frame Items?

Do you know what type of maximum limit should be put in frames?

I don't have thousands of devices to test with at the moment, so I'm not 100% sure how to handle maximum amount of items in the frame.

Would it make sense to stuff as many as possible into a frame? What if I have 5K devices?

Or would it work to say only allow 500 per frame, send when it's full, then create a new frame and send those?

Would I ever need to reconnect the APNS connection?

Sorry this is more of a question not necessarily a bug..

SSL3_WRITE_PENDING error

After some time service using PyAPNS is run in background I start to get such error:
return self._sslobj.write(data)
SSLError: [Errno 1] _ssl.c:1217: error:1409F07F:SSL routines:SSL3_WRITE_PENDING:bad write retry

After restarting service everythong works perfect. I use send_notification method for sending messages to all registered devices in simple for cycle.

PyPi package is not updated

Hi,

When I install PyAPNs from source (using python setup.py install), it works fine. But when I install it from PyPi (pip install apns) and run the same code, I get:

from apns import APNs, Frame, Payload
ImportError: cannot import name Frame

Perhaps the PyPi package is not update?

SSLError: [Errno 8] _ssl.c:1296: EOF occurred in violation of protocol

I'm currently using Django celery in combination with PyAPNs. I worked fine for a while until all of sudden, I received this error:

    return self._connection().write(string)
  File "/usr/lib/python2.7/ssl.py", line 172, in write
    return self._sslobj.write(data)
SSLError: [Errno 8] _ssl.c:1296: EOF occurred in violation of protocol

Any idea on what a possible fix for this could be?

New release

Is there any plans on updating pypi. Current release 1.1.2 was uploaded two years ago and is not working on python 3. I see that on github byte string issues for python3 has already been fixed.

Disconnected From APNS due to Bad Tokens

Hey folks, I've run into this issue during my development. I decided to open an issue just in case others run into the same issue.

I did some testing to see how PyAPNs would react to bad tokens. Let's say there is a token that is invalid (ie. user may have deleted your application, token hex some how got messed up or cut off, wrong token, a token that doesn't exist, you accidentally sent a push to a production token etc...).

Let's make an arbitrary token:

token = 'hecbadd4ed53h45b60f53ed79fef30g11ffddca7abffd0a7f90391ec245fhje'

Great, now that we have our 'bad' token. Let's setup the configuration & payload details.

>>> from apns import *
>>> apns = APNs(use_sandbox=True, cert_file='apns-dev-cert.pem', key_file='apns-dev-key') 
>>> payload = Payload(alert = 'hello', sound="default", badge=0)

Next, let's actually fire off the push notifications.

>>> apns.gateway_server.send_notification(token, payload)
>>> apns.gateway_server.send_notification(token, payload)
>>> apns.gateway_server.send_notification(token, payload)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "apns.py", line 381, in send_notification
    self.write(self._get_notification(token_hex, payload))
  File "apns.py", line 174, in write
    return self._connection().write(string)
  File "/usr/lib/python2.7/ssl.py", line 172, in write
    return self._sslobj.write(data)
socket.error: [Errno 32] Broken pipe

Notice how it didn't raise any errors until the 3rd push notification was sent. Now if I send a 4th one after that:

>>> apns.gateway_server.send_notification(token, payload)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "apns.py", line 381, in send_notification
    self.write(self._get_notification(token_hex, payload))
  File "apns.py", line 174, in write
    return self._connection().write(string)
  File "/usr/lib/python2.7/ssl.py", line 172, in write
    return self._sslobj.write(data)
ssl.SSLError: [Errno 1] _ssl.c:1296: error:1409F07F:SSL     routines:SSL3_WRITE_PENDING:bad write retry

It seems I have been disconnected by APNS because of the bad token. Any pushes that I try to send to VALID tokens will not work because the socket object that keeps the connection is gone. I think using a try and except block would be nice somewhere.

Once the exception is raised, the user can then remove the invalid token and then reconnect to APNS.

But the problem here is that it only raises the error after the third Push notification. Is there some way to detect a bad token right off the start? and reconnect? It gets pretty bad especially if you have apns declared as a global variable.

PayloadTooLarge

If you have unicode characters in payload, json.dumps generates "\uXXXX" phraze (2bytes -> 6bytes)
It's too long and RFC 4627 allows to have unicode characters in strings. And Apple requires JSON strictly adheres to RFC 4627.

Add ensure_ascii=False in json.dumps, please.

How Do I Fix A "PayloadTooLargeError"?

The error message I received does not give much description apart from "PayloadTooLargeError".

How do I fix this error?

What exactly am I doing wrong?

It was working, and all of a sudden this started happening, so I am kind of confused.

Thank you very, very much in advance,
From A Young Developer

Why we need key and cert when i get all together

import time
import math
import random
from apns import APNs, Frame, Payload

apns = APNs(use_sandbox=True, cert_file='CertProduction.pem', key_file='KeyProduction.pem')

# Send a notification
token_hex = '14a9d626e6585b80c1be071de9b99dab4d7c137be51552b792b52b285e513f32'

# Send a notification
payload = Payload(alert="Hello World!", sound="default", badge=1)
apns.gateway_server.send_notification(token_hex, payload)

For my code i get this error

Traceback (most recent call last):
File "C:\env\test\sendpush.py", line 15, in
apns.gateway_server.send_notification(token_hex, payload)
File "C:\Python27\lib\site-packages\apns.py", line 536, in send_notification
self.write(self._get_notification(token_hex, payload))
File "C:\Python27\lib\site-packages\apns.py", line 270, in write
return self._connection().write(string)
File "C:\Python27\lib\site-packages\apns.py", line 252, in _connection
self._connect()
File "C:\Python27\lib\site-packages\apns.py", line 228, in _connect
self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file)
File "C:\Python27\lib\ssl.py", line 891, in wrap_socket
ciphers=ciphers)
File "C:\Python27\lib\ssl.py", line 509, in init
self._context.load_cert_chain(certfile, keyfile)
ssl.SSLError: [SSL] PEM lib (_ssl.c:2506)

Why i need to have cert and key file?

Using frame and enhanced

Hi,
I tried to use enhanced with frame (multiple token).

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 808, in __bootstrap_inner
self.run()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 761, in run
self.__target(_self.__args, *_self.__kwargs)
File "/Users/appsfoundry/sites/flask/scooprms/ENV/lib/python2.7/site-packages/apns.py", line 564, in _read_error_response
self._resend_notifications_by_id(identifier)
File "/Users/appsfoundry/sites/flask/scooprms/ENV/lib/python2.7/site-packages/apns.py", line 567, in _resend_notifications_by_id
fail_idx = Util.getListIndexFromID(self._sent_notifications, failed_identifier)
File "/Users/appsfoundry/sites/flask/scooprms/ENV/lib/python2.7/site-packages/apns.py", line 589, in getListIndexFromID
return next(index for (index, d) in enumerate(the_list)
StopIteration

Wrong SSL Protocol

Hello,

I had a problem with the package, it throws "Violation of protocol" error from ssl when apns called the function ssl.wrap_socket.

There is a quickfix, specify the PROTOCOL_TLSv1 on the wrap_socket call, like this:
(line 126) self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file, ssl_version=PROTOCOL_TLSv1)

PS: Don't forget to import it from ssl module.

PyAPNs fails in Django but goes well if run it directly

i'm writing a model with PyAPNs but it sometimes fails. Sometimes I get this error:

[Errno 336265218] _ssl.c:339: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib

and sometimes get an broken pipe error from socket.py:
error: [Errno 32] Broken pipe

but when i directly run the APNs function nothing goes wrong and my iOS device just normally receives the push notification.

I've referred to stack overflow and other websites. Some claims that this is a privilege problem, but when i try to run django with root privilege the problem still exists. Another post says the push notification was written in an incorrect format, but since i can directly run the program, i don't think that is the reason.

do you have any idea?

ImportError: cannot import name Frame

For some reason, I'm unable to import Frame. Have any of you also experienced this issue?

>>> from apns import APNs, Frame, Payload
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name Frame

I looked inside the apns.py file and Frame isn't in there. It's somehow missing. I downloaded the project via easy_install just as the documents directed me to. Should I just manually add in the code?

How to pass the pass phrase automatically?

Hi, currently my key.pem file has a pass phrase.

The issue happens at the following line:

apns.gateway_server.send_notification(token_hex, payload)

The script asks: Enter PEM pass phrase: and waits for user input.

I would like to know how to pass the pass phrase automatically. Is there an option for that?

Thanks in advance!

Disconnected by APNs

My connection to APNs disconnected by Apple after a long time, should there be a reconnect facility or should I reconnect manually?

If it's my responsibility to reconnect, where should I place the try-except block?

What do multiple notifications in Frame mean?

If I want to send multiple notifications to one device, does the following code work?

frame = Frame()
frame.add_item(token_hex, payloadA, identifier, expiry, priority)
frame.add_item(token_hex, payloadB, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)

Or if I want send single notification to multiple device, how can I do by Frame?

APNS server causes [Errno 32] Broken pipe

It seems under certain condition the apple servers will disconnect

File "/usr/local/lib/python2.7/dist-packages/apns-1.1.1-py2.7.egg/apns.py", line 296, in send_notification
    self.write(self._get_notification(token_hex, payload))
File "/usr/local/lib/python2.7/dist-packages/apns-1.1.1-py2.7.egg/apns.py", line 144, in write
    return self._connection().write(string)
File "/usr/lib/python2.7/ssl.py", line 150, in write
    return self._sslobj.write(data)
socket.error: [Errno 32] Broken pipe

This SO post indicates this might be due to bad tokens (I think that was my problem). The suggested solution is to reconnect. Does this sound sensible, and if so do you think it belongs in apns.py or in user code? If the former, I can work on a patch.

On one hand I think it would be nice to have this in apns.py, as it's easier for the user, but we will need a way to return the failure to the user code, so they can remove this device id (if that's the right action to take, I guess that's not necessarily the case for a broken pipe). Also it's not immediately obvious that the user should handle this exception, although I suppose documentation could be enough.

Thoughts?

APNS to support error-response handling(enhanced message) and re-send mechanism for performance

The problem of current APNS error-response are: (reference: the problem, official doc -> The Binary Interface and Notification Format)

  • async error response (response time varies) => errors not guaranteed to be caught if wait for a fixed time
  • success do not response => cannot wait for response forever
  • async close write stream connection after error-response
  • all message sent after failed msg error are discarded, error-response and write conn close will delay => should be re-sent
  • sometimes APNS close arbitrary

From my experiment of getting error-response with enhanced message format:

  • if wait for error-response(using select.select()) with given timeout = 0s, it often get NO APNS's error-response in time,
  • when I set to 0.3s it got 90% of error-response.
    however, it's not guarantee 100% to get error-response for every failed notification, the network connection might also be a factor of delayed time.

Possible Solution

The solution suggested in the problem is to save sent notification in a queue with no timeout(or minimum), when error-response caught, pop out messages before the error one in queue (considered successfully sent), and re-sent others.
Which will not have performance concern if waiting for error-response in fixed time for each message sent, and also prevent error-response uncaught.

Update PyPI

The version of "apns" on PyPI is old and the usage has since changed. The example in the README doesn't work with the version on PyPI even though it says that you can install the library using easy_install.

Sleep delay required between sends?

I understand from reading past issues that if a bad token is found all remaining tokens will not be sent. The way to deal with this is to send them individually using enhanced mode and the listener to identify which one failed and then start again from the token that follows. However, I find that the error handling doesn't work unless there is a sleep timer in between sends. It seems it may need to be between .5 and 1 seconds but it isn't consistent. What is consistent is that without a sleep timer the error handling simply won't function. Is this delay really required and if so is there a best practice for how long it needs to be?

I have also asked this question out on stackoverflow but with no answers thus far: http://stackoverflow.com/questions/29178740/pyapns-and-the-need-to-sleep-between-sends

Error-response doesn't work with Frames

There is a simple test. enhanced + Frame

a = APNs(use_sandbox=True, cert_file='zzz.pem', enhanced=True)
f = Frame()
payload = Payload(alert="Hello World!", sound="default", badge=1)
f.add_item('CORRECT TOKEN', payload, 1, time.time()+3600, 10)
f.add_item('WRONG TOKEN', payload, 2, time.time()+3600, 10)
a.gateway_server.send_notification_multiple(f)

The log says me everything is fine(it is not true) . Error response worker doesn't start:

2014-12-19 18:46:32,789 - DEBUG - apns - GatewayConnection APNS connection establishing...
2014-12-19 18:46:33,508 - DEBUG - apns - GatewayConnection APNS connection established
2014-12-19 18:46:33,510 - INFO - apns -  GatewayConnection APNS connection closed

Second test. Enhanced without Frame

a = APNs(use_sandbox=True, cert_file='zzz.pem', enhanced=True)
payload = Payload(alert="Hello World!", sound="default", badge=1)
a.gateway_server.send_notification('CORRECT TOKEN', payload, 1)
a.gateway_server.send_notification('WRONG TOKEN', payload, 2)

This time I got an error from APNS, as expected:

2014-12-19 18:48:10,508 - DEBUG - apns - initialized error-response handler worker
2014-12-19 18:48:10,513 - DEBUG - apns - GatewayConnection APNS connection establishing...
2014-12-19 18:48:11,513 - DEBUG - apns - GatewayConnection APNS connection established
2014-12-19 18:48:11,705 - INFO - apns - got error-response from APNS:(8, 1)
2014-12-19 18:48:11,705 - INFO - apns -  GatewayConnection APNS connection closed
2014-12-19 18:48:11,705 - INFO - apns - resending 10 notifications to APNS
2014-12-19 18:48:11,705 - DEBUG - apns - resending notification with id:2 to APNS
2014-12-19 18:48:11,706 - DEBUG - apns - GatewayConnection APNS connection establishing...
2014-12-19 18:48:12,305 - DEBUG - apns - GatewayConnection APNS connection established
2014-12-19 18:48:42,733 - DEBUG - apns - connection idle after 30 secs
2014-12-19 18:48:42,733 - INFO - apns -  GatewayConnection APNS connection closed
2014-12-19 18:48:42,733 - DEBUG - apns - error-response handler worker closed

Question is. Does Frames can work with Enhanced mode (with error handler)?

read_error_response thread dead-loop

read_error_response thread seems like fall into dead-loop when i try to send notification with invalid token. (got error-response status : 8)
error logs as follow :
[INFO] apns: resending 2981 notifications to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: resending 2972 notifications to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: resending 2980 notifications to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: resending 2971 notifications to APNS
[INFO] apns: resending 2979 notifications to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: resending 2979 notifications to APNS
[INFO] apns: resending 2970 notifications to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: resending 2981 notifications to APNS
[INFO] apns: got error-response from APNS:(8, 0)
[INFO] apns: rebuilding connection to APNS
[INFO] apns: resending 2975 notifications to APNS

anyone got this problem ?

Not working on App Engine

Library works fine in a local python script but not in App Engine. I always get

    self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file)
TypeError: 'NoneType' object is not callable

Did anybody get this library working with AppEngine?

OpenSSQL Error

Hello,

When i try to send a test push message, i get the following openssql error:
ssl.SSLError: [Errno 336265225] _ssl.c:351: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib
Exception ssl.SSLError: SSLError(336265225, '_ssl.c:351: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib') in <bound method GatewayConnection.del of <apns.GatewayConnection object at 0x10d16ccd0>> ignored

and then exits without sending the push.

Has this happened to anyone else? What's going wrong with this?

Thanks in advance

Installing from PyPI with pip still broken

Hey,

I can see that you merged PR #97 recently to fix this issue, but it's still not possible to install via pip for me. Here's a transcript:

(tempenv-5f92108943223) cal@hp-elitedesk ~/s/b/i/ops> pip install apns
Downloading/unpacking apns
  Downloading apns-2.0.tar.gz
  Running setup.py (path:/home/cal/.virtualenvs/tempenv-5f92108943223/build/apns/setup.py) egg_info for package apns

Installing collected packages: apns
  Running setup.py install for apns
    error: file '/home/cal/.virtualenvs/tempenv-5f92108943223/build/apns/apns-send' does not exist
    Complete output from command /home/cal/.virtualenvs/tempenv-5f92108943223/bin/python -c "import setuptools, tokenize;__file__='/home/cal/.virtualenvs/tempenv-5f92108943223/build/apns/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-gleqyn-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/cal/.virtualenvs/tempenv-5f92108943223/include/site/python2.7:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

copying apns.py -> build/lib.linux-x86_64-2.7

running build_scripts

creating build/scripts-2.7

error: file '/home/cal/.virtualenvs/tempenv-5f92108943223/build/apns/apns-send' does not exist

----------------------------------------
Cleaning up...
Command /home/cal/.virtualenvs/tempenv-5f92108943223/bin/python -c "import setuptools, tokenize;__file__='/home/cal/.virtualenvs/tempenv-5f92108943223/build/apns/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-gleqyn-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/cal/.virtualenvs/tempenv-5f92108943223/include/site/python2.7 failed with error code 1 in /home/cal/.virtualenvs/tempenv-5f92108943223/build/apns
Storing debug log for failure in /home/cal/.pip/pip.log

passphrase issue

When I run my script on local but it blocks and prompts me to enter the passphrase manually and doesn't work until I do

I don't know how to set it up so to work without prompt

This is my code:

            from apns import APNs, Payload
            import optparse
            import os


            certificate_file = here(".." + app.fichier_PEM.url   )        
            token_hex = '0c99bb3d077eeacdc04667d38dd10ca1a'
            pass_phrase = app.mot_de_passe



            apns = APNs(use_sandbox=True, cert_file= certificate_file)
            payload = Payload(alert = message.decode('utf-8'), sound="default", badge=1)
            apns.gateway_server.send_notification(token_hex, payload)


            # Get feedback messages
            for (token_hex, fail_time) in apns.feedback_server.items():
                print "fail: "+fail_time

NameError: global name 'SSLError' is not defined

Hey!

I'm using PyAPNs on Google App Engine and sometimes I get this error:

Traceback (most recent call last):
File "/base/data/home/apps/xxxxxxxxxx/yyyyyyyyyy/apns.py", line 243, in default
for (token, fail) in connection.feedback_server.items():
File "/base/data/home/apps/xxxxxxxxxx/yyyyyyyyyy/lib/pyapns.py", line 324, in items
for chunk in self._chunks():
File "/base/data/home/apps/xxxxxxxxxx/yyyyyyyyyy/lib/pyapns.py", line 313, in _chunks
data = self.read(BUF_SIZE)
File "/base/data/home/apps/xxxxxxxxxx/yyyyyyyyyy/lib/pyapns.py", line 174, in read
return self._connection().read(n)
File "/base/data/home/apps/xxxxxxxxxx/yyyyyyyyyy/lib/pyapns.py", line 170, in _connection
self._connect()
File "/base/data/home/apps/xxxxxxxxxx/yyyyyyyyyy/lib/pyapns.py", line 156, in _connect
except SSLError, ex:
NameError: global name 'SSLError' is not defined

Is this a bug in PyAPNs or something related to App Engine's enviroment?

Thanks in advance.

ssl.SSLError when connecting using push certificates certificates

Hi,

First - thanks for the much-needed package!

When I am trying to send a push notification via the packege, I get SSL errors:

p12 = '/path/to/dev.p12'
p12_nopass = '/path/to/dev_nopass.p12'
pem = '/path/to/dev.pem'
cer = '/path/to/aps_development.cer'     # From Apple's dev site

apns = APNs(use_sandbox=True,
        cert_file=pem,
        key_file=p12_nopass)

# Send a notification
# Dummy token, but it does not cause the error (SSL fails before token check)
token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
payload = Payload(alert="Hello World!", sound="default", badge=1)
apns.gateway_server.send_notification(token_hex, payload)

Which gives:

Traceback (most recent call last):
  File "apple_push_driver.py", line 18, in <module>
    apns.gateway_server.send_notification(token_hex, payload)
  File "/path_to/site-packages/apns.py", line 381, in send_notification
    self.write(self._get_notification(token_hex, payload))
  File "/path_to/apns.py", line 174, in write
    return self._connection().write(string)
  File "/path_to/apns.py", line 167, in _connection
    self._connect()
  File "/path_to/apns.py", line 151, in _connect
    self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file)
  File "/path_to/ssl.py", line 387, in wrap_socket
    ciphers=ciphers)
  File "/path_to/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265225] _ssl.c:351: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib

I have posted the issue in StackOverflow, but thought it might be relevant here.

http://stackoverflow.com/questions/23457302/ssl-sslerror-when-sending-push-message-using-pyapns

Error handling and frames

  1. I would like to be able to remove unregistered tokens from my database. How do I get the 6 bytes error-response packet that contains the status code when sending using a frame?

  2. If sending a large number of notifications in a frame, and there's an unregistered notification somewhere in the middle (for example, someone uninstalled the app), will all the remaining notifications be delivered?

Push not being recieved by devices anymore

Hi there,

We are using this plugin on Google App Engine with a Cloud Endpoints project.

Several months back when we were testing the integration the push messages were sending.

We have not made any major modifications to our push code and now the messages are not sending.

The App Engine logs show:

GatewayConnection APNS connection establishing...
GatewayConnection APNS connection established
GatewayConnection APNS connection closed

and does not report any 500 errors or SSL/key errors. But the message is not received by the phone.

We are also getting "Deadline Exceeded Errors" at least one of the times we tried.

Our keys are signed correctly using this process:

in keychain access, select both cert and key then export to Certificates.p12 file.

to generate cert.pem
openssl pkcs12 -in Certificates.p12 -out cert.pem -nodes -nokeys

to generate key.pem
openssl pkcs12 -in Certificates.p12 -out key.pem -nodes -nocerts

Our push code is copied directly from the instructions:


def send_single_push(u, payload):

    apns = get_apns_handler(False)

    # Send multiple notifications in a single transmission
    frame = Frame()
    identifier = 1
    expiry = time.time()+3600
    priority = 10

    pa = PushAlias.query(PushAlias.user == u.key).fetch(1)

    if pa:
        pa = pa[0]

    bc = PushBadgeCount.query(PushBadgeCount.alias == pa.key).fetch(1)

    if bc:
        bc = bc[0]

    # Increase the badge count
    bc.badge_count += 1
    bc.put()

    # Set the payload data and badge count
    apns_payload = Payload(
        alert=payload['alert'],
        sound=payload['sound'] if payload.has_key('sound') and payload['sound'] else "default",
        badge=bc.badge_count
    )

    # Add a push to the frame for each device in the alias
    for device in pa.devices:
        frame.add_item(device, apns_payload, identifier, expiry, priority)

    if get_environment() != 'sandbox':
        try:
            apns.gateway_server.send_notification_multiple(frame)
        except:
            # Force re-connect
            apns.gateway_server._connect()

        return False, None

We are mimicking Urban Airship like functionality.

And the keys are set as such:


def get_apns_handler(enhanced=False):

    sandbox = True
    cert = APNS_CERT_SANDBOX
    pem = APNS_PEM_SANDBOX

    # if get_environment() == 'prod':
    #     sandbox = False
    #     cert = APNS_CERT_PRODUCTION
    #     pem = APNS_PEM_PRODUCTION

    return APNs(use_sandbox=sandbox, cert_file=cert, key_file=pem, enhanced=enhanced)

We are using Googles own SSL library via the app.yaml:


libraries:
    - name: ssl
      version: latest

Any help would be greatly appreciated. Let me know if you need more information.

Connect/Reconect in the Enhanced mode

Hi!

I have noticed many many 'connection establishing' and 'connection closed' events in Enhanced mode.
After 30 seconds of idle it says me

2014-12-17 18:23:19,470 - DEBUG - apns - connection idle after 35 secs
2014-12-17 18:23:19,471 - INFO - apns -  GatewayConnection APNS connection closed
2014-12-17 18:23:19,471 - DEBUG - apns - error-response handler worker closed

And when I send one more message then it reconnects again:

2014-12-17 18:29:58,124 - DEBUG - apns - initialized error-response handler worker
2014-12-17 18:29:58,125 - DEBUG - apns - GatewayConnection APNS connection establishing...
2014-12-17 18:29:58,125 - DEBUG - apns - connection idle after 433 secs
2014-12-17 18:29:58,125 - DEBUG - apns - error-response handler worker closed
2014-12-17 18:29:59,196 - DEBUG - apns - GatewayConnection APNS connection established

The question is: does it may cause any penalty from Apple because of many connection/reconnection?
So maybe it is better not to use Enhanced mode? I haven't seen many reconnection in 'normal' mode.

Thanks

Using Frame() to send multiple PNs and failure

When using a frame to send many PNs how would I keep track when a specific PN fails? I.E. if I have a list of 1000 tokens I need to send to and a failure occurs on token number 556 how do I resume the sending of PNs by skipping 556 and continuing with 557?

Is this possible at all? I know that I can check the feedback service for invalid tokens before sending but it's not always that a token has been invalidated before sending, often another kind of error can occur to halt the send_notification_multiple process.

Any feedback would be greatly appreciated.

Thanks!

AttributeError: 'GatewayConnection' object has no attribute 'timeout'

Hi, I'm testing this package with given demo code, but it raises this excepiton.

Press ENTER or type command to continue
Traceback (most recent call last):
  File "test_pyapns.py", line 10, in <module>
    apns.gateway_server.send_notification(token_hex, payload)
  File "/Library/Python/2.7/site-packages/apns.py", line 380, in send_notification
    self.write(self._get_notification(token_hex, payload))
  File "/Library/Python/2.7/site-packages/apns.py", line 173, in write
    return self._connection().write(string)
  File "/Library/Python/2.7/site-packages/apns.py", line 166, in _connection
    self._connect()
  File "/Library/Python/2.7/site-packages/apns.py", line 139, in _connect
    self._socket.settimeout(self.timeout)
AttributeError: 'GatewayConnection' object has no attribute 'timeout'

shell returned 1

After looking at the source code, I found there is not default timeout attribute on GatewayConnection object.

It this a bug or something?

Certificate server verification

Hello,

From a security point of view, it is better to check the server certificate, at least its certificate signature with:

self._ssl = wrap_socket(self._socket, keyfile=self.key_file, certfile=self.cert_file, ca_certs=cacertfile)

Where cacertfile comes from https://www.entrust.net/downloads/binary/entrust_2048_ca.cer. It could be downloaded and included into PyAPNs package.

Even better checking the APN gateway certificate validity by checking the CRL or the OCSP, but I do not think that Python SSL library handle this easily...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.