Browse Source

fix issues with topic, cleanup

pull/43/head
Thodoris1999 6 years ago
parent
commit
9f3d0be3c9
  1. 78
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  2. 11
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java
  3. 53
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTask.java
  4. 31
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTaskResult.java
  5. 20
      app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseHelpers.java
  6. 131
      app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java

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

@ -45,6 +45,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.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;
import timber.log.Timber; import timber.log.Timber;
@ -206,36 +207,41 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
pageIndicator.setText(String.valueOf(pageIndicatorIndex) + "/" + pageIndicator.setText(String.valueOf(pageIndicatorIndex) + "/" +
String.valueOf(viewModel.getPageCount())); String.valueOf(viewModel.getPageCount()));
}); });
viewModel.getTopicTaskResult().observe(this, topicTaskResult -> { viewModel.getTopicTitle().observe(this, newTopicTitle -> {
if (topicTaskResult == null) { if (newTopicTitle == null) return;
progressBar.setVisibility(ProgressBar.VISIBLE); toolbarTitle.setText(newTopicTitle);
} else { });
switch (topicTaskResult.getResultCode()) { viewModel.getPageTopicId().observe(this, pageTopicId -> {
case SUCCESS: if (pageTopicId == null) return;
if (topicTitle == null || Objects.equals(topicTitle, "") if (viewModel.getCurrentPageIndex() == viewModel.getPageCount()) {
|| !Objects.equals(topicTitle, topicTaskResult.getTopicTitle())) {
toolbarTitle.setText(topicTaskResult.getTopicTitle());
}
recyclerView.getRecycledViewPool().clear(); //Avoid inconsistency detected bug
postsList.clear();
postsList.addAll(topicTaskResult.getNewPostsList());
topicAdapter.notifyDataSetChanged();
paginationEnabled(true);
if (topicTaskResult.getCurrentPageIndex() == topicTaskResult.getPageCount()) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) if (notificationManager != null)
notificationManager.cancel(NEW_POST_TAG, topicTaskResult.getLoadedPageTopicId()); notificationManager.cancel(NEW_POST_TAG, pageTopicId);
} }
});
progressBar.setVisibility(ProgressBar.GONE); viewModel.getReplyPageUrl().observe(this, replyPageUrl -> {
if (topicTaskResult.getReplyPageUrl() == null) if (replyPageUrl == null)
replyFAB.hide(); replyFAB.hide();
else else
replyFAB.show(); replyFAB.show();
recyclerView.scrollToPosition(topicTaskResult.getFocusedPostIndex()); });
viewModel.getPostsList().observe(this, postList -> {
if (postList == null) onTopicTaskStarted();
recyclerView.getRecycledViewPool().clear(); //Avoid inconsistency detected bug
postsList.clear();
postsList.addAll(postList);
topicAdapter.notifyDataSetChanged();
});
viewModel.getFocusedPostIndex().observe(this, focusedPostIndex -> {
if (focusedPostIndex == null) return;
recyclerView.scrollToPosition(focusedPostIndex);
});
viewModel.getTopicTaskResultCode().observe(this, resultCode -> {
if (resultCode == null) return;
switch (resultCode) {
case SUCCESS:
paginationEnabled(true);
progressBar.setVisibility(ProgressBar.GONE);
break; break;
case NETWORK_ERROR: case NETWORK_ERROR:
Toast.makeText(getBaseContext(), "Network Error", Toast.LENGTH_SHORT).show(); Toast.makeText(getBaseContext(), "Network Error", Toast.LENGTH_SHORT).show();
@ -251,8 +257,6 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
finish(); finish();
break; break;
} }
}
}); });
viewModel.getPrepareForReplyResult().observe(this, prepareForReplyResult -> { viewModel.getPrepareForReplyResult().observe(this, prepareForReplyResult -> {
if (prepareForReplyResult != null) { if (prepareForReplyResult != null) {
@ -277,7 +281,7 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
bottomNavBar.setVisibility(View.GONE); bottomNavBar.setVisibility(View.GONE);
} }
}); });
viewModel.initialLoad(topicPageUrl); viewModel.loadUrl(topicPageUrl);
} }
@Override @Override
@ -307,18 +311,14 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
TextView usersViewing = infoDialog.findViewById(R.id.users_viewing); TextView usersViewing = infoDialog.findViewById(R.id.users_viewing);
usersViewing.setText(new SpannableStringBuilder("Loading...")); usersViewing.setText(new SpannableStringBuilder("Loading..."));
usersViewing.setMovementMethod(LinkMovementMethod.getInstance()); usersViewing.setMovementMethod(LinkMovementMethod.getInstance());
viewModel.getTopicTaskResult().observe(this, topicTaskResult -> { viewModel.getTopicTreeAndMods().observe(this, topicTreeAndMods -> {
if (topicTaskResult == null) { if (topicTreeAndMods == null) return;
usersViewing.setText(new SpannableStringBuilder("Loading...")); treeAndMods.setText(HTMLUtils.getSpannableFromHtml(this, topicTreeAndMods));
treeAndMods.setText(new SpannableStringBuilder("Loading...")); });
} else { viewModel.getTopicViewers().observe(this, topicViewers -> {
String treeAndModsString = topicTaskResult.getTopicTreeAndMods(); if (topicViewers == null) return;
treeAndMods.setText(HTMLUtils.getSpannableFromHtml(this, treeAndModsString)); usersViewing.setText(HTMLUtils.getSpannableFromHtml(this, topicViewers));
String topicViewersString = topicTaskResult.getTopicViewers();
usersViewing.setText(HTMLUtils.getSpannableFromHtml(this, topicViewersString));
}
}); });
builder.setView(infoDialog); builder.setView(infoDialog);
AlertDialog dialog = builder.create(); AlertDialog dialog = builder.create();
dialog.show(); dialog.show();
@ -559,7 +559,7 @@ public class TopicActivity extends BaseActivity implements TopicTask.TopicTaskOb
if (success) { if (success) {
if ((postsList.get(postsList.size() - 1).getPostNumber() + 1) % 15 == 0) { if ((postsList.get(postsList.size() - 1).getPostNumber() + 1) % 15 == 0) {
viewModel.loadUrl(viewModel.getBaseUrl() + "." + 2147483647); viewModel.loadUrl(ParseHelpers.getBaseURL(viewModel.getTopicUrl()) + "." + 2147483647);
} else { } else {
viewModel.reloadPage(); viewModel.reloadPage();
} }

11
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java

@ -46,6 +46,7 @@ import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyFile; import gr.thmmy.mthmmy.model.ThmmyFile;
import gr.thmmy.mthmmy.model.ThmmyPage; import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.utils.CircleTransform; import gr.thmmy.mthmmy.utils.CircleTransform;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import gr.thmmy.mthmmy.viewmodel.TopicViewModel; import gr.thmmy.mthmmy.viewmodel.TopicViewModel;
import timber.log.Timber; import timber.log.Timber;
@ -628,8 +629,7 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
if (target.is(ThmmyPage.PageCategory.TOPIC)) { if (target.is(ThmmyPage.PageCategory.TOPIC)) {
//This url points to a topic //This url points to a topic
//Checks if the page to be loaded is the one already shown //Checks if the page to be loaded is the one already shown
if (uriString.contains(viewModel.getBaseUrl())) { if (uriString.contains(ParseHelpers.getBaseURL(viewModel.getTopicUrl()))) {
Timber.e("reached here!");
if (uriString.contains("topicseen#new") || uriString.contains("#new")) { if (uriString.contains("topicseen#new") || uriString.contains("#new")) {
if (viewModel.getCurrentPageIndex() == viewModel.getPageCount()) { if (viewModel.getCurrentPageIndex() == viewModel.getPageCount()) {
//same page //same page
@ -643,7 +643,6 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
if (tmpUrlSbstr.contains("msg")) if (tmpUrlSbstr.contains("msg"))
tmpUrlSbstr = tmpUrlSbstr.substring(0, tmpUrlSbstr.indexOf("msg") - 1); tmpUrlSbstr = tmpUrlSbstr.substring(0, tmpUrlSbstr.indexOf("msg") - 1);
int testAgainst = Integer.parseInt(tmpUrlSbstr); int testAgainst = Integer.parseInt(tmpUrlSbstr);
Timber.e("reached tthere! %s", testAgainst);
for (int i = 0; i < postsList.size(); i++) { for (int i = 0; i < postsList.size(); i++) {
if (postsList.get(i).getPostIndex() == testAgainst) { if (postsList.get(i).getPostIndex() == testAgainst) {
//same page //same page
@ -652,11 +651,11 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
return true; return true;
} }
} }
} else if ((Objects.equals(uriString, viewModel.getBaseUrl()) && viewModel.getCurrentPageIndex() == 1) || } else if ((Objects.equals(uriString, ParseHelpers.getBaseURL(viewModel.getTopicUrl())) &&
Integer.parseInt(uriString.substring(viewModel.getBaseUrl().length() + 1)) / 15 + 1 == viewModel.getCurrentPageIndex() == 1) ||
Integer.parseInt(uriString.substring(ParseHelpers.getBaseURL(viewModel.getTopicUrl()).length() + 1)) / 15 + 1 ==
viewModel.getCurrentPageIndex()) { viewModel.getCurrentPageIndex()) {
//same page //same page
Timber.e("ha");
return true; return true;
} }
} }

53
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTask.java

@ -43,18 +43,6 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
@Override @Override
protected TopicTaskResult doInBackground(String... strings) { protected TopicTaskResult doInBackground(String... strings) {
String topicTitle = null;
String topicTreeAndMods = "";
String topicViewers = "";
ArrayList<Post> newPostsList = null;
int loadedPageTopicId = -1;
int focusedPostIndex = 0;
SparseArray<String> pagesUrls = new SparseArray<>();
int currentPageIndex = 1;
int pageCount = 1;
String baseUrl = "";
String lastPageLoadAttemptedUrl = "";
Document topic = null; Document topic = null;
String newPageUrl = strings[0]; String newPageUrl = strings[0];
@ -70,14 +58,9 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
} }
} }
lastPageLoadAttemptedUrl = newPageUrl;
if (strings[0].substring(0, strings[0].lastIndexOf(".")).contains("topic="))
baseUrl = strings[0].substring(0, strings[0].lastIndexOf(".")); //New topic's base url
String replyPageUrl = null;
Request request = new Request.Builder() Request request = new Request.Builder()
.url(newPageUrl) .url(newPageUrl)
.build(); .build();
ResultCode resultCode;
try { try {
Response response = BaseApplication.getInstance().getClient().newCall(request).execute(); Response response = BaseApplication.getInstance().getClient().newCall(request).execute();
topic = Jsoup.parse(response.body().string()); topic = Jsoup.parse(response.body().string());
@ -85,17 +68,18 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
ParseHelpers.Language language = ParseHelpers.Language.getLanguage(topic); ParseHelpers.Language language = ParseHelpers.Language.getLanguage(topic);
//Finds topic's tree, mods and users viewing //Finds topic's tree, mods and users viewing
topicTreeAndMods = topic.select("div.nav").first().html(); String topicTreeAndMods = topic.select("div.nav").first().html();
topicViewers = TopicParser.parseUsersViewingThisTopic(topic, language); String topicViewers = TopicParser.parseUsersViewingThisTopic(topic, language);
//Finds reply page url //Finds reply page url
String replyPageUrl = null;
Element replyButton = topic.select("a:has(img[alt=Reply])").first(); Element replyButton = topic.select("a:has(img[alt=Reply])").first();
if (replyButton == null) if (replyButton == null)
replyButton = topic.select("a:has(img[alt=Απάντηση])").first(); replyButton = topic.select("a:has(img[alt=Απάντηση])").first();
if (replyButton != null) replyPageUrl = replyButton.attr("href"); if (replyButton != null) replyPageUrl = replyButton.attr("href");
//Finds topic title if missing //Finds topic title if missing
topicTitle = topic.select("td[id=top_subject]").first().text(); String topicTitle = topic.select("td[id=top_subject]").first().text();
if (topicTitle.contains("Topic:")) { if (topicTitle.contains("Topic:")) {
topicTitle = topicTitle.substring(topicTitle.indexOf("Topic:") + 7 topicTitle = topicTitle.substring(topicTitle.indexOf("Topic:") + 7
, topicTitle.indexOf("(Read") - 2); , topicTitle.indexOf("(Read") - 2);
@ -106,42 +90,39 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
} }
//Finds current page's index //Finds current page's index
currentPageIndex = TopicParser.parseCurrentPageIndex(topic, language); int currentPageIndex = TopicParser.parseCurrentPageIndex(topic, language);
//Finds number of pages //Finds number of pages
pageCount = TopicParser.parseTopicNumberOfPages(topic, currentPageIndex, language); int pageCount = TopicParser.parseTopicNumberOfPages(topic, currentPageIndex, language);
for (int i = 0; i < pageCount; i++) { ArrayList<Post> newPostsList = TopicParser.parseTopic(topic, language);
//Generate each page's url from topic's base url +".15*numberOfPage"
pagesUrls.put(i, baseUrl + "." + String.valueOf(i * 15));
}
newPostsList = TopicParser.parseTopic(topic, language);
loadedPageTopicId = Integer.parseInt(ThmmyPage.getTopicId(lastPageLoadAttemptedUrl)); int loadedPageTopicId = Integer.parseInt(ThmmyPage.getTopicId(newPageUrl));
//Finds the position of the focused message if present //Finds the position of the focused message if present
int focusedPostIndex = 0;
for (int i = 0; i < newPostsList.size(); ++i) { for (int i = 0; i < newPostsList.size(); ++i) {
if (newPostsList.get(i).getPostIndex() == postFocus) { if (newPostsList.get(i).getPostIndex() == postFocus) {
focusedPostIndex = i; focusedPostIndex = i;
break; break;
} }
} }
resultCode = ResultCode.SUCCESS; return new TopicTaskResult(ResultCode.SUCCESS, topicTitle, replyPageUrl, newPostsList, loadedPageTopicId,
currentPageIndex, pageCount, focusedPostIndex, topicTreeAndMods, topicViewers);
} catch (IOException e) { } catch (IOException e) {
Timber.i(e, "IO Exception"); Timber.i(e, "IO Exception");
resultCode = ResultCode.NETWORK_ERROR; return new TopicTaskResult(ResultCode.NETWORK_ERROR, null, null, null,
0, 0, 0, 0, null, null);
} catch (Exception e) { } catch (Exception e) {
if (isUnauthorized(topic)) { if (isUnauthorized(topic)) {
resultCode = ResultCode.UNAUTHORIZED; return new TopicTaskResult(ResultCode.UNAUTHORIZED, null, null, null,
0, 0, 0, 0, null, null);
} else { } else {
Timber.e(e, "Parsing Error"); Timber.e(e, "Parsing Error");
resultCode = ResultCode.PARSING_ERROR; return new TopicTaskResult(ResultCode.PARSING_ERROR, null, null, null,
0, 0, 0, 0, null, null);
} }
} }
return new TopicTaskResult(resultCode, baseUrl, topicTitle, replyPageUrl, newPostsList,
loadedPageTopicId, currentPageIndex, pageCount, focusedPostIndex, topicTreeAndMods,
topicViewers, lastPageLoadAttemptedUrl, pagesUrls);
} }
private boolean isUnauthorized(Document document) { private boolean isUnauthorized(Document document) {

31
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTaskResult.java

@ -9,13 +9,6 @@ import gr.thmmy.mthmmy.model.Post;
public class TopicTaskResult { public class TopicTaskResult {
private final TopicTask.ResultCode resultCode; private final TopicTask.ResultCode resultCode;
/**
* Holds this topic's base url. For example a topic with url similar to
* "https://www.thmmy.gr/smf/index.php?topic=1.15;topicseen" or
* "https://www.thmmy.gr/smf/index.php?topic=1.msg1#msg1"
* has the base url "https://www.thmmy.gr/smf/index.php?topic=1"
*/
private final String baseUrl;
/** /**
* Holds this topic's title. At first this gets the value of the topic title that came with * Holds this topic's title. At first this gets the value of the topic title that came with
* bundle and is rendered in the toolbar while parsing this topic. Later, if a different topic * bundle and is rendered in the toolbar while parsing this topic. Later, if a different topic
@ -46,18 +39,12 @@ public class TopicTaskResult {
//Topic's info related //Topic's info related
private final String topicTreeAndMods; private final String topicTreeAndMods;
private final String topicViewers; private final String topicViewers;
/**
* The url of the last page that was attempted to be loaded
*/
private final String lastPageLoadAttemptedUrl;
private final SparseArray<String> pagesUrls;
public TopicTaskResult(TopicTask.ResultCode resultCode, String baseUrl, String topicTitle, public TopicTaskResult(TopicTask.ResultCode resultCode, String topicTitle,
String replyPageUrl, ArrayList<Post> newPostsList, int loadedPageTopicId, String replyPageUrl, ArrayList<Post> newPostsList, int loadedPageTopicId,
int currentPageIndex, int pageCount, int focusedPostIndex, String topicTreeAndMods, int currentPageIndex, int pageCount, int focusedPostIndex, String topicTreeAndMods,
String topicViewers, String lastPageLoadAttemptedUrl, SparseArray<String> pagesUrls) { String topicViewers) {
this.resultCode = resultCode; this.resultCode = resultCode;
this.baseUrl = baseUrl;
this.topicTitle = topicTitle; this.topicTitle = topicTitle;
this.replyPageUrl = replyPageUrl; this.replyPageUrl = replyPageUrl;
this.newPostsList = newPostsList; this.newPostsList = newPostsList;
@ -67,18 +54,12 @@ public class TopicTaskResult {
this.focusedPostIndex = focusedPostIndex; this.focusedPostIndex = focusedPostIndex;
this.topicTreeAndMods = topicTreeAndMods; this.topicTreeAndMods = topicTreeAndMods;
this.topicViewers = topicViewers; this.topicViewers = topicViewers;
this.lastPageLoadAttemptedUrl = lastPageLoadAttemptedUrl;
this.pagesUrls = pagesUrls;
} }
public TopicTask.ResultCode getResultCode() { public TopicTask.ResultCode getResultCode() {
return resultCode; return resultCode;
} }
public String getBaseUrl() {
return baseUrl;
}
public String getTopicTitle() { public String getTopicTitle() {
return topicTitle; return topicTitle;
} }
@ -114,12 +95,4 @@ public class TopicTaskResult {
public String getTopicViewers() { public String getTopicViewers() {
return topicViewers; return topicViewers;
} }
public String getLastPageLoadAttemptedUrl() {
return lastPageLoadAttemptedUrl;
}
public SparseArray<String> getPagesUrls() {
return pagesUrls;
}
} }

20
app/src/main/java/gr/thmmy/mthmmy/utils/parsing/ParseHelpers.java

@ -6,6 +6,8 @@ import org.jsoup.select.Elements;
import java.util.ArrayList; import java.util.ArrayList;
import timber.log.Timber;
/** /**
* This class consists exclusively of static classes (enums) and methods (excluding methods of inner * This class consists exclusively of static classes (enums) and methods (excluding methods of inner
* classes). It can be used to resolve a page's language and state or fix embedded videos html code. * classes). It can be used to resolve a page's language and state or fix embedded videos html code.
@ -166,4 +168,22 @@ public class ParseHelpers {
} }
return fixed; return fixed;
} }
/**
* Method that extracts the base URL from a topic's page URL. For example a topic with url similar to
* "https://www.thmmy.gr/smf/index.php?topic=1.15;topicseen" or
* "https://www.thmmy.gr/smf/index.php?topic=1.msg1#msg1"
* has the base url "https://www.thmmy.gr/smf/index.php?topic=1"
*
* @param topicURL a topic's page URL
* @return the base URL of the given topic
*/
public static String getBaseURL(String topicURL) {
if (topicURL.substring(0, topicURL.lastIndexOf(".")).contains("topic="))
return topicURL.substring(0, topicURL.lastIndexOf("."));
else {
Timber.wtf(new ParseException("Could not parse base URL of topic"));
return "";
}
}
} }

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

@ -21,6 +21,7 @@ import gr.thmmy.mthmmy.activities.topic.tasks.TopicTaskResult;
import gr.thmmy.mthmmy.base.BaseActivity; import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTaskCompleted, public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTaskCompleted,
PrepareForReply.OnPrepareForReplyFinished, PrepareForEditTask.OnPrepareEditFinished { PrepareForReply.OnPrepareForReplyFinished, PrepareForEditTask.OnPrepareEditFinished {
@ -59,47 +60,53 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
* navigation bar occurs, aka the value that the page indicator shows * navigation bar occurs, aka the value that the page indicator shows
*/ */
private MutableLiveData<Integer> pageIndicatorIndex = new MutableLiveData<>(); private MutableLiveData<Integer> pageIndicatorIndex = new MutableLiveData<>();
private MutableLiveData<TopicTaskResult> topicTaskResult = new MutableLiveData<>();
private MutableLiveData<PrepareForReplyResult> prepareForReplyResult = new MutableLiveData<>();
private MutableLiveData<PrepareForEditResult> prepareForEditResult = new MutableLiveData<>();
private String firstTopicUrl; private MutableLiveData<String> replyPageUrl = new MutableLiveData<>();
private MutableLiveData<Integer> pageTopicId = new MutableLiveData<>();
private MutableLiveData<String> topicTitle = new MutableLiveData<>();
private MutableLiveData<ArrayList<Post>> postsList = new MutableLiveData<>();
private MutableLiveData<Integer> focusedPostIndex = new MutableLiveData<>();
private MutableLiveData<TopicTask.ResultCode> topicTaskResultCode = new MutableLiveData<>();
private MutableLiveData<String> topicTreeAndMods = new MutableLiveData<>();
private MutableLiveData<String> topicViewers = new MutableLiveData<>();
private String topicUrl;
private int currentPageIndex;
private int pageCount;
public void initialLoad(String pageUrl) { private MutableLiveData<PrepareForReplyResult> prepareForReplyResult = new MutableLiveData<>();
firstTopicUrl = pageUrl; private MutableLiveData<PrepareForEditResult> prepareForEditResult = new MutableLiveData<>();
currentTopicTask = new TopicTask(topicTaskObserver, this);
currentTopicTask.execute(pageUrl);
}
public void loadUrl(String pageUrl) { public void loadUrl(String pageUrl) {
stopLoading(); stopLoading();
topicUrl = pageUrl;
currentTopicTask = new TopicTask(topicTaskObserver, this); currentTopicTask = new TopicTask(topicTaskObserver, this);
currentTopicTask.execute(pageUrl); currentTopicTask.execute(pageUrl);
} }
public void reloadPage() { public void reloadPage() {
if (topicTaskResult.getValue() == null) if (topicUrl == null) throw new NullPointerException("No topic task has finished yet!");
throw new NullPointerException("No topic task has finished yet!"); loadUrl(topicUrl);
loadUrl(topicTaskResult.getValue().getLastPageLoadAttemptedUrl());
} }
public void performPageChange() { public void performPageChange() {
if (topicTaskResult.getValue() == null || pageIndicatorIndex.getValue() == null) if (pageIndicatorIndex.getValue() == null)
throw new NullPointerException("No page has been loaded yet!"); throw new NullPointerException("No page has been loaded yet!");
int pageRequested = pageIndicatorIndex.getValue() - 1; int pageRequested = pageIndicatorIndex.getValue() - 1;
if (pageRequested != topicTaskResult.getValue().getCurrentPageIndex() - 1) { if (pageRequested != currentPageIndex - 1) {
loadUrl(topicTaskResult.getValue().getPagesUrls().get(pageRequested)); loadUrl(ParseHelpers.getBaseURL(topicUrl) + "." + String.valueOf(pageRequested * 15));
pageIndicatorIndex.setValue(pageRequested + 1); pageIndicatorIndex.setValue(pageRequested + 1);
} else {
stopLoading();
} }
} }
public void prepareForReply() { public void prepareForReply() {
if (topicTaskResult.getValue() == null) if (replyPageUrl.getValue() == null)
throw new NullPointerException("Topic task has not finished yet!"); throw new NullPointerException("Topic task has not finished yet!");
stopLoading(); stopLoading();
setPageIndicatorIndex(getPageCount(), true); setPageIndicatorIndex(getPageCount(), true);
currentPrepareForReplyTask = new PrepareForReply(prepareForReplyCallbacks, this, currentPrepareForReplyTask = new PrepareForReply(prepareForReplyCallbacks, this,
topicTaskResult.getValue().getReplyPageUrl()); replyPageUrl.getValue());
currentPrepareForReplyTask.execute(toQuoteList.toArray(new Integer[0])); currentPrepareForReplyTask.execute(toQuoteList.toArray(new Integer[0]));
} }
@ -124,11 +131,11 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
} }
public void prepareForEdit(int position, String postEditURL) { public void prepareForEdit(int position, String postEditURL) {
if (topicTaskResult.getValue() == null) if (replyPageUrl.getValue() == null)
throw new NullPointerException("Topic task has not finished yet!"); throw new NullPointerException("Topic task has not finished yet!");
stopLoading(); stopLoading();
currentPrepareForEditTask = new PrepareForEditTask(prepareForEditCallbacks, this, position, currentPrepareForEditTask = new PrepareForEditTask(prepareForEditCallbacks, this, position,
topicTaskResult.getValue().getReplyPageUrl()); replyPageUrl.getValue());
currentPrepareForEditTask.execute(postEditURL); currentPrepareForEditTask.execute(postEditURL);
} }
@ -166,14 +173,23 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
// callbacks for viewmodel // callbacks for viewmodel
@Override @Override
public void onTopicTaskCompleted(TopicTaskResult result) { public void onTopicTaskCompleted(TopicTaskResult result) {
topicTaskResult.setValue(result);
if (result.getResultCode() == TopicTask.ResultCode.SUCCESS) { if (result.getResultCode() == TopicTask.ResultCode.SUCCESS) {
currentPageIndex = result.getCurrentPageIndex();
pageCount = result.getPageCount();
topicTreeAndMods.setValue(result.getTopicTreeAndMods());
topicViewers.setValue(result.getTopicViewers());
pageTopicId.setValue(result.getLoadedPageTopicId());
replyPageUrl.setValue(result.getReplyPageUrl());
topicTitle.setValue(result.getTopicTitle());
pageIndicatorIndex.setValue(result.getCurrentPageIndex()); pageIndicatorIndex.setValue(result.getCurrentPageIndex());
postsList.setValue(result.getNewPostsList());
focusedPostIndex.setValue(result.getFocusedPostIndex());
isUserExtraInfoVisibile.clear(); isUserExtraInfoVisibile.clear();
for (int i = 0; i < result.getNewPostsList().size(); i++) { for (int i = 0; i < result.getNewPostsList().size(); i++) {
isUserExtraInfoVisibile.add(false); isUserExtraInfoVisibile.add(false);
} }
} }
topicTaskResultCode.setValue(result.getResultCode());
} }
@Override @Override
@ -216,6 +232,41 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
// <-------------Just getters, setters and helper methods below here----------------> // <-------------Just getters, setters and helper methods below here---------------->
public MutableLiveData<String> getTopicViewers() {
return topicViewers;
}
public MutableLiveData<String> getTopicTreeAndMods() {
return topicTreeAndMods;
}
public MutableLiveData<TopicTask.ResultCode> getTopicTaskResultCode() {
return topicTaskResultCode;
}
public MutableLiveData<Integer> getFocusedPostIndex() {
return focusedPostIndex;
}
public MutableLiveData<ArrayList<Post>> getPostsList() {
return postsList;
}
public MutableLiveData<String> getReplyPageUrl() {
return replyPageUrl;
}
public MutableLiveData<Integer> getPageTopicId() {
return pageTopicId;
}
public MutableLiveData<String> getTopicTitle() {
return topicTitle;
}
public String getTopicUrl() {
return topicUrl;
}
public MutableLiveData<Integer> getPageIndicatorIndex() { public MutableLiveData<Integer> getPageIndicatorIndex() {
return pageIndicatorIndex; return pageIndicatorIndex;
@ -268,10 +319,6 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
this.prepareForReplyCallbacks = prepareForReplyCallbacks; this.prepareForReplyCallbacks = prepareForReplyCallbacks;
} }
public MutableLiveData<TopicTaskResult> getTopicTaskResult() {
return topicTaskResult;
}
public MutableLiveData<PrepareForReplyResult> getPrepareForReplyResult() { public MutableLiveData<PrepareForReplyResult> getPrepareForReplyResult() {
return prepareForReplyResult; return prepareForReplyResult;
} }
@ -293,7 +340,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
} }
public boolean canReply() { public boolean canReply() {
return topicTaskResult.getValue() != null && topicTaskResult.getValue().getReplyPageUrl() != null; return replyPageUrl.getValue() != null;
} }
public boolean isWritingReply() { public boolean isWritingReply() {
@ -304,40 +351,14 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
this.writingReply = writingReply; this.writingReply = writingReply;
} }
public String getBaseUrl() {
if (topicTaskResult.getValue() != null) {
return topicTaskResult.getValue().getBaseUrl();
} else {
return "";
}
}
public String getTopicUrl() {
if (topicTaskResult.getValue() != null) {
return topicTaskResult.getValue().getLastPageLoadAttemptedUrl();
} else {
// topic task has not finished yet (log? disable menu button until load is finished?)
return firstTopicUrl;
}
}
public String getTopicTitle() {
if (topicTaskResult.getValue() == null)
throw new NullPointerException("Topic task has not finished yet!");
return topicTaskResult.getValue().getTopicTitle();
}
public int getCurrentPageIndex() { public int getCurrentPageIndex() {
if (topicTaskResult.getValue() == null) if (currentPageIndex == 0) throw new NullPointerException("No page has been loaded yet!");
throw new NullPointerException("No page has been loaded yet!"); return currentPageIndex;
return topicTaskResult.getValue().getCurrentPageIndex();
} }
public int getPageCount() { public int getPageCount() {
if (topicTaskResult.getValue() == null) if (pageCount == 0) throw new NullPointerException("No page has been loaded yet!");
throw new NullPointerException("No page has been loaded yet!"); return pageCount;
return topicTaskResult.getValue().getPageCount();
} }
public String getPostBeingEditedText() { public String getPostBeingEditedText() {

Loading…
Cancel
Save