def test_invalid_topic(self, topic):
        expected = 'Topic must be a non-empty string.'
        with pytest.raises(ValueError) as excinfo:
            messaging.subscribe_to_topic('test-token', topic)
        assert str(excinfo.value) == expected

        with pytest.raises(ValueError) as excinfo:
            messaging.unsubscribe_from_topic('test-tokens', topic)
        assert str(excinfo.value) == expected
    def test_invalid_tokens(self, tokens):
        expected = 'Tokens must be a string or a non-empty list of strings.'
        if isinstance(tokens, six.string_types):
            expected = 'Tokens must be non-empty strings.'

        with pytest.raises(ValueError) as excinfo:
            messaging.subscribe_to_topic(tokens, 'test-topic')
        assert str(excinfo.value) == expected

        with pytest.raises(ValueError) as excinfo:
            messaging.unsubscribe_from_topic(tokens, 'test-topic')
        assert str(excinfo.value) == expected
 def test_unsubscribe_from_topic_non_json_error(self, status):
     _, recorder = self._instrument_iid_service(status=status, payload='not json')
     with pytest.raises(messaging.ApiCallError) as excinfo:
         messaging.unsubscribe_from_topic('foo', 'test-topic')
     reason = 'Unexpected HTTP response with status: {0}; body: not json'.format(status)
     code = messaging._MessagingService.IID_ERROR_CODES.get(
         status, messaging._MessagingService.UNKNOWN_ERROR)
     assert str(excinfo.value) == reason
     assert excinfo.value.code == code
     assert len(recorder) == 1
     assert recorder[0].method == 'POST'
     assert recorder[0].url == self._get_url('iid/v1:batchRemove')
 def test_unsubscribe_from_topic_error(self, status):
     _, recorder = self._instrument_iid_service(
         status=status, payload=self._DEFAULT_ERROR_RESPONSE)
     with pytest.raises(messaging.ApiCallError) as excinfo:
         messaging.unsubscribe_from_topic('foo', 'test-topic')
     assert str(excinfo.value) == 'error_reason'
     code = messaging._MessagingService.IID_ERROR_CODES.get(
         status, messaging._MessagingService.UNKNOWN_ERROR)
     assert excinfo.value.code == code
     assert len(recorder) == 1
     assert recorder[0].method == 'POST'
     assert recorder[0].url == self._get_url('iid/v1:batchRemove')
def unsubscribe_from_topic(topic, tokens, app):
    # [START unsubscribe]
    # Unubscribe the devices corresponding to the registration tokens from the
    # topic.
    response = messaging.unsubscribe_from_topic(tokens, topic, app)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    return response.success_count
 def test_unsubscribe_from_topic(self, args):
     _, recorder = self._instrument_iid_service()
     resp = messaging.unsubscribe_from_topic(args[0], args[1])
     self._check_response(resp)
     assert len(recorder) == 1
     assert recorder[0].method == 'POST'
     assert recorder[0].url == self._get_url('iid/v1:batchRemove')
     assert json.loads(recorder[0].body.decode()) == args[2]
Exemple #7
0
def send_notification_to_all(message):

    registration_tokens = list(
        User.objects.exclude(fcm_token__isnull=True).exclude(
            fcm_token__exact='').values_list('fcm_token', flat=True))
    topic = 'events'
    messaging.subscribe_to_topic(registration_tokens, topic)
    message = messaging.Message(
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=3600),
            priority='normal',
            notification=messaging.AndroidNotification(
                title=message["title"],
                body=message["message"],
            ),
        ),
        topic=topic,
    )

    response = messaging.send(message)
    print(response)
    messaging.unsubscribe_from_topic(registration_tokens, topic)
Exemple #8
0
 def unregister_topic(self, list_registration_token, name_topic):
     """
 Function to remove member to the group or remove group if it's empty
 :param list_registration_token:  [list, registration, token] in list format
 :param name_topic: name of the groups consists of token's app
 :return: None
 """
     response = messaging.unsubscribe_from_topic(list_registration_token,
                                                 name_topic)
     # See the TopicManagementResponse reference documentation
     # for the contents of response.
     print(response.success_count, 'tokens were unsubscribed successfully')
     return
Exemple #9
0
def api_profile_update():

    user_email = get_jwt_identity()
    print("user identity (email): ", user_email)
    
    subscribeAll=request.headers.get('subscribeAll')
    firebaseToken = request.headers.get('firebaseToken')

    user = User.query.filter_by(email=user_email).first()

    if subscribeAll == 0 or subscribeAll == '0':
        user.subscribeAll = False
        messaging.unsubscribe_from_topic(firebaseToken, "all")
    elif subscribeAll == 1 or subscribeAll == '1':
        user.subscribeAll = True
        messaging.subscribe_to_topic(firebaseToken, "all")
    else:
        return jsonify(msg = "Invalid value"), 400

    db.session.commit()
    
    return jsonify(msg = "Successfully update subscribe/Unsubscribe to all"), 200
Exemple #10
0
def refresh_subscription(push_token, topics):
    """
    1. Initialize firebase
    2. find tags to add / remove
    3. update
    :param push_token: required
    :param topics: tagObjs
    :return:
    """
    # if you use multiple environments (e.g. dev,prod..)
    _id = "environment-or-app-id"
    if _id not in topics:
        topics.append(_id)

    _initialize_firebase()
    try:
        followed_tags = _get_topics_by_token(push_token)
    except:
        followed_tags = []

    new_tags = [topic for topic in topics if topic not in followed_tags]
    old_tags = [topic for topic in followed_tags if topic not in topics]
    for topic in new_tags:
        try:
            messaging.subscribe_to_topic([push_token], topic)
            logging.info("Topic %s added to %s" % (topic, push_token))
        except:
            logging.error("Could not subscribe %s to %s" % (push_token, topic))

    for topic in old_tags:
        try:
            messaging.unsubscribe_from_topic([push_token], topic)
            logging.info("Topic %s removed from %s" % (topic, push_token))
        except:
            logging.error("Could not unsubscribe %s from %s" %
                          (topic, push_token))
    return
Exemple #11
0
def unsubscribe_from_topic():
    topic = 'highScores'
    # [START unsubscribe]
    # These registration tokens come from the client FCM SDKs.
    registration_tokens = [
        'YOUR_REGISTRATION_TOKEN_1',
        # ...
        'YOUR_REGISTRATION_TOKEN_n',
    ]

    # Unubscribe the devices corresponding to the registration tokens from the
    # topic.
    response = messaging.unsubscribe_from_topic(registration_tokens, topic)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    print(response.success_count, 'tokens were unsubscribed successfully')
def fcm_unsubscribe(tokens, topic):
    """
    Unsubscribe the given tokens from a specific FCM topic.
    :param tokens: list of FCM tokens
    :param topic: FCM topic/category slug
    :return: success True/False
    :return:
    """

    try:
        _ = messaging.unsubscribe_from_topic(tokens, topic)
    except messaging.ApiCallError as e:
        return False
    except ValueError as e:
        return False

    return True
Exemple #13
0
def unsubscribe_from_topic():
    topic = 'highScores'
    # [START unsubscribe]
    # These registration tokens come from the client FCM SDKs.
    # TODO Custom token
    registration_tokens = [
        'fZJPLFb62PWItwCqle2AoF:APA91bG1V5xxVBjSUVRr2kJkuqGWjG0Tbkywsi_hB1Ss27RgIpCjYSAGGtkm4nL2_vEQKQJ0oWImfp6oQ2VleLch-6_OZuAkkSqGVhVWu80tSa2OK6xvNiPoFJt1Dio_kRk0cDb5Tr-h',
        # ...
        'deXMEcpHQzc:APA91bGH6_kXLK1OaiaHCimQrvadTNpVMiCm14i7PkT59rL7yC7dyVDedgSp2Mq5rHIA4AuajwYXd8FlaLPyoDbndBbPcp78T_yDgAJg2JlLefrGW5et4lEQMIdApAOcJ3G9xi2FC6ke',
    ]

    # Unubscribe the devices corresponding to the registration tokens from the
    # topic.
    response = messaging.unsubscribe_from_topic(registration_tokens, topic)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    print(response.success_count, 'tokens were unsubscribed successfully')
Exemple #14
0
def api_subscribes_delete():
    user_email = get_jwt_identity()
    print("user identity (email): ", user_email)

    player_id = request.headers.get("playerid")
    token = request.headers.get('firebasetoken')

    user = User.query.filter_by(email=user_email).first()
    player = Player.query.filter_by(id=player_id).first()

    print("player: ", player)

    if user and player and token:

        res = messaging.unsubscribe_from_topic(tokens = [token], topic=player_id)

        Subscription.query.filter_by(user_id=user.id, player_id=player_id).delete()
        db.session.commit()
        
        return jsonify(msg="Successfully unsubscribe!"), 200
    else:
        return jsonify(msg="Error while delete subscription"), 500
    def unsubscribe_from_topic(self, topic, *tokens):
        registration_tokens = [*tokens]
        response = messaging.unsubscribe_from_topic(registration_tokens, topic)

        return 200 if response.success_count > 0 else 400
Exemple #16
0
def delete_subscriber_from_topic(token, dist_id):
    registration_tokens = [token]
    topic = _get_topic_from_dist_id(dist_id)

    response = messaging.unsubscribe_from_topic(registration_tokens, topic)
    return str(response.success_count)
Exemple #17
0
def unsubscribe_from_topic(topic, user):
    if not firebase_ins:
        firebase_admin.initialize_app(cred, {'projectId': firebase_app})
    token = user.userprofile.device_token
    if token:
        messaging.unsubscribe_from_topic(tokens=[token], topic=topic, app=None)
Exemple #18
0
def test_unsubscribe():
    resp = messaging.unsubscribe_from_topic(_REGISTRATION_TOKEN, 'mock-topic')
    assert resp.success_count + resp.failure_count == 1
Exemple #19
0
def unsubscribe(tokens, topic):
    response = messaging.unsubscribe_from_topic(tokens, topic)
    print(response.success_count, 'tokens were unsubscribed successfully')