Merge branch 'develop' into pixelfed_stories

# Conflicts:
#	app/src/main/java/app/fedilab/android/client/APIResponse.java
This commit is contained in:
tom79 2020-01-18 15:00:26 +01:00
commit 9f711a9be5
289 changed files with 10544 additions and 4968 deletions

View File

@ -14,6 +14,7 @@ stages:
stage: build-and-test
retry: 2
assembleDebug:
<<: *no-upload
cache:
@ -39,6 +40,7 @@ debugTests:
except:
- tags
## PROTECTED VARIABLES TO SET IN GITLAB:
# - GITLAB_API_TOKEN: token you create on Gitlab
# - NC_REMOTE_DIR: like https://YOUR_NEXTCLOUD/remote.php/dav/files/YOUR_USER/mastalab (no trailing slash)

View File

@ -40,9 +40,9 @@
<img src="./images/device-2019-02-02-114910.png" width="250">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Lead developer: [framapiaf.org/@fedilab](https://framapiaf.org/@fedilab)
Lead developer: [toot.fedilab.app/@fedilab](https://toot.fedilab.app/@fedilab)
<br>
Developer: [mastodon.social/@kasun](https://mastodon.social/@kasun)
Developer: [toot.fedilab.app/@kasun](https://toot.fedilab.app/@kasun)
## Backers

View File

@ -6,8 +6,8 @@ android {
defaultConfig {
minSdkVersion 19
targetSdkVersion 29
versionCode 334
versionName "2.25.0-beta-2"
versionCode 346
versionName "2.28.2"
multiDexEnabled true
renderscriptTargetApi 28 as int
renderscriptSupportModeEnabled true
@ -55,6 +55,20 @@ allprojects {
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
}
task copyAllReleaseNotes(type: Copy) {
from "$buildDir/../src/main/assets/changelogs/"
include "*.txt"
into "$buildDir/../../fastlane/metadata/android/en-US/changelogs/"
}
task gitPushReleaseNotes(type: Exec, dependsOn: 'copyAllReleaseNotes') {
['sh', '-c', "git add $buildDir/../../fastlane/metadata/android/en-US/changelogs/*"].execute().text.trim()
['sh', '-c', "git commit -m 'copy release notes'"].execute().text.trim()
['sh', '-c', "git push"].execute().text.trim()
}
ext.supportLibraryVersion = '29.0.2'
ext.glideLibraryVersion = '4.9.0'
ext.conscryptLibraryVersion = '2.2.1'
@ -74,11 +88,15 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.browser:browser:1.0.0'
implementation 'androidx.exifinterface:exifinterface:1.0.0'
implementation 'androidx.exifinterface:exifinterface:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "com.github.bumptech.glide:glide:$glideLibraryVersion"
implementation ("com.github.bumptech.glide:recyclerview-integration:$glideLibraryVersion") {
// Excludes the support library because it's already included by Glide.
transitive = false
}
annotationProcessor "com.github.bumptech.glide:compiler:$glideLibraryVersion"
annotationProcessor 'com.android.support:support-annotations:28.0.0'
implementation "org.conscrypt:conscrypt-android:$conscryptLibraryVersion"
@ -88,7 +106,7 @@ dependencies {
implementation "com.github.chrisbanes:PhotoView:$photoViewLibraryVersion"
implementation 'com.r0adkll:slidableactivity:2.1.0'
implementation 'com.github.stom79:country-picker-android:1.2.0'
implementation 'com.github.stom79:mytransl:1.5'
implementation 'com.github.stom79:mytransl:2.0'
implementation 'com.github.stom79:SparkButton:1.0.13'
implementation "com.koushikdutta.async:androidasync:2.+"
implementation 'com.vanniktech:emoji-one:0.6.0'
@ -100,7 +118,6 @@ dependencies {
implementation 'com.google.android.exoplayer:exoplayer:2.10.6'
implementation 'org.apache.poi:poi:3.16'
implementation 'com.github.mabbas007:TagsEditText:1.0.5'
implementation 'com.jaredrummler:material-spinner:1.3.1'
implementation "com.tonyodev.fetch2:fetch2:2.3.6"
implementation 'com.github.stom79:horizontalbargraph:1.6'
implementation 'jp.wasabeef:glide-transformations:4.0.0'
@ -125,6 +142,6 @@ dependencies {
implementation 'com.github.penfeizhou.android.animation:gif:1.1.0'
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
implementation 'com.github.smarteist:autoimageslider:1.3.2'
//debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-2'
//debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0'
implementation 'com.jaredrummler:cyanea:1.0.2'
}

View File

@ -41,6 +41,7 @@
android:required="false" />
<application
android:name="app.fedilab.android.activities.MainApplication"
android:requestLegacyExternalStorage="true"
android:allowBackup="false"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher_bubbles"
@ -89,7 +90,13 @@
<action android:name="StopLiveNotificationReceiver" />
</intent-filter>
</receiver>
<receiver
android:name="app.fedilab.android.services.StopDelayedNotificationReceiver"
android:exported="false">
<intent-filter>
<action android:name="StopDelayedNotificationReceiver" />
</intent-filter>
</receiver>
<service
android:name="app.fedilab.android.services.StreamingHomeTimelineService"
android:exported="false" />
@ -470,6 +477,10 @@
android:name="app.fedilab.android.activities.InstanceHealthActivity"
android:excludeFromRecents="true"
android:theme="@style/Base.V7.Theme.AppCompat.Dialog" />
<activity
android:name="app.fedilab.android.activities.InstanceProfileActivity"
android:excludeFromRecents="true"
android:theme="@style/Base.V7.Theme.AppCompat.Dialog" />
<activity
android:name="app.fedilab.android.activities.ProxyActivity"
android:excludeFromRecents="true"

View File

@ -0,0 +1,12 @@
Added
- Unshortened URLs can be copied or shared
- Trends in tags search
- Image are shared/stored from cache
- Message when a media is successfully downloaded
Fixed
- Issue with polls not displayed
- Notifications not stopped
- Pleroma wysiwyg
- Login issue
- Some crashes

View File

@ -0,0 +1,6 @@
Added
- Follow Nitter feeds (ie: Twitter account timelines)
Fixed
- Crash issue when no live notifications
- Trends can't be hidden

View File

@ -0,0 +1,14 @@
Added
- Original & boost dates added separately
- Follow request notifications
- Identity proofs support
Changed
- Media are preloaded when scrolling
- Improve live/delayed notifications
Fixed
- Counter for mentions
- Preview images displayed twice
- Media not saved on Android 10+
- Issue when following instances/pinging tags

View File

@ -0,0 +1,6 @@
Added
- Friendica: Authorize/Reject follow requests
Fixed
- Not cropped media
- Crash when starting the app

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

View File

@ -66,11 +66,9 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
private List<Account> developers = new ArrayList<>();
private List<Account> contributors = new ArrayList<>();
private List<Account> designers = new ArrayList<>();
private List<Account> uxuidesigners = new ArrayList<>();
private AccountSearchDevAdapter accountSearchWebAdapterDeveloper;
private AccountSearchDevAdapter accountSearchWebAdapterDesigner;
private AccountSearchDevAdapter accountSearchWebAdapterContributors;
private AccountSearchDevAdapter accountSearchWebAdapterUxUiDesigners;
@ -83,9 +81,6 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -97,10 +92,10 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(AboutActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(AboutActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -123,7 +118,6 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
}
ExpandableHeightListView lv_developers = findViewById(R.id.lv_developers);
ExpandableHeightListView lv_designers = findViewById(R.id.lv_designers);
ExpandableHeightListView lv_contributors = findViewById(R.id.lv_contributors);
ExpandableHeightListView lv_ux = findViewById(R.id.lv_ux);
@ -133,10 +127,10 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
Button about_trunk = findViewById(R.id.about_trunk);
TextView txt_developers, txt_ux, txt_designers, txt_thankyou1, txt_thankyou2;
TextView txt_developers, txt_ux, txt_thankyou3, txt_thankyou1, txt_thankyou2;
txt_developers = findViewById(R.id.txt_developers);
txt_ux = findViewById(R.id.txt_ux);
txt_designers = findViewById(R.id.txt_designers);
txt_thankyou3 = findViewById(R.id.txt_thankyou3);
txt_thankyou1 = findViewById(R.id.txt_thankyou1);
txt_thankyou2 = findViewById(R.id.txt_thankyou2);
@ -237,34 +231,31 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
setTitle(R.string.action_about);
lv_contributors.setExpanded(true);
lv_developers.setExpanded(true);
lv_designers.setExpanded(true);
lv_ux.setExpanded(true);
accountSearchWebAdapterContributors = new AccountSearchDevAdapter(contributors);
lv_contributors.setAdapter(accountSearchWebAdapterContributors);
accountSearchWebAdapterDesigner = new AccountSearchDevAdapter(designers);
lv_designers.setAdapter(accountSearchWebAdapterDesigner);
accountSearchWebAdapterDeveloper = new AccountSearchDevAdapter(developers);
lv_developers.setAdapter(accountSearchWebAdapterDeveloper);
accountSearchWebAdapterUxUiDesigners = new AccountSearchDevAdapter(uxuidesigners);
lv_ux.setAdapter(accountSearchWebAdapterUxUiDesigners);
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "fedilab", "framapiaf.org", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "kasun", "toot.fedilab.app", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "fedilab", "toot.fedilab.app", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "mmarif", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "kasun", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "PhotonQyv", "mastodon.xyz", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "angrytux", "social.tchncs.de", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteDataAsyncTask(getApplicationContext(), "guzzisti", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
SpannableString name = new SpannableString("@fedilab@framapiaf.org");
SpannableString name = new SpannableString("@fedilab@toot.fedilab.app");
name.setSpan(new UnderlineSpan(), 0, name.length(), 0);
txt_developers.setText(name);
txt_developers.setVisibility(View.VISIBLE);
txt_developers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Helper.openBrowser(AboutActivity.this, "https://framapiaf.org/@fedilab");
Helper.openBrowser(AboutActivity.this, "https://toot.fedilab.app/@fedilab");
}
});
name = new SpannableString("@mmarif@mastodon.social");
@ -297,25 +288,33 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
Helper.openBrowser(AboutActivity.this, "https://social.tchncs.de/@angrytux");
}
});
name = new SpannableString("@kasun@stoot.fedilab.app");
name.setSpan(new UnderlineSpan(), 0, name.length(), 0);
txt_thankyou3.setText(name);
txt_thankyou3.setVisibility(View.VISIBLE);
txt_thankyou3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Helper.openBrowser(AboutActivity.this, "https://toot.fedilab.app/@kasun");
}
});
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRetrieveRemoteAccount(Results results) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
public void onRetrieveRemoteAccount(Results results, boolean developerAccount) {
if (results == null) {
Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show();
return;
@ -330,10 +329,6 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
developers.add(account);
accountSearchWebAdapterDeveloper.notifyDataSetChanged();
break;
case "kasun":
designers.add(account);
accountSearchWebAdapterDesigner.notifyDataSetChanged();
break;
case "mmarif":
uxuidesigners.add(account);
accountSearchWebAdapterUxUiDesigners.notifyDataSetChanged();
@ -356,11 +351,6 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
if (designers != null) {
for (Account account : designers) {
new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
if (contributors != null) {
for (Account account : contributors) {
new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(), AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
@ -387,13 +377,6 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
break;
}
}
for (int i = 0; i < designers.size(); i++) {
if (designers.get(i).getId() != null && designers.get(i).getId().equals(relationship.getId())) {
designers.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId()));
accountSearchWebAdapterDesigner.notifyDataSetChanged();
break;
}
}
for (int i = 0; i < contributors.size(); i++) {
if (contributors.get(i).getId() != null && contributors.get(i).getId().equals(relationship.getId())) {
contributors.get(i).setFollowing(relationship.isFollowing() || userId.trim().equals(relationship.getId()));

View File

@ -26,6 +26,7 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
@ -70,10 +71,10 @@ public class AdminActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(AdminActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(AdminActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -362,7 +363,10 @@ public class AdminActivity extends BaseActivity {
return null;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
}
@Override
public int getCount() {
return 2;

View File

@ -6,6 +6,8 @@ import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.ActionMode;
import android.view.View;
import android.widget.Toast;
@ -21,6 +23,7 @@ import com.vanniktech.emoji.one.EmojiOneProvider;
import java.util.Timer;
import app.fedilab.android.BuildConfig;
import app.fedilab.android.helper.Helper;
import es.dmoral.toasty.Toasty;
@ -35,6 +38,7 @@ public class BaseActivity extends CyaneaAppCompatActivity {
public static final int READ_WRITE_STORAGE = 52;
public static Timer timer;
public static boolean canShowActionMode = true;
static {
Helper.installProvider();
@ -46,7 +50,7 @@ public class BaseActivity extends CyaneaAppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
/* if (BuildConfig.DEBUG) {
/*if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
@ -59,9 +63,10 @@ public class BaseActivity extends CyaneaAppCompatActivity {
.detectLeakedRegistrationObjects()
.detectActivityLeaks()
.penaltyLog()
.penaltyDeath()
// .penaltyDeath()
.build());
}*/
canShowActionMode = true;
super.onCreate(savedInstanceState);
}
@ -135,4 +140,14 @@ public class BaseActivity extends CyaneaAppCompatActivity {
Toasty.info(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onActionModeStarted(ActionMode mode) {
if (!canShowActionMode) {
mode.finish();
}
super.onActionModeStarted(mode);
}
}

View File

@ -33,21 +33,25 @@ import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.Patterns;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@ -71,9 +75,11 @@ import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.jaredrummler.materialspinner.MaterialSpinner;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
@ -92,6 +98,7 @@ import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.android.asynctasks.RetrieveInstanceAsyncTask;
import app.fedilab.android.asynctasks.RetrieveMetaDataAsyncTask;
import app.fedilab.android.asynctasks.RetrievePeertubeInformationAsyncTask;
import app.fedilab.android.asynctasks.RetrieveRelationshipAsyncTask;
import app.fedilab.android.asynctasks.RetrieveRemoteDataAsyncTask;
import app.fedilab.android.asynctasks.RetrieveStoriesAsyncTask;
import app.fedilab.android.asynctasks.SyncTimelinesAsyncTask;
@ -99,13 +106,16 @@ import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoByIDAsyncTask;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.client.Entities.Filters;
import app.fedilab.android.client.Entities.Instance;
import app.fedilab.android.client.Entities.ManageTimelines;
import app.fedilab.android.client.Entities.Relationship;
import app.fedilab.android.client.Entities.Results;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.TagTimeline;
import app.fedilab.android.client.Entities.Version;
import app.fedilab.android.drawers.AccountSearchDevAdapter;
import app.fedilab.android.fragments.DisplayAccountsFragment;
import app.fedilab.android.fragments.DisplayBookmarksPixelfedFragment;
import app.fedilab.android.fragments.DisplayDraftsFragment;
@ -124,12 +134,14 @@ import app.fedilab.android.fragments.TabLayoutNotificationsFragment;
import app.fedilab.android.fragments.TabLayoutScheduleFragment;
import app.fedilab.android.fragments.WhoToFollowFragment;
import app.fedilab.android.helper.CrossActions;
import app.fedilab.android.helper.ExpandableHeightListView;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.helper.MenuFloating;
import app.fedilab.android.interfaces.OnFilterActionInterface;
import app.fedilab.android.interfaces.OnRetrieveEmojiAccountInterface;
import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
import app.fedilab.android.interfaces.OnRetrieveMetaDataInterface;
import app.fedilab.android.interfaces.OnRetrieveRelationshipInterface;
import app.fedilab.android.interfaces.OnRetrieveRemoteAccountInterface;
import app.fedilab.android.interfaces.OnSyncTimelineInterface;
import app.fedilab.android.interfaces.OnUpdateAccountInfoInterface;
@ -148,7 +160,7 @@ import static app.fedilab.android.helper.Helper.changeDrawableColor;
public abstract class BaseMainActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener, OnUpdateAccountInfoInterface, OnRetrieveMetaDataInterface, OnRetrieveInstanceInterface, OnRetrieveRemoteAccountInterface, OnRetrieveEmojiAccountInterface, OnFilterActionInterface, OnSyncTimelineInterface {
implements NavigationView.OnNavigationItemSelectedListener, OnUpdateAccountInfoInterface, OnRetrieveMetaDataInterface, OnRetrieveInstanceInterface, OnRetrieveRemoteAccountInterface, OnRetrieveEmojiAccountInterface, OnFilterActionInterface, OnSyncTimelineInterface, OnRetrieveRelationshipInterface {
public static String currentLocale;
@ -185,6 +197,8 @@ public abstract class BaseMainActivity extends BaseActivity
private Activity activity;
private BroadcastReceiver hidde_menu, update_topbar;
private Instance instanceClass;
private View dialogReleaseNoteView;
private List<Account> developers;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -430,6 +444,15 @@ public abstract class BaseMainActivity extends BaseActivity
pTabLocal.setCustomView(R.layout.tab_badge);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_subscriptions, R.attr.iconColorMenu);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_overview, R.attr.iconColorMenu);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_trending_up, R.attr.iconColorMenu);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_recently_added, R.attr.iconColorMenu);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_home, R.attr.iconColorMenu);
@SuppressWarnings("ConstantConditions") @SuppressLint("CutPasteId")
ImageView iconSub = pTabsub.getCustomView().findViewById(R.id.tab_icon);
@ -522,6 +545,10 @@ public abstract class BaseMainActivity extends BaseActivity
//TabLayout.Tab pfTabDiscover = tabLayout.newTab();
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_notifications, R.attr.iconColorMenu);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_people, R.attr.iconColorMenu);
Helper.changeDrawableColor(getApplicationContext(),R.drawable.ic_home, R.attr.iconColorMenu);
pfTabHome.setCustomView(R.layout.tab_badge);
pfTabLocal.setCustomView(R.layout.tab_badge);
pfTabNotification.setCustomView(R.layout.tab_badge);
@ -628,9 +655,7 @@ public abstract class BaseMainActivity extends BaseActivity
}
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
Helper.startStreaming(BaseMainActivity.this);
}
Helper.startStreaming(BaseMainActivity.this);
if (hidde_menu != null)
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(hidde_menu);
@ -1123,10 +1148,12 @@ public abstract class BaseMainActivity extends BaseActivity
MenuFloating.tags = new ArrayList<>();
Helper.updateHeaderAccountInfo(activity, account, headerLayout);
//Locked account can see follow request
if (account.isLocked()) {
navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(true);
} else {
navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(false);
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA ) {
if (account.isLocked()) {
navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(true);
} else {
navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(false);
}
}
if (!BuildConfig.DONATIONS) {
@ -1179,7 +1206,6 @@ public abstract class BaseMainActivity extends BaseActivity
delete_instance.setVisibility(View.GONE);
}
});
final int[] count2 = {0};
// Asked once for notification opt-in
boolean popupShown = sharedpreferences.getBoolean(Helper.SET_POPUP_PUSH, false);
@ -1199,9 +1225,9 @@ public abstract class BaseMainActivity extends BaseActivity
//Live notification mode
final MaterialSpinner set_live_type = dialogView.findViewById(R.id.set_live_type);
final Spinner set_live_type = dialogView.findViewById(R.id.set_live_type);
String[] labels = {getString(R.string.live_notif), getString(R.string.live_delayed), getString(R.string.no_live_notif)};
ArrayAdapter<String> adapterLive = new ArrayAdapter<>(getApplicationContext(),
ArrayAdapter<String> adapterLive = new ArrayAdapter<>(BaseMainActivity.this,
android.R.layout.simple_spinner_dropdown_item, labels);
set_live_type.setAdapter(adapterLive);
TextView set_live_type_indication = dialogView.findViewById(R.id.set_live_type_indication);
@ -1216,10 +1242,10 @@ public abstract class BaseMainActivity extends BaseActivity
set_live_type_indication.setText(R.string.no_live_indication);
break;
}
set_live_type.setSelectedIndex(Helper.liveNotifType(getApplicationContext()));
set_live_type.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
set_live_type.setSelection(Helper.liveNotifType(getApplicationContext()));
set_live_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SharedPreferences.Editor editor = sharedpreferences.edit();
switch (position) {
case Helper.NOTIF_LIVE:
@ -1254,9 +1280,12 @@ public abstract class BaseMainActivity extends BaseActivity
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dialogBuilderOptin.setTitle(R.string.settings_popup_title);
dialogBuilderOptin.setCancelable(false);
dialogBuilderOptin.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() {
@ -1268,14 +1297,72 @@ public abstract class BaseMainActivity extends BaseActivity
}
});
try {
dialogBuilderOptin.show();
} catch (Exception ignored) {
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
dialogBuilderOptin.show();
}
}, 1000);
} catch (Exception ignored) {}
}else{
int lastReleaseNoteRead = sharedpreferences.getInt(Helper.SET_POPUP_RELEASE_NOTES, 0);
int versionCode = BuildConfig.VERSION_CODE;
if( lastReleaseNoteRead != versionCode ){ //Need to push release notes
if( social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA ) {
new RetrieveRemoteDataAsyncTask(getApplicationContext(), BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("changelogs/"+versionCode+".txt")));
String mLine;
StringBuilder finalContent = new StringBuilder();
while ((mLine = reader.readLine()) != null) {
finalContent.append(mLine).append("\n");
}
AlertDialog.Builder dialogBuilderOptin = new AlertDialog.Builder(BaseMainActivity.this, style);
LayoutInflater inflater = getLayoutInflater();
dialogReleaseNoteView = inflater.inflate(R.layout.popup_release_notes, new LinearLayout(getApplicationContext()), false);
dialogBuilderOptin.setView(dialogReleaseNoteView);
TextView release_title = dialogReleaseNoteView.findViewById(R.id.release_title);
TextView release_notes = dialogReleaseNoteView.findViewById(R.id.release_notes);
release_title.setText(getString(R.string.release_note_title, BuildConfig.VERSION_NAME));
release_notes.setText(finalContent);
dialogBuilderOptin.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
try {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (!BaseMainActivity.this.isFinishing()) {
dialogBuilderOptin.show();
}
}
}, 1000);
} catch (Exception ignored) {}
}
catch (IOException ignored) {}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {}
}
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Helper.SET_POPUP_RELEASE_NOTES, versionCode);
editor.apply();
}
}
Helper.switchLayout(BaseMainActivity.this);
mamageNewIntent(getIntent());
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
@ -1629,6 +1716,12 @@ public abstract class BaseMainActivity extends BaseActivity
}
@Override
protected void onPause() {
super.onPause();
@ -1684,6 +1777,13 @@ public abstract class BaseMainActivity extends BaseActivity
Intent myIntent = new Intent(BaseMainActivity.this, OwnerStatusActivity.class);
startActivity(myIntent);
return false;
}if (id == R.id.nav_trends) {
Intent myIntent = new Intent(BaseMainActivity.this, SearchResultActivity.class);
Bundle b = new Bundle();
b.putString("search", "fedilab_trend");
myIntent.putExtras(b);
startActivity(myIntent);
return false;
} else if (id == R.id.nav_archive_notifications) {
Intent myIntent = new Intent(BaseMainActivity.this, OwnerNotificationActivity.class);
startActivity(myIntent);
@ -1992,23 +2092,49 @@ public abstract class BaseMainActivity extends BaseActivity
}
@Override
public void onRetrieveRemoteAccount(Results results) {
public void onRetrieveRemoteAccount(Results results, boolean developerAccount) {
if (results == null)
return;
List<Account> accounts = results.getAccounts();
List<Status> statuses = results.getStatuses();
if (accounts != null && accounts.size() > 0) {
Intent intent = new Intent(BaseMainActivity.this, ShowAccountActivity.class);
Bundle b = new Bundle();
b.putParcelable("account", accounts.get(0));
intent.putExtras(b);
startActivity(intent);
} else if (statuses != null && statuses.size() > 0) {
Intent intent = new Intent(getApplicationContext(), ShowConversationActivity.class);
Bundle b = new Bundle();
b.putParcelable("status", statuses.get(0));
intent.putExtras(b);
startActivity(intent);
if( !developerAccount) {
if (accounts != null && accounts.size() > 0) {
Intent intent = new Intent(BaseMainActivity.this, ShowAccountActivity.class);
Bundle b = new Bundle();
b.putParcelable("account", accounts.get(0));
intent.putExtras(b);
startActivity(intent);
} else if (statuses != null && statuses.size() > 0) {
Intent intent = new Intent(getApplicationContext(), ShowConversationActivity.class);
Bundle b = new Bundle();
b.putParcelable("status", statuses.get(0));
intent.putExtras(b);
startActivity(intent);
}
}else{
if( accounts != null && accounts.size() > 0 ) {
developers = new ArrayList<>();
developers.addAll(accounts);
new RetrieveRelationshipAsyncTask(getApplicationContext(), accounts.get(0).getId(), BaseMainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
@Override
public void onRetrieveRelationship(Relationship relationship, Error error) {
if( dialogReleaseNoteView != null && developers != null && developers.size() > 0){
if( !relationship.isFollowing()){
TextView dev_follow_title = dialogReleaseNoteView.findViewById(R.id.dev_follow_title);
if( dev_follow_title != null){
dev_follow_title.setVisibility(View.VISIBLE);
}
ExpandableHeightListView lv_developers = dialogReleaseNoteView.findViewById(R.id.lv_developers);
lv_developers.setExpanded(true);
AccountSearchDevAdapter accountSearchWebAdapterDeveloper = new AccountSearchDevAdapter(developers);
lv_developers.setAdapter(accountSearchWebAdapterDeveloper);
accountSearchWebAdapterDeveloper.notifyDataSetChanged();
}
}
}
@ -2044,12 +2170,6 @@ public abstract class BaseMainActivity extends BaseActivity
if (position >= manageTimelines.size()) {
position = manageTimelines.size() - 1;
}
if (position == -1)
position = (timelines.size() - 1);
if (position < 0)
position = 0;
if (toolbarTitle != null)
viewPager.setOffscreenPageLimit(2);
main_app_container = findViewById(R.id.main_app_container);
boolean iconOnly = true;
@ -2139,8 +2259,6 @@ public abstract class BaseMainActivity extends BaseActivity
displayStatusFragment.scrollToTop();
}
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
});
@ -2307,6 +2425,8 @@ public abstract class BaseMainActivity extends BaseActivity
return toot.getVisibility() == View.VISIBLE;
}
public enum iconLauncher {
BUBBLES,
FEDIVERSE,
@ -2327,6 +2447,8 @@ public abstract class BaseMainActivity extends BaseActivity
this.mNumOfTabs = NumOfTabs;
}
@Override
public Parcelable saveState() {
return null;
@ -2466,7 +2588,7 @@ public abstract class BaseMainActivity extends BaseActivity
} else {
mPageReferenceMap = new HashMap<>();
}
super.destroyItem(container, position, object);
// super.destroyItem(container, position, object);
}
@Override

View File

@ -95,10 +95,11 @@ public class BookmarkActivity extends BaseActivity implements OnRetrieveFeedsInt
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(BookmarkActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false);
toolbar.setBackgroundColor(ContextCompat.getColor(BookmarkActivity.this, R.color.cyanea_primary));
view.setBackground(new ColorDrawable(ContextCompat.getColor(BookmarkActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title);

View File

@ -98,10 +98,10 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(CustomSharingActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(CustomSharingActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title);

View File

@ -125,10 +125,10 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(EditProfileActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(EditProfileActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
@ -456,10 +456,10 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou
new Thread(new Runnable() {
@Override
public void run() {
GlideApp.get(getApplicationContext()).clearDiskCache();
Glide.get(getApplicationContext()).clearDiskCache();
}
}).start();
GlideApp.get(getApplicationContext()).clearMemory();
Glide.get(getApplicationContext()).clearMemory();
HashMap<String, String> newCustomFields = new HashMap<>();
String key1, key2, key3, key4, val1, val2, val3, val4;

View File

@ -25,6 +25,7 @@ import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@ -110,7 +111,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf
swipeRefreshLayout.setColorSchemeColors(
c1, c2, c1
);
toolbar.setBackgroundColor(ContextCompat.getColor(GroupActivity.this, R.color.cyanea_primary));
final RecyclerView lv_status = findViewById(R.id.lv_status);
//lv_status.addItemDecoration(new DividerItemDecoration(GroupActivity.this, DividerItemDecoration.VERTICAL));
tootsPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE);

View File

@ -27,6 +27,7 @@ import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
@ -78,9 +79,6 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_NoActionBar_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark_NoActionBar);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack_NoActionBar);
break;
@ -95,8 +93,9 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle b = getIntent().getExtras();
if (b != null)
if (b != null) {
tag = b.getString("tag", null);
}
if (tag == null)
finish();
statuses = new ArrayList<>();
@ -112,7 +111,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
swipeRefreshLayout.setColorSchemeColors(
c1, c2, c1
);
toolbar.setBackgroundColor(ContextCompat.getColor(HashTagActivity.this, R.color.cyanea_primary));
final RecyclerView lv_status = findViewById(R.id.lv_status);
tootsPerPage = sharedpreferences.getInt(Helper.SET_TOOT_PER_PAGE, Helper.TOOTS_PER_PAGE);
mainLoader = findViewById(R.id.loader);
@ -187,6 +186,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
SQLiteDatabase db = Sqlite.getInstance(HashTagActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new SearchDAO(HashTagActivity.this, db).insertSearch(tag);
Intent intent = new Intent(HashTagActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Helper.INTENT_ACTION, Helper.SEARCH_TAG);
intent.putExtra(Helper.SEARCH_KEYWORD, tag);
startActivity(intent);

View File

@ -82,10 +82,10 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(InstanceActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(InstanceActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);

View File

@ -124,17 +124,26 @@ public class InstanceHealthActivity extends BaseActivity {
private void checkInstance() {
if (instance == null)
if (instance == null){
LinearLayout main_container = findViewById(R.id.main_container);
TextView no_instance = findViewById(R.id.no_instance);
instance_container.setVisibility(View.VISIBLE);
main_container.setVisibility(View.GONE);
no_instance.setVisibility(View.VISIBLE);
loader.setVisibility(View.GONE);
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
HashMap<String, String> parameters = new HashMap<>();
parameters.put("name", instance.trim());
final String response = new HttpsConnection(InstanceHealthActivity.this, instance).get("https://instances.social/api/1.0/instances/show", 30, parameters, Helper.THEKINRAR_SECRET_TOKEN);
if (response != null)
final String response = new HttpsConnection(InstanceHealthActivity.this, instance).get("https://instances.social/api/1.0/instances/show", 5, parameters, Helper.THEKINRAR_SECRET_TOKEN);
if (response != null) {
instanceSocial = API.parseInstanceSocialResponse(getApplicationContext(), new JSONObject(response));
}
runOnUiThread(new Runnable() {
@SuppressLint({"SetTextI18n", "DefaultLocale"})
public void run() {
@ -160,7 +169,17 @@ public class InstanceHealthActivity extends BaseActivity {
}
});
} catch (Exception ignored) {
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
LinearLayout main_container = findViewById(R.id.main_container);
TextView no_instance = findViewById(R.id.no_instance);
instance_container.setVisibility(View.VISIBLE);
main_container.setVisibility(View.GONE);
no_instance.setVisibility(View.VISIBLE);
loader.setVisibility(View.GONE);
}
});
}
}
}).start();

View File

@ -0,0 +1,178 @@
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
package app.fedilab.android.activities;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.android.R;
import app.fedilab.android.asynctasks.RetrieveAccountsAsyncTask;
import app.fedilab.android.client.API;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.InstanceNodeInfo;
import app.fedilab.android.drawers.AccountsListAdapter;
import app.fedilab.android.helper.Helper;
import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY;
/**
* Created by Thomas on 15/11/2019.
* Instance info activity class
*/
public class InstanceProfileActivity extends BaseActivity {
private TextView name, description, userCount, statusCount, instanceCount, software, version;
private String instance;
private RecyclerView lv_accounts;
private ConstraintLayout instance_container;
private ImageView back_ground_image;
private ProgressBar loader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if (theme == Helper.THEME_LIGHT) {
setTheme(R.style.Dialog);
} else {
setTheme(R.style.DialogDark);
}
setContentView(R.layout.activity_instance_profile);
getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Bundle b = getIntent().getExtras();
if (getSupportActionBar() != null)
getSupportActionBar().hide();
if (b != null)
instance = b.getString("instance",null);
if( instance == null){
finish();
}
Button close = findViewById(R.id.close);
name = findViewById(R.id.name);
description = findViewById(R.id.description);
userCount = findViewById(R.id.user_count);
statusCount = findViewById(R.id.status_count);
instanceCount = findViewById(R.id.instance_count);
instance_container = findViewById(R.id.instance_container);
loader = findViewById(R.id.loader);
back_ground_image = findViewById(R.id.back_ground_image);
software = findViewById(R.id.software);
version = findViewById(R.id.version);
lv_accounts = findViewById(R.id.lv_accounts);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
checkInstance();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkInstance() {
if (instance == null)
return;
new Thread(new Runnable() {
@Override
public void run() {
try {
InstanceNodeInfo instanceNodeInfo = new API(InstanceProfileActivity.this).instanceInfo(instance.trim());
runOnUiThread(new Runnable() {
public void run() {
if( instanceNodeInfo == null){
finish();
return;
}
if (instanceNodeInfo.getThumbnail() != null && !instanceNodeInfo.getThumbnail().equals("null"))
Glide.with(getApplicationContext())
.asBitmap()
.load(instanceNodeInfo.getThumbnail())
.into(back_ground_image);
name.setText(instanceNodeInfo.getNodeName());
SpannableString descriptionSpan;
if( instanceNodeInfo.getNodeDescription() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
descriptionSpan = new SpannableString(Html.fromHtml(instanceNodeInfo.getNodeDescription(), FROM_HTML_MODE_LEGACY));
else
descriptionSpan = new SpannableString(Html.fromHtml(instanceNodeInfo.getNodeDescription()));
description.setText(descriptionSpan, TextView.BufferType.SPANNABLE);
}
userCount.setText(Helper.withSuffix((instanceNodeInfo.getNumberOfUsers())));
statusCount.setText(Helper.withSuffix((instanceNodeInfo.getNumberOfPosts())));
instanceCount.setText(Helper.withSuffix((instanceNodeInfo.getNumberOfInstance())));
software.setText(instanceNodeInfo.getName() + " - ");
version.setText(instanceNodeInfo.getVersion());
if( instanceNodeInfo.getStaffAccount() != null){
List<Account> accounts = new ArrayList<>();
accounts.add(instanceNodeInfo.getStaffAccount());
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
AccountsListAdapter accountsListAdapter = new AccountsListAdapter(RetrieveAccountsAsyncTask.Type.FOLLOWERS, userId, accounts);
lv_accounts.setAdapter(accountsListAdapter);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(InstanceProfileActivity.this);
lv_accounts.setLayoutManager(mLayoutManager);
}
instance_container.setVisibility(View.VISIBLE);
loader.setVisibility(View.GONE);
}
});
} catch (Exception ignored) {
}
}
}).start();
}
}

View File

@ -34,6 +34,7 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -92,6 +93,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface
}
setContentView(R.layout.activity_list);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setBackgroundColor(ContextCompat.getColor(ListActivity.this, R.color.cyanea_primary));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

View File

@ -63,6 +63,10 @@ public class LiveNotificationSettingsAccountsActivity extends BaseActivity {
ArrayList<Account> accounts = new ArrayList<>();
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Account> accountStreams = new AccountDAO(getApplicationContext(), db).getAllAccountCrossAction();
if( accountStreams == null || accountStreams.size() == 0 ){
finish();
return;
}
for (Account account : accountStreams) {
if (account.getSocial() == null || account.getSocial().equals("MASTODON") || account.getSocial().equals("PLEROMA") || account.getSocial().equals("PIXELFED")) {
accounts.add(account);

View File

@ -51,6 +51,7 @@ import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
@ -95,7 +96,6 @@ public class LoginActivity extends BaseActivity {
private static boolean client_id_for_webview = false;
private static String instance;
private final int PICK_IMPORT = 5557;
boolean isLoadingInstance = false;
private AutoCompleteTextView login_instance;
private EditText login_uid;
private EditText login_passwd;
@ -103,13 +103,12 @@ public class LoginActivity extends BaseActivity {
private Button connectionButton, connect_button;
private String actionToken;
private String autofilledInstance;
private String social;
private UpdateAccountInfoAsyncTask.SOCIAL socialNetwork;
private String basicAuth;
private InstanceNodeInfo instanceNodeInfo;
private LinearLayout step_login_credential, step_instance;
private ConstraintLayout step_login_credential, step_instance;
private TextView instance_chosen;
private ImageView info_instance;
private Thread thread = null;
public static String redirectUserToAuthorizeAndLogin(Context context, UpdateAccountInfoAsyncTask.SOCIAL socialNetwork, String clientId, String instance) {
String queryString = Helper.CLIENT_ID + "=" + clientId;
@ -131,7 +130,6 @@ public class LoginActivity extends BaseActivity {
admin = false;
if (b != null) {
autofilledInstance = b.getString("instance", null);
social = b.getString("social", null);
if (instanceNodeInfo != null) {
socialNetwork = Helper.setSoftware(instanceNodeInfo.getName(), false);
}
@ -183,9 +181,6 @@ public class LoginActivity extends BaseActivity {
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -196,10 +191,10 @@ public class LoginActivity extends BaseActivity {
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(LoginActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(LoginActivity.this), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(LoginActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -246,7 +241,7 @@ public class LoginActivity extends BaseActivity {
instance_chosen = findViewById(R.id.instance_chosen);
step_instance = findViewById(R.id.step_instance);
connectionButton = findViewById(R.id.login_button);
info_instance = findViewById(R.id.info_instance);
ImageView info_instance = findViewById(R.id.info_instance);
ImageView main_logo = findViewById(R.id.main_logo);
main_logo.setImageResource(Helper.getMainLogo(getApplicationContext()));
socialNetwork = UpdateAccountInfoAsyncTask.SOCIAL.MASTODON;
@ -280,7 +275,6 @@ public class LoginActivity extends BaseActivity {
connect_button.setEnabled(true);
if (instanceNodeInfo != null && instanceNodeInfo.getName() != null) {
socialNetwork = Helper.setSoftware(instanceNodeInfo.getName(), false);
if (instanceNodeInfo.getName().equals("PLEROMA") || instanceNodeInfo.getName().equals("MASTODON") || instanceNodeInfo.getName().equals("PIXELFED")) {
client_id_for_webview = true;
retrievesClientId();
@ -331,22 +325,37 @@ public class LoginActivity extends BaseActivity {
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 2 && !isLoadingInstance) {
if (s.length() > 2) {
final String action = "/instances/search";
final HashMap<String, String> parameters = new HashMap<>();
parameters.put("q", s.toString().trim());
String query = s.toString().trim();
if (query.startsWith("http://")){
query =query.replace("http://", "");
}
if (query.startsWith("https://")){
query =query.replace("https://", "");
}
parameters.put("q", query);
parameters.put("count", String.valueOf(1000));
parameters.put("name", String.valueOf(true));
isLoadingInstance = true;
if (oldSearch == null || !oldSearch.equals(s.toString().trim()))
new Thread(new Runnable() {
if( thread != null && thread.isAlive()){
thread.interrupt();
thread = null;
}
if (oldSearch == null || !oldSearch.equals(s.toString().trim())) {
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
final String response = new HttpsConnection(LoginActivity.this, instance).get("https://instances.social/api/1.0" + action, 30, parameters, Helper.THEKINRAR_SECRET_TOKEN);
if( response == null) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
isLoadingInstance = false;
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
@ -373,27 +382,29 @@ public class LoginActivity extends BaseActivity {
oldSearch = s.toString().trim();
} catch (JSONException ignored) {
isLoadingInstance = false;
}
}
});
} catch (Exception e) {
isLoadingInstance = false;
e.printStackTrace();
}
}
}).start();
});
thread.start();
}
}
}
});
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU)
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
connectionButton.setEnabled(false);
login_instance.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU)
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
connectionButton.setEnabled(false);
}
TextInputLayout login_instance_layout = findViewById(R.id.login_instance_layout);
if (!hasFocus) {
retrievesClientId();
@ -465,8 +476,14 @@ public class LoginActivity extends BaseActivity {
}
private void retrievesClientId() {
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
String instanceFromField = login_instance.getText().toString().trim();
if (instanceFromField.startsWith("http://")){
instanceFromField =instanceFromField.replace("http://", "");
}
if (instanceFromField.startsWith("https://")){
instanceFromField =instanceFromField.replace("https://", "");
}
String host = instanceFromField;
try {
URL url = new URL(instanceFromField);
@ -564,7 +581,7 @@ public class LoginActivity extends BaseActivity {
final HashMap<String, String> parameters = new HashMap<>();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
parameters.put(Helper.CLIENT_ID, sharedpreferences.getString(Helper.CLIENT_ID, null));
parameters.put(Helper.CLIENT_SECRET, sharedpreferences.getString(Helper.CLIENT_SECRET, null));
}
@ -586,7 +603,7 @@ public class LoginActivity extends BaseActivity {
} else if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
parameters.put("scope", "user");
oauthUrl = "/api/v1/users/token";
} else if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
} else if (socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.GNU || socialNetwork == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
String instanceFromField = login_instance.getText().toString().trim();
String host;
try {
@ -611,21 +628,21 @@ public class LoginActivity extends BaseActivity {
public void run() {
try {
String response;
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU)
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
response = new HttpsConnection(LoginActivity.this, instance).post(Helper.instanceWithProtocol(getApplicationContext(), instance) + finalOauthUrl, 30, parameters, null);
else {
} else {
response = new HttpsConnection(LoginActivity.this, instance).get(Helper.instanceWithProtocol(getApplicationContext(), instance) + finalOauthUrl, 30, null, basicAuth);
}
runOnUiThread(new Runnable() {
public void run() {
JSONObject resobj;
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
if (socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.GNU && socialNetwork != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
try {
resobj = new JSONObject(response);
String token = resobj.get("access_token").toString();
String refresh_token = null;
if (resobj.has("refresh_token"))
refresh_token = resobj.get("refresh_token").toString();
refresh_token = resobj.getString("refresh_token");
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token);
@ -729,7 +746,7 @@ public class LoginActivity extends BaseActivity {
menu.findItem(R.id.action_custom_tabs).setChecked(!embedded_browser);
boolean security_provider = sharedpreferences.getBoolean(Helper.SET_SECURITY_PROVIDER, true);
menu.findItem(R.id.action_provider).setChecked(security_provider);
return super.onCreateOptionsMenu(menu);
return true;
}
@Override

View File

@ -32,12 +32,14 @@ import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@ -47,8 +49,6 @@ import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.jaredrummler.materialspinner.MaterialSpinner;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
@ -91,9 +91,6 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -104,10 +101,10 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
setContentView(R.layout.activity_register);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(MastodonRegisterActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(MastodonRegisterActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -122,7 +119,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
}
MaterialSpinner reg_category = findViewById(R.id.reg_category);
Spinner reg_category = findViewById(R.id.reg_category);
String[] categoriesA = {
getString(R.string.category_general),
getString(R.string.category_regional),
@ -155,12 +152,16 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
reg_category.setAdapter(adcategories);
reg_category.setSelectedIndex(0);
reg_category.setSelection(0);
//Manage privacies
reg_category.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
reg_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
new RetrieveInstanceRegAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, itemA[position], MastodonRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
@ -217,7 +218,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
@Override
public void onRetrieveInstance(APIResponse apiResponse) {
if (apiResponse.getError() != null) {
if (apiResponse.getError() != null || apiResponse.getInstanceRegs() == null) {
Toasty.error(getApplicationContext(), getString(R.string.toast_error_instance_reg), Toast.LENGTH_LONG).show();
return;
}

View File

@ -98,10 +98,10 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet
setContentView(R.layout.activity_register);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(MastodonShareRegisterActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(MastodonShareRegisterActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -188,7 +188,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet
@Override
public void onRetrieveInstance(APIResponse apiResponse) {
if (apiResponse.getError() != null) {
if (apiResponse.getError() != null || apiResponse.getInstanceRegs() == null) {
Toasty.error(getApplicationContext(), getString(R.string.toast_error_instance_reg), Toast.LENGTH_LONG).show();
return;
}

View File

@ -114,10 +114,10 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(MutedInstanceActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar_muted_instance, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(MutedInstanceActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);

View File

@ -81,10 +81,10 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(OpencollectiveActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(OpencollectiveActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -140,7 +140,7 @@ public class OpencollectiveActivity extends BaseActivity implements OnRetrieveRe
@Override
public void onRetrieveRemoteAccount(Results results) {
public void onRetrieveRemoteAccount(Results results, boolean devAccount) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
if (results == null) {
Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show();

View File

@ -135,10 +135,10 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(OwnerChartsActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(OwnerChartsActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.close_conversation);

View File

@ -167,10 +167,11 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(OwnerNotificationActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(OwnerNotificationActivity.this, R.color.cyanea_primary)));
toolbar.setBackgroundColor(ContextCompat.getColor(OwnerNotificationActivity.this, R.color.cyanea_primary));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

View File

@ -142,10 +142,10 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(OwnerNotificationChartsActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(OwnerNotificationChartsActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.close_conversation);

View File

@ -171,10 +171,11 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(OwnerStatusActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(OwnerStatusActivity.this, R.color.cyanea_primary)));
toolbar.setBackgroundColor(ContextCompat.getColor(OwnerStatusActivity.this, R.color.cyanea_primary));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

View File

@ -83,10 +83,10 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
setContentView(R.layout.activity_partnership);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PartnerShipActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PartnerShipActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -139,7 +139,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
@Override
public void onRetrieveRemoteAccount(Results results) {
public void onRetrieveRemoteAccount(Results results, boolean devAccount) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
if (results == null) {
Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show();

View File

@ -165,9 +165,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -244,10 +241,10 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PeertubeActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PeertubeActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -296,6 +293,10 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
}
}
});
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if( user_agent != null) {
webview_video.getSettings().setUserAgentString(user_agent);
}
webview_video.getSettings().setAllowFileAccess(true);
webview_video.setWebChromeClient(mastalabWebChromeClient);
webview_video.getSettings().setDomStorageEnabled(true);

View File

@ -24,12 +24,14 @@ import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@ -37,8 +39,6 @@ import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import com.jaredrummler.materialspinner.MaterialSpinner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
@ -72,8 +72,8 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
HashMap<Integer, String> privacyToSend;
HashMap<String, String> languageToSend;
HashMap<String, String> channelToSend;
private Button set_upload_submit, set_upload_delete;
private MaterialSpinner set_upload_privacy, set_upload_categories, set_upload_licenses, set_upload_languages, set_upload_channel;
private Button set_upload_submit;
private Spinner set_upload_privacy, set_upload_categories, set_upload_licenses, set_upload_languages, set_upload_channel;
private EditText p_video_title, p_video_description;
private TagsEditText p_video_tags;
private CheckBox set_upload_nsfw, set_upload_enable_comments;
@ -91,9 +91,6 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -112,10 +109,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PeertubeEditUploadActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PeertubeEditUploadActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -132,7 +129,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
set_upload_submit = findViewById(R.id.set_upload_submit);
set_upload_delete = findViewById(R.id.set_upload_delete);
Button set_upload_delete = findViewById(R.id.set_upload_delete);
set_upload_privacy = findViewById(R.id.set_upload_privacy);
set_upload_channel = findViewById(R.id.set_upload_channel);
set_upload_categories = findViewById(R.id.set_upload_categories);
@ -413,9 +410,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
}
//Manage privacies
set_upload_privacy.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
set_upload_privacy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Iterator it = privaciesCheck.entrySet().iterator();
int i = 0;
@ -430,11 +427,15 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
i++;
}
}
});
//Manage license
set_upload_licenses.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onNothingSelected(AdapterView<?> parent) {
}
});
set_upload_licenses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> licensesCheck = new LinkedHashMap<>(peertubeInformation.getLicences());
Iterator it = licensesCheck.entrySet().iterator();
int i = 0;
@ -449,11 +450,16 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
i++;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Manage categories
set_upload_categories.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
set_upload_categories.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> categoriesCheck = new LinkedHashMap<>(peertubeInformation.getCategories());
Iterator it = categoriesCheck.entrySet().iterator();
int i = 0;
@ -468,11 +474,17 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
i++;
}
}
});
//Manage languages
set_upload_languages.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Manage languages
set_upload_languages.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<String, String> languagesCheck = new LinkedHashMap<>(peertubeInformation.getLanguages());
Iterator it = languagesCheck.entrySet().iterator();
int i = 0;
@ -487,13 +499,16 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
i++;
}
}
});
//Manage languages
set_upload_channel.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Manage languages
set_upload_channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<String, String> channelsCheck = new LinkedHashMap<>(channels);
Iterator it = channelsCheck.entrySet().iterator();
int i = 0;
@ -509,6 +524,11 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
i++;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
@ -535,10 +555,10 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
}
});
set_upload_privacy.setSelectedIndex(privacyPosition);
set_upload_languages.setSelectedIndex(languagePosition);
set_upload_licenses.setSelectedIndex(licensePosition);
set_upload_categories.setSelectedIndex(categoryPosition);
set_upload_privacy.setSelection(privacyPosition);
set_upload_languages.setSelection(languagePosition);
set_upload_licenses.setSelection(licensePosition);
set_upload_categories.setSelection(categoryPosition);
List<String> tags = peertube.getTags();
if (tags != null && tags.size() > 0) {
@ -591,7 +611,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
channelPosition++;
}
}
set_upload_channel.setSelectedIndex(channelPosition);
set_upload_channel.setSelection(channelPosition);
set_upload_submit.setEnabled(true);
}

View File

@ -95,10 +95,10 @@ public class PeertubeRegisterActivity extends BaseActivity implements OnRetrieve
setContentView(R.layout.activity_register_peertube);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PeertubeRegisterActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PeertubeRegisterActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);

View File

@ -31,11 +31,13 @@ import android.provider.OpenableColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@ -43,7 +45,6 @@ import androidx.appcompat.app.ActionBar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.jaredrummler.materialspinner.MaterialSpinner;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.ServerResponse;
@ -57,6 +58,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
@ -80,7 +82,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
private final int PICK_IVDEO = 52378;
private final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 724;
private Button set_upload_file, set_upload_submit;
private MaterialSpinner set_upload_privacy, set_upload_channel;
private Spinner set_upload_privacy, set_upload_channel;
private TextView set_upload_file_name;
private EditText video_title;
private HashMap<String, String> channels;
@ -100,9 +102,6 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -113,10 +112,10 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PeertubeUploadActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PeertubeUploadActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -175,10 +174,11 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
} else if (uriString.startsWith("file://")) {
filename = myFile.getName();
}
if (filename != null) {
set_upload_file_name.setVisibility(View.VISIBLE);
set_upload_file_name.setText(filename);
if( filename == null){
filename = new Date().toString();
}
set_upload_file_name.setVisibility(View.VISIBLE);
set_upload_file_name.setText(filename);
}
}
@ -258,9 +258,9 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
set_upload_privacy.setAdapter(adapterPrivacies);
//Manage privacies
set_upload_privacy.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
set_upload_privacy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Iterator it = privaciesCheck.entrySet().iterator();
int i = 0;
@ -275,8 +275,12 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
i++;
}
}
});
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
set_upload_file.setEnabled(true);
set_upload_file.setOnClickListener(new View.OnClickListener() {
@ -308,9 +312,9 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
});
//Manage languages
set_upload_channel.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
set_upload_channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<String, String> channelsCheck = new LinkedHashMap<>(channels);
Iterator it = channelsCheck.entrySet().iterator();
int i = 0;
@ -326,6 +330,11 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
i++;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
set_upload_submit.setOnClickListener(new View.OnClickListener() {
@Override

View File

@ -46,9 +46,6 @@ import com.theartofdev.edmodo.cropper.CropImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import app.fedilab.android.R;
import app.fedilab.android.helper.Helper;
@ -90,7 +87,6 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
private ConstraintSet mConstraintSet = new ConstraintSet();
private boolean mIsFilterVisible;
private Uri uri;
private String tempname;
private boolean exit;
private static int exifToDegrees(int exifOrientation) {
@ -115,9 +111,6 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
@ -188,12 +181,9 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
Button send = findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exit = true;
saveImage();
}
send.setOnClickListener(v -> {
exit = true;
saveImage();
});
}
@ -295,7 +285,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
}
}
@SuppressLint("MissingPermission")
private void saveImage() {
if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showLoading(getString(R.string.saving));
@ -311,7 +301,6 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
@Override
public void onSuccess(@NonNull String imagePath) {
@ -335,7 +324,9 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
} catch (IOException e) {
e.printStackTrace();
hideLoading();
showSnackbar(e.getMessage());
if (e.getMessage() != null) {
showSnackbar(e.getMessage());
}
}
}
}
@ -344,8 +335,8 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
ExifInterface exif = null;
int rotation = 0;
ExifInterface exif;
int rotation;
int rotationInDegrees = 0;
if (data != null && data.getData() != null) {
try (InputStream inputStream = getContentResolver().openInputStream(data.getData())) {
@ -357,42 +348,51 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
e.printStackTrace();
}
}
switch (requestCode) {
case CAMERA_REQUEST:
mPhotoEditor.clearAllViews();
Bitmap photo = (Bitmap) data.getExtras().get("data");
mPhotoEditorView.getSource().setImageBitmap(photo);
mPhotoEditorView.getSource().setRotation(rotationInDegrees);
if( data != null && data.getExtras() != null) {
mPhotoEditor.clearAllViews();
Bitmap photo = (Bitmap) data.getExtras().get("data");
mPhotoEditorView.getSource().setImageBitmap(photo);
mPhotoEditorView.getSource().setRotation(rotationInDegrees);
}
break;
case PICK_REQUEST:
try {
mPhotoEditor.clearAllViews();
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
mPhotoEditorView.getSource().setImageBitmap(bitmap);
mPhotoEditorView.getSource().setRotation(rotationInDegrees);
} catch (IOException e) {
e.printStackTrace();
if( data != null && data.getData() != null) {
try {
mPhotoEditor.clearAllViews();
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
mPhotoEditorView.getSource().setImageBitmap(bitmap);
mPhotoEditorView.getSource().setRotation(rotationInDegrees);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri resultUri = result.getUri();
if (resultUri != null) {
mPhotoEditorView.getSource().setImageURI(resultUri);
mPhotoEditorView.getSource().setRotation(rotationInDegrees);
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
fdelete.delete();
}
uri = resultUri;
String filename = System.currentTimeMillis() + "_" + Helper.getFileName(PhotoEditorActivity.this, uri);
tempname = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) + filename;
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (result != null) {
Uri resultUri = result.getUri();
if (resultUri != null) {
mPhotoEditorView.getSource().setImageURI(resultUri);
mPhotoEditorView.getSource().setRotation(rotationInDegrees);
if (uri != null && uri.getPath() != null) {
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
//noinspection ResultOfMethodCallIgnored
fdelete.delete();
}
}
uri = resultUri;
}
}
break;
}
}
}
@Override

View File

@ -512,7 +512,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
String content = toot_content.getText().toString();
String contentCount = content;
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {
contentCount = contentCount.replaceAll("(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9.\\-]+[a-z0-9]+)", "$1@$3");
contentCount = contentCount.replaceAll("(?i)(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9\\.\\-]+[a-z0-9]+)", "$1@$3");
Matcher matcherALink = Patterns.WEB_URL.matcher(contentCount);
while (matcherALink.find()) {
final String url = matcherALink.group(1);
@ -559,10 +559,10 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
setContentView(R.layout.activity_pixelfed_compose);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PixelfedComposeActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PixelfedComposeActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView close_toot = actionBar.getCustomView().findViewById(R.id.close_toot);
@ -1277,7 +1277,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
toot.setSensitive(isSensitive);
toot.setVisibility(visibility);
toot.setMedia_attachments(attachments);
toot.setContent(tootContent);
toot.setContent(PixelfedComposeActivity.this, tootContent);
if (timestamp == null)
if (scheduledstatus == null)
new PostStatusAsyncTask(getApplicationContext(), social, account, toot, PixelfedComposeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
@ -1960,7 +1960,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
toot.setSensitive(isSensitive);
toot.setMedia_attachments(attachments);
toot.setVisibility(visibility);
toot.setContent(currentContent);
toot.setContent(PixelfedComposeActivity.this, currentContent);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();

View File

@ -94,10 +94,10 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PlaylistsActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PlaylistsActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -113,6 +113,7 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
}
setContentView(R.layout.activity_playlists);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setBackgroundColor(ContextCompat.getColor(PlaylistsActivity.this, R.color.cyanea_primary));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

View File

@ -63,10 +63,10 @@ public class PrivacyActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(PrivacyActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(PrivacyActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);

View File

@ -90,7 +90,7 @@ public class ProxyActivity extends BaseActivity {
count2 = 0;
final Spinner proxy_type = findViewById(R.id.type);
ArrayAdapter<CharSequence> adapterTrans = ArrayAdapter.createFromResource(ProxyActivity.this,
R.array.proxy_type_choice, android.R.layout.simple_spinner_item);
R.array.proxy_type_choice, android.R.layout.simple_spinner_dropdown_item);
proxy_type.setAdapter(adapterTrans);

View File

@ -129,10 +129,10 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(ReorderTimelinesActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar_add, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(ReorderTimelinesActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -160,13 +160,19 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
AutoCompleteTextView instance_list = dialogView.findViewById(R.id.search_instance);
//Manage download of attachments
RadioGroup radioGroup = dialogView.findViewById(R.id.set_attachment_group);
radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
if( checkedId == R.id.twitter_accounts){
instance_list.setHint(R.string.list_of_twitter_accounts);
}else {
instance_list.setHint(R.string.instance);
}
});
instance_list.setFilters(new InputFilter[]{new InputFilter.LengthFilter(60)});
dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceName = instance_list.getText().toString().trim();
String instanceName = instance_list.getText().toString().trim().replace("@","");
new Thread(new Runnable() {
@Override
public void run() {
@ -182,7 +188,6 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
} else if (radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) {
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/statuses/public_timeline.json", 10, null, null);
}
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
@ -196,6 +201,8 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "MISSKEY");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.gnu_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "GNU");
}else if (radioGroup.getCheckedRadioButtonId() == R.id.twitter_accounts) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "NITTER");
}
if (timelines != null && adapter != null) {
List<RemoteInstance> instance = new InstancesDAO(ReorderTimelinesActivity.this, db).getInstanceByName(instanceName);
@ -256,78 +263,84 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
@Override
public void afterTextChanged(Editable s) {
Pattern host = Pattern.compile("([\\da-z\\.-]+\\.[a-z\\.]{2,12})");
Matcher matcher = host.matcher(s.toString().trim());
if (s.toString().trim().length() == 0 || !matcher.find()) {
alertDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(false);
} else {
// Something into edit text. Enable the button.
if (radioGroup.getCheckedRadioButtonId() != R.id.twitter_accounts){
Pattern host = Pattern.compile("([\\da-z\\.-]+\\.[a-z\\.]{2,12})");
Matcher matcher = host.matcher(s.toString().trim());
if (s.toString().trim().length() == 0 || !matcher.find()) {
alertDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(false);
} else {
// Something into edit text. Enable the button.
alertDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
if (s.length() > 2 && !isLoadingInstance) {
final String action = "/instances/search";
final HashMap<String, String> parameters = new HashMap<>();
parameters.put("q", s.toString().trim());
parameters.put("count", String.valueOf(1000));
parameters.put("name", String.valueOf(true));
isLoadingInstance = true;
if (oldSearch == null || !oldSearch.equals(s.toString().trim()))
new Thread(new Runnable() {
@Override
public void run() {
try {
final String response = new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://instances.social/api/1.0" + action, 30, parameters, Helper.THEKINRAR_SECRET_TOKEN);
runOnUiThread(new Runnable() {
public void run() {
isLoadingInstance = false;
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("instances");
if (jsonArray != null) {
int length = 0;
for (int i = 0; i < jsonArray.length(); i++) {
if (!jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true"))
length++;
}
instances = new String[length];
int j = 0;
for (int i = 0; i < jsonArray.length(); i++) {
if (!jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true")) {
instances[j] = jsonArray.getJSONObject(i).get("name").toString();
j++;
}
}
} else {
instances = new String[]{};
}
instance_list.setAdapter(null);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(ReorderTimelinesActivity.this, android.R.layout.simple_list_item_1, instances);
instance_list.setAdapter(adapter);
if (instance_list.hasFocus() && !ReorderTimelinesActivity.this.isFinishing())
instance_list.showDropDown();
oldSearch = s.toString().trim();
} catch (JSONException ignored) {
isLoadingInstance = false;
}
}
});
} catch (HttpsConnection.HttpsConnectionException e) {
isLoadingInstance = false;
} catch (Exception e) {
isLoadingInstance = false;
}
}
}).start();
else
isLoadingInstance = false;
}
}else {
alertDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
if (s.length() > 2 && !isLoadingInstance) {
final String action = "/instances/search";
final HashMap<String, String> parameters = new HashMap<>();
parameters.put("q", s.toString().trim());
parameters.put("count", String.valueOf(1000));
parameters.put("name", String.valueOf(true));
isLoadingInstance = true;
if (oldSearch == null || !oldSearch.equals(s.toString().trim()))
new Thread(new Runnable() {
@Override
public void run() {
try {
final String response = new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://instances.social/api/1.0" + action, 30, parameters, Helper.THEKINRAR_SECRET_TOKEN);
runOnUiThread(new Runnable() {
public void run() {
isLoadingInstance = false;
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("instances");
if (jsonArray != null) {
int length = 0;
for (int i = 0; i < jsonArray.length(); i++) {
if (!jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true"))
length++;
}
instances = new String[length];
int j = 0;
for (int i = 0; i < jsonArray.length(); i++) {
if (!jsonArray.getJSONObject(i).get("name").toString().contains("@") && jsonArray.getJSONObject(i).get("up").toString().equals("true")) {
instances[j] = jsonArray.getJSONObject(i).get("name").toString();
j++;
}
}
} else {
instances = new String[]{};
}
instance_list.setAdapter(null);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(ReorderTimelinesActivity.this, android.R.layout.simple_list_item_1, instances);
instance_list.setAdapter(adapter);
if (instance_list.hasFocus() && !ReorderTimelinesActivity.this.isFinishing())
instance_list.showDropDown();
oldSearch = s.toString().trim();
} catch (JSONException ignored) {
isLoadingInstance = false;
}
}
});
} catch (HttpsConnection.HttpsConnectionException e) {
isLoadingInstance = false;
} catch (Exception e) {
isLoadingInstance = false;
}
}
}).start();
else
isLoadingInstance = false;
}
}
});
}
@ -419,6 +432,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
super.onStop();
if (updated) {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Helper.INTENT_ACTION, Helper.REFRESH_TIMELINE);
intent.putExtra(Helper.REFRESH_LIST_TIMELINE, refresh_list);
startActivity(intent);

View File

@ -41,7 +41,9 @@ import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.Trends;
import app.fedilab.android.drawers.SearchListAdapter;
import app.fedilab.android.drawers.TrendsAdapter;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnRetrieveSearchInterface;
import app.fedilab.android.interfaces.OnRetrieveSearchStatusInterface;
@ -59,6 +61,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
private String search;
private ListView lv_search;
private RelativeLayout loader;
private boolean forTrends;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -69,16 +72,13 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
case Helper.THEME_LIGHT:
setTheme(R.style.AppTheme_Fedilab);
break;
case Helper.THEME_DARK:
setTheme(R.style.AppThemeDark);
break;
case Helper.THEME_BLACK:
setTheme(R.style.AppThemeBlack);
break;
default:
setTheme(R.style.AppThemeDark);
}
forTrends = false;
setContentView(R.layout.activity_search_result);
loader = findViewById(R.id.loader);
@ -94,14 +94,17 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
} else {
Toasty.error(getApplicationContext(), getString(R.string.toast_error_search), Toast.LENGTH_LONG).show();
}
if( search.compareTo("fedilab_trend") == 0 ) {
forTrends = true;
}
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(SearchResultActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(SearchResultActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -112,9 +115,17 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
finish();
}
});
toolbar_title.setText(search);
if( !forTrends) {
toolbar_title.setText(search);
}else{
toolbar_title.setText(getString(R.string.trending_now));
}
}
if( !forTrends) {
setTitle(search);
}else{
setTitle(R.string.trending_now);
}
setTitle(search);
loader.setVisibility(View.VISIBLE);
lv_search.setVisibility(View.GONE);
@ -147,20 +158,31 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show();
return;
}
if (apiResponse.getResults() == null || (apiResponse.getResults().getAccounts().size() == 0 && apiResponse.getResults().getStatuses().size() == 0 && apiResponse.getResults().getHashtags().size() == 0)) {
RelativeLayout no_result = findViewById(R.id.no_result);
no_result.setVisibility(View.VISIBLE);
return;
}
lv_search.setVisibility(View.VISIBLE);
List<String> tags = apiResponse.getResults().getHashtags();
List<Account> accounts = apiResponse.getResults().getAccounts();
List<Status> statuses = apiResponse.getResults().getStatuses();
SearchListAdapter searchListAdapter = new SearchListAdapter(SearchResultActivity.this, statuses, accounts, tags);
lv_search.setAdapter(searchListAdapter);
searchListAdapter.notifyDataSetChanged();
if (!forTrends) {
if (apiResponse.getResults() == null || (apiResponse.getResults().getAccounts().size() == 0 && apiResponse.getResults().getStatuses().size() == 0 && apiResponse.getResults().getHashtags().size() == 0)) {
RelativeLayout no_result = findViewById(R.id.no_result);
no_result.setVisibility(View.VISIBLE);
return;
}
List<String> tags = apiResponse.getResults().getHashtags();
List<Account> accounts = apiResponse.getResults().getAccounts();
List<Status> statuses = apiResponse.getResults().getStatuses();
SearchListAdapter searchListAdapter = new SearchListAdapter(SearchResultActivity.this, statuses, accounts, tags);
lv_search.setAdapter(searchListAdapter);
searchListAdapter.notifyDataSetChanged();
} else {
if (apiResponse.getTrends() == null || apiResponse.getTrends().size() == 0 ) {
RelativeLayout no_result = findViewById(R.id.no_result);
no_result.setVisibility(View.VISIBLE);
return;
}
List<Trends> trends = apiResponse.getTrends();
TrendsAdapter trendsAdapter = new TrendsAdapter(SearchResultActivity.this, trends);
lv_search.setAdapter(trendsAdapter);
trendsAdapter.notifyDataSetChanged();
}
}

View File

@ -27,6 +27,7 @@ import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
@ -104,10 +105,10 @@ public class SearchResultTabActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(SearchResultTabActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(SearchResultTabActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -233,7 +234,10 @@ public class SearchResultTabActivity extends BaseActivity {
return null;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
}
@Override
public int getCount() {
return 4;

View File

@ -78,10 +78,11 @@ public class SettingsActivity extends BaseActivity {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(SettingsActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(SettingsActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -109,6 +110,7 @@ public class SettingsActivity extends BaseActivity {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.notifications)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.settings_category_label_interface)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.compose)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.action_privacy)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.theming)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.hide_menu_items)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.administration)));
@ -215,14 +217,17 @@ public class SettingsActivity extends BaseActivity {
typeOfSettings = ContentSettingsFragment.type.COMPOSE;
break;
case 4:
return new ColorSettingsFragment();
typeOfSettings = ContentSettingsFragment.type.PRIVACY;
break;
case 5:
return new ColorSettingsFragment();
case 6:
typeOfSettings = ContentSettingsFragment.type.MENU;
break;
case 6:
case 7:
typeOfSettings = ContentSettingsFragment.type.ADMIN;
break;
case 7:
case 8:
typeOfSettings = ContentSettingsFragment.type.LANGUAGE;
break;
default:
@ -238,7 +243,7 @@ public class SettingsActivity extends BaseActivity {
@Override
public int getCount() {
return 8;
return 9;
}
}
}

View File

@ -32,6 +32,7 @@ import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@ -51,6 +52,8 @@ import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
@ -77,6 +80,7 @@ import app.fedilab.android.asynctasks.PostActionAsyncTask;
import app.fedilab.android.asynctasks.RetrieveAccountAsyncTask;
import app.fedilab.android.asynctasks.RetrieveAccountsAsyncTask;
import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.android.asynctasks.RetrieveIdentityProofAsyncTask;
import app.fedilab.android.asynctasks.RetrieveRelationshipAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.client.API;
@ -84,6 +88,7 @@ import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Attachment;
import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.client.Entities.IdentityProof;
import app.fedilab.android.client.Entities.InstanceNodeInfo;
import app.fedilab.android.client.Entities.ManageTimelines;
import app.fedilab.android.client.Entities.Relationship;
@ -91,6 +96,7 @@ import app.fedilab.android.client.Entities.RemoteInstance;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.UserNote;
import app.fedilab.android.client.HttpsConnection;
import app.fedilab.android.drawers.IdentityProofsAdapter;
import app.fedilab.android.drawers.StatusListAdapter;
import app.fedilab.android.fragments.DisplayAccountsFragment;
import app.fedilab.android.fragments.DisplayStatusFragment;
@ -103,6 +109,7 @@ import app.fedilab.android.interfaces.OnRetrieveAccountInterface;
import app.fedilab.android.interfaces.OnRetrieveEmojiAccountInterface;
import app.fedilab.android.interfaces.OnRetrieveFeedsAccountInterface;
import app.fedilab.android.interfaces.OnRetrieveFeedsInterface;
import app.fedilab.android.interfaces.OnRetrieveIdentityProofInterface;
import app.fedilab.android.interfaces.OnRetrieveRelationshipInterface;
import app.fedilab.android.sqlite.AccountDAO;
import app.fedilab.android.sqlite.InstancesDAO;
@ -121,7 +128,7 @@ import static app.fedilab.android.helper.Helper.getLiveInstance;
* Show account activity class
*/
public class ShowAccountActivity extends BaseActivity implements OnPostActionInterface, OnRetrieveAccountInterface, OnRetrieveFeedsAccountInterface, OnRetrieveRelationshipInterface, OnRetrieveFeedsInterface, OnRetrieveEmojiAccountInterface, OnListActionInterface {
public class ShowAccountActivity extends BaseActivity implements OnPostActionInterface, OnRetrieveAccountInterface, OnRetrieveFeedsAccountInterface, OnRetrieveRelationshipInterface, OnRetrieveFeedsInterface, OnRetrieveEmojiAccountInterface, OnListActionInterface, OnRetrieveIdentityProofInterface {
private List<Status> statuses;
@ -306,7 +313,10 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
header_edit_profile.setVisibility(View.VISIBLE);
header_edit_profile.bringToFront();
}
//TODO: add other software that supports identity proofs
if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {
new RetrieveIdentityProofAsyncTask(ShowAccountActivity.this, account.getId(), ShowAccountActivity.this).execute();
}
String urlHeader = account.getHeader();
if (urlHeader != null && urlHeader.startsWith("/")) {
urlHeader = Helper.getLiveInstanceWithProtocol(ShowAccountActivity.this) + account.getHeader();
@ -335,7 +345,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
//Redraws icon for locked accounts
final float scale = getResources().getDisplayMetrics().density;
if (account.isLocked()) {
Drawable img = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_lock_outline);
Drawable img = ContextCompat.getDrawable(ShowAccountActivity.this, R.drawable.ic_locked_account);
assert img != null;
img.setBounds(0, 0, (int) (16 * scale + 0.5f), (int) (16 * scale + 0.5f));
account_un.setCompoundDrawables(null, null, img, null);
@ -343,9 +353,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
account_un.setCompoundDrawables(null, null, null, null);
}
//Peertube account watched by a Mastodon account
/*if( peertubeAccount && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) {
account_type.setVisibility(View.VISIBLE);
}*/
//Bot account
if (account.isBot()) {
account_bot.setVisibility(View.VISIBLE);
@ -861,6 +868,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
TextView account_date = findViewById(R.id.account_date);
account_date.setText(Helper.shortDateToString(account.getCreated_at()));
account_date.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
@Override
public void run() {
@ -870,15 +878,22 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
instance = account.getAcct().split("@")[1];
}
InstanceNodeInfo instanceNodeInfo = new API(ShowAccountActivity.this).displayNodeInfo(instance);
String finalInstance = instance;
runOnUiThread(new Runnable() {
public void run() {
if (instanceNodeInfo != null && instanceNodeInfo.getName() != null) {
TextView instance_info = findViewById(R.id.instance_info);
instance_info.setText(instanceNodeInfo.getName());
instance_info.setVisibility(View.VISIBLE);
TextView seperator = findViewById(R.id.seperator);
seperator.setVisibility(View.VISIBLE);
instance_info.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), InstanceProfileActivity.class);
Bundle b = new Bundle();
b.putString("instance", finalInstance);
intent.putExtras(b);
startActivity(intent);
});
}
}
});
@ -941,15 +956,34 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
private void manageButtonVisibility() {
if (relationship == null)
return;
account_follow.setEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
account_follow.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4)));
int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4),
ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4___),
ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4),
ContextCompat.getColor(ShowAccountActivity.this, R.color.mastodonC4)
};
account_follow.setBackgroundTintList(new ColorStateList(states, colors));
}
account_follow.setEnabled(true);
if (relationship.isBlocking()) {
account_follow.setImageResource(R.drawable.ic_lock_open);
doAction = action.UNBLOCK;
account_follow.setVisibility(View.VISIBLE);
} else if (relationship.isRequested()) {
} else if (relationship.isBlocked_by()) {
account_follow.setImageResource(R.drawable.ic_user_plus);
account_follow.setVisibility(View.VISIBLE);
account_follow.setEnabled(false);
doAction = action.NOTHING;
}else if (relationship.isRequested()) {
account_follow_request.setVisibility(View.VISIBLE);
account_follow.setImageResource(R.drawable.ic_hourglass_full);
account_follow.setVisibility(View.VISIBLE);
@ -1513,6 +1547,50 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
return show_boosts;
}
@Override
public void onIdentityProof(APIResponse apiResponse) {
if( apiResponse == null) {
return;
}
List<IdentityProof> identityProofs = apiResponse.getIdentityProofs();
if( identityProofs != null && identityProofs.size() > 0 ){
ImageView identity_proofs_indicator = findViewById(R.id.identity_proofs_indicator);
identity_proofs_indicator.setVisibility(View.VISIBLE);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
accountUrl = account.getUrl();
int style;
if (theme == Helper.THEME_LIGHT)
style = R.style.Dialog;
else if (theme == Helper.THEME_BLACK)
style = R.style.DialogBlack;
else
style = R.style.DialogDark;
identity_proofs_indicator.setOnClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(ShowAccountActivity.this, style);
LayoutInflater inflater = getLayoutInflater();
View identityProofsView = inflater.inflate(R.layout.popup_identity_proof, new LinearLayout(ShowAccountActivity.this), false);
RecyclerView identityProofsRecycler = identityProofsView.findViewById(R.id.identity_proofs_list);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(ShowAccountActivity.this);
identityProofsRecycler.setLayoutManager(mLayoutManager);
IdentityProofsAdapter identityProofsAdapter = new IdentityProofsAdapter(identityProofs);
identityProofsRecycler.setAdapter(identityProofsAdapter);
builder.setView(identityProofsView);
builder
.setTitle(R.string.identity_proofs)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
});
}
}
public enum action {
FOLLOW,

View File

@ -20,6 +20,7 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
@ -28,6 +29,9 @@ import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -115,13 +119,16 @@ public class ShowConversationActivity extends BaseActivity implements OnRetrieve
assert b != null;
Status status = b.getParcelable("status");
if (status != null && statusListAdapter != null) {
statusListAdapter.notifyStatusWithActionChanged(status);
statusListAdapter.notifyStatusChanged(status);
}
}
};
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receive_action, new IntentFilter(Helper.RECEIVE_ACTION));
}
Toolbar actionBar = findViewById(R.id.toolbar);
if (actionBar != null) {
actionBar.setBackground(new ColorDrawable(ContextCompat.getColor(ShowConversationActivity.this, R.color.cyanea_primary)));
}
TextView title = findViewById(R.id.toolbar_title);
ImageView pp_actionBar = findViewById(R.id.pp_actionBar);
ImageView action_refresh = findViewById(R.id.action_refresh);

View File

@ -26,6 +26,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@ -63,6 +64,7 @@ import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.fragments.MediaSliderFragment;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnDownloadInterface;
import es.dmoral.toasty.Toasty;
/**
@ -95,13 +97,14 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
Uri uri = manager.getUriForDownloadedFile(downloadID);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_with));
ContentResolver cR = context.getContentResolver();
shareIntent.setType(cR.getType(uri));
try {
startActivity(shareIntent);
} catch (Exception ignored) {
}
}else{
Toasty.success(context, context.getString(R.string.save_over), Toasty.LENGTH_LONG).show();
}
}
};
@ -126,6 +129,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
fullscreen = false;
media_description = findViewById(R.id.media_description);
final int med_desc_timeout = sharedpreferences.getInt(Helper.SET_MED_DESC_TIMEOUT, 3) * 1000;
flags = getWindow().getDecorView().getSystemUiVisibility();
swipeEnabled = true;
@ -135,6 +139,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.media_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(SlideMediaActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -152,17 +157,30 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
public void onClick(View view) {
int position = mPager.getCurrentItem();
Attachment attachment = attachments.get(position);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SlideMediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE);
if( attachment.getType().compareTo("image") == 0 ){
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SlideMediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE);
} else {
Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), false);
}
} else {
Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), false);
}
}else {
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(SlideMediaActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SlideMediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE);
} else {
Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
downloadID = -1;
}
} else {
Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
downloadID = -1;
}
} else {
Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
downloadID = -1;
}
}
});
media_share.setOnClickListener(new View.OnClickListener() {
@ -170,7 +188,9 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
public void onClick(View view) {
int position = mPager.getCurrentItem();
Attachment attachment = attachments.get(position);
if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv")) {
if( attachment.getType().compareTo("image") == 0 ){
Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), true);
}else if (attachment.getType().toLowerCase().equals("video") || attachment.getType().toLowerCase().equals("audio") || attachment.getType().toLowerCase().equals("gifv")) {
downloadID = Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
} else {
if (Build.VERSION.SDK_INT >= 23) {
@ -212,7 +232,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
public void run() {
media_description.setVisibility(View.GONE);
}
}, 3000);
}, med_desc_timeout);
} else {
media_description.setVisibility(View.GONE);
@ -239,7 +259,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
public void run() {
media_description.setVisibility(View.GONE);
}
}, 3000);
}, med_desc_timeout);
} else {
media_description.setVisibility(View.GONE);
@ -273,6 +293,9 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
final int med_desc_timeout = sharedpreferences.getInt(Helper.SET_MED_DESC_TIMEOUT, 3) * 1000;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
@ -298,7 +321,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
public void run() {
media_description.setVisibility(View.GONE);
}
}, 3000);
}, med_desc_timeout);
} else {
media_description.setVisibility(View.GONE);

View File

@ -249,7 +249,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
private ImageView pp_actionBar;
private ProgressBar pp_progress;
private Toast mToast;
private RelativeLayout drawer_layout;
private LinearLayout drawer_layout;
private HorizontalScrollView picture_scrollview;
private TextView toot_space_left;
private String initialContent;
@ -340,6 +340,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
@Override
public void afterTextChanged(Editable s) {
if (status != null) {
status.setQuickReplyContent(s.toString());
}
@ -687,7 +688,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
String cwContent = toot_cw_content.getText().toString();
String contentCount = content;
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {
contentCount = contentCount.replaceAll("(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9\\.\\-]+[a-z0-9]+)", "$1@$3");
contentCount = contentCount.replaceAll("(?i)(^|[^/\\w])@(([a-z0-9_]+)@[a-z0-9\\.\\-]+[a-z0-9]+)", "$1@$3");
Matcher matcherALink = Patterns.WEB_URL.matcher(contentCount);
while (matcherALink.find()) {
final String url = matcherALink.group(1);
@ -729,13 +730,13 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
autocomplete = false;
setContentView(R.layout.activity_toot);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(TootActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.toot_action_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(TootActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView close_toot = actionBar.getCustomView().findViewById(R.id.close_toot);
@ -792,7 +793,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
pp_progress = actionBar.getCustomView().findViewById(R.id.pp_progress);
}
setContentView(R.layout.activity_toot);
//By default the toot is not restored so the id -1 is defined
currentToId = -1;
@ -1005,7 +1006,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
}
restored = b.getLong("restored", -1);
}
if (tootReply != null) {
if (tootReply != null && tootReply.getAccount() != null) {
if (tootReply.getAccount() != null && tootReply.getAccount().getMoved_to_account() != null) {
warning_message.setVisibility(View.VISIBLE);
}
@ -1315,10 +1316,15 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
private void addNewMedia(JSONObject response, ArrayList<String> successfullyUploadedFiles) {
Attachment attachment;
//response = new JSONObject(serverResponse.getBodyAsString());
if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
if( response == null ){
Toasty.error(TootActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show();
return;
}
if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
attachment = API.parseAttachmentResponse(response);
else
} else {
attachment = GNUAPI.parseUploadedAttachmentResponse(response);
}
boolean alreadyAdded = false;
int index = 0;
@ -1691,7 +1697,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
public boolean onOptionsItemSelected(@NotNull MenuItem item) {
final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
int style;
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
@ -1895,6 +1901,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
return true;
case R.id.action_emoji:
if( emojis != null){
emojis.clear();
emojis = null;
}
emojis = new CustomEmojiDAO(getApplicationContext(), db).getAllEmojis(account.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(this, style);
int paddingPixel = 15;
@ -2302,7 +2312,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toot.setVisibility(visibility);
if (tootReply != null)
toot.setIn_reply_to_id(tootReply.getId());
toot.setContent(tootContent);
toot.setContent(TootActivity.this, tootContent);
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {
if (poll != null) {
toot.setPoll(poll);
@ -2692,7 +2702,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toot.setVisibility(visibility);
if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0)
toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId());
toot.setContent(tootContent);
toot.setContent(TootActivity.this, tootContent);
new PostStatusAsyncTask(getApplicationContext(), social, account, toot, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return;
@ -3661,10 +3671,10 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
});
ArrayAdapter<CharSequence> pollduration = ArrayAdapter.createFromResource(TootActivity.this,
R.array.poll_duration, android.R.layout.simple_spinner_item);
R.array.poll_duration, android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<CharSequence> pollchoice = ArrayAdapter.createFromResource(TootActivity.this,
R.array.poll_choice_type, android.R.layout.simple_spinner_item);
R.array.poll_choice_type, android.R.layout.simple_spinner_dropdown_item);
poll_choice.setAdapter(pollchoice);
poll_duration.setAdapter(pollduration);
poll_duration.setSelection(4);
@ -3857,7 +3867,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
if (toot_cw_content.getText().toString().trim().length() > 0)
toot.setSpoiler_text(toot_cw_content.getText().toString().trim());
toot.setVisibility(visibility);
toot.setContent(currentContent);
toot.setContent(TootActivity.this, currentContent);
if (poll != null)
toot.setPoll(poll);
@ -4169,8 +4179,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
@Override
protected void onPostExecute(Void result) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE);
activityWeakReference.get().findViewById(R.id.picture_scrollview).setVisibility(View.VISIBLE);
if( activityWeakReference.get().findViewById(R.id.compression_loader) != null) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE);
}
if( activityWeakReference.get().findViewById(R.id.picture_scrollview) != null){
activityWeakReference.get().findViewById(R.id.picture_scrollview).setVisibility(View.VISIBLE);
}
if (!error) {
if (commpressedFilePath != null) {
uriFile = Uri.fromFile(new File(commpressedFilePath));
@ -4181,15 +4195,19 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toot_picture = this.activityWeakReference.get().findViewById(R.id.toot_picture);
toot_it = this.activityWeakReference.get().findViewById(R.id.toot_it);
toot_picture_container = this.activityWeakReference.get().findViewById(R.id.toot_picture_container);
toot_picture_container.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
toot_it.setEnabled(false);
if( toot_picture_container != null){
toot_picture_container.setVisibility(View.VISIBLE);
}
if( toot_picture != null){
toot_picture.setEnabled(false);
}
if( toot_it != null){
toot_it.setEnabled(false);
}
if (filename == null) {
filename = Helper.getFileName(this.activityWeakReference.get(), uriFile);
}
filesMap.put(filename, uriFile);
upload(activityWeakReference.get(), account, social, uriFile, filename, uploadReceiver);
}
}

View File

@ -114,10 +114,10 @@ public class WebviewConnectActivity extends BaseActivity {
clientSecret = sharedpreferences.getString(Helper.CLIENT_SECRET, null);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(WebviewConnectActivity.this, R.color.cyanea_primary)));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(getApplicationContext()), false);
view.setBackground(new ColorDrawable(ContextCompat.getColor(WebviewConnectActivity.this, R.color.cyanea_primary)));
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
@ -133,6 +133,10 @@ public class WebviewConnectActivity extends BaseActivity {
webView = findViewById(R.id.webviewConnect);
clearCookies(getApplicationContext());
webView.getSettings().setJavaScriptEnabled(true);
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if( user_agent != null) {
webView.getSettings().setUserAgentString(user_agent);
}
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
} else {

View File

@ -28,6 +28,7 @@ import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Calendar;
@ -90,6 +91,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
setContentView(R.layout.activity_who_to_follow);
no_action = findViewById(R.id.no_action);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setBackgroundColor(ContextCompat.getColor(WhoToFollowActivity.this, R.color.cyanea_primary));
progess_action = findViewById(R.id.progess_action);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)

View File

@ -239,7 +239,15 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
statusCode = gnuapi.statusAction(status);
else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS)
statusCode = gnuapi.muteNotifications(targetedId, muteNotifications);
else
else if (apiAction == API.StatusAction.AUTHORIZE || apiAction == API.StatusAction.REJECT) {
//This part uses the Mastodon API
API api;
if (account != null)
api = new API(contextReference.get(), account.getInstance(), account.getToken());
else
api = new API(contextReference.get());
statusCode = api.postAction(apiAction, targetedId);
} else
statusCode = gnuapi.postAction(apiAction, targetedId);
error = gnuapi.getError();
}

View File

@ -32,6 +32,7 @@ import app.fedilab.android.client.Entities.Results;
import app.fedilab.android.client.Entities.RetrieveFeedsParam;
import app.fedilab.android.client.GNUAPI;
import app.fedilab.android.client.PeertubeAPI;
import app.fedilab.android.fragments.DisplayStatusFragment;
import app.fedilab.android.helper.FilterToots;
import app.fedilab.android.interfaces.OnRetrieveFeedsInterface;
import app.fedilab.android.sqlite.InstancesDAO;
@ -66,6 +67,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
private int timelineId;
private String currentfilter;
private String social;
private boolean fromCahe;
public RetrieveFeedsAsyncTask(Context context, FilterToots filterToots, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context);
@ -73,16 +75,26 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id;
this.listener = onRetrieveFeedsInterface;
this.filterToots = filterToots;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context);
this.action = action;
this.max_id = max_id;
this.listener = onRetrieveFeedsInterface;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, boolean fromCahe, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context);
this.action = action;
this.max_id = max_id;
this.listener = onRetrieveFeedsInterface;
this.fromCahe = fromCahe;
}
public RetrieveFeedsAsyncTask(Context context, Type action, String instanceName, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context);
@ -90,6 +102,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id;
this.listener = onRetrieveFeedsInterface;
this.instanceName = instanceName;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, Type action, int timelineId, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -98,6 +111,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id;
this.listener = onRetrieveFeedsInterface;
this.timelineId = timelineId;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -108,6 +122,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.targetedID = targetedID;
this.showMediaOnly = showMediaOnly;
this.showPinned = showPinned;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, boolean showReply, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -119,6 +134,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.showMediaOnly = showMediaOnly;
this.showPinned = showPinned;
this.showReply = showReply;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, Type action, String tag, String targetedID, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -128,6 +144,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface;
this.targetedID = targetedID;
this.tag = tag;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, String remoteInstance, String name, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -137,6 +154,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface;
this.name = name;
this.action = Type.REMOTE_INSTANCE;
this.fromCahe = false;
}
public RetrieveFeedsAsyncTask(Context context, RetrieveFeedsParam retrieveFeedsParam, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -154,8 +172,12 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.social = retrieveFeedsParam.getSocial();
this.instanceName = retrieveFeedsParam.getInstanceName();
this.remoteInstance = retrieveFeedsParam.getRemoteInstance();
this.fromCahe = false;
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
@ -164,7 +186,11 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
return null;
switch (action) {
case HOME:
apiResponse = api.getHomeTimelineCache(max_id);
if (this.fromCahe) {
apiResponse = api.getHomeTimelineCache(max_id);
} else {
apiResponse = api.getHomeTimeline(max_id);
}
break;
case LOCAL:
apiResponse = api.getPublicTimeline(true, max_id);
@ -223,7 +249,15 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
status.setType(action);
}
}
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("PIXELFED")) {
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("NITTER")) {
apiResponse = api.getNitter(this.instanceName, max_id);
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
if (statusesTemp != null) {
for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
status.setType(action);
}
}
}else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("PIXELFED")) {
apiResponse = api.getPixelfedTimeline(instanceName, max_id);
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("GNU")) {
apiResponse = api.getGNUTimeline(instanceName, max_id);

View File

@ -45,7 +45,6 @@ public class RetrieveFollowRequestSentAsyncTask extends AsyncTask<Void, Void, Vo
@Override
protected Void doInBackground(Void... params) {
apiResponse = new API(this.contextReference.get()).getFollowRequest(max_id);
return null;
}

View File

@ -0,0 +1,60 @@
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.interfaces.OnRetrieveIdentityProofInterface;
/**
* Created by Thomas on 17/12/2019.
* Retrieves identity
*/
public class RetrieveIdentityProofAsyncTask extends AsyncTask<Void, Void, Void> {
private APIResponse apiResponse;
private OnRetrieveIdentityProofInterface listener;
private WeakReference<Context> contextReference;
private String userId;
public RetrieveIdentityProofAsyncTask(Context context, String userId, OnRetrieveIdentityProofInterface onRetrieveHowToInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveHowToInterface;
this.userId = userId;
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getIdentityProof(userId);
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onIdentityProof(apiResponse);
}
}

View File

@ -91,6 +91,9 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask<Void, Void, Void> {
Pattern descriptionPattern = Pattern.compile("meta[ a-zA-Z=\"'-]+property=[\"']og:description[\"']\\s+content=[\"']([^>]*)[\"']");
Pattern imagePattern = Pattern.compile("meta[ a-zA-Z=\"'-]+property=[\"']og:image[\"']\\s+content=[\"']([^>]*)[\"']");
try {
if( !potentialUrl.startsWith("http")){
potentialUrl = "http://" + potentialUrl;
}
String response = new HttpsConnection(this.contextWeakReference.get(), null).get(potentialUrl);
Matcher matcherTitle = titlePattern.matcher(response);
Matcher matcherDescription = descriptionPattern.matcher(response);

View File

@ -53,7 +53,7 @@ public class RetrieveOpenCollectiveAsyncTask extends AsyncTask<Void, Void, Void>
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveRemoteAccount(results);
listener.onRetrieveRemoteAccount(results, false);
}
public enum Type {

View File

@ -39,8 +39,16 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask<Void, Void, Void> {
private String url;
private Results results;
private WeakReference<Context> contextReference;
private boolean developerAccount = false;
public RetrieveRemoteDataAsyncTask(Context context, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) {
this.url = "https://toot.fedilab.app/@fedilab";
developerAccount = true;
this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context);
}
public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) {
this.url = Helper.instanceWithProtocol(context, instance) + "/@" + username;
this.listener = onRetrieveRemoteAccountInterface;
@ -64,7 +72,7 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveRemoteAccount(results);
listener.onRetrieveRemoteAccount(results, developerAccount);
}
}

View File

@ -72,7 +72,9 @@ public class RetrieveSearchAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (this.type == null) {
if( query.compareTo("fedilab_trend") == 0 ) {
apiResponse = new API(this.contextReference.get()).getTrends();
}else if (this.type == null) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api = new API(this.contextReference.get());
String[] split = query.trim().split("@");

View File

@ -86,7 +86,9 @@ public class UpdateAccountInfoByIDAsyncTask extends AsyncTask<Void, Void, Void>
if (response != null && response.getEmojis() != null && response.getEmojis().size() > 0) {
new CustomEmojiDAO(contextReference.get(), db).removeAll();
for (Emojis emojis : response.getEmojis()) {
new CustomEmojiDAO(contextReference.get(), db).insertEmoji(emojis);
if( emojis.isVisible_in_picker()) {
new CustomEmojiDAO(contextReference.get(), db).insertEmoji(emojis);
}
}
}
} catch (Exception ignored) {

File diff suppressed because it is too large Load Diff

View File

@ -25,6 +25,7 @@ import app.fedilab.android.client.Entities.Emojis;
import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.client.Entities.Filters;
import app.fedilab.android.client.Entities.HowToVideo;
import app.fedilab.android.client.Entities.IdentityProof;
import app.fedilab.android.client.Entities.Instance;
import app.fedilab.android.client.Entities.InstanceReg;
import app.fedilab.android.client.Entities.Notification;
@ -38,6 +39,7 @@ import app.fedilab.android.client.Entities.Report;
import app.fedilab.android.client.Entities.Results;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.StoredStatus;
import app.fedilab.android.client.Entities.Trends;
/**
* Created by Thomas on 03/06/2017.
@ -73,6 +75,9 @@ public class APIResponse {
private Context context = null;
private List<PixelFedStory> pixelFedStories = null;
private List<PixelFedStoryItem> pixelFedStoryItems = null;
private PixelFedStory pixelFedStory = null;
private List<Trends> trends = null;
private List<IdentityProof> identityProofs = null;
public List<Account> getAccounts() {
return accounts;
@ -298,4 +303,20 @@ public class APIResponse {
public void setPixelFedStoryItems(List<PixelFedStoryItem> pixelFedStoryItems) {
this.pixelFedStoryItems = pixelFedStoryItems;
}
public List<Trends> getTrends() {
return trends;
}
public void setTrends(List<Trends> trends) {
this.trends = trends;
}
public List<IdentityProof> getIdentityProofs() {
return identityProofs;
}
public void setIdentityProofs(List<IdentityProof> identityProofs) {
this.identityProofs = identityProofs;
}
}

View File

@ -0,0 +1,74 @@
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
package app.fedilab.android.client.Entities;
import java.util.Date;
/**
* Created by Thomas on 17/12/2019.
* Manage identity proof
*/
public class IdentityProof {
private String provider;
private String provider_username;
private Date updated_at;
private String proof_url;
private String profile_url;
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getProvider_username() {
return provider_username;
}
public void setProvider_username(String provider_username) {
this.provider_username = provider_username;
}
public Date getUpdated_at() {
return updated_at;
}
public void setUpdated_at(Date updated_at) {
this.updated_at = updated_at;
}
public String getProof_url() {
return proof_url;
}
public void setProof_url(String proof_url) {
this.proof_url = proof_url;
}
public String getProfile_url() {
return profile_url;
}
public void setProfile_url(String profile_url) {
this.profile_url = profile_url;
}
}

View File

@ -30,6 +30,11 @@ public class Instance {
private String version;
private boolean registration;
private boolean approval_required;
private Account contactAccount;
private int userCount;
private int statusCount;
private int domainCount;
private String thumbnail;
private HashMap<String, Integer> poll_limits;
@ -96,4 +101,44 @@ public class Instance {
public void setApproval_required(boolean approval_required) {
this.approval_required = approval_required;
}
public Account getContactAccount() {
return contactAccount;
}
public void setContactAccount(Account contactAccount) {
this.contactAccount = contactAccount;
}
public int getUserCount() {
return userCount;
}
public void setUserCount(int userCount) {
this.userCount = userCount;
}
public int getStatusCount() {
return statusCount;
}
public void setStatusCount(int statusCount) {
this.statusCount = statusCount;
}
public int getDomainCount() {
return domainCount;
}
public void setDomainCount(int domainCount) {
this.domainCount = domainCount;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}

View File

@ -17,9 +17,18 @@ package app.fedilab.android.client.Entities;
public class InstanceNodeInfo {
private String name;
private String title;
private String version;
private boolean openRegistrations;
private boolean connectionError;
private int numberOfUsers = 0;
private int numberOfPosts = 0;
private int numberOfInstance = 0;
private String staffAccountStr;
private Account staffAccount;
private String nodeName;
private String nodeDescription;
private String thumbnail;
public String getName() {
return name;
@ -52,4 +61,76 @@ public class InstanceNodeInfo {
public void setConnectionError(boolean connectionError) {
this.connectionError = connectionError;
}
public int getNumberOfUsers() {
return numberOfUsers;
}
public void setNumberOfUsers(int numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public int getNumberOfPosts() {
return numberOfPosts;
}
public void setNumberOfPosts(int numberOfPosts) {
this.numberOfPosts = numberOfPosts;
}
public String getStaffAccountStr() {
return staffAccountStr;
}
public void setStaffAccountStr(String staffAccountStr) {
this.staffAccountStr = staffAccountStr;
}
public Account getStaffAccount() {
return staffAccount;
}
public void setStaffAccount(Account staffAccount) {
this.staffAccount = staffAccount;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeDescription() {
return nodeDescription;
}
public void setNodeDescription(String nodeDescription) {
this.nodeDescription = nodeDescription;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public int getNumberOfInstance() {
return numberOfInstance;
}
public void setNumberOfInstance(int numberOfInstance) {
this.numberOfInstance = numberOfInstance;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -18,6 +18,7 @@ public class MainMenuItem {
private boolean
nav_news = true,
nav_trends = true,
nav_list = true,
nav_scheduled = true,
nav_archive = true,
@ -125,4 +126,12 @@ public class MainMenuItem {
public void setNav_howto(boolean nav_howto) {
this.nav_howto = nav_howto;
}
public boolean isNav_trends() {
return nav_trends;
}
public void setNav_trends(boolean nav_trends) {
this.nav_trends = nav_trends;
}
}

View File

@ -270,7 +270,6 @@ public class ManageTimelines {
public TabLayout createTabs(Context context, TabLayout tabLayout, java.util.List<ManageTimelines> manageTimelines) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
tabLayout.removeAllTabs();
int position = 0;
for (ManageTimelines tl : manageTimelines) {
@ -281,6 +280,14 @@ public class ManageTimelines {
if (tb.getCustomView() != null)
icon = tb.getCustomView().findViewById(R.id.tab_icon);
}
Helper.changeDrawableColor(context,R.drawable.ic_home, R.attr.iconColorMenu);
Helper.changeDrawableColor(context,R.drawable.ic_notifications, R.attr.iconColorMenu);
Helper.changeDrawableColor(context,R.drawable.ic_direct_messages, R.attr.iconColorMenu);
Helper.changeDrawableColor(context,R.drawable.ic_people, R.attr.iconColorMenu);
Helper.changeDrawableColor(context,R.drawable.ic_public, R.attr.iconColorMenu);
Helper.changeDrawableColor(context,R.drawable.ic_color_lens, R.attr.iconColorMenu);
Helper.changeDrawableColor(context,R.drawable.ic_video_peertube, R.attr.iconColorMenu);
if (icon != null) {
switch (tl.getType()) {
case HOME:
@ -427,8 +434,9 @@ public class ManageTimelines {
public void onDismiss(PopupMenu menu) {
if (mPageReferenceMap != null) {
TabLayoutNotificationsFragment tabLayoutNotificationsFragment = (TabLayoutNotificationsFragment) mPageReferenceMap.get(tl.getPosition());
assert tabLayoutNotificationsFragment != null;
tabLayoutNotificationsFragment.refreshAll();
if (tabLayoutNotificationsFragment != null) {
tabLayoutNotificationsFragment.refreshAll();
}
}
}
});

View File

@ -127,6 +127,12 @@ public class Notification implements Parcelable {
else
typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_follow));
break;
case "follow_request":
if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0)
typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_follow_request));
else
typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_follow_request));
break;
}
SpannableString displayNameSpan = new SpannableString(typeString);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);

View File

@ -40,6 +40,7 @@ public class Poll implements Parcelable {
private boolean expired;
private boolean multiple;
private int votes_count;
private int voters_count;
private boolean voted;
private List<PollOptions> optionsList;
@ -54,6 +55,7 @@ public class Poll implements Parcelable {
this.expired = in.readByte() != 0;
this.multiple = in.readByte() != 0;
this.votes_count = in.readInt();
this.voters_count = in.readInt();
this.voted = in.readByte() != 0;
this.optionsList = in.createTypedArrayList(PollOptions.CREATOR);
}
@ -135,7 +137,16 @@ public class Poll implements Parcelable {
dest.writeByte(this.expired ? (byte) 1 : (byte) 0);
dest.writeByte(this.multiple ? (byte) 1 : (byte) 0);
dest.writeInt(this.votes_count);
dest.writeInt(this.voters_count);
dest.writeByte(this.voted ? (byte) 1 : (byte) 0);
dest.writeTypedList(this.optionsList);
}
public int getVoters_count() {
return voters_count;
}
public void setVoters_count(int voters_count) {
this.voters_count = voters_count;
}
}

View File

@ -12,6 +12,7 @@ public class Results {
private List<Account> accounts;
private List<Status> statuses;
private List<String> hashtags;
private List<Trends> trends;
public List<Account> getAccounts() {
return accounts;
@ -36,4 +37,12 @@ public class Results {
public void setHashtags(List<String> hashtags) {
this.hashtags = hashtags;
}
public List<Trends> getTrends() {
return trends;
}
public void setTrends(List<Trends> trends) {
this.trends = trends;
}
}

View File

@ -16,7 +16,10 @@ package app.fedilab.android.client.Entities;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
@ -24,6 +27,7 @@ import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html;
@ -38,10 +42,14 @@ import android.text.style.ImageSpan;
import android.text.style.QuoteSpan;
import android.text.style.URLSpan;
import android.util.Patterns;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
@ -57,6 +65,8 @@ import com.github.penfeizhou.animation.apng.decode.APNGParser;
import com.github.penfeizhou.animation.gif.GifDrawable;
import com.github.penfeizhou.animation.gif.decode.GifParser;
import net.gotev.uploadservice.http.HttpConnection;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
@ -70,6 +80,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import app.fedilab.android.R;
import app.fedilab.android.activities.BaseActivity;
import app.fedilab.android.activities.BaseMainActivity;
import app.fedilab.android.activities.GroupActivity;
import app.fedilab.android.activities.HashTagActivity;
import app.fedilab.android.activities.MainActivity;
@ -77,14 +89,21 @@ import app.fedilab.android.activities.PeertubeActivity;
import app.fedilab.android.activities.ShowAccountActivity;
import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.client.HttpsConnection;
import app.fedilab.android.fragments.TabLayoutNotificationsFragment;
import app.fedilab.android.helper.CrossActions;
import app.fedilab.android.helper.CustomQuoteSpan;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.helper.LongClickLinkMovementMethod;
import app.fedilab.android.helper.LongClickableSpan;
import app.fedilab.android.helper.ThemeHelper;
import app.fedilab.android.interfaces.OnRetrieveEmojiInterface;
import app.fedilab.android.interfaces.OnRetrieveImageInterface;
import app.fedilab.android.sqlite.StatusStoredDAO;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static app.fedilab.android.activities.BaseMainActivity.mPageReferenceMap;
import static app.fedilab.android.drawers.StatusListAdapter.COMPACT_STATUS;
import static app.fedilab.android.drawers.StatusListAdapter.CONSOLE_STATUS;
import static app.fedilab.android.drawers.StatusListAdapter.DISPLAYED_STATUS;
@ -455,18 +474,20 @@ public class Status implements Parcelable {
account.setInstance(instance);
account.setUrl(url);
String accountId = null;
for (Mention mention : mentions) {
String[] accountMentionAcct = mention.getAcct().split("@");
//Different isntance
if (accountMentionAcct.length > 1) {
if (mention.getAcct().equals(account.getAcct() + "@" + account.getInstance())) {
accountId = mention.getId();
break;
}
} else {
if (mention.getAcct().equals(account.getAcct())) {
accountId = mention.getId();
break;
if( mentions != null) {
for (Mention mention : mentions) {
String[] accountMentionAcct = mention.getAcct().split("@");
//Different isntance
if (accountMentionAcct.length > 1) {
if (mention.getAcct().equals(account.getAcct() + "@" + account.getInstance())) {
accountId = mention.getId();
break;
}
} else {
if (mention.getAcct().equals(account.getAcct())) {
accountId = mention.getId();
break;
}
}
}
}
@ -601,58 +622,191 @@ public class Status implements Parcelable {
endPosition = startPosition + key.length();
}
if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) {
spannableStringT.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
String finalUrl = url;
Pattern link = Pattern.compile("https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\w._-]*[0-9]*)(\\/[0-9]{1,})?$");
Matcher matcherLink = link.matcher(url);
if (matcherLink.find() && !url.contains("medium.com")) {
if (matcherLink.group(3) != null && matcherLink.group(3).length() > 0) { //It's a toot
CrossActions.doCrossConversation(context, finalUrl);
} else {//It's an account
Account account = new Account();
String acct = matcherLink.group(2);
if (acct != null) {
if (acct.startsWith("@"))
acct = acct.substring(1);
account.setAcct(acct);
account.setInstance(matcherLink.group(1));
CrossActions.doCrossProfile(context, account);
}
}
} else {
link = Pattern.compile("(https?:\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/videos\\/watch\\/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$");
matcherLink = link.matcher(url);
if (matcherLink.find()) { //Peertubee video
Intent intent = new Intent(context, PeertubeActivity.class);
Bundle b = new Bundle();
String url = matcherLink.group(1) + "/videos/watch/" + matcherLink.group(2);
b.putString("peertubeLinkToFetch", url);
b.putString("peertube_instance", matcherLink.group(1).replace("https://", "").replace("http://", ""));
b.putString("video_id", matcherLink.group(2));
intent.putExtras(b);
context.startActivity(intent);
} else {
if (!url.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://"))
finalUrl = "http://" + url;
Helper.openBrowser(context, finalUrl);
}
spannableStringT.setSpan(new LongClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
String finalUrl = url;
Pattern link = Pattern.compile("https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\w._-]*[0-9]*)(\\/[0-9]{1,})?$");
Matcher matcherLink = link.matcher(url);
if (matcherLink.find() && !url.contains("medium.com")) {
if (matcherLink.group(3) != null && matcherLink.group(3).length() > 0) { //It's a toot
CrossActions.doCrossConversation(context, finalUrl);
} else {//It's an account
Account account = new Account();
String acct = matcherLink.group(2);
if (acct != null) {
if (acct.startsWith("@"))
acct = acct.substring(1);
account.setAcct(acct);
account.setInstance(matcherLink.group(1));
CrossActions.doCrossProfile(context, account);
}
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(link_color);
} else {
link = Pattern.compile("(https?:\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/videos\\/watch\\/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$");
matcherLink = link.matcher(url);
if (matcherLink.find()) { //Peertubee video
Intent intent = new Intent(context, PeertubeActivity.class);
Bundle b = new Bundle();
String url = matcherLink.group(1) + "/videos/watch/" + matcherLink.group(2);
b.putString("peertubeLinkToFetch", url);
b.putString("peertube_instance", matcherLink.group(1).replace("https://", "").replace("http://", ""));
b.putString("video_id", matcherLink.group(2));
intent.putExtras(b);
context.startActivity(intent);
} else {
if (!url.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://"))
finalUrl = "http://" + url;
Helper.openBrowser(context, finalUrl);
}
},
startPosition, endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
@Override
public void onLongClick(@NonNull View textView) {
PopupMenu popup = new PopupMenu(context, textView);
popup.getMenuInflater()
.inflate(R.menu.links_popup, popup.getMenu());
int style;
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
} else if (theme == Helper.THEME_BLACK) {
style = R.style.DialogBlack;
} else {
style = R.style.Dialog;
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_show_link:
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
AlertDialog.Builder builder = new AlertDialog.Builder(context, style);
builder.setMessage(url);
builder.setTitle(context.getString(R.string.display_full_link));
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
break;
case R.id.action_share_link:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via));
sendIntent.putExtra(Intent.EXTRA_TEXT, url);
sendIntent.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with)));
break;
case R.id.action_open_other_app:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
try {
context.startActivity(intent);
} catch (Exception e) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
break;
case R.id.action_copy_link:
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, url);
if (clipboard != null) {
clipboard.setPrimaryClip(clip);
Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show();
}
break;
case R.id.action_unshorten:
Thread thread = new Thread() {
@Override
public void run() {
String response = new HttpsConnection(context, null).checkUrl(url);
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(context, style);
if( response != null ) {
builder.setMessage(context.getString(R.string.redirect_detected,url,response));
builder.setNegativeButton(R.string.copy_link, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, response);
if (clipboard != null) {
clipboard.setPrimaryClip(clip);
Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
});
builder.setNeutralButton(R.string.share_link, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via));
sendIntent.putExtra(Intent.EXTRA_TEXT, url);
sendIntent.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with)));
dialog.dismiss();
}
});
}else{
builder.setMessage(R.string.no_redirect);
}
builder.setTitle(context.getString(R.string.check_redirect));
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
};
mainHandler.post(myRunnable);
}
};
thread.start();
break;
}
return true;
}
});
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
BaseActivity.canShowActionMode = true;
}
});
popup.show();
textView.clearFocus();
BaseActivity.canShowActionMode = false;
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(link_color);
}
},
startPosition, endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
it.remove();
@ -903,9 +1057,16 @@ public class Status implements Parcelable {
if (endPosition <= contentSpan.toString().length() && endPosition >= startPosition) {
ImageSpan imageSpan;
if (!disableAnimatedEmoji) {
resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context));
resource.setVisible(true, true);
imageSpan = new ImageSpan(resource);
try {
resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context));
resource.setVisible(true, true);
imageSpan = new ImageSpan(resource);
}catch (Exception e) {
Bitmap bitmap = drawableToBitmap(resource.getCurrent());
imageSpan = new ImageSpan(context,
Bitmap.createScaledBitmap(bitmap, (int) Helper.convertDpToPixel(20, context),
(int) Helper.convertDpToPixel(20, context), false));
}
} else {
Bitmap bitmap = drawableToBitmap(resource.getCurrent());
@ -972,7 +1133,7 @@ public class Status implements Parcelable {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
Poll poll = status.getReblog() == null ? status.getPoll() : status.getReblog().getPoll();
if (poll == null) {
if (poll == null || poll.getOptionsList() == null) {
status.setPollEmojiFound(true);
return;
}
@ -1202,11 +1363,7 @@ public class Status implements Parcelable {
spannable.removeSpan(quoteSpan);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
int colord;
if (theme == THEME_BLACK)
colord = ContextCompat.getColor(context, R.color.dark_blockquote);
else
colord = ContextCompat.getColor(context, R.color.mastodonC4);
int colord = ContextCompat.getColor(context, R.color.cyanea_accent_reference);
spannable.setSpan(new CustomQuoteSpan(
ContextCompat.getColor(context, R.color.transparent),
colord,
@ -1342,9 +1499,9 @@ public class Status implements Parcelable {
return content;
}
public void setContent(String content) {
public void setContent(Context context, String content) {
//Remove UTM by default
this.content = Helper.remove_tracking_param(content);
this.content = Helper.remove_tracking_param(context, content);
}
public boolean isShortReply() {

View File

@ -17,6 +17,9 @@ package app.fedilab.android.client.Entities;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Thomas on 23/04/2017.
* Manage Tags
@ -24,26 +27,18 @@ import android.os.Parcelable;
public class Tag implements Parcelable {
public static final Creator<Tag> CREATOR = new Creator<Tag>() {
@Override
public Tag createFromParcel(Parcel in) {
return new Tag(in);
}
@Override
public Tag[] newArray(int size) {
return new Tag[size];
}
};
private String name;
private String url;
private List<TrendsHistory> trendsHistory;
public Tag() {
}
protected Tag(Parcel in) {
name = in.readString();
url = in.readString();
public List<TrendsHistory> getTrendsHistory() {
return trendsHistory;
}
public void setTrendsHistory(List<TrendsHistory> trendsHistory) {
this.trendsHistory = trendsHistory;
}
public String getName() {
@ -69,7 +64,27 @@ public class Tag implements Parcelable {
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
dest.writeString(this.name);
dest.writeString(this.url);
dest.writeList(this.trendsHistory);
}
protected Tag(Parcel in) {
this.name = in.readString();
this.url = in.readString();
this.trendsHistory = new ArrayList<TrendsHistory>();
in.readList(this.trendsHistory, TrendsHistory.class.getClassLoader());
}
public static final Creator<Tag> CREATOR = new Creator<Tag>() {
@Override
public Tag createFromParcel(Parcel source) {
return new Tag(source);
}
@Override
public Tag[] newArray(int size) {
return new Tag[size];
}
};
}

View File

@ -0,0 +1,55 @@
package app.fedilab.android.client.Entities;
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import java.util.List;
/**
* Created by Thomas on 30/11/2019.
* Manage Tag trends
*/
public class Trends {
private String name;
private String url;
private List<TrendsHistory> trendsHistory;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<TrendsHistory> getTrendsHistory() {
return trendsHistory;
}
public void setTrendsHistory(List<TrendsHistory> trendsHistory) {
this.trendsHistory = trendsHistory;
}
}

View File

@ -0,0 +1,88 @@
package app.fedilab.android.client.Entities;
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Thomas on 30/11/2019.
* Manage Tag trends history
*/
public class TrendsHistory implements Parcelable {
private long days;
private int uses;
private int accounts;
public long getDays() {
return days;
}
public void setDays(long days) {
this.days = days;
}
public int getUses() {
return uses;
}
public void setUses(int uses) {
this.uses = uses;
}
public int getAccounts() {
return accounts;
}
public void setAccounts(int accounts) {
this.accounts = accounts;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.days);
dest.writeInt(this.uses);
dest.writeInt(this.accounts);
}
public TrendsHistory() {
}
protected TrendsHistory(Parcel in) {
this.days = in.readLong();
this.uses = in.readInt();
this.accounts = in.readInt();
}
public static final Parcelable.Creator<TrendsHistory> CREATOR = new Parcelable.Creator<TrendsHistory>() {
@Override
public TrendsHistory createFromParcel(Parcel source) {
return new TrendsHistory(source);
}
@Override
public TrendsHistory[] newArray(int size) {
return new TrendsHistory[size];
}
};
}

View File

@ -268,6 +268,7 @@ public class GNUAPI {
}
//Retrieves mentions
List<Mention> mentions = new ArrayList<>();
Helper.largeLog( resobj.toString());
if (resobj.has("attentions")) {
JSONArray arrayMention = resobj.getJSONArray("attentions");
if (arrayMention != null) {
@ -306,9 +307,9 @@ public class GNUAPI {
else if (resobj.has("sender"))
status.setAccount(parseAccountResponse(context, resobj.getJSONObject("sender")));
if (resobj.has("statusnet_html"))
status.setContent(resobj.get("statusnet_html").toString());
status.setContent(context, resobj.get("statusnet_html").toString());
else if (resobj.has("text"))
status.setContent(resobj.get("text").toString());
status.setContent(context, resobj.get("text").toString());
if (resobj.has("fave_num"))
status.setFavourites_count(Integer.valueOf(resobj.get("fave_num").toString()));
else
@ -379,7 +380,7 @@ public class GNUAPI {
} catch (Exception e) {
status.setVisibility("public");
}
status.setContent(resobj.get("text").toString());
status.setContent(context, resobj.get("text").toString());
} catch (JSONException ignored) {
}
return status;
@ -396,16 +397,24 @@ public class GNUAPI {
Account account = new Account();
try {
account.setId(resobj.get("id").toString());
if (resobj.has("ostatus_uri"))
if( resobj.has("id_str")){
account.setId(resobj.getString("id_str"));
}else{
account.setId(resobj.get("id").toString());
}
if (resobj.has("ostatus_uri")) {
account.setUuid(resobj.get("ostatus_uri").toString());
else
account.setUuid(resobj.get("id").toString());
account.setUsername(resobj.get("screen_name").toString());
account.setAcct(resobj.get("screen_name").toString());
account.setDisplay_name(resobj.get("name").toString());
}else {
if( resobj.has("id_str")){
account.setUuid(resobj.getString("id_str"));
}else{
account.setUuid(resobj.get("id").toString());
}
}
account.setUsername(resobj.getString("screen_name"));
account.setAcct(resobj.getString("screen_name"));
account.setDisplay_name(resobj.getString("name"));
account.setLocked(Boolean.parseBoolean(resobj.get("protected").toString()));
account.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString()));
account.setFollowers_count(Integer.valueOf(resobj.get("followers_count").toString()));
account.setFollowing_count(Integer.valueOf(resobj.get("friends_count").toString()));
account.setStatuses_count(Integer.valueOf(resobj.get("statuses_count").toString()));
@ -428,8 +437,8 @@ public class GNUAPI {
else
account.setSocial("GNU");
account.setEmojis(new ArrayList<>());
} catch (JSONException ignored) {
} catch (ParseException e) {
account.setCreated_at(Helper.mstStringToDate(context, resobj.get("created_at").toString()));
} catch (JSONException | ParseException e) {
e.printStackTrace();
}
return account;
@ -1386,13 +1395,7 @@ public class GNUAPI {
}
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
}
apiResponse.setStatuses(statuses);
@ -1632,64 +1635,7 @@ public class GNUAPI {
}
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
apiResponse.setAccounts(accounts);
return apiResponse;
}
/**
* Retrieves follow requests for the authenticated account *synchronously*
*
* @param max_id String id max
* @return APIResponse
*/
public APIResponse getFollowRequest(String max_id) {
return getFollowRequest(max_id, null, accountPerPage);
}
/**
* Retrieves follow requests for the authenticated account *synchronously*
*
* @param max_id String id max
* @param since_id String since the id
* @param limit int limit - max value 40
* @return APIResponse
*/
@SuppressWarnings("SameParameterValue")
private APIResponse getFollowRequest(String max_id, String since_id, int limit) {
HashMap<String, String> params = new HashMap<>();
if (max_id != null)
params.put("max_id", max_id);
if (since_id != null)
params.put("since_id", since_id);
if (0 > limit || limit > 40)
limit = 40;
params.put("limit", String.valueOf(limit));
accounts = new ArrayList<>();
try {
HttpsConnection httpsConnection = new HttpsConnection(context, this.instance);
String response = httpsConnection.get(getAbsoluteUrl("/follow_requests"), 60, params, prefKeyOauthTokenT);
apiResponse.setSince_id(httpsConnection.getSince_id());
apiResponse.setMax_id(httpsConnection.getMax_id());
accounts = parseAccountResponse(new JSONArray(response));
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
}
apiResponse.setAccounts(accounts);
@ -1954,11 +1900,7 @@ public class GNUAPI {
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
e.printStackTrace();
}
return actionCode;
@ -2025,13 +1967,7 @@ public class GNUAPI {
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
}
apiResponse.setStatuses(statuses);
@ -2121,15 +2057,16 @@ public class GNUAPI {
apiResponse.setMax_id(httpsConnection.getMax_id());
if (type == DisplayNotificationsFragment.Type.FOLLOW) {
List<Account> accounts = parseAccountResponse(new JSONArray(response));
if (accounts != null)
if (accounts != null) {
for (Account st : accounts) {
Notification notification = new Notification();
notification.setType(stringType);
notification.setId(st.getId());
notification.setStatus(null);
notification.setAccount(account);
notification.setAccount(st);
notifications.add(notification);
}
}
} else {
List<Status> statuses = parseStatuses(context, new JSONArray(response));
if (statuses != null)
@ -2146,13 +2083,7 @@ public class GNUAPI {
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
}
apiResponse.setNotifications(notifications);
@ -2257,13 +2188,40 @@ public class GNUAPI {
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
} catch (IOException e) {
}
return apiResponse;
}
/**
* Retrieves Accounts and feeds when searching *synchronously*
*
* @param query String search
* @return Results
*/
public APIResponse search2(String query) {
Results results = new Results();
HashMap<String, String> params = new HashMap<>();
apiResponse = new APIResponse();
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
params.put("q", query);
else
try {
params.put("q", URLEncoder.encode(query, "UTF-8"));
} catch (UnsupportedEncodingException e) {
params.put("q", query);
}
try {
HttpsConnection httpsConnection = new HttpsConnection(context, this.instance);
String response = httpsConnection.get(getAbsoluteUrl("/search.json"), 60, params, prefKeyOauthTokenT);
List<Status> statuses = parseStatuses(context, new JSONArray(response));
results.setStatuses(statuses);
apiResponse.setResults(results);
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
}
return apiResponse;
@ -2598,6 +2556,11 @@ public class GNUAPI {
return Helper.instanceWithProtocol(this.context, this.instance) + "/api" + action;
}
private String getAbsoluteMastodonUrl(String action) {
return Helper.instanceWithProtocol(this.context, this.instance) + "/api/v1" + action;
}
private String getAbsoluteRemoteUrl(String instance, String action) {
return Helper.instanceWithProtocol(this.context, instance) + "/api" + action;
}

View File

@ -53,7 +53,9 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -68,6 +70,13 @@ import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.helper.FileNameCleaner;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnDownloadInterface;
import okhttp3.Cache;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static app.fedilab.android.helper.Helper.urlPattern;
/**
@ -86,6 +95,8 @@ public class HttpsConnection {
private SharedPreferences sharedpreferences;
private Proxy proxy;
private String instance;
private String USER_AGENT;
private int cacheSize = 30*1024*1024;
public HttpsConnection(Context context, String instance) {
this.instance = instance;
@ -94,6 +105,8 @@ public class HttpsConnection {
boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false);
int type = sharedpreferences.getInt(Helper.SET_PROXY_TYPE, 0);
proxy = null;
USER_AGENT = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT);
if (proxyEnabled) {
try {
String host = sharedpreferences.getString(Helper.SET_PROXY_HOST, "127.0.0.1");
@ -132,35 +145,102 @@ public class HttpsConnection {
}
@SuppressWarnings("ConstantConditions")
/**
* Get calls
* @param urlConnection String url
* @param timeout int timeout
* @param paramaters HashMap<String, String> paramaters
* @param token String token
* @return String
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws HttpsConnectionException
*/
public String get(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if (urlConnection.startsWith("https://")) {
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
StringBuilder postData = new StringBuilder();
}
StringBuilder postData = new StringBuilder();
URL url;
if( params.size() > 0 ) {
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(param.getValue());
}
URL url = new URL(urlConnection + "?" + postData);
url = new URL(urlConnection + "?" + postData);
}else{
url = new URL(urlConnection);
}
if (Build.VERSION.SDK_INT >= 21) {
Cache cache = new Cache(context.getCacheDir(), cacheSize);
OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(timeout, TimeUnit.SECONDS).cache(cache);
if (proxy != null) {
builder.proxy(proxy);
}
OkHttpClient client = builder.build();
Request.Builder requestBuilder = new Request.Builder()
.url(urlConnection);
HttpUrl.Builder httpBuider = Objects.requireNonNull(HttpUrl.parse(url.toString())).newBuilder();
if (token != null && !token.startsWith("Basic ")) {
requestBuilder.addHeader("Authorization", "Bearer " + token);
} else if (token != null && token.startsWith("Basic ")) {
requestBuilder.addHeader("Authorization", token);
}
Request requesthttp = requestBuilder
.url(httpBuider.build())
.build();
try {
Response httpresponse = client.newCall(requesthttp).execute();
assert httpresponse.body() != null;
String response = httpresponse.body().string();
int code = httpresponse.code();
String error = httpresponse.message();
if (code >= 200 && code < 400) {
if (!cache.isClosed()) {
try {
cache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
getOKHttpHeader(httpresponse.headers().toMultimap());
return response;
} else {
throw new HttpsConnectionException(code, error);
}
} catch (Exception ignored){}
finally {
if (!cache.isClosed()) {
try {
cache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
throw new HttpsConnectionException(500, context.getString(R.string.toast_error));
}else{
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setRequestProperty("http.keepAlive", "false");
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setRequestProperty("Content-Type", "application/json");
httpsURLConnection.setRequestProperty("Accept", "application/json");
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
@ -198,71 +278,97 @@ public class HttpsConnection {
getSinceMaxId();
httpsURLConnection.getInputStream().close();
return response;
} else {
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(param.getValue());
}
URL url = new URL(urlConnection + "?" + postData);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(timeout * 1000);
httpURLConnection.setRequestProperty("http.keepAlive", "false");
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
if (token != null && !token.startsWith("Basic "))
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
else if (token != null && token.startsWith("Basic "))
httpsURLConnection.setRequestProperty("Authorization", token);
httpURLConnection.setRequestMethod("GET");
String response;
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
response = converToString(httpURLConnection.getInputStream());
} else {
String error = null;
if (httpURLConnection.getErrorStream() != null) {
InputStream stream = httpURLConnection.getErrorStream();
if (stream == null) {
stream = httpURLConnection.getInputStream();
}
try (Scanner scanner = new Scanner(stream)) {
scanner.useDelimiter("\\Z");
if (scanner.hasNext()) {
error = scanner.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
int responseCode = httpURLConnection.getResponseCode();
try {
httpURLConnection.getInputStream().close();
} catch (Exception ignored) {
}
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpURLConnection.getInputStream().close();
return response;
}
}
/**
* Will check if the current url is redirecting
* @param urlConnection String the url to check
* @return String null|string url redirection
*/
public String checkUrl(String urlConnection){
URL url;
String redirect = null;
try {
url = new URL(urlConnection);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("http.keepAlive", "false");
httpsURLConnection.setInstanceFollowRedirects(false);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
httpsURLConnection.setRequestMethod("HEAD");
if( httpsURLConnection.getResponseCode() == 301) {
Map<String, List<String>> map = httpsURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.toString().toLowerCase().startsWith("location")) {
Matcher matcher = urlPattern.matcher(entry.toString());
if (matcher.find()) {
redirect = matcher.group(1);
}
}
}
}
httpsURLConnection.getInputStream().close();
if (redirect != null && redirect.compareTo(urlConnection)!=0){
URL redirectURL = new URL(redirect);
String host = redirectURL.getHost();
String protocol = redirectURL.getProtocol();
if( protocol == null || host == null){
redirect = null;
}
}
return redirect;
} catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
public String get(String urlConnection) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if (urlConnection.startsWith("https://")) {
if (Build.VERSION.SDK_INT >= 21) {
Cache cache = new Cache(context.getCacheDir(), cacheSize);
OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).cache(cache);
if (proxy != null) {
builder.proxy(proxy);
}
if( !urlConnection.startsWith("http")){
urlConnection = "http://" + urlConnection;
}
OkHttpClient client = builder.build();
Request.Builder requestBuilder = new Request.Builder()
.url(urlConnection);
HttpUrl.Builder httpBuider = Objects.requireNonNull(HttpUrl.parse(urlConnection)).newBuilder();
Request requesthttp = requestBuilder
.url(httpBuider.build())
.build();
try (Response httpresponse = client.newCall(requesthttp).execute()) {
assert httpresponse.body() != null;
String response = httpresponse.body().string();
int code = httpresponse.code();
String error = httpresponse.message();
if (code >= 200 && code < 400) {
getOKHttpHeader(httpresponse.headers().toMultimap());
return response;
} else {
throw new HttpsConnectionException(code, error);
}
}finally {
if (!cache.isClosed()) {
try {
cache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
URL url = new URL(urlConnection);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
@ -305,46 +411,6 @@ public class HttpsConnection {
getSinceMaxId();
httpsURLConnection.getInputStream().close();
return response;
} else {
URL url = new URL(urlConnection);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(30 * 1000);
httpURLConnection.setRequestProperty("http.keepAlive", "false");
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");
httpURLConnection.setRequestMethod("GET");
String response;
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpURLConnection.getInputStream());
} else {
String error = null;
if (httpURLConnection.getErrorStream() != null) {
InputStream stream = httpURLConnection.getErrorStream();
if (stream == null) {
stream = httpURLConnection.getInputStream();
}
try (Scanner scanner = new Scanner(stream)) {
scanner.useDelimiter("\\Z");
if (scanner.hasNext()) {
error = scanner.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
int responseCode = httpURLConnection.getResponseCode();
try {
httpURLConnection.getInputStream().close();
} catch (Exception ignored) {
}
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpURLConnection.getInputStream().close();
return response;
}
}
@ -373,7 +439,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
@ -440,7 +506,7 @@ public class HttpsConnection {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
@ -495,7 +561,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
@ -548,7 +614,7 @@ public class HttpsConnection {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
@ -601,7 +667,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
@ -666,7 +732,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpsURLConnection.getResponseCode();
// always check HTTP response code first
@ -754,7 +820,7 @@ public class HttpsConnection {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
// always check HTTP response code first
@ -850,7 +916,7 @@ public class HttpsConnection {
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpsURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
@ -858,8 +924,7 @@ public class HttpsConnection {
return httpsURLConnection.getInputStream();
}
httpsURLConnection.getInputStream().close();
} catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {
}
} catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {}
if (httpsURLConnection != null)
try {
httpsURLConnection.getInputStream().close();
@ -873,7 +938,7 @@ public class HttpsConnection {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
@ -980,7 +1045,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
@ -1061,7 +1126,7 @@ public class HttpsConnection {
httpURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
httpURLConnection.setRequestMethod("PATCH");
@ -1144,7 +1209,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
if (token != null && !token.startsWith("Basic "))
@ -1212,7 +1277,7 @@ public class HttpsConnection {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
if (token != null && !token.startsWith("Basic "))
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
@ -1284,7 +1349,7 @@ public class HttpsConnection {
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
if (token != null && !token.startsWith("Basic "))
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
@ -1347,7 +1412,7 @@ public class HttpsConnection {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
if (token != null && !token.startsWith("Basic "))
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
else if (token != null && token.startsWith("Basic "))
@ -1398,6 +1463,32 @@ public class HttpsConnection {
return max_id;
}
private void getOKHttpHeader(Map<String, List<String>> headers){
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) {
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{1,}).*");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
}
if (entry.toString().startsWith("Link")) {
Pattern patternSinceId = Pattern.compile("since_id=([0-9a-zA-Z]{1,}).*");
Matcher matcherSinceId = patternSinceId.matcher(entry.toString());
if (matcherSinceId.find()) {
since_id = matcherSinceId.group(1);
}
}
}else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) {
Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]{1,}).*\\]");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
}
}
}
}
private void getSinceMaxId() {
if (Helper.getLiveInstanceWithProtocol(context) == null)
return;
@ -1405,6 +1496,7 @@ public class HttpsConnection {
if (httpsURLConnection == null)
return;
Map<String, List<String>> map = httpsURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) {
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{1,}).*");
@ -1420,6 +1512,12 @@ public class HttpsConnection {
}
}
}else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) {
Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]{1,}).*\\]");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
}
}
}
} else {

View File

@ -413,7 +413,7 @@ public class PeertubeAPI {
status.setUrl(comment.get("url").toString());
status.setSensitive(false);
status.setSpoiler_text("");
status.setContent(comment.get("text").toString());
status.setContent(context, comment.get("text").toString());
status.setIn_reply_to_id(comment.get("inReplyToCommentId").toString());
status.setAccount(parseAccountResponsePeertube(context, comment.getJSONObject("account")));
status.setCreated_at(Helper.mstStringToDate(context, comment.get("createdAt").toString()));
@ -713,7 +713,7 @@ public class PeertubeAPI {
}
/***
* Verifiy credential of the authenticated user *synchronously*
* Verifiy PeertubeInformation of the authenticated user *synchronously*
* @return Account
*/
public PeertubeInformation getPeertubeInformation() throws HttpsConnection.HttpsConnectionException {
@ -791,13 +791,7 @@ public class PeertubeAPI {
peertubeInformation.setTranslations(_translations);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
}
return peertubeInformation;
@ -827,34 +821,38 @@ public class PeertubeAPI {
if (e.getStatusCode() == 401 || e.getStatusCode() == 403) {
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account targetedAccount = new AccountDAO(context, db).getAccountByToken(prefKeyOauthTokenT);
HashMap<String, String> values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token());
if (values.containsKey("access_token") && values.get("access_token") != null) {
targetedAccount.setToken(values.get("access_token"));
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
//This account is currently logged in, the token is updated
if (prefKeyOauthTokenT.equals(token)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, targetedAccount.getToken());
editor.apply();
if (targetedAccount != null) {
HashMap<String, String> values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token());
if (values.containsKey("access_token") && values.get("access_token") != null) {
targetedAccount.setToken(values.get("access_token"));
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
//This account is currently logged in, the token is updated
if (prefKeyOauthTokenT != null && prefKeyOauthTokenT.equals(token)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, targetedAccount.getToken());
editor.apply();
}
}
}
if (values.containsKey("refresh_token") && values.get("refresh_token") != null)
targetedAccount.setRefresh_token(values.get("refresh_token"));
new AccountDAO(context, db).updateAccount(targetedAccount);
if (values.containsKey("refresh_token") && values.get("refresh_token") != null)
targetedAccount.setRefresh_token(values.get("refresh_token"));
new AccountDAO(context, db).updateAccount(targetedAccount);
String response;
try {
response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/users/me"), 60, null, targetedAccount.getToken());
JSONObject accountObject = new JSONObject(response).getJSONObject("account");
account = parseAccountResponsePeertube(context, accountObject);
if (social != null) {
account.setSocial(social.toUpperCase());
String response;
try {
response = new HttpsConnection(context, this.instance).get(getAbsoluteUrl("/users/me"), 60, null, targetedAccount.getToken());
JSONObject accountObject = new JSONObject(response).getJSONObject("account");
account = parseAccountResponsePeertube(context, accountObject);
if (social != null) {
account.setSocial(social.toUpperCase());
}
} catch (IOException | NoSuchAlgorithmException | KeyManagementException | JSONException e1) {
e1.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e1) {
e1.printStackTrace();
setError(e.getStatusCode(), e);
}
} catch (IOException | NoSuchAlgorithmException | KeyManagementException | JSONException e1) {
e1.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e1) {
e1.printStackTrace();
}else{
setError(e.getStatusCode(), e);
}
e.printStackTrace();
@ -921,15 +919,7 @@ public class PeertubeAPI {
refresh_token = resobj.get("refresh_token").toString();
newValues.put("access_token", token);
newValues.put("refresh_token", refresh_token);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException | HttpsConnection.HttpsConnectionException e) {
e.printStackTrace();
}
return newValues;

View File

@ -14,6 +14,7 @@ package app.fedilab.android.drawers;
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
@ -54,7 +55,6 @@ import es.dmoral.toasty.Toasty;
public class AccountSearchDevAdapter extends BaseAdapter implements OnPostActionInterface {
private List<Account> accounts;
private LayoutInflater layoutInflater;
private Context context;
private ViewHolder holder;
@ -83,7 +83,7 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction
public View getView(final int position, View convertView, ViewGroup parent) {
context = parent.getContext();
layoutInflater = LayoutInflater.from(context);
LayoutInflater layoutInflater = LayoutInflater.from(context);
final Account account = accounts.get(position);
if (convertView == null) {
@ -132,13 +132,17 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction
//Profile picture
if (account.getAvatar().startsWith("http")) {
Glide.with(holder.account_pp.getContext())
.load(account.getAvatar())
.into(holder.account_pp);
if( !((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) {
Glide.with(context)
.load(account.getAvatar())
.into(holder.account_pp);
}
} else if (account.getSocial() != null && account.getSocial().contains("OPENCOLLECTIVE")) {
Glide.with(holder.account_pp.getContext())
.load(R.drawable.missing)
.into(holder.account_pp);
if( !((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) {
Glide.with(context)
.load(R.drawable.missing)
.into(holder.account_pp);
}
}

View File

@ -39,8 +39,10 @@ import java.util.ArrayList;
import java.util.List;
import app.fedilab.android.R;
import app.fedilab.android.activities.MainActivity;
import app.fedilab.android.activities.ShowAccountActivity;
import app.fedilab.android.asynctasks.PostActionAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.client.API;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Error;
@ -80,6 +82,11 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement
final Account account = accounts.get(position);
holder.btn_authorize.getBackground().setColorFilter(ContextCompat.getColor(context, R.color.green_1), PorterDuff.Mode.MULTIPLY);
holder.btn_reject.getBackground().setColorFilter(ContextCompat.getColor(context, R.color.red_1), PorterDuff.Mode.MULTIPLY);
//TODO: check if Friendica has a way to accept/deny follow requests
if(MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
holder.btn_authorize.setVisibility(View.GONE);
holder.btn_reject.setVisibility(View.GONE);
}
holder.account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true));
holder.account_un.setText(account.getAcct());
//Profile picture

View File

@ -280,19 +280,6 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction
}
}
public void notifyStatusWithActionChanged(Status status) {
for (int i = 0; i < statusListAdapter.getItemCount(); i++) {
//noinspection ConstantConditions
if (statusListAdapter.getItemAt(i) != null && statusListAdapter.getItemAt(i).getId().equals(status.getId())) {
try {
statuses.set(i, status);
statusListAdapter.notifyItemChanged(i);
} catch (Exception ignored) {
}
}
}
}
@Override
public void onRetrieveEmoji(Status status, boolean fromTranslation) {
if (status != null) {

View File

@ -84,7 +84,7 @@ public class CustomEmojiAdapter extends BaseAdapter {
}
if (!emoji.isDrawableFound()) {
//if (!emoji.isDrawableFound()) {
emoji.setDrawableFound(true);
Glide.with(parent.getContext())
.asFile()
@ -116,7 +116,7 @@ public class CustomEmojiAdapter extends BaseAdapter {
imageView.setImageDrawable(emoji.getDrawable());
}
});
}
// }
return convertView;
}
}

View File

@ -41,6 +41,7 @@ import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import app.fedilab.android.R;
import app.fedilab.android.activities.BaseMainActivity;
@ -134,8 +135,8 @@ public class FilterAdapter extends BaseAdapter implements OnFilterActionInterfac
CheckBox context_whole_word = dialogView.findViewById(R.id.context_whole_word);
CheckBox context_drop = dialogView.findViewById(R.id.context_drop);
Spinner filter_expire = dialogView.findViewById(R.id.filter_expire);
ArrayAdapter<CharSequence> adapterResize = ArrayAdapter.createFromResource(context,
R.array.filter_expire, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> adapterResize = ArrayAdapter.createFromResource(Objects.requireNonNull(context),
R.array.filter_expire, android.R.layout.simple_spinner_dropdown_item);
filter_expire.setAdapter(adapterResize);
final int[] expire = {-1};
filter_expire.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

View File

@ -0,0 +1,96 @@
package app.fedilab.android.drawers;
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import app.fedilab.android.R;
import app.fedilab.android.client.Entities.IdentityProof;
import app.fedilab.android.helper.Helper;
/**
* Created by Thomas on 19/12/2019.
* Adapter for identity proofs
*/
public class IdentityProofsAdapter extends RecyclerView.Adapter {
private Context context;
private List<IdentityProof> identityProofs;
public IdentityProofsAdapter(List<IdentityProof> identityProofs) {
this.identityProofs = identityProofs;
}
public IdentityProof getItem(int position) {
return identityProofs.get(position);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
context = parent.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
return new ViewHolder(layoutInflater.inflate(R.layout.drawer_identity_proofs, parent, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
final ViewHolder holder = (ViewHolder) viewHolder;
final IdentityProof identityProof = getItem(i);
holder.proof_name.setText(String.format("@%s", identityProof.getProvider_username()));
holder.proof_name.setOnClickListener(v -> {
Helper.openBrowser(context, identityProof.getProfile_url());
});
holder.proof_name_network.setText(context.getString(R.string.verified_by, identityProof.getProvider(),Helper.shortDateToString(identityProof.getUpdated_at())));
holder.proof_container.setOnClickListener(v -> {
Helper.openBrowser(context, identityProof.getProfile_url());
});
holder.proof_name_network.setOnClickListener(v -> {
Helper.openBrowser(context, identityProof.getProof_url());
});
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return identityProofs.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView proof_name, proof_name_network;
private ConstraintLayout proof_container;
public ViewHolder(@NonNull View itemView) {
super(itemView);
proof_name = itemView.findViewById(R.id.proof_name);
proof_name_network = itemView.findViewById(R.id.proof_name_network);
proof_container = itemView.findViewById(R.id.proof_container);
}
}
}

View File

@ -70,6 +70,7 @@ import java.util.TimerTask;
import app.fedilab.android.R;
import app.fedilab.android.activities.AccountReportActivity;
import app.fedilab.android.activities.BaseActivity;
import app.fedilab.android.activities.BaseMainActivity;
import app.fedilab.android.activities.CustomSharingActivity;
import app.fedilab.android.activities.MainActivity;
@ -247,6 +248,11 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
style = R.style.Dialog;
}
int theme_text_color = prefs.getInt("theme_text_color", -1);
if (holder.notification_status_content != null && theme_text_color != -1) {
holder.notification_status_content.setTextColor(theme_text_color);
holder.status_spoiler.setTextColor(theme_text_color);
}
int reblogColor = prefs.getInt("theme_statuses_color", -1);
if (holder.main_linear_container != null && reblogColor != -1) {
@ -301,6 +307,16 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
holder.main_container_trans.setVisibility(View.VISIBLE);
holder.status_more.setVisibility(View.GONE);
break;
case "follow_request":
holder.status_action_container.setVisibility(View.GONE);
holder.status_date.setVisibility(View.GONE);
if (notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0)
typeString = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true), context.getString(R.string.notif_follow_request));
else
typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_follow_request));
imgH = ContextCompat.getDrawable(context, R.drawable.ic_follow_notif_header);
holder.main_container_trans.setVisibility(View.GONE);
break;
case "follow":
holder.status_action_container.setVisibility(View.GONE);
holder.status_date.setVisibility(View.GONE);
@ -336,7 +352,11 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
holder.notification_status_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14 * textSizePercent / 100);
holder.notification_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14 * textSizePercent / 100);
holder.status_date.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12 * textSizePercent / 100);
int theme_text_header_1_line = prefs.getInt("theme_text_header_1_line", -1);
if (theme_text_header_1_line == -1) {
theme_text_header_1_line = ThemeHelper.getAttColor(context, R.attr.textColor);
}
holder.notification_type.setTextColor(theme_text_header_1_line);
holder.spark_button_fav.pressOnTouch(false);
holder.spark_button_reblog.pressOnTouch(false);
@ -534,7 +554,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
greaterValue = pollOption.getVotes_count();
}
for (PollOptions pollOption : status.getPoll().getOptionsList()) {
double value = ((double) (pollOption.getVotes_count() * 100) / (double) poll.getVotes_count());
double value = ((double) (pollOption.getVotes_count() * 100) / (double) poll.getVoters_count());
if (pollOption.getVotes_count() == greaterValue) {
BarItem bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC4), Color.WHITE);
bar.setRounded(true);
@ -623,8 +643,12 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
}
});
holder.poll_container.setVisibility(View.VISIBLE);
holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_vote, status.getPoll().getVotes_count(), status.getPoll().getVotes_count()));
holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at())));
holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_voters, status.getPoll().getVoters_count(), status.getPoll().getVoters_count()));
if( poll.isExpired()){
holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at())));
}else{
holder.remaining_time.setText(context.getString(R.string.poll_finish_in, Helper.dateDiffPoll(context, poll.getExpires_at())));
}
} else {
holder.poll_container.setVisibility(View.GONE);
}
@ -1282,6 +1306,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
if (!url.trim().contains("missing.png"))
Glide.with(imageView.getContext())
.load(url)
.override(640, 480)
.into(imageView);
final int finalPosition = position;
imageView.setOnClickListener(new View.OnClickListener() {
@ -1468,10 +1493,10 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
if (!disableAnimatedEmoji) {
if (BaseMainActivity.timer == null) {
BaseMainActivity.timer = new Timer();
if (BaseActivity.timer == null) {
BaseActivity.timer = new Timer();
}
BaseMainActivity.timer.schedule(new TimerTask() {
BaseActivity.timer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(updateAnimatedEmoji);

View File

@ -172,7 +172,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio
}
});
} else {
holder.main_container.setOnClickListener(new View.OnClickListener() {
holder.bottom_container.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, PeertubeEditUploadActivity.class);
@ -182,6 +182,26 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio
context.startActivity(intent);
}
});
holder.peertube_video_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, PeertubeActivity.class);
Bundle b = new Bundle();
if ((instance == null || instance.trim().length() == 0) && MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
instance = Helper.getLiveInstance(context);
String finalUrl = "https://" + instance + peertube.getEmbedPath();
Pattern link = Pattern.compile("(https?:\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/videos\\/embed\\/(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})$");
Matcher matcherLink = link.matcher(finalUrl);
if (matcherLink.find()) {
String url = matcherLink.group(1) + "/videos/watch/" + matcherLink.group(2);
b.putString("peertubeLinkToFetch", url);
b.putString("peertube_instance", matcherLink.group(1).replace("https://", "").replace("http://", ""));
b.putString("video_id", matcherLink.group(2));
}
intent.putExtras(b);
context.startActivity(intent);
}
});
}
}
@ -203,7 +223,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio
}
class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout main_container;
LinearLayout main_container, bottom_container;
ImageView peertube_profile, peertube_video_image;
TextView peertube_account_name, peertube_views, peertube_duration;
TextView peertube_title, peertube_date, header_title;
@ -219,6 +239,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActio
peertube_duration = itemView.findViewById(R.id.peertube_duration);
main_container = itemView.findViewById(R.id.main_container);
header_title = itemView.findViewById(R.id.header_title);
bottom_container = itemView.findViewById(R.id.bottom_container);
}
}

View File

@ -133,9 +133,6 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
private MastalabAutoCompleteTextView comment_content;
private String in_reply_to_status;
private String visibility;
private int theme;
private long currentToId = -1;
private Status tootReply;
private boolean redraft = false;
private Status toot;
@ -204,8 +201,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
comment_content = null;
tootReply = null;
currentToId = -1;
long currentToId = -1;
if (apiResponse.getError() == null) {
boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true);
if (display_confirm) {
@ -434,14 +430,32 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
iconColor = ThemeHelper.getAttColor(context, R.attr.iconColor);
}
int reblogColor = prefs.getInt("theme_boost_header_color", -1);
holder.pf_likes.setTextColor(iconColor);
int statusColor = prefs.getInt("theme_statuses_color", -1);
if (holder.pf_cardview != null && statusColor != -1) {
holder.pf_cardview.setCardBackgroundColor(statusColor);
} else if (holder.pf_cardview != null) {
holder.pf_cardview.setCardBackgroundColor(ThemeHelper.getAttColor(context, R.attr.cardviewColor));
}
int theme_text_color = prefs.getInt("theme_text_color", -1);
if (holder.pf_description != null && theme_text_color != -1) {
holder.pf_description.setTextColor(theme_text_color);
}
int theme_text_header_2_line = prefs.getInt("theme_text_header_2_line", -1);
if (theme_text_header_2_line == -1) {
theme_text_header_2_line = ThemeHelper.getAttColor(context, R.attr.textHeader);
}
holder.pf_username.setTextColor(theme_text_header_2_line);
holder.pf_date.setTextColor(theme_text_header_2_line);
if (statusColor != -1) {
holder.quick_reply_container.setBackgroundColor(statusColor);
}
holder.quick_reply_switch_to_full.setVisibility(View.GONE);
int theme;
if (status.isShortReply()) {
holder.quick_reply_container.setVisibility(View.VISIBLE);
holder.pixelfed_comments.setVisibility(View.VISIBLE);
@ -457,7 +471,11 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
status.setCommentsFetched(true);
new RetrieveContextAsyncTask(context, false, false, status.getId(), PixelfedListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
InputMethodManager inputMethodManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
holder.quick_reply_text.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
EditText content_cw = new EditText(context);
content_cw.setText(status.getReblog() != null ? status.getReblog().getSpoiler_text() : status.getSpoiler_text());
String content = TootActivity.manageMentions(context, userId, status.getReblog() != null ? status.getReblog() : status);
@ -471,7 +489,6 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
int newInputType = comment_content.getInputType() & (comment_content.getInputType() ^ InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
comment_content.setInputType(newInputType);
in_reply_to_status = status.getReblog() != null ? status.getReblog().getId() : status.getId();
tootReply = status;
theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
@ -596,12 +613,12 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
holder.quick_reply_privacy.setVisibility(View.GONE);
holder.quick_reply_button.setOnClickListener(view -> {
sendToot();
//status.setShortReply(false);
sendToot(status);
status.setShortReply(false);
holder.quick_reply_container.setVisibility(View.GONE);
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(holder.quick_reply_button.getWindowToken(), 0);
notifyStatusChanged(status);
});
holder.pf_description.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE);
@ -900,7 +917,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
toot.setMedia_attachments(status.getMedia_attachments());
if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0)
toot.setSpoiler_text(status.getSpoiler_text().trim());
toot.setContent(status.getContent());
toot.setContent(context, status.getContent());
toot.setVisibility(status.getVisibility());
if (status.getPoll() != null) {
toot.setPoll(status.getPoll());
@ -915,7 +932,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0)
toot.setSpoiler_text(status.getSpoiler_text().trim());
toot.setVisibility(status.getVisibility());
toot.setContent(status.getContent());
toot.setContent(context, status.getContent());
if (status.getPoll() != null) {
toot.setPoll(status.getPoll());
} else if (status.getReblog() != null && status.getReblog().getPoll() != null) {
@ -1065,6 +1082,8 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
et = MyTransL.translatorEngine.YANDEX;
} else if (trans == Helper.TRANS_DEEPL) {
et = MyTransL.translatorEngine.DEEPL;
}else if (trans == Helper.TRANS_SYSTRAN) {
et = MyTransL.translatorEngine.SYSTRAN;
}
final MyTransL myTransL = MyTransL.getInstance(et);
myTransL.setObfuscation(true);
@ -1074,6 +1093,9 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
} else if (trans == Helper.TRANS_DEEPL) {
api_key = sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, "");
myTransL.setDeeplAPIKey(api_key);
} else if (trans == Helper.TRANS_SYSTRAN) {
api_key = sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, "");
myTransL.setSystranAPIKey(api_key);
}
@ -1127,7 +1149,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
context.startActivity(intent);
}
private void sendToot() {
private void sendToot(Status status) {
if (comment_content.getText() == null) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
@ -1148,8 +1170,10 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
toot.setVisibility(visibility);
toot.setIn_reply_to_id(in_reply_to_status);
toot.setContent(tootContent);
toot.setContent(context, tootContent);
new PostStatusAsyncTask(context, social, account, toot, PixelfedListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
status.setQuickReplyPrivacy(null);
status.setQuickReplyContent(null);
}
@ -1411,18 +1435,6 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
}
}
public void notifyStatusWithActionChanged(Status status) {
for (int i = 0; i < pixelfedListAdapter.getItemCount(); i++) {
//noinspection ConstantConditions
if (pixelfedListAdapter.getItemAt(i) != null && pixelfedListAdapter.getItemAt(i).getId().equals(status.getId())) {
try {
statuses.set(i, status);
pixelfedListAdapter.notifyItemChanged(i);
} catch (Exception ignored) {
}
}
}
}
@Override
public void onRetrieveEmoji(Status status, boolean fromTranslation) {

View File

@ -129,6 +129,9 @@ public class ReorderTabAdapter extends RecyclerView.Adapter<ReorderTabAdapter.It
case "GNU":
holder.iconView.setImageResource(R.drawable.ic_gnu_social);
break;
case "NITTER":
holder.iconView.setImageResource(R.drawable.nitter);
break;
}
holder.textView.setText(tl.getRemoteInstance().getHost());
break;

View File

@ -63,9 +63,9 @@ public class SearchListAdapter extends BaseAdapter {
public SearchListAdapter(Context context, List<Status> statuses, List<Account> accounts, List<String> tags) {
this.context = context;
this.statuses = (statuses != null) ? statuses : new ArrayList<Status>();
this.accounts = (accounts != null) ? accounts : new ArrayList<Account>();
this.tags = (tags != null) ? tags : new ArrayList<String>();
this.statuses = (statuses != null) ? statuses : new ArrayList<>();
this.accounts = (accounts != null) ? accounts : new ArrayList<>();
this.tags = (tags != null) ? tags : new ArrayList<>();
layoutInflater = LayoutInflater.from(context);
}
@ -180,7 +180,6 @@ public class SearchListAdapter extends BaseAdapter {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
holder.status_content.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY));
else
//noinspection deprecation
holder.status_content.setText(Html.fromHtml(content));
holder.status_content.setAutoLinkMask(Linkify.WEB_URLS);
holder.status_toot_date.setText(Helper.dateDiff(context, status.getCreated_at()));

View File

@ -33,6 +33,7 @@ import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.InputType;
import android.text.Spannable;
@ -110,11 +111,13 @@ import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import app.fedilab.android.R;
import app.fedilab.android.activities.AccountReportActivity;
import app.fedilab.android.activities.BaseActivity;
import app.fedilab.android.activities.BaseMainActivity;
import app.fedilab.android.activities.CustomSharingActivity;
import app.fedilab.android.activities.MainActivity;
@ -148,10 +151,12 @@ import app.fedilab.android.client.Entities.Relationship;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.StoredStatus;
import app.fedilab.android.client.Entities.TagTimeline;
import app.fedilab.android.client.Glide.GlideApp;
import app.fedilab.android.fragments.DisplayStatusFragment;
import app.fedilab.android.helper.CrossActions;
import app.fedilab.android.helper.CustomTextView;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.helper.LongClickLinkMovementMethod;
import app.fedilab.android.helper.MastalabAutoCompleteTextView;
import app.fedilab.android.helper.ThemeHelper;
import app.fedilab.android.interfaces.OnPollInterface;
@ -224,6 +229,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
private List<ViewHolder> lstHolders;
private List<Emojis> emojisPicker;
private Status statusForQuickReply;
private String instanceType;
private Runnable updateAnimatedEmoji = new Runnable() {
@Override
@ -263,6 +269,21 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
currentToId = -1;
}
public StatusListAdapter(String instanceType, RetrieveFeedsAsyncTask.Type type, String targetedId, boolean isOnWifi, List<Status> statuses) {
super();
this.statuses = statuses;
this.isOnWifi = isOnWifi;
statusListAdapter = this;
this.type = type;
this.targetedId = targetedId;
redraft = false;
lstHolders = new ArrayList<>();
toot_content = null;
toot_cw_content = null;
tootReply = null;
currentToId = -1;
this.instanceType = instanceType;
}
public StatusListAdapter(TagTimeline tagTimeline, String targetedId, boolean isOnWifi, List<Status> statuses) {
super();
@ -280,6 +301,23 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
currentToId = -1;
}
public StatusListAdapter(String instanceType, TagTimeline tagTimeline, String targetedId, boolean isOnWifi, List<Status> statuses) {
super();
this.statuses = statuses;
this.isOnWifi = isOnWifi;
statusListAdapter = this;
this.type = RetrieveFeedsAsyncTask.Type.TAG;
this.targetedId = targetedId;
redraft = false;
this.tagTimeline = tagTimeline;
this.instanceType = instanceType;
lstHolders = new ArrayList<>();
toot_content = null;
toot_cw_content = null;
tootReply = null;
currentToId = -1;
}
public StatusListAdapter(int position, String targetedId, boolean isOnWifi, List<Status> statuses) {
this.statuses = statuses;
this.isOnWifi = isOnWifi;
@ -352,7 +390,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
new TimelineCacheDAO(context, db).remove(refreshedStatus.getId());
new PostActionAsyncTask(context, API.StatusAction.UNSTATUS, refreshedStatus.getId(), StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
statusListAdapter.notifyStatusWithActionChanged(refreshedStatus);
statusListAdapter.notifyStatusChanged(refreshedStatus);
}
@Override
@ -361,7 +399,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
return;
final List<Account> accounts = apiResponse.getAccounts();
if (accounts != null && accounts.size() > 0) {
if (accounts != null && accounts.size() > 0 && toot_content != null) {
int currentCursorPosition = toot_content.getSelectionStart();
AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(context, accounts);
toot_content.setThreshold(1);
@ -415,9 +453,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
@Override
public void onRetrieveSearchEmoji(List<Emojis> emojis) {
int currentCursorPosition = toot_content.getSelectionStart();
if (emojis != null && emojis.size() > 0) {
if (emojis != null && emojis.size() > 0 && toot_content != null) {
int currentCursorPosition = toot_content.getSelectionStart();
EmojisSearchAdapter emojisSearchAdapter = new EmojisSearchAdapter(context, emojis);
toot_content.setThreshold(1);
toot_content.setAdapter(emojisSearchAdapter);
@ -543,7 +581,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
toot.setVisibility(apiResponse.getStatuses().get(0).getVisibility());
if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0)
toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId());
toot.setContent(tootContent);
toot.setContent(context, tootContent);
final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
new PostStatusAsyncTask(context, social, account, toot, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
@ -613,15 +651,20 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
show_boosts = ((ShowAccountActivity) context).showBoosts();
show_replies = ((ShowAccountActivity) context).showReplies();
}
if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS && !Helper.filterToots(statuses.get(position), type, context instanceof ShowAccountActivity, show_boosts, show_replies))
if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS && !Helper.filterToots(statuses.get(position), type, context instanceof ShowAccountActivity, show_boosts, show_replies)) {
return HIDDEN_STATUS;
}
if (statuses.get(position).isFocused() && type == RetrieveFeedsAsyncTask.Type.CONTEXT && statuses.get(position).getViewType() != CONSOLE_STATUS)
return FOCUSED_STATUS;
else {
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED && type == RetrieveFeedsAsyncTask.Type.CONTEXT) {
return COMPACT_STATUS;
} else {
return statuses.get(position).getViewType();
if( instanceType == null || instanceType.compareTo("NITTER") != 0 ) {
return statuses.get(position).getViewType();
}else{
return COMPACT_STATUS;
}
}
}
}
@ -650,6 +693,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
context = viewHolder.itemView.getContext();
if (viewHolder.getItemViewType() != HIDDEN_STATUS) {
final ViewHolder holder = (ViewHolder) viewHolder;
synchronized (lock) {
@ -659,9 +703,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.startUpdateTimer();
final Status status = statuses.get(i);
if (status == null)
return;
//TODO:It sounds that sometimes this value is null - need deeper investigation
if (status.getVisibility() == null) {
status.setVisibility("public");
@ -688,11 +733,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.status_reply_indicator_top.setVisibility(View.VISIBLE);
holder.reply_indicator_dot.setVisibility(View.VISIBLE);
if (holder.status_reply_indicator_diag_top != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
holder.status_reply_indicator_diag_top.setBackgroundResource(R.drawable.diag_top_android4);
} else {
holder.status_reply_indicator_diag_top.setBackgroundResource(R.drawable.diag_top);
}
holder.status_reply_indicator_diag_top.setBackgroundResource(R.drawable.diag_top);
holder.status_reply_indicator_diag_top.setVisibility(View.VISIBLE);
}
}
@ -700,12 +741,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.reply_indicator_dot.setVisibility(View.VISIBLE);
holder.status_reply_indicator_bottom.setVisibility(View.VISIBLE);
if (holder.status_reply_indicator_diag_bottom != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
holder.status_reply_indicator_diag_bottom.setBackgroundResource(R.drawable.diag_bottom_android4);
} else {
holder.status_reply_indicator_diag_bottom.setBackgroundResource(R.drawable.diag_bottom);
}
holder.status_reply_indicator_diag_bottom.setBackgroundResource(R.drawable.diag_bottom);
holder.status_reply_indicator_diag_bottom.setVisibility(View.VISIBLE);
}
}
@ -792,7 +828,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
greaterValue = pollOption.getVotes_count();
}
for (PollOptions pollOption : poll.getOptionsList()) {
double value = ((double) (pollOption.getVotes_count() * 100) / (double) poll.getVotes_count());
double value = ((double) (pollOption.getVotes_count() * 100) / (double) poll.getVoters_count());
if (pollOption.getVotes_count() == greaterValue) {
BarItem bar = new BarItem(pollOption.getTitle(), value, "%", ContextCompat.getColor(context, R.color.mastodonC4), Color.WHITE);
bar.setDescriptionSpan(pollOption.getTitleSpan());
@ -894,8 +930,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
});
holder.poll_container.setVisibility(View.VISIBLE);
holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_vote, poll.getVotes_count(), poll.getVotes_count()));
holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at())));
holder.number_votes.setText(context.getResources().getQuantityString(R.plurals.number_of_voters, poll.getVoters_count(), poll.getVoters_count()));
if( poll.isExpired()){
holder.remaining_time.setText(context.getString(R.string.poll_finish_at, Helper.dateToStringPoll(poll.getExpires_at())));
}else{
holder.remaining_time.setText(context.getString(R.string.poll_finish_in, Helper.dateDiffPoll(context, poll.getExpires_at())));
}
} else {
holder.poll_container.setVisibility(View.GONE);
}
@ -1113,9 +1153,25 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.status_reblog_count.setTextColor(iconColor);
holder.status_account_displayname.setTextColor(ThemeHelper.getAttColor(context, R.attr.textHeader));
holder.status_toot_date.setTextColor(ThemeHelper.getAttColor(context, R.attr.textHeader));
Helper.changeDrawableColor(context, R.drawable.ic_repeat_head_toot, R.attr.textHeader);
int theme_text_header_2_line = prefs.getInt("theme_text_header_2_line", -1);
if (theme_text_header_2_line == -1) {
theme_text_header_2_line = ThemeHelper.getAttColor(context, R.attr.textHeader);
}
holder.status_account_displayname.setTextColor(theme_text_header_2_line);
holder.status_toot_date.setTextColor(theme_text_header_2_line);
if( holder.status_boosted_date != null ) {
holder.status_boosted_date.setTextColor(theme_text_header_2_line);
}
Helper.changeDrawableColor(context, R.drawable.ic_repeat_head_toot, theme_text_header_2_line);
int theme_text_header_1_line = prefs.getInt("theme_text_header_1_line", -1);
if (theme_text_header_1_line == -1) {
theme_text_header_1_line = ThemeHelper.getAttColor(context, R.attr.textColor);
}
holder.status_account_displayname_owner.setTextColor(theme_text_header_1_line);
Helper.changeDrawableColor(context, holder.cached_status, theme_text_header_1_line);
if (holder.cached_status != null && holder.getItemViewType() == DISPLAYED_STATUS) {
@ -1250,10 +1306,17 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.spark_button_reblog.setMinimumWidth((int) Helper.convertDpToPixel((20 * iconSizePercent / 100 * scale + 0.5f), context));
Drawable imgConversation = null;
if (type != RetrieveFeedsAsyncTask.Type.CONTEXT && ((status.getIn_reply_to_account_id() != null && status.getIn_reply_to_account_id().equals(status.getAccount().getId()))
|| (status.getReblog() != null && status.getReblog().getIn_reply_to_account_id() != null && status.getReblog().getIn_reply_to_account_id().equals(status.getReblog().getAccount().getId())))) {
imgConversation = ContextCompat.getDrawable(context, R.drawable.ic_conversation);
imgConversation.setBounds(0, 0, (int) (15 * iconSizePercent / 100 * scale + 0.5f), (int) (15 * iconSizePercent / 100 * scale + 0.5f));
if( social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {
if (type != RetrieveFeedsAsyncTask.Type.CONTEXT && ((status.getIn_reply_to_account_id() != null && status.getIn_reply_to_account_id().equals(status.getAccount().getId()))
|| (status.getReblog() != null && status.getReblog().getIn_reply_to_account_id() != null && status.getReblog().getIn_reply_to_account_id().equals(status.getReblog().getAccount().getId())))) {
imgConversation = ContextCompat.getDrawable(context, R.drawable.ic_conversation);
imgConversation.setBounds(0, 0, (int) (15 * iconSizePercent / 100 * scale + 0.5f), (int) (15 * iconSizePercent / 100 * scale + 0.5f));
}
}else {
if (type != RetrieveFeedsAsyncTask.Type.CONTEXT && status.getIn_reply_to_id() != null) {
imgConversation = ContextCompat.getDrawable(context, R.drawable.ic_conversation);
imgConversation.setBounds(0, 0, (int) (15 * iconSizePercent / 100 * scale + 0.5f), (int) (15 * iconSizePercent / 100 * scale + 0.5f));
}
}
if (status.getReblog() != null) {
Drawable img = ContextCompat.getDrawable(context, R.drawable.ic_repeat_head_toot);
@ -1290,6 +1353,38 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
status.setImageFound(true);
Status.makeImage(context, this, status);
}
if (instanceType != null && instanceType.compareTo("NITTER") == 0) {
holder.status_action_container.setVisibility(View.GONE);
if( holder.status_action_container_twitter != null){
holder.status_action_container_twitter.setVisibility(View.VISIBLE);
holder.status_action_container_twitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via));
String url = status.getUrl();
String extra_text;
extra_text = (status.getReblog() != null) ? status.getReblog().getAccount().getAcct() : status.getAccount().getAcct();
if (extra_text.split("@").length == 1)
extra_text = "@" + extra_text + "@" + Helper.getLiveInstance(context);
else
extra_text = "@" + extra_text;
extra_text += " " + Helper.shortnameToUnicode(":link:", true) + " " + url + "\r\n-\n";
final String contentToot;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
contentToot = Html.fromHtml((status.getReblog() != null) ? status.getReblog().getContent() : status.getContent(), Html.FROM_HTML_MODE_LEGACY).toString();
else
//noinspection deprecation
contentToot = Html.fromHtml((status.getReblog() != null) ? status.getReblog().getContent() : status.getContent()).toString();
extra_text += contentToot;
sendIntent.putExtra(Intent.EXTRA_TEXT, extra_text);
sendIntent.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_with)));
}
});
}
}
holder.status_content.setOnTouchListener(new View.OnTouchListener() {
@Override
@ -1317,7 +1412,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
});
//Click on a conversation
if ((getItemViewType(viewHolder.getAdapterPosition()) == DISPLAYED_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == COMPACT_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == CONSOLE_STATUS)) {
if (( instanceType == null || instanceType.compareTo("NITTER") != 0) && (getItemViewType(viewHolder.getAdapterPosition()) == DISPLAYED_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == COMPACT_STATUS || getItemViewType(viewHolder.getAdapterPosition()) == CONSOLE_STATUS)) {
holder.status_spoiler.setOnClickListener(new View.OnClickListener() {
@Override
@ -1513,7 +1608,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
holder.status_content.setMovementMethod(LinkMovementMethod.getInstance());
holder.status_content.setMovementMethod(LongClickLinkMovementMethod.getInstance());
holder.status_spoiler.setMovementMethod(LinkMovementMethod.getInstance());
if (truncate_toots_size > 0) {
holder.status_content.setMaxLines(truncate_toots_size);
@ -1581,7 +1676,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
else
holder.status_account_displayname_owner.setText(status.getReblog().getAccount().getAcct().replace("@", ""));
holder.status_account_displayname_owner.setVisibility(View.VISIBLE);
if (holder.status_boosted_date != null) {
holder.status_boosted_date.setText(Helper.dateDiff(context, status.getCreated_at()));
}
} else {
accountForUrl = status.getAccount();
holder.status_account_displayname.setVisibility(View.GONE);
@ -1608,7 +1705,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
int matchStart = matcherAcct.start(1);
int matchEnd = matcherAcct.end();
if (wordtoSpan.length() >= matchEnd && matchStart < matchEnd) {
wordtoSpan.setSpan(new ForegroundColorSpan(ThemeHelper.getAttColor(context, R.attr.textHeader)), matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new ForegroundColorSpan(theme_text_header_2_line), matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
@ -1730,7 +1827,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
fullDate = fullDate_tmp.substring(0, 1).toUpperCase() + fullDate_tmp.substring(1);
holder.status_toot_date.setText(fullDate);
} else {
holder.status_toot_date.setText(Helper.dateDiff(context, status.getCreated_at()));
if (status.getReblog() != null)
holder.status_toot_date.setText(Helper.dateDiff(context, status.getReblog().getCreated_at()));
else
holder.status_toot_date.setText(Helper.dateDiff(context, status.getCreated_at()));
Helper.absoluteDateTimeReveal(context, holder.status_toot_date, status.getCreated_at());
}
@ -2029,11 +2129,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (status.isTranslationShown() && status.getContentSpanTranslated() != null) {
holder.status_content_translated.setText(status.getContentSpanTranslated(), TextView.BufferType.SPANNABLE);
holder.status_content_translated_container.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
holder.translation_border_view.setBackgroundResource(R.drawable.translation_border_android4);
} else {
holder.translation_border_view.setBackgroundResource(R.drawable.translation_border);
}
holder.translation_border_view.setBackgroundResource(R.drawable.translation_border);
} else { //Toot is not translated
holder.status_content_translated_container.setVisibility(View.GONE);
@ -2055,11 +2151,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.spark_button_reblog.setVisibility(View.GONE);
}
break;
case "public":
case "unlisted":
holder.status_reblog_count.setVisibility(View.VISIBLE);
holder.spark_button_reblog.setVisibility(View.VISIBLE);
break;
default:
holder.status_reblog_count.setVisibility(View.VISIBLE);
holder.spark_button_reblog.setVisibility(View.VISIBLE);
@ -2303,6 +2394,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
.into(holder.webview_preview_card);
holder.status_cardview.setVisibility(View.GONE);
holder.status_cardview_video.setVisibility(View.VISIBLE);
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if( user_agent != null) {
holder.status_cardview_webview.getSettings().setUserAgentString(user_agent);
}
holder.status_cardview_webview.getSettings().setJavaScriptEnabled(true);
String html = card.getHtml();
String src = card.getUrl();
@ -2508,8 +2603,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
break;
}
}
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)
holder.quick_reply_text.addTextChangedListener(textWatcher);
holder.quick_reply_text.addTextChangedListener(textWatcher);
} else {
status.setShortReply(false);
@ -2664,7 +2759,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
toot.setMedia_attachments(status.getMedia_attachments());
if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0)
toot.setSpoiler_text(status.getSpoiler_text().trim());
toot.setContent(status.getContent());
toot.setContent(context, status.getContent());
toot.setVisibility(status.getVisibility());
new RetrieveFeedsAsyncTask(context, RetrieveFeedsAsyncTask.Type.ONESTATUS, status.getIn_reply_to_id(), null, false, false, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
@ -2674,7 +2769,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0)
toot.setSpoiler_text(status.getSpoiler_text().trim());
toot.setVisibility(status.getVisibility());
toot.setContent(status.getContent());
toot.setContent(context, status.getContent());
final SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
long id = new StatusStoredDAO(context, db).insertStatus(toot, null);
Intent intentToot = new Intent(context, TootActivity.class);
@ -3065,7 +3160,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
toot.setMedia_attachments(status.getMedia_attachments());
if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0)
toot.setSpoiler_text(status.getSpoiler_text().trim());
toot.setContent(status.getContent());
toot.setContent(context, status.getContent());
toot.setVisibility(status.getVisibility());
if (status.getPoll() != null) {
toot.setPoll(status.getPoll());
@ -3080,7 +3175,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0)
toot.setSpoiler_text(status.getSpoiler_text().trim());
toot.setVisibility(status.getVisibility());
toot.setContent(status.getContent());
toot.setContent(context, status.getContent());
if (status.getPoll() != null) {
toot.setPoll(status.getPoll());
} else if (status.getReblog() != null && status.getReblog().getPoll() != null) {
@ -3146,7 +3241,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
});
} else {
} else if( instanceType == null || instanceType.compareTo("NITTER") != 0){
holder.status_account_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@ -3219,6 +3314,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
}
}
private void loadAttachments(final Status status, final ViewHolder holder, boolean blur) {
@ -3240,21 +3336,29 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.status_horizontal_document_container.setVisibility(View.VISIBLE);
else
holder.status_document_container.setVisibility(View.VISIBLE);
if (attachments.size() == 1) {
if (!fullAttachement)
holder.status_container2.setVisibility(View.GONE);
else {
holder.status_prev1_h.setVisibility(View.VISIBLE);
holder.status_prev2_h.setVisibility(View.GONE);
holder.status_prev3_h.setVisibility(View.GONE);
holder.status_prev4_h.setVisibility(View.GONE);
holder.horizontal_second_image.setVisibility(View.GONE);
}
if (attachments.get(0).getUrl().trim().contains("missing.png"))
if (attachments.size() == 1 ) {
if ((status.getCard() == null || status.getCard().getType().compareTo("video") != 0|| status.getCard().getImage() == null)) {
if (!fullAttachement)
holder.status_container2.setVisibility(View.GONE);
else {
holder.status_prev1_h.setVisibility(View.VISIBLE);
holder.status_prev2_h.setVisibility(View.GONE);
holder.status_prev3_h.setVisibility(View.GONE);
holder.status_prev4_h.setVisibility(View.GONE);
holder.horizontal_second_image.setVisibility(View.GONE);
}
if (attachments.get(0).getUrl().trim().contains("missing.png")) {
if (fullAttachement)
holder.status_horizontal_document_container.setVisibility(View.GONE);
else
holder.status_document_container.setVisibility(View.GONE);
}
}else {
if (fullAttachement)
holder.status_horizontal_document_container.setVisibility(View.GONE);
else
holder.status_document_container.setVisibility(View.GONE);
}
} else if (attachments.size() == 2) {
if (!fullAttachement) {
holder.status_container2.setVisibility(View.VISIBLE);
@ -3409,6 +3513,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
.asBitmap()
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.thumbnail(0.1f)
//.override(640, 480)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(new SimpleTarget<Bitmap>() {
@Override
@ -3432,6 +3537,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
.asBitmap()
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.thumbnail(0.1f)
// .override(640, 480)
.apply(new RequestOptions().transforms(new BlurTransformation(50, 3), new RoundedCorners(10)))
.into(new SimpleTarget<Bitmap>() {
@Override
@ -3457,6 +3563,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
Glide.with(imageView.getContext())
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.thumbnail(0.1f)
.override(640, 480)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageView);
@ -3464,6 +3571,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
Glide.with(imageView.getContext())
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.thumbnail(0.1f)
.override(640, 480)
.apply(new RequestOptions().transforms(new BlurTransformation(50, 3), new RoundedCorners(10)))
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageView);
@ -3520,12 +3628,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
});
boolean long_press_media = sharedpreferences.getBoolean(Helper.SET_LONG_PRESS_MEDIA, true);
if (long_press_media) {
String finalUrl = url;
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String myDir = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
String fileName = URLUtil.guessFileName(attachment.getUrl(), null, null);
Helper.download(context, myDir + "/" + fileName, attachment.getUrl());
Helper.manageMove(context, finalUrl, false);
return true;
}
});
@ -3819,19 +3926,17 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = Helper.getLiveInstance(context);
int split_toot_size = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE);
boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false);
String tootContent;
if (toot_cw_content.getText() != null && toot_cw_content.getText().toString().trim().length() > 0)
split_toot_size -= toot_cw_content.getText().toString().trim().length();
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || !split_toot || (TootActivity.countLength(social, toot_content, toot_cw_content) < split_toot_size)) {
tootContent = toot_content.getText().toString().trim();
createAndSendToot(status, content_type, userId, instance);
createAndSendToot(status, null, content_type, userId, instance);
} else {
splitToot = Helper.splitToots(toot_content.getText().toString().trim(), split_toot_size, true);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
tootContent = splitToot.get(0);
stepSpliToot = 1;
int style;
if (theme == Helper.THEME_DARK) {
@ -3881,7 +3986,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
createAndSendToot(status, content_type, userId, instance);
createAndSendToot(status, splitToot.get(0), content_type, userId, instance);
dialog.dismiss();
}
});
@ -3891,7 +3996,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
private void createAndSendToot(Status status, String content_type, String userId, String instance) {
private void createAndSendToot(Status status, String content, String content_type, String userId, String instance) {
Status toot = new Status();
if (content_type != null)
toot.setContentType(content_type);
@ -3902,7 +4007,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
toot.setSpoiler_text(toot_cw_content.getText().toString().trim());
toot.setVisibility(status.getQuickReplyPrivacy());
toot.setIn_reply_to_id(in_reply_to_status);
toot.setContent(status.getQuickReplyContent());
if( content == null) {
content = status.getQuickReplyContent();
}
toot.setContent(context, content);
new PostStatusAsyncTask(context, social, account, toot, StatusListAdapter.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
status.setQuickReplyPrivacy(null);
status.setQuickReplyContent(null);
@ -4015,38 +4123,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
//noinspection ConstantConditions
if (statusListAdapter.getItemAt(i) != null && statusListAdapter.getItemAt(i).getId().equals(status.getId())) {
try {
if (statuses.get(i).isFocused()) {
status.setFocused(true);
}
if (statuses.get(i).isFetchMore()) {
status.setFetchMore(true);
}
if (statuses.get(i).isShortReply()) {
status.setShortReply(true);
}
if (statuses.get(i).getQuickReplyContent() != null) {
status.setQuickReplyContent(statuses.get(i).getQuickReplyContent());
}
if (statuses.get(i).getQuickReplyPrivacy() != null) {
status.setQuickReplyPrivacy(statuses.get(i).getQuickReplyPrivacy());
}
if (statuses.get(i).isShowTopLine()) {
status.setShowTopLine(true);
}
if (statuses.get(i).isShowBottomLine()) {
status.setShowBottomLine(true);
}
statuses.set(i, status);
statuses.get(i).setFavourites_count(status.getFavourites_count());
statuses.get(i).setReblogs_count(status.getReblogs_count());
statuses.get(i).setFavourited(status.isFavourited());
statuses.get(i).setReblogged(status.isReblogged());
statuses.get(i).setReplies_count(status.getReplies_count());
statusListAdapter.notifyItemChanged(i);
/*if( mRecyclerView != null) {
int finalI = i;
mRecyclerView.post(new Runnable() {
@Override
public void run() {
statusListAdapter.notifyItemChanged(finalI);
}
});
}*/
} catch (Exception ignored) {
}
break;
@ -4054,51 +4136,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
}
public void notifyStatusWithActionChanged(Status status) {
if (status == null)
return;
for (int i = 0; i < statusListAdapter.getItemCount(); i++) {
//noinspection ConstantConditions
if (statusListAdapter.getItemAt(i) != null && statusListAdapter.getItemAt(i).getId().equals(status.getId())) {
try {
if (statuses.get(i).isFocused()) {
status.setFocused(true);
}
if (statuses.get(i).isFetchMore()) {
status.setFetchMore(true);
}
if (statuses.get(i).isShortReply()) {
status.setShortReply(true);
}
if (statuses.get(i).getQuickReplyContent() != null) {
status.setQuickReplyContent(statuses.get(i).getQuickReplyContent());
}
if (statuses.get(i).getQuickReplyPrivacy() != null) {
status.setQuickReplyPrivacy(statuses.get(i).getQuickReplyPrivacy());
}
if (statuses.get(i).isShowTopLine()) {
status.setShowTopLine(true);
}
if (statuses.get(i).isShowBottomLine()) {
status.setShowBottomLine(true);
}
statuses.set(i, status);
statusListAdapter.notifyItemChanged(i);
/*if( mRecyclerView != null) {
int finalI = i;
mRecyclerView.post(new Runnable() {
@Override
public void run() {
statusListAdapter.notifyItemChanged(finalI);
}
});
}*/
} catch (Exception ignored) {
}
break;
}
}
}
@Override
public void onRetrieveImage(Status status, boolean fromTranslation) {
@ -4134,13 +4171,15 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int trans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX);
MyTransL.translatorEngine et = MyTransL.translatorEngine.YANDEX;
String api_key = null;
String api_key;
if (trans == Helper.TRANS_YANDEX) {
et = MyTransL.translatorEngine.YANDEX;
} else if (trans == Helper.TRANS_DEEPL) {
et = MyTransL.translatorEngine.DEEPL;
} else if (trans == Helper.TRANS_SYSTRAN) {
et = MyTransL.translatorEngine.SYSTRAN;
}
final MyTransL myTransL = MyTransL.getInstance(et);
myTransL.setObfuscation(true);
@ -4150,6 +4189,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
} else if (trans == Helper.TRANS_DEEPL) {
api_key = sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, "");
myTransL.setDeeplAPIKey(api_key);
} else if (trans == Helper.TRANS_SYSTRAN) {
api_key = sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, "");
myTransL.setSystranAPIKey(api_key);
}
@ -4158,7 +4200,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
statusToTranslate = Html.fromHtml(status.getReblog() != null ? status.getReblog().getContent() : status.getContent(), Html.FROM_HTML_MODE_LEGACY).toString();
else
//noinspection deprecation
statusToTranslate = Html.fromHtml(status.getReblog() != null ? status.getReblog().getContent() : status.getContent()).toString();
//TODO: removes the replaceAll once fixed with the lib
myTransL.translate(statusToTranslate, myTransL.getLocale(), new Results() {
@ -4203,7 +4244,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
toot.setVisibility(statusForQuickReply.getQuickReplyPrivacy());
}
if (statusForQuickReply.getQuickReplyContent() != null) {
toot.setContent(statusForQuickReply.getQuickReplyContent().trim());
toot.setContent(context, statusForQuickReply.getQuickReplyContent().trim());
}
toot.setIn_reply_to_id(tootReply.getId());
@ -4238,7 +4279,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
TextView status_content_translated;
ConstraintLayout status_content_translated_container;
TextView status_account_username;
TextView status_account_displayname, status_account_displayname_owner;
TextView status_account_displayname, status_account_displayname_owner, status_boosted_date;
ImageView status_account_profile;
ImageView status_account_profile_boost_by;
ConstraintLayout status_boosted_by_info;
@ -4281,6 +4322,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
ConstraintLayout main_container;
TextView yandex_translate;
ConstraintLayout status_action_container;
ConstraintLayout status_action_container_twitter;
Button fetch_more;
ImageView new_element;
LinearLayout status_spoiler_mention_container;
@ -4342,6 +4384,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
status_content_translated = itemView.findViewById(R.id.status_content_translated);
status_account_username = itemView.findViewById(R.id.status_account_username);
status_account_displayname = itemView.findViewById(R.id.status_account_displayname);
status_boosted_date = itemView.findViewById(R.id.status_boosted_date);
status_account_displayname_owner = itemView.findViewById(R.id.status_account_displayname_owner);
status_account_profile = itemView.findViewById(R.id.status_account_profile);
status_account_profile_boost_by = itemView.findViewById(R.id.status_account_profile_boost_by);
@ -4386,6 +4429,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
yandex_translate = itemView.findViewById(R.id.yandex_translate);
new_element = itemView.findViewById(R.id.new_element);
status_action_container = itemView.findViewById(R.id.status_action_container);
status_action_container_twitter = itemView.findViewById(R.id.status_action_container_twitter);
status_spoiler_mention_container = itemView.findViewById(R.id.status_spoiler_mention_container);
status_mention_spoiler = itemView.findViewById(R.id.status_mention_spoiler);
status_cardview = itemView.findViewById(R.id.status_cardview);
@ -4474,10 +4518,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
if (!disableAnimatedEmoji) {
if (BaseMainActivity.timer == null) {
BaseMainActivity.timer = new Timer();
if (BaseActivity.timer == null) {
BaseActivity.timer = new Timer();
}
BaseMainActivity.timer.schedule(new TimerTask() {
BaseActivity.timer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(updateAnimatedEmoji);

View File

@ -0,0 +1,176 @@
package app.fedilab.android.drawers;
/* Copyright 2019 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import app.fedilab.android.R;
import app.fedilab.android.activities.HashTagActivity;
import app.fedilab.android.client.Entities.Trends;
import app.fedilab.android.client.Entities.TrendsHistory;
import app.fedilab.android.helper.Helper;
/**
* Created by Thomas on 30/11/2019.
* Adapter for Trends results
*/
public class TrendsAdapter extends BaseAdapter {
private List<Trends> trends;
private Context context;
private LayoutInflater layoutInflater;
public TrendsAdapter(Context context, List<Trends> trends) {
this.context = context;
this.trends = (trends != null) ? trends : new ArrayList<>();
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return trends.size();
}
@Override
public Object getItem(int position) {
return trends.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Trends trend = (Trends) getItem(position);
final ViewHolderTag holder;
View v = convertView;
if (v == null) {
v = layoutInflater.inflate(R.layout.drawer_tag_trends, parent, false);
holder = new ViewHolderTag();
holder.trends_container = v.findViewById(R.id.trends_container);
holder.tag_name = v.findViewById(R.id.tag_name);
holder.tag_stats = v.findViewById(R.id.tag_stats);
holder.count = v.findViewById(R.id.count);
holder.chart = v.findViewById(R.id.chart);
v.setTag(holder);
} else {
holder = (ViewHolderTag) v.getTag();
}
List<TrendsHistory> trendsHistory = trend.getTrendsHistory();
int people = 0;
int days = 0;
int uses = 0;
LinkedHashMap<Long, Integer> tendency = new LinkedHashMap<>();
for(TrendsHistory _th : trendsHistory) {
people += _th.getAccounts();
days ++;
uses += _th.getUses();
tendency.put(_th.getDays(), _th.getUses());
}
people = people / days;
uses = uses / days;
holder.count.setText(String.valueOf(uses));
holder.tag_stats.setText(context.getString(R.string.talking_about, people));
holder.tag_name.setText(String.format("#%s", trend.getName()));
holder.trends_container.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, HashTagActivity.class);
Bundle b = new Bundle();
b.putString("tag", trend.getName().trim());
intent.putExtras(b);
context.startActivity(intent);
}
});
List<Entry> trendsEntry = new ArrayList<>();
Iterator it = tendency.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
trendsEntry.add(0, new Entry((long) pair.getKey(), (int) pair.getValue()));
it.remove();
}
LineDataSet dataTrending = new LineDataSet(trendsEntry,context.getString(R.string.trending));
dataTrending.setColor(ContextCompat.getColor(context, R.color.cyanea_accent_reference));
dataTrending.setValueTextColor(ContextCompat.getColor(context, R.color.cyanea_accent_reference));
dataTrending.setFillColor(ContextCompat.getColor(context, R.color.cyanea_accent_reference));
dataTrending.setDrawValues(false);
dataTrending.setDrawFilled(true);
dataTrending.setDrawCircles(false);
dataTrending.setDrawCircleHole(false);
holder.chart.getAxis(YAxis.AxisDependency.LEFT).setEnabled(false);
holder.chart.getAxis(YAxis.AxisDependency.RIGHT).setEnabled(false);
holder.chart.getXAxis().setEnabled(false);
holder.chart.getLegend().setEnabled(false);
holder.chart.setTouchEnabled(false);
dataTrending.setMode(LineDataSet.Mode.CUBIC_BEZIER);
Description description = holder.chart.getDescription();
description.setEnabled(false);
List<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(dataTrending);
LineData data = new LineData(dataSets);
holder.chart.setData(data);
holder.chart.invalidate();
return v;
}
private class ViewHolderTag {
LinearLayout trends_container;
TextView tag_name;
TextView tag_stats;
TextView count;
LineChart chart;
}
}

View File

@ -178,12 +178,16 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
if (key.compareTo("base_theme") == 0) {
SharedPreferences sharedpreferences = getActivity().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor appEditor = sharedpreferences.edit();
appEditor.putInt(Helper.SET_THEME, Integer.parseInt(value));
if( value != null && value.matches("-?\\d+")) {
appEditor.putInt(Helper.SET_THEME, Integer.parseInt(value));
}
appEditor.commit();
} else if (key.compareTo("pref_color_navigation_bar") == 0 || key.compareTo("pref_color_status_bar") == 0) {
editor.putBoolean(key, Boolean.valueOf(value));
editor.putBoolean(key, Boolean.parseBoolean(value));
} else {
editor.putInt(key, Integer.valueOf(value));
if( value != null && value.matches("-?\\d+")) {
editor.putInt(key, Integer.parseInt(value));
}
}
}
}
@ -246,10 +250,16 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
PreferenceScreen preferenceScreen = getPreferenceScreen();
FragmentActivity context = getActivity();
assert context != null;
if( preferenceScreen == null){
Toasty.error(getActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show();
return;
}
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
ListPreference pref_theme_picker = (ListPreference) findPreference("pref_theme_picker");
Preference theme_link_color = findPreference("theme_link_color");
Preference theme_boost_header_color = findPreference("theme_boost_header_color");
Preference theme_text_header_1_line = findPreference("theme_text_header_1_line");
Preference theme_text_header_2_line = findPreference("theme_text_header_2_line");
Preference theme_statuses_color = findPreference("theme_statuses_color");
Preference theme_icons_color = findPreference("theme_icons_color");
Preference theme_text_color = findPreference("theme_text_color");
@ -261,9 +271,11 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
Preference pref_import = findPreference("pref_import");
Preference pref_export = findPreference("pref_export");
Preference reset_pref = findPreference("reset_pref");
if (!sharedpreferences.getBoolean("use_custom_theme", false)) {
if (!sharedpreferences.getBoolean("use_custom_theme", false) ) {
preferenceScreen.removePreference(theme_link_color);
preferenceScreen.removePreference(theme_boost_header_color);
preferenceScreen.removePreference(theme_text_header_1_line);
preferenceScreen.removePreference(theme_text_header_2_line);
preferenceScreen.removePreference(theme_statuses_color);
preferenceScreen.removePreference(theme_icons_color);
preferenceScreen.removePreference(theme_text_color);
@ -361,6 +373,8 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.remove("theme_boost_header_color");
editor.remove("theme_text_header_1_line");
editor.remove("theme_text_header_2_line");
editor.remove("theme_statuses_color");
editor.remove("theme_link_color");
editor.remove("theme_icons_color");
@ -370,7 +384,7 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
editor.remove("theme_accent");
editor.remove("theme_text_color");
editor.remove("theme_primary");
editor.remove("use_custom_theme");
//editor.remove("use_custom_theme");
editor.commit();
}
@ -387,6 +401,8 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
builder.append("value").append(',');
builder.append('\n');
int theme_boost_header_color = prefs.getInt("theme_boost_header_color", -1);
int theme_text_header_1_line = prefs.getInt("theme_text_header_1_line", -1);
int theme_text_header_2_line = prefs.getInt("theme_text_header_2_line", -1);
int theme_statuses_color = prefs.getInt("theme_statuses_color", -1);
int theme_link_color = prefs.getInt("theme_link_color", -1);
int theme_icons_color = prefs.getInt("theme_icons_color", -1);
@ -408,6 +424,14 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
builder.append(theme_boost_header_color).append(',');
builder.append('\n');
builder.append("theme_text_header_1_line").append(',');
builder.append(theme_text_header_1_line).append(',');
builder.append('\n');
builder.append("theme_text_header_2_line").append(',');
builder.append(theme_text_header_2_line).append(',');
builder.append('\n');
builder.append("theme_statuses_color").append(',');
builder.append(theme_statuses_color).append(',');
builder.append('\n');

View File

@ -68,9 +68,11 @@ import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import app.fedilab.android.R;
@ -118,6 +120,7 @@ import static app.fedilab.android.fragments.ContentSettingsFragment.type.INTERFA
import static app.fedilab.android.fragments.ContentSettingsFragment.type.LANGUAGE;
import static app.fedilab.android.fragments.ContentSettingsFragment.type.MENU;
import static app.fedilab.android.fragments.ContentSettingsFragment.type.NOTIFICATIONS;
import static app.fedilab.android.fragments.ContentSettingsFragment.type.PRIVACY;
import static app.fedilab.android.fragments.ContentSettingsFragment.type.TIMELINES;
public class ContentSettingsFragment extends Fragment implements OnRetrieveRemoteAccountInterface, OnRetrieveRelationshipInterface {
@ -263,7 +266,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
}
@Override
public void onRetrieveRemoteAccount(Results results) {
public void onRetrieveRemoteAccount(Results results, boolean devAccount) {
if (results == null) {
return;
}
@ -378,6 +381,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
LinearLayout settings_admin = rootView.findViewById(R.id.settings_admin);
LinearLayout settings_interface = rootView.findViewById(R.id.settings_interface);
LinearLayout settings_compose = rootView.findViewById(R.id.settings_compose);
LinearLayout settings_privacy = rootView.findViewById(R.id.settings_privacy);
LinearLayout settings_hide_menu = rootView.findViewById(R.id.settings_hide_menu);
LinearLayout settings_translation = rootView.findViewById(R.id.settings_translation);
@ -392,6 +396,8 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
settings_interface.setVisibility(View.VISIBLE);
} else if (type == COMPOSE) {
settings_compose.setVisibility(View.VISIBLE);
} else if (type == PRIVACY) {
settings_privacy.setVisibility(View.VISIBLE);
} else if (type == MENU) {
settings_hide_menu.setVisibility(View.VISIBLE);
} else if (type == LANGUAGE) {
@ -504,7 +510,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
Spinner set_attachment_group = rootView.findViewById(R.id.set_attachment_group);
String[] attachment_labels = {context.getString(R.string.set_attachment_always), context.getString(R.string.set_attachment_wifi), context.getString(R.string.set_attachment_ask)};
ArrayAdapter<String> adapterAttachment = new ArrayAdapter<>(context,
ArrayAdapter<String> adapterAttachment = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_dropdown_item, attachment_labels);
set_attachment_group.setAdapter(adapterAttachment);
int attachmentAction = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS);
@ -552,8 +558,8 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
//Video mode
final Spinner video_mode_spinner = rootView.findViewById(R.id.set_video_mode);
ArrayAdapter<CharSequence> video_mode_spinnerAdapter = ArrayAdapter.createFromResource(getContext(),
R.array.settings_video_mode, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> video_mode_spinnerAdapter = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()),
R.array.settings_video_mode, android.R.layout.simple_spinner_dropdown_item);
video_mode_spinner.setAdapter(video_mode_spinnerAdapter);
if (videoMode == Helper.VIDEO_MODE_TORRENT)
videoMode = Helper.VIDEO_MODE_DIRECT;
@ -715,6 +721,8 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
store = Helper.SET_YANDEX_API_KEY;
else if (translatore == Helper.TRANS_DEEPL)
store = Helper.SET_DEEPL_API_KEY;
else if (translatore == Helper.TRANS_SYSTRAN)
store = Helper.SET_SYSTRAN_API_KEY;
if (store != null)
if (s != null && s.length() > 0)
editor.putString(store, s.toString().trim());
@ -915,6 +923,46 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
});
TextView set_user_agent = rootView.findViewById(R.id.set_user_agent);
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if (user_agent != null) {
set_user_agent.setText(user_agent);
}
set_user_agent.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
SharedPreferences.Editor editor = sharedpreferences.edit();
if (s.toString().trim().length() > 0) {
editor.putString(Helper.SET_CUSTOM_USER_AGENT, s.toString().toLowerCase().trim());
} else {
editor.putString(Helper.SET_CUSTOM_USER_AGENT, null);
}
editor.apply();
}
});
final SwitchCompat set_utm_parameters = rootView.findViewById(R.id.set_utm_parameters);
boolean utm_parameters = sharedpreferences.getBoolean(Helper.SET_FILTER_UTM, true);
set_utm_parameters.setChecked(utm_parameters);
set_utm_parameters.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(Helper.SET_FILTER_UTM, set_utm_parameters.isChecked());
editor.apply();
}
});
TextView set_nitter_host = rootView.findViewById(R.id.set_nitter_host);
boolean nitter = sharedpreferences.getBoolean(Helper.SET_NITTER, false);
final SwitchCompat set_nitter = rootView.findViewById(R.id.set_nitter);
@ -1138,7 +1186,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
Spinner set_mode = rootView.findViewById(R.id.set_mode);
String[] mode_labels = {context.getString(R.string.set_normal), context.getString(R.string.set_compact), context.getString(R.string.set_console)};
ArrayAdapter<String> adapterMode = new ArrayAdapter<>(context,
ArrayAdapter<String> adapterMode = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_dropdown_item, mode_labels);
set_mode.setAdapter(adapterMode);
boolean compact_mode = sharedpreferences.getBoolean(Helper.SET_COMPACT_MODE, false);
@ -1303,11 +1351,12 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true);
final SwitchCompat switchCompatNotify = rootView.findViewById(R.id.set_notify);
switchCompatNotify.setChecked(notify);
final LinearLayout notification_settings = rootView.findViewById(R.id.notification_settings);
if (notify)
notification_settings.setVisibility(View.VISIBLE);
else
notification_settings.setVisibility(View.GONE);
final LinearLayout notification_container = rootView.findViewById(R.id.notification_container);
if (notify) {
notification_container.setVisibility(View.VISIBLE);
} else {
notification_container.setVisibility(View.GONE);
}
switchCompatNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
@ -1316,9 +1365,15 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
editor.putBoolean(Helper.SET_NOTIFY, isChecked);
editor.apply();
if (isChecked) {
notification_settings.setVisibility(View.VISIBLE);
notification_container.setVisibility(View.VISIBLE);
notification_container.setVisibility(View.VISIBLE);
Helper.startStreaming(context);
}else {
context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class));
context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class));
ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH);
notification_container.setVisibility(View.GONE);
}
Helper.startStreaming(context);
}
});
@ -1326,7 +1381,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
//Live notification mode
final Spinner set_live_type = rootView.findViewById(R.id.set_live_type);
String[] labels = {context.getString(R.string.live_notif), context.getString(R.string.live_delayed), context.getString(R.string.no_live_notif)};
ArrayAdapter<String> adapterLive = new ArrayAdapter<>(context,
ArrayAdapter<String> adapterLive = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_dropdown_item, labels);
LinearLayout live_notif_per_account = rootView.findViewById(R.id.live_notif_per_account);
@ -1353,43 +1408,34 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (liveNotificationCount > 0) {
SharedPreferences.Editor editor = sharedpreferences.edit();
context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class));
context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class));
ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH);
switch (position) {
case Helper.NOTIF_LIVE:
editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, true);
editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false);
live_notif_per_account.setVisibility(View.VISIBLE);
editor.apply();
context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class));
ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH);
editor.commit();
set_live_type_indication.setText(R.string.live_notif_indication);
Helper.startStreaming(context);
break;
case Helper.NOTIF_DELAYED:
editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false);
editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, true);
live_notif_per_account.setVisibility(View.VISIBLE);
context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class));
editor.apply();
ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH);
set_live_type_indication.setText(R.string.set_live_type_indication);
editor.commit();
Helper.startStreaming(context);
break;
case Helper.NOTIF_NONE:
editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false);
editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false);
live_notif_per_account.setVisibility(View.GONE);
context.sendBroadcast(new Intent(context, StopLiveNotificationReceiver.class));
context.sendBroadcast(new Intent(context, StopDelayedNotificationReceiver.class));
NotificationsSyncJob.schedule(false);
editor.apply();
break;
}
Helper.startStreaming(context);
switch (Helper.liveNotifType(context)) {
case Helper.NOTIF_LIVE:
set_live_type_indication.setText(R.string.live_notif_indication);
break;
case Helper.NOTIF_DELAYED:
set_live_type_indication.setText(R.string.set_live_type_indication);
break;
case Helper.NOTIF_NONE:
editor.commit();
set_live_type_indication.setText(R.string.no_live_indication);
live_notif_per_account.setVisibility(View.GONE);
NotificationsSyncJob.schedule(false);
break;
}
} else {
@ -1605,6 +1651,38 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
});
// Media Description Timeout
SeekBar medDescTimeoutSeekBar = rootView.findViewById(R.id.set_med_desc_timeout);
final TextView set_med_desc_timeout_value = rootView.findViewById(R.id.set_med_desc_timeout_value);
medDescTimeoutSeekBar.setMax(30);
int medDescTimeout = sharedpreferences.getInt(Helper.SET_MED_DESC_TIMEOUT, 3);
medDescTimeoutSeekBar.setProgress(medDescTimeout);
set_med_desc_timeout_value.setText(String.valueOf(medDescTimeout));
medDescTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
set_med_desc_timeout_value.setText(String.valueOf(progress));
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Helper.SET_MED_DESC_TIMEOUT, progress);
editor.apply();
}
});
LinearLayout toot_visibility_container = rootView.findViewById(R.id.toot_visibility_container);
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
@ -1691,7 +1769,9 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
boolean allow_live_notifications = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + userId + instance, true);
TextView set_allow_live_notifications_title = rootView.findViewById(R.id.set_allow_live_notifications_title);
set_allow_live_notifications_title.setText(context.getString(R.string.set_allow_live_notifications, account.getAcct() + "@" + account.getInstance()));
if (account != null) {
set_allow_live_notifications_title.setText(context.getString(R.string.set_allow_live_notifications, account.getAcct() + "@" + account.getInstance()));
}
final SwitchCompat set_allow_live_notifications = rootView.findViewById(R.id.set_allow_live_notifications);
set_allow_live_notifications.setChecked(allow_live_notifications);
set_allow_live_notifications.setOnClickListener(new View.OnClickListener() {
@ -1784,10 +1864,15 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
//Translators
final Spinner translation_layout_spinner = rootView.findViewById(R.id.translation_layout_spinner);
ArrayAdapter<CharSequence> adapterTrans = ArrayAdapter.createFromResource(getContext(),
R.array.settings_translation, android.R.layout.simple_spinner_item);
translation_layout_spinner.setAdapter(adapterTrans);
List<String> translatorsList = Arrays.asList(getResources().getStringArray(R.array.settings_translation));
ArrayList<String> trans = new ArrayList<>(translatorsList);
trans.add(getString(R.string.no));
ArrayAdapter<String> adapterTrans = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, trans);
translation_layout_spinner.setAdapter(adapterTrans);
int positionSpinnerTrans;
switch (sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX)) {
case Helper.TRANS_YANDEX:
@ -1800,8 +1885,13 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
your_api_key.setVisibility(View.VISIBLE);
your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, ""));
break;
case Helper.TRANS_NONE:
case Helper.TRANS_SYSTRAN:
positionSpinnerTrans = 2;
your_api_key.setVisibility(View.VISIBLE);
your_api_key.setText(sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, ""));
break;
case Helper.TRANS_NONE:
positionSpinnerTrans = 3;
your_api_key.setVisibility(View.GONE);
break;
default:
@ -1819,30 +1909,30 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
case 0:
your_api_key.setVisibility(View.VISIBLE);
editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX);
editor.apply();
if (sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, null) != null)
your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, ""));
editor.commit();
your_api_key.setText(sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, ""));
break;
case 1:
your_api_key.setVisibility(View.VISIBLE);
editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_DEEPL);
editor.apply();
if (sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, null) != null)
your_api_key.setText(sharedpreferences.getString(Helper.SET_YANDEX_API_KEY, null));
editor.commit();
your_api_key.setText(sharedpreferences.getString(Helper.SET_DEEPL_API_KEY, ""));
break;
case 2:
your_api_key.setVisibility(View.VISIBLE);
editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_SYSTRAN);
editor.commit();
your_api_key.setText(sharedpreferences.getString(Helper.SET_SYSTRAN_API_KEY, ""));
break;
case 3:
your_api_key.setVisibility(View.GONE);
set_trans_forced.isChecked();
editor.putBoolean(Helper.SET_TRANS_FORCED, false);
editor.putInt(Helper.SET_TRANSLATOR, Helper.TRANS_NONE);
editor.apply();
editor.commit();
break;
}
if (getActivity() != null)
getActivity().recreate();
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(Helper.INTENT_ACTION, Helper.BACK_TO_SETTINGS);
startActivity(intent);
} else {
countTrans++;
}
@ -2092,8 +2182,8 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
final Spinner action_notification = rootView.findViewById(R.id.action_notification);
ArrayAdapter<CharSequence> adapterAction = ArrayAdapter.createFromResource(getContext(),
R.array.action_notification, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> adapterAction = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()),
R.array.action_notification, android.R.layout.simple_spinner_dropdown_item);
action_notification.setAdapter(adapterAction);
int positionNotificationAntion;
switch (sharedpreferences.getInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE)) {
@ -2227,7 +2317,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
ledLabel.setEnabled(true);
led_colour_spinner.setEnabled(true);
ArrayAdapter<CharSequence> adapterLEDColour = ArrayAdapter.createFromResource(getContext(), R.array.led_colours, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> adapterLEDColour = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()), R.array.led_colours, android.R.layout.simple_spinner_dropdown_item);
led_colour_spinner.setAdapter(adapterLEDColour);
int positionSpinnerLEDColour = (sharedpreferences.getInt(Helper.SET_LED_COLOUR, Helper.LED_COLOUR));
led_colour_spinner.setSelection(positionSpinnerLEDColour);
@ -2258,6 +2348,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
}
SwitchCompat nav_news = rootView.findViewById(R.id.nav_news);
SwitchCompat nav_trends = rootView.findViewById(R.id.nav_trends);
SwitchCompat nav_list = rootView.findViewById(R.id.nav_list);
SwitchCompat nav_scheduled = rootView.findViewById(R.id.nav_scheduled);
SwitchCompat nav_archive = rootView.findViewById(R.id.nav_archive);
@ -2276,6 +2367,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
mainMenu = new MainMenuItem();
}
nav_news.setChecked(mainMenu.isNav_news());
nav_trends.setChecked(mainMenu.isNav_trends());
nav_list.setChecked(mainMenu.isNav_list());
nav_scheduled.setChecked(mainMenu.isNav_scheduled());
nav_archive.setChecked(mainMenu.isNav_archive());
@ -2292,6 +2384,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
validate.setOnClickListener(view -> {
MainMenuItem mainMenuItem = new MainMenuItem();
mainMenuItem.setNav_news(nav_news.isChecked());
mainMenuItem.setNav_trends(nav_trends.isChecked());
mainMenuItem.setNav_list(nav_list.isChecked());
mainMenuItem.setNav_scheduled(nav_scheduled.isChecked());
mainMenuItem.setNav_archive(nav_archive.isChecked());
@ -2340,7 +2433,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
String currentLanguage = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, Helper.localeToStringStorage(Locale.getDefault()));
Locale currentLocale = Helper.restoreLocaleFromString(currentLanguage);
final Spinner set_change_locale = rootView.findViewById(R.id.set_change_locale);
ArrayAdapter<String> adapterLocale = new ArrayAdapter<>(context,
ArrayAdapter<String> adapterLocale = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_dropdown_item, Helper.getLocales(context));
set_change_locale.setAdapter(adapterLocale);
@ -2595,6 +2688,7 @@ public class ContentSettingsFragment extends Fragment implements OnRetrieveRemot
NOTIFICATIONS,
INTERFACE,
COMPOSE,
PRIVACY,
LANGUAGE,
MENU,
COLORS

View File

@ -127,8 +127,8 @@ public class DisplayFiltersFragment extends Fragment implements OnFilterActionIn
CheckBox context_whole_word = dialogView.findViewById(R.id.context_whole_word);
CheckBox context_drop = dialogView.findViewById(R.id.context_drop);
Spinner filter_expire = dialogView.findViewById(R.id.filter_expire);
ArrayAdapter<CharSequence> adapterResize = ArrayAdapter.createFromResource(Objects.requireNonNull(getContext()),
R.array.filter_expire, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> adapterResize = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()),
R.array.filter_expire, android.R.layout.simple_spinner_dropdown_item);
filter_expire.setAdapter(adapterResize);
final int[] expire = {-1};
filter_expire.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

View File

@ -24,6 +24,7 @@ import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@ -31,15 +32,23 @@ import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.util.FixedPreloadSizeProvider;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import app.fedilab.android.R;
@ -49,6 +58,7 @@ import app.fedilab.android.asynctasks.RetrieveNotificationsAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Attachment;
import app.fedilab.android.client.Entities.Notification;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.drawers.NotificationsListAdapter;
@ -117,6 +127,13 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve
}
RelativeLayout main_timeline_container;
lv_notifications = rootView.findViewById(R.id.lv_notifications);
ListPreloader.PreloadSizeProvider sizeProvider =
new FixedPreloadSizeProvider(640, 480);
ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider();
RecyclerViewPreloader<ContactsContract.CommonDataKinds.Photo> preloader =
new RecyclerViewPreloader<>(
Glide.with(context), modelProvider, sizeProvider, 20 );
lv_notifications.addOnScrollListener(preloader);
mainLoader = rootView.findViewById(R.id.loader);
nextElementLoader = rootView.findViewById(R.id.loading_next_notifications);
textviewNoAction = rootView.findViewById(R.id.no_action);
@ -500,6 +517,31 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve
}
}
private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider<String> {
@Override
@NonNull
public List<String> getPreloadItems(int position) {
Status status = notifications.get(position).getStatus();
if (status == null || status.getMedia_attachments() == null || status.getMedia_attachments().size() ==0) {
return Collections.emptyList();
}
List<String> preloaded_urls = new ArrayList<>();
for(Attachment attachment: status.getMedia_attachments()) {
preloaded_urls.add(attachment.getPreview_url());
}
return preloaded_urls;
}
@Nullable
@Override
public RequestBuilder<?> getPreloadRequestBuilder(@NonNull String url) {
return Glide.with(context)
.load(url)
.override(640, 480);
}
}
public enum Type {
ALL,

View File

@ -27,11 +27,13 @@ import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
@ -40,7 +42,6 @@ import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jaredrummler.materialspinner.MaterialSpinner;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.ServerResponse;
@ -55,6 +56,7 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import app.fedilab.android.R;
import app.fedilab.android.activities.MainActivity;
@ -89,8 +91,8 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi
private RelativeLayout textviewNoAction;
private HashMap<Integer, String> privacyToSend;
private HashMap<String, String> channelToSend;
private MaterialSpinner set_upload_channel;
private MaterialSpinner set_upload_privacy;
private Spinner set_upload_channel;
private Spinner set_upload_privacy;
private HashMap<String, String> channels;
@Override
@ -394,7 +396,7 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi
channelToSend = new HashMap<>();
channelToSend.put(channelName[0], channelId[0]);
ArrayAdapter<String> adapterChannel = new ArrayAdapter<>(context,
ArrayAdapter<String> adapterChannel = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_dropdown_item, channelName);
set_upload_channel.setAdapter(adapterChannel);
@ -421,14 +423,14 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi
i++;
}
ArrayAdapter<String> adapterPrivacies = new ArrayAdapter<>(context,
ArrayAdapter<String> adapterPrivacies = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_dropdown_item, privaciesA);
set_upload_privacy.setAdapter(adapterPrivacies);
//Manage privacies
set_upload_privacy.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
set_upload_privacy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Iterator it = privaciesCheck.entrySet().iterator();
int i = 0;
@ -443,11 +445,16 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi
i++;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Manage languages
set_upload_channel.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
set_upload_channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<String, String> channelsCheck = new LinkedHashMap<>(channels);
Iterator it = channelsCheck.entrySet().iterator();
int i = 0;
@ -462,6 +469,11 @@ public class DisplayPlaylistsFragment extends Fragment implements OnPlaylistActi
i++;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

View File

@ -20,15 +20,17 @@ import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@ -36,7 +38,8 @@ import app.fedilab.android.R;
import app.fedilab.android.asynctasks.RetrieveSearchAsyncTask;
import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.drawers.SearchTagsAdapter;
import app.fedilab.android.client.Entities.Trends;
import app.fedilab.android.drawers.TrendsAdapter;
import app.fedilab.android.interfaces.OnRetrieveSearchInterface;
import es.dmoral.toasty.Toasty;
@ -49,14 +52,13 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
private Context context;
private SearchTagsAdapter searchTagsAdapter;
private List<String> tags;
private TrendsAdapter trendsAdapter;
private List<Trends> tags;
private String search;
private RecyclerView lv_search_tags;
private ListView lv_search_tags;
private RelativeLayout loader;
private RelativeLayout textviewNoAction;
private RelativeLayout loading_next_tags;
private LinearLayoutManager mLayoutManager;
private boolean flag_loading;
private SwipeRefreshLayout swipeRefreshLayout;
private String max_id;
@ -88,8 +90,6 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
Toasty.error(context, getString(R.string.toast_error_search), Toast.LENGTH_LONG).show();
}
mLayoutManager = new LinearLayoutManager(context);
lv_search_tags.setLayoutManager(mLayoutManager);
int c1 = getResources().getColor(R.color.cyanea_accent);
int c2 = getResources().getColor(R.color.cyanea_primary_dark);
int c3 = getResources().getColor(R.color.cyanea_primary);
@ -100,36 +100,37 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
int size = tags.size();
tags.clear();
tags = new ArrayList<>();
max_id = "0";
searchTagsAdapter.notifyItemRangeRemoved(0, size);
trendsAdapter.notifyDataSetChanged();
if (search != null) {
new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, null, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
});
lv_search_tags.addOnScrollListener(new RecyclerView.OnScrollListener() {
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (dy > 0) {
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) {
if (!flag_loading) {
flag_loading = true;
if (search != null) {
new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, max_id, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
loading_next_tags.setVisibility(View.VISIBLE);
lv_search_tags.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount && context != null) {
if (!flag_loading) {
flag_loading = true;
if (search != null) {
new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, max_id, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
} else {
loading_next_tags.setVisibility(View.GONE);
loading_next_tags.setVisibility(View.VISIBLE);
}
} else {
loading_next_tags.setVisibility(View.GONE);
}
}
});
if (search != null) {
new RetrieveSearchAsyncTask(context, search, API.searchType.TAGS, null, DisplaySearchTagsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@ -138,8 +139,8 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
public void scrollToTop() {
if (lv_search_tags != null && searchTagsAdapter != null) {
lv_search_tags.setAdapter(searchTagsAdapter);
if (lv_search_tags != null && trendsAdapter != null) {
lv_search_tags.setAdapter(trendsAdapter);
}
}
@ -158,7 +159,7 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
}
@Override
public void onAttach(Context context) {
public void onAttach(@NotNull Context context) {
super.onAttach(context);
this.context = context;
}
@ -167,7 +168,7 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
@Override
public void onRetrieveSearch(APIResponse apiResponse) {
searchTagsAdapter = new SearchTagsAdapter(tags);
trendsAdapter = new TrendsAdapter(context, tags);
loader.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
if (apiResponse.getError() != null) {
@ -185,14 +186,14 @@ public class DisplaySearchTagsFragment extends Fragment implements OnRetrieveSea
max_id = "0";
max_id = String.valueOf(Integer.valueOf(max_id) + 20);
lv_search_tags.setVisibility(View.VISIBLE);
List<String> newTags = new ArrayList<>();
List<Trends> newTags = new ArrayList<>();
if (apiResponse.getResults() != null) {
newTags = apiResponse.getResults().getHashtags();
newTags = apiResponse.getResults().getTrends();
}
tags.addAll(newTags);
SearchTagsAdapter searchTagsAdapter = new SearchTagsAdapter(tags);
lv_search_tags.setAdapter(searchTagsAdapter);
searchTagsAdapter.notifyDataSetChanged();
TrendsAdapter trendsAdapter = new TrendsAdapter(context, tags);
lv_search_tags.setAdapter(trendsAdapter);
trendsAdapter.notifyDataSetChanged();
if (newTags.size() == 0 && tags.size() == 0)
textviewNoAction.setVisibility(View.VISIBLE);
else

View File

@ -25,6 +25,7 @@ import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@ -34,13 +35,21 @@ import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.util.FixedPreloadSizeProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@ -56,6 +65,7 @@ import app.fedilab.android.asynctasks.RetrievePeertubeSearchAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Attachment;
import app.fedilab.android.client.Entities.Conversation;
import app.fedilab.android.client.Entities.Peertube;
import app.fedilab.android.client.Entities.RemoteInstance;
@ -130,6 +140,35 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
public DisplayStatusFragment() {
}
private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider<String> {
@Override
@NonNull
public List<String> getPreloadItems(int position) {
if( statuses == null || statuses.size() == 0){
return Collections.emptyList();
}
Status status = statuses.get(position);
if (status.getMedia_attachments() == null || status.getMedia_attachments().size() ==0) {
return Collections.emptyList();
}
List<String> preloaded_urls = new ArrayList<>();
for(Attachment attachment: status.getMedia_attachments()) {
preloaded_urls.add(attachment.getPreview_url());
}
return preloaded_urls;
}
@Nullable
@Override
public RequestBuilder<?> getPreloadRequestBuilder(@NonNull String url) {
return Glide.with(context)
.load(url)
.override(640, 480);
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_status, container, false);
@ -189,6 +228,13 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
c1, c2, c1
);
lv_status = rootView.findViewById(R.id.lv_status);
ListPreloader.PreloadSizeProvider sizeProvider =
new FixedPreloadSizeProvider(640, 480);
ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider();
RecyclerViewPreloader<ContactsContract.CommonDataKinds.Photo> preloader =
new RecyclerViewPreloader<>(
Glide.with(context), modelProvider, sizeProvider, 20 );
lv_status.addOnScrollListener(preloader);
mainLoader = rootView.findViewById(R.id.loader);
nextElementLoader = rootView.findViewById(R.id.loading_next_status);
textviewNoAction = rootView.findViewById(R.id.no_action);
@ -206,7 +252,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
lastReadToot = sharedpreferences.getString(Helper.LAST_READ_TOOT_ID + userId + instance, null);
lastReadTootDate = Helper.stringToDate(context, sharedpreferences.getString(Helper.LAST_READ_TOOT_DATE + userId + instance, null));
}
if (instanceType == null || instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU")) {
if (instanceType == null || instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU") || instanceType.equals("NITTER")) {
if (type == RetrieveFeedsAsyncTask.Type.TAG && tag != null) {
BaseMainActivity.displayPeertube = null;
List<TagTimeline> tagTimelines = new SearchDAO(context, db).getTimelineInfo(tag);
@ -217,7 +263,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
}
} else {
BaseMainActivity.displayPeertube = null;
statusListAdapter = new StatusListAdapter(type, targetedId, isOnWifi, this.statuses);
statusListAdapter = new StatusListAdapter(instanceType, type, targetedId, isOnWifi, this.statuses);
lv_status.setAdapter(statusListAdapter);
}
} else if (instanceType.equals("PEERTUBE")) {
@ -257,7 +303,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
Status status = b.getParcelable("status");
String delete_statuses_from = b.getString("delete_statuses_for_id", null);
if (status != null && statusListAdapter != null) {
statusListAdapter.notifyStatusWithActionChanged(status);
statusListAdapter.notifyStatusChanged(status);
} else if (delete_statuses_from != null) {
List<Status> statusesToRemove = new ArrayList<>();
for (Status status_temp : statuses) {
@ -580,7 +626,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
}
//Let's deal with statuses
if (statuses != null && statuses.size() > 0) {
if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) {
if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("NITTER") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))) {
this.statuses.addAll(statuses);
statusListAdapter.notifyItemRangeInserted(previousPosition, statuses.size());
} else if (artListAdapter != null && instanceType.equals("ART")) {
@ -736,7 +782,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
if (type == RetrieveFeedsAsyncTask.Type.HOME || type == RetrieveFeedsAsyncTask.Type.PF_HOME)
asyncTask = new RetrieveFeedsAfterBookmarkAsyncTask(context, null, false, DisplayStatusFragment.this).execute();
if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE)
if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && (instanceType == null || instanceType.compareTo("NITTER") != 0))
asyncTask = new RetrieveMissingFeedsAsyncTask(context, remoteInstance, sinceId, type, DisplayStatusFragment.this).execute();
else if (type == RetrieveFeedsAsyncTask.Type.TAG)
asyncTask = new RetrieveMissingFeedsAsyncTask(context, tag, sinceId, type, DisplayStatusFragment.this).execute();
@ -831,15 +877,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
public void scrollToTop() {
if (lv_status != null && instanceType != null) {
if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU")))
lv_status.setAdapter(statusListAdapter);
else if (pixelfedListAdapter != null && instanceType.equals("PIXELFED"))
lv_status.setAdapter(pixelfedListAdapter);
else if (artListAdapter != null && instanceType.equals("ART"))
lv_status.setAdapter(artListAdapter);
else if (peertubeAdapater != null && instanceType.equals("PEERTUBE"))
lv_status.setAdapter(peertubeAdapater);
if( mLayoutManager != null ) {
mLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
@ -870,6 +909,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
switch (instanceType) {
case "MASTODON":
case "MISSKEY":
case "NITTER":
case "GNU":
statusListAdapter.notifyItemRangeChanged(0, this.statuses.size());
break;
@ -899,7 +939,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
Status status = it.next();
for (Status status1 : statuses) {
if (status.getConversationId() != null && status.getConversationId().equals(status1.getConversationId())) {
if (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU"))
if (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("NITTER")|| instanceType.equals("GNU"))
statusListAdapter.notifyItemRemoved(position);
else if (instanceType.equals("PIXELFED"))
pixelfedListAdapter.notifyItemRemoved(position);
@ -938,7 +978,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
}
}
}
if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("GNU")))
if (statusListAdapter != null && (instanceType.equals("MASTODON") || instanceType.equals("MISSKEY") || instanceType.equals("NITTER") || instanceType.equals("GNU")))
statusListAdapter.notifyItemRangeInserted(0, inserted);
else if (pixelfedListAdapter != null && instanceType.equals("PIXELFED"))
pixelfedListAdapter.notifyItemRangeInserted(0, inserted);
@ -1083,7 +1124,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
if (context instanceof BaseMainActivity) {
boolean remember_position_home = sharedpreferences.getBoolean(Helper.SET_REMEMBER_POSITION_HOME, true);
if (remember_position_home)
asyncTask = new RetrieveFeedsAsyncTask(context, type, initialBookMark, DisplayStatusFragment.this).execute();
asyncTask = new RetrieveFeedsAsyncTask(context, type, initialBookMark, true,DisplayStatusFragment.this).execute();
else
asyncTask = new RetrieveFeedsAsyncTask(context, type, null, DisplayStatusFragment.this).execute();
}
@ -1165,6 +1206,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
switch (instanceType) {
case "MASTODON":
case "MISSKEY":
case "NITTER":
case "GNU":
statusListAdapter.notifyItemRangeRemoved(0, lenght);
break;

View File

@ -294,6 +294,10 @@ public class MediaSliderFragment extends Fragment implements MediaPlayer.OnCompl
webview_video.setWebChromeClient(mastalabWebChromeClient);
webview_video.getSettings().setDomStorageEnabled(true);
webview_video.getSettings().setAppCacheEnabled(true);
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if( user_agent != null) {
webview_video.getSettings().setUserAgentString(user_agent);
}
webview_video.getSettings().setMediaPlaybackRequiresUserGesture(false);
webview_video.setWebViewClient(new MastalabWebViewClient((Activity) context));
webview_video.loadUrl(attachment.getUrl());

View File

@ -28,6 +28,8 @@ import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import java.util.Objects;
import app.fedilab.android.R;
import app.fedilab.android.helper.Helper;
@ -56,8 +58,8 @@ public class SettingsPeertubeFragment extends Fragment {
//Video mode
final Spinner video_mode_spinner = rootView.findViewById(R.id.set_video_mode);
ArrayAdapter<CharSequence> video_mode_spinnerAdapter = ArrayAdapter.createFromResource(getContext(),
R.array.settings_video_mode, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> video_mode_spinnerAdapter = ArrayAdapter.createFromResource(Objects.requireNonNull(getActivity()),
R.array.settings_video_mode, android.R.layout.simple_spinner_dropdown_item);
video_mode_spinner.setAdapter(video_mode_spinnerAdapter);
if (videoMode == Helper.VIDEO_MODE_TORRENT)
videoMode = Helper.VIDEO_MODE_DIRECT;

Some files were not shown because too many files have changed in this diff Show More