Browse Source

Merge branch 'develop' into polls

pull/55/head
Thodoris1999 6 years ago
parent
commit
a4fabfd5a1
  1. 89
      app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java
  2. 67
      app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java
  3. 71
      app/src/main/java/gr/thmmy/mthmmy/activities/main/unread/UnreadFragment.java
  4. 28
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  5. 53
      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

89
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<Category> 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<Category> 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<ArrayList<Category>> {
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<ArrayList<Category>> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, onParseTaskFinishedListener);
}
@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]");
if (categoryBlocks.size() != 0) {
ArrayList<Category> 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<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);
}
}

67
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<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-----------------------------------
private class RecentTask extends ParseTask {
private List<TopicSummary> fetchedRecent;
private class RecentTask extends NewParseTask<ArrayList<TopicSummary>> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(ProgressBar.VISIBLE);
fetchedRecent = new ArrayList<>();
public RecentTask(OnParseTaskStartedListener onParseTaskStartedListener,
OnParseTaskFinishedListener<ArrayList<TopicSummary>> onParseTaskFinishedListener) {
super(onParseTaskStartedListener, onParseTaskFinishedListener);
}
@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");
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<TopicSummary> data) {
return NetworkResultCodes.SUCCESSFUL;
}
}
}

71
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<Void> {
UnreadTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<Void> 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());
}

28
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java

@ -38,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 +51,7 @@ import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.model.TopicItem;
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 +498,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() {

53
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<String, Void, Boolean> {
private DeleteTaskCallbacks listener;
public class DeleteTask extends NetworkTask<Void> {
public DeleteTask(DeleteTaskCallbacks listener) {
this.listener = listener;
public DeleteTask(OnParseTaskStartedListener onParseTaskStartedListener, OnParseTaskFinishedListener<Void> 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;
}
}

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.
*/
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);
}
}

16
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;
@ -52,7 +52,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<Void> deleteTaskFinishedListener;
private ReplyTask.ReplyTaskCallbacks replyFinishListener;
private PrepareForEditTask.PrepareForEditCallbacks prepareForEditCallbacks;
private EditTask.EditTaskCallbacks editTaskCallbacks;
@ -135,7 +136,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) {
@ -325,8 +326,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<Void> deleteTaskFinishedListener) {
this.deleteTaskFinishedListener = deleteTaskFinishedListener;
}
public void setReplyFinishListener(ReplyTask.ReplyTaskCallbacks replyFinishListener) {

Loading…
Cancel
Save