use of net.dean.jraw.models.Submission in project Slide by ccrama.
the class OfflineSubreddit method getSubreddit.
public static OfflineSubreddit getSubreddit(String subreddit, Long time, boolean offline, Context c) {
if (cache == null)
cache = new HashMap<>();
String title;
if (subreddit != null) {
title = subreddit.toLowerCase(Locale.ENGLISH) + "," + time;
} else {
title = "";
subreddit = "";
}
if (cache.containsKey(title)) {
return cache.get(title);
} else {
subreddit = subreddit.toLowerCase(Locale.ENGLISH);
OfflineSubreddit o = new OfflineSubreddit();
o.subreddit = subreddit.toLowerCase(Locale.ENGLISH);
if (time == 0) {
o.base = true;
}
o.time = time;
String[] split = Reddit.cachedData.getString(subreddit.toLowerCase(Locale.ENGLISH) + "," + time, "").split(",");
if (split.length > 0) {
o.time = time;
o.submissions = new ArrayList<>();
ObjectMapper mapperBase = new ObjectMapper();
ObjectReader reader = mapperBase.reader();
for (String s : split) {
if (!s.contains("_"))
s = "t3_" + s;
if (!s.isEmpty()) {
try {
Submission sub = getSubmissionFromStorage(s, c, offline, reader);
if (sub != null) {
o.submissions.add(sub);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
o.submissions = new ArrayList<>();
}
cache.put(title, o);
return o;
}
}
use of net.dean.jraw.models.Submission in project Slide by ccrama.
the class OfflineSubreddit method writeToMemory.
public void writeToMemory(Context c) {
if (cache == null)
cache = new HashMap<>();
if (subreddit != null) {
String title = subreddit.toLowerCase(Locale.ENGLISH) + "," + (base ? 0 : time);
String fullNames = "";
cache.put(title, this);
for (Submission sub : new ArrayList<>(submissions)) {
fullNames += sub.getFullName() + ",";
if (!isStored(sub.getFullName(), c)) {
writeSubmissionToStorage(sub, sub.getDataNode(), c);
}
}
if (fullNames.length() > 0) {
Reddit.cachedData.edit().putString(title, fullNames.substring(0, fullNames.length() - 1)).apply();
}
cache.put(title, this);
}
}
use of net.dean.jraw.models.Submission in project Slide by ccrama.
the class ListViewRemoteViewsFactory method onCreate.
// Initialize the data set.
public void onCreate() {
// In onCreate() you set up any connections / cursors to your data source. Heavy lifting,
// for example downloading or creating content etc, should be deferred to onDataSetChanged()
// or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.
records = new ArrayList<>();
if (NetworkUtil.isConnected(mContext)) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
if (Authentication.reddit == null) {
new Authentication(mContext.getApplicationContext());
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(mContext);
Reddit.notifications.start(mContext.getApplicationContext());
}
if (Reddit.cachedData.contains("toCache")) {
Reddit.autoCache = new AutoCacheScheduler(mContext);
Reddit.autoCache.start(mContext.getApplicationContext());
}
final String name = Authentication.me.getFullName();
Authentication.name = name;
LogUtil.v("AUTHENTICATED");
if (Authentication.reddit.isAuthenticated()) {
final Set<String> accounts = Authentication.authentication.getStringSet("accounts", new HashSet<String>());
if (accounts.contains(name)) {
// convert to new system
accounts.remove(name);
accounts.add(name + ":" + Authentication.refresh);
Authentication.authentication.edit().putStringSet("accounts", accounts).apply();
}
Authentication.isLoggedIn = true;
Reddit.notFirst = true;
}
}
String sub = SubredditWidgetProvider.getSubFromId(id, mContext);
Paginator p;
if (sub.equals("frontpage")) {
p = new SubredditPaginator(Authentication.reddit);
} else if (!sub.contains(".")) {
p = new SubredditPaginator(Authentication.reddit, sub);
} else {
p = new DomainPaginator(Authentication.reddit, sub);
}
p.setLimit(50);
switch(SubredditWidgetProvider.getSorting(id, mContext)) {
case 0:
p.setSorting(Sorting.HOT);
break;
case 1:
p.setSorting(Sorting.NEW);
break;
case 2:
p.setSorting(Sorting.RISING);
break;
case 3:
p.setSorting(Sorting.TOP);
break;
case 4:
p.setSorting(Sorting.CONTROVERSIAL);
break;
}
switch(SubredditWidgetProvider.getSortingTime(id, mContext)) {
case 0:
p.setTimePeriod(TimePeriod.HOUR);
break;
case 1:
p.setTimePeriod(TimePeriod.DAY);
break;
case 2:
p.setTimePeriod(TimePeriod.WEEK);
break;
case 3:
p.setTimePeriod(TimePeriod.MONTH);
break;
case 4:
p.setTimePeriod(TimePeriod.YEAR);
break;
case 5:
p.setTimePeriod(TimePeriod.ALL);
break;
}
try {
ArrayList<Submission> s = new ArrayList<>(p.next());
records = new ArrayList<>();
for (Submission subm : s) {
if (!PostMatch.doesMatch(subm) && !subm.isStickied()) {
records.add(subm);
}
}
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Intent widgetUpdateIntent = new Intent(mContext, SubredditWidgetProvider.class);
widgetUpdateIntent.setAction(SubredditWidgetProvider.UPDATE_MEETING_ACTION);
widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
mContext.sendBroadcast(widgetUpdateIntent);
}
}.execute();
} else {
Intent widgetUpdateIntent = new Intent(mContext, SubredditWidgetProvider.class);
widgetUpdateIntent.setAction(SubredditWidgetProvider.UPDATE_MEETING_ACTION);
widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
mContext.sendBroadcast(widgetUpdateIntent);
}
}
use of net.dean.jraw.models.Submission in project Slide by ccrama.
the class ListViewRemoteViewsFactory method getViewAt.
// Given the position (index) of a WidgetItem in the array, use the item's text value in
// combination with the app widget item XML file to construct a RemoteViews object.
public RemoteViews getViewAt(int position) {
// position will always range from 0 to getCount() - 1.
// Construct a RemoteViews item based on the app widget item XML file, and set the
// text based on the position.
int view = R.layout.submission_widget_light;
switch(SubredditWidgetProvider.getViewType(id, mContext)) {
case 1:
case 0:
if (SubredditWidgetProvider.getThemeFromId(id, mContext) == 2) {
view = R.layout.submission_widget_light;
} else {
view = R.layout.submission_widget;
}
break;
case 2:
if (SubredditWidgetProvider.getThemeFromId(id, mContext) == 2) {
view = R.layout.submission_widget_compact_light;
} else {
view = R.layout.submission_widget_compact;
}
break;
}
final RemoteViews rv = new RemoteViews(mContext.getPackageName(), view);
try {
// feed row
Submission data = records.get(position);
rv.setTextViewText(R.id.title, Html.fromHtml(data.getTitle()));
rv.setTextViewText(R.id.score, data.getScore() + "");
rv.setTextViewText(R.id.comments, data.getCommentCount() + "");
rv.setTextViewText(R.id.information, data.getAuthor() + " " + TimeUtils.getTimeAgo(data.getCreated().getTime(), mContext));
rv.setTextViewText(R.id.subreddit, data.getSubredditName());
rv.setTextColor(R.id.subreddit, Palette.getColor(data.getSubredditName()));
if (SubredditWidgetProvider.getViewType(id, mContext) == 1) {
Thumbnails s = data.getThumbnails();
rv.setViewVisibility(R.id.thumbimage2, View.GONE);
if (s != null && s.getVariations() != null && s.getSource() != null) {
rv.setImageViewBitmap(R.id.bigpic, ((Reddit) mContext.getApplicationContext()).getImageLoader().loadImageSync(Html.fromHtml(data.getThumbnails().getSource().getUrl()).toString()));
rv.setViewVisibility(R.id.bigpic, View.VISIBLE);
} else {
rv.setViewVisibility(R.id.bigpic, View.GONE);
}
} else {
if (SubredditWidgetProvider.getViewType(id, mContext) != 2) {
rv.setViewVisibility(R.id.bigpic, View.GONE);
}
if (data.getThumbnailType() == Submission.ThumbnailType.URL) {
rv.setImageViewBitmap(R.id.thumbimage2, ((Reddit) mContext.getApplicationContext()).getImageLoader().loadImageSync(data.getThumbnail()));
rv.setViewVisibility(R.id.thumbimage2, View.VISIBLE);
} else {
rv.setViewVisibility(R.id.thumbimage2, View.GONE);
}
}
switch(SubredditWidgetProvider.getViewType(id, mContext)) {
case 1:
case 0:
if (SubredditWidgetProvider.getThemeFromId(id, mContext) == 2) {
} else {
rv.setTextColor(R.id.title, Color.WHITE);
rv.setTextColor(R.id.score, Color.WHITE);
rv.setTextColor(R.id.comments, Color.WHITE);
rv.setTextColor(R.id.information, Color.WHITE);
}
break;
case 2:
if (SubredditWidgetProvider.getThemeFromId(id, mContext) == 2) {
} else {
rv.setTextColor(R.id.title, Color.WHITE);
rv.setTextColor(R.id.score, Color.WHITE);
rv.setTextColor(R.id.comments, Color.WHITE);
rv.setTextColor(R.id.information, Color.WHITE);
}
break;
}
Bundle infos = new Bundle();
infos.putString(OpenContent.EXTRA_URL, data.getPermalink());
infos.putBoolean("popup", true);
final Intent activityIntent = new Intent();
activityIntent.putExtras(infos);
activityIntent.setAction(data.getTitle());
rv.setOnClickFillInIntent(R.id.card, activityIntent);
} catch (Exception e) {
}
return rv;
}
use of net.dean.jraw.models.Submission in project Slide by ccrama.
the class MainActivity method onCreate.
@Override
protected void onCreate(final Bundle savedInstanceState) {
inNightMode = SettingValues.isNight();
disableSwipeBackLayout();
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
// Activity was brought to front and not created
finish();
return;
}
if (!Slide.hasStarted) {
Slide.hasStarted = true;
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
boolean first = false;
if (Reddit.colors != null && !Reddit.colors.contains("firstStart53")) {
new AlertDialogWrapper.Builder(this).setTitle("Content settings have moved!").setMessage("NSFW content is now disabled by default. If you are over the age of 18, to re-enable NSFW content, visit Settings > Content settings").setPositiveButton(R.string.btn_ok, null).setCancelable(false).show();
Reddit.colors.edit().putBoolean("firstStart53", true).apply();
}
if (Reddit.colors != null && !Reddit.colors.contains("Tutorial")) {
first = true;
if (Reddit.appRestart == null) {
Reddit.appRestart = getSharedPreferences("appRestart", 0);
}
Reddit.appRestart.edit().putBoolean("firststart52", true).apply();
Intent i = new Intent(this, Tutorial.class);
doForcePrefs();
startActivity(i);
} else {
if (Authentication.didOnline && NetworkUtil.isConnected(MainActivity.this) && !checkedPopups) {
runAfterLoad = new Runnable() {
@Override
public void run() {
runAfterLoad = null;
if (Authentication.isLoggedIn) {
new AsyncNotificationBadge().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if (!Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, "").isEmpty()) {
new CheckForMail.AsyncGetSubs(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
new AsyncTask<Void, Void, Submission>() {
@Override
protected Submission doInBackground(Void... params) {
if (Authentication.isLoggedIn)
UserSubscriptions.doOnlineSyncing();
try {
SubredditPaginator p = new SubredditPaginator(Authentication.reddit, "slideforreddit");
p.setLimit(2);
ArrayList<Submission> posts = new ArrayList<>(p.next());
for (Submission s : posts) {
String version = BuildConfig.VERSION_NAME;
if (version.length() > 5) {
version = version.substring(0, version.lastIndexOf("."));
}
if (s.isStickied() && s.getSubmissionFlair().getText() != null && s.getSubmissionFlair().getText().equalsIgnoreCase("Announcement") && !Reddit.appRestart.contains("announcement" + s.getFullName()) && s.getTitle().contains(version)) {
Reddit.appRestart.edit().putBoolean("announcement" + s.getFullName(), true).apply();
return s;
} else if (BuildConfig.VERSION_NAME.contains("alpha") && s.isStickied() && s.getSubmissionFlair().getText() != null && s.getSubmissionFlair().getText().equalsIgnoreCase("Alpha") && !Reddit.appRestart.contains("announcement" + s.getFullName()) && s.getTitle().contains(BuildConfig.VERSION_NAME)) {
Reddit.appRestart.edit().putBoolean("announcement" + s.getFullName(), true).apply();
return s;
} else if (s.isStickied() && s.getSubmissionFlair().getText().equalsIgnoreCase("PRO") && !SettingValues.tabletUI && !Reddit.appRestart.contains("announcement" + s.getFullName())) {
Reddit.appRestart.edit().putBoolean("announcement" + s.getFullName(), true).apply();
return s;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(final Submission s) {
checkedPopups = true;
if (s != null) {
Reddit.appRestart.edit().putString("page", s.getDataNode().get("selftext_html").asText()).apply();
Reddit.appRestart.edit().putString("title", s.getTitle()).apply();
Reddit.appRestart.edit().putString("url", s.getUrl()).apply();
String title;
if (s.getTitle().toLowerCase(Locale.ENGLISH).contains("release")) {
title = getString(R.string.btn_changelog);
} else {
title = getString(R.string.btn_view);
}
Snackbar snack = Snackbar.make(pager, s.getTitle(), Snackbar.LENGTH_INDEFINITE).setAction(title, new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(MainActivity.this, Announcement.class);
startActivity(i);
}
});
View view = snack.getView();
TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
snack.show();
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// todo this new AsyncStartNotifSocket().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
};
}
}
if (savedInstanceState != null && !changed) {
Authentication.isLoggedIn = savedInstanceState.getBoolean(LOGGED_IN);
Authentication.name = savedInstanceState.getString(USERNAME, "LOGGEDOUT");
Authentication.didOnline = savedInstanceState.getBoolean(IS_ONLINE);
} else {
changed = false;
}
if (getIntent().getBooleanExtra("EXIT", false))
finish();
applyColorTheme();
setContentView(R.layout.activity_overview);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setPopupTheme(new ColorPreferences(this).getFontStyle().getBaseId());
setSupportActionBar(mToolbar);
if (getIntent() != null && getIntent().hasExtra(EXTRA_PAGE_TO)) {
toGoto = getIntent().getIntExtra(EXTRA_PAGE_TO, 0);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = this.getWindow();
window.setStatusBarColor(Palette.getDarkerColor(Palette.getDarkerColor(Palette.getDefaultColor())));
}
mTabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
header = findViewById(R.id.header);
// Gets the height of the header
if (header != null) {
header.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
headerHeight = header.getHeight();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
header.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
header.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
pager = (ToggleSwipeViewPager) findViewById(R.id.content_view);
singleMode = SettingValues.single;
if (singleMode) {
commentPager = SettingValues.commentPager;
}
// Inflate tabs if single mode is disabled
if (!singleMode) {
mTabLayout = (TabLayout) ((ViewStub) findViewById(R.id.stub_tabs)).inflate();
}
// Disable swiping if single mode is enabled
if (singleMode) {
pager.setSwipingEnabled(false);
}
sidebarBody = (SpoilerRobotoTextView) findViewById(R.id.sidebar_text);
sidebarOverflow = (CommentOverflow) findViewById(R.id.commentOverflow);
if (!Reddit.appRestart.getBoolean("isRestarting", false) && Reddit.colors.contains("Tutorial")) {
LogUtil.v("Starting main " + Authentication.name);
Authentication.isLoggedIn = Reddit.appRestart.getBoolean("loggedin", false);
Authentication.name = Reddit.appRestart.getString("name", "LOGGEDOUT");
UserSubscriptions.doMainActivitySubs(this);
} else if (!first) {
LogUtil.v("Starting main 2 " + Authentication.name);
Authentication.isLoggedIn = Reddit.appRestart.getBoolean("loggedin", false);
Authentication.name = Reddit.appRestart.getString("name", "LOGGEDOUT");
Reddit.appRestart.edit().putBoolean("isRestarting", false).commit();
Reddit.isRestarting = false;
UserSubscriptions.doMainActivitySubs(this);
}
final SharedPreferences seen = getSharedPreferences("SEEN", 0);
if (!seen.contains("isCleared") && !seen.getAll().isEmpty() || !Reddit.appRestart.contains("hasCleared")) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
KVManger m = KVStore.getInstance();
Map<String, ?> values = seen.getAll();
for (Map.Entry<String, ?> entry : values.entrySet()) {
if (entry.getKey().length() == 6 && entry.getValue() instanceof Boolean) {
m.insert(entry.getKey(), "true");
} else if (entry.getValue() instanceof Long) {
m.insert(entry.getKey(), String.valueOf(seen.getLong(entry.getKey(), 0)));
}
}
seen.edit().clear().putBoolean("isCleared", true).apply();
if (getSharedPreferences("HIDDEN_POSTS", 0).getAll().size() != 0) {
getSharedPreferences("HIDDEN", 0).edit().clear().apply();
getSharedPreferences("HIDDEN_POSTS", 0).edit().clear().apply();
}
if (!Reddit.appRestart.contains("hasCleared")) {
SharedPreferences.Editor e = Reddit.appRestart.edit();
Map<String, ?> toClear = Reddit.appRestart.getAll();
for (Map.Entry<String, ?> entry : toClear.entrySet()) {
if (entry.getValue() instanceof String && ((String) entry.getValue()).length() > 300) {
e.remove(entry.getKey());
}
}
e.putBoolean("hasCleared", true);
e.apply();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
dismissProgressDialog();
}
@Override
protected void onPreExecute() {
d = new MaterialDialog.Builder(MainActivity.this).title(R.string.misc_setting_up).content(R.string.misc_setting_up_message).progress(true, 100).cancelable(false).build();
d.show();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if (!FDroid.isFDroid && Authentication.isLoggedIn && NetworkUtil.isConnected(MainActivity.this)) {
// Display an snackbar that asks the user to rate the app after this
// activity was created 6 times, never again when once clicked or with a maximum of
// two times.
SnackEngage.from(MainActivity.this).withSnack(new RateSnack().withConditions(new NeverAgainWhenClickedOnce(), new AfterNumberOfOpportunities(10), new WithLimitedNumberOfTimes(2)).overrideActionText(getString(R.string.misc_rate_msg)).overrideTitleText(getString(R.string.misc_rate_title)).withDuration(BaseSnack.DURATION_LONG)).build().engageWhenAppropriate();
}
if (SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_TOOLBAR || SettingValues.subredditSearchMethod == Constants.SUBREDDIT_SEARCH_METHOD_BOTH) {
setupSubredditSearchToolbar();
}
/**
* int for the current base theme selected.
* 0 = Dark, 1 = Light, 2 = AMOLED, 3 = Dark blue, 4 = AMOLED with contrast, 5 = Sepia
*/
SettingValues.currentTheme = new ColorPreferences(this).getFontStyle().getThemeType();
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
try {
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
}
}
Aggregations