diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java b/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java index 3b6366b4..ceb41e13 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java @@ -10,6 +10,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; +import android.widget.Toast; import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter; @@ -17,21 +18,26 @@ import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import gr.thmmy.mthmmy.R; import gr.thmmy.mthmmy.base.BaseActivity; +import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.model.Board; import gr.thmmy.mthmmy.model.Category; import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.utils.CustomRecyclerView; +import gr.thmmy.mthmmy.utils.NetworkResultCodes; +import gr.thmmy.mthmmy.utils.parsing.NewParseTask; import gr.thmmy.mthmmy.utils.parsing.ParseException; -import gr.thmmy.mthmmy.utils.parsing.ParseTask; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; import okhttp3.Request; +import okhttp3.Response; import timber.log.Timber; /** @@ -83,7 +89,7 @@ public class ForumFragment extends BaseFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (categories.isEmpty()) { - forumTask = new ForumTask(); + forumTask = new ForumTask(this::onForumTaskStarted, this::onForumTaskFinished); forumTask.execute(); } @@ -106,7 +112,7 @@ public class ForumFragment extends BaseFragment { if (BaseActivity.getSessionManager().isLoggedIn()) { if (forumTask.getStatus() == AsyncTask.Status.RUNNING) forumTask.cancel(true); - forumTask = new ForumTask(); + forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished); forumTask.setUrl(categories.get(parentPosition).getCategoryURL()); forumTask.execute(); } @@ -117,7 +123,7 @@ public class ForumFragment extends BaseFragment { if (BaseActivity.getSessionManager().isLoggedIn()) { if (forumTask.getStatus() == AsyncTask.Status.RUNNING) forumTask.cancel(true); - forumTask = new ForumTask(); + forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished); forumTask.setUrl(categories.get(parentPosition).getCategoryURL()); forumTask.execute(); } @@ -135,16 +141,12 @@ public class ForumFragment extends BaseFragment { swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary); swipeRefreshLayout.setColorSchemeResources(R.color.accent); - swipeRefreshLayout.setOnRefreshListener( - new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - if (forumTask != null && forumTask.getStatus() != AsyncTask.Status.RUNNING) { - forumTask = new ForumTask(); - forumTask.execute(SessionManager.indexUrl.toString()); - } + swipeRefreshLayout.setOnRefreshListener(() -> { + if (forumTask != null && forumTask.getStatus() != AsyncTask.Status.RUNNING) { + forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished); + //forumTask.execute(SessionManager.indexUrl.toString()); + forumTask.execute(); } - } ); @@ -163,33 +165,38 @@ public class ForumFragment extends BaseFragment { void onForumFragmentInteraction(Board board); } - //---------------------------------------ASYNC TASK----------------------------------- + public void onForumTaskStarted() { + progressBar.setVisibility(ProgressBar.VISIBLE); + } - private class ForumTask extends ParseTask { - private HttpUrl forumUrl = SessionManager.forumUrl; //may change upon collapse/expand + public void onForumTaskFinished(int resultCode, ArrayList fetchedCategories) { + if (resultCode == NetworkResultCodes.SUCCESSFUL) { + categories.clear(); + categories.addAll(fetchedCategories); + forumAdapter.notifyParentDataSetChanged(false); + } else if (resultCode == NetworkResultCodes.NETWORK_ERROR) { + Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show(); + } - private final List fetchedCategories; + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + } - ForumTask() { - fetchedCategories = new ArrayList<>(); - } + //---------------------------------------ASYNC TASK----------------------------------- - protected void onPreExecute() { - progressBar.setVisibility(ProgressBar.VISIBLE); - } + private class ForumTask extends NewParseTask> { + private HttpUrl forumUrl = SessionManager.forumUrl; //may change upon collapse/expand - @Override - protected Request prepareRequest(String... params) { - return new Request.Builder() - .url(forumUrl) - .build(); + public ForumTask(OnParseTaskStartedListener onParseTaskStartedListener, + OnParseTaskFinishedListener> onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } - @Override - public void parse(Document document) throws ParseException { + protected ArrayList parse(Document document) throws ParseException { Elements categoryBlocks = document.select(".tborder:not([style])>table[cellpadding=5]"); if (categoryBlocks.size() != 0) { + ArrayList fetchedCategories = new ArrayList<>(); for (Element categoryBlock : categoryBlocks) { Element categoryElement = categoryBlock.select("td[colspan=2]>[name]").first(); String categoryUrl = categoryElement.attr("href"); @@ -207,24 +214,26 @@ public class ForumFragment extends BaseFragment { fetchedCategories.add(category); } - categories.clear(); - categories.addAll(fetchedCategories); - fetchedCategories.clear(); + return fetchedCategories; } else throw new ParseException("Parsing failed"); } @Override - protected void postExecution(ParseTask.ResultCode result) { - if (result == ResultCode.SUCCESS) - forumAdapter.notifyParentDataSetChanged(false); + protected Response sendRequest(OkHttpClient client, String... input) throws IOException { + Request request = new Request.Builder() + .url(forumUrl) + .build(); + return client.newCall(request).execute(); + } - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); + @Override + protected int getResultCode(Response response, ArrayList data) { + return NetworkResultCodes.SUCCESSFUL; } - public void setUrl(String string) //TODO delete and simplify e.g. in prepareRequest possible? - { + //TODO delete and simplify e.g. in prepareRequest possible? + public void setUrl(String string) { forumUrl = HttpUrl.parse(string); } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java b/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java index aee35e37..98ad7f69 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java @@ -10,6 +10,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; +import android.widget.Toast; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; @@ -20,13 +21,16 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import gr.thmmy.mthmmy.R; +import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.model.TopicSummary; import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.utils.CustomRecyclerView; +import gr.thmmy.mthmmy.utils.NetworkResultCodes; +import gr.thmmy.mthmmy.utils.parsing.NewParseTask; import gr.thmmy.mthmmy.utils.parsing.ParseException; -import gr.thmmy.mthmmy.utils.parsing.ParseTask; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; +import okhttp3.Response; import timber.log.Timber; @@ -79,7 +83,7 @@ public class RecentFragment extends BaseFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (topicSummaries.isEmpty()) { - recentTask = new RecentTask(); + recentTask = new RecentTask(this::onRecentTaskStarted, this::onRecentTaskFinished); recentTask.execute(SessionManager.indexUrl.toString()); } @@ -109,16 +113,11 @@ public class RecentFragment extends BaseFragment { swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary); swipeRefreshLayout.setColorSchemeResources(R.color.accent); - swipeRefreshLayout.setOnRefreshListener( - new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - if (recentTask != null && recentTask.getStatus() != AsyncTask.Status.RUNNING) { - recentTask = new RecentTask(); - recentTask.execute(SessionManager.indexUrl.toString()); - } + swipeRefreshLayout.setOnRefreshListener(() -> { + if (recentTask != null && recentTask.getStatus() != AsyncTask.Status.RUNNING) { + recentTask = new RecentTask(this::onRecentTaskStarted, this::onRecentTaskFinished); + recentTask.execute(SessionManager.indexUrl.toString()); } - } ); } @@ -138,18 +137,34 @@ public class RecentFragment extends BaseFragment { void onRecentFragmentInteraction(TopicSummary topicSummary); } + private void onRecentTaskStarted() { + progressBar.setVisibility(ProgressBar.VISIBLE); + } + + private void onRecentTaskFinished(int resultCode, ArrayList fetchedRecent) { + if (resultCode == NetworkResultCodes.SUCCESSFUL) { + topicSummaries.clear(); + topicSummaries.addAll(fetchedRecent); + recentAdapter.notifyDataSetChanged(); + } else if (resultCode == NetworkResultCodes.NETWORK_ERROR) { + Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show(); + } + + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + } + //---------------------------------------ASYNC TASK----------------------------------- - private class RecentTask extends ParseTask { - private List fetchedRecent; + private class RecentTask extends NewParseTask> { - @Override - protected void onPreExecute() { - progressBar.setVisibility(ProgressBar.VISIBLE); - fetchedRecent = new ArrayList<>(); + public RecentTask(OnParseTaskStartedListener onParseTaskStartedListener, + OnParseTaskFinishedListener> onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } @Override - public void parse(Document document) throws ParseException { + protected ArrayList parse(Document document) throws ParseException { + ArrayList fetchedRecent = new ArrayList<>(); Elements recent = document.select("#block8 :first-child div"); if (!recent.isEmpty()) { for (int i = 0; i < recent.size(); i += 3) { @@ -174,7 +189,7 @@ public class RecentFragment extends BaseFragment { dateTime.contains(" πμ") || dateTime.contains(" μμ")) { dateTime = dateTime.replaceAll(":[0-5][0-9] ", " "); } else { - dateTime=dateTime.substring(0,dateTime.lastIndexOf(":")); + dateTime = dateTime.substring(0, dateTime.lastIndexOf(":")); } if (!dateTime.contains(",")) { dateTime = dateTime.replaceAll(".+? ([0-9])", "$1"); @@ -184,22 +199,14 @@ public class RecentFragment extends BaseFragment { fetchedRecent.add(new TopicSummary(link, title, lastUser, dateTime)); } - return; + return fetchedRecent; } throw new ParseException("Parsing failed"); } @Override - protected void postExecution(ParseTask.ResultCode result) { - if (result == ResultCode.SUCCESS) - { - topicSummaries.clear(); - topicSummaries.addAll(fetchedRecent); - recentAdapter.notifyDataSetChanged(); - } - - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); + protected int getResultCode(Response response, ArrayList data) { + return NetworkResultCodes.SUCCESSFUL; } } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java b/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java index b18874d5..0681c4af 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java @@ -22,13 +22,17 @@ import java.util.ArrayList; import java.util.List; import gr.thmmy.mthmmy.R; +import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.model.TopicSummary; import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.utils.CustomRecyclerView; -import gr.thmmy.mthmmy.utils.parsing.ParseTask; +import gr.thmmy.mthmmy.utils.NetworkResultCodes; +import gr.thmmy.mthmmy.utils.parsing.NewParseTask; +import gr.thmmy.mthmmy.utils.parsing.ParseException; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; import okhttp3.Request; +import okhttp3.Response; import timber.log.Timber; /** @@ -83,7 +87,7 @@ public class UnreadFragment extends BaseFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (topicSummaries.isEmpty()) { - unreadTask = new UnreadTask(); + unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished); assert SessionManager.unreadUrl != null; unreadTask.execute(SessionManager.unreadUrl.toString()); } @@ -126,7 +130,7 @@ public class UnreadFragment extends BaseFragment { topicSummaries.clear(); numberOfPages = 0; loadedPages = 0; - unreadTask = new UnreadTask(); + unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished); assert SessionManager.unreadUrl != null; unreadTask.execute(SessionManager.unreadUrl.toString()); } @@ -151,13 +155,42 @@ public class UnreadFragment extends BaseFragment { } //---------------------------------------ASYNC TASK----------------------------------- - private class UnreadTask extends ParseTask { - protected void onPreExecute() { - progressBar.setVisibility(ProgressBar.VISIBLE); + + private void onUnreadTaskStarted() { + progressBar.setVisibility(ProgressBar.VISIBLE); + } + + private void onUnreadTaskFinished(int resultCode, Void data) { + if (resultCode == NetworkResultCodes.SUCCESSFUL) { + unreadAdapter.notifyDataSetChanged(); + + ++loadedPages; + if (loadedPages < numberOfPages) { + unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished); + assert SessionManager.unreadUrl != null; + unreadTask.execute(SessionManager.unreadUrl.toString() + ";start=" + loadedPages * 20); + } + else { + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + } + } + else{ + progressBar.setVisibility(ProgressBar.INVISIBLE); + swipeRefreshLayout.setRefreshing(false); + if (resultCode == NetworkResultCodes.NETWORK_ERROR) + Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show(); + } + } + + private class UnreadTask extends NewParseTask { + + UnreadTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } @Override - public void parse(Document document) { + protected Void parse(Document document) throws ParseException { Elements unread = document.select("table.bordercolor[cellspacing=1] tr:not(.titlebg)"); if (!unread.isEmpty()) { //topicSummaries.clear(); @@ -217,28 +250,12 @@ public class UnreadFragment extends BaseFragment { } topicSummaries.add(new TopicSummary(null, null, null, message)); } + return null; } @Override - protected void postExecution(ParseTask.ResultCode result) { - if (result == ResultCode.SUCCESS) { - unreadAdapter.notifyDataSetChanged(); - - ++loadedPages; - if (loadedPages < numberOfPages) { - unreadTask = new UnreadTask(); - assert SessionManager.unreadUrl != null; - unreadTask.execute(SessionManager.unreadUrl.toString() + ";start=" + loadedPages * 20); - } - else { - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); - } - } - else{ - progressBar.setVisibility(ProgressBar.INVISIBLE); - swipeRefreshLayout.setRefreshing(false); - } + protected int getResultCode(Response response, Void data) { + return NetworkResultCodes.SUCCESSFUL; } } @@ -282,7 +299,7 @@ public class UnreadFragment extends BaseFragment { , "Fatal error!\n Task aborted...", Toast.LENGTH_LONG).show(); } else { if (unreadTask != null && unreadTask.getStatus() != AsyncTask.Status.RUNNING) { - unreadTask = new UnreadTask(); + unreadTask = new UnreadTask(UnreadFragment.this::onUnreadTaskStarted, UnreadFragment.this::onUnreadTaskFinished); assert SessionManager.unreadUrl != null; unreadTask.execute(SessionManager.unreadUrl.toString()); } diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java b/app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java index 953f7ad8..00e16471 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java @@ -12,7 +12,6 @@ import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; -import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatDelegate; @@ -39,7 +38,6 @@ import android.widget.Toast; import java.util.ArrayList; import gr.thmmy.mthmmy.R; -import gr.thmmy.mthmmy.activities.topic.tasks.DeleteTask; import gr.thmmy.mthmmy.activities.topic.tasks.EditTask; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditTask; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForReply; @@ -52,6 +50,7 @@ import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.ThmmyPage; import gr.thmmy.mthmmy.utils.CustomLinearLayoutManager; import gr.thmmy.mthmmy.utils.HTMLUtils; +import gr.thmmy.mthmmy.utils.NetworkResultCodes; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.viewmodel.TopicViewModel; import me.zhanghai.android.materialprogressbar.MaterialProgressBar; @@ -498,23 +497,15 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo progressBar.setVisibility(ProgressBar.GONE); } }); - viewModel.setDeleteTaskCallbacks(new DeleteTask.DeleteTaskCallbacks() { - @Override - public void onDeleteTaskStarted() { - progressBar.setVisibility(ProgressBar.VISIBLE); - } - - @Override - public void onDeleteTaskFinished(boolean result) { - progressBar.setVisibility(ProgressBar.GONE); - - if (result) { - Timber.i("Post deleted successfully"); - viewModel.reloadPage(); - } else { - Timber.w("Failed to delete post"); - Toast.makeText(getBaseContext(), "Delete failed!", Toast.LENGTH_SHORT).show(); - } + viewModel.setDeleteTaskStartedListener(() -> progressBar.setVisibility(ProgressBar.VISIBLE)); + viewModel.setDeleteTaskFinishedListener((resultCode, data) -> { + progressBar.setVisibility(ProgressBar.GONE); + if (resultCode == NetworkResultCodes.SUCCESSFUL) { + Timber.i("Post deleted successfully"); + viewModel.reloadPage(); + } else { + Timber.w("Failed to delete post"); + Toast.makeText(getBaseContext(), "Delete failed!", Toast.LENGTH_SHORT).show(); } }); viewModel.setReplyFinishListener(new ReplyTask.ReplyTaskCallbacks() { diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java b/app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java index 0a9486b1..41563ae5 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java @@ -1,62 +1,39 @@ package gr.thmmy.mthmmy.activities.topic.tasks; -import android.os.AsyncTask; +import org.jsoup.nodes.Document; import java.io.IOException; -import gr.thmmy.mthmmy.activities.topic.Posting; -import gr.thmmy.mthmmy.base.BaseApplication; +import gr.thmmy.mthmmy.utils.NetworkResultCodes; +import gr.thmmy.mthmmy.utils.NetworkTask; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -import timber.log.Timber; -public class DeleteTask extends AsyncTask { - private DeleteTaskCallbacks listener; +public class DeleteTask extends NetworkTask { - public DeleteTask(DeleteTaskCallbacks listener) { - this.listener = listener; + public DeleteTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); } @Override - protected void onPreExecute() { - listener.onDeleteTaskStarted(); - } - - @Override - protected Boolean doInBackground(String... args) { + protected Response sendRequest(OkHttpClient client, String... input) throws IOException { Request delete = new Request.Builder() - .url(args[0]) + .url(input[0]) .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36") .build(); - - try { - OkHttpClient client = BaseApplication.getInstance().getClient(); - client.newCall(delete).execute(); - Response response = client.newCall(delete).execute(); - //Response response = client.newCall(delete).execute(); - switch (Posting.replyStatus(response)) { - case SUCCESSFUL: - BaseApplication.getInstance().logFirebaseAnalyticsEvent("post_deletion", null); - return true; - default: - Timber.e("Something went wrong. Request string: %s", delete.toString()); - return false; - } - } catch (IOException e) { - Timber.e(e, "Delete failed."); - return false; - } + client.newCall(delete).execute(); + return client.newCall(delete).execute(); } @Override - protected void onPostExecute(Boolean result) { - listener.onDeleteTaskFinished(result); + protected Void performTask(Document document) { + return null; } - public interface DeleteTaskCallbacks { - void onDeleteTaskStarted(); - void onDeleteTaskFinished(boolean result); + @Override + protected int getResultCode(Response response, Void data) { + return NetworkResultCodes.SUCCESSFUL; } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/ExternalAsyncTask.java b/app/src/main/java/gr/thmmy/mthmmy/utils/ExternalAsyncTask.java new file mode 100644 index 00000000..82b535b6 --- /dev/null +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/ExternalAsyncTask.java @@ -0,0 +1,80 @@ +package gr.thmmy.mthmmy.utils; + +import android.os.AsyncTask; + +public abstract class ExternalAsyncTask extends AsyncTask { + + protected OnParseTaskStartedListener onParseTaskStartedListener; + protected OnParseTaskCancelledListener onParseTaskCancelledListener; + protected OnParseTaskFinishedListener onParseTaskFinishedListener; + + @Override + protected void onPreExecute() { + if (onParseTaskStartedListener != null) + onParseTaskStartedListener.onParseStart(); + else + super.onPreExecute(); + } + + @Override + protected void onCancelled() { + if (onParseTaskCancelledListener != null) + onParseTaskCancelledListener.onParseCancel(); + else + super.onCancelled(); + } + + @Override + protected void onCancelled(V v) { + if (onParseTaskCancelledListener != null) + onParseTaskCancelledListener.onParseCancel(); + else + super.onCancelled(); + } + + @Override + protected void onPostExecute(V v) { + if (onParseTaskFinishedListener != null) + onParseTaskFinishedListener.onParseFinish(v); + else + super.onPostExecute(v); + } + + public ExternalAsyncTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskCancelledListener onParseTaskCancelledListener, + OnParseTaskFinishedListener onParseTaskFinishedListener) { + this.onParseTaskStartedListener = onParseTaskStartedListener; + this.onParseTaskCancelledListener = onParseTaskCancelledListener; + this.onParseTaskFinishedListener = onParseTaskFinishedListener; + } + + public ExternalAsyncTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener onParseTaskFinishedListener) { + this.onParseTaskStartedListener = onParseTaskStartedListener; + this.onParseTaskFinishedListener = onParseTaskFinishedListener; + } + + public ExternalAsyncTask() { } + + public void setOnParseTaskStartedListener(OnParseTaskStartedListener onParseTaskStartedListener) { + this.onParseTaskStartedListener = onParseTaskStartedListener; + } + + public void setOnParseTaskCancelledListener(OnParseTaskCancelledListener onParseTaskCancelledListener) { + this.onParseTaskCancelledListener = onParseTaskCancelledListener; + } + + public void setOnParseTaskFinishedListener(OnParseTaskFinishedListener onParseTaskFinishedListener) { + this.onParseTaskFinishedListener = onParseTaskFinishedListener; + } + + public interface OnParseTaskStartedListener { + void onParseStart(); + } + + public interface OnParseTaskCancelledListener { + void onParseCancel(); + } + + public interface OnParseTaskFinishedListener { + void onParseFinish(V result); + } +} diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/NetworkResultCodes.java b/app/src/main/java/gr/thmmy/mthmmy/utils/NetworkResultCodes.java new file mode 100644 index 00000000..90cd8771 --- /dev/null +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/NetworkResultCodes.java @@ -0,0 +1,32 @@ +package gr.thmmy.mthmmy.utils; + +public class NetworkResultCodes { + /** + * The request was successful + */ + public static final int SUCCESSFUL = 0; + /** + * Error 404, page was not found + */ + public static final int NOT_FOUND = 1; + /** + * User session ended while posting the reply + */ + public static final int SESSION_ENDED = 2; + /** + * Exception occured while parsing + */ + public static final int PARSE_ERROR = 3; + /** + * Other undefined of unidentified error + */ + public static final int OTHER_ERROR = 4; + /** + * Failed to connect to thmmy.gr + */ + public static final int NETWORK_ERROR = 5; + /** + * Error while excecuting NetworkTask's performTask() + */ + public static final int PERFORM_TASK_ERROR = 6; +} diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/NetworkTask.java b/app/src/main/java/gr/thmmy/mthmmy/utils/NetworkTask.java new file mode 100644 index 00000000..6793120a --- /dev/null +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/NetworkTask.java @@ -0,0 +1,91 @@ +package gr.thmmy.mthmmy.utils; + +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; + +import java.io.IOException; + +import gr.thmmy.mthmmy.base.BaseApplication; +import gr.thmmy.mthmmy.utils.parsing.ParseException; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import timber.log.Timber; + +public abstract class NetworkTask extends ExternalAsyncTask> { + + protected OnParseTaskFinishedListener onParseTaskFinishedListener; + + public NetworkTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskCancelledListener onParseTaskCancelledListener, + OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskCancelledListener, null); + this.onParseTaskFinishedListener = onParseTaskFinishedListener; + } + + public NetworkTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, null); + this.onParseTaskFinishedListener = onParseTaskFinishedListener; + } + + public NetworkTask() {} + + @Override + protected final Parcel doInBackground(String... input) { + Response response; + try { + response = sendRequest(BaseApplication.getInstance().getClient(), input); + } catch (IOException e) { + Timber.e(e, "Error connecting to thmmy.gr"); + return new Parcel<>(NetworkResultCodes.NETWORK_ERROR, null); + } + String responseBodyString; + try { + responseBodyString = response.body().string(); + } catch (NullPointerException npe) { + Timber.wtf(npe, "Invalid response. Detatails: https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#body--"); + return new Parcel<>(NetworkResultCodes.NETWORK_ERROR, null); + } catch (IOException e) { + Timber.e(e, "Error getting response body string"); + return new Parcel<>(NetworkResultCodes.NETWORK_ERROR, null); + } + try { + T data = performTask(Jsoup.parse(responseBodyString)); + int resultCode = getResultCode(response, data); + return new Parcel<>(resultCode, data); + } catch (ParseException pe) { + Timber.e(pe); + return new Parcel<>(NetworkResultCodes.PARSE_ERROR, null); + } catch (Exception e) { + Timber.e(e); + return new Parcel<>(NetworkResultCodes.PERFORM_TASK_ERROR, null); + } + } + + @Override + protected void onPostExecute(Parcel tParcel) { + if (onParseTaskFinishedListener != null) + onParseTaskFinishedListener.onParseFinish(tParcel.getResultCode(), tParcel.getData()); + else + super.onPostExecute(tParcel); + } + + protected Response sendRequest(OkHttpClient client, String... input) throws IOException { + String url = input[0]; + Request request = new Request.Builder() + .url(url) + .build(); + return client.newCall(request).execute(); + } + + protected abstract T performTask(Document document); + + protected abstract int getResultCode(Response response, T data); + + public void setOnParseTaskFinishedListener(OnParseTaskFinishedListener onParseTaskFinishedListener) { + this.onParseTaskFinishedListener = onParseTaskFinishedListener; + } + + public interface OnParseTaskFinishedListener { + void onParseFinish(int resultCode, T data); + } +} diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/Parcel.java b/app/src/main/java/gr/thmmy/mthmmy/utils/Parcel.java new file mode 100644 index 00000000..83e65285 --- /dev/null +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/Parcel.java @@ -0,0 +1,20 @@ +package gr.thmmy.mthmmy.utils; + +public class Parcel { + + private int resultCode; + private T data; + + public Parcel(int resultCode, T data) { + this.resultCode = resultCode; + this.data = data; + } + + public int getResultCode() { + return resultCode; + } + + public T getData() { + return data; + } +} diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NewParseTask.java b/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NewParseTask.java new file mode 100644 index 00000000..51749f2a --- /dev/null +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NewParseTask.java @@ -0,0 +1,30 @@ +package gr.thmmy.mthmmy.utils.parsing; + +import org.jsoup.nodes.Document; + +import gr.thmmy.mthmmy.utils.NetworkTask; + +public abstract class NewParseTask extends NetworkTask { + + public NewParseTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskCancelledListener onParseTaskCancelledListener, + OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskCancelledListener, onParseTaskFinishedListener); + } + + public NewParseTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener onParseTaskFinishedListener) { + super(onParseTaskStartedListener, onParseTaskFinishedListener); + } + + public NewParseTask() {} + + @Override + protected final T performTask(Document document) { + try { + return parse(document); + } catch (Exception e) { + throw new ParseException("Parse failed.", e); + } + } + + protected abstract T parse (Document document) throws ParseException; +} diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseException.java b/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseException.java index fea7be6b..942e789b 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseException.java +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseException.java @@ -3,11 +3,15 @@ package gr.thmmy.mthmmy.utils.parsing; /** * ParseException is to be used for errors while parsing. */ -public class ParseException extends Exception { +public class ParseException extends RuntimeException { public ParseException() {} public ParseException(String message) { super(message); } + + public ParseException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java b/app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java index 96cecf4a..78284b11 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java +++ b/app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java @@ -9,8 +9,8 @@ import android.preference.PreferenceManager; import java.util.ArrayList; import gr.thmmy.mthmmy.activities.settings.SettingsActivity; -import gr.thmmy.mthmmy.activities.topic.tasks.DeleteTask; import gr.thmmy.mthmmy.activities.topic.tasks.EditTask; +import gr.thmmy.mthmmy.activities.topic.tasks.DeleteTask; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditResult; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditTask; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForReply; @@ -50,7 +50,8 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa //callbacks for topic activity private TopicTask.TopicTaskObserver topicTaskObserver; - private DeleteTask.DeleteTaskCallbacks deleteTaskCallbacks; + private DeleteTask.OnParseTaskStartedListener deleteTaskStartedListener; + private DeleteTask.OnParseTaskFinishedListener deleteTaskFinishedListener; private ReplyTask.ReplyTaskCallbacks replyFinishListener; private PrepareForEditTask.PrepareForEditCallbacks prepareForEditCallbacks; private EditTask.EditTaskCallbacks editTaskCallbacks; @@ -133,7 +134,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa public void deletePost(String postDeleteUrl) { Timber.i("Deleting post"); - new DeleteTask(deleteTaskCallbacks).execute(postDeleteUrl); + new DeleteTask(deleteTaskStartedListener, deleteTaskFinishedListener).execute(postDeleteUrl); } public void prepareForEdit(int position, String postEditURL) { @@ -313,8 +314,13 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa this.topicTaskObserver = topicTaskObserver; } - public void setDeleteTaskCallbacks(DeleteTask.DeleteTaskCallbacks deleteTaskCallbacks) { - this.deleteTaskCallbacks = deleteTaskCallbacks; + + public void setDeleteTaskStartedListener(DeleteTask.OnParseTaskStartedListener deleteTaskStartedListener) { + this.deleteTaskStartedListener = deleteTaskStartedListener; + } + + public void setDeleteTaskFinishedListener(DeleteTask.OnParseTaskFinishedListener deleteTaskFinishedListener) { + this.deleteTaskFinishedListener = deleteTaskFinishedListener; } public void setReplyFinishListener(ReplyTask.ReplyTaskCallbacks replyFinishListener) {