Final refactor

This commit is contained in:
androiddevkkotlin 2020-11-06 11:27:36 +02:00
parent 54ed389553
commit 585534102a
16 changed files with 324 additions and 341 deletions

View file

@ -9,12 +9,8 @@ import com.github.scribejava.core.model.*;
import com.github.scribejava.core.oauth.OAuth10aService; import com.github.scribejava.core.oauth.OAuth10aService;
import net.osmand.PlatformUtil; import net.osmand.PlatformUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
/** /**
@ -93,39 +89,6 @@ public class OsmOAuthAuthorizationClient {
service.execute(req, callback); service.execute(req, callback);
} }
public String authorizeOsmUserDetails() throws InterruptedException, ExecutionException, IOException, XmlPullParserException {
OAuth1RequestToken requestToken = startOAuth();
if (requestToken == null) {
throw new IllegalArgumentException("Illegal request token: ");
}
// save for reuse of request ( they usually don't match and should'nt be an issue)
String url = "https://api.openstreetmap.org/api/0.6/user/details";
OAuthRequest req = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, req);
req.addHeader("Content-Type", "application/xml");
Response response = service.execute(req);
String user = "";
String home = "";
String lang = "";
XmlPullParser parser = PlatformUtil.newXMLPullParser();
parser.setInput(response.getStream(), "UTF-8");
List<String> languages = new ArrayList<>();
int tok;
while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (tok == XmlPullParser.START_TAG) {
String name = parser.getName();
if ("user".equals(name)) {
user = parser.getAttributeValue("", "display_name");
} else if ("home".equals(name)) {
} else if ("lang".equals(name)) {
languages.add(parser.nextText());
}
}
}
return user;
}
public Response performRequest(String url, String method, String body) public Response performRequest(String url, String method, String body)
throws InterruptedException, ExecutionException, IOException { throws InterruptedException, ExecutionException, IOException {
service.getApi().getSignatureType(); service.getApi().getSignatureType();
@ -140,8 +103,6 @@ public class OsmOAuthAuthorizationClient {
return service.execute(req); return service.execute(req);
} }
public OAuth1RequestToken startOAuth() { public OAuth1RequestToken startOAuth() {
try { try {
requestToken = service.getRequestToken(); requestToken = service.getRequestToken();

View file

@ -25,6 +25,7 @@
android:textSize="@dimen/default_desc_text_size" android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_medium" osmand:typeface="@string/font_roboto_medium"
android:duplicateParentState="true" android:duplicateParentState="true"
android:drawablePadding="@dimen/content_padding_half"
tools:text="Button" tools:text="Button"
android:paddingStart="@dimen/content_padding_small" android:paddingStart="@dimen/content_padding_small"
android:paddingEnd="@dimen/content_padding_small" /> android:paddingEnd="@dimen/content_padding_small" />

View file

@ -10,7 +10,8 @@
android:paddingTop="@dimen/measurement_tool_menu_title_padding_top" android:paddingTop="@dimen/measurement_tool_menu_title_padding_top"
android:orientation="vertical" android:orientation="vertical"
android:paddingEnd="@dimen/content_padding" android:paddingEnd="@dimen/content_padding"
android:paddingStart="@dimen/content_padding"> android:paddingStart="@dimen/content_padding"
android:paddingBottom="@dimen/content_padding_half">
<ImageView <ImageView
android:id="@+id/header" android:id="@+id/header"

View file

@ -54,5 +54,4 @@
</com.google.android.material.textfield.TextInputLayout> </com.google.android.material.textfield.TextInputLayout>
</LinearLayout> </LinearLayout>

View file

@ -1,81 +1,80 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:osmand="http://schemas.android.com/apk/res-auto" xmlns:osmand="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:background="?attr/list_background_color" android:background="?attr/list_background_color"
android:gravity="center_vertical"> android:gravity="center_vertical">
<LinearLayout <LinearLayout
android:id="@+id/selectable_list_item" android:id="@+id/selectable_list_item"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:minHeight="@dimen/setting_list_item_large_height" android:minHeight="@dimen/setting_list_item_large_height"
tools:background="?android:attr/selectableItemBackground"> tools:background="?android:attr/selectableItemBackground">
<androidx.appcompat.widget.AppCompatImageView
android:id="@android:id/icon"
android:layout_width="@dimen/standard_icon_size"
android:layout_height="@dimen/standard_icon_size"
android:layout_gravity="center"
android:layout_marginStart="@dimen/content_padding"
android:layout_marginLeft="@dimen/content_padding"
android:layout_marginTop="@dimen/bottom_sheet_icon_margin"
android:layout_marginEnd="@dimen/content_padding"
android:layout_marginRight="@dimen/content_padding"
android:layout_marginBottom="@dimen/bottom_sheet_icon_margin"
tools:src="@drawable/ic_action_user_account" />
<androidx.appcompat.widget.AppCompatImageView <LinearLayout
android:id="@android:id/icon" android:layout_width="0dp"
android:layout_width="@dimen/standard_icon_size" android:layout_height="wrap_content"
android:layout_height="@dimen/standard_icon_size" android:layout_gravity="center_vertical"
android:layout_gravity="center" android:layout_weight="1"
android:layout_marginLeft="@dimen/content_padding" android:orientation="vertical"
android:layout_marginTop="@dimen/bottom_sheet_icon_margin" android:paddingStart="@dimen/content_padding"
android:layout_marginRight="@dimen/content_padding" android:paddingLeft="@dimen/content_padding"
android:layout_marginBottom="@dimen/bottom_sheet_icon_margin" android:paddingEnd="@dimen/content_padding"
tools:src="@drawable/ic_action_user_account" android:paddingRight="@dimen/content_padding">
android:layout_marginEnd="@dimen/content_padding"
android:layout_marginStart="@dimen/content_padding" />
<LinearLayout <net.osmand.plus.widgets.TextViewEx
android:layout_width="0dp" android:id="@android:id/title"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_gravity="center_vertical" android:layout_height="wrap_content"
android:layout_weight="1" android:ellipsize="marquee"
android:orientation="vertical" android:letterSpacing="@dimen/text_button_letter_spacing"
android:paddingLeft="@dimen/content_padding" android:singleLine="true"
android:paddingRight="@dimen/content_padding" android:textColor="?android:textColorPrimary"
android:paddingStart="@dimen/content_padding" android:textSize="@dimen/default_list_text_size"
android:paddingEnd="@dimen/content_padding"> osmand:typeface="@string/font_roboto_regular" />
<net.osmand.plus.widgets.TextViewEx <net.osmand.plus.widgets.TextViewEx
android:id="@android:id/title" android:id="@android:id/summary"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:ellipsize="marquee" android:letterSpacing="@dimen/description_letter_spacing"
android:singleLine="true" android:maxLines="4"
android:letterSpacing="@dimen/text_button_letter_spacing" android:textColor="?android:textColorSecondary"
android:textColor="?android:textColorPrimary" android:textSize="@dimen/default_desc_text_size"
android:textSize="@dimen/default_list_text_size" osmand:typeface="@string/font_roboto_regular" />
osmand:typeface="@string/font_roboto_regular" />
<net.osmand.plus.widgets.TextViewEx </LinearLayout>
android:id="@android:id/summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:letterSpacing="@dimen/description_letter_spacing"
android:maxLines="4"
android:textColor="?android:textColorSecondary"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular" />
</LinearLayout> <androidx.appcompat.widget.AppCompatImageView
android:id="@+id/icon_logout"
android:layout_width="wrap_content"
android:layout_height="@dimen/standard_icon_size"
android:layout_gravity="center"
android:layout_marginStart="@dimen/content_padding"
android:layout_marginLeft="@dimen/content_padding"
android:layout_marginTop="@dimen/bottom_sheet_icon_margin"
android:layout_marginEnd="@dimen/content_padding"
android:layout_marginRight="@dimen/content_padding"
android:layout_marginBottom="@dimen/bottom_sheet_icon_margin"
android:tint="@color/active_buttons_and_links_text_disabled_light"
osmand:srcCompat="@drawable/ic_action_logout" />
<androidx.appcompat.widget.AppCompatImageView </LinearLayout>
android:id="@+id/icon_logout"
android:layout_width="wrap_content"
android:layout_height="@dimen/standard_icon_size"
android:layout_gravity="center"
android:layout_marginStart="@dimen/content_padding"
android:layout_marginLeft="@dimen/content_padding"
android:layout_marginTop="@dimen/bottom_sheet_icon_margin"
android:layout_marginEnd="@dimen/content_padding"
android:layout_marginRight="@dimen/content_padding"
android:layout_marginBottom="@dimen/bottom_sheet_icon_margin"
osmand:srcCompat="@drawable/ic_action_logout"
android:tint="@color/active_buttons_and_links_text_disabled_light"/>
</LinearLayout>
</LinearLayout> </LinearLayout>

View file

@ -11,6 +11,16 @@
Thx - Hardy Thx - Hardy
--> -->
<string name="user_login">Login</string>
<string name="user_password">Password</string>
<string name="login_account">Account</string>
<string name="use_login_password">Use login and password</string>
<string name="open_street_map_login_mode">You need to login to upload new or modified changes. \n\nYou can log in using the safe OAuth method or use your login and password.</string>
<string name="osm_edits_view_descr">You can view all your unloaded edits or OSM bugs in %1$s. Uploaded points dont show in OsmAnd.</string>
<string name="sing_in_with_open_street_map">Sing in with OpenStreetMap</string>
<string name="login_open_street_map_org">Login to OpenStreetMap.org</string>
<string name="login_open_street_map">Login to OpenStreetMap</string>
<string name="plugin_global_prefs_info">These plugin setting are global, and apply to all profiles</string>
<string name="message_you_need_add_two_points_to_show_graphs">You must add at least two points.</string> <string name="message_you_need_add_two_points_to_show_graphs">You must add at least two points.</string>
<string name="icon_group_travel">Travel</string> <string name="icon_group_travel">Travel</string>
<string name="icon_group_emergency">Emergency</string> <string name="icon_group_emergency">Emergency</string>
@ -482,9 +492,7 @@
<string name="route_recalculation">Route recalculation</string> <string name="route_recalculation">Route recalculation</string>
<string name="accessibility_announce">Announce</string> <string name="accessibility_announce">Announce</string>
<string name="login_and_pass">Username and password</string> <string name="login_and_pass">Username and password</string>
<string name="plugin_global_prefs_info">These settings apply to all profiles.</string>
<string name="osm_editing">OSM editing</string> <string name="osm_editing">OSM editing</string>
<string name="osm_edits_view_descr">View your edits or OSM bugs not yet uploaded in %1$s. Uploaded points will not show any more.</string>
<string name="app_mode_osm">OSM</string> <string name="app_mode_osm">OSM</string>
<string name="select_nav_icon_descr">Icon shown while navigating or moving.</string> <string name="select_nav_icon_descr">Icon shown while navigating or moving.</string>
<string name="select_map_icon_descr">Icon shown at rest.</string> <string name="select_map_icon_descr">Icon shown at rest.</string>
@ -3196,7 +3204,6 @@
<string name="global_app_settings">Global app settings</string> <string name="global_app_settings">Global app settings</string>
<string name="user_name">Your OSM username</string> <string name="user_name">Your OSM username</string>
<string name="open_street_map_login_descr">Needed for openstreetmap.org submissions.</string> <string name="open_street_map_login_descr">Needed for openstreetmap.org submissions.</string>
<string name="user_password">Your OSM password</string>
<string name="osmand_service">Background mode</string> <string name="osmand_service">Background mode</string>
<string name="osmand_service_descr">OsmAnd runs in the background with the screen off.</string> <string name="osmand_service_descr">OsmAnd runs in the background with the screen off.</string>
<string name="download_files_not_enough_space">There is not enough free space to download %1$s MB (free: %2$s).</string> <string name="download_files_not_enough_space">There is not enough free space to download %1$s MB (free: %2$s).</string>

View file

@ -541,10 +541,10 @@ public abstract class OsmandPlugin {
protected void addMyPlacesTab(FavoritesActivity favoritesActivity, List<TabItem> mTabs, Intent intent) { protected void addMyPlacesTab(FavoritesActivity favoritesActivity, List<TabItem> mTabs, Intent intent) {
} }
protected void contextMenuFragment(Activity activity, Fragment fragment, Object info, ContextMenuAdapter adapter) { protected void contextMenuFragment(FragmentActivity activity, Fragment fragment, Object info, ContextMenuAdapter adapter) {
} }
protected void optionsMenuFragment(Activity activity, Fragment fragment, ContextMenuAdapter optionsMenuAdapter) { protected void optionsMenuFragment(FragmentActivity activity, Fragment fragment, ContextMenuAdapter optionsMenuAdapter) {
} }
protected boolean searchFinished(QuickSearchDialogFragment searchFragment, SearchPhrase phrase, boolean isResultEmpty) { protected boolean searchFinished(QuickSearchDialogFragment searchFragment, SearchPhrase phrase, boolean isResultEmpty) {
@ -815,14 +815,13 @@ public abstract class OsmandPlugin {
} }
} }
public static void onContextMenuActivity(Activity activity, Fragment fragment, Object info, ContextMenuAdapter adapter) { public static void onContextMenuActivity(FragmentActivity activity, Fragment fragment, Object info, ContextMenuAdapter adapter) {
for (OsmandPlugin plugin : getEnabledPlugins()) { for (OsmandPlugin plugin : getEnabledPlugins()) {
plugin.contextMenuFragment(activity, fragment, info, adapter); plugin.contextMenuFragment(activity, fragment, info, adapter);
} }
} }
public static void onOptionsMenuActivity(FragmentActivity activity, Fragment fragment, ContextMenuAdapter optionsMenuAdapter) {
public static void onOptionsMenuActivity(Activity activity, Fragment fragment, ContextMenuAdapter optionsMenuAdapter) {
for (OsmandPlugin plugin : getEnabledPlugins()) { for (OsmandPlugin plugin : getEnabledPlugins()) {
plugin.optionsMenuFragment(activity, fragment, optionsMenuAdapter); plugin.optionsMenuFragment(activity, fragment, optionsMenuAdapter);
} }

View file

@ -119,7 +119,6 @@ import net.osmand.plus.measurementtool.LoginBottomSheetFragment;
import net.osmand.plus.measurementtool.MeasurementEditingContext; import net.osmand.plus.measurementtool.MeasurementEditingContext;
import net.osmand.plus.measurementtool.MeasurementToolFragment; import net.osmand.plus.measurementtool.MeasurementToolFragment;
import net.osmand.plus.measurementtool.SnapTrackWarningFragment; import net.osmand.plus.measurementtool.SnapTrackWarningFragment;
import net.osmand.plus.osmedit.OsmEditingFragment;
import net.osmand.plus.render.RendererRegistry; import net.osmand.plus.render.RendererRegistry;
import net.osmand.plus.resources.ResourceManager; import net.osmand.plus.resources.ResourceManager;
import net.osmand.plus.routepreparationmenu.ChooseRouteFragment; import net.osmand.plus.routepreparationmenu.ChooseRouteFragment;

View file

@ -20,7 +20,6 @@ import net.osmand.plus.dashboard.DashboardOnMap.DashboardType;
import net.osmand.plus.mapmarkers.MapMarkersDialogFragment; import net.osmand.plus.mapmarkers.MapMarkersDialogFragment;
import net.osmand.plus.mapsource.EditMapSourceDialogFragment; import net.osmand.plus.mapsource.EditMapSourceDialogFragment;
import net.osmand.plus.measurementtool.LoginBottomSheetFragment; import net.osmand.plus.measurementtool.LoginBottomSheetFragment;
import net.osmand.plus.osmedit.OsmEditingFragment;
import net.osmand.plus.search.QuickSearchDialogFragment; import net.osmand.plus.search.QuickSearchDialogFragment;
import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.ApplicationMode;
import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings;

View file

@ -4,145 +4,144 @@ import android.graphics.drawable.Drawable;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentManager;
import net.osmand.AndroidUtils; import net.osmand.AndroidUtils;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.UiUtilities.DialogButtonType; import net.osmand.plus.UiUtilities.DialogButtonType;
import net.osmand.plus.base.MenuBottomSheetDialogFragment; import net.osmand.plus.base.MenuBottomSheetDialogFragment;
import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem; import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem;
import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerSpaceItem; import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem;
import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem;
import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter;
import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.ApplicationMode;
import net.osmand.plus.settings.bottomsheets.OsmLoginDataBottomSheet; import net.osmand.plus.settings.bottomsheets.OsmLoginDataBottomSheet;
import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class LoginBottomSheetFragment extends MenuBottomSheetDialogFragment { public class LoginBottomSheetFragment extends MenuBottomSheetDialogFragment {
private ApplicationMode appMode; public static final String TAG = LoginBottomSheetFragment.class.getSimpleName();
private OsmOAuthAuthorizationAdapter client; private static final Log log = PlatformUtil.getLog(LoginBottomSheetFragment.class);
private static final String OSM_LOGIN_DATA = "osm_login_data"; private static final String OSM_LOGIN_DATA = "osm_login_data";
public static final String TAG = LoginBottomSheetFragment.class.getSimpleName(); private OsmOAuthAuthorizationAdapter authorizationAdapter;
@Override @Override
public void createMenuItems(Bundle savedInstanceState) { public void createMenuItems(Bundle savedInstanceState) {
items.add(new SimpleBottomSheetItem.Builder() OsmandApplication app = requiredMyApplication();
.setLayoutId(R.layout.bottom_sheet_login) authorizationAdapter = new OsmOAuthAuthorizationAdapter(app);
.create()); items.add(new SimpleBottomSheetItem.Builder().setLayoutId(R.layout.bottom_sheet_login).create());
items.add(new DividerSpaceItem(getContext(),
getResources().getDimensionPixelSize(R.dimen.bottom_sheet_content_margin)));
} }
@Override @Override
protected int getDismissButtonTextId() { protected int getDismissButtonTextId() {
return R.string.shared_string_cancel; return R.string.shared_string_cancel;
} }
@Override @Override
protected int getRightBottomButtonTextId() { protected int getRightBottomButtonTextId() {
return R.string.use_login_password; return R.string.use_login_password;
} }
@Override @Override
protected void setupThirdButton() { protected void setupThirdButton() {
super.setupThirdButton(); super.setupThirdButton();
TextView textViewIcon = thirdButton.findViewById(R.id.button_text); OsmandApplication app = getMyApplication();
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_openstreetmap_logo); if (app != null) {
drawable = DrawableCompat.wrap(drawable); Drawable icon = app.getUIUtilities().getIcon(R.drawable.ic_action_openstreetmap_logo, R.color.popup_text_color);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.popup_text_color)); TextView buttonText = thirdButton.findViewById(R.id.button_text);
AndroidUtils.setCompoundDrawablesWithIntrinsicBounds( AndroidUtils.setCompoundDrawablesWithIntrinsicBounds(buttonText, icon, null, null, null);
textViewIcon, }
drawable, }
null,
null,
null);
textViewIcon.setCompoundDrawablePadding(AndroidUtils.dpToPx(getActivity(), 8f));
}
@Override @Override
protected int getThirdBottomButtonTextId() { protected int getThirdBottomButtonTextId() {
return R.string.sing_in_with_open_street_map; return R.string.sing_in_with_open_street_map;
} }
@Override @Override
public int getFirstDividerHeight() { public int getFirstDividerHeight() {
return getResources().getDimensionPixelSize(R.dimen.card_content_padding_large); return getResources().getDimensionPixelSize(R.dimen.card_content_padding_large);
} }
@Override @Override
public int getSecondDividerHeight() { public int getSecondDividerHeight() {
return getResources().getDimensionPixelSize(R.dimen.content_padding_small); return getResources().getDimensionPixelSize(R.dimen.content_padding_small);
} }
public ApplicationMode getSelectedAppMode() { @Override
return appMode; protected void onRightBottomButtonClick() {
} FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager != null) {
OsmLoginDataBottomSheet.showInstance(fragmentManager, OSM_LOGIN_DATA, getTargetFragment(), usedOnMap, null);
}
dismiss();
}
@Override @Override
protected void onRightBottomButtonClick() { protected void onThirdBottomButtonClick() {
ApplicationMode appMode = getSelectedAppMode(); View view = getView();
FragmentManager fragmentManager = getFragmentManager(); if (view != null) {
if (fragmentManager != null) { authorizationAdapter.startOAuth((ViewGroup) view);
OsmLoginDataBottomSheet.showInstance(fragmentManager, OSM_LOGIN_DATA, getTargetFragment(), false, appMode); }
} }
dismiss();
}
public OsmOAuthAuthorizationAdapter getClient() { @Override
return client; protected DialogButtonType getRightBottomButtonType() {
} return (DialogButtonType.SECONDARY);
}
@Override public static void showInstance(@NonNull FragmentManager fragmentManager, @Nullable Fragment targetFragment) {
protected void onThirdBottomButtonClick() { if (!fragmentManager.isStateSaved()) {
View view = getView(); LoginBottomSheetFragment fragment = new LoginBottomSheetFragment();
client = new OsmOAuthAuthorizationAdapter(getMyApplication()); fragment.setTargetFragment(targetFragment, 0);
if (view != null) { fragment.show(fragmentManager, TAG);
client.startOAuth((ViewGroup) view); }
} }
}
@Override public void authorize(String oauthVerifier) {
protected DialogButtonType getThirdBottomButtonType() { if (authorizationAdapter != null) {
return (DialogButtonType.PRIMARY); authorizationAdapter.authorize(oauthVerifier);
} updateUserName();
}
Fragment target = getTargetFragment();
if (target instanceof OsmAuthorizationListener) {
((OsmAuthorizationListener) target).authorizationCompleted();
}
dismiss();
}
@Override private void updateUserName() {
protected DialogButtonType getRightBottomButtonType() { OsmandApplication app = getMyApplication();
return (DialogButtonType.SECONDARY); if (app != null) {
} String userName = "";
try {
userName = authorizationAdapter.getUserName();
} catch (InterruptedException e) {
log.error(e);
} catch (ExecutionException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (XmlPullParserException e) {
log.error(e);
}
app.getSettings().USER_DISPLAY_NAME.set(userName);
}
}
public static void showInstance(@NonNull FragmentManager fragmentManager, @Nullable Fragment targetFragment) { public interface OsmAuthorizationListener {
if (!fragmentManager.isStateSaved()) { void authorizationCompleted();
LoginBottomSheetFragment fragment = new LoginBottomSheetFragment(); }
fragment.setTargetFragment(targetFragment, 0);
fragment.show(fragmentManager, TAG);
}
}
public interface LoginOsmAuthorizationListener {
void informAuthorizationPrefsUpdate();
}
public void authorize(String oauthVerifier) {
if (client != null) {
client.authorize(oauthVerifier);
}
Fragment target = getTargetFragment();
if (target instanceof LoginOsmAuthorizationListener) {
((LoginOsmAuthorizationListener) target).informAuthorizationPrefsUpdate();
}
dismiss();
}
} }

View file

@ -2,18 +2,20 @@ package net.osmand.plus.osmedit;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import net.osmand.data.PointDescription; import net.osmand.data.PointDescription;
import net.osmand.osm.PoiType; import net.osmand.osm.PoiType;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin; import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.mapcontextmenu.MenuController; import net.osmand.plus.mapcontextmenu.MenuController;
import net.osmand.plus.measurementtool.LoginBottomSheetFragment; import net.osmand.plus.measurementtool.LoginBottomSheetFragment;
import net.osmand.plus.osmedit.OsmPoint.Action; import net.osmand.plus.osmedit.OsmPoint.Action;
import net.osmand.plus.osmedit.dialogs.SendPoiDialogFragment; import net.osmand.plus.osmedit.dialogs.SendPoiDialogFragment.SimpleProgressDialogPoiUploader;
import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter;
import net.osmand.plus.render.RenderingIcons; import net.osmand.plus.render.RenderingIcons;
import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings;
@ -42,12 +44,15 @@ public class EditPOIMenuController extends MenuController {
@Override @Override
public void buttonPressed() { public void buttonPressed() {
MapActivity activity = getMapActivity(); MapActivity activity = getMapActivity();
OsmandSettings settings = activity.getMyApplication().getSettings();
if (plugin != null && activity != null) { if (plugin != null && activity != null) {
OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(activity.getMyApplication()); OsmandApplication app = activity.getMyApplication();
if (client.isValidToken() || !Algorithms.isEmpty(settings.USER_NAME.get()) && !Algorithms.isEmpty(settings.USER_PASSWORD.get())){ OsmandSettings settings = app.getSettings();
new SendPoiDialogFragment.SimpleProgressDialogPoiUploader(activity). OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(app);
showProgressDialog(new OsmPoint[] { getOsmPoint() }, false, false); if (client.isValidToken()
|| !Algorithms.isEmpty(settings.USER_NAME.get())
&& !Algorithms.isEmpty(settings.USER_PASSWORD.get())) {
SimpleProgressDialogPoiUploader poiDialogUploader = new SimpleProgressDialogPoiUploader(activity);
poiDialogUploader.showProgressDialog(new OsmPoint[] {getOsmPoint()}, false, false);
} else { } else {
LoginBottomSheetFragment.showInstance(activity.getSupportFragmentManager(), activity.getLoginBottomSheetFragment()); LoginBottomSheetFragment.showInstance(activity.getSupportFragmentManager(), activity.getLoginBottomSheetFragment());
} }
@ -206,7 +211,7 @@ public class EditPOIMenuController extends MenuController {
return null; return null;
} }
} }
@Override @Override
public int getAdditionalInfoIconRes() { public int getAdditionalInfoIconRes() {
if (osmPoint.getAction() == Action.DELETE) { if (osmPoint.getAction() == Action.DELETE) {

View file

@ -19,6 +19,8 @@ import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.helpers.FontCache; import net.osmand.plus.helpers.FontCache;
import net.osmand.plus.measurementtool.LoginBottomSheetFragment; import net.osmand.plus.measurementtool.LoginBottomSheetFragment;
import net.osmand.plus.measurementtool.LoginBottomSheetFragment.OsmAuthorizationListener;
import net.osmand.plus.osmedit.ValidateOsmLoginDetailsTask.ValidateOsmLoginListener;
import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter;
import net.osmand.plus.settings.backend.OsmAndAppCustomization; import net.osmand.plus.settings.backend.OsmAndAppCustomization;
import net.osmand.plus.settings.fragments.BaseSettingsFragment; import net.osmand.plus.settings.fragments.BaseSettingsFragment;
@ -32,26 +34,21 @@ import org.apache.commons.logging.Log;
import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID;
import static net.osmand.plus.osmedit.OsmEditingPlugin.OSM_EDIT_TAB; import static net.osmand.plus.osmedit.OsmEditingPlugin.OSM_EDIT_TAB;
public class OsmEditingFragment extends BaseSettingsFragment implements OnPreferenceChanged, ValidateOsmLoginDetailsTask.ValidateOsmLoginListener, LoginBottomSheetFragment.LoginOsmAuthorizationListener { public class OsmEditingFragment extends BaseSettingsFragment implements OnPreferenceChanged, ValidateOsmLoginListener, OsmAuthorizationListener {
private static final Log log = PlatformUtil.getLog(OsmEditingFragment.class); private static final Log log = PlatformUtil.getLog(OsmEditingFragment.class);
private static final String OSM_EDITING_INFO = "osm_editing_info"; private static final String OSM_LOGOUT = "osm_logout";
private static final String OPEN_OSM_EDITS = "open_osm_edits"; private static final String OPEN_OSM_EDITS = "open_osm_edits";
private static final String OSM_LOGIN_DATA = "osm_login_data"; private static final String OSM_LOGIN_DATA = "osm_login_data";
private static final String OSM_LOGOUT = "osm_logout"; private static final String OSM_EDITING_INFO = "osm_editing_info";
private OsmOAuthAuthorizationAdapter client; private OsmOAuthAuthorizationAdapter authorizationAdapter;
@Override
public void loginValidationFinished(String error) {
updateAllSettings();
}
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
client = new OsmOAuthAuthorizationAdapter(app); authorizationAdapter = new OsmOAuthAuthorizationAdapter(app);
} }
@Override @Override
@ -85,31 +82,40 @@ public class OsmEditingFragment extends BaseSettingsFragment implements OnPrefer
} }
} }
@Override
public void loginValidationFinished(String warning) {
updateAllSettings();
}
private void setupLoginPref() { private void setupLoginPref() {
Preference nameAndPasswordPref = findPreference(OSM_LOGIN_DATA); Preference nameAndPasswordPref = findPreference(OSM_LOGIN_DATA);
nameAndPasswordPref.setTitle(R.string.login_open_street_map); if (!isValidToken() && !isLoginExists()) {
nameAndPasswordPref.setIcon(getContentIcon(R.drawable.ic_action_user_account)); nameAndPasswordPref.setIcon(getContentIcon(R.drawable.ic_action_user_account));
nameAndPasswordPref.setVisible(true);
boolean validToken = client.isValidToken(); } else {
boolean loginExists = !Algorithms.isEmpty(settings.USER_NAME.get()) && !Algorithms.isEmpty(settings.USER_PASSWORD.get()); nameAndPasswordPref.setVisible(false);
boolean visible = !validToken && !loginExists; }
nameAndPasswordPref.setVisible(visible);
} }
private void setupLogoutPref() { private void setupLogoutPref() {
boolean validToken = isValidToken();
Preference nameAndPasswordPref = findPreference(OSM_LOGOUT); Preference nameAndPasswordPref = findPreference(OSM_LOGOUT);
boolean validToken = client.isValidToken(); if (validToken || isLoginExists()) {
if (validToken){ String userName = validToken ? settings.USER_DISPLAY_NAME.get() : settings.USER_NAME.get();
nameAndPasswordPref.setSummary(settings.USER_DISPLAY_NAME.get()); nameAndPasswordPref.setVisible(true);
nameAndPasswordPref.setSummary(userName);
nameAndPasswordPref.setIcon(getContentIcon(R.drawable.ic_action_user_account));
} else { } else {
nameAndPasswordPref.setSummary(settings.USER_NAME.get()); nameAndPasswordPref.setVisible(false);
} }
nameAndPasswordPref.setIcon(getContentIcon(R.drawable.ic_action_user_account)); }
boolean loginExists = !Algorithms.isEmpty(settings.USER_NAME.get()) && !Algorithms.isEmpty(settings.USER_PASSWORD.get()); private boolean isValidToken() {
boolean visible = validToken || loginExists; return authorizationAdapter.isValidToken();
nameAndPasswordPref.setVisible(visible); }
private boolean isLoginExists() {
return !Algorithms.isEmpty(settings.USER_NAME.get()) && !Algorithms.isEmpty(settings.USER_PASSWORD.get());
} }
private void setupOfflineEditingPref() { private void setupOfflineEditingPref() {
@ -165,15 +171,15 @@ public class OsmEditingFragment extends BaseSettingsFragment implements OnPrefer
return true; return true;
} }
} else if (OSM_LOGOUT.equals(prefId)) { } else if (OSM_LOGOUT.equals(prefId)) {
if (client.isValidToken()) { if (isValidToken()) {
settings.USER_ACCESS_TOKEN.set(""); settings.USER_ACCESS_TOKEN.resetToDefault();
settings.USER_ACCESS_TOKEN_SECRET.set(""); settings.USER_ACCESS_TOKEN_SECRET.resetToDefault();
client.resetToken(); authorizationAdapter.resetToken();
client = new OsmOAuthAuthorizationAdapter(app); authorizationAdapter = new OsmOAuthAuthorizationAdapter(app);
} else { } else {
settings.USER_NAME.set(""); settings.USER_NAME.resetToDefault();
settings.USER_PASSWORD.set(""); settings.USER_PASSWORD.resetToDefault();
} }
app.showShortToastMessage(R.string.osm_edit_logout_success); app.showShortToastMessage(R.string.osm_edit_logout_success);
updateAllSettings(); updateAllSettings();
@ -188,8 +194,8 @@ public class OsmEditingFragment extends BaseSettingsFragment implements OnPrefer
} }
@Override @Override
public void informAuthorizationPrefsUpdate() { public void authorizationCompleted() {
client = new OsmOAuthAuthorizationAdapter(app); authorizationAdapter = new OsmOAuthAuthorizationAdapter(app);
updateAllSettings(); updateAllSettings();
} }
} }

View file

@ -1,6 +1,5 @@
package net.osmand.plus.osmedit; package net.osmand.plus.osmedit;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
@ -16,13 +15,11 @@ import android.view.View;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.EditText; import android.widget.EditText;
import android.widget.Spinner; import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import net.osmand.AndroidUtils; import net.osmand.AndroidUtils;
import net.osmand.PlatformUtil; import net.osmand.PlatformUtil;
@ -398,15 +395,15 @@ public class OsmEditingPlugin extends OsmandPlugin {
} }
@Override @Override
public void contextMenuFragment(final Activity la, final Fragment fragment, final Object info, ContextMenuAdapter adapter) { public void contextMenuFragment(final FragmentActivity activity, final Fragment fragment, final Object info, ContextMenuAdapter adapter) {
if (fragment instanceof AvailableGPXFragment) { if (fragment instanceof AvailableGPXFragment) {
adapter.addItem(new ContextMenuItem.ItemBuilder().setTitleId(R.string.local_index_mi_upload_gpx, la) adapter.addItem(new ContextMenuItem.ItemBuilder().setTitleId(R.string.local_index_mi_upload_gpx, activity)
.setIcon(R.drawable.ic_action_export) .setIcon(R.drawable.ic_action_export)
.setListener(new ContextMenuAdapter.ItemClickListener() { .setListener(new ContextMenuAdapter.ItemClickListener() {
@Override @Override
public boolean onContextMenuClick(ArrayAdapter<ContextMenuItem> adapter, int itemId, int pos, boolean isChecked, int[] viewCoordinates) { public boolean onContextMenuClick(ArrayAdapter<ContextMenuItem> adapter, int itemId, int pos, boolean isChecked, int[] viewCoordinates) {
sendGPXFiles(la, (AvailableGPXFragment) fragment, (GpxInfo) info); sendGPXFiles(activity, (AvailableGPXFragment) fragment, (GpxInfo) info);
return true; return true;
} }
}).createItem()); }).createItem());
@ -414,7 +411,7 @@ public class OsmEditingPlugin extends OsmandPlugin {
} }
@Override @Override
public void optionsMenuFragment(final Activity activity, final Fragment fragment, ContextMenuAdapter optionsMenuAdapter) { public void optionsMenuFragment(final FragmentActivity activity, final Fragment fragment, ContextMenuAdapter optionsMenuAdapter) {
if (fragment instanceof AvailableGPXFragment) { if (fragment instanceof AvailableGPXFragment) {
final AvailableGPXFragment f = ((AvailableGPXFragment) fragment); final AvailableGPXFragment f = ((AvailableGPXFragment) fragment);
optionsMenuAdapter.addItem(new ContextMenuItem.ItemBuilder().setTitleId(R.string.local_index_mi_upload_gpx, activity) optionsMenuAdapter.addItem(new ContextMenuItem.ItemBuilder().setTitleId(R.string.local_index_mi_upload_gpx, activity)
@ -440,7 +437,6 @@ public class OsmEditingPlugin extends OsmandPlugin {
} }
} }
public enum UploadVisibility implements IEnumWithResource { public enum UploadVisibility implements IEnumWithResource {
Public(R.string.gpxup_public), Public(R.string.gpxup_public),
Identifiable(R.string.gpxup_identifiable), Identifiable(R.string.gpxup_identifiable),
@ -462,16 +458,16 @@ public class OsmEditingPlugin extends OsmandPlugin {
} }
} }
public boolean sendGPXFiles(final Activity la, AvailableGPXFragment f, final GpxInfo... info) { public boolean sendGPXFiles(final FragmentActivity activity, AvailableGPXFragment fragment, final GpxInfo... info) {
String name = settings.USER_NAME.get(); String name = settings.USER_NAME.get();
String pwd = settings.USER_PASSWORD.get(); String pwd = settings.USER_PASSWORD.get();
String authToken = settings.USER_ACCESS_TOKEN.get(); String authToken = settings.USER_ACCESS_TOKEN.get();
if ((Algorithms.isEmpty(name) || Algorithms.isEmpty(pwd)) && Algorithms.isEmpty(authToken)) { if ((Algorithms.isEmpty(name) || Algorithms.isEmpty(pwd)) && Algorithms.isEmpty(authToken)) {
LoginBottomSheetFragment.showInstance(f.getFragmentManager(), f.getTargetFragment()); LoginBottomSheetFragment.showInstance(activity.getSupportFragmentManager(), fragment.getTargetFragment());
return false; return false;
} }
AlertDialog.Builder bldr = new AlertDialog.Builder(la); AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LayoutInflater inflater = (LayoutInflater) la.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.send_gpx_osm, null); final View view = inflater.inflate(R.layout.send_gpx_osm, null);
final EditText descr = (EditText) view.findViewById(R.id.memory_size); final EditText descr = (EditText) view.findViewById(R.id.memory_size);
if (info.length > 0 && info[0].getFileName() != null) { if (info.length > 0 && info[0].getFileName() != null) {
@ -480,23 +476,23 @@ public class OsmEditingPlugin extends OsmandPlugin {
} }
final EditText tags = (EditText) view.findViewById(R.id.TagsText); final EditText tags = (EditText) view.findViewById(R.id.TagsText);
final Spinner visibility = ((Spinner) view.findViewById(R.id.Visibility)); final Spinner visibility = ((Spinner) view.findViewById(R.id.Visibility));
EnumAdapter<UploadVisibility> adapter = new EnumAdapter<>(la, android.R.layout.simple_spinner_item, UploadVisibility.values()); EnumAdapter<UploadVisibility> adapter = new EnumAdapter<>(activity, android.R.layout.simple_spinner_item, UploadVisibility.values());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
visibility.setAdapter(adapter); visibility.setAdapter(adapter);
visibility.setSelection(0); visibility.setSelection(0);
bldr.setView(view); builder.setView(view);
bldr.setNegativeButton(R.string.shared_string_no, null); builder.setNegativeButton(R.string.shared_string_no, null);
bldr.setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() { builder.setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
new UploadGPXFilesTask(la, descr.getText().toString(), tags.getText().toString(), new UploadGPXFilesTask(activity, descr.getText().toString(), tags.getText().toString(),
(UploadVisibility) visibility.getItemAtPosition(visibility.getSelectedItemPosition()) (UploadVisibility) visibility.getItemAtPosition(visibility.getSelectedItemPosition())
).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, info); ).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, info);
} }
}); });
bldr.show(); builder.show();
return true; return true;
} }

View file

@ -2,32 +2,23 @@ package net.osmand.plus.osmedit;
import android.os.AsyncTask; import android.os.AsyncTask;
import net.osmand.plus.GpxSelectionHelper; import androidx.annotation.NonNull;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin; import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.osmedit.OsmBugsUtil.OsmBugResult; import net.osmand.plus.osmedit.OsmBugsUtil.OsmBugResult;
import java.lang.ref.WeakReference;
public class ValidateOsmLoginDetailsTask extends AsyncTask<Void, Void, OsmBugResult> { public class ValidateOsmLoginDetailsTask extends AsyncTask<Void, Void, OsmBugResult> {
private OsmandApplication app; private OsmandApplication app;
private ValidateOsmLoginListener validateOsmLoginListener; private ValidateOsmLoginListener validateListener;
public interface ValidateOsmLoginListener { public ValidateOsmLoginDetailsTask(@NonNull OsmandApplication app, ValidateOsmLoginListener validateListener) {
void loginValidationFinished(String error);
}
public ValidateOsmLoginDetailsTask(OsmandApplication app, ValidateOsmLoginListener validateTargetOsmLoginDetailsTask ) {
this.app = app; this.app = app;
this.validateOsmLoginListener = validateTargetOsmLoginDetailsTask; this.validateListener = validateListener;
} }
@Override @Override
protected OsmBugResult doInBackground(Void... params) { protected OsmBugResult doInBackground(Void... params) {
OsmEditingPlugin plugin = OsmandPlugin.getPlugin(OsmEditingPlugin.class); OsmEditingPlugin plugin = OsmandPlugin.getPlugin(OsmEditingPlugin.class);
@ -39,14 +30,20 @@ public class ValidateOsmLoginDetailsTask extends AsyncTask<Void, Void, OsmBugRes
@Override @Override
protected void onPostExecute(OsmBugResult osmBugResult) { protected void onPostExecute(OsmBugResult osmBugResult) {
if (osmBugResult.warning != null) { if (osmBugResult.warning != null) {
app.getSettings().USER_NAME.set(""); app.getSettings().USER_NAME.resetToDefault();
app.getSettings().USER_PASSWORD.set(""); app.getSettings().USER_PASSWORD.resetToDefault();
app.showToastMessage(osmBugResult.warning); app.showToastMessage(osmBugResult.warning);
} else { } else {
app.showToastMessage(R.string.osm_authorization_success); app.showToastMessage(R.string.osm_authorization_success);
} }
if (validateOsmLoginListener != null) { if (validateListener != null) {
validateOsmLoginListener.loginValidationFinished(osmBugResult.warning); validateListener.loginValidationFinished(osmBugResult.warning);
} }
} }
public interface ValidateOsmLoginListener {
void loginValidationFinished(String warning);
}
} }

View file

@ -4,13 +4,14 @@ import android.net.TrafficStats;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.webkit.WebView; import android.webkit.WebView;
import com.github.scribejava.core.model.OAuth1AccessToken; import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken; import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuthAsyncRequestCallback; import com.github.scribejava.core.model.OAuthAsyncRequestCallback;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.model.Verb;
import net.osmand.PlatformUtil;
import net.osmand.osm.oauth.OsmOAuthAuthorizationClient; import net.osmand.osm.oauth.OsmOAuthAuthorizationClient;
import net.osmand.plus.BuildConfig; import net.osmand.plus.BuildConfig;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
@ -22,14 +23,19 @@ import java.io.IOException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
public class OsmOAuthAuthorizationAdapter { public class OsmOAuthAuthorizationAdapter {
private OsmandApplication application;
private static final int THREAD_ID = 10101;
private static final String OSM_USER = "user";
private static final String DISPLAY_NAME = "display_name";
private static final String OSM_USER_DETAILS_URL = "https://api.openstreetmap.org/api/0.6/user/details";
private OsmandApplication app;
private OsmOAuthAuthorizationClient client = private OsmOAuthAuthorizationClient client =
new OsmOAuthAuthorizationClient(BuildConfig.OSM_OAUTH_CONSUMER_KEY, BuildConfig.OSM_OAUTH_CONSUMER_SECRET); new OsmOAuthAuthorizationClient(BuildConfig.OSM_OAUTH_CONSUMER_KEY, BuildConfig.OSM_OAUTH_CONSUMER_SECRET);
private static final int THREAD_ID = 10101;
public OsmOAuthAuthorizationAdapter(OsmandApplication application) { public OsmOAuthAuthorizationAdapter(OsmandApplication app) {
TrafficStats.setThreadStatsTag(THREAD_ID); TrafficStats.setThreadStatsTag(THREAD_ID);
this.application = application; this.app = app;
restoreToken(); restoreToken();
} }
@ -46,8 +52,8 @@ public class OsmOAuthAuthorizationAdapter {
} }
public void restoreToken() { public void restoreToken() {
String token = application.getSettings().USER_ACCESS_TOKEN.get(); String token = app.getSettings().USER_ACCESS_TOKEN.get();
String tokenSecret = application.getSettings().USER_ACCESS_TOKEN_SECRET.get(); String tokenSecret = app.getSettings().USER_ACCESS_TOKEN_SECRET.get();
if (!(token.isEmpty() || tokenSecret.isEmpty())) { if (!(token.isEmpty() || tokenSecret.isEmpty())) {
client.setAccessToken(new OAuth1AccessToken(token, tokenSecret)); client.setAccessToken(new OAuth1AccessToken(token, tokenSecret));
} else { } else {
@ -62,8 +68,8 @@ public class OsmOAuthAuthorizationAdapter {
private void saveToken() { private void saveToken() {
OAuth1AccessToken accessToken = client.getAccessToken(); OAuth1AccessToken accessToken = client.getAccessToken();
application.getSettings().USER_ACCESS_TOKEN.set(accessToken.getToken()); app.getSettings().USER_ACCESS_TOKEN.set(accessToken.getToken());
application.getSettings().USER_ACCESS_TOKEN_SECRET.set(accessToken.getTokenSecret()); app.getSettings().USER_ACCESS_TOKEN_SECRET.set(accessToken.getTokenSecret());
} }
private void loadWebView(ViewGroup root, String url) { private void loadWebView(ViewGroup root, String url) {
@ -77,10 +83,6 @@ public class OsmOAuthAuthorizationAdapter {
client.performGetRequest(url, callback); client.performGetRequest(url, callback);
} }
public String authorizeOsmUserDetails () throws InterruptedException, ExecutionException, IOException, XmlPullParserException {
return client.authorizeOsmUserDetails();
}
public Response performRequest(String url, String method, String body) public Response performRequest(String url, String method, String body)
throws InterruptedException, ExecutionException, IOException { throws InterruptedException, ExecutionException, IOException {
return client.performRequest(url, method, body); return client.performRequest(url, method, body);
@ -93,20 +95,28 @@ public class OsmOAuthAuthorizationAdapter {
public void authorize(String oauthVerifier) { public void authorize(String oauthVerifier) {
client.authorize(oauthVerifier); client.authorize(oauthVerifier);
String response = "";
try {
response= client.authorizeOsmUserDetails();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
saveToken(); saveToken();
application.getSettings().USER_DISPLAY_NAME.set(response);
} }
public String getUserName() throws InterruptedException, ExecutionException, IOException, XmlPullParserException {
Response response = getOsmUserDetails();
return parseUserName(response);
}
public Response getOsmUserDetails() throws InterruptedException, ExecutionException, IOException {
return performRequest(OSM_USER_DETAILS_URL, Verb.GET.name(), null);
}
public String parseUserName(Response response) throws XmlPullParserException, IOException {
String userName = null;
XmlPullParser parser = PlatformUtil.newXMLPullParser();
parser.setInput(response.getStream(), "UTF-8");
int tok;
while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (tok == XmlPullParser.START_TAG && OSM_USER.equals(parser.getName())) {
userName = parser.getAttributeValue("", DISPLAY_NAME);
}
}
return userName;
}
} }

View file

@ -1,7 +1,6 @@
package net.osmand.plus.settings.bottomsheets; package net.osmand.plus.settings.bottomsheets;
import android.content.Context; import android.content.Context;
import android.content.res.ColorStateList;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
@ -14,14 +13,14 @@ import androidx.fragment.app.FragmentManager;
import com.google.android.material.textfield.TextInputLayout; import com.google.android.material.textfield.TextInputLayout;
import net.osmand.plus.osmedit.OsmEditingFragment;
import net.osmand.plus.osmedit.ValidateOsmLoginDetailsTask;
import net.osmand.plus.settings.backend.ApplicationMode;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.UiUtilities; import net.osmand.plus.UiUtilities;
import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem;
import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem; import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem;
import net.osmand.plus.osmedit.ValidateOsmLoginDetailsTask;
import net.osmand.plus.osmedit.ValidateOsmLoginDetailsTask.ValidateOsmLoginListener;
import net.osmand.plus.settings.backend.ApplicationMode;
public class OsmLoginDataBottomSheet extends BasePreferenceBottomSheet { public class OsmLoginDataBottomSheet extends BasePreferenceBottomSheet {
@ -33,7 +32,6 @@ public class OsmLoginDataBottomSheet extends BasePreferenceBottomSheet {
private EditText userNameEditText; private EditText userNameEditText;
private EditText passwordEditText; private EditText passwordEditText;
@Override @Override
public void createMenuItems(Bundle savedInstanceState) { public void createMenuItems(Bundle savedInstanceState) {
Context context = getContext(); Context context = getContext();
@ -46,8 +44,6 @@ public class OsmLoginDataBottomSheet extends BasePreferenceBottomSheet {
userNameEditText = view.findViewById(R.id.name_edit_text); userNameEditText = view.findViewById(R.id.name_edit_text);
passwordEditText = view.findViewById(R.id.password_edit_text); passwordEditText = view.findViewById(R.id.password_edit_text);
TextInputLayout passwordBox = view.findViewById(R.id.password_text_box);
TextInputLayout loginBox = view.findViewById(R.id.name_text_box);
String name = app.getSettings().USER_NAME.get(); String name = app.getSettings().USER_NAME.get();
String password = app.getSettings().USER_PASSWORD.get(); String password = app.getSettings().USER_PASSWORD.get();
@ -59,10 +55,14 @@ public class OsmLoginDataBottomSheet extends BasePreferenceBottomSheet {
userNameEditText.setText(name); userNameEditText.setText(name);
passwordEditText.setText(password); passwordEditText.setText(password);
passwordBox.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE);
loginBox.setEndIconMode(TextInputLayout.END_ICON_CLEAR_TEXT); TextInputLayout loginBox = view.findViewById(R.id.name_text_box);
TextInputLayout passwordBox = view.findViewById(R.id.password_text_box);
passwordBox.setStartIconDrawable(R.drawable.ic_action_lock); passwordBox.setStartIconDrawable(R.drawable.ic_action_lock);
loginBox.setStartIconDrawable(R.drawable.ic_action_user_account); loginBox.setStartIconDrawable(R.drawable.ic_action_user_account);
loginBox.setEndIconMode(TextInputLayout.END_ICON_CLEAR_TEXT);
passwordBox.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE);
BaseBottomSheetItem titleItem = new SimpleBottomSheetItem.Builder() BaseBottomSheetItem titleItem = new SimpleBottomSheetItem.Builder()
.setCustomView(view) .setCustomView(view)
@ -93,13 +93,18 @@ public class OsmLoginDataBottomSheet extends BasePreferenceBottomSheet {
app.getSettings().USER_NAME.set(userNameEditText.getText().toString()); app.getSettings().USER_NAME.set(userNameEditText.getText().toString());
app.getSettings().USER_PASSWORD.set(passwordEditText.getText().toString()); app.getSettings().USER_PASSWORD.set(passwordEditText.getText().toString());
new ValidateOsmLoginDetailsTask(app, (OsmEditingFragment) getTargetFragment()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Fragment targetFragment = getTargetFragment();
if (targetFragment instanceof ValidateOsmLoginListener) {
ValidateOsmLoginDetailsTask validateTask = new ValidateOsmLoginDetailsTask(app, (ValidateOsmLoginListener) targetFragment);
validateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
dismiss(); dismiss();
} }
public static boolean showInstance(@NonNull FragmentManager fragmentManager, String key, Fragment target, public static boolean showInstance(@NonNull FragmentManager fragmentManager, String key, Fragment target,
boolean usedOnMap, @Nullable ApplicationMode appMode) { boolean usedOnMap, @Nullable ApplicationMode appMode) {
try { try {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putString(PREFERENCE_ID, key); args.putString(PREFERENCE_ID, key);