parse-community / parse-server-push-adapter

A push notification adapter for Parse Server
https://parseplatform.org
MIT License
85 stars 100 forks source link

Right way to send Push to all user without sending it multiple times #110

Closed thisfiore closed 6 years ago

thisfiore commented 6 years ago

Hello!

I build a job that schedules push and my goal is to send 1 weekly push to all my users.

Right now if I query all my installations and I send them 50 by 50 for ex. I got my push sent multiple times to all users like 5x times.

Am I missing something? I see that there are multiple installations for the same user on the same device. Should I delete/skip them someway?

I can't understand because I don't know the logic they get created/deleted.

Thanks

thisfiore commented 6 years ago

@flovilmart Can you help with this? How can I send a push to all my users ( including guest app users ) without sending it multiple times? At the moment I query directly all Installation but I get it sent multiple times. What is the right discriminant I could use to query or filter in my loop ?

funkenstrahlen commented 6 years ago

I see that there are multiple installations for the same user on the same device.

This should not be the case. You should try to fix this to resolve your push issues.

thisfiore commented 6 years ago

Thanks @funkenstrahlen I thought this process was self-managed by the server.

I could create a routine that clears old installations each time a new installation is created for that user. Correct? What if the user uses the app on two devices for example?

funkenstrahlen commented 6 years ago

Parse can only send pushes based on installations by default. You have to implement sending pushes by user yourself.

However in your case it is not required. Just sending a notification to all installations should do the job.

One installation should always be linked to one device. If your app client is implemented correctly it is not possible to have multiple (active) installations for one device.

funkenstrahlen commented 6 years ago

Can you post the code you use to send your pushes? Probably it is not correct.

thisfiore commented 6 years ago

on app I have this:

// Swift app didRegisterForRemoteNotificationsWithDeviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let installation = PFInstallation.current()
        installation?.setDeviceTokenFrom(deviceToken as Data)
        installation?.saveInBackground()
        let mixpanel = Mixpanel.mainInstance()
        mixpanel.people.addPushDeviceToken(deviceToken)
    }

// Than if the user logs in I do this
let installation: PFInstallation = PFInstallation.current()!
installation["user"] = PFUser.current()
installation.saveInBackground()

This is my scheduling job:


// SCHEDULING PUSH

Parse.Cloud.job('sendScheduledPush', function(req, status) {
    papertrail.log.info('Push Scheduler Called');
    var sPQ = new Parse.Query(myPushArchive);
    sPQ.equalTo('state', 'scheduled');
    sPQ.equalTo('test', false);
    sPQ.include('zone');
    sPQ.first().then(function(pushArchive) {
        console.log('');
        var iQ = new Parse.Query(Parse.Installation);
        var lang = pushArchive.get('lang');
        if (lang == 'EN') {
            iQ.notEqualTo('localeIdentifier', 'it-IT');
        } else {
            iQ.equalTo('localeIdentifier', 'it-IT');
        }
        papertrail.log.info('Preparing Queue for', lang, 'push');
        // iQ.limit(10000);
        iQ.count({ useMasterKey: true }).then(function(totalEntries) {
            papertrail.log.info('Total entries are ', totalEntries);
            pushArchive.set('totalToSend', totalEntries);
            pushArchive.save();
            runBatchOfPush(0, totalEntries, pushArchive);
            status.success();
        });
    });
});

const BATCH_DIMENSION = 25;
const BATCH_TIMEOUT = 10000;

function runBatchOfPush(current, cap, pushArchive) {
    if (current + BATCH_DIMENSION < cap) {
        const skip = current;
        const limit = current + BATCH_DIMENSION;
        papertrail.log.info('Processing', skip, 'to', limit);
        pushArchive.set('sent', limit);
        pushArchive.save();
        sendBatchOfPush(pushArchive, skip);
        setTimeout(() => {
            runBatchOfPush(limit, cap, pushArchive);
        }, BATCH_TIMEOUT);
    } else {
        const remaining = cap - current;
        sendBatchOfPush(pushArchive, current);
        papertrail.log.info('Processing last ', remaining);
        pushArchive.set('sent', cap);
        pushArchive.set('state', 'processed');
        pushArchive.save();
    }
}

function sendBatchOfPush(pushArchive, skip) {
    var query = new Parse.Query(Parse.Installation);
    var lang = pushArchive.get('lang');
    var message = pushArchive.get('message');

    if (lang == 'EN') {
        query.notEqualTo('localeIdentifier', 'it-IT');
    } else {
        query.equalTo('localeIdentifier', 'it-IT');
    }
    query.skip(skip);
    query.limit(BATCH_DIMENSION);
    var zone = pushArchive.get('zone');

    if (!zone) {
        return papertrail.log.error('Zone not found');
    }
    if (zone.get('enabled') == false || zone.get('state') == 'draft') {
        return papertrail.log.error('Zone not found');
    }

    if (!zone.get('center')) {
        return papertrail.log.error('Zone center not set');
    }

    const pushData = {
        alert: {
            body: message,
            title: zone.get('iShortDisplayName')[lang]
        },
        name: zone.get('iShortDisplayName')[lang],
        zoneId: zone.id,
        type: 'setZone',
        state: zone.get('state'),
        center: [ zone.get('center').latitude, zone.get('center').longitude ],
        mapStartingZoom: zone.get('mapStartingZoom'),
        featuredTags: zone.get('featuredTags') || [],
        selectedName: zone.get('iShortDisplayName')[lang],
        shortDisplayName: zone.get('iShortDisplayName')[lang]
    };
    Parse.Push.send(
        {
            where: query,
            data: pushData
        },
        {
            useMasterKey: true,
            success: function(response) {
                papertrail.log.info('Batch', skip, skip + BATCH_DIMENSION, 'Sent');
            },
            error: function(error) {
                papertrail.log.error('Batch', skip, skip + BATCH_DIMENSION, 'Error', error);
            }
        }
    );
}
thisfiore commented 6 years ago

It's a pure query, using skip + limit: var query = new Parse.Query(Parse.Installation); query.skip(skip); query.limit(BATCH_DIMENSION);

thisfiore commented 6 years ago

Ok, I'm testing a job that goes through all installation to make a clean:

What I see is:

Can you confirm that I should keep: - The most recent Installation WITH devicetoken SET

This is a crucial operation, I could lose retention on 10K users. Thanks

flovilmart commented 6 years ago

That’s not an issue with the push adapter. You should probably ask over on stackoverflow.

Also, I discourage using limit and skip, even more that you don’t specify any order.

And yes, the most recent installation may be the valid one. On iOS that should not matter.