diff --git a/wail-app/build.gradle b/wail-app/build.gradle index 739388b..dc9cc7a 100755 --- a/wail-app/build.gradle +++ b/wail-app/build.gradle @@ -22,7 +22,19 @@ android { packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' + exclude 'META-INF/LICENSE.txt' + exclude 'META-INF/NOTICE.txt' + exclude 'META-INF/notice.txt' + exclude 'META-INF/license.txt' + exclude 'META-INF/ASL2.0' + exclude 'META-INF/LICENSE' + exclude 'META-INF/NOTICE' } + + dexOptions { + preDexLibraries = false + } + lintOptions { disable 'InvalidPackage' } @@ -69,6 +81,14 @@ dependencies { compile 'com.melnykov:floatingactionbutton:1.1.0' compile 'com.rengwuxian.materialedittext:library:1.7.1' compile 'com.jakewharton:butterknife:5.1.2' + compile 'com.path:android-priority-jobqueue:1.1.2' + compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE' + compile 'de.greenrobot:eventbus:2.4.0' + compile('org.simpleframework:simple-xml:2.7') { + exclude module: 'stax' + exclude module: 'stax-api' + exclude module: 'xpp3' + } compile fileTree(dir: 'libs', include: '*.jar') } diff --git a/wail-app/src/main/AndroidManifest.xml b/wail-app/src/main/AndroidManifest.xml index c1b2565..9b486a9 100755 --- a/wail-app/src/main/AndroidManifest.xml +++ b/wail-app/src/main/AndroidManifest.xml @@ -54,6 +54,10 @@ android:name="com.google.analytics.tracking.android.CampaignTrackingService" android:enabled="true" /> + + { + private HttpMessageConverter inputConverter; + private HttpMessageConverter> outputConverter; + + CustomMessageConverter() { + inputConverter = new SimpleXmlHttpMessageConverter(); + outputConverter = new FormHttpMessageConverter(); + } + + @Override + public boolean canRead(Class clazz, MediaType mediaType) { + return inputConverter.canRead(clazz, mediaType); + } + + @Override + public boolean canWrite(Class clazz, MediaType mediaType) { + return outputConverter.canWrite(clazz, mediaType); + } + + @Override + public List getSupportedMediaTypes() { + List supportedMediaTypes = new ArrayList<>(inputConverter.getSupportedMediaTypes()); + supportedMediaTypes.addAll(outputConverter.getSupportedMediaTypes()); + return supportedMediaTypes; + } + + @Override + public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { + return inputConverter.read(clazz, inputMessage); + } + + @Override + @SuppressWarnings("unchecked") + public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + if (!(o instanceof MultiValueMap)) { + throw new HttpMessageNotWritableException("Can't write object " + o); + } + outputConverter.write((MultiValueMap) o, contentType, outputMessage); + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/LFAuthApi.java b/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/LFAuthApi.java deleted file mode 100755 index 73eb208..0000000 --- a/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/LFAuthApi.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.artemzin.android.wail.api.lastfm; - -import com.artemzin.android.wail.api.lastfm.model.response.LFSessionResponseModel; -import com.artemzin.android.wail.api.network.NetworkException; -import com.artemzin.android.wail.api.network.NetworkRequest; - -public class LFAuthApi { - - private LFAuthApi() {} - - public static LFSessionResponseModel getMobileSession(String apiKey, String secret, String userName, String password) - throws LFApiException, NetworkException { - - final String requestParams = new LFRequestParamContainer("auth.getMobileSession", secret) - .addParam("username", userName) - .addParam("password", password) - .addParam(LFApiCommon.PARAM_API_KEY, apiKey) - .generateRequestParamsAsStringWithSign(); - - return LFSessionResponseModel.parseFromJson(NetworkRequest.newPostRequestInstance(LFApiCommon.API_ROOT_URL, requestParams) - .getResponse()); - } -} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/LastFmClient.java b/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/LastFmClient.java new file mode 100644 index 0000000..bfb1c5c --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/LastFmClient.java @@ -0,0 +1,157 @@ +package com.artemzin.android.wail.api.lastfm; + +import com.artemzin.android.wail.api.MD5Hash; +import com.artemzin.android.wail.api.lastfm.model.LastFmSession; +import com.artemzin.android.wail.events.InvalidUsernamePasswordEvent; +import com.artemzin.android.wail.events.NetworkErrorEvent; +import com.artemzin.android.wail.events.ServiceUnavailableEvent; +import com.artemzin.android.wail.events.UnknownLoginErrorEvent; +import com.artemzin.android.wail.storage.WAILSettings; + +import org.simpleframework.xml.Attribute; +import org.simpleframework.xml.Element; +import org.simpleframework.xml.Root; +import org.springframework.http.HttpRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.xml.SimpleXmlHttpMessageConverter; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.ResponseErrorHandler; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import de.greenrobot.event.EventBus; + +/** + * @author Ilya Murzinov + */ +public class LastFmClient { + public static final String API_ROOT_URL = "https://ws.audioscrobbler.com/2.0/"; + + public static final String PARAM_API_KEY = "api_key"; + public static final String PARAM_API_SIG = "api_sig"; + public static final String PARAM_SK = "sk"; + + public static final int INVALID_USERNAME_PASSWORD = 4; + public static final int SERVICE_UNAVAILABLE = 11; + + private final RestTemplate restTemplate; + + public LastFmClient() { + restTemplate = new RestTemplate(); + + restTemplate.setMessageConverters( + Collections.>singletonList(new CustomMessageConverter()) + ); + restTemplate.setInterceptors(Collections.singletonList(new ClientHttpRequestInterceptor() { + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + request.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); + return execution.execute(request, body); + } + })); + restTemplate.setErrorHandler(new LastFmResponseErrorHandler()); + } + + public LastFmSession authenticate(String username, String password) { + MultiValueMap request = new LinkedMultiValueMap<>(); + request.add("method", "auth.getMobileSession"); + request.add("username", username); + request.add("password", password); + try { + return restTemplate.postForObject( + API_ROOT_URL, + generateSignedRequest(request), + LastFmSession.class + ); + } catch (RestClientException e) { + EventBus.getDefault().post(new NetworkErrorEvent()); + throw e; + } + } + + private MultiValueMap generateSignedRequest(MultiValueMap request) { + MultiValueMap result = new LinkedMultiValueMap<>(request); + + result.add(PARAM_API_KEY, WAILSettings.getLastfmApiKey()); + + StringBuilder stringBuilder = new StringBuilder(); + List>> entrySet = new ArrayList<>(result.entrySet()); + Collections.sort(entrySet, new Comparator>>() { + @Override + public int compare(Map.Entry> lhs, Map.Entry> rhs) { + return String.CASE_INSENSITIVE_ORDER.compare(lhs.getKey(), rhs.getKey()); + } + }); + for (Map.Entry> entry : entrySet) { + stringBuilder.append(entry.getKey()).append(entry.getValue().get(0)); + } + stringBuilder.append(WAILSettings.getLastfmSecret()); + result.add(PARAM_API_SIG, MD5Hash.calculateMD5(stringBuilder.toString())); + return result; + } + + private static class LastFmResponseErrorHandler implements ResponseErrorHandler { + private ErrorResponse errorResponse; + + @Override + public boolean hasError(ClientHttpResponse response) throws IOException { + if (response.getStatusCode() != HttpStatus.OK) { + errorResponse = (ErrorResponse) new SimpleXmlHttpMessageConverter().read(ErrorResponse.class, response); + return true; + } + return false; + } + + @Override + public void handleError(ClientHttpResponse response) throws IOException { + if (errorResponse.getError().getCode() == INVALID_USERNAME_PASSWORD) { + EventBus.getDefault().post(new InvalidUsernamePasswordEvent()); + } else if (errorResponse.getError().getCode() == SERVICE_UNAVAILABLE) { + EventBus.getDefault().post(new ServiceUnavailableEvent()); + } else { + EventBus.getDefault().post(new UnknownLoginErrorEvent()); + } + throw new RuntimeException(); + } + } + + @Root(name = "lfm", strict = false) + private static class ErrorResponse { + @Element(name = "error") + private Error error; + + public Error getError() { + return error; + } + + public void setError(Error error) { + this.error = error; + } + + public static class Error { + @Attribute(name = "code") + private int code; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + } + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/model/LastFmSession.java b/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/model/LastFmSession.java new file mode 100644 index 0000000..7aa5c40 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/model/LastFmSession.java @@ -0,0 +1,39 @@ +package com.artemzin.android.wail.api.lastfm.model; + +import org.simpleframework.xml.Element; +import org.simpleframework.xml.Root; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +@Root(name = "lfm", strict = false) +public class LastFmSession { + @Element(name = "session", required = true) + private Session session; + + public Session getSession() { + return session; + } + + public void setSession(Session session) { + this.session = session; + } + + public static class Session { + private String name; + private String key; + private String subscriber; + + public String getName() { + return name; + } + + public String getKey() { + return key; + } + + public String getSubscriber() { + return subscriber; + } + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/model/response/LFSessionResponseModel.java b/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/model/response/LFSessionResponseModel.java deleted file mode 100755 index e8b6346..0000000 --- a/wail-app/src/main/java/com/artemzin/android/wail/api/lastfm/model/response/LFSessionResponseModel.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.artemzin.android.wail.api.lastfm.model.response; - -import com.artemzin.android.wail.api.lastfm.LFApiException; - -import org.json.JSONException; -import org.json.JSONObject; - -public class LFSessionResponseModel extends LFBaseResponseModel { - - private String name; - private String key; - private String subscriber; - - protected LFSessionResponseModel(String json) throws LFApiException { - super(json); - } - - public static LFSessionResponseModel parseFromJson(String json) throws LFApiException { - try { - final LFSessionResponseModel sessionModel = new LFSessionResponseModel(json); - final JSONObject sessionJson = sessionModel.getJsonObject().getJSONObject("session"); - - sessionModel.name = sessionJson.optString("name"); - sessionModel.key = sessionJson.optString("key"); - sessionModel.subscriber = sessionJson.optString("subscriber"); - - return sessionModel; - } catch (JSONException e) { - throw LFApiException.newDataFormatErrorInstance(null, e.getMessage()); - } - } - - public String getName() { - return name; - } - - public String getKey() { - return key; - } - - public String getSubscriber() { - return subscriber; - } -} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/events/InvalidUsernamePasswordEvent.java b/wail-app/src/main/java/com/artemzin/android/wail/events/InvalidUsernamePasswordEvent.java new file mode 100644 index 0000000..1eb021e --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/events/InvalidUsernamePasswordEvent.java @@ -0,0 +1,7 @@ +package com.artemzin.android.wail.events; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class InvalidUsernamePasswordEvent { +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/events/LoginButtonClickedEvent.java b/wail-app/src/main/java/com/artemzin/android/wail/events/LoginButtonClickedEvent.java new file mode 100644 index 0000000..23d2604 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/events/LoginButtonClickedEvent.java @@ -0,0 +1,22 @@ +package com.artemzin.android.wail.events; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class LoginButtonClickedEvent { + private final String username; + private final String password; + + public LoginButtonClickedEvent(String username, String password) { + this.username = username; + this.password = password; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/events/NetworkErrorEvent.java b/wail-app/src/main/java/com/artemzin/android/wail/events/NetworkErrorEvent.java new file mode 100644 index 0000000..ccbf19a --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/events/NetworkErrorEvent.java @@ -0,0 +1,7 @@ +package com.artemzin.android.wail.events; + +/** + * @author Ilya Murzinov + */ +public class NetworkErrorEvent { +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/events/ServiceUnavailableEvent.java b/wail-app/src/main/java/com/artemzin/android/wail/events/ServiceUnavailableEvent.java new file mode 100644 index 0000000..31e0d66 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/events/ServiceUnavailableEvent.java @@ -0,0 +1,7 @@ +package com.artemzin.android.wail.events; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class ServiceUnavailableEvent { +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/events/SuccessfulLoginEvent.java b/wail-app/src/main/java/com/artemzin/android/wail/events/SuccessfulLoginEvent.java new file mode 100644 index 0000000..0a47bdf --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/events/SuccessfulLoginEvent.java @@ -0,0 +1,18 @@ +package com.artemzin.android.wail.events; + +import com.artemzin.android.wail.api.lastfm.model.LastFmSession; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class SuccessfulLoginEvent { + private final LastFmSession session; + + public SuccessfulLoginEvent(LastFmSession session) { + this.session = session; + } + + public LastFmSession getSession() { + return session; + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/events/UnknownLoginErrorEvent.java b/wail-app/src/main/java/com/artemzin/android/wail/events/UnknownLoginErrorEvent.java new file mode 100644 index 0000000..fb6c3b0 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/events/UnknownLoginErrorEvent.java @@ -0,0 +1,7 @@ +package com.artemzin.android.wail.events; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class UnknownLoginErrorEvent { +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/service/JobAdapter.java b/wail-app/src/main/java/com/artemzin/android/wail/service/JobAdapter.java new file mode 100644 index 0000000..6792a67 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/service/JobAdapter.java @@ -0,0 +1,33 @@ +package com.artemzin.android.wail.service; + +import com.path.android.jobqueue.Job; +import com.path.android.jobqueue.Params; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class JobAdapter extends Job { + protected JobAdapter(int priority) { + super(new Params(priority)); + } + + @Override + public void onAdded() { + + } + + @Override + public void onRun() throws Throwable { + + } + + @Override + protected void onCancel() { + + } + + @Override + protected boolean shouldReRunOnThrowable(Throwable throwable) { + return false; + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/service/JobManagerService.java b/wail-app/src/main/java/com/artemzin/android/wail/service/JobManagerService.java new file mode 100644 index 0000000..033a668 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/service/JobManagerService.java @@ -0,0 +1,36 @@ +package com.artemzin.android.wail.service; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +import com.path.android.jobqueue.Job; +import com.path.android.jobqueue.JobManager; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class JobManagerService extends Service { + private static JobManagerService instance; + private JobManager jobManager; + + public static JobManagerService getInstance() { + return instance; + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public void onCreate() { + super.onCreate(); + jobManager = new JobManager(getApplicationContext()); + instance = this; + } + + public void execute(Job job) { + jobManager.addJobInBackground(job); + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/service/LastFmEventHandler.java b/wail-app/src/main/java/com/artemzin/android/wail/service/LastFmEventHandler.java new file mode 100644 index 0000000..a88ec87 --- /dev/null +++ b/wail-app/src/main/java/com/artemzin/android/wail/service/LastFmEventHandler.java @@ -0,0 +1,25 @@ +package com.artemzin.android.wail.service; + +import com.artemzin.android.wail.api.lastfm.LastFmClient; +import com.artemzin.android.wail.events.LoginButtonClickedEvent; +import com.artemzin.android.wail.events.SuccessfulLoginEvent; + +import de.greenrobot.event.EventBus; + +/** + * @author Ilya Murzinov [murz42@gmail.com] + */ +public class LastFmEventHandler { + private LastFmClient client = new LastFmClient(); + + public void onEvent(final LoginButtonClickedEvent event) { + JobManagerService.getInstance().execute(new JobAdapter(1) { + @Override + public void onRun() throws Throwable { + EventBus.getDefault().post(new SuccessfulLoginEvent( + client.authenticate(event.getUsername(), event.getPassword()) + )); + } + }); + } +} diff --git a/wail-app/src/main/java/com/artemzin/android/wail/ui/fragment/LastfmLoginFragment.java b/wail-app/src/main/java/com/artemzin/android/wail/ui/fragment/LastfmLoginFragment.java index 15d9ac4..9e4e050 100755 --- a/wail-app/src/main/java/com/artemzin/android/wail/ui/fragment/LastfmLoginFragment.java +++ b/wail-app/src/main/java/com/artemzin/android/wail/ui/fragment/LastfmLoginFragment.java @@ -2,9 +2,7 @@ import android.app.Activity; import android.app.AlertDialog; -import android.os.AsyncTask; import android.os.Bundle; -import android.os.SystemClock; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -15,15 +13,13 @@ import com.artemzin.android.bytes.common.StringUtil; import com.artemzin.android.wail.R; -import com.artemzin.android.wail.api.lastfm.LFApiException; -import com.artemzin.android.wail.api.lastfm.LFAuthApi; -import com.artemzin.android.wail.api.lastfm.model.response.LFSessionResponseModel; -import com.artemzin.android.wail.api.network.NetworkException; +import com.artemzin.android.wail.events.InvalidUsernamePasswordEvent; +import com.artemzin.android.wail.events.LoginButtonClickedEvent; +import com.artemzin.android.wail.events.NetworkErrorEvent; +import com.artemzin.android.wail.events.ServiceUnavailableEvent; +import com.artemzin.android.wail.events.SuccessfulLoginEvent; +import com.artemzin.android.wail.events.UnknownLoginErrorEvent; import com.artemzin.android.wail.storage.WAILSettings; -import com.artemzin.android.wail.storage.db.PlayersDBHelper; -import com.artemzin.android.wail.storage.db.TracksDBHelper; -import com.artemzin.android.wail.util.AsyncTaskExecutor; -import com.artemzin.android.wail.util.ThreadUtil; import com.artemzin.android.wail.util.validation.TextValidator; import com.google.analytics.tracking.android.EasyTracker; import com.google.analytics.tracking.android.MapBuilder; @@ -31,11 +27,10 @@ import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; +import de.greenrobot.event.EventBus; public class LastfmLoginFragment extends BaseFragment { - private final String GA_EVENT_LOGIN_LASTFM = "LastfmLogin"; - @InjectView(R.id.lastfm_login_login_edit_text) public EditText loginEditText; @@ -46,6 +41,7 @@ public class LastfmLoginFragment extends BaseFragment { public Button loginButton; private TextValidator loginValidator, passwordValidator; + private AlertDialog progressDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -55,114 +51,79 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa @OnClick(R.id.lastfm_login_login_button) public void onLoginButtonClick(View v) { - final String userName = loginEditText.getText().toString(); + final String username = loginEditText.getText().toString(); final String password = passwordEditText.getText().toString(); View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_progress_dialog, null); ((TextView) view.findViewById(R.id.progress_dialog_message)).setText(getString(R.string.lastfm_logging_progress_dialog_message)); - final AlertDialog progressDialog = new AlertDialog.Builder(getActivity()) + progressDialog = new AlertDialog.Builder(getActivity()) .setView(view) .setCancelable(false) .show(); - AsyncTaskExecutor.executeConcurrently(new AsyncTask() { + EventBus.getDefault().post(new LoginButtonClickedEvent(username, password)); + } - NetworkException networkException; - LFApiException lfApiException; - LFSessionResponseModel sessionModel; + @SuppressWarnings("UnusedDeclaration") + public void onEventMainThread(InvalidUsernamePasswordEvent event) { + sendReport("failed with LastFmException: Invalid username or password"); - @Override - protected Void doInBackground(Void... params) { - final long requestStartTime = SystemClock.elapsedRealtime(); - - EasyTracker.getInstance(getActivity()).send( - MapBuilder.createEvent(GA_EVENT_LOGIN_LASTFM, - "started login", - null, - 1L) - .build() - ); - - try { - sessionModel = LFAuthApi.getMobileSession( - WAILSettings.getLastfmApiKey(), - WAILSettings.getLastfmSecret(), - userName, - password - ); - - // if new logged user is not same to previous we should clear all prev user's dat - final String prevLastfmUserName = WAILSettings.getLastfmUserName(getActivity()); - - if (!StringUtil.isNullOrEmpty(prevLastfmUserName) && !prevLastfmUserName.equals(userName)) { - WAILSettings.setEnabled(getActivity(), false); - - PlayersDBHelper.getInstance(getActivity()).removeAll(); - TracksDBHelper.getInstance(getActivity()).deleteAll(); - } + progressDialog.dismiss(); + Toast.makeText(getActivity(), getString(R.string.lastfm_logging_api_error_4), Toast.LENGTH_LONG).show(); + } - } catch (NetworkException e) { - networkException = e; - EasyTracker.getInstance(getActivity()).send( - MapBuilder.createEvent(GA_EVENT_LOGIN_LASTFM, - "failed with NetworkException: " + e.getMessage(), - null, - 0L) - .build() - ); - } catch (LFApiException e) { - lfApiException = e; - EasyTracker.getInstance(getActivity()).send( - MapBuilder.createEvent(GA_EVENT_LOGIN_LASTFM, - "failed with LFApiException: " + e.getMessage(), - null, - 0L) - .build() - ); - } + @SuppressWarnings("UnusedDeclaration") + public void onEventMainThread(ServiceUnavailableEvent event) { + sendReport("failed with LastFmException: Service unavailable"); - ThreadUtil.sleepIfRequired(requestStartTime, 2000); + progressDialog.dismiss(); + Toast.makeText(getActivity(), getString(R.string.lastfm_api_error_11), Toast.LENGTH_LONG).show(); + } - return null; - } + @SuppressWarnings("UnusedDeclaration") + public void onEventMainThread(UnknownLoginErrorEvent event) { + sendReport("failed with LastFmException: Unknown LastFm error"); - @Override - protected void onPostExecute(Void aVoid) { - progressDialog.dismiss(); - - if (networkException != null) { - Toast.makeText(getActivity(), getString(R.string.lastfm_logging_network_error), Toast.LENGTH_LONG).show(); - } else if (lfApiException != null) { - if ("4".equals(lfApiException.getError())) { - Toast.makeText(getActivity(), getString(R.string.lastfm_logging_api_error_4), Toast.LENGTH_LONG).show(); - } else if ("11".equals(lfApiException.getError())) { - Toast.makeText(getActivity(), getString(R.string.lastfm_api_error_11), Toast.LENGTH_LONG).show(); - } else { - Toast.makeText(getActivity(), getString(R.string.lastfm_logging_api_error_unknown), Toast.LENGTH_LONG).show(); - } - } else { - - if (sessionModel != null && sessionModel.getKey() != null) { - WAILSettings.setLastfmSessionKey(getActivity(), sessionModel.getKey()); - WAILSettings.setLastfmUserName(getActivity(), userName); - WAILSettings.setEnabled(getActivity(), true); - getActivity().setResult(Activity.RESULT_OK); - - EasyTracker.getInstance(getActivity()).send( - MapBuilder.createEvent(GA_EVENT_LOGIN_LASTFM, - "login success", - null, - 1L) - .build() - ); - - getActivity().finish(); - } - } - } - }); + progressDialog.dismiss(); + Toast.makeText(getActivity(), getString(R.string.lastfm_logging_api_error_unknown), Toast.LENGTH_LONG).show(); } + @SuppressWarnings("UnusedDeclaration") + public void onEventMainThread(SuccessfulLoginEvent event) { + sendReport("login success"); + + WAILSettings.setLastfmSessionKey(getActivity(), event.getSession().getSession().getKey()); + WAILSettings.setLastfmUserName(getActivity(), event.getSession().getSession().getName()); + WAILSettings.setEnabled(getActivity(), true); + + getActivity().setResult(Activity.RESULT_OK); + getActivity().finish(); + } + + @SuppressWarnings("UnusedDeclaration") + public void onEventMainThread(NetworkErrorEvent event) { + sendReport("failed with NetworkException"); + + progressDialog.dismiss(); + Toast.makeText(getActivity(), getString(R.string.lastfm_logging_network_error), Toast.LENGTH_LONG).show(); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public void onResume() { + super.onResume(); + EventBus.getDefault().register(this); + } + + @Override + public void onPause() { + super.onPause(); + EventBus.getDefault().unregister(this); + } @Override public void onViewCreated(View view, Bundle savedInstanceState) { @@ -221,4 +182,16 @@ private void changeLoginButtonState() { && passwordValidator.isValid() != null && passwordValidator.isValid() ); } + + private void sendReport(String msg) { + String GA_EVENT_LOGIN_LASTFM = "LastfmLogin"; + EasyTracker.getInstance(getActivity()).send( + MapBuilder.createEvent(GA_EVENT_LOGIN_LASTFM, + msg, + null, + 0L) + .build() + ); + } + }