From 98a935dda6723dbe66c01059ad10f6fa941d5ace Mon Sep 17 00:00:00 2001 From: gabriellsh <40830821+gabriellsh@users.noreply.github.com> Date: Tue, 30 Jun 2020 20:17:53 -0300 Subject: [PATCH] [FIX] Geolocation permission being asked on load (#18030) --- .../client/messageBox/messageBoxActions.js | 91 ++++++++++++++----- packages/rocketchat-i18n/i18n/en.i18n.json | 3 + 2 files changed, 73 insertions(+), 21 deletions(-) diff --git a/app/ui-message/client/messageBox/messageBoxActions.js b/app/ui-message/client/messageBox/messageBoxActions.js index d9ed4d48f1c..0837cdebd2c 100644 --- a/app/ui-message/client/messageBox/messageBoxActions.js +++ b/app/ui-message/client/messageBox/messageBoxActions.js @@ -65,15 +65,78 @@ messageBox.actions.add('Add_files_from', 'Computer', { }, }); -const geolocation = new ReactiveVar(false); +const canGetGeolocation = new ReactiveVar(false); + +const getGeolocationPermission = () => new Promise((resolve) => { + if (!navigator.permissions) { resolve(true); } + navigator.permissions.query({ name: 'geolocation' }).then(({ state }) => { resolve(state); }); +}); + +const getGeolocationPosition = () => new Promise((resolvePos) => { + navigator.geolocation.getCurrentPosition(resolvePos, () => { resolvePos(false); }, { + enableHighAccuracy: true, + maximumAge: 0, + timeout: 10000, + }); +}); + +const getCoordinates = async () => { + const status = await getGeolocationPermission(); + if (status === 'prompt') { + let resolveModal; + const modalAnswer = new Promise((resolve) => { resolveModal = resolve; }); + modal.open({ + title: t('You_will_be_asked_for_permissions'), + confirmButtonText: t('Continue'), + showCancelButton: true, + closeOnConfirm: true, + closeOnCancel: true, + }, async (isConfirm) => { + if (!isConfirm) { + resolveModal(false); + } + const position = await getGeolocationPosition(); + if (!position) { + const newStatus = getGeolocationPermission(); + resolveModal(newStatus); + } + resolveModal(position); + }); + const position = await modalAnswer; + return position; + } + + if (status === 'denied') { + return status; + } + + const position = await getGeolocationPosition(); + return position; +}; + messageBox.actions.add('Share', 'My_location', { id: 'share-location', icon: 'map-pin', - condition: () => geolocation.get() !== false, - action({ rid, tmid }) { - const position = geolocation.get(); - const { latitude, longitude } = position.coords; + condition: () => canGetGeolocation.get(), + async action({ rid, tmid }) { + const position = await getCoordinates(); + + if (!position) { + return; + } + + if (position === 'denied') { + modal.open({ + title: t('Cannot_share_your_location'), + text: t('The_necessary_browser_permissions_for_location_sharing_are_not_granted'), + confirmButtonText: t('Ok'), + closeOnConfirm: true, + }); + return; + } + + const { coords: { latitude, longitude } } = position; const text = `