Ejemplo n.º 1
0
def api_login_post():
    # process user login
    email = request.headers.get('email')
    password = request.headers.get('password')
    remember = True if request.headers.get('remember') else False
    firebaseToken = request.headers.get('firebase_token')

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

    if user and check_password_hash(user.password, password):

        print("==> New user logged in: ", email)

        if firebaseToken and firebaseToken != '':
            print("This user need to setup firebase...")
            # subscribe to followed topic using new firebase token
            if user.subscribeAll:
                messaging.subscribe_to_topic([firebaseToken], 'all')
                print('Subscribe to all')

            cs = []
            for c in user.channels:
                cs.append(c.id)
                messaging.subscribe_to_topic([firebaseToken], c.id)

            print('Subscribe to channels: ', cs)

        # Identity can be any data that is json serializable
        access_token = create_access_token(identity=email)
        refresh_token = create_refresh_token(identity=email)
        return jsonify(access_token=access_token,
                       refresh_token=refresh_token), 200
    else:
        return jsonify(msg='Email or password is incorrect!'), 400
Ejemplo n.º 2
0
async def register(request):
    data = await request.json()
    subscriber_id = data['subscriber_id']
    tokens = [subscriber_id]

    messaging.subscribe_to_topic(tokens, 'updates')

    return JSONResponse({'success': True})
    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_topic_management_timeout(self):
     self.fcm_service._client.session.mount(
         'https://iid.googleapis.com',
         testutils.MockAdapter(
             json.dumps({'results': [{}, {
                 'error': 'error_reason'
             }]}), 200, self.recorder))
     messaging.subscribe_to_topic(['1'], 'a')
     assert len(self.recorder) == 1
     assert self.recorder[0]._extra_kwargs['timeout'] == 4
    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_subscribe_to_topic_non_json_error(self, status):
     _, recorder = self._instrument_iid_service(status=status, payload='not json')
     with pytest.raises(messaging.ApiCallError) as excinfo:
         messaging.subscribe_to_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:batchAdd')
 def test_subscribe_to_topic_error(self, status):
     _, recorder = self._instrument_iid_service(
         status=status, payload=self._DEFAULT_ERROR_RESPONSE)
     with pytest.raises(messaging.ApiCallError) as excinfo:
         messaging.subscribe_to_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:batchAdd')
Ejemplo n.º 8
0
def create_match(db, user, matching_user):
    """Does all the setup for creating a new match"""

    # Create a new match
    _, match = db.collection("matches").add({
        "users": [
            db.collection("users").document(user["id"]),
            db.collection("users").document(matching_user["id"]),
        ]
    })

    message = {
        "content": db.collection("matches").document(match.id),
        "type": "match",
        "sender": None,
        "createdAt": datetime.now(),
    }

    # Add message to conversations with Aida
    db.collection("users").document(
        user["id"]).collection("messages").add(message)
    db.collection("users").document(
        matching_user["id"]).collection("messages").add(message)

    tokens = []

    if user.get("notification_token"):
        tokens.append(user["notification_token"])

    if matching_user.get("notification_token"):
        tokens.append(matching_user["notification_token"])

    if not tokens:
        return

    # Setup notifications for messages between users
    topic = f"/topics/match-{match.id}"
    messaging.subscribe_to_topic(
        tokens=tokens,
        topic=topic,
    )

    # Send a match notification to both users
    messaging.send(
        messaging.Message(
            notification=messaging.Notification(
                title="Aida", body="I've found you a match! 😍"),
            topic=topic,
        ))
Ejemplo n.º 9
0
def send_to_topic():
    # [START send_to_topic]
    # The topic name can be optionally prefixed with "/topics/".
    topic = 'notify'

    # See documentation on defining a message payload.
    message = messaging.Message(
        data={
            'score': '850',
            'time': '2:45',
        },
        topic=topic,
    )

    # Send a message to the devices subscribed to the provided topic.
    response = messaging.send(message)
    # Response is a message ID string.
    print('Successfully sent message:', response)

    registration_tokens = [
        'chCK9jrYEQ8:APA91bEf0ZxbIsw0yCvHw1SrnitL1iDLV3eus-bXcfnuyDCSHlJwyh2saKLpEpHrJUDJT6ExcF0YIk0oA83Ps_IjlBk-MAxX3_74m6fQtHql1kP5Ks0lehn2xbdbA5TQ87aj6B0_R2kN',
        # ...
    ]

    # Unubscribe the devices corresponding to the registration tokens from the
    # topic.
    response = messaging.subscribe_to_topic(registration_tokens, topic)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    print(response, 'tokens were subscribed successfully')
Ejemplo n.º 10
0
def subscribe_to_topic(topic, tokens, app):
    # [START subscribe]
    # Subscribe the devices corresponding to the registration tokens to the
    # topic.
    response = messaging.subscribe_to_topic(tokens, topic, app)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    return response.success_count
 def test_subscribe_to_topic(self, args):
     _, recorder = self._instrument_iid_service()
     resp = messaging.subscribe_to_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:batchAdd')
     assert json.loads(recorder[0].body.decode()) == args[2]
Ejemplo n.º 12
0
 def register_topic(self, list_registration_token, name_topic):
     """
 Function to add or create group under name is topic
 :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.subscribe_to_topic(list_registration_token,
                                             name_topic)
     print(response.success_count, 'tokens were subscribed successfully')
     return
Ejemplo n.º 13
0
def add_subscriber_to_topic(token, dist_id):
    registration_tokens = [token]
    topic = _get_topic_from_dist_id(dist_id)
    response = messaging.subscribe_to_topic(registration_tokens, topic)

    if dist_id not in _get_all_subscribed_dists_from_db():
        doc_ref = db.collection(u'static').document(u'topics_subscribed')
        dist_name = get_dist_name_from_id_db(dist_id)
        doc = {str(dist_id): {"name": dist_name, "count": 0}}
        doc_ref.set(doc, merge=True)

    return response.success_count
Ejemplo n.º 14
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
Ejemplo n.º 15
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)
Ejemplo n.º 16
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
def fcm_subscribe(tokens, topic):
    """
    Subscribe the given tokens to a specific FCM topic.
    :param tokens: list of FCM tokens
    :param topic: FCM topic/category slug
    :return: success True/False
    """

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

    return True
Ejemplo n.º 18
0
def subscribe_to_topic():
    topic = 'highScores'
    # [START subscribe]
    # These registration tokens come from the client FCM SDKs.
    registration_tokens = [
        'YOUR_REGISTRATION_TOKEN_1',
        # ...
        'YOUR_REGISTRATION_TOKEN_n',
    ]

    # Subscribe the devices corresponding to the registration tokens to the
    # topic.
    response = messaging.subscribe_to_topic(registration_tokens, topic)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    print(response.success_count, 'tokens were subscribed successfully')
Ejemplo n.º 19
0
    def __get_chunk_topic__(self,chunk):

        # print(chunk)
        topic = ",".join(chunk).encode('utf-8')
        topic_sha = hashlib.sha1(topic).hexdigest()       
        topic_ref = db.reference('all_user_topics_test/{0}'.format(topic_sha))
        topic_result = topic_ref.get()

        if topic_result is None:
           
            register_response = messaging.subscribe_to_topic(chunk, topic_sha)
            self.__handle_register_response__(register_response)   
            topic_ref.set(topic_sha)
            topic_result = topic_sha

        return topic_result        
Ejemplo n.º 20
0
def subscribe_to_topic():
    topic = 'highScores'
    # [START subscribe]
    # 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',
    ]

    # Subscribe the devices corresponding to the registration tokens to the
    # topic.
    response = messaging.subscribe_to_topic(registration_tokens, topic)
    # See the TopicManagementResponse reference documentation
    # for the contents of response.
    print(response.success_count, 'tokens were subscribed successfully')
Ejemplo n.º 21
0
    def __create_or_get_topic__(self,user_ids):
        
        if not self.__is_list_of_strings__(user_ids):
            raise TypeError("user_id must be a list when sending bulk message")
    
        topic = ",".join(user_ids).encode('utf-8')
        topic_sha = hashlib.sha1(topic).hexdigest()       
        topic_ref = db.reference('topics/{0}'.format(topic_sha))
        topic_result = topic_ref.get()

        if topic_result is None:
            tokens = self.__get_token_list__(user_ids)            
            register_response = messaging.subscribe_to_topic(tokens, topic_sha)
            self.__handle_register_response__(register_response)             
            topic_ref.set(topic_sha)
            topic_result = topic_sha

        return topic_result
Ejemplo n.º 22
0
def api_subscribes_post():
    
    user_email = get_jwt_identity()
    print("user identity (email): ", user_email)

    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=id).first()

    if user and player and token:

        res = messaging.subscribe_to_topic(tokens = [token], topic=id)
        user.channels.append(player)
        db.session.commit()

        return jsonify(msg="Successfully create new relation"), 200
    else:
        return jsonify(msg="There is no Pro Player with id %s" % id), 400
Ejemplo n.º 23
0
def update_topic_registrations():
    topics = map(toString, range(21))
    tokens = {}
    for topic in topics:
        tokens[topic] = []

    # get database reference
    ref = db.reference('/')

    # get user data
    snapshot = ref.get()

    # parse
    users = snapshot["users"]
    for key, val in users.items():
        tokens[str(val['numTimesPerDay'])].append(key)

    # register each topic
    for topic, tokens in tokens.items():
        if tokens != []:
            token_reg_res = messaging.subscribe_to_topic(tokens, topic)
            print(token_reg_res)
        else:
            print("'{}' Topic Empty".format(topic))
Ejemplo n.º 24
0
 def subscribe_to_topics(self, registration_token, topics):
     registration_tokens = [registration_token]
     for topic in topics:
         messaging.subscribe_to_topic(registration_tokens, topic)
Ejemplo n.º 25
0
cred = credentials.Certificate(
    '/home/alex/Downloads/chat/threshold-chat-firebase-adminsdk-fg92b-3258681a34.json'
)

# This is registration token received on mobile phone from the client FCM SDKs.
# There is no way to receive it in Python: it is specific to the given app installation on the phone.
# Every chat client has such a token. All the communication is encrypted with this token.
# How it is received - see Android application at
# https://medium.com/@min2bhandari/firebase-cloud-messaging-with-kotlin-165ac1b0d841

# Replace this token with yours!
registration_token = "eT6B_xQRRFGVtK8xa71zBp:APA91bE9IK2wQtJkoLvEQdjhASPvmdFzxJs-sWedpbh3nSbUWinmtVZ10A8bun4YxG5UXaQHK3ExRZajQSYetdk-Yil-TEkKNjz03b_n45Yp5zV9ZHExtlIlbwr5dd5ukpNSQbx9RkuO"

reg_token2 = "e7Kvae-1T7m54syh-qcDs1:APA91bH4CFtJCssNcPN1OEubMat88zXzW7qrzA2zHzPtzQ6lJa1ddNYuEAAXcDxqXcgvoIKjLc6jOYtYW7QcysgHXRKFLe6AU69kNVqvOZlaTQuA3cHtE8YK1BYFb8wFkrYYpexBrrVf"

# default initialization based on
# export GOOGLE_APPLICATION_CREDENTIALS="/home/alex/Downloads/chat/threshold-chat-firebase-adminsdk-fg92b-3258681a34.json"
# Mentor will give this file. You must not commit it into GitHub!!!
# firebase_admin.initialize_app()

# initialization with explicitly indicated credentials
firebase_admin.initialize_app(cred)

# Now we can subscribe the client to our Chat.
resp = messaging.subscribe_to_topic(registration_token, "ThresholdChat")

# you may check success as follows
# print(resp.success_count)
# 1
# From this point the client will receive messages (Notifications will appear in PopUps in the phone's tray)
Ejemplo n.º 26
0
 def subscribe(self, code: str, locator: str) -> bool:
     messaging.subscribe_to_topic(tokens=[locator], topic=code)
     return True
Ejemplo n.º 27
0
def subscribe(token, topic):
    messaging.subscribe_to_topic(token, topic)
Ejemplo n.º 28
0
def test_subscribe():
    resp = messaging.subscribe_to_topic(_REGISTRATION_TOKEN, 'mock-topic')
    assert resp.success_count + resp.failure_count == 1
Ejemplo n.º 29
0
def subscribe_to_topic(topic, user):
    if not firebase_ins:
        firebase_admin.initialize_app(cred, {'projectId': firebase_app})
    token = user.userprofile.device_token
    if token:
        messaging.subscribe_to_topic(tokens=[token], topic=topic, app=None)
Ejemplo n.º 30
0
                              options={
                                  'project-id':
                                  'vandyhacks-dbd1b',
                                  'storageBucket':
                                  'vandyhacks-dbd1b.appspot.com',
                                  'databaseURL':
                                  'https://vandyhacks-dbd1b.firebaseio.com'
                              })

while (True):
    # Subscribe to the topic used for communication
    topic = 'bcdMessaging'  # bcd stands for our project, BottleCompositionDetector

    registrationToken = 'AAAArSnKi2M:APA91bGEnpiiHpihogal7C5A34sLBcr8fPThAGHh1lr-s_DnWhAlm2_ODdWaoFmHdqVqX3KmElJBX_rKVjf_tsmQKBaduyNFfbPbF4B1c4gfZA-LgKruYgN7Eg0zPnBBbH0VcAGhMN3j'

    subResponse = messaging.subscribe_to_topic(registrationToken, topic)

    ref = db.reference('messageVH')

    name = ref['name']

    bucket = storage.bucket()

    imageBlob = bucket.blob(name)

    imageBlob.download_to_filename("imageToRead.jpg")

    inputFile = cv2.imread("imageToRead.jpg")

    #model = tf.keras.applications.VGG16(weights="")
    model = tf.keras.models.load_model("convNetModel.h5")