Browse Source

Merge pull request #54 from ThmmyNoLife/new_parse_task

New parse task
pull/61/merge
oogee 6 years ago
committed by GitHub
parent
commit
a83cff42d5
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 87
      app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java
  2. 61
      app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java
  3. 69
      app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java
  4. 17
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  5. 51
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java
  6. 80
      app/src/main/java/gr/thmmy/mthmmy/utils/ExternalAsyncTask.java
  7. 32
      app/src/main/java/gr/thmmy/mthmmy/utils/NetworkResultCodes.java
  8. 91
      app/src/main/java/gr/thmmy/mthmmy/utils/NetworkTask.java
  9. 20
      app/src/main/java/gr/thmmy/mthmmy/utils/Parcel.java
  10. 30
      app/src/main/java/gr/thmmy/mthmmy/utils/parsing/NewParseTask.java
  11. 6
      app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseException.java
  12. 16
      app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java

87
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.view.ViewGroup;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import android.widget.Toast;
import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter; import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter;
@ -17,21 +18,26 @@ import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import gr.thmmy.mthmmy.R; import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.base.BaseActivity; import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.base.BaseApplication;
import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.base.BaseFragment;
import gr.thmmy.mthmmy.model.Board; import gr.thmmy.mthmmy.model.Board;
import gr.thmmy.mthmmy.model.Category; import gr.thmmy.mthmmy.model.Category;
import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.CustomRecyclerView; 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.ParseException;
import gr.thmmy.mthmmy.utils.parsing.ParseTask;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar; import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber; import timber.log.Timber;
/** /**
@ -83,7 +89,7 @@ public class ForumFragment extends BaseFragment {
public void onActivityCreated(Bundle savedInstanceState) { public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); super.onActivityCreated(savedInstanceState);
if (categories.isEmpty()) { if (categories.isEmpty()) {
forumTask = new ForumTask(); forumTask = new ForumTask(this::onForumTaskStarted, this::onForumTaskFinished);
forumTask.execute(); forumTask.execute();
} }
@ -106,7 +112,7 @@ public class ForumFragment extends BaseFragment {
if (BaseActivity.getSessionManager().isLoggedIn()) { if (BaseActivity.getSessionManager().isLoggedIn()) {
if (forumTask.getStatus() == AsyncTask.Status.RUNNING) if (forumTask.getStatus() == AsyncTask.Status.RUNNING)
forumTask.cancel(true); forumTask.cancel(true);
forumTask = new ForumTask(); forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished);
forumTask.setUrl(categories.get(parentPosition).getCategoryURL()); forumTask.setUrl(categories.get(parentPosition).getCategoryURL());
forumTask.execute(); forumTask.execute();
} }
@ -117,7 +123,7 @@ public class ForumFragment extends BaseFragment {
if (BaseActivity.getSessionManager().isLoggedIn()) { if (BaseActivity.getSessionManager().isLoggedIn()) {
if (forumTask.getStatus() == AsyncTask.Status.RUNNING) if (forumTask.getStatus() == AsyncTask.Status.RUNNING)
forumTask.cancel(true); forumTask.cancel(true);
forumTask = new ForumTask(); forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished);
forumTask.setUrl(categories.get(parentPosition).getCategoryURL()); forumTask.setUrl(categories.get(parentPosition).getCategoryURL());
forumTask.execute(); forumTask.execute();
} }
@ -135,17 +141,13 @@ public class ForumFragment extends BaseFragment {
swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh);
swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary); swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary);
swipeRefreshLayout.setColorSchemeResources(R.color.accent); swipeRefreshLayout.setColorSchemeResources(R.color.accent);
swipeRefreshLayout.setOnRefreshListener( swipeRefreshLayout.setOnRefreshListener(() -> {
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (forumTask != null && forumTask.getStatus() != AsyncTask.Status.RUNNING) { if (forumTask != null && forumTask.getStatus() != AsyncTask.Status.RUNNING) {
forumTask = new ForumTask(); forumTask = new ForumTask(ForumFragment.this::onForumTaskStarted, ForumFragment.this::onForumTaskFinished);
forumTask.execute(SessionManager.indexUrl.toString()); //forumTask.execute(SessionManager.indexUrl.toString());
forumTask.execute();
} }
} }
}
); );
} }
@ -163,33 +165,38 @@ public class ForumFragment extends BaseFragment {
void onForumFragmentInteraction(Board board); 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
private final List<Category> fetchedCategories;
ForumTask() {
fetchedCategories = new ArrayList<>();
} }
protected void onPreExecute() { public void onForumTaskFinished(int resultCode, ArrayList<Category> fetchedCategories) {
progressBar.setVisibility(ProgressBar.VISIBLE); 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();
} }
@Override progressBar.setVisibility(ProgressBar.INVISIBLE);
protected Request prepareRequest(String... params) { swipeRefreshLayout.setRefreshing(false);
return new Request.Builder()
.url(forumUrl)
.build();
} }
//---------------------------------------ASYNC TASK-----------------------------------
private class ForumTask extends NewParseTask<ArrayList<Category>> {
private HttpUrl forumUrl = SessionManager.forumUrl; //may change upon collapse/expand
public ForumTask(OnParseTaskStartedListener onParseTaskStartedListener,
OnParseTaskFinishedListener<ArrayList<Category>> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, onParseTaskFinishedListener);
}
@Override @Override
public void parse(Document document) throws ParseException { protected ArrayList<Category> parse(Document document) throws ParseException {
Elements categoryBlocks = document.select(".tborder:not([style])>table[cellpadding=5]"); Elements categoryBlocks = document.select(".tborder:not([style])>table[cellpadding=5]");
if (categoryBlocks.size() != 0) { if (categoryBlocks.size() != 0) {
ArrayList<Category> fetchedCategories = new ArrayList<>();
for (Element categoryBlock : categoryBlocks) { for (Element categoryBlock : categoryBlocks) {
Element categoryElement = categoryBlock.select("td[colspan=2]>[name]").first(); Element categoryElement = categoryBlock.select("td[colspan=2]>[name]").first();
String categoryUrl = categoryElement.attr("href"); String categoryUrl = categoryElement.attr("href");
@ -207,24 +214,26 @@ public class ForumFragment extends BaseFragment {
fetchedCategories.add(category); fetchedCategories.add(category);
} }
categories.clear(); return fetchedCategories;
categories.addAll(fetchedCategories);
fetchedCategories.clear();
} else } else
throw new ParseException("Parsing failed"); throw new ParseException("Parsing failed");
} }
@Override @Override
protected void postExecution(ParseTask.ResultCode result) { protected Response sendRequest(OkHttpClient client, String... input) throws IOException {
if (result == ResultCode.SUCCESS) Request request = new Request.Builder()
forumAdapter.notifyParentDataSetChanged(false); .url(forumUrl)
.build();
return client.newCall(request).execute();
}
progressBar.setVisibility(ProgressBar.INVISIBLE); @Override
swipeRefreshLayout.setRefreshing(false); protected int getResultCode(Response response, ArrayList<Category> 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); forumUrl = HttpUrl.parse(string);
} }
} }

61
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.view.ViewGroup;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import android.widget.Toast;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.jsoup.select.Elements; import org.jsoup.select.Elements;
@ -20,13 +21,16 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import gr.thmmy.mthmmy.R; import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.base.BaseApplication;
import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.base.BaseFragment;
import gr.thmmy.mthmmy.model.TopicSummary; import gr.thmmy.mthmmy.model.TopicSummary;
import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.CustomRecyclerView; 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.ParseException;
import gr.thmmy.mthmmy.utils.parsing.ParseTask;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar; import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.Response;
import timber.log.Timber; import timber.log.Timber;
@ -79,7 +83,7 @@ public class RecentFragment extends BaseFragment {
public void onActivityCreated(Bundle savedInstanceState) { public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); super.onActivityCreated(savedInstanceState);
if (topicSummaries.isEmpty()) { if (topicSummaries.isEmpty()) {
recentTask = new RecentTask(); recentTask = new RecentTask(this::onRecentTaskStarted, this::onRecentTaskFinished);
recentTask.execute(SessionManager.indexUrl.toString()); recentTask.execute(SessionManager.indexUrl.toString());
} }
@ -109,17 +113,12 @@ public class RecentFragment extends BaseFragment {
swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); swipeRefreshLayout = rootView.findViewById(R.id.swiperefresh);
swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary); swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.primary);
swipeRefreshLayout.setColorSchemeResources(R.color.accent); swipeRefreshLayout.setColorSchemeResources(R.color.accent);
swipeRefreshLayout.setOnRefreshListener( swipeRefreshLayout.setOnRefreshListener(() -> {
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (recentTask != null && recentTask.getStatus() != AsyncTask.Status.RUNNING) { if (recentTask != null && recentTask.getStatus() != AsyncTask.Status.RUNNING) {
recentTask = new RecentTask(); recentTask = new RecentTask(this::onRecentTaskStarted, this::onRecentTaskFinished);
recentTask.execute(SessionManager.indexUrl.toString()); recentTask.execute(SessionManager.indexUrl.toString());
} }
} }
}
); );
} }
@ -138,18 +137,34 @@ public class RecentFragment extends BaseFragment {
void onRecentFragmentInteraction(TopicSummary topicSummary); void onRecentFragmentInteraction(TopicSummary topicSummary);
} }
private void onRecentTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
private void onRecentTaskFinished(int resultCode, ArrayList<TopicSummary> 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----------------------------------- //---------------------------------------ASYNC TASK-----------------------------------
private class RecentTask extends ParseTask { private class RecentTask extends NewParseTask<ArrayList<TopicSummary>> {
private List<TopicSummary> fetchedRecent;
@Override public RecentTask(OnParseTaskStartedListener onParseTaskStartedListener,
protected void onPreExecute() { OnParseTaskFinishedListener<ArrayList<TopicSummary>> onParseTaskFinishedListener) {
progressBar.setVisibility(ProgressBar.VISIBLE); super(onParseTaskStartedListener, onParseTaskFinishedListener);
fetchedRecent = new ArrayList<>();
} }
@Override @Override
public void parse(Document document) throws ParseException { protected ArrayList<TopicSummary> parse(Document document) throws ParseException {
ArrayList<TopicSummary> fetchedRecent = new ArrayList<>();
Elements recent = document.select("#block8 :first-child div"); Elements recent = document.select("#block8 :first-child div");
if (!recent.isEmpty()) { if (!recent.isEmpty()) {
for (int i = 0; i < recent.size(); i += 3) { for (int i = 0; i < recent.size(); i += 3) {
@ -184,22 +199,14 @@ public class RecentFragment extends BaseFragment {
fetchedRecent.add(new TopicSummary(link, title, lastUser, dateTime)); fetchedRecent.add(new TopicSummary(link, title, lastUser, dateTime));
} }
return; return fetchedRecent;
} }
throw new ParseException("Parsing failed"); throw new ParseException("Parsing failed");
} }
@Override @Override
protected void postExecution(ParseTask.ResultCode result) { protected int getResultCode(Response response, ArrayList<TopicSummary> data) {
if (result == ResultCode.SUCCESS) return NetworkResultCodes.SUCCESSFUL;
{
topicSummaries.clear();
topicSummaries.addAll(fetchedRecent);
recentAdapter.notifyDataSetChanged();
}
progressBar.setVisibility(ProgressBar.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
} }
} }
} }

69
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 java.util.List;
import gr.thmmy.mthmmy.R; import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.base.BaseApplication;
import gr.thmmy.mthmmy.base.BaseFragment; import gr.thmmy.mthmmy.base.BaseFragment;
import gr.thmmy.mthmmy.model.TopicSummary; import gr.thmmy.mthmmy.model.TopicSummary;
import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.CustomRecyclerView; 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 me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber; import timber.log.Timber;
/** /**
@ -83,7 +87,7 @@ public class UnreadFragment extends BaseFragment {
public void onActivityCreated(Bundle savedInstanceState) { public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); super.onActivityCreated(savedInstanceState);
if (topicSummaries.isEmpty()) { if (topicSummaries.isEmpty()) {
unreadTask = new UnreadTask(); unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished);
assert SessionManager.unreadUrl != null; assert SessionManager.unreadUrl != null;
unreadTask.execute(SessionManager.unreadUrl.toString()); unreadTask.execute(SessionManager.unreadUrl.toString());
} }
@ -126,7 +130,7 @@ public class UnreadFragment extends BaseFragment {
topicSummaries.clear(); topicSummaries.clear();
numberOfPages = 0; numberOfPages = 0;
loadedPages = 0; loadedPages = 0;
unreadTask = new UnreadTask(); unreadTask = new UnreadTask(this::onUnreadTaskStarted, this::onUnreadTaskFinished);
assert SessionManager.unreadUrl != null; assert SessionManager.unreadUrl != null;
unreadTask.execute(SessionManager.unreadUrl.toString()); unreadTask.execute(SessionManager.unreadUrl.toString());
} }
@ -151,13 +155,42 @@ public class UnreadFragment extends BaseFragment {
} }
//---------------------------------------ASYNC TASK----------------------------------- //---------------------------------------ASYNC TASK-----------------------------------
private class UnreadTask extends ParseTask {
protected void onPreExecute() { private void onUnreadTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE); 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<Void> {
UnreadTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<Void> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, onParseTaskFinishedListener);
}
@Override @Override
public void parse(Document document) { protected Void parse(Document document) throws ParseException {
Elements unread = document.select("table.bordercolor[cellspacing=1] tr:not(.titlebg)"); Elements unread = document.select("table.bordercolor[cellspacing=1] tr:not(.titlebg)");
if (!unread.isEmpty()) { if (!unread.isEmpty()) {
//topicSummaries.clear(); //topicSummaries.clear();
@ -217,28 +250,12 @@ public class UnreadFragment extends BaseFragment {
} }
topicSummaries.add(new TopicSummary(null, null, null, message)); topicSummaries.add(new TopicSummary(null, null, null, message));
} }
return null;
} }
@Override @Override
protected void postExecution(ParseTask.ResultCode result) { protected int getResultCode(Response response, Void data) {
if (result == ResultCode.SUCCESS) { return NetworkResultCodes.SUCCESSFUL;
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);
}
} }
} }
@ -282,7 +299,7 @@ public class UnreadFragment extends BaseFragment {
, "Fatal error!\n Task aborted...", Toast.LENGTH_LONG).show(); , "Fatal error!\n Task aborted...", Toast.LENGTH_LONG).show();
} else { } else {
if (unreadTask != null && unreadTask.getStatus() != AsyncTask.Status.RUNNING) { if (unreadTask != null && unreadTask.getStatus() != AsyncTask.Status.RUNNING) {
unreadTask = new UnreadTask(); unreadTask = new UnreadTask(UnreadFragment.this::onUnreadTaskStarted, UnreadFragment.this::onUnreadTaskFinished);
assert SessionManager.unreadUrl != null; assert SessionManager.unreadUrl != null;
unreadTask.execute(SessionManager.unreadUrl.toString()); unreadTask.execute(SessionManager.unreadUrl.toString());
} }

17
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.os.Handler;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat; import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDelegate; import android.support.v7.app.AppCompatDelegate;
@ -39,7 +38,6 @@ import android.widget.Toast;
import java.util.ArrayList; import java.util.ArrayList;
import gr.thmmy.mthmmy.R; 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.EditTask;
import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditTask; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditTask;
import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForReply; 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.model.ThmmyPage;
import gr.thmmy.mthmmy.utils.CustomLinearLayoutManager; import gr.thmmy.mthmmy.utils.CustomLinearLayoutManager;
import gr.thmmy.mthmmy.utils.HTMLUtils; import gr.thmmy.mthmmy.utils.HTMLUtils;
import gr.thmmy.mthmmy.utils.NetworkResultCodes;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import gr.thmmy.mthmmy.viewmodel.TopicViewModel; import gr.thmmy.mthmmy.viewmodel.TopicViewModel;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar; import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
@ -498,24 +497,16 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
progressBar.setVisibility(ProgressBar.GONE); progressBar.setVisibility(ProgressBar.GONE);
} }
}); });
viewModel.setDeleteTaskCallbacks(new DeleteTask.DeleteTaskCallbacks() { viewModel.setDeleteTaskStartedListener(() -> progressBar.setVisibility(ProgressBar.VISIBLE));
@Override viewModel.setDeleteTaskFinishedListener((resultCode, data) -> {
public void onDeleteTaskStarted() {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
public void onDeleteTaskFinished(boolean result) {
progressBar.setVisibility(ProgressBar.GONE); progressBar.setVisibility(ProgressBar.GONE);
if (resultCode == NetworkResultCodes.SUCCESSFUL) {
if (result) {
Timber.i("Post deleted successfully"); Timber.i("Post deleted successfully");
viewModel.reloadPage(); viewModel.reloadPage();
} else { } else {
Timber.w("Failed to delete post"); Timber.w("Failed to delete post");
Toast.makeText(getBaseContext(), "Delete failed!", Toast.LENGTH_SHORT).show(); Toast.makeText(getBaseContext(), "Delete failed!", Toast.LENGTH_SHORT).show();
} }
}
}); });
viewModel.setReplyFinishListener(new ReplyTask.ReplyTaskCallbacks() { viewModel.setReplyFinishListener(new ReplyTask.ReplyTaskCallbacks() {
@Override @Override

51
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/DeleteTask.java

@ -1,62 +1,39 @@
package gr.thmmy.mthmmy.activities.topic.tasks; package gr.thmmy.mthmmy.activities.topic.tasks;
import android.os.AsyncTask; import org.jsoup.nodes.Document;
import java.io.IOException; import java.io.IOException;
import gr.thmmy.mthmmy.activities.topic.Posting; import gr.thmmy.mthmmy.utils.NetworkResultCodes;
import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.utils.NetworkTask;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import timber.log.Timber;
public class DeleteTask extends AsyncTask<String, Void, Boolean> { public class DeleteTask extends NetworkTask<Void> {
private DeleteTaskCallbacks listener;
public DeleteTask(DeleteTaskCallbacks listener) { public DeleteTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<Void> onParseTaskFinishedListener) {
this.listener = listener; super(onParseTaskStartedListener, onParseTaskFinishedListener);
} }
@Override @Override
protected void onPreExecute() { protected Response sendRequest(OkHttpClient client, String... input) throws IOException {
listener.onDeleteTaskStarted();
}
@Override
protected Boolean doInBackground(String... args) {
Request delete = new Request.Builder() Request delete = new Request.Builder()
.url(args[0]) .url(input[0])
.header("User-Agent", .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") "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36")
.build(); .build();
try {
OkHttpClient client = BaseApplication.getInstance().getClient();
client.newCall(delete).execute(); client.newCall(delete).execute();
Response response = client.newCall(delete).execute(); return 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;
}
} }
@Override @Override
protected void onPostExecute(Boolean result) { protected Void performTask(Document document) {
listener.onDeleteTaskFinished(result); return null;
} }
public interface DeleteTaskCallbacks { @Override
void onDeleteTaskStarted(); protected int getResultCode(Response response, Void data) {
void onDeleteTaskFinished(boolean result); return NetworkResultCodes.SUCCESSFUL;
} }
} }

80
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<U, V> extends AsyncTask<U, Void, V> {
protected OnParseTaskStartedListener onParseTaskStartedListener;
protected OnParseTaskCancelledListener onParseTaskCancelledListener;
protected OnParseTaskFinishedListener<V> 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<V> onParseTaskFinishedListener) {
this.onParseTaskStartedListener = onParseTaskStartedListener;
this.onParseTaskCancelledListener = onParseTaskCancelledListener;
this.onParseTaskFinishedListener = onParseTaskFinishedListener;
}
public ExternalAsyncTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<V> 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<V> onParseTaskFinishedListener) {
this.onParseTaskFinishedListener = onParseTaskFinishedListener;
}
public interface OnParseTaskStartedListener {
void onParseStart();
}
public interface OnParseTaskCancelledListener {
void onParseCancel();
}
public interface OnParseTaskFinishedListener<V> {
void onParseFinish(V result);
}
}

32
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;
}

91
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<T> extends ExternalAsyncTask<String, Parcel<T>> {
protected OnParseTaskFinishedListener<T> onParseTaskFinishedListener;
public NetworkTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskCancelledListener onParseTaskCancelledListener,
OnParseTaskFinishedListener<T> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, onParseTaskCancelledListener, null);
this.onParseTaskFinishedListener = onParseTaskFinishedListener;
}
public NetworkTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<T> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, null);
this.onParseTaskFinishedListener = onParseTaskFinishedListener;
}
public NetworkTask() {}
@Override
protected final Parcel<T> 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<T> 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<T> onParseTaskFinishedListener) {
this.onParseTaskFinishedListener = onParseTaskFinishedListener;
}
public interface OnParseTaskFinishedListener<T> {
void onParseFinish(int resultCode, T data);
}
}

20
app/src/main/java/gr/thmmy/mthmmy/utils/Parcel.java

@ -0,0 +1,20 @@
package gr.thmmy.mthmmy.utils;
public class Parcel<T> {
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;
}
}

30
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<T> extends NetworkTask<T> {
public NewParseTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskCancelledListener onParseTaskCancelledListener,
OnParseTaskFinishedListener<T> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, onParseTaskCancelledListener, onParseTaskFinishedListener);
}
public NewParseTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<T> 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;
}

6
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. * ParseException is to be used for errors while parsing.
*/ */
public class ParseException extends Exception { public class ParseException extends RuntimeException {
public ParseException() {} public ParseException() {}
public ParseException(String message) public ParseException(String message)
{ {
super(message); super(message);
} }
public ParseException(String message, Throwable cause) {
super(message, cause);
}
} }

16
app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java

@ -9,8 +9,8 @@ import android.preference.PreferenceManager;
import java.util.ArrayList; import java.util.ArrayList;
import gr.thmmy.mthmmy.activities.settings.SettingsActivity; 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.EditTask;
import gr.thmmy.mthmmy.activities.topic.tasks.DeleteTask;
import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditResult; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditResult;
import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditTask; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForEditTask;
import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForReply; import gr.thmmy.mthmmy.activities.topic.tasks.PrepareForReply;
@ -50,7 +50,8 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
//callbacks for topic activity //callbacks for topic activity
private TopicTask.TopicTaskObserver topicTaskObserver; private TopicTask.TopicTaskObserver topicTaskObserver;
private DeleteTask.DeleteTaskCallbacks deleteTaskCallbacks; private DeleteTask.OnParseTaskStartedListener deleteTaskStartedListener;
private DeleteTask.OnParseTaskFinishedListener<Void> deleteTaskFinishedListener;
private ReplyTask.ReplyTaskCallbacks replyFinishListener; private ReplyTask.ReplyTaskCallbacks replyFinishListener;
private PrepareForEditTask.PrepareForEditCallbacks prepareForEditCallbacks; private PrepareForEditTask.PrepareForEditCallbacks prepareForEditCallbacks;
private EditTask.EditTaskCallbacks editTaskCallbacks; private EditTask.EditTaskCallbacks editTaskCallbacks;
@ -133,7 +134,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
public void deletePost(String postDeleteUrl) { public void deletePost(String postDeleteUrl) {
Timber.i("Deleting post"); Timber.i("Deleting post");
new DeleteTask(deleteTaskCallbacks).execute(postDeleteUrl); new DeleteTask(deleteTaskStartedListener, deleteTaskFinishedListener).execute(postDeleteUrl);
} }
public void prepareForEdit(int position, String postEditURL) { public void prepareForEdit(int position, String postEditURL) {
@ -313,8 +314,13 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
this.topicTaskObserver = topicTaskObserver; 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<Void> deleteTaskFinishedListener) {
this.deleteTaskFinishedListener = deleteTaskFinishedListener;
} }
public void setReplyFinishListener(ReplyTask.ReplyTaskCallbacks replyFinishListener) { public void setReplyFinishListener(ReplyTask.ReplyTaskCallbacks replyFinishListener) {

Loading…
Cancel
Save