Merge branch 'develop' into lite_version

# Conflicts:
#	app/build.gradle
This commit is contained in:
Thomas 2020-07-12 17:58:39 +02:00
commit d7697a0458
300 changed files with 12157 additions and 9179 deletions

View File

@ -6,8 +6,8 @@ android {
defaultConfig {
minSdkVersion 19
targetSdkVersion 29
versionCode 366
versionName "2.35.3"
versionCode 376
versionName "2.36.2"
multiDexEnabled true
renderscriptTargetApi 28 as int
renderscriptSupportModeEnabled true
@ -96,7 +96,7 @@ dependencies {
annotationProcessor 'com.android.support:support-annotations:28.0.0'
implementation "com.evernote:android-job:1.2.6"
implementation "com.google.code.gson:gson:2.8.5"
implementation "com.google.code.gson:gson:2.8.6"
implementation "com.google.guava:guava:28.2-android"
implementation "com.github.chrisbanes:PhotoView:2.3.0"
implementation 'com.r0adkll:slidableactivity:2.1.0'

View File

@ -69,6 +69,11 @@
android:name="app.fedilab.android.services.BackupNotificationInDataBaseService"
android:exported="false" />
<receiver android:name=".services.UpgradeReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<receiver
android:name="app.fedilab.android.services.RestartLiveNotificationReceiver"
android:exported="false">
@ -111,6 +116,7 @@
android:name="app.fedilab.android.activities.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTask"
android:theme="@style/AppThemeDark_NoActionBar"
android:windowSoftInputMode="adjustResize">
<intent-filter>
@ -526,5 +532,6 @@
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>

View File

@ -1,12 +0,0 @@
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

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

View File

@ -1,14 +0,0 @@
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

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

View File

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

View File

@ -1,13 +0,0 @@
Added
- Pixelfed: post media to stories
- Long press bio to open the contextual menu
- Allow to invite with Pleroma
Changed
- Import theme always visible
- Improve login activity
Fixed
- Filter with regex
- Issues with talk back and magnifying glass
- Some crashes

View File

@ -1,5 +0,0 @@
Fixed:
- Mentions with delete & re-draft for Pleroma accounts
- Nitter timelines with refresh
- Remove notification bar for Android 8-
- Fix "No Internet connection" error on some instances when posting

View File

@ -1,13 +0,0 @@
Added:
- Català language
- Push notifications for Friendica & GNU Social
- Add follow/unfollow buttons for Pixelfed
- View your own story (need to wait the endpoint)
- Increase max bio chars to 500 for Pleroma
Fixed:
- Proxy not applied with embedded videos
- Fix no toots that remains displayed on Nitter timelines
- Avoid to lose composed message when not sent
- Notifications not pushed
- Fix some crashes

View File

@ -1,7 +0,0 @@
Added:
- Text selectable for fields in profiles
Fixed:
- Fix the scrolling issue in timelines
- Peertube videos crashes
- Color of the compose menu for the light theme

View File

@ -1,9 +0,0 @@
Added:
- Announcements for Mastodon with reactions
- Pleroma: reactions in posts
Changed:
- Filters changed to speed-up the scroll
Fixed:
- Custom emojis not displayed in compose activity

View File

@ -1,14 +0,0 @@
Added:
- Allow to edit searches
Changed:
- Move the favourite item in menu
Fixed:
- Filters not working
- Crash when sharing http URLs
- Missing ogg image when sharing
- Extra space with quick replies
- Crash when doing searches
- Fix crash when clicking on conversations
- Fix crash when editing profile

View File

@ -1,4 +0,0 @@
Fixed:
- Crash due to a library update
- Missing animate profile pictures
- Fix some color issues

View File

@ -1,9 +0,0 @@
Changed:
- Improve memory management
- Improve scroll
- One logout entry in the menu (it will remove the account from the app)
- Clear push notifications when visiting notifications tab
Fixed:
- Long press to store media download the preview image
- Fix pagination with Nitter timelines

View File

@ -1,11 +0,0 @@
Changed:
- Improve memory management
- Improve scroll
- Poll layouts cleaner
- One logout entry in the menu (it will remove the account from the app)
- Clear push notifications when visiting notifications tab
Fixed:
- Long press to store media download the preview image
- Fix pagination with Nitter timelines
- Avatars not displayed for Peertube

View File

@ -1,8 +0,0 @@
Added:
- Gif support for some keyboards.
- Support animated emoji for reactions
Fixed:
- Crash when playing Youtube videos in timelines
- Announcements not displayed
- A crash due to recent changes

View File

@ -1,9 +0,0 @@
Added:
- Gif support for some keyboards.
- Support animated emoji for reactions
Fixed:
- Crash when playing Youtube videos in timelines
- Announcements not displayed
- A crash due to recent changes
- +Fix a crash due to polls

View File

@ -1,3 +0,0 @@
Fixed:
- Empty content for Friendica/GNU accounts
- Username can't be changed in profile

View File

@ -1,4 +0,0 @@
Fixed:
- Lot of crashes 🥺🥺😱
- Push notifications not working
- Some issues with filters

View File

@ -0,0 +1,13 @@
Added:
- 100 Mb of cache for videos (can be changed in settings)
- Bibliogram support (default: disabled)
- Ouiches support for audio
Changed:
- Closing media
- Smoother settings
Fixed:
- Peertube comments
- Some layout issues
- Some other crashes

View File

@ -0,0 +1,13 @@
Added:
- 100 Mb of cache for videos (can be changed in settings)
- Bibliogram support (default: disabled)
- Ouiches support for audio
Changed:
- Closing media
- Smoother settings
Fixed:
- Peertube comments
- Some layout issues
- Some other crashes

View File

@ -0,0 +1,10 @@
Added:
- Silesian localization
Changed:
- Add Silesian in language picker
Fixed:
- Some URLs not clickable
- Empty home timeline
- Some crashes when scrolling

View File

@ -0,0 +1,11 @@
Added:
- Silesian localization
Changed:
- Add Silesian in language picker
Fixed:
- Some URLs not clickable
- Empty home timeline
- Some crashes when scrolling
- Question mark bug

View File

@ -0,0 +1,6 @@
Added:
- Automatically add hashtag to messages when composing from a search
Fixed:
- Some issues with content and URLs
- Some crashes

View File

@ -0,0 +1,4 @@
Fixed:
- Issue with not clickable URLs
- Custom emoji in polls not displayed
- Auto-split toots feature

View File

@ -0,0 +1,18 @@
Added:
- Select text for media description
changed:
- Increase media description length to 1500 chars
- More details about accounts in notifications
- Media management in timelines
- Allow cross-account replies on followed instances
Fixed:
- Remove extra spaces at the bottom of messages
- Some issue with custom emoji
- Fix issue with "Your toots/notifications"
- Fix issue with CW and Pixelfed
- Fix some media not loaded in profiles
- Scheduled toots from server side have an incorrect date
- Incorrect feeds when checking instance admin account
- Some crashes

View File

@ -0,0 +1,19 @@
Added:
- Select text for media description
changed:
- Increase media description length to 1500 chars
- More details about accounts in notifications
- Media management in timelines
- Allow cross-account replies on followed instances
Fixed:
- Crash when adding media
- Remove extra spaces at the bottom of messages
- Some issue with custom emoji
- Fix issue with "Your toots/notifications"
- Fix issue with CW and Pixelfed
- Fix some media not loaded in profiles
- Scheduled toots from server side have an incorrect date
- Incorrect feeds when checking instance admin account
- Some crashes

View File

@ -0,0 +1,20 @@
Added:
- Select text for media description
changed:
- Increase media description length to 1500 chars
- More details about accounts in notifications
- Media management in timelines
- Allow cross-account replies on followed instances
Fixed:
- Crash when having custom emoji in display name
- Crash when adding media
- Remove extra spaces at the bottom of messages
- Some issue with custom emoji
- Fix issue with "Your toots/notifications"
- Fix issue with CW and Pixelfed
- Fix some media not loaded in profiles
- Scheduled toots from server side have an incorrect date
- Incorrect feeds when checking instance admin account
- Some crashes

View File

@ -0,0 +1,2 @@
Fixed:
- Crash when adding media (Pixelfed/Mastodon)

View File

@ -15,8 +15,8 @@ package app.fedilab.android.activities;
* see <http://www.gnu.org/licenses>. */
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
@ -34,6 +34,7 @@ import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.Group;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
@ -175,8 +176,18 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
public void onAdminAction(APIResponse apiResponse) {
if (apiResponse.getError() != null) {
if (apiResponse.getError().getStatusCode() == 403) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
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;
}
AlertDialog.Builder builderInner;
builderInner = new AlertDialog.Builder(AccountReportActivity.this, R.style.AppThemeDark);
builderInner = new AlertDialog.Builder(AccountReportActivity.this, style);
builderInner.setTitle(R.string.reconnect_account);
builderInner.setMessage(R.string.reconnect_account_message);
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());

View File

@ -5,10 +5,11 @@ import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.ActionMode;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import androidx.annotation.NonNull;
@ -25,7 +26,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.Timer;
import app.fedilab.android.BuildConfig;
import app.fedilab.android.helper.Helper;
import es.dmoral.toasty.Toasty;
@ -52,7 +52,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()
@ -67,8 +67,11 @@ public class BaseActivity extends CyaneaAppCompatActivity {
.penaltyLog()
// .penaltyDeath()
.build());
}
}*/
canShowActionMode = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
}
super.onCreate(savedInstanceState);
}

View File

@ -0,0 +1,26 @@
package app.fedilab.android.activities;
import android.annotation.SuppressLint;
import androidx.appcompat.app.AppCompatActivity;
import com.vanniktech.emoji.EmojiManager;
import com.vanniktech.emoji.one.EmojiOneProvider;
import app.fedilab.android.helper.Helper;
/**
* Created by Thomas on 16/05/2020.
* Fragment base activity which updates security provider
*/
@SuppressLint("Registered")
public class BaseFragmentActivity extends AppCompatActivity {
static {
Helper.installProvider();
EmojiManager.install(new EmojiOneProvider());
}
}

View File

@ -986,8 +986,8 @@ public abstract class BaseMainActivity extends BaseActivity
SeekBar set_icon_size = popup_quick_settings.findViewById(R.id.set_icon_size);
final TextView set_text_size_value = popup_quick_settings.findViewById(R.id.set_text_size_value);
final TextView set_icon_size_value = popup_quick_settings.findViewById(R.id.set_icon_size_value);
set_text_size_value.setText(String.format("%s%%", String.valueOf(textSize)));
set_icon_size_value.setText(String.format("%s%%", String.valueOf(iconSize)));
set_text_size_value.setText(String.format("%s%%", textSize));
set_icon_size_value.setText(String.format("%s%%", iconSize));
set_text_size.setMax(20);
set_icon_size.setMax(20);
@ -1008,7 +1008,7 @@ public abstract class BaseMainActivity extends BaseActivity
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int value = 80 + progress * 5;
set_text_size_value.setText(String.format("%s%%", String.valueOf(value)));
set_text_size_value.setText(String.format("%s%%", value));
SharedPreferences.Editor editor = sharedpreferences1.edit();
editor.putInt(Helper.SET_TEXT_SIZE, value);
editor.apply();
@ -1026,7 +1026,7 @@ public abstract class BaseMainActivity extends BaseActivity
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int value = 80 + progress * 5;
set_icon_size_value.setText(String.format("%s%%", String.valueOf(value)));
set_icon_size_value.setText(String.format("%s%%", value));
SharedPreferences.Editor editor = sharedpreferences1.edit();
editor.putInt(Helper.SET_ICON_SIZE, value);
editor.apply();
@ -1258,7 +1258,7 @@ public abstract class BaseMainActivity extends BaseActivity
int lastReleaseNoteRead = sharedpreferences.getInt(Helper.SET_POPUP_RELEASE_NOTES, 0);
int versionCode = BuildConfig.VERSION_CODE;
if (lastReleaseNoteRead != versionCode ) { //Need to push release notes
if (lastReleaseNoteRead != versionCode) { //Need to push release notes
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, BaseMainActivity.this).execute();
}
@ -1279,12 +1279,12 @@ public abstract class BaseMainActivity extends BaseActivity
Button liberapay_support = dialogReleaseNoteView.findViewById(R.id.liberapay_support);
release_title.setText(getString(R.string.release_note_title, BuildConfig.VERSION_NAME));
release_notes.setText(finalContent);
if( BuildConfig.DONATIONS) {
if (BuildConfig.DONATIONS) {
liberapay_support.setVisibility(View.VISIBLE);
}else{
} else {
liberapay_support.setVisibility(View.GONE);
}
liberapay_support.setOnClickListener(v->{
liberapay_support.setOnClickListener(v -> {
Intent intentLiberapay = new Intent(Intent.ACTION_VIEW);
intentLiberapay.setData(Uri.parse("https://liberapay.com/tom79"));
try {
@ -1503,9 +1503,9 @@ public abstract class BaseMainActivity extends BaseActivity
}
} else if (type.startsWith("image/") || type.startsWith("video/")) {
Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (!TootActivity.active) {
Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
Bundle b = new Bundle();
b.putParcelable("sharedUri", imageUri);
@ -1513,7 +1513,6 @@ public abstract class BaseMainActivity extends BaseActivity
CrossActions.doCrossShare(BaseMainActivity.this, b);
}
} else {
Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
intent = new Intent(BaseMainActivity.this, TootActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
@ -1693,7 +1692,7 @@ public abstract class BaseMainActivity extends BaseActivity
}
});
}
if( trackingDomains != null){
if (trackingDomains != null) {
trackingDomains = null;
}
if (hidde_menu != null)
@ -2381,7 +2380,13 @@ public abstract class BaseMainActivity extends BaseActivity
}
}
final NavigationView navigationView = findViewById(R.id.nav_view);
if (navigationView == null) {
return;
}
MenuItem item = navigationView.getMenu().findItem(R.id.nav_announcements);
if (item == null || item.getActionView() == null) {
return;
}
TextView actionView = item.getActionView().findViewById(R.id.counter);
if (actionView != null) {
if (unread > 0) {

View File

@ -32,6 +32,8 @@ import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
@ -42,6 +44,7 @@ import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.StatusDrawerParams;
import app.fedilab.android.client.Entities.StoredStatus;
import app.fedilab.android.drawers.StatusListAdapter;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnRetrieveFeedsInterface;
@ -112,6 +115,21 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
swipeRefreshLayout.setColorSchemeColors(
c1, c2, c1
);
FloatingActionButton toot = findViewById(R.id.toot);
toot.setOnClickListener(v -> {
Intent intentToot = new Intent(HashTagActivity.this, TootActivity.class);
Bundle val = new Bundle();
StoredStatus storedStatus = new StoredStatus();
Status tagStatus = new Status();
tagStatus.setVisibility("public");
tagStatus.setContent(HashTagActivity.this, String.format("#%s ", tag));
storedStatus.setStatus(tagStatus);
val.putParcelable("storedStatus", storedStatus);
intentToot.putExtras(val);
startActivity(intentToot);
});
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);

View File

@ -122,7 +122,7 @@ public class InstanceProfileActivity extends BaseActivity {
finish();
return;
}
if (instanceNodeInfo.getThumbnail() != null && !instanceNodeInfo.getThumbnail().equals("null"))
if (instanceNodeInfo.getThumbnail() != null && !instanceNodeInfo.getThumbnail().equals("null") && Helper.isValidContextForGlide(InstanceProfileActivity.this))
Glide.with(InstanceProfileActivity.this)
.asBitmap()
.load(instanceNodeInfo.getThumbnail())
@ -149,7 +149,7 @@ public class InstanceProfileActivity extends BaseActivity {
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);
AccountsListAdapter accountsListAdapter = new AccountsListAdapter(RetrieveAccountsAsyncTask.Type.FOLLOWERS, userId, true, accounts);
lv_accounts.setAdapter(accountsListAdapter);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(InstanceProfileActivity.this);

View File

@ -248,6 +248,9 @@ public class LoginActivity extends BaseActivity {
return;
}
instance = login_instance.getText().toString().trim().toLowerCase();
if(instance.length() == 0) {
return;
}
connect_button.setEnabled(false);
new Thread(() -> {
instanceNodeInfo = new API(LoginActivity.this).displayNodeInfo(instance);
@ -593,7 +596,12 @@ public class LoginActivity extends BaseActivity {
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token);
editor.apply();
//Update the account with the token;
new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
if (instance != null) {
new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
connectionButton.setEnabled(true);
Toasty.error(LoginActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}

View File

@ -15,6 +15,7 @@
package app.fedilab.android.activities;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
@ -174,6 +175,11 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
dateEnd = new StatusCacheDAO(OwnerChartsActivity.this, db).getGreaterDate(StatusCacheDAO.ARCHIVE_CACHE);
if (dateIni == null) {
dateIni = new Date();
dateEnd = new Date();
}
int style;
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
@ -264,26 +270,26 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
public void onCharts(Charts charts) {
List<Entry> boostsEntry = new ArrayList<>();
Iterator it = charts.getBoosts().entrySet().iterator();
Iterator<Map.Entry<Long, Integer>> it = charts.getBoosts().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
boostsEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
boostsEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
List<Entry> repliesEntry = new ArrayList<>();
it = charts.getReplies().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
repliesEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
repliesEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
List<Entry> statusesEntry = new ArrayList<>();
it = charts.getStatuses().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
statusesEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
statusesEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
@ -389,6 +395,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
chart.invalidate();
}
@SuppressLint("ViewConstructor")
public static class CustomMarkerView extends MarkerView {
private TextView tvContent;
private MPPointF mOffset;
@ -410,7 +417,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
@Override
public MPPointF getOffset() {
if (mOffset == null) {
mOffset = new MPPointF(-(getWidth() / 2), -getHeight());
mOffset = new MPPointF(-((float) getWidth() / 2), -getHeight());
}
return mOffset;
}

View File

@ -15,6 +15,7 @@
package app.fedilab.android.activities;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
@ -260,27 +261,26 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
List<Entry> boostsEntry = new ArrayList<>();
Iterator it = charts.getReblogs().entrySet().iterator();
Iterator<Map.Entry<Long, Integer>> it = charts.getReblogs().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
boostsEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
boostsEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
List<Entry> favEntry = new ArrayList<>();
it = charts.getFavourites().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
favEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
favEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
List<Entry> mentionEntry = new ArrayList<>();
it = charts.getMentions().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
mentionEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
mentionEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
@ -288,8 +288,8 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
List<Entry> followEntry = new ArrayList<>();
it = charts.getFollows().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
followEntry.add(new Entry((long) pair.getKey(), (int) pair.getValue()));
Map.Entry<Long, Integer> pair = it.next();
followEntry.add(new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
@ -482,6 +482,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
super.onDestroy();
}
@SuppressLint("ViewConstructor")
public static class CustomMarkerView extends MarkerView {
private TextView tvContent;
private MPPointF mOffset;
@ -503,7 +504,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
@Override
public MPPointF getOffset() {
if (mOffset == null) {
mOffset = new MPPointF(-(getWidth() / 2), -getHeight());
mOffset = new MPPointF(-((float) getWidth() / 2), -getHeight());
}
return mOffset;
}

View File

@ -522,11 +522,11 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
frequency.setText(getString(R.string.toot_per_day, df.format(statistics.getFrequency())));
if (statistics.getTagsTrend() != null && statistics.getTagsTrend().size() > 0) {
Iterator it = statistics.getTagsTrend().entrySet().iterator();
Iterator<Map.Entry<String, Integer>> it = statistics.getTagsTrend().entrySet().iterator();
StringBuilder text = new StringBuilder();
int i = 1;
while (it.hasNext() && i <= 10) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, Integer> pair = it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
text.append(i).append(" - ").append(pair.getKey()).append("").append(pair.getValue()).append("\r\n");
i++;

View File

@ -60,10 +60,10 @@ import androidx.recyclerview.widget.RecyclerView;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlaybackControlView;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
@ -96,6 +96,7 @@ import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.StatusDrawerParams;
import app.fedilab.android.client.TLSSocketFactory;
import app.fedilab.android.drawers.StatusListAdapter;
import app.fedilab.android.helper.CacheDataSourceFactory;
import app.fedilab.android.helper.CrossActions;
import app.fedilab.android.helper.FullScreenMediaController;
import app.fedilab.android.helper.Helper;
@ -130,7 +131,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
private ScrollView peertube_information_container;
private Peertube peertube;
private TextView toolbar_title;
private SimpleExoPlayerView playerView;
private PlayerView playerView;
private SimpleExoPlayer player;
private boolean fullScreenMode;
private Dialog fullScreenDialog;
@ -278,10 +279,8 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
peertube_information_container.setVisibility(View.VISIBLE);
}
});
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if (user_agent != null) {
webview_video.getSettings().setUserAgentString(user_agent);
}
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT);
webview_video.getSettings().setUserAgentString(user_agent);
webview_video.getSettings().setAllowFileAccess(true);
webview_video.setWebChromeClient(mastalabWebChromeClient);
webview_video.getSettings().setDomStorageEnabled(true);
@ -369,40 +368,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
case R.id.action_comment:
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
Toasty.info(PeertubeActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show();
new AsyncTask<Void, Void, Void>() {
private List<app.fedilab.android.client.Entities.Status> remoteStatuses;
private WeakReference<Context> contextReference = new WeakReference<>(PeertubeActivity.this);
@Override
protected Void doInBackground(Void... voids) {
if (peertube != null) {
APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid());
if (search != null && search.getResults() != null) {
remoteStatuses = search.getResults().getStatuses();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(contextReference.get(), TootActivity.class);
Bundle b = new Bundle();
if (remoteStatuses == null || remoteStatuses.size() == 0) {
Toasty.error(contextReference.get(), getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
return;
}
if (remoteStatuses.get(0).getReblog() != null) {
b.putParcelable("tootReply", remoteStatuses.get(0).getReblog());
} else {
b.putParcelable("tootReply", remoteStatuses.get(0));
}
intent.putExtras(b); //Put your id to your next Intent
contextReference.get().startActivity(intent);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new commentTask(new WeakReference<>(PeertubeActivity.this), peertube).execute();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
if (!peertube.isCommentsEnabled()) {
Toasty.info(PeertubeActivity.this, getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show();
@ -583,16 +549,24 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
if (mode == Helper.VIDEO_MODE_DIRECT) {
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this,
Util.getUserAgent(PeertubeActivity.this, "Mastalab"), null);
ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(apiResponse.getPeertubes().get(0).getFileUrl(null, apiResponse.getPeertubes().get(0).isStreamService())));
String userAgent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT);
int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB);
ProgressiveMediaSource videoSource;
if (video_cache == 0) {
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this,
Util.getUserAgent(PeertubeActivity.this, userAgent), null);
videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(apiResponse.getPeertubes().get(0).getFileUrl(null, apiResponse.getPeertubes().get(0).isStreamService())));
} else {
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(PeertubeActivity.this);
videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
.createMediaSource(Uri.parse(apiResponse.getPeertubes().get(0).getFileUrl(null, apiResponse.getPeertubes().get(0).isStreamService())));
}
player = ExoPlayerFactory.newSimpleInstance(PeertubeActivity.this);
playerView.setPlayer(player);
loader.setVisibility(View.GONE);
player.prepare(videoSource);
player.setPlayWhenReady(true);
}
@ -662,30 +636,21 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
});
}
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mode != Helper.VIDEO_MODE_WEBVIEW) {
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (mode != Helper.VIDEO_MODE_WEBVIEW) {
openFullscreenDialog();
setFullscreen(FullScreenMediaController.fullscreen.ON);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
}
setFullscreen(FullScreenMediaController.fullscreen.ON);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (mode != Helper.VIDEO_MODE_WEBVIEW) {
closeFullscreenDialog();
setFullscreen(FullScreenMediaController.fullscreen.OFF);
}
change();
} else {
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setFullscreen(FullScreenMediaController.fullscreen.ON);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setFullscreen(FullScreenMediaController.fullscreen.OFF);
}
change();
setFullscreen(FullScreenMediaController.fullscreen.OFF);
}
change();
}
@ -745,7 +710,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
}
}
@Override
public void onResume() {
super.onResume();
@ -777,7 +741,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
if (playerView != null) {
loader.setVisibility(View.VISIBLE);
long position = player.getCurrentPosition();
PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller);
PlayerControlView controlView = playerView.findViewById(R.id.exo_controller);
resolution = controlView.findViewById(R.id.resolution);
resolution.setText(String.format("%sp", res));
if (mode == Helper.VIDEO_MODE_DIRECT) {
@ -786,11 +750,19 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
player = ExoPlayerFactory.newSimpleInstance(PeertubeActivity.this);
playerView.setPlayer(player);
loader.setVisibility(View.GONE);
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this,
Util.getUserAgent(PeertubeActivity.this, "Mastalab"), null);
ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(peertube.getFileUrl(res, peertube.isStreamService())));
String userAgent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT);
int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB);
ProgressiveMediaSource videoSource;
if (video_cache == 0) {
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this,
Util.getUserAgent(PeertubeActivity.this, userAgent), null);
videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(peertube.getFileUrl(res, peertube.isStreamService())));
} else {
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(PeertubeActivity.this);
videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
.createMediaSource(Uri.parse(peertube.getFileUrl(res, peertube.isStreamService())));
}
player.prepare(videoSource);
player.seekTo(0, position);
player.setPlayWhenReady(true);
@ -809,7 +781,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
}
private void initFullscreenDialog() {
fullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) {
@ -830,7 +801,6 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
fullScreenDialog.show();
}
private void closeFullscreenDialog() {
((ViewGroup) playerView.getParent()).removeView(playerView);
@ -842,7 +812,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
private void initFullscreenButton() {
PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller);
PlayerControlView controlView = playerView.findViewById(R.id.exo_controller);
fullScreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
View fullScreenButton = controlView.findViewById(R.id.exo_fullscreen_button);
fullScreenButton.setOnClickListener(v -> {
@ -854,13 +824,12 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
}
private void initResolution() {
PlaybackControlView controlView = playerView.findViewById(R.id.exo_controller);
PlayerControlView controlView = playerView.findViewById(R.id.exo_controller);
resolution = controlView.findViewById(R.id.resolution);
resolution.setText(String.format("%sp", peertube.getResolution().get(0)));
resolution.setOnClickListener(v -> displayResolution());
}
private void changeColor() {
if (peertube.getMyRating() != null && peertube.getMyRating().equals("like")) {
changeDrawableColor(PeertubeActivity.this, R.drawable.ic_thumb_up_peertube, R.color.positive_thumbs);
@ -882,4 +851,49 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
playlists = apiResponse.getPlaylists();
}
}
private static class commentTask extends AsyncTask<Void, Void, app.fedilab.android.client.Entities.Status> {
private WeakReference<Context> contextReference;
private Peertube peertube;
commentTask(WeakReference<Context> contextReference, Peertube peertube) {
this.peertube = peertube;
this.contextReference = contextReference;
}
@Override
protected app.fedilab.android.client.Entities.Status doInBackground(Void... voids) {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = null;
if (peertube != null) {
APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid());
if (search != null && search.getResults() != null) {
remoteStatuses = search.getResults().getStatuses();
}
}
if (remoteStatuses != null && remoteStatuses.size() > 0) {
return remoteStatuses.get(0);
} else {
return null;
}
}
@Override
protected void onPostExecute(app.fedilab.android.client.Entities.Status remoteStatuses) {
Intent intent = new Intent(contextReference.get(), TootActivity.class);
Bundle b = new Bundle();
if (remoteStatuses == null) {
Toasty.error(contextReference.get(), contextReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
return;
}
if (remoteStatuses.getReblog() != null) {
b.putParcelable("tootReply", remoteStatuses.getReblog());
} else {
b.putParcelable("tootReply", remoteStatuses);
}
intent.putExtras(b);
contextReference.get().startActivity(intent);
}
}
}

View File

@ -167,12 +167,12 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
translations = new LinkedHashMap<>(peertubeInformation.getTranslations());
//Populate catgories
String[] categoriesA = new String[categories.size()];
Iterator it = categories.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = categories.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
categoriesA[i] = (String) pair.getValue();
categoriesA[i] = pair.getValue();
else
categoriesA[i] = translations.get(pair.getValue());
it.remove();
@ -188,9 +188,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
it = licences.entrySet().iterator();
i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
licensesA[i] = (String) pair.getValue();
licensesA[i] = pair.getValue();
else
licensesA[i] = translations.get(pair.getValue());
it.remove();
@ -203,12 +203,12 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
//Populate languages
String[] languagesA = new String[languages.size()];
it = languages.entrySet().iterator();
Iterator<Map.Entry<String, String>> itl = languages.entrySet().iterator();
i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, String> pair = itl.next();
if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
languagesA[i] = (String) pair.getValue();
languagesA[i] = pair.getValue();
else
languagesA[i] = translations.get(pair.getValue());
it.remove();
@ -224,9 +224,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
it = privacies.entrySet().iterator();
i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
privaciesA[i] = (String) pair.getValue();
privaciesA[i] = pair.getValue();
else
privaciesA[i] = translations.get(pair.getValue());
it.remove();
@ -346,9 +346,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
int languagePosition = 0;
if (languages.containsValue(language)) {
Iterator it = languages.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = languages.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, String> pair = it.next();
if (pair.getValue().equals(language))
break;
it.remove();
@ -357,9 +357,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
}
int privacyPosition = 0;
if (privacy != null && privacies.containsValue(privacy)) {
Iterator it = privacies.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = privacies.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (pair.getValue().equals(privacy))
break;
it.remove();
@ -368,9 +368,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
}
int licensePosition = 0;
if (license != null && licences.containsValue(license)) {
Iterator it = licences.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = licences.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (pair.getValue().equals(license))
break;
it.remove();
@ -379,9 +379,9 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
}
int categoryPosition = 0;
if (category != null && categories.containsValue(category)) {
Iterator it = categories.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = categories.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (pair.getValue().equals(category))
break;
it.remove();
@ -394,13 +394,13 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Iterator it = privaciesCheck.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = privaciesCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (i == position) {
privacyToSend = new HashMap<>();
privacyToSend.put((Integer) pair.getKey(), (String) pair.getValue());
privacyToSend.put(pair.getKey(), pair.getValue());
break;
}
it.remove();
@ -417,13 +417,13 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
@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();
Iterator<Map.Entry<Integer, String>> it = licensesCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (i == position) {
licenseToSend = new HashMap<>();
licenseToSend.put((Integer) pair.getKey(), (String) pair.getValue());
licenseToSend.put(pair.getKey(), pair.getValue());
break;
}
it.remove();
@ -441,13 +441,13 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> categoriesCheck = new LinkedHashMap<>(peertubeInformation.getCategories());
Iterator it = categoriesCheck.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = categoriesCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (i == position) {
categoryToSend = new HashMap<>();
categoryToSend.put((Integer) pair.getKey(), (String) pair.getValue());
categoryToSend.put(pair.getKey(), pair.getValue());
break;
}
it.remove();
@ -466,13 +466,13 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
@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();
Iterator<Map.Entry<String, String>> it = languagesCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, String> pair = it.next();
if (i == position) {
languageToSend = new HashMap<>();
languageToSend.put((String) pair.getKey(), (String) pair.getValue());
languageToSend.put(pair.getKey(), pair.getValue());
break;
}
it.remove();
@ -490,13 +490,13 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<String, String> channelsCheck = new LinkedHashMap<>(channels);
Iterator it = channelsCheck.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = channelsCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, String> pair = it.next();
if (i == position) {
channelToSend = new HashMap<>();
channelToSend.put((String) pair.getKey(), (String) pair.getValue());
channelToSend.put(pair.getKey(), pair.getValue());
break;
}
@ -539,7 +539,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
List<String> tags = peertube.getTags();
if (tags != null && tags.size() > 0) {
String[] tagsA = tags.toArray(new String[tags.size()]);
String[] tagsA = tags.toArray(new String[0]);
p_video_tags.setTags(tagsA);
}
@ -576,12 +576,12 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
int channelPosition = 0;
if (channels.containsKey(channel.getUsername())) {
LinkedHashMap<String, String> channelsIterator = new LinkedHashMap<>(channels);
Iterator it = channelsIterator.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = channelsIterator.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, String> pair = it.next();
if (pair.getKey().equals(channel.getUsername())) {
channelToSend = new HashMap<>();
channelToSend.put((String) pair.getKey(), (String) pair.getValue());
channelToSend.put(pair.getKey(), pair.getValue());
break;
}
it.remove();

View File

@ -16,6 +16,7 @@ package app.fedilab.android.activities;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
@ -235,12 +236,12 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
LinkedHashMap<Integer, String> privacies = new LinkedHashMap<>(peertubeInformation.getPrivacies());
//Populate privacies
String[] privaciesA = new String[privacies.size()];
Iterator it = privacies.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = privacies.entrySet().iterator();
i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
privaciesA[i] = (String) pair.getValue();
privaciesA[i] = pair.getValue();
else
privaciesA[i] = translations.get(pair.getValue());
it.remove();
@ -256,13 +257,13 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
Iterator it = privaciesCheck.entrySet().iterator();
Iterator<Map.Entry<Integer, String>> it = privaciesCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<Integer, String> pair = it.next();
if (i == position) {
privacyToSend = new HashMap<>();
privacyToSend.put((Integer) pair.getKey(), (String) pair.getValue());
privacyToSend.put(pair.getKey(), pair.getValue());
break;
}
it.remove();
@ -277,32 +278,29 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
});
set_upload_file.setEnabled(true);
set_upload_file.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(PeertubeUploadActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(PeertubeUploadActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
return;
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent.setType("*/*");
String[] mimetypes = {"video/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(intent, PICK_IVDEO);
} else {
intent.setType("video/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_image));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
startActivityForResult(chooserIntent, PICK_IVDEO);
}
set_upload_file.setOnClickListener(v -> {
if (ContextCompat.checkSelfPermission(PeertubeUploadActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(PeertubeUploadActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
return;
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent.setType("*/*");
String[] mimetypes = {"video/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(intent, PICK_IVDEO);
} else {
intent.setType("video/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent chooserIntent = Intent.createChooser(intent, getString(R.string.toot_select_image));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
startActivityForResult(chooserIntent, PICK_IVDEO);
}
});
//Manage languages
@ -310,13 +308,13 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
LinkedHashMap<String, String> channelsCheck = new LinkedHashMap<>(channels);
Iterator it = channelsCheck.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = channelsCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Map.Entry<String, String> pair = it.next();
if (i == position) {
channelToSend = new HashMap<>();
channelToSend.put((String) pair.getKey(), (String) pair.getValue());
channelToSend.put(pair.getKey(), pair.getValue());
break;
}
@ -391,6 +389,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
exception.printStackTrace();
}
@SuppressLint("ApplySharedPref")
@Override
public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
try {

View File

@ -18,6 +18,7 @@ import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
@ -33,6 +34,8 @@ import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.exifinterface.media.ExifInterface;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
@ -74,6 +77,7 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
private static final int CAMERA_REQUEST = 52;
private static final int PICK_REQUEST = 53;
private final int STORE_REQUEST = 54;
private PhotoEditor mPhotoEditor;
private PhotoEditorView mPhotoEditorView;
private PropertiesBSFragment mPropertiesBSFragment;
@ -302,6 +306,13 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
if (ContextCompat.checkSelfPermission(PhotoEditorActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(PhotoEditorActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
STORE_REQUEST);
return;
}
mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
@Override
public void onSuccess(@NonNull String imagePath) {
@ -332,6 +343,18 @@ public class PhotoEditorActivity extends BaseActivity implements OnPhotoEditorLi
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == STORE_REQUEST) {// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// We have the permission.
saveImage();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

View File

@ -113,6 +113,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
@ -254,8 +255,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
final int[] currentCursorPosition = {toot_content.getSelectionStart()};
final String[] newContent = {null};
final int[] searchLength = {searchDeep};
TextWatcher textw = null;
TextWatcher finalTextw = textw;
TextWatcher textw;
textw = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
@ -270,7 +270,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
public void afterTextChanged(Editable s) {
if (autocomplete) {
toot_content.removeTextChangedListener(finalTextw);
toot_content.removeTextChangedListener(this);
Thread thread = new Thread() {
@Override
public void run() {
@ -357,11 +357,8 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
if (s.toString().length() == 0)
currentCursorPosition[0] = 0;
//Only check last 15 characters before cursor position to avoid lags
if (currentCursorPosition[0] < searchDeep) { //Less than 15 characters are written before the cursor position
searchLength[0] = currentCursorPosition[0];
} else {
searchLength[0] = searchDeep;
}
//Less than 15 characters are written before the cursor position
searchLength[0] = Math.min(currentCursorPosition[0], searchDeep);
int totalChar = countLength(social, toot_content);
@ -700,6 +697,9 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
}
restored = b.getLong("restored", -1);
}
if (!sharedUri.isEmpty()) {
uploadSharedImage(sharedUri);
}
if (scheduledstatus != null)
toot_it.setText(R.string.modify);
if (restoredScheduled) {
@ -1266,7 +1266,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
toot_space_left.setText("0");
if (attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
View namebar = findViewById(attachment.getViewId());
if (namebar != null && namebar.getParent() != null)
((ViewGroup) namebar.getParent()).removeView(namebar);
}
@ -1464,7 +1464,7 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
toot_space_left.setText("0");
if (attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
View namebar = findViewById(attachment.getViewId());
if (namebar != null && namebar.getParent() != null)
((ViewGroup) namebar.getParent()).removeView(namebar);
}
@ -1796,7 +1796,10 @@ public class PixelfedComposeActivity extends BaseActivity implements UploadStatu
if (url == null || url.trim().equals(""))
url = attachment.getUrl();
final ImageView imageView = new ImageView(PixelfedComposeActivity.this);
imageView.setId(Integer.parseInt(attachment.getId()));
Random rand = new Random();
int n = rand.nextInt(10000000);
imageView.setId(n);
attachment.setViewId(n);
LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
imParams.setMargins(20, 5, 20, 5);

View File

@ -81,9 +81,6 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
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;
@ -102,12 +99,7 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
toolbar_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar_close.setOnClickListener(v -> finish());
toolbar_title.setText(R.string.upload_video);
}
@ -140,7 +132,6 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
mainLoader.setVisibility(View.VISIBLE);
nextElementLoader.setVisibility(View.GONE);
boolean isOnWifi = Helper.isOnWIFI(PlaylistsActivity.this);
peertubeAdapter = new PeertubeAdapter(Helper.getLiveInstance(PlaylistsActivity.this), false, this.peertubes);
@ -181,16 +172,13 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
max_id = null;
firstLoad = true;
flag_loading = true;
swiped = true;
MainActivity.countNewStatus = 0;
new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
swipeRefreshLayout.setOnRefreshListener(() -> {
max_id = null;
firstLoad = true;
flag_loading = true;
swiped = true;
MainActivity.countNewStatus = 0;
new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
});
new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
@ -199,19 +187,16 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
@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 onActionDone(ManagePlaylistsAsyncTask.action actionType, APIResponse apiResponse, int statusCode) {
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
mainLoader.setVisibility(View.GONE);
nextElementLoader.setVisibility(View.GONE);
//Discards 404 - error which can often happen due to toots which have been deleted
@ -236,9 +221,7 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
if (swiped) {
if (previousPosition > 0) {
for (int i = 0; i < previousPosition; i++) {
this.peertubes.remove(0);
}
this.peertubes.subList(0, previousPosition).clear();
peertubeAdapter.notifyItemRangeRemoved(0, previousPosition);
}
swiped = false;

View File

@ -60,13 +60,10 @@ public class ProxyActivity extends BaseActivity {
boolean enable_proxy = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false);
final CheckBox set_enable_proxy = findViewById(R.id.enable_proxy);
set_enable_proxy.setChecked(enable_proxy);
set_enable_proxy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(Helper.SET_PROXY_ENABLED, set_enable_proxy.isChecked());
editor.apply();
}
set_enable_proxy.setOnClickListener(v -> {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(Helper.SET_PROXY_ENABLED, set_enable_proxy.isChecked());
editor.apply();
});
Button save = findViewById(R.id.set_proxy_save);
@ -112,34 +109,29 @@ public class ProxyActivity extends BaseActivity {
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String hostVal = host.getText().toString().trim();
String portVal = port.getText().toString().trim();
String proxy_loginVal = proxy_login.getText().toString().trim();
String proxy_passwordVal = proxy_password.getText().toString().trim();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.SET_PROXY_HOST, hostVal);
if (portVal.matches("\\d+"))
editor.putInt(Helper.SET_PROXY_PORT, Integer.parseInt(portVal));
editor.putString(Helper.SET_PROXY_LOGIN, proxy_loginVal);
editor.putString(Helper.SET_PROXY_PASSWORD, proxy_passwordVal);
editor.apply();
finish();
}
save.setOnClickListener(view -> {
String hostVal1 = host.getText().toString().trim();
String portVal1 = port.getText().toString().trim();
String proxy_loginVal = proxy_login.getText().toString().trim();
String proxy_passwordVal = proxy_password.getText().toString().trim();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.SET_PROXY_HOST, hostVal1);
if (portVal1.matches("\\d+"))
editor.putInt(Helper.SET_PROXY_PORT, Integer.parseInt(portVal1));
editor.putString(Helper.SET_PROXY_LOGIN, proxy_loginVal);
editor.putString(Helper.SET_PROXY_PASSWORD, proxy_passwordVal);
editor.apply();
finish();
});
}
@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);
}

View File

@ -15,7 +15,6 @@
package app.fedilab.android.activities;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
@ -33,7 +32,6 @@ 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.AutoCompleteTextView;
import android.widget.ImageView;
@ -138,212 +136,174 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
ImageView add_remote_instance = actionBar.getCustomView().findViewById(R.id.add_remote_instance);
toolbar_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar_close.setOnClickListener(v -> finish());
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
add_remote_instance.setVisibility(View.VISIBLE);
} else {
add_remote_instance.setVisibility(View.GONE);
}
add_remote_instance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ReorderTimelinesActivity.this, style);
LayoutInflater inflater = getLayoutInflater();
@SuppressLint("InflateParams") View dialogView = inflater.inflate(R.layout.search_instance, null);
dialogBuilder.setView(dialogView);
add_remote_instance.setOnClickListener(v -> {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ReorderTimelinesActivity.this, style);
LayoutInflater inflater1 = getLayoutInflater();
@SuppressLint("InflateParams") View dialogView = inflater1.inflate(R.layout.search_instance, null);
dialogBuilder.setView(dialogView);
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().replace("@", "");
new Thread(new Runnable() {
@Override
public void run() {
try {
if (radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance)
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/timelines/public?local=true", 10, null, null);
else if (radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance)
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/videos/", 10, null, null);
else if (radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) {
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/timelines/public", 10, null, null);
} else if (radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) {
new HttpsConnection(ReorderTimelinesActivity.this, null).post("https://" + instanceName + "/api/notes/local-timeline", 10, null, null);
} 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();
if (radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "MASTODON");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "PEERTUBE");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "PIXELFED");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) {
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);
if (instance != null && instance.size() > 0) {
ManageTimelines manageTimelines = new ManageTimelines();
manageTimelines.setRemoteInstance(instance.get(0));
manageTimelines.setPosition(timelines.size());
manageTimelines.setDisplayed(true);
manageTimelines.setType(ManageTimelines.Type.INSTANCE);
timelines.add(manageTimelines);
adapter.notifyItemInserted((timelines.size() - 1));
}
updated = true;
}
}
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toasty.warning(ReorderTimelinesActivity.this, getString(R.string.toast_instance_unavailable), Toast.LENGTH_LONG).show();
}
});
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, (dialog, id) -> {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceName = instance_list.getText().toString().trim().replace("@", "");
new Thread(() -> {
try {
if (radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance)
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/timelines/public?local=true", 10, null, null);
else if (radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance)
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/videos/", 10, null, null);
else if (radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) {
new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://" + instanceName + "/api/v1/timelines/public", 10, null, null);
} else if (radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) {
new HttpsConnection(ReorderTimelinesActivity.this, null).post("https://" + instanceName + "/api/notes/local-timeline", 10, null, null);
} 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(() -> {
dialog.dismiss();
if (radioGroup.getCheckedRadioButtonId() == R.id.mastodon_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "MASTODON");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.peertube_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "PEERTUBE");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.pixelfed_instance) {
new InstancesDAO(ReorderTimelinesActivity.this, db).insertInstance(instanceName, "PIXELFED");
} else if (radioGroup.getCheckedRadioButtonId() == R.id.misskey_instance) {
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);
if (instance != null && instance.size() > 0) {
ManageTimelines manageTimelines = new ManageTimelines();
manageTimelines.setRemoteInstance(instance.get(0));
manageTimelines.setPosition(timelines.size());
manageTimelines.setDisplayed(true);
manageTimelines.setType(ManageTimelines.Type.INSTANCE);
timelines.add(manageTimelines);
adapter.notifyItemInserted((timelines.size() - 1));
}
updated = true;
}
}).start();
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toasty.warning(ReorderTimelinesActivity.this, getString(R.string.toast_instance_unavailable), Toast.LENGTH_LONG).show());
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
//Hide keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(instance_list.getWindowToken(), 0);
}
});
if (alertDialog.getWindow() != null)
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
alertDialog.show();
}).start();
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.setOnDismissListener(dialogInterface -> {
//Hide keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(instance_list.getWindowToken(), 0);
});
if (alertDialog.getWindow() != null)
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
alertDialog.show();
instance_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String oldSearch = parent.getItemAtPosition(position).toString().trim();
}
});
instance_list.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
instance_list.setOnItemClickListener((parent, view1, position, id) -> {
});
instance_list.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 onTextChanged(CharSequence s, int start, int before, int count) {
}
}
@Override
public void afterTextChanged(Editable s) {
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;
}
@Override
public void afterTextChanged(Editable s) {
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(() -> {
try {
final String response = new HttpsConnection(ReorderTimelinesActivity.this, null).get("https://instances.social/api/1.0" + action, 30, parameters, Helper.THEKINRAR_SECRET_TOKEN);
runOnUiThread(() -> {
isLoadingInstance = false;
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("instances");
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++;
}
}
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 (Exception e) {
isLoadingInstance = false;
}
}).start();
else
isLoadingInstance = false;
}
} else {
alertDialog.getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
});
}
}
});
});
toolbar_title.setText(R.string.action_reorder_timeline);
}
@ -390,40 +350,34 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
break;
}
undo_action.setPaintFlags(undo_action.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Runnable runnable = new Runnable() {
@Override
public void run() {
undo_container.setVisibility(View.GONE);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
switch (manageTimelines.getType()) {
case TAG:
new SearchDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines.getTagTimeline().getName());
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines);
break;
case INSTANCE:
new InstancesDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines.getRemoteInstance().getHost());
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines);
break;
case LIST:
timeline = manageTimelines;
new ManageListsAsyncTask(ReorderTimelinesActivity.this, ManageListsAsyncTask.action.DELETE_LIST, null, null, manageTimelines.getListTimeline().getId(), null, ReorderTimelinesActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(timeline);
refresh_list = true;
break;
}
updated = true;
Runnable runnable = () -> {
undo_container.setVisibility(View.GONE);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
switch (manageTimelines.getType()) {
case TAG:
new SearchDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines.getTagTimeline().getName());
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines);
break;
case INSTANCE:
new InstancesDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines.getRemoteInstance().getHost());
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(manageTimelines);
break;
case LIST:
timeline = manageTimelines;
new ManageListsAsyncTask(ReorderTimelinesActivity.this, ManageListsAsyncTask.action.DELETE_LIST, null, null, manageTimelines.getListTimeline().getId(), null, ReorderTimelinesActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(timeline);
refresh_list = true;
break;
}
updated = true;
};
Handler handler = new Handler();
handler.postDelayed(runnable, 4000);
undo_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timelines.add(position, manageTimelines);
adapter.notifyItemInserted(position);
undo_container.setVisibility(View.GONE);
handler.removeCallbacks(runnable);
}
undo_action.setOnClickListener(v -> {
timelines.add(position, manageTimelines);
adapter.notifyItemInserted(position);
undo_container.setVisibility(View.GONE);
handler.removeCallbacks(runnable);
});
}

View File

@ -109,12 +109,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
toolbar_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar_close.setOnClickListener(v -> finish());
if (!forTrends) {
toolbar_title.setText(search);
} else {
@ -134,13 +129,11 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
@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);
}

View File

@ -154,7 +154,7 @@ public class SettingsActivity extends BaseActivity {
}
@Override
public void onDestroy(){
public void onDestroy() {
super.onDestroy();
}

View File

@ -48,6 +48,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
@ -545,14 +546,14 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if ((MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) && account.getFields() != null && account.getFields().size() > 0) {
LinkedHashMap<String, String> fields = account.getFields();
LinkedHashMap<String, Boolean> fieldsVerified = account.getFieldsVerified();
Iterator it = fields.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = fields.entrySet().iterator();
int i = 1;
LinearLayout fields_container = findViewById(R.id.fields_container);
if (fields_container != null)
fields_container.setVisibility(View.VISIBLE);
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
String label = (String) pair.getKey();
Map.Entry<String, String> pair = it.next();
String label = pair.getKey();
if (label != null && fieldsVerified != null && fieldsVerified.containsKey(label)) {
boolean verified = fieldsVerified.get(label);
@ -618,7 +619,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
SpannableString spannableString = Helper.clickableElementsDescription(ShowAccountActivity.this, account.getNote());
account.setNoteSpan(spannableString);
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)
account.makeEmojisAccountProfile(ShowAccountActivity.this, ShowAccountActivity.this, account);
account.fillProfileAccount(ShowAccountActivity.this, ShowAccountActivity.this, account);
account_note.setText(account.getNoteSpan(), TextView.BufferType.SPANNABLE);
account_note.setMovementMethod(LinkMovementMethod.getInstance());
if (!peertubeAccount && tabLayout.getTabAt(0) != null && tabLayout.getTabAt(1) != null && tabLayout.getTabAt(2) != null) {
@ -737,8 +738,17 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
attachments.add(attachment);
intent.putParcelableArrayListExtra("mediaArray", attachments);
b.putInt("position", 1);
b.putInt("bgcolor", getResources().getColor(R.color.cyanea_primary_dark));
intent.putExtras(b);
startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(ShowAccountActivity.this, account_pp, attachment.getUrl());
// start the new activity
startActivity(intent, options.toBundle());
} else {
// start the new activity
startActivity(intent);
}
});
//Follow button
String target = account.getId();
@ -961,24 +971,20 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
LinkedHashMap<String, Boolean> fieldsVerified = account.getFieldsVerified();
if (account.getFieldsSpan() != null && account.getFieldsSpan().size() > 0) {
HashMap<SpannableString, SpannableString> fieldsSpan = account.getFieldsSpan();
Iterator it = fieldsSpan.entrySet().iterator();
Iterator<Map.Entry<SpannableString, SpannableString>> it = fieldsSpan.entrySet().iterator();
int i = 1;
LinearLayout fields_container = findViewById(R.id.fields_container);
if (fields_container != null)
fields_container.setVisibility(View.VISIBLE);
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
SpannableString label = (SpannableString) pair.getKey();
SpannableString value = (SpannableString) pair.getValue();
Map.Entry<SpannableString, SpannableString> pair = it.next();
SpannableString label = pair.getKey();
SpannableString value = pair.getValue();
LinearLayout field;
TextView labelView;
TextView valueView;
switch (i) {
case 1:
field = findViewById(R.id.field1);
labelView = findViewById(R.id.label1);
valueView = findViewById(R.id.value1);
break;
case 2:
field = findViewById(R.id.field2);
labelView = findViewById(R.id.label2);
@ -1165,7 +1171,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
tags = new ArrayList<>(featuredTagsSet);
}
tags.add(0, getString(R.string.no_tags));
String[] tagsString = tags.toArray(new String[tags.size()]);
String[] tagsString = tags.toArray(new String[0]);
List<String> finalTags = tags;
String tag = sharedpreferences.getString(Helper.SET_FEATURED_TAG_ACTION, null);
int checkedposition = 0;
@ -1330,8 +1336,13 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
return true;
case R.id.action_block:
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(stringArrayConf[1]);
doActionAccount = API.StatusAction.BLOCK;
if (relationship.isBlocking()) {
builderInner.setTitle(stringArrayConf[5]);
doActionAccount = API.StatusAction.UNBLOCK;
} else {
builderInner.setTitle(stringArrayConf[1]);
doActionAccount = API.StatusAction.BLOCK;
}
break;
case R.id.action_block_instance:
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);

View File

@ -111,10 +111,6 @@ public class ShowConversationActivity extends BaseActivity implements OnRetrieve
detailsStatus.setFocused(true);
//Some spannable
Status.fillSpan(new WeakReference<>(ShowConversationActivity.this), detailsStatus);
if (detailsStatus.getPoll() != null) {
Status.makeEmojiPoll(new WeakReference<>(ShowConversationActivity.this), detailsStatus.getPoll());
}
Account.makeAccountNameEmoji(new WeakReference<>(ShowConversationActivity.this), detailsStatus.getAccount());
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {

View File

@ -36,10 +36,12 @@ import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
@ -49,11 +51,6 @@ import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrConfig;
import com.r0adkll.slidr.model.SlidrInterface;
import com.r0adkll.slidr.model.SlidrPosition;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
@ -72,7 +69,7 @@ import es.dmoral.toasty.Toasty;
* Media Activity
*/
public class SlideMediaActivity extends BaseActivity implements OnDownloadInterface {
public class SlideMediaActivity extends BaseFragmentActivity implements OnDownloadInterface {
int flags;
private ArrayList<Attachment> attachments;
@ -80,13 +77,13 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
private ViewPager mPager;
private long downloadID;
private boolean fullscreen;
private SlidrInterface slidrInterface;
private TextView media_description;
private Handler handler;
private boolean swipeEnabled;
private int minTouch, maxTouch;
private float startX;
private float startY;
private int bgColor;
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@ -98,10 +95,14 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
ContentResolver cR = context.getContentResolver();
shareIntent.setType(cR.getType(uri));
try {
startActivity(shareIntent);
} catch (Exception ignored) {
if (cR != null && uri != null) {
shareIntent.setType(cR.getType(uri));
try {
startActivity(shareIntent);
} catch (Exception ignored) {
}
} else {
Toasty.error(context, context.getString(R.string.toast_error), Toasty.LENGTH_LONG).show();
}
} else {
Toasty.success(context, context.getString(R.string.save_over), Toasty.LENGTH_LONG).show();
@ -125,49 +126,56 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
default:
setTheme(R.style.TransparentDark);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityCompat.postponeEnterTransition(SlideMediaActivity.this);
}
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_media_pager);
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();
if (getIntent().getExtras() != null) {
mediaPosition = getIntent().getExtras().getInt("position", 1);
bgColor = getIntent().getExtras().getInt("bgcolor", -1);
}
swipeEnabled = true;
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
//actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(SlideMediaActivity.this, R.color.cyanea_primary)));
actionBar.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
actionBar.setElevation(0);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
assert inflater != null;
View view = inflater.inflate(R.layout.media_action_bar, new LinearLayout(SlideMediaActivity.this), 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);
TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
ImageView media_save = getSupportActionBar().getCustomView().findViewById(R.id.media_save);
ImageView media_share = getSupportActionBar().getCustomView().findViewById(R.id.media_share);
toolbar_close.setOnClickListener(v -> finish());
ImageView media_save = actionBar.getCustomView().findViewById(R.id.media_save);
ImageView media_share = actionBar.getCustomView().findViewById(R.id.media_share);
toolbar_close.setOnClickListener(v -> ActivityCompat.finishAfterTransition(this));
media_save.setOnClickListener(view12 -> {
int position = mPager.getCurrentItem();
Attachment attachment = attachments.get(position);
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);
}
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_MEDIA_SAVE);
} 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);
if (attachment.getType().compareTo("image") == 0) {
Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), false);
} else {
Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
downloadID = -1;
}
}
} else {
if (attachment.getType().compareTo("image") == 0) {
Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), false);
} else {
Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
downloadID = -1;
@ -185,7 +193,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
} 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);
ActivityCompat.requestPermissions(SlideMediaActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Helper.EXTERNAL_STORAGE_REQUEST_CODE_MEDIA_SHARE);
} else {
downloadID = Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
}
@ -198,8 +206,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
}
attachments = getIntent().getParcelableArrayListExtra("mediaArray");
if (getIntent().getExtras() != null)
mediaPosition = getIntent().getExtras().getInt("position", 1);
if (attachments == null || attachments.size() == 0)
finish();
@ -208,6 +215,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
mPager.setAdapter(mPagerAdapter);
mPager.setCurrentItem(mediaPosition - 1);
mPager.setOffscreenPageLimit(0);
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
String description = attachments.get(mediaPosition - 1).getDescription();
@ -216,10 +224,16 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
media_description.setText(description);
media_description.setVisibility(View.VISIBLE);
handler.postDelayed(() -> media_description.setVisibility(View.GONE), med_desc_timeout);
handler.postDelayed(() -> {
if (!media_description.hasSelection()) {
media_description.setVisibility(View.GONE);
}
}, med_desc_timeout);
} else {
media_description.setVisibility(View.GONE);
if (!media_description.hasSelection()) {
media_description.setVisibility(View.GONE);
}
}
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
@ -238,27 +252,21 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
media_description.setText(description);
media_description.setVisibility(View.VISIBLE);
handler.postDelayed(() -> media_description.setVisibility(View.GONE), med_desc_timeout);
handler.postDelayed(() -> {
if (!media_description.hasSelection()) {
media_description.setVisibility(View.GONE);
}
}, med_desc_timeout);
} else {
media_description.setVisibility(View.GONE);
if (!media_description.hasSelection()) {
media_description.setVisibility(View.GONE);
}
}
}
});
SlidrConfig config = new SlidrConfig.Builder()
.sensitivity(1f)
.scrimColor(Color.BLACK)
.scrimStartAlpha(0.8f)
.scrimEndAlpha(0f)
.position(SlidrPosition.VERTICAL)
.velocityThreshold(2400)
.distanceThreshold(0.25f)
.edgeSize(0.18f)
.build();
slidrInterface = Slidr.attach(SlideMediaActivity.this, config);
setFullscreen(true);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
@ -269,12 +277,36 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case Helper.EXTERNAL_STORAGE_REQUEST_CODE_MEDIA_SAVE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
int position = mPager.getCurrentItem();
Attachment attachment = attachments.get(position);
if (attachment.getType().compareTo("image") == 0) {
Helper.manageMove(SlideMediaActivity.this, attachment.getUrl(), false);
} else {
Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
downloadID = -1;
}
} else { /*Todo: Toast "Storage Permission Required" */ }
return;
case Helper.EXTERNAL_STORAGE_REQUEST_CODE_MEDIA_SHARE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
int position = mPager.getCurrentItem();
Attachment attachment = attachments.get(position);
downloadID = Helper.manageDownloadsNoPopup(SlideMediaActivity.this, attachment.getUrl());
} else { /*Todo: Toast "Storage Permission Required" */ }
break;
}
}
@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();
@ -295,10 +327,16 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
media_description.setText(description);
media_description.setVisibility(View.VISIBLE);
handler.postDelayed(() -> media_description.setVisibility(View.GONE), med_desc_timeout);
handler.postDelayed(() -> {
if (!media_description.hasSelection()) {
media_description.setVisibility(View.GONE);
}
}, med_desc_timeout);
} else {
media_description.setVisibility(View.GONE);
if (!media_description.hasSelection()) {
media_description.setVisibility(View.GONE);
}
}
}
}
@ -352,15 +390,6 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
super.onPostResume();
}
public void enableSliding(boolean enable) {
if (enable && !swipeEnabled) {
slidrInterface.unlock();
swipeEnabled = true;
} else if (!enable && swipeEnabled) {
slidrInterface.lock();
swipeEnabled = false;
}
}
public boolean getFullScreen() {
return this.fullscreen;
@ -419,6 +448,7 @@ public class SlideMediaActivity extends BaseActivity implements OnDownloadInterf
MediaSliderFragment mediaSliderFragment = new MediaSliderFragment();
bundle.putInt("position", position);
bundle.putParcelable("attachment", attachments.get(position));
bundle.putInt("bgcolor", bgColor);
mediaSliderFragment.setArguments(bundle);
return mediaSliderFragment;
}

View File

@ -19,7 +19,6 @@ import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
@ -70,40 +69,34 @@ public class TagCacheActivity extends BaseActivity {
EditText tag_add = findViewById(R.id.tag_add);
ImageButton save_tag = findViewById(R.id.save_tag);
save_tag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tag_add.getText() != null && tag_add.getText().toString().trim().replaceAll("\\#", "").length() > 0) {
String tagToInsert = tag_add.getText().toString().trim().replaceAll("\\#", "");
boolean isPresent = new TagsCacheDAO(TagCacheActivity.this, db).isPresent(tagToInsert);
if (isPresent)
Toasty.warning(TagCacheActivity.this, getString(R.string.tags_already_stored), Toast.LENGTH_LONG).show();
else {
new TagsCacheDAO(TagCacheActivity.this, db).insert(tagToInsert);
int position = tags.size();
tags.add(tagToInsert);
Toasty.success(TagCacheActivity.this, getString(R.string.tags_stored), Toast.LENGTH_LONG).show();
tag_add.setText("");
tagsEditAdapter.notifyItemInserted(position);
}
save_tag.setOnClickListener(v -> {
if (tag_add.getText() != null && tag_add.getText().toString().trim().replaceAll("#", "").length() > 0) {
String tagToInsert = tag_add.getText().toString().trim().replaceAll("#", "");
boolean isPresent = new TagsCacheDAO(TagCacheActivity.this, db).isPresent(tagToInsert);
if (isPresent)
Toasty.warning(TagCacheActivity.this, getString(R.string.tags_already_stored), Toast.LENGTH_LONG).show();
else {
new TagsCacheDAO(TagCacheActivity.this, db).insert(tagToInsert);
int position = tags.size();
tags.add(tagToInsert);
Toasty.success(TagCacheActivity.this, getString(R.string.tags_stored), Toast.LENGTH_LONG).show();
tag_add.setText("");
tagsEditAdapter.notifyItemInserted(position);
}
}
});
setTitle(R.string.manage_tags);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
AsyncTask.execute(() -> {
List<String> tagsTemp = new TagsCacheDAO(TagCacheActivity.this, db).getAll();
if (tagsTemp != null)
tags = tagsTemp;
if (tags != null) {
tagsEditAdapter = new TagsEditAdapter(tags);
tag_list.setAdapter(tagsEditAdapter);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(TagCacheActivity.this);
tag_list.setLayoutManager(mLayoutManager);
}
List<String> tagsTemp = new TagsCacheDAO(TagCacheActivity.this, db).getAll();
if (tagsTemp != null)
tags = tagsTemp;
if (tags != null) {
tagsEditAdapter = new TagsEditAdapter(tags);
tag_list.setAdapter(tagsEditAdapter);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(TagCacheActivity.this);
tag_list.setLayoutManager(mLayoutManager);
}
});

View File

@ -134,7 +134,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
@ -207,6 +207,7 @@ import static app.fedilab.android.helper.Helper.THEME_BLACK;
import static app.fedilab.android.helper.Helper.THEME_DARK;
import static app.fedilab.android.helper.Helper.THEME_LIGHT;
import static app.fedilab.android.helper.Helper.countWithEmoji;
import static app.fedilab.android.helper.Helper.isValidContextForGlide;
/**
@ -329,7 +330,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
final String[] newContent = {null};
final int[] searchLength = {searchDeep};
TextWatcher textw = null;
TextWatcher finalTextw = textw;
textw = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
@ -347,7 +348,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
status.setQuickReplyContent(s.toString());
}
if (autocomplete) {
toot_content.removeTextChangedListener(finalTextw);
toot_content.removeTextChangedListener(this);
Thread thread = new Thread() {
@Override
public void run() {
@ -435,11 +436,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
if (s.toString().length() == 0)
currentCursorPosition[0] = 0;
//Only check last 15 characters before cursor position to avoid lags
if (currentCursorPosition[0] < searchDeep) { //Less than 15 characters are written before the cursor position
searchLength[0] = currentCursorPosition[0];
} else {
searchLength[0] = searchDeep;
}
//Less than 15 characters are written before the cursor position
searchLength[0] = Math.min(currentCursorPosition[0], searchDeep);
int totalChar = countLength(social, toot_content, toot_cw_content);
@ -646,7 +644,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
}
}
public static String manageMentions(Context context, String userIdReply, Status tootReply) {
public static String manageMentions(String userIdReply, Status tootReply) {
String contentView = "";
//Retrieves mentioned accounts + OP and adds them at the beginin of the toot
ArrayList<String> mentionedAccountsAdded = new ArrayList<>();
@ -893,12 +891,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
if (s.toString().length() == 0)
currentCursorPosition = 0;
//Only check last 15 characters before cursor position to avoid lags
int searchLength;
if (currentCursorPosition < searchDeep) { //Less than 15 characters are written before the cursor position
searchLength = currentCursorPosition;
} else {
searchLength = searchDeep;
}
int searchLength = Math.min(currentCursorPosition, searchDeep);
int totalChar = countLength(wysiwyg, toot_cw_content);
toot_space_left.setText(String.valueOf(totalChar));
if (currentCursorPosition - (searchLength - 1) < 0 || currentCursorPosition == 0 || currentCursorPosition > s.toString().length())
@ -1017,6 +1010,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
if (tootReply.getAccount() != null && tootReply.getAccount().getMoved_to_account() != null) {
warning_message.setVisibility(View.VISIBLE);
}
assert tootReply.getAccount() != null;
new RetrieveRelationshipAsyncTask(TootActivity.this, tootReply.getAccount().getId(), TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if (scheduledstatus != null)
@ -1328,65 +1322,72 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
final ImageView imageView = new ImageView(TootActivity.this);
imageView.setId(Integer.parseInt(attachment.getId()));
Random rand = new Random();
int n = rand.nextInt(10000000);
imageView.setId(n);
attachment.setViewId(n);
if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
if (successfullyUploadedFiles != null && successfullyUploadedFiles.size() > 0) {
Iterator it = filesMap.entrySet().iterator();
Iterator<Map.Entry<String, Uri>> it = filesMap.entrySet().iterator();
Uri fileName = null;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
fileName = (Uri) pair.getValue();
Map.Entry<String, Uri> pair = it.next();
fileName = pair.getValue();
it.remove();
}
if (fileName != null) {
Glide.with(imageView.getContext())
.asBitmap()
.load(fileName)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
if (isValidContextForGlide(imageView.getContext())) {
Glide.with(imageView.getContext())
.asBitmap()
.load(fileName)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
});
}
}
}
} else {
String finalUrl = url;
Glide.with(imageView.getContext())
.asBitmap()
.load(url)
.error(Glide.with(imageView).asBitmap().load(R.drawable.ic_audio_wave))
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
if (displayWYSIWYG()) {
url_for_media = finalUrl;
Iterator it = filesMap.entrySet().iterator();
String fileName = null;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
fileName = (String) pair.getKey();
it.remove();
}
if (fileName != null && fileName.contains("fedilabins_")) {
wysiwyg.insertImage(resource);
if (isValidContextForGlide(imageView.getContext())) {
String finalUrl = url;
Glide.with(imageView.getContext())
.asBitmap()
.load(url)
.error(Glide.with(imageView).asBitmap().load(R.drawable.ic_audio_wave))
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
if (displayWYSIWYG()) {
url_for_media = finalUrl;
Iterator<Map.Entry<String, Uri>> it = filesMap.entrySet().iterator();
String fileName = null;
while (it.hasNext()) {
Map.Entry<String, Uri> pair = it.next();
fileName = pair.getKey();
it.remove();
}
if (fileName != null && fileName.contains("fedilabins_")) {
wysiwyg.insertImage(resource);
}
}
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
});
}
}
@ -2075,9 +2076,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
dialog.dismiss();
});
builderSingle1.setPositiveButton(R.string.server_schedule, (dialog, which) -> {
int offset = TimeZone.getDefault().getRawOffset();
calendar.add(Calendar.MILLISECOND, -offset);
final String date = Helper.dateToString(new Date(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
String date = sdf.format(calendar.getTime());
serverSchedule(date);
});
builderSingle1.show();
@ -2119,6 +2119,8 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
} else {
tootContent = wysiwyg.getContentAsHTML();
}
//Reset old values
splitToot = new ArrayList<>();
createAndSendToot(tootContent, content_type, timestamp);
} else {
splitToot = Helper.splitToots(toot_content.getText().toString().trim(), split_toot_size, true);
@ -2242,12 +2244,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toot_space_left.setText("0");
if (attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
View namebar = findViewById(attachment.getViewId());
if (namebar != null && namebar.getParent() != null)
((ViewGroup) namebar.getParent()).removeView(namebar);
}
List<Attachment> tmp_attachment = new ArrayList<>();
tmp_attachment.addAll(attachments);
List<Attachment> tmp_attachment = new ArrayList<>(attachments);
attachments.removeAll(tmp_attachment);
tmp_attachment.clear();
}
@ -2361,7 +2362,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
//Text for report
final EditText input = popup_media_description.findViewById(R.id.media_description);
input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(420)});
input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1500)});
final ImageView media_picture = popup_media_description.findViewById(R.id.media_picture);
Glide.with(TootActivity.this)
.asBitmap()
@ -2412,7 +2413,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
dialog.setPositiveButton(R.string.yes, (dialog12, which) -> {
View namebar = findViewById(viewId);
for (Attachment attachment : attachments) {
if (Integer.parseInt(attachment.getId()) == viewId) {
if (attachment.getViewId() == viewId) {
attachments.remove(attachment);
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, false);
@ -2581,12 +2582,11 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toot_space_left.setText("0");
if (attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
View namebar = findViewById(attachment.getViewId());
if (namebar != null && namebar.getParent() != null)
((ViewGroup) namebar.getParent()).removeView(namebar);
}
List<Attachment> tmp_attachment = new ArrayList<>();
tmp_attachment.addAll(attachments);
List<Attachment> tmp_attachment = new ArrayList<>(attachments);
attachments.removeAll(tmp_attachment);
tmp_attachment.clear();
}
@ -3045,7 +3045,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
if (url == null || url.trim().equals(""))
url = attachment.getUrl();
final ImageView imageView = new ImageView(TootActivity.this);
imageView.setId(Integer.parseInt(attachment.getId()));
imageView.setId(attachment.getViewId());
LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
imParams.setMargins(20, 5, 20, 5);
@ -3069,9 +3069,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
}
});
imageView.setTag(attachment.getId());
imageView.setOnClickListener(view -> {
imageView.setOnClickListener(view1 -> showAddDescription(attachment));
});
imageView.setOnClickListener(view -> imageView.setOnClickListener(view1 -> showAddDescription(attachment)));
imageView.setOnLongClickListener(view -> {
showRemove(imageView.getId());
return false;
@ -3173,10 +3171,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toRemove.clear();
}
String content = status.getContent();
Pattern mentionLink = Pattern.compile("(<\\s?a\\s?href=\"https?://([\\da-z.-]+\\.[a-z.]{2,10})/(@[/\\w._-]*)\"\\s?[^.]*<\\s?/\\s?a\\s?>)");
Matcher matcher = mentionLink.matcher(content);
if (matcher.find()) {
content = matcher.replaceAll("$3@$2");
if (content != null) {
Pattern mentionLink = Pattern.compile("(<\\s?a\\s?href=\"https?://([\\da-z.-]+\\.[a-z.]{2,10})/(@[/\\w._-]*)\"\\s?[^.]*<\\s?/\\s?a\\s?>)");
Matcher matcher = mentionLink.matcher(content);
if (matcher.find()) {
content = matcher.replaceAll("$3@$2");
}
}
if (removed) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
@ -3193,7 +3193,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
if (url == null || url.trim().equals(""))
url = attachment.getUrl();
final ImageView imageView = new ImageView(TootActivity.this);
imageView.setId(Integer.parseInt(attachment.getId()));
imageView.setId(attachment.getViewId());
LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
imParams.setMargins(20, 5, 20, 5);
@ -3217,9 +3217,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
}
});
imageView.setTag(attachment.getId());
imageView.setOnClickListener(view -> {
imageView.setOnClickListener(view1 -> showAddDescription(attachment));
});
imageView.setOnClickListener(view -> imageView.setOnClickListener(view1 -> showAddDescription(attachment)));
imageView.setOnLongClickListener(view -> {
showRemove(imageView.getId());
return false;
@ -3242,6 +3240,12 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
toot_cw_content.setText("");
toot_cw_content.setVisibility(View.GONE);
}
if (status.getVisibility() == null) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String defaultVisibility = account.isLocked() ? "private" : "public";
String settingsVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility);
status.setVisibility(settingsVisibility);
}
toot_content.setText(content);
toot_space_left.setText(String.valueOf(countLength(social, toot_content, toot_cw_content)));
@ -3343,12 +3347,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
ownerTootVisibility = 1;
break;
}
int tootVisibility;
if (ownerTootVisibility >= initialTootVisibility) {
tootVisibility = initialTootVisibility;
} else {
tootVisibility = ownerTootVisibility;
}
int tootVisibility = Math.min(ownerTootVisibility, initialTootVisibility);
switch (tootVisibility) {
case 4:
visibility = "public";
@ -3396,7 +3395,7 @@ public class TootActivity extends BaseActivity implements UploadStatusDelegate,
private void displayPollPopup() {
AlertDialog.Builder alertPoll = new AlertDialog.Builder(TootActivity.this, style);
alertPoll.setTitle(R.string.create_poll);
View view = getLayoutInflater().inflate(R.layout.popup_poll, null);
View view = getLayoutInflater().inflate(R.layout.popup_poll, new LinearLayout(TootActivity.this), false);
alertPoll.setView(view);
Spinner poll_choice = view.findViewById(R.id.poll_choice);
Spinner poll_duration = view.findViewById(R.id.poll_duration);

View File

@ -190,7 +190,7 @@ public class WebviewActivity extends BaseActivity {
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (!peertubeLink)
setCount(this, "0");
setCount(WebviewActivity.this, "0");
defaultMenu = menu;
return super.onPrepareOptionsMenu(menu);
}

View File

@ -125,10 +125,8 @@ public class WebviewConnectActivity extends BaseActivity {
webView = findViewById(R.id.webviewConnect);
clearCookies(WebviewConnectActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, null);
if (user_agent != null) {
webView.getSettings().setUserAgentString(user_agent);
}
String user_agent = sharedpreferences.getString(Helper.SET_CUSTOM_USER_AGENT, Helper.USER_AGENT);
webView.getSettings().setUserAgentString(user_agent);
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
} else {
@ -150,7 +148,9 @@ public class WebviewConnectActivity extends BaseActivity {
}
});
if (instance == null) {
finish();
}
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
@ -200,6 +200,7 @@ public class WebviewConnectActivity extends BaseActivity {
});
webView.loadUrl(LoginActivity.redirectUserToAuthorizeAndLogin(WebviewConnectActivity.this, clientId, instance));
}
@Override

View File

@ -79,9 +79,6 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
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;
@ -146,51 +143,41 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
}
Button follow_accounts_select = findViewById(R.id.follow_accounts_select);
follow_accounts_select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (follow_accounts_select.getText().equals(getString(R.string.select_all))) {
follow_accounts_select.setText(R.string.unselect_all);
for (TrunkAccount trunkAccount : trunkAccounts) {
trunkAccount.setChecked(true);
}
whoToFollowAccountsAdapter.notifyDataSetChanged();
} else {
follow_accounts_select.setText(R.string.select_all);
for (TrunkAccount trunkAccount : trunkAccounts) {
trunkAccount.setChecked(false);
}
whoToFollowAccountsAdapter.notifyDataSetChanged();
}
follow_accounts_select.setOnClickListener(v -> {
if (follow_accounts_select.getText().equals(getString(R.string.select_all))) {
follow_accounts_select.setText(R.string.unselect_all);
} else {
follow_accounts_select.setText(R.string.select_all);
}
for (TrunkAccount trunkAccount : trunkAccounts) {
trunkAccount.setChecked(false);
}
whoToFollowAccountsAdapter.notifyDataSetChanged();
});
Button follow_accounts = findViewById(R.id.follow_accounts);
follow_accounts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
follow_accounts.setEnabled(false);
follow_accounts_select.setEnabled(false);
progess_action.setVisibility(View.VISIBLE);
toFollowdId = new ArrayList<>();
for (TrunkAccount trunkAccount : trunkAccounts) {
if (trunkAccount.isChecked()) {
toFollowdId.add(trunkAccount.getAcct());
}
follow_accounts.setOnClickListener(v -> {
follow_accounts.setEnabled(false);
follow_accounts_select.setEnabled(false);
progess_action.setVisibility(View.VISIBLE);
toFollowdId = new ArrayList<>();
for (TrunkAccount trunkAccount : trunkAccounts) {
if (trunkAccount.isChecked()) {
toFollowdId.add(trunkAccount.getAcct());
}
if (toFollowdId.size() > 0) {
Account account = new Account();
String[] val = toFollowdId.get(0).split("@");
progess_action.setText(getString(R.string.follow_trunk, toFollowdId.get(0)));
if (val.length > 1) {
account.setAcct(val[0]);
account.setInstance(val[1]);
new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
Toasty.error(WhoToFollowActivity.this, getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show();
follow_accounts.setEnabled(true);
follow_accounts_select.setEnabled(true);
progess_action.setVisibility(View.GONE);
}
}
if (toFollowdId.size() > 0) {
Account account = new Account();
String[] val = toFollowdId.get(0).split("@");
progess_action.setText(getString(R.string.follow_trunk, toFollowdId.get(0)));
if (val.length > 1) {
account.setAcct(val[0]);
account.setInstance(val[1]);
new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
Toasty.error(WhoToFollowActivity.this, getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show();
follow_accounts.setEnabled(true);
follow_accounts_select.setEnabled(true);
progess_action.setVisibility(View.GONE);
}
}
});
@ -199,13 +186,11 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
@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
@ -237,6 +222,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.CREATE_LIST, null, null, null, item, WhoToFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
Account account = new Account();
assert followedId != null;
String[] val = toFollowdId.get(followedId.size()).split("@");
progess_action.setText(getString(R.string.follow_trunk, toFollowdId.get(followedId.size())));
if (val.length > 1) {
@ -253,7 +239,6 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
List<app.fedilab.android.client.Entities.List> lists = apiResponse.getLists();
if (lists != null && lists.size() > 0 && actionType == ManageListsAsyncTask.action.CREATE_LIST) {
String[] accountsId = followedId.toArray(new String[0]);
progess_action.setText(R.string.add_account_list_trunk);
listId = lists.get(0).getId();
listTitle = lists.get(0).getTitle();
@ -264,18 +249,14 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
if (accountListId.size() >= followedId.size() - 1) {
progess_action.setText(R.string.account_added_list_trunk);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(WhoToFollowActivity.this, ListActivity.class);
Bundle b = new Bundle();
b.putString("id", listId);
b.putString("title", listTitle);
intent.putExtras(b);
startActivity(intent);
finish();
}
handler.postDelayed(() -> {
Intent intent = new Intent(WhoToFollowActivity.this, ListActivity.class);
Bundle b = new Bundle();
b.putString("id", listId);
b.putString("title", listTitle);
intent.putExtras(b);
startActivity(intent);
finish();
}, 1000);
} else {

View File

@ -33,7 +33,6 @@ import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import app.fedilab.android.R;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.sqlite.DomainBlockDAO;
import app.fedilab.android.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;

View File

@ -35,9 +35,7 @@ import app.fedilab.android.interfaces.OnRetrieveContextInterface;
public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
private String statusId;
private app.fedilab.android.client.Entities.Context statusContext;
private OnRetrieveContextInterface listener;
private Error error;
private WeakReference<Context> contextReference;
private boolean expanded;
private boolean directtimeline;
@ -55,6 +53,8 @@ public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
apiResponse = new APIResponse();
apiResponse.setTargetedId(this.statusId);
app.fedilab.android.client.Entities.Context statusContext;
Error error;
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api = new API(this.contextReference.get());
statusContext = api.getStatusContext(statusId);
@ -63,7 +63,6 @@ public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId());
}
error = api.getError();
apiResponse.setError(error);
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
statusContext = gnuapi.getStatusContext(statusId, directtimeline);
@ -72,8 +71,8 @@ public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
statusContext = gnuapi.getStatusContext(statusContext.getAncestors().get(0).getId(), directtimeline);
}
error = gnuapi.getError();
apiResponse.setError(error);
}
apiResponse.setError(error);
apiResponse.setContext(statusContext);
return null;
}

View File

@ -25,7 +25,6 @@ import java.util.List;
import app.fedilab.android.activities.MainActivity;
import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.ManageTimelines;
import app.fedilab.android.client.Entities.Peertube;
import app.fedilab.android.client.Entities.RemoteInstance;
@ -368,10 +367,9 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<app.fedilab.android.client.Entities.Status> statuses = new StatusCacheDAO(contextReference.get(), db).getAllStatus(StatusCacheDAO.BOOKMARK_CACHE);
if (statuses != null) {
for (app.fedilab.android.client.Entities.Status status : statuses) {
app.fedilab.android.client.Entities.Status.fillSpan(contextReference, status);
app.fedilab.android.client.Entities.Status.makeEmojiPoll(contextReference, status.getReblog() != null ? status.getReblog().getPoll() : status.getPoll());
Account.makeAccountNameEmoji(contextReference, status.getReblog() != null ? status.getReblog().getAccount() : status.getAccount());
}
} else {
statuses = new ArrayList<>();
@ -389,6 +387,9 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
statuses = new StatusCacheDAO(contextReference.get(), db).getStatusFromID(StatusCacheDAO.ARCHIVE_CACHE, filterToots, max_id);
if (statuses != null && statuses.size() > 0) {
for (app.fedilab.android.client.Entities.Status status : statuses) {
app.fedilab.android.client.Entities.Status.fillSpan(contextReference, status);
}
apiResponse.setStatuses(statuses);
apiResponse.setSince_id(statuses.get(0).getId());
apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId());
@ -419,10 +420,6 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getLocalTL(max_id);
break;
case PMYVIDEOS:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getLocalTL(max_id);
break;
case PF_HOME:
api = new API(this.contextReference.get());
apiResponse = api.getHomeTimeline(max_id);
@ -506,7 +503,6 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
POVERVIEW,
PTRENDING,
PRECENTLYADDED,
PMYVIDEOS,
PLOCAL,
CHANNEL,
MYVIDEOS,

View File

@ -57,6 +57,11 @@ public class RetrieveNotificationsCacheAsyncTask extends AsyncTask<Void, Void, V
apiResponse = new APIResponse();
apiResponse.setNotifications(notifications);
if (notifications != null && notifications.size() > 0) {
for (Notification notification : notifications) {
if (notification.getStatus() != null) {
app.fedilab.android.client.Entities.Status.fillSpan(contextReference, notification.getStatus());
}
}
apiResponse.setMax_id(notifications.get(notifications.size() - 1).getId());
}
return null;

File diff suppressed because it is too large Load Diff

View File

@ -78,7 +78,6 @@ 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;

View File

@ -47,7 +47,6 @@ import com.bumptech.glide.request.transition.Transition;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
@ -139,7 +138,7 @@ public class Account implements Parcelable {
private String invite_request;
private String created_by_application_id;
private String invited_by_account_id;
private boolean emojiFound = false;
private transient boolean emojiFound = false;
public Account() {
}
@ -200,63 +199,6 @@ public class Account implements Parcelable {
this.invited_by_account_id = in.readString();
}
public static void makeAccountNameEmoji(final WeakReference<Context> contextWeakReference, Account account) {
Context context = contextWeakReference.get();
if ((context instanceof Activity && ((Activity) context).isFinishing()) || account.getDisplay_name() == null)
return;
account.setDisplayNameSpan(new SpannableString(account.getDisplay_name()));
SpannableString displayNameSpan = account.getDisplayNameSpan();
if (displayNameSpan == null)
return;
final List<Emojis> emojis = account.getEmojis();
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
if (emojis != null && emojis.size() > 0) {
final int[] i = {0};
for (final Emojis emoji : emojis) {
try {
Glide.with(context)
.asDrawable()
.load(disableAnimatedEmoji ? emoji.getStatic_url() : emoji.getUrl())
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
final String targetedEmoji = ":" + emoji.getShortcode() + ":";
if (displayNameSpan.toString().contains(targetedEmoji)) {
//emojis can be used several times so we have to loop
for (int startPosition = -1; (startPosition = displayNameSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) {
final int endPosition = startPosition + targetedEmoji.length();
if (resource != null && endPosition <= displayNameSpan.toString().length() && endPosition >= startPosition) {
try {
resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context));
resource.setVisible(true, true);
ImageSpan imageSpan = new ImageSpan(resource);
displayNameSpan.setSpan(
imageSpan, startPosition,
endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
} catch (Exception ignored) {
}
return;
}
}
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
public int describeContents() {
@ -534,6 +476,9 @@ public class Account implements Parcelable {
}
public SpannableString getDisplayNameSpan() {
if (this.displayNameSpan == null) {
displayNameSpan = new SpannableString(display_name);
}
return displayNameSpan;
}
@ -723,7 +668,7 @@ public class Account implements Parcelable {
int startPositionTar = spannableString.toString().indexOf("@" + this.getMoved_to_account().getAcct());
int endPositionTar = startPositionTar + ("@" + this.getMoved_to_account().getAcct()).length();
final Account idTar = this.getMoved_to_account();
if (endPositionTar <= spannableString.toString().length() && endPositionTar >= startPositionTar)
if (startPositionTar >= 0 && endPositionTar <= spannableString.toString().length() && endPositionTar >= startPositionTar)
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -745,15 +690,14 @@ public class Account implements Parcelable {
return spannableString;
}
public void makeEmojisAccountProfile(final Context context, final OnRetrieveEmojiAccountInterface listener, Account account) {
public void fillProfileAccount(final Context context, final OnRetrieveEmojiAccountInterface listener, Account account) {
if (context instanceof Activity && ((Activity) context).isFinishing())
return;
if (fields == null)
fields = new LinkedHashMap<>();
if (fieldsSpan == null)
fieldsSpan = new LinkedHashMap<>();
if (account.getDisplay_name() != null)
displayNameSpan = new SpannableString(account.getDisplay_name());
displayNameSpan = account.getDisplayNameSpan();
ArrayList<Account> accountsMentionUnknown = new ArrayList<>();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
@ -801,7 +745,7 @@ public class Account implements Parcelable {
int matchStart = matcher.start(0);
int matchEnd = matcher.end();
final String url = fieldSpan.toString().substring(matchStart, matchEnd);
if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) {
if (matchStart >= 0 && matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) {
fieldSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -832,7 +776,7 @@ public class Account implements Parcelable {
int matchStart = matcher.start(0);
int matchEnd = matcher.end();
final String email = fieldSpan.toString().substring(matchStart, matchEnd);
if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) {
if (matchStart >= 0 && matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) {
fieldSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -865,7 +809,7 @@ public class Account implements Parcelable {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
final String tag = fieldSpan.toString().substring(matchStart, matchEnd);
if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart)
if (matchStart >= 0 && matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart)
fieldSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -935,7 +879,7 @@ public class Account implements Parcelable {
int matchStart = matcher.start(0);
int matchEnd = matcher.end();
final String url = fieldSpan.toString().substring(matchStart, matchEnd);
if (matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) {
if (matchStart >= 0 && matchEnd <= fieldSpan.toString().length() && matchEnd >= matchStart) {
fieldSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {

View File

@ -37,6 +37,7 @@ public class Attachment implements Parcelable {
}
};
private String id;
private int viewId;
private String type;
private String url;
private String remote_url;
@ -50,8 +51,17 @@ public class Attachment implements Parcelable {
}
public int getViewId() {
return viewId;
}
public void setViewId(int viewId) {
this.viewId = viewId;
}
protected Attachment(Parcel in) {
this.id = in.readString();
this.viewId = in.readInt();
this.type = in.readString();
this.url = in.readString();
this.remote_url = in.readString();
@ -142,6 +152,7 @@ public class Attachment implements Parcelable {
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeInt(this.viewId);
dest.writeString(this.type);
dest.writeString(this.url);
dest.writeString(this.remote_url);

View File

@ -500,10 +500,11 @@ public class ManageTimelines {
if (mPageReferenceMap != null) {
FragmentTransaction fragTransaction = ((MainActivity) context).getSupportFragmentManager().beginTransaction();
DisplayStatusFragment displayStatusFragment = (DisplayStatusFragment) mPageReferenceMap.get(tl.getPosition());
assert displayStatusFragment != null;
fragTransaction.detach(displayStatusFragment);
fragTransaction.attach(displayStatusFragment);
fragTransaction.commit();
if (displayStatusFragment != null) {
fragTransaction.detach(displayStatusFragment);
fragTransaction.attach(displayStatusFragment);
fragTransaction.commit();
}
}
}
});

View File

@ -74,6 +74,9 @@ public class PollOptions implements Parcelable {
}
public SpannableString getTitleSpan() {
if (titleSpan == null) {
titleSpan = new SpannableString(title);
}
return titleSpan;
}

View File

@ -52,11 +52,7 @@ import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import java.lang.ref.WeakReference;
@ -66,6 +62,7 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -87,7 +84,6 @@ import app.fedilab.android.helper.CustomQuoteSpan;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.helper.LongClickableSpan;
import app.fedilab.android.helper.ThemeHelper;
import app.fedilab.android.interfaces.OnRetrieveEmojiInterface;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
@ -145,17 +141,17 @@ public class Status implements Parcelable {
private Card card;
private String language;
private boolean isTranslated = false;
private boolean isEmojiFound = false;
private boolean isPollEmojiFound = false;
private boolean isImageFound = false;
private boolean isEmojiTranslateFound = false;
private transient boolean isEmojiFound = false;
private transient boolean isPollEmojiFound = false;
private transient boolean isImageFound = false;
private transient boolean isEmojiTranslateFound = false;
private boolean isTranslationShown = false;
private boolean isNew = false;
private boolean isVisible = true;
private boolean fetchMore = false;
private String content, contentCW, contentTranslated;
private SpannableString contentSpan, contentSpanCW, contentSpanTranslated;
private RetrieveFeedsAsyncTask.Type type;
private transient RetrieveFeedsAsyncTask.Type type;
private int itemViewType;
private String conversationId;
private boolean isExpanded = false;
@ -184,9 +180,9 @@ public class Status implements Parcelable {
private List<String> imageURL;
private int viewType;
private boolean isFocused = false;
private long db_id;
private boolean commentsFetched = false;
private List<Status> comments = new ArrayList<>();
private transient long db_id;
private transient boolean commentsFetched = false;
private transient List<Status> comments = new ArrayList<>();
public Status() {
}
@ -266,7 +262,6 @@ public class Status implements Parcelable {
public static void fillSpan(WeakReference<Context> contextWeakReference, Status status) {
Status.transform(contextWeakReference, status);
Status.makeEmojis(contextWeakReference, status);
Status.makeImage(contextWeakReference, status);
}
@ -310,31 +305,42 @@ public class Status implements Parcelable {
}
}
matcher = Helper.bibliogramPattern.matcher(content);
boolean bibliogram = sharedpreferences.getBoolean(Helper.SET_BIBLIOGRAM, false);
if (bibliogram) {
while (matcher.find()) {
final String bibliogram_directory = matcher.group(2);
String bibliogramHost = sharedpreferences.getString(Helper.SET_BIBLIOGRAM_HOST, Helper.DEFAULT_BIBLIOGRAM_HOST).toLowerCase();
content = content.replaceAll("https://" + Pattern.quote(matcher.group()), Matcher.quoteReplacement("https://" + bibliogramHost + bibliogram_directory));
content = content.replaceAll(">" + Pattern.quote(matcher.group()), Matcher.quoteReplacement(">" + bibliogramHost + bibliogram_directory));
}
}
matcher = Helper.ouichesPattern.matcher(content);
while (matcher.find()) {
Attachment attachment = new Attachment();
attachment.setType("audio");
String tag = matcher.group(1);
attachment.setId(tag);
if( tag == null){
continue;
}
attachment.setRemote_url("http://ouich.es/mp3/"+tag+".mp3");
attachment.setUrl("http://ouich.es/mp3/"+tag+".mp3");
if( status.getMedia_attachments() == null) {
status.setMedia_attachments(new ArrayList<>());
}
boolean alreadyAdded = false;
for(Attachment at: status.getMedia_attachments()){
if( tag.compareTo(at.getId()) == 0 ){
alreadyAdded = true;
break;
}
}
if( !alreadyAdded) {
status.getMedia_attachments().add(attachment);
}
Attachment attachment = new Attachment();
attachment.setType("audio");
String tag = matcher.group(1);
attachment.setId(tag);
if (tag == null) {
continue;
}
attachment.setRemote_url("http://ouich.es/mp3/" + tag + ".mp3");
attachment.setUrl("http://ouich.es/mp3/" + tag + ".mp3");
if (status.getMedia_attachments() == null) {
status.setMedia_attachments(new ArrayList<>());
}
boolean alreadyAdded = false;
for (Attachment at : status.getMedia_attachments()) {
if (tag.compareTo(at.getId()) == 0) {
alreadyAdded = true;
break;
}
}
if (!alreadyAdded) {
status.getMedia_attachments().add(attachment);
}
}
Pattern aLink = Pattern.compile("<a((?!href).)*href=\"([^\"]*)\"[^>]*(((?!</a).)*)</a>");
@ -409,9 +415,10 @@ public class Status implements Parcelable {
Matcher matcher;
Pattern linkPattern = Pattern.compile("<a((?!href).)*href=\"([^\"]*)\"[^>]*(((?!</a).)*)</a>");
matcher = linkPattern.matcher(spannableString);
HashMap<String, String> targetedURL = new HashMap<>();
LinkedHashMap<String, String> targetedURL = new LinkedHashMap<>();
HashMap<String, Account> accountsMentionUnknown = new HashMap<>();
String liveInstance = Helper.getLiveInstance(context);
int i = 1;
while (matcher.find()) {
String key;
@ -422,14 +429,14 @@ public class Status implements Parcelable {
key = key.substring(1);
if (!key.startsWith("#") && !key.startsWith("@") && !key.trim().equals("") && !Objects.requireNonNull(matcher.group(2)).contains("search?tag=") && !Objects.requireNonNull(matcher.group(2)).contains(liveInstance + "/users/")) {
String url;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
url = Html.fromHtml(matcher.group(2), Html.FROM_HTML_MODE_LEGACY).toString();
} else {
url = Html.fromHtml(matcher.group(2)).toString();
}
targetedURL.put(key, url);
targetedURL.put(key + "|" + i, url);
i++;
} else if (key.startsWith("@") || Objects.requireNonNull(matcher.group(2)).contains(liveInstance + "/users/")) {
String acct;
String url;
@ -489,11 +496,11 @@ public class Status implements Parcelable {
}
}
SpannableString spannableStringT;
SpannableStringBuilder spannableStringT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
spannableStringT = new SpannableString(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}", "&nbsp;&nbsp;"), Html.FROM_HTML_MODE_LEGACY));
spannableStringT = new SpannableStringBuilder(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}", "&nbsp;&nbsp;"), Html.FROM_HTML_MODE_LEGACY));
else
spannableStringT = new SpannableString(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}", "&nbsp;&nbsp;")));
spannableStringT = new SpannableStringBuilder(Html.fromHtml(spannableString.toString().replaceAll("[\\s]{2}", "&nbsp;&nbsp;")));
replaceQuoteSpans(context, spannableStringT);
URLSpan[] spans = spannableStringT.getSpans(0, spannableStringT.length(), URLSpan.class);
for (URLSpan span : spans) {
@ -513,7 +520,7 @@ public class Status implements Parcelable {
int matchStart = matcher.start(2);
int matchEnd = matcher.end();
final String twittername = matcher.group(2);
if (matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart)
if (matchStart >= 0 && matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart)
spannableStringT.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -541,11 +548,11 @@ public class Status implements Parcelable {
}
if (accountsMentionUnknown.size() > 0) {
Iterator it = accountsMentionUnknown.entrySet().iterator();
Iterator<Map.Entry<String, Account>> it = accountsMentionUnknown.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
String key = (String) pair.getKey();
Account account = (Account) pair.getValue();
Map.Entry<String, Account> pair = it.next();
String key = pair.getKey();
Account account = pair.getValue();
String targetedAccount = "@" + account.getAcct();
if (spannableStringT.toString().toLowerCase().contains(targetedAccount.toLowerCase())) {
@ -558,11 +565,11 @@ public class Status implements Parcelable {
if (ssb.length() >= endPosition) {
ssb.replace(startPosition, endPosition, key);
}
spannableStringT = SpannableString.valueOf(ssb);
spannableStringT = SpannableStringBuilder.valueOf(ssb);
endPosition = startPosition + key.length();
}
//Accounts can be mentioned several times so we have to loop
if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition)
if (startPosition >= 0 && endPosition <= spannableStringT.toString().length() && endPosition >= startPosition)
spannableStringT.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -591,177 +598,181 @@ public class Status implements Parcelable {
}
}
if (targetedURL.size() > 0) {
Iterator it = targetedURL.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = targetedURL.entrySet().iterator();
int endPosition = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
String key = (String) pair.getKey();
String url = (String) pair.getValue();
Map.Entry<String, String> pair = it.next();
String key = (pair.getKey()).split("\\|")[0];
String url = pair.getValue();
if (spannableStringT.toString().toLowerCase().contains(key.toLowerCase())) {
//Accounts can be mentioned several times so we have to loop
int startPosition = spannableStringT.toString().toLowerCase().indexOf(key.toLowerCase());
int endPosition = startPosition + key.length();
if (key.contains("") && !key.endsWith("")) {
key = key.split("")[0] + "";
SpannableStringBuilder ssb = new SpannableStringBuilder();
ssb.append(spannableStringT, 0, spannableStringT.length());
if (ssb.length() >= endPosition) {
ssb.replace(startPosition, endPosition, key);
}
spannableStringT = SpannableString.valueOf(ssb);
int startPosition = spannableStringT.toString().toLowerCase().indexOf(key.toLowerCase(), endPosition);
if (startPosition >= 0) {
endPosition = startPosition + key.length();
}
if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) {
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]+)?$");
Matcher matcherLink = link.matcher(url);
if (matcherLink.find() && !url.contains("medium.com")) {
if (matcherLink.group(3) != null && Objects.requireNonNull(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);
if (key.contains("") && !key.endsWith("")) {
key = key.split("")[0] + "";
SpannableStringBuilder ssb = new SpannableStringBuilder();
ssb.append(spannableStringT, 0, spannableStringT.length());
if (ssb.length() >= endPosition) {
ssb.replace(startPosition, endPosition, key);
}
spannableStringT = SpannableStringBuilder.valueOf(ssb);
endPosition = startPosition + key.length();
}
if (endPosition <= spannableStringT.toString().length() && endPosition >= startPosition) {
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]+)?$");
Matcher matcherLink = link.matcher(url);
if (matcherLink.find() && !url.contains("medium.com")) {
if (matcherLink.group(3) != null && Objects.requireNonNull(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", Objects.requireNonNull(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);
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", Objects.requireNonNull(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);
}
}
}
}
@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(item -> {
switch (item.getItemId()) {
case R.id.action_show_link:
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, (dialog, 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 = () -> {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context, style);
if (response != null) {
builder1.setMessage(context.getString(R.string.redirect_detected, url, response));
builder1.setNegativeButton(R.string.copy_link, (dialog, which) -> {
ClipboardManager clipboard1 = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip1 = ClipData.newPlainText(Helper.CLIP_BOARD, response);
if (clipboard1 != null) {
clipboard1.setPrimaryClip(clip1);
Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
});
builder1.setNeutralButton(R.string.share_link, (dialog, which) -> {
Intent sendIntent1 = new Intent(Intent.ACTION_SEND);
sendIntent1.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via));
sendIntent1.putExtra(Intent.EXTRA_TEXT, url);
sendIntent1.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent1, context.getString(R.string.share_with)));
dialog.dismiss();
});
} else {
builder1.setMessage(R.string.no_redirect);
}
builder1.setTitle(context.getString(R.string.check_redirect));
builder1.setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss())
.show();
};
mainHandler.post(myRunnable);
@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(item -> {
switch (item.getItemId()) {
case R.id.action_show_link:
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, (dialog, 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();
}
};
thread.start();
break;
}
return true;
});
popup.setOnDismissListener(menu -> BaseActivity.canShowActionMode = true);
popup.show();
textView.clearFocus();
BaseActivity.canShowActionMode = false;
}
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 = () -> {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context, style);
if (response != null) {
builder1.setMessage(context.getString(R.string.redirect_detected, url, response));
builder1.setNegativeButton(R.string.copy_link, (dialog, which) -> {
ClipboardManager clipboard1 = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip1 = ClipData.newPlainText(Helper.CLIP_BOARD, response);
if (clipboard1 != null) {
clipboard1.setPrimaryClip(clip1);
Toasty.info(context, context.getString(R.string.clipboard_url), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
});
builder1.setNeutralButton(R.string.share_link, (dialog, which) -> {
Intent sendIntent1 = new Intent(Intent.ACTION_SEND);
sendIntent1.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.shared_via));
sendIntent1.putExtra(Intent.EXTRA_TEXT, url);
sendIntent1.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent1, context.getString(R.string.share_with)));
dialog.dismiss();
});
} else {
builder1.setMessage(R.string.no_redirect);
}
builder1.setTitle(context.getString(R.string.check_redirect));
builder1.setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss())
.show();
};
mainHandler.post(myRunnable);
}
};
thread.start();
break;
}
return true;
});
popup.setOnDismissListener(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);
@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();
}
@ -771,7 +782,7 @@ public class Status implements Parcelable {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
final String tag = spannableStringT.toString().substring(matchStart, matchEnd);
if (matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart)
if (matchStart >= 0 && matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart)
spannableStringT.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -780,6 +791,7 @@ public class Status implements Parcelable {
Bundle b = new Bundle();
b.putString("tag", tag.substring(1));
intent.putExtras(b);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
@ -800,7 +812,7 @@ public class Status implements Parcelable {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
final String groupname = spannableStringT.toString().substring(matchStart, matchEnd);
if (matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart)
if (matchStart >= 0 && matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart)
spannableStringT.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -823,7 +835,17 @@ public class Status implements Parcelable {
}
}
return spannableStringT;
Pattern carriagePattern = Pattern.compile("(\\n)+$");
matcher = carriagePattern.matcher(spannableStringT);
while (matcher.find()) {
int matchStart = matcher.start();
int matchEnd = matcher.end();
if (matchStart >= 0 && matchEnd <= spannableStringT.toString().length() && matchEnd >= matchStart) {
spannableStringT.delete(matchStart, matchEnd);
}
}
return SpannableString.valueOf(spannableStringT);
}
public static void transformTranslation(Context context, Status status) {
@ -853,7 +875,7 @@ public class Status implements Parcelable {
int matchStart = matcherALink.start();
int matchEnd = matcherALink.end();
final String url = contentSpanTranslated.toString().substring(matcherALink.start(1), matcherALink.end(1));
if (matchEnd <= contentSpanTranslated.toString().length() && matchEnd >= matchStart)
if (matchStart >= 0 && matchEnd <= contentSpanTranslated.toString().length() && matchEnd >= matchStart)
contentSpanTranslated.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View textView) {
@ -877,148 +899,6 @@ public class Status implements Parcelable {
status.setContentSpanTranslated(contentSpanTranslated);
}
private static void makeEmojis(final WeakReference<Context> contextWeakReference, Status status) {
Context context = contextWeakReference.get();
if (context instanceof Activity && ((Activity) context).isFinishing())
return;
if (status.getReblog() != null && status.getReblog().getEmojis() == null)
return;
if (status.getReblog() == null && status.getEmojis() == null)
return;
final List<Emojis> emojis = status.getReblog() != null ? status.getReblog().getEmojis() : status.getEmojis();
SpannableString contentSpan = status.getContentSpan();
SpannableString contentSpanCW = status.getContentSpanCW();
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
if (emojis != null && emojis.size() > 0) {
final int[] i = {0};
for (final Emojis emoji : emojis) {
Glide.with(context)
.asDrawable()
.load(disableAnimatedEmoji ? emoji.getStatic_url() : emoji.getUrl())
.listener(new RequestListener<Drawable>() {
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
return false;
}
})
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
final String targetedEmoji = ":" + emoji.getShortcode() + ":";
if (contentSpan != null && contentSpan.toString().contains(targetedEmoji)) {
//emojis can be used several times so we have to loop
for (int startPosition = -1; (startPosition = contentSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) {
final int endPosition = startPosition + targetedEmoji.length();
if (resource != null && endPosition <= contentSpan.toString().length() && endPosition >= startPosition) {
ImageSpan imageSpan;
try {
resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context));
resource.setVisible(true, true);
imageSpan = new ImageSpan(resource);
contentSpan.setSpan(
imageSpan, startPosition,
endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
} catch (Exception ignored) {
}
}
}
}
if (contentSpanCW != null && contentSpanCW.toString().contains(targetedEmoji)) {
//emojis can be used several times so we have to loop
for (int startPosition = -1; (startPosition = contentSpanCW.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) {
final int endPosition = startPosition + targetedEmoji.length();
if (endPosition <= contentSpanCW.toString().length() && endPosition >= startPosition) {
ImageSpan imageSpan;
resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context));
resource.setVisible(true, true);
imageSpan = new ImageSpan(resource);
contentSpanCW.setSpan(
imageSpan, startPosition,
endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
}
}
public static void makeEmojiPoll(final WeakReference<Context> contextWeakReference, Poll poll) {
Context context = contextWeakReference.get();
if ((context instanceof Activity && ((Activity) context).isFinishing()) || poll == null || poll.getOptionsList() == null)
return;
final List<Emojis> emojis = poll.getEmojis();
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
int inc = 0;
for (PollOptions pollOption : poll.getOptionsList()) {
inc++;
SpannableString titleSpan = new SpannableString(pollOption.getTitle());
if (emojis != null && emojis.size() > 0) {
final int[] i = {0};
for (final Emojis emoji : emojis) {
Glide.with(context)
.asDrawable()
.load(disableAnimatedEmoji ? emoji.getStatic_url() : emoji.getUrl())
.listener(new RequestListener<Drawable>() {
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
return false;
}
})
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
final String targetedEmoji = ":" + emoji.getShortcode() + ":";
if (titleSpan.toString().contains(targetedEmoji)) {
//emojis can be used several times so we have to loop
for (int startPosition = -1; (startPosition = titleSpan.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) {
final int endPosition = startPosition + targetedEmoji.length();
if (endPosition <= titleSpan.toString().length() && endPosition >= startPosition) {
ImageSpan imageSpan;
resource.setBounds(0, 0, (int) Helper.convertDpToPixel(20, context), (int) Helper.convertDpToPixel(20, context));
resource.setVisible(true, true);
imageSpan = new ImageSpan(resource);
titleSpan.setSpan(
imageSpan, startPosition,
endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
pollOption.setTitleSpan(titleSpan);
}
}
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
}
}
}
private static void makeImage(final WeakReference<Context> contextWeakReference, Status status) {
Context context = contextWeakReference.get();
@ -1038,17 +918,6 @@ public class Status implements Parcelable {
Glide.with(context)
.asBitmap()
.load(imgURL)
.listener(new RequestListener<Bitmap>() {
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
return false;
}
})
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
@ -1083,79 +952,6 @@ public class Status implements Parcelable {
}
public static void makeEmojisTranslation(final Context context, final OnRetrieveEmojiInterface listener, Status status) {
if (context instanceof Activity && ((Activity) context).isFinishing())
return;
SpannableString spannableStringTranslated = null;
if (status.getContentTranslated() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
spannableStringTranslated = new SpannableString(Html.fromHtml(status.getContentTranslated(), Html.FROM_HTML_MODE_LEGACY));
else
spannableStringTranslated = new SpannableString(Html.fromHtml(status.getContentTranslated()));
}
final List<Emojis> emojis = status.getReblog() != null ? status.getReblog().getEmojis() : status.getEmojis();
if (emojis != null && emojis.size() > 0) {
final int[] i = {0};
for (final Emojis emoji : emojis) {
final SpannableString finalSpannableStringTranslated = spannableStringTranslated;
Glide.with(context)
.asBitmap()
.load(emoji.getUrl())
.listener(new RequestListener<Bitmap>() {
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
i[0]++;
if (i[0] == (emojis.size())) {
if (finalSpannableStringTranslated != null)
status.setContentSpanTranslated(finalSpannableStringTranslated);
listener.onRetrieveEmoji(status, true);
}
return false;
}
})
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
final String targetedEmoji = ":" + emoji.getShortcode() + ":";
if (finalSpannableStringTranslated != null && finalSpannableStringTranslated.toString().contains(targetedEmoji)) {
//emojis can be used several times so we have to loop
for (int startPosition = -1; (startPosition = finalSpannableStringTranslated.toString().indexOf(targetedEmoji, startPosition + 1)) != -1; startPosition++) {
final int endPosition = startPosition + targetedEmoji.length();
if (endPosition <= finalSpannableStringTranslated.toString().length() && endPosition >= startPosition)
finalSpannableStringTranslated.setSpan(
new ImageSpan(context,
Bitmap.createScaledBitmap(resource, (int) Helper.convertDpToPixel(20, context),
(int) Helper.convertDpToPixel(20, context), false)), startPosition,
endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
i[0]++;
if (i[0] == (emojis.size())) {
if (finalSpannableStringTranslated != null)
status.setContentSpanTranslated(finalSpannableStringTranslated);
status.setEmojiTranslateFound(true);
listener.onRetrieveEmoji(status, true);
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
}
}
private static void replaceQuoteSpans(Context context, Spannable spannable) {
QuoteSpan[] quoteSpans = spannable.getSpans(0, spannable.length(), QuoteSpan.class);
for (QuoteSpan quoteSpan : quoteSpans) {

View File

@ -212,14 +212,24 @@ public class GNUAPI {
return statuses;
}
/**
* Parse json response for unique status
*
* @param resobj JSONObject
* @return Status
*/
@SuppressWarnings("InfiniteRecursion")
private static Status parseStatuses(Context context, JSONObject resobj) {
return parseStatuses(context, resobj, true);
}
/**
* Parse json response for unique status
*
* @param resobj JSONObject
* @return Status
*/
private static Status parseStatuses(Context context, JSONObject resobj, boolean recursive) {
Status status = new Status();
try {
status.setId(resobj.get("id").toString());
@ -337,7 +347,9 @@ public class GNUAPI {
status.setMuted(false);
status.setPinned(false);
try {
status.setReblog(parseStatuses(context, resobj.getJSONObject("retweeted_status")));
if (recursive) {
status.setReblog(parseStatuses(context, resobj.getJSONObject("retweeted_status"), false));
}
} catch (Exception ignored) {
status.setReblog(null);
}
@ -1476,24 +1488,20 @@ public class GNUAPI {
case FAVOURITE:
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
action = "/favorites/create.json";
params = new HashMap<>();
params.put("id", targetedId);
} else {
action = "/friendica/activity/like.json";
params = new HashMap<>();
params.put("id", targetedId);
}
params = new HashMap<>();
params.put("id", targetedId);
break;
case UNFAVOURITE:
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
action = "/favorites/destroy.json";
params = new HashMap<>();
params.put("id", targetedId);
} else {
action = "/friendica/activity/unlike.json";
params = new HashMap<>();
params.put("id", targetedId);
}
params = new HashMap<>();
params.put("id", targetedId);
break;
case REBLOG:
action = String.format("/statuses/retweet/%s.json", targetedId);

View File

@ -11,6 +11,8 @@ import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.AppGlideModule;
import org.jetbrains.annotations.NotNull;
import java.io.InputStream;
/**
@ -27,7 +29,7 @@ public final class TLSLibraryGlideModule extends AppGlideModule {
}
@Override
public void applyOptions(Context context, GlideBuilder builder) {
public void applyOptions(@NotNull Context context, @NotNull GlideBuilder builder) {
}
}

View File

@ -147,10 +147,10 @@ public class HttpsConnection {
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
Iterator<Map.Entry<String, String>> it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
Map.Entry<String, String> pair = it.next();
params.put(pair.getKey(), pair.getValue());
it.remove();
}
}
@ -236,7 +236,7 @@ public class HttpsConnection {
httpsURLConnection.setInstanceFollowRedirects(false);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(this.instance));
httpsURLConnection.setRequestMethod("HEAD");
if (httpsURLConnection.getResponseCode() == 301) {
if (httpsURLConnection.getResponseCode() == 301 || httpsURLConnection.getResponseCode() == 302) {
Map<String, List<String>> map = httpsURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.toString().toLowerCase().startsWith("location")) {
@ -362,25 +362,25 @@ public class HttpsConnection {
public String post(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator<Map.Entry<String, String>> it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
params.put(pair.getKey(), 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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -429,25 +429,6 @@ public class HttpsConnection {
httpsURLConnection.getInputStream().close();
return response;
} else {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
@ -499,10 +480,12 @@ public class HttpsConnection {
String postJson(String urlConnection, int timeout, JsonObject jsonObject, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
URL url = new URL(urlConnection);
byte[] postDataBytes;
postDataBytes = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
if (urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
byte[] postDataBytes;
postDataBytes = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -553,9 +536,6 @@ public class HttpsConnection {
httpsURLConnection.getInputStream().close();
return response;
} else {
URL url = new URL(urlConnection);
byte[] postDataBytes = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
@ -812,9 +792,15 @@ public class HttpsConnection {
public InputStream getPicture(final String downloadUrl) {
URL url;
try {
url = new URL(downloadUrl);
} catch (MalformedURLException e) {
return null;
}
if (downloadUrl.startsWith("https://")) {
try {
URL url = new URL(downloadUrl);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -823,7 +809,7 @@ public class HttpsConnection {
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpsURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
if (responseCode >= 200 && responseCode < 400) {
// opens input stream from the HTTP connection
return httpsURLConnection.getInputStream();
}
@ -835,10 +821,8 @@ public class HttpsConnection {
httpsURLConnection.getInputStream().close();
} catch (Exception ignored) {
}
return null;
} else {
try {
URL url = new URL(downloadUrl);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
@ -846,7 +830,7 @@ public class HttpsConnection {
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
if (responseCode >= 200 && responseCode < 400) {
// opens input stream from the HTTP connection
return httpURLConnection.getInputStream();
}
@ -858,8 +842,8 @@ public class HttpsConnection {
httpURLConnection.getInputStream().close();
} catch (Exception ignored) {
}
return null;
}
return null;
}
private void uploadMedia(String urlConnection, InputStream avatar, InputStream header, String filename) {
@ -923,27 +907,27 @@ public class HttpsConnection {
@SuppressWarnings("SameParameterValue")
public String patch(String urlConnection, int timeout, HashMap<String, String> paramaters, InputStream avatar, String avatarName, InputStream header, String headerName, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator<Map.Entry<String, String>> it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
params.put(pair.getKey(), 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());
}
byte[] postDataBytes = (postData.toString()).getBytes(StandardCharsets.UTF_8);
if (urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = (postData.toString()).getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -1006,25 +990,6 @@ public class HttpsConnection {
httpsURLConnection.getInputStream().close();
return response;
} else {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = (postData.toString()).getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -1088,26 +1053,27 @@ public class HttpsConnection {
}
public String put(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if (urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator<Map.Entry<String, String>> it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
params.put(pair.getKey(), 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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (urlConnection.startsWith("https://")) {
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -1157,25 +1123,6 @@ public class HttpsConnection {
httpsURLConnection.getInputStream().close();
return response;
} else {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
@ -1228,26 +1175,27 @@ public class HttpsConnection {
}
public int delete(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if (urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator<Map.Entry<String, String>> it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
params.put(pair.getKey(), 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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (urlConnection.startsWith("https://")) {
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
@ -1292,25 +1240,6 @@ public class HttpsConnection {
throw new HttpsConnectionException(responseCode, error);
}
} else {
URL url = new URL(urlConnection);
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());
}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else

View File

@ -40,7 +40,7 @@ import static android.content.Context.MODE_PRIVATE;
* Created by Thomas on 03/10/2019
* Adapter for accounts and live notifications
*/
public class AccountLiveAdapter extends RecyclerView.Adapter {
public class AccountLiveAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Account> accounts;

View File

@ -47,6 +47,8 @@ import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnPostActionInterface;
import es.dmoral.toasty.Toasty;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 03/09/2017.
@ -125,6 +127,7 @@ public class AccountSearchDevAdapter extends BaseAdapter implements OnPostAction
}
} else {
holder.account_dn.setText(account.getDisplay_name());
makeEmojis(context, holder.account_dn, account.getDisplayNameSpan(), account.getEmojis());
holder.account_un.setText(account.getAcct());
holder.account_follow.hide();
}

View File

@ -36,12 +36,14 @@ import app.fedilab.android.client.Entities.AccountAdmin;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnRetrieveEmojiAccountInterface;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 19/06/2019.
* Adapter for account admins
*/
public class AccountsAdminListAdapter extends RecyclerView.Adapter implements OnRetrieveEmojiAccountInterface {
public class AccountsAdminListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnRetrieveEmojiAccountInterface {
private List<AccountAdmin> accountAdmins;
private Context context;
@ -74,8 +76,11 @@ public class AccountsAdminListAdapter extends RecyclerView.Adapter implements On
else if (account.getDisplay_name() != null) {
holder.account_dn.setText(account.getDisplay_name().replace("@", ""));
}
} else
} else {
holder.account_dn.setText(account.getDisplayNameSpan(), TextView.BufferType.SPANNABLE);
makeEmojis(context, holder.account_dn, account.getDisplayNameSpan(), account.getEmojis());
}
if (account.getDisplayNameSpan() == null || account.getDisplayNameSpan().toString().trim().equals("")) {
if (account.getDisplay_name() != null && !account.getDisplay_name().trim().equals(""))

View File

@ -50,12 +50,14 @@ import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnPostActionInterface;
import es.dmoral.toasty.Toasty;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 07/05/2017.
* Adapter for accounts asking a follow request
*/
public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implements OnPostActionInterface {
public class AccountsFollowRequestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface {
private List<Account> accounts;
private Context context;
@ -88,6 +90,7 @@ public class AccountsFollowRequestAdapter extends RecyclerView.Adapter implement
holder.btn_reject.setVisibility(View.GONE);
}
holder.account_dn.setText(account.getDisplay_name());
makeEmojis(context, holder.account_dn, account.getDisplayNameSpan(), account.getEmojis());
holder.account_un.setText(account.getAcct());
//Profile picture
Glide.with(holder.account_pp.getContext())

View File

@ -45,12 +45,14 @@ import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnListActionInterface;
import es.dmoral.toasty.Toasty;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 15/12/2017.
* Adapter for accounts in lists
*/
public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnListActionInterface {
public class AccountsInAListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnListActionInterface {
private List<Account> accounts;
private Context context;
@ -90,6 +92,7 @@ public class AccountsInAListAdapter extends RecyclerView.Adapter implements OnLi
holder.account_un.setText(account.getDisplay_name());
makeEmojis(context, holder.account_un, account.getDisplayNameSpan(), account.getEmojis());
holder.account_ac.setText(account.getAcct());
if (account.getDisplay_name().equals(account.getAcct()))
holder.account_ac.setVisibility(View.GONE);

View File

@ -60,24 +60,38 @@ import app.fedilab.android.sqlite.InstancesDAO;
import app.fedilab.android.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 27/04/2017.
* Adapter for accounts
*/
public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnRetrieveEmojiAccountInterface {
public class AccountsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface, OnRetrieveEmojiAccountInterface {
private List<Account> accounts;
private RetrieveAccountsAsyncTask.Type action;
private Context context;
private AccountsListAdapter accountsListAdapter;
private String targetedId;
private boolean crossAction;
public AccountsListAdapter(RetrieveAccountsAsyncTask.Type action, String targetedId, boolean crossAction, List<Account> accounts) {
this.accounts = accounts;
this.action = action;
this.accountsListAdapter = this;
this.targetedId = targetedId;
this.crossAction = crossAction;
}
public AccountsListAdapter(RetrieveAccountsAsyncTask.Type action, String targetedId, List<Account> accounts) {
this.accounts = accounts;
this.action = action;
this.accountsListAdapter = this;
this.targetedId = targetedId;
crossAction = false;
}
@ -172,8 +186,10 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA
holder.account_dn.setText(account.getDisplay_name());
else
holder.account_dn.setText(account.getUsername().replace("@", ""));
} else
} else {
holder.account_dn.setText(account.getDisplayNameSpan(), TextView.BufferType.SPANNABLE);
makeEmojis(context, holder.account_dn, account.getDisplayNameSpan(), account.getEmojis());
}
holder.account_un.setText(String.format("@%s", account.getUsername()));
holder.account_ac.setText(account.getAcct());
if (account.getUsername().equals(account.getAcct()))
@ -239,7 +255,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostA
});
if (action != RetrieveAccountsAsyncTask.Type.GROUPS) {
holder.account_pp.setOnClickListener(v -> {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || action != RetrieveAccountsAsyncTask.Type.CHANNELS) {
if (!crossAction && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || action != RetrieveAccountsAsyncTask.Type.CHANNELS)) {
//Avoid to reopen details about the current account
if (targetedId == null || !targetedId.equals(account.getId())) {
Intent intent = new Intent(context, ShowAccountActivity.class);

View File

@ -15,6 +15,7 @@ package app.fedilab.android.drawers;
* see <http://www.gnu.org/licenses>. */
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
@ -30,6 +31,7 @@ import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityOptionsCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
@ -58,13 +60,14 @@ import app.fedilab.android.sqlite.StatusCacheDAO;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 14/01/2019.
* Adapter for art drawer
*/
public class ArtListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface {
public class ArtListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface {
private static final int DISPLAYED_STATUS = 1;
private final int HIDDEN_STATUS = 0;
@ -173,9 +176,19 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction
else if (status.getMedia_attachments() != null && status.getMedia_attachments().size() > 0)
attachments.add(status.getMedia_attachments().get(0));
intent.putParcelableArrayListExtra("mediaArray", attachments);
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
b.putInt("position", 1);
intent.putExtras(b);
context.startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, holder.art_media, status.getMedia_attachments().get(0).getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
// start the new activity
context.startActivity(intent);
}
});
holder.art_author.setOnClickListener(v -> {
Intent intent = new Intent(context, ShowConversationActivity.class);
@ -185,9 +198,10 @@ public class ArtListAdapter extends RecyclerView.Adapter implements OnPostAction
context.startActivity(intent);
});
if (status.getAccount().getDisplayNameSpan() != null && status.getAccount().getDisplayNameSpan().toString().trim().length() > 0)
if (status.getAccount().getDisplayNameSpan() != null && status.getAccount().getDisplayNameSpan().toString().trim().length() > 0) {
holder.art_username.setText(status.getAccount().getDisplayNameSpan(), TextView.BufferType.SPANNABLE);
else
makeEmojis(context, holder.art_username, status.getAccount().getDisplayNameSpan(), status.getAccount().getEmojis());
} else
holder.art_username.setText(status.getAccount().getUsername());
holder.art_acct.setText(String.format("@%s", status.getAccount().getAcct()));

View File

@ -88,7 +88,9 @@ public class CustomEmojiAdapter extends BaseAdapter {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
emoji.setDrawable(resource);
imageView.setImageDrawable(emoji.getDrawable());
if (imageView != null && emoji.getDrawable() != null) {
imageView.setImageDrawable(emoji.getDrawable());
}
}
@Override

View File

@ -43,7 +43,7 @@ import es.dmoral.toasty.Toasty;
* Created by Thomas on 26/09/2018.
* Adapter for domains
*/
public class DomainsListAdapter extends RecyclerView.Adapter implements OnRetrieveDomainsInterface {
public class DomainsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnRetrieveDomainsInterface {
private List<String> domains;
private Context context;

View File

@ -35,7 +35,7 @@ import app.fedilab.android.helper.Helper;
* Created by Thomas on 19/12/2019.
* Adapter for identity proofs
*/
public class IdentityProofsAdapter extends RecyclerView.Adapter {
public class IdentityProofsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<IdentityProof> identityProofs;

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.os.Bundle;
@ -23,6 +24,7 @@ import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityOptionsCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
@ -43,7 +45,7 @@ import app.fedilab.android.client.Entities.Status;
* Adapter to display media related to status
*/
public class ImageAdapter extends RecyclerView.Adapter {
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Status> statuses;
@ -84,8 +86,17 @@ public class ImageAdapter extends RecyclerView.Adapter {
}
intent.putParcelableArrayListExtra("mediaArray", attachmentsTmp);
b.putInt("position", (viewHolder.getAdapterPosition() + 1));
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
intent.putExtras(b);
context.startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, holder.imageView, attachmentsTmp.get((viewHolder.getAdapterPosition())).getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
// start the new activity
context.startActivity(intent);
}
});
holder.imageView.setOnLongClickListener(v -> {
Intent intent = new Intent(context, ShowConversationActivity.class);

View File

@ -37,7 +37,7 @@ import app.fedilab.android.helper.Helper;
* Adapter to display instances
*/
public class InstancePeertubeRegAdapter extends RecyclerView.Adapter {
public class InstancePeertubeRegAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<InstanceReg> instanceRegs;
private LayoutInflater layoutInflater;

View File

@ -43,7 +43,7 @@ import app.fedilab.android.helper.Helper;
* Adapter to display instances
*/
public class InstanceRegAdapter extends RecyclerView.Adapter {
public class InstanceRegAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<InstanceReg> instanceRegs;
private LayoutInflater layoutInflater;

View File

@ -30,7 +30,10 @@ import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
@ -53,6 +56,7 @@ import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.preference.PreferenceManager;
@ -70,6 +74,8 @@ import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import app.fedilab.android.R;
import app.fedilab.android.activities.AccountReportActivity;
@ -111,6 +117,7 @@ import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static app.fedilab.android.activities.BaseMainActivity.social;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
@ -118,7 +125,7 @@ import static app.fedilab.android.activities.BaseMainActivity.social;
* Adapter for Status
*/
public class NotificationsListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnPostNotificationsActionInterface, OnRetrieveEmojiInterface, OnRetrieveEmojiAccountInterface, OnPollInterface, OnRetrieveImageInterface {
public class NotificationsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface, OnPostNotificationsActionInterface, OnRetrieveEmojiInterface, OnRetrieveEmojiAccountInterface, OnPollInterface, OnRetrieveImageInterface {
private final Object lock = new Object();
private Context context;
@ -261,7 +268,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
else
typeString = String.format("@%s %s", notification.getAccount().getUsername(), context.getString(R.string.notif_mention));
imgH = ContextCompat.getDrawable(context, R.drawable.ic_chat_bubble_outline);
if (notification.getStatus().getVisibility().equals("direct")) {
if (notification.getStatus() != null && notification.getStatus().getVisibility().equals("direct")) {
holder.main_container_trans.setVisibility(View.GONE);
} else {
holder.main_container_trans.setVisibility(View.VISIBLE);
@ -322,8 +329,10 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
if (notification.getAccount().getDisplayNameSpan() == null) {
holder.notification_type.setText(typeString);
notification.getAccount().setStored_displayname(notification.getAccount().getDisplay_name());
} else
holder.notification_type.setText(notification.getAccount().getDisplayNameSpan(), TextView.BufferType.SPANNABLE);
} else {
holder.notification_type.setText(typeString, TextView.BufferType.SPANNABLE);
makeEmojis(context, holder.notification_type, notification.getAccount().getDisplayNameSpan(), notification.getAccount().getEmojis());
}
if (imgH != null) {
DrawableCompat.setTint(imgH, ContextCompat.getColor(context, R.color.cyanea_accent));
@ -376,6 +385,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
holder.status_privacy.setContentDescription(context.getString(R.string.toot_visibility_tilte) + ": " + v);
});
holder.notification_status_content.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE);
makeEmojis(context, holder.notification_status_content, status.getContentSpan(), status.getEmojis());
holder.status_spoiler.setText(status.getContentSpanCW(), TextView.BufferType.SPANNABLE);
holder.status_spoiler.setMovementMethod(LinkMovementMethod.getInstance());
holder.notification_status_content.setMovementMethod(LinkMovementMethod.getInstance());
@ -539,8 +549,9 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
TextView poll_item_percent = item.findViewById(R.id.poll_item_percent);
TextView poll_item_text = item.findViewById(R.id.poll_item_text);
ProgressBar poll_item_value = item.findViewById(R.id.poll_item_value);
poll_item_percent.setText(String.format("%s %%", String.valueOf((int) value)));
poll_item_percent.setText(String.format("%s %%", (int) value));
poll_item_text.setText(pollOption.getTitle(), TextView.BufferType.SPANNABLE);
makeEmojis(context, poll_item_text, pollOption.getTitleSpan(), poll.getEmojis());
poll_item_value.setProgress((int) value);
holder.rated.addView(item);
if (pollOption.getVotes_count() == greaterValue) {
@ -564,6 +575,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
for (PollOptions pollOption : poll.getOptionsList()) {
CheckBox cb = new CheckBox(context);
cb.setText(pollOption.getTitle());
makeEmojis(context, cb, pollOption.getTitleSpan(), poll.getEmojis());
holder.multiple_choice.addView(cb);
}
holder.multiple_choice.setVisibility(View.VISIBLE);
@ -573,6 +585,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
for (PollOptions pollOption : poll.getOptionsList()) {
RadioButton rb = new RadioButton(context);
rb.setText(pollOption.getTitle());
makeEmojis(context, rb, pollOption.getTitleSpan(), poll.getEmojis());
holder.radio_group.addView(rb);
}
holder.single_choice.setVisibility(View.VISIBLE);
@ -742,7 +755,27 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
holder.notification_delete.setOnClickListener(v -> displayConfirmationNotificationDialog(notification));
holder.notification_account_username.setVisibility(View.GONE);
if (notification.getAccount() != null) {
SpannableString wordtoSpan = new SpannableString("@" + notification.getAccount().getAcct());
Pattern hashAcct = Pattern.compile("(@" + notification.getAccount().getAcct() + ")");
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);
}
Matcher matcherAcct = hashAcct.matcher(wordtoSpan);
while (matcherAcct.find()) {
int matchStart = matcherAcct.start(1);
int matchEnd = matcherAcct.end();
if (wordtoSpan.length() >= matchEnd && matchStart < matchEnd) {
wordtoSpan.setSpan(new ForegroundColorSpan(theme_text_header_2_line), matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
holder.notification_account_username.setText(wordtoSpan);
}
final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
final View attached = holder.status_more;
@ -1046,13 +1079,12 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
* @param notification Notification
*/
private void displayConfirmationNotificationDialog(final Notification notification) {
final ArrayList seletedItems = new ArrayList();
final ArrayList<Integer> seletedItems = new ArrayList<>();
AlertDialog dialog = new AlertDialog.Builder(context, style)
.setTitle(R.string.delete_notification_ask)
.setMultiChoiceItems(new String[]{context.getString(R.string.delete_notification_ask_all)}, null, (dialog1, indexSelected, isChecked) -> {
if (isChecked) {
//noinspection unchecked
seletedItems.add(indexSelected);
} else {
if (seletedItems.contains(indexSelected))
@ -1184,8 +1216,17 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On
Bundle b = new Bundle();
intent.putParcelableArrayListExtra("mediaArray", notification.getStatus().getMedia_attachments());
b.putInt("position", finalPosition);
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
intent.putExtras(b);
context.startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, imageView, notification.getStatus().getMedia_attachments().get(finalPosition - 1).getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
// start the new activity
context.startActivity(intent);
}
});
i++;
position++;

View File

@ -55,7 +55,7 @@ import app.fedilab.android.interfaces.OnListActionInterface;
* Created by Thomas on 06/10/2018.
* Adapter for peertube
*/
public class PeertubeAdapter extends RecyclerView.Adapter implements OnListActionInterface {
public class PeertubeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnListActionInterface {
private List<Peertube> peertubes;
private Context context;

View File

@ -48,7 +48,7 @@ import app.fedilab.android.helper.Helper;
* Adapter for Peertube notifications
*/
public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter {
public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<PeertubeNotification> notifications;

View File

@ -47,6 +47,7 @@ import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityOptionsCompat;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -120,7 +121,7 @@ import static app.fedilab.android.activities.BaseMainActivity.social;
* Created by Thomas on 14/01/2019.
* Adapter for pixelfed drawer
*/
public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnRetrieveEmojiInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveSearcAccountshInterface, OnRetrieveContextInterface, OnRetrieveFeedsInterface {
public class PixelfedListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface, OnRetrieveEmojiInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveSearcAccountshInterface, OnRetrieveContextInterface, OnRetrieveFeedsInterface {
private static final int DISPLAYED_STATUS = 1;
private final int HIDDEN_STATUS = 0;
@ -397,8 +398,17 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
Bundle b = new Bundle();
intent.putParcelableArrayListExtra("mediaArray", status.getMedia_attachments());
b.putInt("position", 1);
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
intent.putExtras(b);
context.startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, holder.art_media, status.getMedia_attachments().get(0).getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
// start the new activity
context.startActivity(intent);
}
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
@ -458,7 +468,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
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);
String content = TootActivity.manageMentions(userId, status.getReblog() != null ? status.getReblog() : status);
TextWatcher textWatcher = PixelfedComposeActivity.initializeTextWatcher(context, social, holder.quick_reply_text, holder.toot_space_left, null, null, PixelfedListAdapter.this, PixelfedListAdapter.this, PixelfedListAdapter.this);
holder.quick_reply_text.addTextChangedListener(textWatcher);
holder.quick_reply_text.setText(content);
@ -510,12 +520,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
ownerTootVisibility = 1;
break;
}
int tootVisibility;
if (ownerTootVisibility >= initialTootVisibility) {
tootVisibility = initialTootVisibility;
} else {
tootVisibility = ownerTootVisibility;
}
int tootVisibility = Math.min(ownerTootVisibility, initialTootVisibility);
switch (tootVisibility) {
case 4:
visibility = "public";
@ -1062,7 +1067,7 @@ public class PixelfedListAdapter extends RecyclerView.Adapter implements OnPostA
status.setTranslationShown(true);
status.setContentTranslated(translate.getTranslatedContent());
Status.transformTranslation(context, status);
Status.makeEmojisTranslation(context, PixelfedListAdapter.this, status);
//makeEmojis(context, view, status.getContentSpan(), status.getReblog()!=null?status.getReblog().getEmojis():status.getEmojis());
notifyStatusChanged(status);
} else {
Toasty.error(context, context.getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show();

View File

@ -28,6 +28,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
@ -56,7 +57,7 @@ import app.fedilab.android.helper.Helper;
* Created by Thomas on 02/11/2019.
* Adapter for pixelfed stories drawer
*/
public class PixelfedStoriesListAdapter extends RecyclerView.Adapter {
public class PixelfedStoriesListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int DISPLAYED_STATUS = 1;
private Context context;
@ -134,8 +135,17 @@ public class PixelfedStoriesListAdapter extends RecyclerView.Adapter {
Bundle b = new Bundle();
intent.putParcelableArrayListExtra("mediaArray", attachments);
b.putInt("position", 1);
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
intent.putExtras(b);
context.startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, holder.art_media, attachments.get(0).getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
// start the new activity
context.startActivity(intent);
}
});

View File

@ -46,7 +46,7 @@ import app.fedilab.android.interfaces.OnPostActionInterface;
* Created by Thomas on 10/03/2020.
* Adapter for reactions on messages
*/
public class ReactionAdapter extends RecyclerView.Adapter implements OnPostActionInterface {
public class ReactionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface {
private List<Reaction> reactions;
private RetrieveFeedsAsyncTask.Type type;

View File

@ -41,7 +41,7 @@ import app.fedilab.android.interfaces.OnRetrieveEmojiAccountInterface;
* Created by Thomas on 19/06/2019.
* Adapter for reports
*/
public class ReportsListAdapter extends RecyclerView.Adapter implements OnRetrieveEmojiAccountInterface {
public class ReportsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnRetrieveEmojiAccountInterface {
private List<Report> reports;
private Context context;

View File

@ -151,20 +151,21 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi
Helper.changeDrawableColor(context, R.drawable.ic_mail_outline, R.color.action_light);
}
switch (status.getVisibility()) {
case "public":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_public);
break;
case "unlisted":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_lock_open);
break;
case "private":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_lock_outline);
break;
case "direct":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_mail_outline);
break;
}
if (status.getVisibility() != null)
switch (status.getVisibility()) {
case "public":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_public);
break;
case "unlisted":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_lock_open);
break;
case "private":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_lock_outline);
break;
case "direct":
holder.scheduled_toot_privacy.setImageResource(R.drawable.ic_mail_outline);
break;
}
final SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
int style;
if (theme == Helper.THEME_DARK) {
@ -374,7 +375,7 @@ public class ScheduledTootsListAdapter extends BaseAdapter implements OnPostActi
holder.scheduled_toot_container.setOnClickListener(v -> {
Intent intentToot = new Intent(context, TootActivity.class);
Bundle b = new Bundle();
if (storedStatus.getStatus().getSpoiler_text().equals("null"))
if (storedStatus.getStatus().getSpoiler_text() != null && storedStatus.getStatus().getSpoiler_text().equals("null"))
storedStatus.getStatus().setSpoiler_text("");
b.putParcelable("storedStatus", storedStatus);
intentToot.putExtras(b);

View File

@ -36,6 +36,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityOptionsCompat;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
@ -107,8 +108,17 @@ public class SliderAdapter extends SliderViewAdapter<SliderAdapter.SliderAdapter
intent.putParcelableArrayListExtra("mediaArray", attachments);
b.putInt("position", (position + 1));
b.putInt("bgcolor", contextWeakReference.get().getResources().getColor(R.color.cyanea_primary_dark));
intent.putExtras(b);
contextWeakReference.get().startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) contextWeakReference.get(), viewHolder.imageViewBackground, attachments.get((position)).getUrl());
// start the new activity
contextWeakReference.get().startActivity(intent, options.toBundle());
} else {
// start the new activity
contextWeakReference.get().startActivity(intent);
}
});
} else {
viewHolder.imageViewBackground.setOnClickListener(v -> showAddDescription(attachments.get(position)));
@ -140,7 +150,7 @@ public class SliderAdapter extends SliderViewAdapter<SliderAdapter.SliderAdapter
//Text for report
final EditText input = popup_media_description.findViewById(R.id.media_description);
input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(420)});
input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1500)});
final ImageView media_picture = popup_media_description.findViewById(R.id.media_picture);
Glide.with(contextWeakReference.get())
.asBitmap()

View File

@ -51,8 +51,6 @@ import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
@ -78,6 +76,7 @@ import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.SwitchCompat;
import androidx.appcompat.widget.TooltipCompat;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
@ -182,7 +181,6 @@ import app.fedilab.android.sqlite.StatusStoredDAO;
import app.fedilab.android.sqlite.TempMuteDAO;
import app.fedilab.android.sqlite.TimelineCacheDAO;
import app.fedilab.android.sqlite.TimelinesDAO;
import app.fedilab.android.webview.CustomWebview;
import es.dmoral.toasty.Toasty;
import jp.wasabeef.glide.transformations.BlurTransformation;
@ -191,13 +189,15 @@ import static android.content.Context.MODE_PRIVATE;
import static app.fedilab.android.activities.BaseMainActivity.mPageReferenceMap;
import static app.fedilab.android.activities.BaseMainActivity.mutedAccount;
import static app.fedilab.android.activities.BaseMainActivity.social;
import static app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE_FILTERED;
import static app.fedilab.android.helper.Helper.makeEmojis;
/**
* Created by Thomas on 24/04/2017.
* Adapter for Status
*/
public class StatusListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnRetrieveFeedsInterface, OnRetrieveImageInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface, OnRetrieveCardInterface, OnPollInterface, OnRefreshCachedStatusInterface, OnRetrieveSearcAccountshInterface, OnRetrieveSearchInterface, OnPostStatusActionInterface, OnRetrieveRelationshipQuickReplyInterface, OnSyncBookmarksInterface {
public class StatusListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnPostActionInterface, OnRetrieveFeedsInterface, OnRetrieveImageInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface, OnRetrieveCardInterface, OnPollInterface, OnRefreshCachedStatusInterface, OnRetrieveSearcAccountshInterface, OnRetrieveSearchInterface, OnPostStatusActionInterface, OnRetrieveRelationshipQuickReplyInterface, OnSyncBookmarksInterface {
public static final int DISPLAYED_STATUS = 1;
public static final int COMPACT_STATUS = 3;
@ -480,6 +480,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
public void onPostStatusAction(APIResponse apiResponse) {
if (apiResponse.getError() != null) {
Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_SHORT).show();
storeToot();
return;
}
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
@ -487,7 +488,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
String instance = Helper.getLiveInstance(context);
boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false);
if (split_toot && splitToot != null && stepSpliToot < splitToot.size()) {
String tootContent = splitToot.get(stepSpliToot);
stepSpliToot += 1;
@ -755,8 +755,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
TextView poll_item_percent = item.findViewById(R.id.poll_item_percent);
TextView poll_item_text = item.findViewById(R.id.poll_item_text);
ProgressBar poll_item_value = item.findViewById(R.id.poll_item_value);
poll_item_percent.setText(String.format("%s %%", String.valueOf((int) value)));
poll_item_text.setText(pollOption.getTitle(), TextView.BufferType.SPANNABLE);
poll_item_percent.setText(String.format("%s %%", (int) value));
poll_item_text.setText(pollOption.getTitleSpan(), TextView.BufferType.SPANNABLE);
poll_item_text.setText(pollOption.getTitle());
makeEmojis(context, poll_item_text, pollOption.getTitleSpan(), poll.getEmojis());
poll_item_value.setProgress((int) value);
holder.rated.addView(item);
if (pollOption.getVotes_count() == greaterValue) {
@ -780,11 +782,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
(holder.multiple_choice).removeAllViews();
for (PollOptions pollOption : poll.getOptionsList()) {
CheckBox cb = new CheckBox(context);
if (pollOption.getTitleSpan() != null) {
cb.setText(pollOption.getTitleSpan(), TextView.BufferType.SPANNABLE);
} else {
cb.setText(pollOption.getTitle());
}
cb.setText(pollOption.getTitle());
makeEmojis(context, cb, pollOption.getTitleSpan(), poll.getEmojis());
holder.multiple_choice.addView(cb);
}
@ -795,11 +794,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
(holder.radio_group).removeAllViews();
for (PollOptions pollOption : poll.getOptionsList()) {
RadioButton rb = new RadioButton(context);
if (pollOption.getTitleSpan() != null) {
rb.setText(pollOption.getTitleSpan(), TextView.BufferType.SPANNABLE);
} else {
rb.setText(pollOption.getTitle());
}
rb.setText(pollOption.getTitle());
makeEmojis(context, rb, pollOption.getTitleSpan(), poll.getEmojis());
holder.radio_group.addView(rb);
}
holder.single_choice.setVisibility(View.VISIBLE);
@ -857,6 +853,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
holder.status_action_container.setVisibility(View.GONE);
holder.fedilab_features.setVisibility(View.GONE);
holder.status_peertube_container.setVisibility(View.VISIBLE);
holder.status_peertube_reply.setOnClickListener(v -> {
AlertDialog.Builder builderInner;
@ -982,15 +979,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.status_spoiler.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (14 * textSizePercent) / 100);
switch (translator) {
case Helper.TRANS_NONE:
holder.yandex_translate.setVisibility(View.GONE);
break;
case Helper.TRANS_YANDEX:
holder.yandex_translate.setVisibility(View.VISIBLE);
break;
default:
holder.yandex_translate.setVisibility(View.GONE);
if (translator == Helper.TRANS_YANDEX) {
holder.yandex_translate.setVisibility(View.VISIBLE);
} else {
holder.yandex_translate.setVisibility(View.GONE);
}
//Manages theme for icon colors
@ -1228,7 +1220,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
TooltipCompat.setTooltipText(holder.custom_feature_translate, context.getString(R.string.translate));
holder.custom_feature_translate.setOnClickListener(view -> {
translateToot(status);
translateToot(status, holder.status_content_translated);
status.setCustomFeaturesDisplayed(false);
notifyStatusChanged(status);
});
@ -1323,11 +1315,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
assert img != null;
img.setBounds(0, 0, (int) (20 * iconSizePercent / 100 * scale + 0.5f), (int) (15 * iconSizePercent / 100 * scale + 0.5f));
holder.status_account_displayname.setCompoundDrawables(img, null, null, null);
holder.status_toot_date.setCompoundDrawables(imgConversation, null, null, null);
} else {
holder.status_account_displayname.setCompoundDrawables(null, null, null, null);
holder.status_toot_date.setCompoundDrawables(imgConversation, null, null, null);
}
holder.status_toot_date.setCompoundDrawables(imgConversation, null, null, null);
if (expand_media && status.isSensitive() || (status.getReblog() != null && status.getReblog().isSensitive())) {
Helper.changeDrawableColor(context, holder.hide_preview, R.color.red_1);
Helper.changeDrawableColor(context, holder.hide_preview_h, R.color.red_1);
@ -1407,7 +1398,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
});
holder.status_content.setOnClickListener(v -> {
if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != RetrieveFeedsAsyncTask.Type.NEWS) {
if (type != RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE && type != REMOTE_INSTANCE_FILTERED && type != RetrieveFeedsAsyncTask.Type.NEWS) {
Intent intent = new Intent(context, ShowConversationActivity.class);
Bundle b = new Bundle();
if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
@ -1560,6 +1551,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.status_content.setText(status.getContentSpan(), TextView.BufferType.SPANNABLE);
holder.status_spoiler.setText(status.getContentSpanCW(), TextView.BufferType.SPANNABLE);
}
makeEmojis(context, holder.status_content, status.getContentSpan(), status.getReblog() != null ? status.getReblog().getEmojis() : status.getEmojis());
holder.status_content.setMovementMethod(LongClickLinkMovementMethod.getInstance());
@ -1612,10 +1604,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
context.startActivity(intent);
});
if (status.getReblog().getAccount().getDisplay_name().length() > 0)
if (status.getReblog().getAccount().getDisplay_name().length() > 0) {
holder.status_account_displayname_owner.setText(displayNameSpan, TextView.BufferType.SPANNABLE);
else
makeEmojis(context, holder.status_account_displayname_owner, status.getReblog().getAccount().getDisplayNameSpan(), status.getReblog().getAccount().getEmojis());
} 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()));
@ -1623,10 +1617,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
} else {
accountForUrl = status.getAccount();
holder.status_account_displayname.setVisibility(View.GONE);
if (displayNameSpan == null || displayNameSpan.toString().trim().length() == 0)
if (displayNameSpan == null || displayNameSpan.toString().trim().length() == 0) {
holder.status_account_displayname_owner.setText(status.getAccount().getUsername().replace("@", ""), TextView.BufferType.SPANNABLE);
else
} else {
holder.status_account_displayname_owner.setText(displayNameSpan, TextView.BufferType.SPANNABLE);
makeEmojis(context, holder.status_account_displayname_owner, displayNameSpan, status.getAccount().getEmojis());
}
}
//-------- END -> Displays name & emoji in toot header
@ -1703,6 +1699,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
holder.fetch_more.setVisibility(View.GONE);
}
if (type == RetrieveFeedsAsyncTask.Type.CONTEXT) {
holder.fetch_more.setVisibility(View.GONE);
}
if (status.getMentions() != null)
holder.status_mention_spoiler.setText(Helper.makeMentionsClick(context, status.getMentions()), TextView.BufferType.SPANNABLE);
@ -2143,33 +2142,17 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (status.getReblog() == null) {
if (status.getWebviewURL() != null) {
String url = status.getWebviewURL().replaceAll("&amp;", "&");
try {
holder.status_cardview_webview.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
holder.status_cardview_webview.setVisibility(View.VISIBLE);
holder.status_cardview_video.setVisibility(View.VISIBLE);
holder.webview_preview.setVisibility(View.GONE);
} else {
holder.status_cardview_webview.setVisibility(View.GONE);
holder.status_cardview_video.setVisibility(View.GONE);
holder.webview_preview.setVisibility(View.VISIBLE);
}
} else {
if (status.getReblog().getWebviewURL() != null) {
String url = status.getReblog().getWebviewURL().replaceAll("&amp;", "&");
try {
holder.status_cardview_webview.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
holder.status_cardview_webview.setVisibility(View.VISIBLE);
holder.status_cardview_video.setVisibility(View.VISIBLE);
holder.webview_preview.setVisibility(View.GONE);
} else {
holder.status_cardview_webview.setVisibility(View.GONE);
holder.status_cardview_video.setVisibility(View.GONE);
holder.webview_preview.setVisibility(View.VISIBLE);
}
@ -2289,20 +2272,26 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
url = url.replaceAll("https://" + Pattern.quote(matcher.group()), Matcher.quoteReplacement("https://" + nitterHost + nitter_directory));
}
}
boolean bibliogram = sharedpreferences.getBoolean(Helper.SET_BIBLIOGRAM, false);
if (bibliogram) {
Matcher matcher = Helper.bibliogramPattern.matcher(url);
while (matcher.find()) {
final String bibliogram_directory = matcher.group(2);
String bibliogramHost = sharedpreferences.getString(Helper.SET_BIBLIOGRAM_HOST, Helper.DEFAULT_BIBLIOGRAM_HOST).toLowerCase();
url = url.replaceAll("https://" + Pattern.quote(matcher.group()), Matcher.quoteReplacement("https://" + bibliogramHost + bibliogram_directory));
}
}
Helper.openBrowser(context, url);
});
} else if (card.getType().toLowerCase().equals("video") && (display_video_preview || (type == RetrieveFeedsAsyncTask.Type.CONTEXT && viewHolder.getAdapterPosition() == conversationPosition))) {
Glide.with(holder.status_cardview_image.getContext())
.load(card.getImage())
.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(10)))
.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();
if (html != null) {
@ -2311,12 +2300,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
src = matcher.group(1);
}
final String finalSrc = src;
holder.status_cardview_webview.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
holder.status_cardview_video.setVisibility(View.GONE);
}
});
holder.webview_preview.setOnClickListener(v -> {
String url = finalSrc;
if (url != null) {
@ -2334,12 +2318,27 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
}
}
if (status.getReblog() == null) {
status.setWebviewURL(url);
Intent intent = new Intent(context, SlideMediaActivity.class);
Bundle b = new Bundle();
Attachment attachment = new Attachment();
attachment.setType("web");
attachment.setUrl(url);
attachment.setPreview_url(card.getImage());
ArrayList<Attachment> attachmentArrayList = new ArrayList<>();
attachmentArrayList.add(attachment);
intent.putParcelableArrayListExtra("mediaArray", attachmentArrayList);
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
b.putInt("position", 1);
intent.putExtras(b);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, holder.webview_preview, attachment.getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
status.getReblog().setWebviewURL(url);
// start the new activity
context.startActivity(intent);
}
notifyStatusChanged(status);
});
} else {
holder.status_cardview.setVisibility(View.GONE);
@ -2461,12 +2460,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
break;
}
}
int tootVisibility;
if (ownerTootVisibility >= initialTootVisibility) {
tootVisibility = initialTootVisibility;
} else {
tootVisibility = ownerTootVisibility;
}
int tootVisibility = Math.min(ownerTootVisibility, initialTootVisibility);
switch (tootVisibility) {
case 4:
@ -2660,6 +2654,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
CrossActions.doCrossAction(context, type, status, null, API.StatusAction.REBLOG, statusListAdapter, StatusListAdapter.this, false);
return true;
});
if (!status.getVisibility().equals("direct"))
holder.status_reply.setOnLongClickListener(view -> {
CrossActions.doCrossReply(context, status, type, false);
@ -2878,7 +2873,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (translator == Helper.TRANS_NONE)
Toasty.info(context, R.string.toast_error_translations_disabled, Toast.LENGTH_SHORT).show();
else
translateToot(status);
translateToot(status, holder.status_content_translated);
return true;
case R.id.action_report:
builderInner = new AlertDialog.Builder(context, style);
@ -3323,7 +3318,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
.asBitmap()
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.thumbnail(0.1f)
.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(10)))
//.dontTransform()
.apply(new RequestOptions().transform(new RoundedCorners(10)))
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
@ -3342,6 +3338,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)
// .dontTransform()
.apply(new RequestOptions().transform(new BlurTransformation(50, 3), new RoundedCorners(10)))
.into(new CustomTarget<Bitmap>() {
@Override
@ -3362,18 +3359,20 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
if (!blur) {
Glide.with(imageView.getContext())
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.dontTransform()
.thumbnail(0.1f)
// .override(640, 480)
.apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(10)))
// .transition(DrawableTransitionOptions.withCrossFade())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageView);
} else {
Glide.with(imageView.getContext())
.load(!attachment.getType().toLowerCase().equals("audio") ? url : R.drawable.ic_audio_wave)
.thumbnail(0.1f)
.dontTransform()
// .override(640, 480)
.apply(new RequestOptions().transform(new BlurTransformation(50, 3), new RoundedCorners(10)))
// .transition(DrawableTransitionOptions.withCrossFade())
.apply(new RequestOptions().transform(new CenterCrop(), new BlurTransformation(50, 3), new RoundedCorners(10)))
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageView);
}
}
@ -3395,9 +3394,19 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
Intent intent = new Intent(context, SlideMediaActivity.class);
Bundle b = new Bundle();
intent.putParcelableArrayListExtra("mediaArray", attachmentArrayList);
b.putInt("bgcolor", context.getResources().getColor(R.color.cyanea_primary_dark));
b.putInt("position", finalPosition);
intent.putExtras(b);
context.startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation((Activity) context, imageView, attachment.getUrl());
// start the new activity
context.startActivity(intent, options.toBundle());
} else {
// start the new activity
context.startActivity(intent);
}
}
} else {
status.setAttachmentShown(true);
@ -3871,11 +3880,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
@Override
public void onRetrieveImage(Status status, boolean fromTranslation) {
if (status != null) {
if (!fromTranslation) {
status.setImageFound(true);
} else {
status.setImageFound(true);
}
status.setImageFound(true);
notifyStatusChanged(status);
}
}
@ -3897,7 +3902,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
}
private void translateToot(Status status) {
private void translateToot(Status status, TextView view) {
//Manages translations
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int trans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX);
@ -3939,7 +3944,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
status.setTranslationShown(true);
status.setContentTranslated(translate.getTranslatedContent());
Status.transformTranslation(context, status);
Status.makeEmojisTranslation(context, StatusListAdapter.this, status);
makeEmojis(context, view, status.getContentSpan(), status.getReblog() != null ? status.getReblog().getEmojis() : status.getEmojis());
notifyStatusChanged(status);
} else {
Toasty.error(context, context.getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show();
@ -4067,7 +4072,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
ImageView status_cardview_image;
TextView status_cardview_title, status_cardview_content, status_cardview_url;
FrameLayout status_cardview_video;
CustomWebview status_cardview_webview;
ImageView hide_preview, hide_preview_h;
TextView status_toot_app;
RelativeLayout webview_preview;
@ -4181,8 +4185,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct
status_cardview_content = itemView.findViewById(R.id.status_cardview_content);
status_cardview_url = itemView.findViewById(R.id.status_cardview_url);
status_cardview_video = itemView.findViewById(R.id.status_cardview_video);
status_cardview_webview = Helper.initializeWebview((Activity) context, R.id.status_cardview_webview, itemView);
status_cardview_webview.getSettings().setJavaScriptEnabled(true);
hide_preview = itemView.findViewById(R.id.hide_preview);
hide_preview_h = itemView.findViewById(R.id.hide_preview_h);
status_toot_app = itemView.findViewById(R.id.status_toot_app);

View File

@ -35,7 +35,7 @@ import app.fedilab.android.helper.Helper;
* Created by Thomas on 19/07/2019.
* Adapter for suggestions results
*/
public class SuggestionsAdapter extends RecyclerView.Adapter {
public class SuggestionsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Suggestion> suggestions;

View File

@ -39,7 +39,7 @@ import es.dmoral.toasty.Toasty;
* Created by Thomas on 01/12/2018.
* Adapter for tags when editing
*/
public class TagsEditAdapter extends RecyclerView.Adapter {
public class TagsEditAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<String> tags;

View File

@ -110,8 +110,10 @@ public class TrendsAdapter extends BaseAdapter {
uses += _th.getUses();
tendency.put(_th.getDays(), _th.getUses());
}
people = people / days;
uses = uses / days;
if (days > 0) {
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()));
@ -126,10 +128,10 @@ public class TrendsAdapter extends BaseAdapter {
List<Entry> trendsEntry = new ArrayList<>();
Iterator it = tendency.entrySet().iterator();
Iterator<Map.Entry<Long, Integer>> 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()));
Map.Entry<Long, Integer> pair = it.next();
trendsEntry.add(0, new Entry(pair.getKey(), pair.getValue()));
it.remove();
}
LineDataSet dataTrending = new LineDataSet(trendsEntry, context.getString(R.string.trending));

View File

@ -266,7 +266,7 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
}
List<String> array = Arrays.asList(getResources().getStringArray(R.array.settings_theme));
CharSequence[] entries = array.toArray(new CharSequence[array.size()]);
CharSequence[] entries = array.toArray(new CharSequence[0]);
CharSequence[] entryValues = new CharSequence[3];
final SharedPreferences sharedpref = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpref.getInt(Helper.SET_THEME, Helper.THEME_DARK);
@ -275,7 +275,7 @@ public class ColorSettingsFragment extends PreferenceFragmentCompat implements S
entryValues[2] = String.valueOf(Helper.THEME_BLACK);
pref_theme_picker.setEntries(entries);
int default_theme_value;
switch (theme){
switch (theme) {
case Helper.THEME_LIGHT:
default_theme_value = 1;
break;

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