diff --git a/app/src/main/java/me/ccrama/redditslide/Activities/CommentsScreenSingle.java b/app/src/main/java/me/ccrama/redditslide/Activities/CommentsScreenSingle.java index edbd940ee4..1f1c32617a 100644 --- a/app/src/main/java/me/ccrama/redditslide/Activities/CommentsScreenSingle.java +++ b/app/src/main/java/me/ccrama/redditslide/Activities/CommentsScreenSingle.java @@ -10,6 +10,7 @@ import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; +import android.util.Log; import android.util.TypedValue; import android.view.KeyEvent; import android.view.ViewGroup; @@ -31,6 +32,7 @@ import me.ccrama.redditslide.Notifications.NotificationJobScheduler; import me.ccrama.redditslide.R; import me.ccrama.redditslide.Reddit; +import me.ccrama.redditslide.Services.CommentScreenTask; import me.ccrama.redditslide.SettingValues; import me.ccrama.redditslide.UserSubscriptions; import me.ccrama.redditslide.util.LogUtil; @@ -49,6 +51,7 @@ public class CommentsScreenSingle extends BaseActivityAnim { private String name; private String context; private int contextNumber; + private CommentScreenTask.AsyncGetSubredditName asyncGetSubredditName; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { @@ -92,15 +95,14 @@ public void onCreate(Bundle savedInstance) { applyColorTheme(); setContentView(R.layout.activity_slide); name = getIntent().getExtras().getString(EXTRA_SUBMISSION, ""); - subreddit = getIntent().getExtras().getString(EXTRA_SUBREDDIT, ""); np = getIntent().getExtras().getBoolean(EXTRA_NP, false); context = getIntent().getExtras().getString(EXTRA_CONTEXT, ""); - contextNumber = getIntent().getExtras().getInt(EXTRA_CONTEXT_NUMBER, 5); if (subreddit.equals(Reddit.EMPTY_STRING)) { - new AsyncGetSubredditName().execute(name); + asyncGetSubredditName = new CommentScreenTask.AsyncGetSubredditName(this); + asyncGetSubredditName.execute(name); TypedValue typedValue = new TypedValue(); getTheme().resolveAttribute(R.attr.activity_background, typedValue, true); int color = typedValue.data; @@ -209,69 +211,20 @@ public void onPageScrollStateChanged(int state) { boolean archived; boolean contest; - private class AsyncGetSubredditName extends AsyncTask { - - @Override - protected void onPostExecute(String s) { - subreddit = s; - setupAdapter(); - } - - @Override - protected String doInBackground(String... params) { - try { - final Submission s = Authentication.reddit.getSubmission(params[0]); - if (SettingValues.storeHistory) { - if (SettingValues.storeNSFWHistory && s.isNsfw() || !s.isNsfw()) { - HasSeen.addSeen(s.getFullName()); - } - LastComments.setComments(s); - } - HasSeen.setHasSeenSubmission(new ArrayList() {{ - this.add(s); - }}); - locked = s.isLocked(); - archived = s.isArchived(); - contest = s.getDataNode().get("contest_mode").asBoolean(); - if(s.getSubredditName() == null){ - subreddit = "Promoted"; - } else { - subreddit = s.getSubredditName(); - } - return subreddit; - - } catch (Exception e) { - try { - runOnUiThread(new Runnable() { - @Override - public void run() { - new AlertDialogWrapper.Builder(CommentsScreenSingle.this).setTitle( - R.string.submission_not_found) - .setMessage(R.string.submission_not_found_msg) - .setPositiveButton(R.string.btn_ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, - int which) { - finish(); - } - }) - .setOnDismissListener(new DialogInterface.OnDismissListener() { - @Override - public void onDismiss(DialogInterface dialog) { - finish(); - } - }) - .show(); - } - }); - } catch (Exception ignored) { - - } - return null; - } - + public void update(Submission s, String subreddit) { + this.subreddit = subreddit; + locked = s.isLocked(); + archived = s.isArchived(); + contest = s.getDataNode().get("contest_mode").asBoolean(); + setupAdapter(); + } + @Override + public void onDestroy() { + super.onDestroy(); + if (asyncGetSubredditName != null) { + asyncGetSubredditName.cancel(true); + asyncGetSubredditName = null; } } diff --git a/app/src/main/java/me/ccrama/redditslide/Activities/Inbox.java b/app/src/main/java/me/ccrama/redditslide/Activities/Inbox.java index 4a5e90db33..2a124b8ef1 100644 --- a/app/src/main/java/me/ccrama/redditslide/Activities/Inbox.java +++ b/app/src/main/java/me/ccrama/redditslide/Activities/Inbox.java @@ -18,22 +18,14 @@ import android.view.animation.LinearInterpolator; import android.view.inputmethod.InputMethodManager; -import net.dean.jraw.managers.InboxManager; - -import java.util.HashSet; -import java.util.Set; - import me.ccrama.redditslide.Authentication; -import me.ccrama.redditslide.Autocache.AutoCacheScheduler; import me.ccrama.redditslide.ColorPreferences; import me.ccrama.redditslide.ContentGrabber; import me.ccrama.redditslide.Fragments.InboxPage; import me.ccrama.redditslide.Fragments.SettingsGeneralFragment; -import me.ccrama.redditslide.Notifications.NotificationJobScheduler; import me.ccrama.redditslide.R; -import me.ccrama.redditslide.Reddit; +import me.ccrama.redditslide.Services.InboxTask; import me.ccrama.redditslide.SettingValues; -import me.ccrama.redditslide.UserSubscriptions; import me.ccrama.redditslide.Visuals.Palette; import me.ccrama.redditslide.util.LogUtil; @@ -46,6 +38,8 @@ public class Inbox extends BaseActivityAnim { public Inbox.OverviewPagerAdapter adapter; private TabLayout tabs; private ViewPager pager; + private InboxTask.AuthenticationVerify authenticationVerify; + private InboxTask.ReadStatus readStatus; @Override public boolean onCreateOptionsMenu(Menu menu) { @@ -58,7 +52,7 @@ public boolean onCreateOptionsMenu(Menu menu) { return true; } - private boolean changed; + //private boolean changed; public long last; @Override @@ -77,43 +71,33 @@ public boolean onOptionsItemSelected(MenuItem item) { startActivity(i); break; case (R.id.read): - changed = false; - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - try { - new InboxManager(Authentication.reddit).setAllRead(); - changed = true; - } catch (Exception ignored) { - ignored.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - if (changed) { //restart the fragment - adapter.notifyDataSetChanged(); - - try { - final int CURRENT_TAB = tabs.getSelectedTabPosition(); - adapter = new OverviewPagerAdapter(getSupportFragmentManager()); - pager.setAdapter(adapter); - tabs.setupWithViewPager(pager); - - scrollToTabAfterLayout(CURRENT_TAB); - pager.setCurrentItem(CURRENT_TAB); - } catch (Exception e) { - - } - } - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + readStatus = new InboxTask.ReadStatus(this); + readStatus.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); break; } return super.onOptionsItemSelected(item); } + /** + * Method to update the Inbox UI when user tap on read option + * + */ + public void updateInboxUI(){ + adapter.notifyDataSetChanged(); + + try { + final int CURRENT_TAB = tabs.getSelectedTabPosition(); + adapter = new Inbox.OverviewPagerAdapter(getSupportFragmentManager()); + pager.setAdapter(adapter); + tabs.setupWithViewPager(pager); + + scrollToTabAfterLayout(CURRENT_TAB); + pager.setCurrentItem(CURRENT_TAB); + } catch (Exception e) { + + } + } + /** * Method to scroll the TabLayout to a specific index * @@ -142,56 +126,9 @@ public void onCreate(Bundle savedInstance) { if (Authentication.reddit == null || !Authentication.reddit.isAuthenticated() || Authentication.me == null) { LogUtil.v("Reauthenticating"); - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - if (Authentication.reddit == null) { - new Authentication(getApplicationContext()); - } - - try { - Authentication.me = Authentication.reddit.me(); - Authentication.mod = Authentication.me.isMod(); - - Authentication.authentication.edit() - .putBoolean(Reddit.SHARED_PREF_IS_MOD, Authentication.mod) - .apply(); - - if (Reddit.notificationTime != -1) { - Reddit.notifications = new NotificationJobScheduler(Inbox.this); - Reddit.notifications.start(getApplicationContext()); - } - - if (Reddit.cachedData.contains("toCache")) { - Reddit.autoCache = new AutoCacheScheduler(Inbox.this); - Reddit.autoCache.start(getApplicationContext()); - } - - final String name = Authentication.me.getFullName(); - Authentication.name = name; - LogUtil.v("AUTHENTICATED"); - UserSubscriptions.doCachedModSubs(); - - if (Authentication.reddit.isAuthenticated()) { - final Set accounts = - Authentication.authentication.getStringSet("accounts", new HashSet()); - if (accounts.contains(name)) { //convert to new system - accounts.remove(name); - accounts.add(name + ":" + Authentication.refresh); - Authentication.authentication.edit() - .putStringSet("accounts", accounts) - .apply(); //force commit - } - Authentication.isLoggedIn = true; - Reddit.notFirst = true; - } - - } catch (Exception ignored){ + authenticationVerify = new InboxTask.AuthenticationVerify(Inbox.this); + authenticationVerify.execute(); - } - return null; - } - }.execute(); } super.onCreate(savedInstance); @@ -279,4 +216,17 @@ public void onResume(){ InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.hideSoftInputFromWindow(getWindow().getAttributes().token, 0); } + + @Override + public void onDestroy() { + super.onDestroy(); + if (authenticationVerify != null) { + authenticationVerify.cancel(true); + authenticationVerify = null; + } + if (readStatus != null) { + readStatus.cancel(true); + readStatus = null; + } + } } diff --git a/app/src/main/java/me/ccrama/redditslide/Activities/LiveThread.java b/app/src/main/java/me/ccrama/redditslide/Activities/LiveThread.java index d789a3f507..71f85230c2 100644 --- a/app/src/main/java/me/ccrama/redditslide/Activities/LiveThread.java +++ b/app/src/main/java/me/ccrama/redditslide/Activities/LiveThread.java @@ -11,6 +11,7 @@ import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; +import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; @@ -53,6 +54,7 @@ import me.ccrama.redditslide.ContentType; import me.ccrama.redditslide.R; import me.ccrama.redditslide.Reddit; +import me.ccrama.redditslide.Services.LiveThreadTask; import me.ccrama.redditslide.SpoilerRobotoTextView; import me.ccrama.redditslide.TimeUtils; import me.ccrama.redditslide.Views.CommentOverflow; @@ -68,7 +70,12 @@ public class LiveThread extends BaseActivityAnim { public static final String EXTRA_LIVEURL = "liveurl"; - public net.dean.jraw.models.LiveThread thread; + public net.dean.jraw.models.LiveThread thread; + private LiveThreadTask.LoadTwitter loadTwitter; + private LiveThreadTask.LiveUpdateThread liveUpdateThread; + private LiveThreadTask.DialogThread dialogThread; + private LiveThreadTask.PaginatorThread paginatorThread; + private PaginatorAdapter adapter; @Override @@ -100,9 +107,24 @@ public boolean onCreateOptionsMenu(Menu menu) { public void onDestroy() { super.onDestroy(); //todo finish + if (loadTwitter != null) { + loadTwitter.cancel(true); + loadTwitter = null; + } + if (liveUpdateThread != null) { + liveUpdateThread.cancel(true); + liveUpdateThread = null; + } + if (dialogThread != null) { + dialogThread.cancel(true); + paginatorThread = null; + } + if (paginatorThread != null) { + paginatorThread.cancel(true); + dialogThread = null; + } } - @Override public void onCreate(Bundle savedInstanceState) { overrideSwipeFromAnywhere(); @@ -115,313 +137,103 @@ public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_livethread); baseRecycler = (RecyclerView) findViewById(R.id.content_view); baseRecycler.setLayoutManager(new LinearLayoutManager(LiveThread.this)); - new AsyncTask() { - MaterialDialog d; - - @Override - public void onPreExecute() { - d = new MaterialDialog.Builder(LiveThread.this) - .title(R.string.livethread_loading_title) - .content(R.string.misc_please_wait) - .progress(true, 100) - .cancelable(false) - .show(); - } - @Override - protected Void doInBackground(Void... params) { - try { - thread = new LiveThreadManager(Authentication.reddit).get(getIntent().getStringExtra(EXTRA_LIVEURL)); - } catch(Exception e){ + dialogThread = new LiveThreadTask.DialogThread(this); + dialogThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - return null; - } + } - @Override - public void onPostExecute(Void aVoid) { - if(thread == null){ - new AlertDialogWrapper.Builder(LiveThread.this) - .setTitle(R.string.livethread_not_found) - .setMessage(R.string.misc_please_try_again_soon) - .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - finish(); - } - }).setOnDismissListener(new DialogInterface.OnDismissListener() { + + public void updateToolBar() { + if(thread == null){ + new AlertDialogWrapper.Builder(this) + .setTitle(R.string.livethread_not_found) + .setMessage(R.string.misc_please_try_again_soon) + .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() { @Override - public void onDismiss(DialogInterface dialog) { + public void onClick(DialogInterface dialog, int which) { finish(); } - }).setCancelable(false).show(); - } else { - d.dismiss(); - setupAppBar(R.id.toolbar, thread.getTitle(), true, false); - (findViewById(R.id.toolbar)).setBackgroundResource(R.color.md_red_300); - (findViewById(R.id.header_sub)).setBackgroundResource(R.color.md_red_300); - themeSystemBars(Palette.getDarkerColor(getResources().getColor(R.color.md_red_300))); - setRecentBar(getString(R.string.livethread_recents_title, thread.getTitle()), getResources().getColor(R.color.md_red_300)); - - doPaginator(); + }).setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialog) { + finish(); } - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }).setCancelable(false).show(); + } else { + setupAppBar(R.id.toolbar, thread.getTitle(), true, false); + (findViewById(R.id.toolbar)).setBackgroundResource(R.color.md_red_300); + (findViewById(R.id.header_sub)).setBackgroundResource(R.color.md_red_300); + themeSystemBars(Palette.getDarkerColor(getResources().getColor(R.color.md_red_300))); + setRecentBar(getString(R.string.livethread_recents_title, thread.getTitle()), getResources().getColor(R.color.md_red_300)); + doPaginator(); + } } - ArrayList updates; - LiveThreadPaginator paginator; + public ArrayList updates; + public LiveThreadPaginator paginator; public void doPaginator() { - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - paginator = new LiveThreadManager(Authentication.reddit).stream(thread); - updates = new ArrayList<>(paginator.accumulateMerged(5)); - return null; - } - @Override - public void onPostExecute(Void aVoid) { + paginatorThread = new LiveThreadTask.PaginatorThread(this); + paginatorThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - doLiveThreadUpdates(); - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public void doLiveThreadUpdates() { - final PaginatorAdapter adapter = new PaginatorAdapter(this); + adapter = new PaginatorAdapter(this); baseRecycler.setAdapter(adapter); doLiveSidebar(); if (thread.getWebsocketUrl() != null && !thread.getWebsocketUrl().isEmpty()) { - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - final ObjectReader o = new ObjectMapper().reader(); - - try { - com.neovisionaries.ws.client.WebSocket ws = new WebSocketFactory().createSocket(thread.getWebsocketUrl()); - ws.addListener(new WebSocketListener() { - @Override - public void onStateChanged( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketState newState) { - - } - - @Override - public void onConnected( - com.neovisionaries.ws.client.WebSocket websocket, - Map> headers) { - - } - - @Override - public void onConnectError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause) { - - } - - @Override - public void onDisconnected( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame serverCloseFrame, - WebSocketFrame clientCloseFrame, boolean closedByServer) { - - } - - @Override - public void onFrame(com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onContinuationFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onTextFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onBinaryFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onCloseFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onPingFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onPongFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onTextMessage( - com.neovisionaries.ws.client.WebSocket websocket, String s) { - LogUtil.v("Recieved" + s); - if (s.contains("\"type\": \"update\"")) { - try { - LiveUpdate u = new LiveUpdate(o.readTree(s).get("payload").get("data")); - updates.add(0, u); - runOnUiThread(new Runnable() { - @Override - public void run() { - adapter.notifyItemInserted(0); - baseRecycler.smoothScrollToPosition(0); - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - } else if (s.contains("embeds_ready")) { - String node = updates.get(0).getDataNode().toString(); - LogUtil.v("Getting"); - try { - node = node.replace("\"embeds\":[]", "\"embeds\":" + o.readTree(s).get("payload").get("media_embeds").toString()); - LiveUpdate u = new LiveUpdate(o.readTree(node)); - updates.set(0, u); - runOnUiThread(new Runnable() { - @Override - public void run() { - adapter.notifyItemChanged(0); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - - } /* todoelse if(s.contains("delete")){ - updates.remove(0); - adapter.notifyItemRemoved(0); - }*/ - - } - - @Override - public void onBinaryMessage( - com.neovisionaries.ws.client.WebSocket websocket, - byte[] binary) { - - } - - @Override - public void onSendingFrame( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onFrameSent( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onFrameUnsent( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketFrame frame) { - - } - - @Override - public void onError(com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause) { - - } - - @Override - public void onFrameError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause, WebSocketFrame frame) { - - } - - @Override - public void onMessageError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause, List frames) { - - } - - @Override - public void onMessageDecompressionError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause, byte[] compressed) { - - } - - @Override - public void onTextMessageError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause, byte[] data) { - - } - - @Override - public void onSendError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause, WebSocketFrame frame) { - - } - - @Override - public void onUnexpectedError( - com.neovisionaries.ws.client.WebSocket websocket, - WebSocketException cause) { - - } - - @Override - public void handleCallbackError( - com.neovisionaries.ws.client.WebSocket websocket, - Throwable cause) { - - } - - @Override - public void onSendingHandshake( - com.neovisionaries.ws.client.WebSocket websocket, - String requestLine, List headers) { + liveUpdateThread = new LiveThreadTask.LiveUpdateThread(this); + liveUpdateThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + } - } - }); - ws.connect(); - } catch (IOException e) { - e.printStackTrace(); - } catch (WebSocketException e) { - e.printStackTrace(); + /** + * Method to update the recyclerView adapter + * + * @param s received string + */ + public void updateLive(String s) { + final ObjectReader o = new ObjectMapper().reader(); + LogUtil.v("Recieved" + s); + if (s.contains("\"type\": \"update\"")) { + try { + LiveUpdate u = new LiveUpdate(o.readTree(s).get("payload").get("data")); + updates.add(0, u); + runOnUiThread(new Runnable() { + @Override + public void run() { + adapter.notifyItemInserted(0); + baseRecycler.smoothScrollToPosition(0); } - return null; - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }); + } catch (IOException e) { + e.printStackTrace(); + } + } else if (s.contains("embeds_ready")) { + String node = updates.get(0).getDataNode().toString(); + LogUtil.v("Getting"); + try { + node = node.replace("\"embeds\":[]", "\"embeds\":" + o.readTree(s).get("payload").get("media_embeds").toString()); + LiveUpdate u = new LiveUpdate(o.readTree(node)); + updates.set(0, u); + runOnUiThread(new Runnable() { + @Override + public void run() { + adapter.notifyItemChanged(0); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } /* todoelse if(s.contains("delete")){ + updates.remove(0); + adapter.notifyItemRemoved(0); + }*/ } + } public class PaginatorAdapter extends RecyclerView.Adapter { @@ -489,51 +301,11 @@ public void onClick(View v) { LogUtil.v("Twitter"); holder.twitterArea.setVisibility(View.VISIBLE); - new LoadTwitter(holder.twitterArea, url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - } - - } - - public class LoadTwitter extends AsyncTask { - - private OkHttpClient client; - private Gson gson; - String url; - private WebView view; - TwitterObject twitter; - - public LoadTwitter(@NotNull WebView view, @NotNull String url) { - this.view = view; - this.url = url; - client = Reddit.client; - gson = new Gson(); - } - - public void parseJson() { - try { - JsonObject result = HttpUtil.getJsonObject(client, gson, "https://publish.twitter.com/oembed?url=" + url, null); - LogUtil.v("Got " + Html.fromHtml(result.toString())); - twitter = new ObjectMapper().readValue(result.toString(), TwitterObject.class); - } catch (Exception e) { - e.printStackTrace(); + loadTwitter = new LiveThreadTask.LoadTwitter(holder.twitterArea, url); + loadTwitter.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } - @Override - protected Void doInBackground(final String... sub) { - parseJson(); - return null; - } - - @Override - public void onPostExecute(Void aVoid) { - if (twitter != null && twitter.getHtml() != null) { - view.loadData(twitter.getHtml().replace("//platform.twitter", "https://platform.twitter"), "text/html", "UTF-8"); - } - } - - } diff --git a/app/src/main/java/me/ccrama/redditslide/Services/CommentScreenTask.java b/app/src/main/java/me/ccrama/redditslide/Services/CommentScreenTask.java new file mode 100644 index 0000000000..e9f3fa168a --- /dev/null +++ b/app/src/main/java/me/ccrama/redditslide/Services/CommentScreenTask.java @@ -0,0 +1,99 @@ +package me.ccrama.redditslide.Services; + +import android.content.Context; +import android.content.DialogInterface; +import android.os.AsyncTask; + +import com.afollestad.materialdialogs.AlertDialogWrapper; + +import net.dean.jraw.models.Submission; + +import org.jetbrains.annotations.NotNull; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; + +import me.ccrama.redditslide.Activities.CommentsScreenSingle; +import me.ccrama.redditslide.Authentication; +import me.ccrama.redditslide.HasSeen; +import me.ccrama.redditslide.LastComments; +import me.ccrama.redditslide.R; +import me.ccrama.redditslide.SettingValues; + +public class CommentScreenTask { + + public static class AsyncGetSubredditName extends AsyncTask { + + private WeakReference activity; + + public AsyncGetSubredditName(@NotNull CommentsScreenSingle activity) { + this.activity = new WeakReference<>(activity); + } + + @Override + protected void onPostExecute(String s) { + + } + + @Override + protected String doInBackground(String... params) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + CommentsScreenSingle screenSingle = this.activity.get(); + if (screenSingle != null) { + try { + final Submission s = Authentication.reddit.getSubmission(params[0]); + if (SettingValues.storeHistory) { + if (SettingValues.storeNSFWHistory && s.isNsfw() || !s.isNsfw()) { + HasSeen.addSeen(s.getFullName()); + } + LastComments.setComments(s); + } + HasSeen.setHasSeenSubmission(new ArrayList() {{ + this.add(s); + }}); + + if(s.getSubredditName() == null){ + //subreddit = "Promoted"; + screenSingle.update(s, "Promoted"); + } else {// + //subreddit = s.getSubredditName(); + screenSingle.update(s, s.getSubredditName()); + } + return ""; + + } catch (Exception e) { + try { + screenSingle.runOnUiThread(new Runnable() { + @Override + public void run() { + new AlertDialogWrapper.Builder(screenSingle).setTitle( + R.string.submission_not_found) + .setMessage(R.string.submission_not_found_msg) + .setPositiveButton(R.string.btn_ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int which) { + screenSingle.finish(); + } + }) + .setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialog) { + screenSingle.finish(); + } + }) + .show(); + } + }); + } catch (Exception ignored) { + + } + } + } + return null; + } + } + +} diff --git a/app/src/main/java/me/ccrama/redditslide/Services/InboxTask.java b/app/src/main/java/me/ccrama/redditslide/Services/InboxTask.java new file mode 100644 index 0000000000..2a8494040d --- /dev/null +++ b/app/src/main/java/me/ccrama/redditslide/Services/InboxTask.java @@ -0,0 +1,122 @@ +package me.ccrama.redditslide.Services; + +import android.content.Context; +import android.os.AsyncTask; +import android.util.Log; +import android.webkit.WebView; + +import net.dean.jraw.managers.InboxManager; + +import org.jetbrains.annotations.NotNull; + +import java.lang.ref.WeakReference; +import java.util.HashSet; +import java.util.Set; + +import me.ccrama.redditslide.Activities.Inbox; +import me.ccrama.redditslide.Authentication; +import me.ccrama.redditslide.Autocache.AutoCacheScheduler; +import me.ccrama.redditslide.Notifications.NotificationJobScheduler; +import me.ccrama.redditslide.Reddit; +import me.ccrama.redditslide.UserSubscriptions; +import me.ccrama.redditslide.util.LogUtil; + +public class InboxTask { + + + public static class AuthenticationVerify extends AsyncTask { + + private WeakReference context; + + public AuthenticationVerify(@NotNull Context context) { + this.context = new WeakReference<>(context); + + } + + @Override + protected Void doInBackground(Void... params) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + Context context = this.context.get(); + + if (Authentication.reddit == null && context != null) { + new Authentication(context); + } + + if (context != null) { + try { + Authentication.me = Authentication.reddit.me(); + Authentication.mod = Authentication.me.isMod(); + + Authentication.authentication.edit() + .putBoolean(Reddit.SHARED_PREF_IS_MOD, Authentication.mod) + .apply(); + + if (Reddit.notificationTime != -1) { + Reddit.notifications = new NotificationJobScheduler(context); + Reddit.notifications.start(context); + } + + if (Reddit.cachedData.contains("toCache")) { + Reddit.autoCache = new AutoCacheScheduler(context); + Reddit.autoCache.start(context); + } + + final String name = Authentication.me.getFullName(); + Authentication.name = name; + LogUtil.v("AUTHENTICATED"); + UserSubscriptions.doCachedModSubs(); + + if (Authentication.reddit.isAuthenticated()) { + final Set accounts = + Authentication.authentication.getStringSet("accounts", new HashSet()); + if (accounts.contains(name)) { //convert to new system + accounts.remove(name); + accounts.add(name + ":" + Authentication.refresh); + Authentication.authentication.edit() + .putStringSet("accounts", accounts) + .apply(); //force commit + } + Authentication.isLoggedIn = true; + Reddit.notFirst = true; + } + + } catch (Exception ignored){ + + } + } + return null; + } + } + + public static class ReadStatus extends AsyncTask { + + private WeakReference inbox; + private boolean changed = false; + + public ReadStatus(@NotNull Inbox inbox) { + this.inbox = new WeakReference<>(inbox); + } + + @Override + protected Void doInBackground(Void... params) { + try { + new InboxManager(Authentication.reddit).setAllRead(); + changed = true; + } catch (Exception ignored) { + ignored.printStackTrace(); + } + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + Inbox inbox = this.inbox.get(); + if (changed && inbox != null) { //restart the fragment + inbox.updateInboxUI(); + } + } + } +} diff --git a/app/src/main/java/me/ccrama/redditslide/Services/LiveThreadTask.java b/app/src/main/java/me/ccrama/redditslide/Services/LiveThreadTask.java new file mode 100644 index 0000000000..f6a71a77bd --- /dev/null +++ b/app/src/main/java/me/ccrama/redditslide/Services/LiveThreadTask.java @@ -0,0 +1,377 @@ +package me.ccrama.redditslide.Services; + +import android.app.Activity; +import android.content.DialogInterface; +import android.os.AsyncTask; +import android.text.Html; +import android.util.Log; +import android.webkit.WebView; + +import com.afollestad.materialdialogs.AlertDialogWrapper; +import com.afollestad.materialdialogs.MaterialDialog; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.neovisionaries.ws.client.WebSocketException; +import com.neovisionaries.ws.client.WebSocketFactory; +import com.neovisionaries.ws.client.WebSocketFrame; +import com.neovisionaries.ws.client.WebSocketListener; +import com.neovisionaries.ws.client.WebSocketState; + +import net.dean.jraw.managers.LiveThreadManager; +import net.dean.jraw.models.LiveUpdate; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import me.ccrama.redditslide.Activities.LiveThread; +import me.ccrama.redditslide.Authentication; +import me.ccrama.redditslide.R; +import me.ccrama.redditslide.Reddit; +import me.ccrama.redditslide.Visuals.Palette; +import me.ccrama.redditslide.util.HttpUtil; +import me.ccrama.redditslide.util.LogUtil; +import me.ccrama.redditslide.util.TwitterObject; +import okhttp3.OkHttpClient; + +public class LiveThreadTask { + + public static class LiveUpdateThread extends AsyncTask { + + private WeakReference activity; + + public LiveUpdateThread(@NotNull LiveThread activity) { + this.activity = new WeakReference<>(activity); + } + + @Override + protected Void doInBackground(Void... params) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + LiveThread liveThread = this.activity.get(); + if (liveThread != null) { + try { + com.neovisionaries.ws.client.WebSocket ws = new WebSocketFactory().createSocket(liveThread.thread.getWebsocketUrl()); + ws.addListener(new WebSocketListener() { + @Override + public void onStateChanged( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketState newState) { + + } + + @Override + public void onConnected( + com.neovisionaries.ws.client.WebSocket websocket, + Map> headers) { + + } + + @Override + public void onConnectError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause) { + + } + + @Override + public void onDisconnected( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame serverCloseFrame, + WebSocketFrame clientCloseFrame, boolean closedByServer) { + + } + + @Override + public void onFrame(com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onContinuationFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onTextFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onBinaryFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onCloseFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onPingFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onPongFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onTextMessage( + com.neovisionaries.ws.client.WebSocket websocket, String s) { + liveThread.updateLive(s); + } + + @Override + public void onBinaryMessage( + com.neovisionaries.ws.client.WebSocket websocket, + byte[] binary) { + + } + + @Override + public void onSendingFrame( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onFrameSent( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onFrameUnsent( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketFrame frame) { + + } + + @Override + public void onError(com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause) { + + } + + @Override + public void onFrameError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause, WebSocketFrame frame) { + + } + + @Override + public void onMessageError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause, List frames) { + + } + + @Override + public void onMessageDecompressionError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause, byte[] compressed) { + + } + + @Override + public void onTextMessageError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause, byte[] data) { + + } + + @Override + public void onSendError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause, WebSocketFrame frame) { + + } + + @Override + public void onUnexpectedError( + com.neovisionaries.ws.client.WebSocket websocket, + WebSocketException cause) { + + } + + @Override + public void handleCallbackError( + com.neovisionaries.ws.client.WebSocket websocket, + Throwable cause) { + + } + + @Override + public void onSendingHandshake( + com.neovisionaries.ws.client.WebSocket websocket, + String requestLine, List headers) { + + } + }); + ws.connect(); + } catch (IOException e) { + e.printStackTrace(); + } catch (WebSocketException e) { + e.printStackTrace(); + } + } + + return null; + } + } + + public static class DialogThread extends AsyncTask { + private String EXTRA_LIVEURL = "liveurl"; + MaterialDialog d; + private WeakReference activity; + + public DialogThread(@NotNull LiveThread activity) { + this.activity = new WeakReference<>(activity); + } + + @Override + public void onPreExecute() { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + LiveThread liveThread = this.activity.get(); + if (liveThread != null) { + d = new MaterialDialog.Builder(activity.get()) + .title(R.string.livethread_loading_title) + .content(R.string.misc_please_wait) + .progress(true, 100) + .cancelable(false) + .show(); + } + + } + + @Override + protected Void doInBackground(Void... params) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + LiveThread liveThread = this.activity.get(); + if (liveThread != null) { + try { + liveThread.thread = new LiveThreadManager(Authentication.reddit).get(activity.get().getIntent().getStringExtra(EXTRA_LIVEURL)); + } catch(Exception e){ + } + } + + return null; + } + + @Override + public void onPostExecute(Void aVoid) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + LiveThread liveThread = this.activity.get(); + if (liveThread.thread == null) { + liveThread.updateToolBar(); + } + else { + d.dismiss(); + liveThread.updateToolBar(); + } + } + } + + public static class PaginatorThread extends AsyncTask { + + private WeakReference activity; + + public PaginatorThread(@NotNull LiveThread activity) { + this.activity = new WeakReference<>(activity); + } + + @Override + protected Void doInBackground(Void... params) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + LiveThread liveThread = this.activity.get(); + if (liveThread != null) { + liveThread.paginator = new LiveThreadManager(Authentication.reddit).stream(liveThread.thread); + liveThread.updates = new ArrayList<>(activity.get().paginator.accumulateMerged(5)); + } + return null; + } + + @Override + public void onPostExecute(Void aVoid) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + LiveThread liveThread = this.activity.get(); + if (liveThread != null) { + liveThread.doLiveThreadUpdates(); + } + } + } + + public static class LoadTwitter extends AsyncTask { + + private OkHttpClient client; + private Gson gson; + private String url; + private WeakReference view; + private TwitterObject twitter; + + public LoadTwitter(@NotNull WebView view, @NotNull String url) { + this.view = new WeakReference<>(view); + this.url = url; + client = Reddit.client; + gson = new Gson(); + } + + private void parseJson() { + try { + JsonObject result = HttpUtil.getJsonObject(client, gson, "https://publish.twitter.com/oembed?url=" + url, null); + LogUtil.v("Got " + Html.fromHtml(result.toString())); + twitter = new ObjectMapper().readValue(result.toString(), TwitterObject.class); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + protected Void doInBackground(final String... sub) { + parseJson(); + return null; + } + + @Override + public void onPostExecute(Void aVoid) { + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + WebView view = this.view.get(); + if (twitter != null && twitter.getHtml() != null && view != null) { + view.loadData(twitter.getHtml().replace("//platform.twitter", "https://platform.twitter"), "text/html", "UTF-8"); + } + } + + + } + +} diff --git a/app/src/main/java/me/ccrama/redditslide/Vote.java b/app/src/main/java/me/ccrama/redditslide/Vote.java index 24a90cc0f0..98824c848a 100644 --- a/app/src/main/java/me/ccrama/redditslide/Vote.java +++ b/app/src/main/java/me/ccrama/redditslide/Vote.java @@ -5,6 +5,7 @@ import android.graphics.Color; import android.os.AsyncTask; import android.support.design.widget.Snackbar; +import android.util.Log; import android.view.View; import android.widget.TextView; @@ -13,44 +14,46 @@ import net.dean.jraw.models.PublicContribution; import net.dean.jraw.models.VoteDirection; +import java.lang.ref.WeakReference; + /** * Created by ccrama on 9/19/2015. */ public class Vote extends AsyncTask { private final VoteDirection direction; - private View v; - private Context c; + private WeakReference v; + private WeakReference c; + public Vote(Boolean b, View v, Context c) { direction = b ? VoteDirection.UPVOTE : VoteDirection.DOWNVOTE; - this.v = v; - this.c = c; + this.v = new WeakReference<>(v); + this.c = new WeakReference<>(c); Reddit.setDefaultErrorHandler(c); - } public Vote(View v, Context c) { - direction = VoteDirection.NO_VOTE; - - this.v = v; - this.c = c; - + this.v = new WeakReference<>(v); + this.c = new WeakReference<>(c); } @Override protected Void doInBackground(PublicContribution... sub) { - + // Calling get() method just one time so it wont produce NPEs + // As subsequent access may produce NPEs + View view = v.get(); + Context context = c.get(); if (Authentication.isLoggedIn) { try { new AccountManager(Authentication.reddit).vote(sub[0], direction); } catch (ApiException | RuntimeException e) { - ((Activity) c).runOnUiThread(new Runnable() { + ((Activity) context).runOnUiThread(new Runnable() { public void run() { try { - if (v != null && c != null && v.getContext() != null) { - Snackbar s = Snackbar.make(v, R.string.vote_err, Snackbar.LENGTH_SHORT); + if (view != null && context != null) { + Snackbar s = Snackbar.make(view, R.string.vote_err, Snackbar.LENGTH_SHORT); View view = s.getView(); TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text); tv.setTextColor(Color.WHITE); @@ -61,16 +64,17 @@ public void run() { } c = null; v = null; + } }); e.printStackTrace(); } } else { - ((Activity) c).runOnUiThread(new Runnable() { + ((Activity) context).runOnUiThread(new Runnable() { public void run() { try { - if (v != null && c != null && v.getContext() != null) { - Snackbar s = Snackbar.make(v, R.string.vote_err_login, Snackbar.LENGTH_SHORT); + if (view != null && context != null) { + Snackbar s = Snackbar.make(view, R.string.vote_err_login, Snackbar.LENGTH_SHORT); View view = s.getView(); TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text); tv.setTextColor(Color.WHITE);