Using Firebase server timestamp to create a synchronized countdown timer on Android

I want to show the countdown timer unified for all users. I choose a way to do this, but I'm not sure if this is the best option.

server side:

  • The node server calls Firebase requesting the timestamp of the server.
  • server added X millis to timestamp
  • Firebase db server update with new timestamp

user side:

  • gets timestamp from db (created by server)
  • send a Firebase db request to get the current server timestamp
  • computes delta between server timestamp and current timestamp (local)
  • add the calculated delta to the future timestamp obtained in step 1
  • Displays the corrected countdown time.

The main problem that I see in this method is that the user has unrestricted read / write access to the "timestamp" value. Can this be used against me to make fake calls on db, thus increasing the use of my Firebase (cost of money).

Is there a better way to sync all devices at a single time in the future?

+4
source share
1 answer

, . Firebase /.info/serverTimeOffset, , Firebase .

, , , , () .

public class ServerTimeSyncer {

    private static final String TAG = "ServerTimeSyncer";

    private DatabaseReference mServerTimeOffsetReference;
    private long mServerTimeOffset;

    public long convertServerTimestampToLocal(final long serverTimestamp) {
        return serverTimestamp - mServerTimeOffset;
    }

    public void startServerTimeSync() {
        if (mServerTimeOffsetReference == null) {
            mServerTimeOffsetReference = FirebaseDatabase.getInstance().getReference("/.info/serverTimeOffset");
            mServerTimeOffsetReference.addValueEventListener(mServerTimeOffsetListener);
        }
    }

    public void stopServerTimeSync() {
        if (mServerTimeOffsetReference != null) {
            mServerTimeOffsetReference.removeEventListener(mServerTimeOffsetListener);
            mServerTimeOffsetReference = null;
        }
    }

    private final ValueEventListener mServerTimeOffsetListener = new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot snapshot) {
            mServerTimeOffset = snapshot.getValue(Long.class);
            Log.i(TAG, "Server time offset set to: " + mServerTimeOffset);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.w(TAG, "Server time sync cancelled");
        }
    };

}

. https://firebase.google.com/docs/database/android/offline-capabilities#clock-skew.

: , , , .

0

Source: https://habr.com/ru/post/1661480/


All Articles