Remove asyncTask

This commit is contained in:
Thomas 2021-01-19 17:43:51 +01:00
parent 7e264d1f91
commit 92a96368c6
193 changed files with 4090 additions and 4369 deletions

View File

@ -87,7 +87,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
private int theme; private int theme;
private RelativeLayout loader; private RelativeLayout loader;
private ImageButton validate; private ImageButton validate;
private DatePickerDialog.OnDateSetListener iniDateSetListener = private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -99,7 +99,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
} }
}; };
private DatePickerDialog.OnDateSetListener endDateSetListener = private final DatePickerDialog.OnDateSetListener endDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -256,7 +256,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
chart.setVisibility(View.GONE); chart.setVisibility(View.GONE);
loader.setVisibility(View.VISIBLE); loader.setVisibility(View.VISIBLE);
validate.setEnabled(false); validate.setEnabled(false);
new RetrieveChartsAsyncTask(OwnerChartsActivity.this, dateIni, dateEnd, OwnerChartsActivity.this).execute(); new RetrieveChartsAsyncTask(OwnerChartsActivity.this, dateIni, dateEnd, OwnerChartsActivity.this);
} }
@ -396,7 +396,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
@SuppressLint("ViewConstructor") @SuppressLint("ViewConstructor")
public static class CustomMarkerView extends MarkerView { public static class CustomMarkerView extends MarkerView {
private TextView tvContent; private final TextView tvContent;
private MPPointF mOffset; private MPPointF mOffset;
public CustomMarkerView(Context context, int layoutResource) { public CustomMarkerView(Context context, int layoutResource) {
@ -423,8 +423,8 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
} }
public static class MyXAxisValueFormatter extends ValueFormatter { public static class MyXAxisValueFormatter extends ValueFormatter {
private DateFormat mDataFormat; private final DateFormat mDataFormat;
private Date mDate; private final Date mDate;
MyXAxisValueFormatter() { MyXAxisValueFormatter() {
this.mDataFormat = new SimpleDateFormat("dd.MM", Locale.getDefault()); this.mDataFormat = new SimpleDateFormat("dd.MM", Locale.getDefault());

View File

@ -100,7 +100,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
private Date dateIni, dateEnd; private Date dateIni, dateEnd;
private View statsDialogView; private View statsDialogView;
private StatisticsNotification statistics; private StatisticsNotification statistics;
private DatePickerDialog.OnDateSetListener iniDateSetListener = private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -112,7 +112,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
} }
}; };
private DatePickerDialog.OnDateSetListener endDateSetListener = private final DatePickerDialog.OnDateSetListener endDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -125,14 +125,14 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
} }
}; };
private BroadcastReceiver backupFinishedReceiver = new BroadcastReceiver() { private final BroadcastReceiver backupFinishedReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
max_id = null; max_id = null;
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).execute(); new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this);
} }
}; };
@ -221,13 +221,13 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
swipeRefreshLayout.setColorSchemeColors( swipeRefreshLayout.setColorSchemeColors(
c1, c2, c1 c1, c2, c1
); );
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).execute(); new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this);
swipeRefreshLayout.setOnRefreshListener(() -> { swipeRefreshLayout.setOnRefreshListener(() -> {
max_id = null; max_id = null;
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).execute(); new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this);
}); });
lv_notifications.addOnScrollListener(new RecyclerView.OnScrollListener() { lv_notifications.addOnScrollListener(new RecyclerView.OnScrollListener() {
@ -239,7 +239,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, max_id, OwnerNotificationActivity.this).execute(); new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, max_id, OwnerNotificationActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
} else { } else {
@ -288,7 +288,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
.setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss()); .setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss());
dialogBuilder.create().show(); dialogBuilder.create().show();
if (statistics == null) { if (statistics == null) {
new RetrieveNotificationStatsAsyncTask(OwnerNotificationActivity.this, OwnerNotificationActivity.this).execute(); new RetrieveNotificationStatsAsyncTask(OwnerNotificationActivity.this, OwnerNotificationActivity.this);
} else { } else {
displayStats(); displayStats();
} }
@ -375,7 +375,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).execute(); new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this);
dialog.dismiss(); dialog.dismiss();
}) })
.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());

View File

@ -90,7 +90,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
private RelativeLayout loader; private RelativeLayout loader;
private ImageButton validate; private ImageButton validate;
private String status_id; private String status_id;
private DatePickerDialog.OnDateSetListener iniDateSetListener = private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -102,7 +102,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
} }
}; };
private DatePickerDialog.OnDateSetListener endDateSetListener = private final DatePickerDialog.OnDateSetListener endDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -472,7 +472,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
chart.setVisibility(View.GONE); chart.setVisibility(View.GONE);
loader.setVisibility(View.VISIBLE); loader.setVisibility(View.VISIBLE);
validate.setEnabled(false); validate.setEnabled(false);
new RetrieveNotificationChartsAsyncTask(OwnerNotificationChartsActivity.this, status_id, dateIni, dateEnd, OwnerNotificationChartsActivity.this).execute(); new RetrieveNotificationChartsAsyncTask(OwnerNotificationChartsActivity.this, status_id, dateIni, dateEnd, OwnerNotificationChartsActivity.this);
} }
@ -483,7 +483,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
@SuppressLint("ViewConstructor") @SuppressLint("ViewConstructor")
public static class CustomMarkerView extends MarkerView { public static class CustomMarkerView extends MarkerView {
private TextView tvContent; private final TextView tvContent;
private MPPointF mOffset; private MPPointF mOffset;
public CustomMarkerView(Context context, int layoutResource) { public CustomMarkerView(Context context, int layoutResource) {
@ -510,8 +510,8 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
} }
public class MyXAxisValueFormatter extends ValueFormatter { public class MyXAxisValueFormatter extends ValueFormatter {
private DateFormat mDataFormat; private final DateFormat mDataFormat;
private Date mDate; private final Date mDate;
MyXAxisValueFormatter() { MyXAxisValueFormatter() {
if (status_id == null) { if (status_id == null) {

View File

@ -105,7 +105,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
private Date dateIni, dateEnd; private Date dateIni, dateEnd;
private View statsDialogView; private View statsDialogView;
private Statistics statistics; private Statistics statistics;
private DatePickerDialog.OnDateSetListener iniDateSetListener = private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -117,7 +117,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
} }
}; };
private DatePickerDialog.OnDateSetListener endDateSetListener = private final DatePickerDialog.OnDateSetListener endDateSetListener =
new DatePickerDialog.OnDateSetListener() { new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, public void onDateSet(DatePicker view, int year,
@ -130,14 +130,14 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
} }
}; };
private BroadcastReceiver backupFinishedReceiver = new BroadcastReceiver() { private final BroadcastReceiver backupFinishedReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
max_id = null; max_id = null;
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).execute(); new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this);
} }
}; };
@ -230,13 +230,13 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
swipeRefreshLayout.setColorSchemeColors( swipeRefreshLayout.setColorSchemeColors(
c1, c2, c1 c1, c2, c1
); );
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).execute(); new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this);
swipeRefreshLayout.setOnRefreshListener(() -> { swipeRefreshLayout.setOnRefreshListener(() -> {
max_id = null; max_id = null;
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).execute(); new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this);
}); });
lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() {
@ -248,7 +248,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, max_id, OwnerStatusActivity.this).execute(); new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, max_id, OwnerStatusActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
} else { } else {
@ -297,7 +297,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
.setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss()); .setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss());
dialogBuilder.create().show(); dialogBuilder.create().show();
if (statistics == null) { if (statistics == null) {
new RetrieveStatsAsyncTask(OwnerStatusActivity.this, OwnerStatusActivity.this).execute(); new RetrieveStatsAsyncTask(OwnerStatusActivity.this, OwnerStatusActivity.this);
} else { } else {
displayStats(); displayStats();
} }
@ -408,7 +408,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).execute(); new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this);
dialog.dismiss(); dialog.dismiss();
}) })
.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());

View File

@ -71,7 +71,7 @@ public class StatusListAdapter extends BaseStatusListAdapter {
} else { } else {
statusAction = alreadyAdded ? API.StatusAction.REMOVE_PLEROMA_REACTION : API.StatusAction.ADD_PLEROMA_REACTION; statusAction = alreadyAdded ? API.StatusAction.REMOVE_PLEROMA_REACTION : API.StatusAction.ADD_PLEROMA_REACTION;
} }
new PostActionAsyncTask(context, statusAction, status.getId(), null, emojiStr, StatusListAdapter.this).execute(); new PostActionAsyncTask(context, statusAction, status.getId(), null, emojiStr, StatusListAdapter.this);
}) })
.build(holder.fake_edittext); .build(holder.fake_edittext);
emojiPopup.toggle(); emojiPopup.toggle();

View File

@ -207,11 +207,11 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
lv_ux.setAdapter(accountSearchWebAdapterUxUiDesigners); lv_ux.setAdapter(accountSearchWebAdapterUxUiDesigners);
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "apps", "toot.fedilab.app", AboutActivity.this).execute(); new RetrieveRemoteDataAsyncTask(AboutActivity.this, "apps", "toot.fedilab.app", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "mmarif", "mastodon.social", AboutActivity.this).execute(); new RetrieveRemoteDataAsyncTask(AboutActivity.this, "mmarif", "mastodon.social", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "PhotonQyv", "mastodon.xyz", AboutActivity.this).execute(); new RetrieveRemoteDataAsyncTask(AboutActivity.this, "PhotonQyv", "mastodon.xyz", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "angrytux", "social.tchncs.de", AboutActivity.this).execute(); new RetrieveRemoteDataAsyncTask(AboutActivity.this, "angrytux", "social.tchncs.de", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "guzzisti", "mastodon.social", AboutActivity.this).execute(); new RetrieveRemoteDataAsyncTask(AboutActivity.this, "guzzisti", "mastodon.social", AboutActivity.this);
} else { } else {
SpannableString name = new SpannableString("@apps@toot.fedilab.app"); SpannableString name = new SpannableString("@apps@toot.fedilab.app");
name.setSpan(new UnderlineSpan(), 0, name.length(), 0); name.setSpan(new UnderlineSpan(), 0, name.length(), 0);
@ -272,7 +272,7 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
accountSearchWebAdapterContributors.notifyDataSetChanged(); accountSearchWebAdapterContributors.notifyDataSetChanged();
break; break;
} }
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this).execute(); new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this);
} }
} }
@ -282,17 +282,17 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
super.onResume(); super.onResume();
if (developers != null) { if (developers != null) {
for (Account account : developers) { for (Account account : developers) {
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this).execute(); new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this);
} }
} }
if (contributors != null) { if (contributors != null) {
for (Account account : contributors) { for (Account account : contributors) {
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this).execute(); new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this);
} }
} }
if (uxuidesigners != null) { if (uxuidesigners != null) {
for (Account account : uxuidesigners) { for (Account account : uxuidesigners) {
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this).execute(); new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this);
} }
} }
} }

View File

@ -138,7 +138,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
assign.setVisibility(View.GONE); assign.setVisibility(View.GONE);
status.setVisibility(View.GONE); status.setVisibility(View.GONE);
if (account_id != null) { if (account_id != null) {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.GET_ONE_ACCOUNT, account_id, null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.GET_ONE_ACCOUNT, account_id, null, AccountReportActivity.this);
return; return;
} }
if (report != null) { if (report != null) {
@ -156,7 +156,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
Group statuses_group = findViewById(R.id.statuses_group); Group statuses_group = findViewById(R.id.statuses_group);
statuses_group.setVisibility(View.VISIBLE); statuses_group.setVisibility(View.VISIBLE);
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.GET_ONE_ACCOUNT, report.getTarget_account().getUsername(), null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.GET_ONE_ACCOUNT, report.getTarget_account().getUsername(), null, AccountReportActivity.this);
} }
} }
@ -226,13 +226,13 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
reject.setOnClickListener(view -> { reject.setOnClickListener(view -> {
AdminAction adminAction = new AdminAction(); AdminAction adminAction = new AdminAction();
adminAction.setType(REJECT); adminAction.setType(REJECT);
new PostAdminActionAsyncTask(AccountReportActivity.this, REJECT, account_id, adminAction, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, REJECT, account_id, adminAction, AccountReportActivity.this);
}); });
allow.setOnClickListener(view -> { allow.setOnClickListener(view -> {
AdminAction adminAction = new AdminAction(); AdminAction adminAction = new AdminAction();
adminAction.setType(APPROVE); adminAction.setType(APPROVE);
new PostAdminActionAsyncTask(AccountReportActivity.this, APPROVE, account_id, adminAction, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, APPROVE, account_id, adminAction, AccountReportActivity.this);
}); });
warn.setOnClickListener(view -> { warn.setOnClickListener(view -> {
@ -240,7 +240,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
adminAction.setType(NONE); adminAction.setType(NONE);
adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setSend_email_notification(email_user.isChecked());
adminAction.setText(comment.getText().toString().trim()); adminAction.setText(comment.getText().toString().trim());
new PostAdminActionAsyncTask(AccountReportActivity.this, NONE, account_id, adminAction, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, NONE, account_id, adminAction, AccountReportActivity.this);
}); });
@ -255,9 +255,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
adminAction.setType(SILENCE); adminAction.setType(SILENCE);
adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setSend_email_notification(email_user.isChecked());
adminAction.setText(comment.getText().toString().trim()); adminAction.setText(comment.getText().toString().trim());
new PostAdminActionAsyncTask(AccountReportActivity.this, SILENCE, account_id, adminAction, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, SILENCE, account_id, adminAction, AccountReportActivity.this);
} else { } else {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.UNSILENCE, account_id, null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.UNSILENCE, account_id, null, AccountReportActivity.this);
} }
}); });
@ -272,9 +272,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
adminAction.setType(DISABLE); adminAction.setType(DISABLE);
adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setSend_email_notification(email_user.isChecked());
adminAction.setText(comment.getText().toString().trim()); adminAction.setText(comment.getText().toString().trim());
new PostAdminActionAsyncTask(AccountReportActivity.this, DISABLE, account_id, adminAction, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, DISABLE, account_id, adminAction, AccountReportActivity.this);
} else { } else {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.ENABLE, account_id, null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.ENABLE, account_id, null, AccountReportActivity.this);
} }
}); });
if (!accountAdmin.isSuspended()) { if (!accountAdmin.isSuspended()) {
@ -288,9 +288,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
adminAction.setType(SUSPEND); adminAction.setType(SUSPEND);
adminAction.setSend_email_notification(email_user.isChecked()); adminAction.setSend_email_notification(email_user.isChecked());
adminAction.setText(comment.getText().toString().trim()); adminAction.setText(comment.getText().toString().trim());
new PostAdminActionAsyncTask(AccountReportActivity.this, SUSPEND, account_id, adminAction, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, SUSPEND, account_id, adminAction, AccountReportActivity.this);
} else { } else {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.UNSUSPEND, account_id, null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.UNSUSPEND, account_id, null, AccountReportActivity.this);
} }
}); });
@ -422,9 +422,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
} }
assign.setOnClickListener(view -> { assign.setOnClickListener(view -> {
if (report.getAssigned_account() == null) { if (report.getAssigned_account() == null) {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.ASSIGN_TO_SELF, report.getId(), null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.ASSIGN_TO_SELF, report.getId(), null, AccountReportActivity.this);
} else { } else {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.UNASSIGN, report.getId(), null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.UNASSIGN, report.getId(), null, AccountReportActivity.this);
} }
}); });
if (report.isAction_taken()) { if (report.isAction_taken()) {
@ -434,9 +434,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
} }
status.setOnClickListener(view -> { status.setOnClickListener(view -> {
if (report.isAction_taken()) { if (report.isAction_taken()) {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.REOPEN, report.getId(), null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.REOPEN, report.getId(), null, AccountReportActivity.this);
} else { } else {
new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.RESOLVE, report.getId(), null, AccountReportActivity.this).execute(); new PostAdminActionAsyncTask(AccountReportActivity.this, API.adminAction.RESOLVE, report.getId(), null, AccountReportActivity.this);
} }
}); });

View File

@ -183,9 +183,9 @@ public abstract class BaseMainActivity extends BaseActivity
public static iconLauncher mLauncher = iconLauncher.BUBBLES; public static iconLauncher mLauncher = iconLauncher.BUBBLES;
private static boolean notificationChecked = false; private static boolean notificationChecked = false;
private final int PICK_IMPORT = 5556; private final int PICK_IMPORT = 5556;
private FloatingActionButton toot, delete_all, add_new;
private final HashMap<String, String> tagTile = new HashMap<>(); private final HashMap<String, String> tagTile = new HashMap<>();
private final HashMap<String, Integer> tagItem = new HashMap<>(); private final HashMap<String, Integer> tagItem = new HashMap<>();
private FloatingActionButton toot, delete_all, add_new;
private TextView toolbarTitle; private TextView toolbarTitle;
private SearchView toolbar_search; private SearchView toolbar_search;
private View headerLayout; private View headerLayout;
@ -312,7 +312,7 @@ public abstract class BaseMainActivity extends BaseActivity
//This task will allow to instance a static PeertubeInformation class //This task will allow to instance a static PeertubeInformation class
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
try { try {
new RetrievePeertubeInformationAsyncTask(BaseMainActivity.this).execute(); new RetrievePeertubeInformationAsyncTask(BaseMainActivity.this);
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
@ -420,7 +420,7 @@ public abstract class BaseMainActivity extends BaseActivity
main_app_container = findViewById(R.id.main_app_container); main_app_container = findViewById(R.id.main_app_container);
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
new SyncTimelinesAsyncTask(BaseMainActivity.this, 0, Helper.canFetchList(BaseMainActivity.this, account), BaseMainActivity.this).execute(); new SyncTimelinesAsyncTask(BaseMainActivity.this, 0, Helper.canFetchList(BaseMainActivity.this, account), BaseMainActivity.this);
} else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { } else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
TabLayout.Tab pTabsub = tabLayout.newTab(); TabLayout.Tab pTabsub = tabLayout.newTab();
@ -709,7 +709,7 @@ public abstract class BaseMainActivity extends BaseActivity
int position = 0; int position = 0;
if (tabLayout != null) if (tabLayout != null)
position = tabLayout.getSelectedTabPosition(); position = tabLayout.getSelectedTabPosition();
new SyncTimelinesAsyncTask(BaseMainActivity.this, position, true, BaseMainActivity.this).execute(); new SyncTimelinesAsyncTask(BaseMainActivity.this, position, true, BaseMainActivity.this);
} }
}; };
LocalBroadcastManager.getInstance(BaseMainActivity.this).registerReceiver(hidde_menu, new IntentFilter(Helper.RECEIVE_HIDE_ITEM)); LocalBroadcastManager.getInstance(BaseMainActivity.this).registerReceiver(hidde_menu, new IntentFilter(Helper.RECEIVE_HIDE_ITEM));
@ -974,7 +974,7 @@ public abstract class BaseMainActivity extends BaseActivity
} }
return true; return true;
case R.id.action_cache: case R.id.action_cache:
new Helper.CacheTask(BaseMainActivity.this).execute(); new Helper.CacheTask(BaseMainActivity.this);
return true; return true;
case R.id.action_size: case R.id.action_size:
final SharedPreferences sharedpreferences1 = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); final SharedPreferences sharedpreferences1 = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
@ -1259,7 +1259,7 @@ public abstract class BaseMainActivity extends BaseActivity
int versionCode = BuildConfig.VERSION_CODE; 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) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, BaseMainActivity.this).execute(); new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, BaseMainActivity.this);
} }
try (BufferedReader reader = new BufferedReader( try (BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("changelogs/" + versionCode + ".txt")))) { new InputStreamReader(getAssets().open("changelogs/" + versionCode + ".txt")))) {
@ -1315,10 +1315,10 @@ public abstract class BaseMainActivity extends BaseActivity
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
// Retrieves instance // Retrieves instance
new RetrieveInstanceAsyncTask(BaseMainActivity.this, BaseMainActivity.this).execute(); new RetrieveInstanceAsyncTask(BaseMainActivity.this, BaseMainActivity.this);
// Retrieves filters // Retrieves filters
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new ManageFiltersAsyncTask(BaseMainActivity.this, GET_ALL_FILTER, null, BaseMainActivity.this).execute(); new ManageFiltersAsyncTask(BaseMainActivity.this, GET_ALL_FILTER, null, BaseMainActivity.this);
} }
} }
@ -1331,14 +1331,14 @@ public abstract class BaseMainActivity extends BaseActivity
}); });
if (Helper.isLoggedIn(BaseMainActivity.this)) { if (Helper.isLoggedIn(BaseMainActivity.this)) {
final Handler handler = new Handler(); final Handler handler = new Handler();
handler.postDelayed(() -> new UpdateAccountInfoByIDAsyncTask(BaseMainActivity.this, account, BaseMainActivity.this).execute(), 2000); handler.postDelayed(() -> new UpdateAccountInfoByIDAsyncTask(BaseMainActivity.this, account, BaseMainActivity.this), 2000);
} }
mutedAccount = new TempMuteDAO(BaseMainActivity.this, db).getAllTimeMuted(account); mutedAccount = new TempMuteDAO(BaseMainActivity.this, db).getAllTimeMuted(account);
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
final Handler handler = new Handler(); final Handler handler = new Handler();
handler.postDelayed(() -> { handler.postDelayed(() -> {
new RetrieveFeedsAsyncTask(BaseMainActivity.this, RetrieveFeedsAsyncTask.Type.ANNOUNCEMENTS, null, BaseMainActivity.this).execute(); new RetrieveFeedsAsyncTask(BaseMainActivity.this, RetrieveFeedsAsyncTask.Type.ANNOUNCEMENTS, null, BaseMainActivity.this);
if (BuildConfig.lite) { if (BuildConfig.lite) {
String datesupdate = sharedpreferences.getString(Helper.TRACKING_LAST_UPDATE, null); String datesupdate = sharedpreferences.getString(Helper.TRACKING_LAST_UPDATE, null);
Date dateLastUpdate = Helper.stringToDate(BaseMainActivity.this, datesupdate); Date dateLastUpdate = Helper.stringToDate(BaseMainActivity.this, datesupdate);
@ -1461,13 +1461,13 @@ public abstract class BaseMainActivity extends BaseActivity
} else if (extras.getInt(Helper.INTENT_ACTION) == Helper.REDRAW_MENU) { } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.REDRAW_MENU) {
Helper.hideMenuItem(BaseMainActivity.this, navigationView.getMenu()); Helper.hideMenuItem(BaseMainActivity.this, navigationView.getMenu());
} else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_TAG) { } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_TAG) {
new SyncTimelinesAsyncTask(BaseMainActivity.this, -1, false, BaseMainActivity.this).execute(); new SyncTimelinesAsyncTask(BaseMainActivity.this, -1, false, BaseMainActivity.this);
} else if (extras.getInt(Helper.INTENT_ACTION) == Helper.REFRESH_TIMELINE) { } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.REFRESH_TIMELINE) {
int position = 0; int position = 0;
boolean refreshList = extras.getBoolean(Helper.REFRESH_LIST_TIMELINE, false); boolean refreshList = extras.getBoolean(Helper.REFRESH_LIST_TIMELINE, false);
if (tabLayout != null) if (tabLayout != null)
position = tabLayout.getSelectedTabPosition(); position = tabLayout.getSelectedTabPosition();
new SyncTimelinesAsyncTask(BaseMainActivity.this, position, refreshList, BaseMainActivity.this).execute(); new SyncTimelinesAsyncTask(BaseMainActivity.this, position, refreshList, BaseMainActivity.this);
} else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_REMOTE) { } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.SEARCH_REMOTE) {
String url = extras.getString(Helper.SEARCH_URL); String url = extras.getString(Helper.SEARCH_URL);
intent.replaceExtras(new Bundle()); intent.replaceExtras(new Bundle());
@ -1488,7 +1488,7 @@ public abstract class BaseMainActivity extends BaseActivity
if (!isUrl) if (!isUrl)
return; return;
//Here we know that the intent contains a valid URL //Here we know that the intent contains a valid URL
new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this).execute(); new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this);
} }
} else if (Intent.ACTION_SEND.equals(action) && type != null) { } else if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) { if ("text/plain".equals(type)) {
@ -1513,7 +1513,7 @@ public abstract class BaseMainActivity extends BaseActivity
if (matchStart < matchEnd && sharedText.length() >= matchEnd) if (matchStart < matchEnd && sharedText.length() >= matchEnd)
url = sharedText.substring(matchStart, matchEnd); url = sharedText.substring(matchStart, matchEnd);
} }
new RetrieveMetaDataAsyncTask(BaseMainActivity.this, shouldRetrieveMetaData, sharedSubject, sharedText, url, BaseMainActivity.this).execute(); new RetrieveMetaDataAsyncTask(BaseMainActivity.this, shouldRetrieveMetaData, sharedSubject, sharedText, url, BaseMainActivity.this);
} }
} else if (type.startsWith("image/") || type.startsWith("video/")) { } else if (type.startsWith("image/") || type.startsWith("video/")) {
@ -1575,7 +1575,7 @@ public abstract class BaseMainActivity extends BaseActivity
} }
//Here we know that the intent contains a valid URL //Here we know that the intent contains a valid URL
if (!url.contains("medium.com")) { if (!url.contains("medium.com")) {
new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this).execute(); new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this);
} else { } else {
forwardToBrowser(intent); forwardToBrowser(intent);
} }
@ -2070,7 +2070,7 @@ public abstract class BaseMainActivity extends BaseActivity
if (accounts != null && accounts.size() > 0) { if (accounts != null && accounts.size() > 0) {
developers = new ArrayList<>(); developers = new ArrayList<>();
developers.addAll(accounts); developers.addAll(accounts);
new RetrieveRelationshipAsyncTask(BaseMainActivity.this, accounts.get(0).getId(), BaseMainActivity.this).execute(); new RetrieveRelationshipAsyncTask(BaseMainActivity.this, accounts.get(0).getId(), BaseMainActivity.this);
} }
} }
} }

View File

@ -33,7 +33,6 @@ import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment; import android.os.Environment;
@ -45,6 +44,7 @@ import android.text.Html;
import android.text.InputType; import android.text.InputType;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan; import android.text.style.ForegroundColorSpan;
import android.util.Patterns; import android.util.Patterns;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -177,11 +177,11 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 754; public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 754;
public static final int SEND_VOICE_MESSAGE = 1423; public static final int SEND_VOICE_MESSAGE = 1423;
private static final int searchDeep = 15;
public static HashMap<String, Uri> filesMap; public static HashMap<String, Uri> filesMap;
public static boolean autocomplete; public static boolean autocomplete;
public static Uri photoFileUri = null; public static Uri photoFileUri = null;
static boolean active = false; static boolean active = false;
private static final int searchDeep = 15;
private final int PICK_IMAGE = 56556; private final int PICK_IMAGE = 56556;
private final int TAKE_PHOTO = 56532; private final int TAKE_PHOTO = 56532;
public long currentToId; public long currentToId;
@ -399,7 +399,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount).execute(); new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount);
} else { } else {
mt = tPattern.matcher(searchIn); mt = tPattern.matcher(searchIn);
if (mt.matches()) { if (mt.matches()) {
@ -408,7 +408,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveSearchAsyncTask(context, search, true, listener).execute(); new RetrieveSearchAsyncTask(context, search, true, listener);
} else { } else {
mt = ePattern.matcher(searchIn); mt = ePattern.matcher(searchIn);
if (mt.matches()) { if (mt.matches()) {
@ -417,7 +417,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji).execute(); new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji);
} else { } else {
toot_content.dismissDropDown(); toot_content.dismissDropDown();
} }
@ -443,8 +443,8 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
ContentResolver cr = activity.getContentResolver(); ContentResolver cr = activity.getContentResolver();
String mime = cr.getType(inUri); String mime = cr.getType(inUri);
if ((mime == null || mime.toLowerCase().contains("image")) && isWM) { if ((mime == null || mime.toLowerCase().contains("image")) && isWM) {
String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT+account.getId()+account.getInstance(), null); String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT + account.getId() + account.getInstance(), null);
if( WMText == null || WMText.trim().length() == 0) { if (WMText == null || WMText.trim().length() == 0) {
WMText = "@" + account.getUsername() + "@" + account.getInstance(); WMText = "@" + account.getUsername() + "@" + account.getInstance();
} }
float textSize = 15; float textSize = 15;
@ -452,16 +452,16 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
mPaint.setTextSize(textSize); mPaint.setTextSize(textSize);
float width = mPaint.measureText(WMText, 0, WMText.length()); float width = mPaint.measureText(WMText, 0, WMText.length());
try { try {
Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver() , inUri); Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), inUri);
int w = backgroundBitmap.getWidth(); int w = backgroundBitmap.getWidth();
int h = backgroundBitmap.getHeight(); int h = backgroundBitmap.getHeight();
float valx = (float)1.0 - ( (Helper.convertDpToPixel(width, activity) + 10) )/(float)w; float valx = (float) 1.0 - ((Helper.convertDpToPixel(width, activity) + 10)) / (float) w;
if( valx < 0 ) if (valx < 0)
valx = 0; valx = 0;
float valy = (h - Helper.convertDpToPixel(textSize, activity) - 10)/(float)h; float valy = (h - Helper.convertDpToPixel(textSize, activity) - 10) / (float) h;
WatermarkText watermarkText = new WatermarkText(WMText) WatermarkText watermarkText = new WatermarkText(WMText)
.setPositionX(valx) .setPositionX(valx)
.setPositionY(valy) .setPositionY(valy)
@ -478,11 +478,10 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
.getOutputImage(); .getOutputImage();
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray(); byte[] bitmapdata = bos.toByteArray();
tempInput = new ByteArrayInputStream(bitmapdata); tempInput = new ByteArrayInputStream(bitmapdata);
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -494,7 +493,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
if (suffixPosition > 0) suffix = filename.substring(suffixPosition); if (suffixPosition > 0) suffix = filename.substring(suffixPosition);
try { try {
File file; File file;
if( tempInput == null) { if (tempInput == null) {
tempInput = activity.getContentResolver().openInputStream(inUri); tempInput = activity.getContentResolver().openInputStream(inUri);
} }
if (fname.startsWith("fedilabins_")) { if (fname.startsWith("fedilabins_")) {
@ -520,7 +519,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
uri = FileProvider.getUriForFile(activity, uri = FileProvider.getUriForFile(activity,
"app.fedilab.lite.fileProvider", "app.fedilab.lite.fileProvider",
file); file);
}else{ } else {
uri = FileProvider.getUriForFile(activity, uri = FileProvider.getUriForFile(activity,
"app.fedilab.android.fileProvider", "app.fedilab.android.fileProvider",
file); file);
@ -821,20 +820,11 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
Intent intent; Intent intent;
intent = new Intent(Intent.ACTION_GET_CONTENT); intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent.setType("*/*");
intent.setType("*/*"); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMAGE);
startActivityForResult(intent, PICK_IMAGE);
} else {
intent.setType("image/* video/* audio/mpeg audio/opus audio/flac audio/wav audio/ogg");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Intent pickIntent = new Intent(Intent.ACTION_PICK, 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_IMAGE);
}
}); });
@ -850,20 +840,11 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
Intent intent; Intent intent;
intent = new Intent(Intent.ACTION_GET_CONTENT); intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent.setType("*/*");
intent.setType("*/*"); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMAGE);
startActivityForResult(intent, PICK_IMAGE);
} else {
intent.setType("image/* video/* audio/mpeg audio/opus audio/flac audio/wav audio/ogg");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Intent pickIntent = new Intent(Intent.ACTION_PICK, 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_IMAGE);
}
}); });
@ -1001,7 +982,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
photoFileUri = FileProvider.getUriForFile(this, photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.lite.fileProvider", "app.fedilab.lite.fileProvider",
photoFile); photoFile);
}else{ } else {
photoFileUri = FileProvider.getUriForFile(this, photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.android.fileProvider", "app.fedilab.android.fileProvider",
photoFile); photoFile);
@ -1089,7 +1070,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
uploadReceiver = new UploadServiceSingleBroadcastReceiver(BasePixelfedComposeActivity.this); uploadReceiver = new UploadServiceSingleBroadcastReceiver(BasePixelfedComposeActivity.this);
uploadReceiver.register(this); uploadReceiver.register(this);
} }
new asyncPicture(activity, pixelfed_story.isChecked(), account, uri, filename, uploadReceiver).execute(); new asyncPicture(activity, pixelfed_story.isChecked(), account, uri, filename, uploadReceiver);
} }
@Override @Override
@ -1170,92 +1151,91 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
style = R.style.Dialog; style = R.style.Dialog;
} }
switch (item.getItemId()) { int itemId = item.getItemId();
case android.R.id.home: if (itemId == android.R.id.home) {
finish(); finish();
return true;
} else if (itemId == R.id.action_photo_camera) {
dispatchTakePictureIntent();
return true;
} else if (itemId == R.id.action_store) {
storeToot(true, true);
return true;
} else if (itemId == R.id.action_schedule) {
if (toot_content.getText().toString().trim().length() == 0) {
Toasty.error(BasePixelfedComposeActivity.this, getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show();
return true; return true;
case R.id.action_photo_camera: }
dispatchTakePictureIntent(); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(BasePixelfedComposeActivity.this, style);
return true; LayoutInflater inflater = this.getLayoutInflater();
case R.id.action_store: View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(BasePixelfedComposeActivity.this), false);
storeToot(true, true); dialogBuilder.setView(dialogView);
return true; final AlertDialog alertDialog = dialogBuilder.create();
case R.id.action_schedule:
if (toot_content.getText().toString().trim().length() == 0) { final DatePicker datePicker = dialogView.findViewById(R.id.date_picker);
Toasty.error(BasePixelfedComposeActivity.this, getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show(); final TimePicker timePicker = dialogView.findViewById(R.id.time_picker);
return true; if (DateFormat.is24HourFormat(BasePixelfedComposeActivity.this))
timePicker.setIs24HourView(true);
Button date_time_cancel = dialogView.findViewById(R.id.date_time_cancel);
final ImageButton date_time_previous = dialogView.findViewById(R.id.date_time_previous);
final ImageButton date_time_next = dialogView.findViewById(R.id.date_time_next);
final ImageButton date_time_set = dialogView.findViewById(R.id.date_time_set);
//Buttons management
date_time_cancel.setOnClickListener(v -> alertDialog.dismiss());
date_time_next.setOnClickListener(v -> {
datePicker.setVisibility(View.GONE);
timePicker.setVisibility(View.VISIBLE);
date_time_previous.setVisibility(View.VISIBLE);
date_time_next.setVisibility(View.GONE);
date_time_set.setVisibility(View.VISIBLE);
});
date_time_previous.setOnClickListener(v -> {
datePicker.setVisibility(View.VISIBLE);
timePicker.setVisibility(View.GONE);
date_time_previous.setVisibility(View.GONE);
date_time_next.setVisibility(View.VISIBLE);
date_time_set.setVisibility(View.GONE);
});
date_time_set.setOnClickListener(v -> {
int hour, minute;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
} }
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(BasePixelfedComposeActivity.this, style); Calendar calendar = new GregorianCalendar(datePicker.getYear(),
LayoutInflater inflater = this.getLayoutInflater(); datePicker.getMonth(),
View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(BasePixelfedComposeActivity.this), false); datePicker.getDayOfMonth(),
dialogBuilder.setView(dialogView); hour,
final AlertDialog alertDialog = dialogBuilder.create(); minute);
final long[] time = {calendar.getTimeInMillis()};
final DatePicker datePicker = dialogView.findViewById(R.id.date_picker); if ((time[0] - new Date().getTime()) < 60000) {
final TimePicker timePicker = dialogView.findViewById(R.id.time_picker); Toasty.warning(BasePixelfedComposeActivity.this, getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show();
if (android.text.format.DateFormat.is24HourFormat(BasePixelfedComposeActivity.this)) } else {
timePicker.setIs24HourView(true); AlertDialog.Builder builderSingle = new AlertDialog.Builder(BasePixelfedComposeActivity.this, style);
Button date_time_cancel = dialogView.findViewById(R.id.date_time_cancel); builderSingle.setTitle(getString(R.string.choose_schedule));
final ImageButton date_time_previous = dialogView.findViewById(R.id.date_time_previous); builderSingle.setNegativeButton(R.string.device_schedule, (dialog, which) -> {
final ImageButton date_time_next = dialogView.findViewById(R.id.date_time_next); deviceSchedule(time[0]);
final ImageButton date_time_set = dialogView.findViewById(R.id.date_time_set); dialog.dismiss();
});
//Buttons management builderSingle.setPositiveButton(R.string.server_schedule, (dialog, which) -> {
date_time_cancel.setOnClickListener(v -> alertDialog.dismiss()); int offset = TimeZone.getDefault().getRawOffset();
date_time_next.setOnClickListener(v -> { calendar.add(Calendar.MILLISECOND, -offset);
datePicker.setVisibility(View.GONE); final String date = Helper.dateToString(new Date(calendar.getTimeInMillis()));
timePicker.setVisibility(View.VISIBLE); serverSchedule(date);
date_time_previous.setVisibility(View.VISIBLE); });
date_time_next.setVisibility(View.GONE); builderSingle.show();
date_time_set.setVisibility(View.VISIBLE); alertDialog.dismiss();
}); }
date_time_previous.setOnClickListener(v -> { });
datePicker.setVisibility(View.VISIBLE); alertDialog.show();
timePicker.setVisibility(View.GONE); return true;
date_time_previous.setVisibility(View.GONE);
date_time_next.setVisibility(View.VISIBLE);
date_time_set.setVisibility(View.GONE);
});
date_time_set.setOnClickListener(v -> {
int hour, minute;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
hour,
minute);
final long[] time = {calendar.getTimeInMillis()};
if ((time[0] - new Date().getTime()) < 60000) {
Toasty.warning(BasePixelfedComposeActivity.this, getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(BasePixelfedComposeActivity.this, style);
builderSingle.setTitle(getString(R.string.choose_schedule));
builderSingle.setNegativeButton(R.string.device_schedule, (dialog, which) -> {
deviceSchedule(time[0]);
dialog.dismiss();
});
builderSingle.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()));
serverSchedule(date);
});
builderSingle.show();
alertDialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
} }
return super.onOptionsItemSelected(item);
} }
@ -1277,17 +1257,17 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
toot.setContent(BasePixelfedComposeActivity.this, tootContent); toot.setContent(BasePixelfedComposeActivity.this, tootContent);
if (timestamp == null) if (timestamp == null)
if (scheduledstatus == null) if (scheduledstatus == null)
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this).execute(); new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this);
else { else {
toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date())); toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date()));
scheduledstatus.setStatus(toot); scheduledstatus.setStatus(toot);
isScheduled = true; isScheduled = true;
new PostActionAsyncTask(BasePixelfedComposeActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BasePixelfedComposeActivity.this).execute(); new PostActionAsyncTask(BasePixelfedComposeActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BasePixelfedComposeActivity.this);
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this).execute(); new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this);
} }
else { else {
toot.setScheduled_at(timestamp); toot.setScheduled_at(timestamp);
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this).execute(); new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this);
} }
} }
@ -1938,8 +1918,8 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String userId = accountReply!=null?accountReply.getId():account.getId(); String userId = accountReply != null ? accountReply.getId() : account.getId();
String instance = accountReply!=null?accountReply.getInstance():account.getInstance(); String instance = accountReply != null ? accountReply.getInstance() : account.getInstance();
try { try {
if (currentToId == -1) { if (currentToId == -1) {
currentToId = new StatusStoredDAO(BasePixelfedComposeActivity.this, db).insertStatus(toot, null, userId, instance); currentToId = new StatusStoredDAO(BasePixelfedComposeActivity.this, db).insertStatus(toot, null, userId, instance);
@ -1977,7 +1957,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
protected abstract void displayEmojiPopup(); protected abstract void displayEmojiPopup();
static class asyncPicture extends AsyncTask<Void, Void, Void> { static class asyncPicture {
String commpressedFilePath = null; String commpressedFilePath = null;
WeakReference<Activity> activityWeakReference; WeakReference<Activity> activityWeakReference;
@ -1995,46 +1975,42 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
this.filename = filename; this.filename = filename;
this.pixelfedStory = pixelfedStory; this.pixelfedStory = pixelfedStory;
this.account = account; this.account = account;
}
@Override
protected void onPreExecute() {
if (uriFile == null) { if (uriFile == null) {
Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
error = true; error = true;
} }
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.VISIBLE); activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.VISIBLE);
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... voids) { if (error) {
if (error) { return;
return null;
}
commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile);
return null;
}
@Override
protected void onPostExecute(Void result) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE);
if (!error) {
if (commpressedFilePath != null) {
uriFile = Uri.fromFile(new File(commpressedFilePath));
} }
Button upload_media = this.activityWeakReference.get().findViewById(R.id.upload_media); commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile);
Button toot_it = this.activityWeakReference.get().findViewById(R.id.toot_it); Handler mainHandler = new Handler(Looper.getMainLooper());
upload_media.setEnabled(false); Runnable myRunnable = () -> {
toot_it.setEnabled(false); activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE);
if (filename == null) { if (!error) {
filename = Helper.getFileName(this.activityWeakReference.get(), uriFile); if (commpressedFilePath != null) {
} uriFile = Uri.fromFile(new File(commpressedFilePath));
filesMap.put(filename, uriFile); }
upload(activityWeakReference.get(), pixelfedStory, account, uriFile, filename, uploadReceiver); Button upload_media = this.activityWeakReference.get().findViewById(R.id.upload_media);
} Button toot_it = this.activityWeakReference.get().findViewById(R.id.toot_it);
upload_media.setEnabled(false);
toot_it.setEnabled(false);
if (filename == null) {
filename = Helper.getFileName(this.activityWeakReference.get(), uriFile);
}
filesMap.put(filename, uriFile);
upload(activityWeakReference.get(), pixelfedStory, account, uriFile, filename, uploadReceiver);
}
};
mainHandler.post(myRunnable);
}).start();
} }
} }
} }

View File

@ -33,7 +33,6 @@ import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment; import android.os.Environment;
@ -46,6 +45,7 @@ import android.text.InputFilter;
import android.text.InputType; import android.text.InputType;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan; import android.text.style.ForegroundColorSpan;
import android.util.Patterns; import android.util.Patterns;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -97,7 +97,6 @@ import com.github.irshulx.Editor;
import com.github.irshulx.EditorListener; import com.github.irshulx.EditorListener;
import com.github.irshulx.models.EditorTextStyle; import com.github.irshulx.models.EditorTextStyle;
import com.watermark.androidwm_light.WatermarkBuilder; import com.watermark.androidwm_light.WatermarkBuilder;
import com.watermark.androidwm_light.bean.WatermarkImage;
import com.watermark.androidwm_light.bean.WatermarkText; import com.watermark.androidwm_light.bean.WatermarkText;
import net.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.MultipartUploadRequest;
@ -219,12 +218,12 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 754; public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 754;
public static final int REQUEST_CAMERA_PERMISSION_RESULT = 1653; public static final int REQUEST_CAMERA_PERMISSION_RESULT = 1653;
public static final int SEND_VOICE_MESSAGE = 1423; public static final int SEND_VOICE_MESSAGE = 1423;
private static final int searchDeep = 15;
public static HashMap<String, Uri> filesMap; public static HashMap<String, Uri> filesMap;
public static boolean autocomplete; public static boolean autocomplete;
public static Uri photoFileUri = null; public static Uri photoFileUri = null;
static boolean active = false; static boolean active = false;
private static String instance; private static String instance;
private static final int searchDeep = 15;
private final int PICK_IMAGE = 56556; private final int PICK_IMAGE = 56556;
private final int TAKE_PHOTO = 56532; private final int TAKE_PHOTO = 56532;
public long currentToId; public long currentToId;
@ -472,7 +471,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount).execute(); new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount);
} else { } else {
mt = tPattern.matcher(searchIn); mt = tPattern.matcher(searchIn);
if (mt.matches()) { if (mt.matches()) {
@ -481,7 +480,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveSearchAsyncTask(context, search, true, listener).execute(); new RetrieveSearchAsyncTask(context, search, true, listener);
} else { } else {
mt = ePattern.matcher(searchIn); mt = ePattern.matcher(searchIn);
if (mt.matches()) { if (mt.matches()) {
@ -490,7 +489,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji).execute(); new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji);
} else { } else {
toot_content.dismissDropDown(); toot_content.dismissDropDown();
} }
@ -516,8 +515,8 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
ContentResolver cr = activity.getContentResolver(); ContentResolver cr = activity.getContentResolver();
String mime = cr.getType(inUri); String mime = cr.getType(inUri);
if ((mime == null || mime.toLowerCase().contains("image")) && isWM) { if ((mime == null || mime.toLowerCase().contains("image")) && isWM) {
String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT+account.getId()+account.getInstance(), null); String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT + account.getId() + account.getInstance(), null);
if( WMText == null || WMText.trim().length() == 0) { if (WMText == null || WMText.trim().length() == 0) {
WMText = "@" + account.getUsername() + "@" + account.getInstance(); WMText = "@" + account.getUsername() + "@" + account.getInstance();
} }
@ -526,15 +525,15 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
mPaint.setTextSize(textSize); mPaint.setTextSize(textSize);
float width = mPaint.measureText(WMText, 0, WMText.length()); float width = mPaint.measureText(WMText, 0, WMText.length());
try { try {
Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver() , inUri); Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), inUri);
int w = backgroundBitmap.getWidth(); int w = backgroundBitmap.getWidth();
int h = backgroundBitmap.getHeight(); int h = backgroundBitmap.getHeight();
float valx = (float)1.0 - ( (Helper.convertDpToPixel(width, activity) + 10) )/(float)w; float valx = (float) 1.0 - ((Helper.convertDpToPixel(width, activity) + 10)) / (float) w;
if( valx < 0 ) if (valx < 0)
valx = 0; valx = 0;
float valy = (h - Helper.convertDpToPixel(textSize, activity) - 10)/(float)h; float valy = (h - Helper.convertDpToPixel(textSize, activity) - 10) / (float) h;
WatermarkText watermarkText = new WatermarkText(WMText) WatermarkText watermarkText = new WatermarkText(WMText)
.setPositionX(valx) .setPositionX(valx)
.setPositionY(valy) .setPositionY(valy)
@ -551,12 +550,11 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
.getOutputImage(); .getOutputImage();
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray(); byte[] bitmapdata = bos.toByteArray();
tempInput = new ByteArrayInputStream(bitmapdata); tempInput = new ByteArrayInputStream(bitmapdata);
} } catch (Exception e) {
catch (Exception e) { e.printStackTrace();
e.printStackTrace();
} }
} }
Uri uri; Uri uri;
@ -567,7 +565,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
if (suffixPosition > 0) suffix = filename.substring(suffixPosition); if (suffixPosition > 0) suffix = filename.substring(suffixPosition);
try { try {
File file; File file;
if( tempInput == null) { if (tempInput == null) {
tempInput = activity.getContentResolver().openInputStream(inUri); tempInput = activity.getContentResolver().openInputStream(inUri);
} }
if (fname.startsWith("fedilabins_")) { if (fname.startsWith("fedilabins_")) {
@ -593,7 +591,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
uri = FileProvider.getUriForFile(activity, uri = FileProvider.getUriForFile(activity,
"app.fedilab.lite.fileProvider", "app.fedilab.lite.fileProvider",
file); file);
}else{ } else {
uri = FileProvider.getUriForFile(activity, uri = FileProvider.getUriForFile(activity,
"app.fedilab.android.fileProvider", "app.fedilab.android.fileProvider",
file); file);
@ -949,7 +947,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, search, BaseTootActivity.this).execute(); new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, search, BaseTootActivity.this);
} else { } else {
mt = tPattern.matcher(searchIn); mt = tPattern.matcher(searchIn);
if (mt.matches()) { if (mt.matches()) {
@ -958,7 +956,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveSearchAsyncTask(BaseTootActivity.this, search, true, BaseTootActivity.this).execute(); new RetrieveSearchAsyncTask(BaseTootActivity.this, search, true, BaseTootActivity.this);
} else { } else {
mt = ePattern.matcher(searchIn); mt = ePattern.matcher(searchIn);
if (mt.matches()) { if (mt.matches()) {
@ -967,7 +965,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE); pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE); pp_actionBar.setVisibility(View.GONE);
} }
new RetrieveEmojiAsyncTask(BaseTootActivity.this, shortcode, BaseTootActivity.this).execute(); new RetrieveEmojiAsyncTask(BaseTootActivity.this, shortcode, BaseTootActivity.this);
} }
} }
} }
@ -1053,7 +1051,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
warning_message.setVisibility(View.VISIBLE); warning_message.setVisibility(View.VISIBLE);
} }
assert tootReply.getAccount() != null; assert tootReply.getAccount() != null;
new RetrieveRelationshipAsyncTask(BaseTootActivity.this, tootReply.getAccount().getId(), BaseTootActivity.this).execute(); new RetrieveRelationshipAsyncTask(BaseTootActivity.this, tootReply.getAccount().getId(), BaseTootActivity.this);
} }
if (scheduledstatus != null) if (scheduledstatus != null)
toot_it.setText(R.string.modify); toot_it.setText(R.string.modify);
@ -1231,19 +1229,15 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
popup.getMenuInflater() popup.getMenuInflater()
.inflate(R.menu.main_content_type, popup.getMenu()); .inflate(R.menu.main_content_type, popup.getMenu());
popup.setOnMenuItemClickListener(item -> { popup.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) { int itemId = item.getItemId();
case R.id.action_plain_text: if (itemId == R.id.action_plain_text) {
contentType = "text/plain"; contentType = "text/plain";
break; } else if (itemId == R.id.action_html) {
case R.id.action_html: contentType = "text/html";
contentType = "text/html"; } else if (itemId == R.id.action_markdown) {
break; contentType = "text/markdown";
case R.id.action_markdown: } else if (itemId == R.id.action_bbcode) {
contentType = "text/markdown"; contentType = "text/bbcode";
break;
case R.id.action_bbcode:
contentType = "text/bbcode";
break;
} }
popup.dismiss(); popup.dismiss();
sendToot(null, contentType); sendToot(null, contentType);
@ -1265,20 +1259,11 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
Intent intent; Intent intent;
intent = new Intent(Intent.ACTION_GET_CONTENT); intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent.setType("*/*");
intent.setType("*/*"); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"}; intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes); startActivityForResult(intent, PICK_IMAGE);
startActivityForResult(intent, PICK_IMAGE);
} else {
intent.setType("image/* video/* audio/mpeg audio/opus audio/flac audio/wav audio/ogg");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Intent pickIntent = new Intent(Intent.ACTION_PICK, 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_IMAGE);
}
}); });
@ -1545,7 +1530,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
photoFileUri = FileProvider.getUriForFile(this, photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.lite.fileProvider", "app.fedilab.lite.fileProvider",
photoFile); photoFile);
}else{ } else {
photoFileUri = FileProvider.getUriForFile(this, photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.android.fileProvider", "app.fedilab.android.fileProvider",
photoFile); photoFile);
@ -1634,7 +1619,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
private void prepareUpload(Activity activity, android.net.Uri uri, String filename) { private void prepareUpload(Activity activity, android.net.Uri uri, String filename) {
UploadServiceSingleBroadcastReceiver uploadReceiver = new UploadServiceSingleBroadcastReceiver(BaseTootActivity.this); UploadServiceSingleBroadcastReceiver uploadReceiver = new UploadServiceSingleBroadcastReceiver(BaseTootActivity.this);
uploadReceiver.register(this); uploadReceiver.register(this);
new asyncPicture(activity, account, social, uri, filename, uploadReceiver).execute(); new asyncPicture(activity, account, social, uri, filename, uploadReceiver);
} }
@Override @Override
@ -1721,271 +1706,270 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
style = R.style.Dialog; style = R.style.Dialog;
} }
switch (item.getItemId()) { int itemId = item.getItemId();
case android.R.id.home: if (itemId == android.R.id.home) {
finish(); finish();
return true; return true;
case R.id.action_view_reply: } else if (itemId == R.id.action_view_reply) {
AlertDialog.Builder alert = new AlertDialog.Builder(BaseTootActivity.this, style); AlertDialog.Builder alert = new AlertDialog.Builder(BaseTootActivity.this, style);
alert.setTitle(R.string.toot_reply_content_title); alert.setTitle(R.string.toot_reply_content_title);
final TextView input = new TextView(BaseTootActivity.this); final TextView input = new TextView(BaseTootActivity.this);
//Set the padding //Set the padding
input.setPadding(30, 30, 30, 30); input.setPadding(30, 30, 30, 30);
alert.setView(input); alert.setView(input);
String content = tootReply.getContent(); String content = tootReply.getContent();
if (tootReply.getReblog() != null) if (tootReply.getReblog() != null)
content = tootReply.getReblog().getContent(); content = tootReply.getReblog().getContent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY)); input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY));
else else
input.setText(Html.fromHtml(content)); input.setText(Html.fromHtml(content));
alert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss()); alert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss());
alert.setNegativeButton(R.string.accounts, (dialog, whichButton) -> { alert.setNegativeButton(R.string.accounts, (dialog, whichButton) -> {
new RetrieveAccountsForReplyAsyncTask(BaseTootActivity.this, tootReply.getReblog() != null ? tootReply.getReblog() : tootReply, BaseTootActivity.this).execute(); new RetrieveAccountsForReplyAsyncTask(BaseTootActivity.this, tootReply.getReblog() != null ? tootReply.getReblog() : tootReply, BaseTootActivity.this);
dialog.dismiss(); dialog.dismiss();
});
alert.show();
return true;
} else if (itemId == R.id.action_poll) {
displayPollPopup();
return false;
} else if (itemId == R.id.action_translate) {
return actionTranslateClick();
} else if (itemId == R.id.action_emoji) {
if (emojis != null) {
emojis.clear();
emojis = null;
}
emojis = new CustomEmojiDAO(BaseTootActivity.this, db).getAllEmojis(account.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(this, style);
int paddingPixel = 15;
float density = getResources().getDisplayMetrics().density;
int paddingDp = (int) (paddingPixel * density);
builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builder.setTitle(R.string.insert_emoji);
if (emojis != null && emojis.size() > 0) {
GridView gridView = new GridView(BaseTootActivity.this);
gridView.setAdapter(new CustomEmojiAdapter(emojis));
gridView.setNumColumns(5);
gridView.setOnItemClickListener((parent, view, position, id) -> {
toot_content.getText().insert(toot_content.getSelectionStart(), " :" + emojis.get(position).getShortcode() + ": ");
alertDialogEmoji.dismiss();
}); });
alert.show(); gridView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp);
return true; builder.setView(gridView);
} else {
TextView textView = new TextView(BaseTootActivity.this);
textView.setText(getString(R.string.no_emoji));
textView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp);
builder.setView(textView);
}
alertDialogEmoji = builder.show();
case R.id.action_poll:
displayPollPopup(); return true;
return false; } else if (itemId == R.id.action_photo_camera) {
case R.id.action_translate: dispatchTakePictureIntent();
return actionTranslateClick(); return true;
case R.id.action_emoji: } else if (itemId == R.id.action_contacts) {
if (emojis != null) { AlertDialog.Builder builderSingle = new AlertDialog.Builder(BaseTootActivity.this, style);
emojis.clear();
emojis = null; builderSingle.setTitle(getString(R.string.select_accounts));
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.popup_contact, new LinearLayout(BaseTootActivity.this), false);
loader = dialogView.findViewById(R.id.loader);
EditText search_account = dialogView.findViewById(R.id.search_account);
lv_accounts_search = dialogView.findViewById(R.id.lv_accounts_search);
loader.setVisibility(View.VISIBLE);
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, "a", true, BaseTootActivity.this);
search_account.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
} }
emojis = new CustomEmojiDAO(BaseTootActivity.this, db).getAllEmojis(account.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(this, style);
int paddingPixel = 15;
float density = getResources().getDisplayMetrics().density;
int paddingDp = (int) (paddingPixel * density);
builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builder.setTitle(R.string.insert_emoji);
if (emojis != null && emojis.size() > 0) {
GridView gridView = new GridView(BaseTootActivity.this);
gridView.setAdapter(new CustomEmojiAdapter(emojis));
gridView.setNumColumns(5);
gridView.setOnItemClickListener((parent, view, position, id) -> {
toot_content.getText().insert(toot_content.getSelectionStart(), " :" + emojis.get(position).getShortcode() + ": ");
alertDialogEmoji.dismiss();
});
gridView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp);
builder.setView(gridView);
} else {
TextView textView = new TextView(BaseTootActivity.this);
textView.setText(getString(R.string.no_emoji));
textView.setPadding(paddingDp, paddingDp, paddingDp, paddingDp);
builder.setView(textView);
}
alertDialogEmoji = builder.show();
@Override
return true; public void onTextChanged(CharSequence s, int start, int before, int count) {
case R.id.action_photo_camera: if (count > 0) {
dispatchTakePictureIntent(); search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close, 0);
return true;
case R.id.action_contacts:
AlertDialog.Builder builderSingle = new AlertDialog.Builder(BaseTootActivity.this, style);
builderSingle.setTitle(getString(R.string.select_accounts));
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.popup_contact, new LinearLayout(BaseTootActivity.this), false);
loader = dialogView.findViewById(R.id.loader);
EditText search_account = dialogView.findViewById(R.id.search_account);
lv_accounts_search = dialogView.findViewById(R.id.lv_accounts_search);
loader.setVisibility(View.VISIBLE);
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, "a", true, BaseTootActivity.this).execute();
search_account.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) {
if (count > 0) {
search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close, 0);
} else {
search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_search, 0);
}
}
@Override
public void afterTextChanged(Editable s) {
if (s != null && s.length() > 0) {
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, s.toString(), true, BaseTootActivity.this).execute();
}
}
});
search_account.setOnTouchListener((v, event) -> {
final int DRAWABLE_RIGHT = 2;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (search_account.length() > 0 && event.getRawX() >= (search_account.getRight() - search_account.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
search_account.setText("");
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, "a", true, BaseTootActivity.this).execute();
}
}
return false;
});
builderSingle.setView(dialogView);
builderSingle.setNegativeButton(R.string.validate, (dialog, which) -> {
dialog.dismiss();
toot_content.setSelection(toot_content.getText().length());
});
builderSingle.show();
return true;
case R.id.action_microphone:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED) {
recordAudio();
} else { } else {
if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) { search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_search, 0);
Toast.makeText(this,
getString(R.string.audio), Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO
}, REQUEST_CAMERA_PERMISSION_RESULT);
} }
}
} else { @Override
public void afterTextChanged(Editable s) {
if (s != null && s.length() > 0) {
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, s.toString(), true, BaseTootActivity.this);
}
}
});
search_account.setOnTouchListener((v, event) -> {
final int DRAWABLE_RIGHT = 2;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (search_account.length() > 0 && event.getRawX() >= (search_account.getRight() - search_account.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
search_account.setText("");
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, "a", true, BaseTootActivity.this);
}
}
return false;
});
builderSingle.setView(dialogView);
builderSingle.setNegativeButton(R.string.validate, (dialog, which) -> {
dialog.dismiss();
toot_content.setSelection(toot_content.getText().length());
});
builderSingle.show();
return true;
} else if (itemId == R.id.action_microphone) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED) {
recordAudio(); recordAudio();
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(this,
getString(R.string.audio), Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO
}, REQUEST_CAMERA_PERMISSION_RESULT);
} }
} else {
recordAudio();
}
return true;
case R.id.action_store:
storeToot(true, true);
return true;
case R.id.action_tags:
Intent intentTags = new Intent(BaseTootActivity.this, TagCacheActivity.class);
intentTags.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intentTags);
return true;
case R.id.action_restore:
try {
final List<StoredStatus> drafts = new StatusStoredDAO(BaseTootActivity.this, db).getAllDrafts();
if (drafts == null || drafts.size() == 0) {
Toasty.info(BaseTootActivity.this, getString(R.string.no_draft), Toast.LENGTH_LONG).show();
return true;
}
builderSingle = new AlertDialog.Builder(BaseTootActivity.this, style);
builderSingle.setTitle(getString(R.string.choose_toot));
final DraftsListAdapter draftsListAdapter = new DraftsListAdapter(drafts);
final int[] ids = new int[drafts.size()];
int i = 0;
for (StoredStatus draft : drafts) {
ids[i] = draft.getId();
i++;
}
builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderSingle.setPositiveButton(R.string.delete_all, (dialog, which) -> {
AlertDialog.Builder builder1 = new AlertDialog.Builder(BaseTootActivity.this, style);
builder1.setTitle(R.string.delete_all);
builder1.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.yes, (dialogConfirm, which1) -> {
new StatusStoredDAO(BaseTootActivity.this, db).removeAllDrafts();
dialogConfirm.dismiss();
dialog.dismiss();
})
.setNegativeButton(R.string.no, (dialogConfirm, which12) -> dialogConfirm.dismiss())
.show();
}); return true;
builderSingle.setAdapter(draftsListAdapter, } else if (itemId == R.id.action_store) {
(dialog, which) -> { storeToot(true, true);
int id = ids[which]; return true;
restoreToot(id); } else if (itemId == R.id.action_tags) {
dialog.dismiss(); Intent intentTags = new Intent(BaseTootActivity.this, TagCacheActivity.class);
}); intentTags.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
builderSingle.show(); startActivity(intentTags);
} catch (Exception e) { return true;
Toasty.error(BaseTootActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } else if (itemId == R.id.action_restore) {
} AlertDialog.Builder builderSingle;
return true; try {
final List<StoredStatus> drafts = new StatusStoredDAO(BaseTootActivity.this, db).getAllDrafts();
case R.id.action_schedule: if (drafts == null || drafts.size() == 0) {
if (toot_content.getText().toString().trim().length() == 0) { Toasty.info(BaseTootActivity.this, getString(R.string.no_draft), Toast.LENGTH_LONG).show();
Toasty.error(BaseTootActivity.this, getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show();
return true; return true;
} }
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(BaseTootActivity.this, style); builderSingle = new AlertDialog.Builder(BaseTootActivity.this, style);
inflater = this.getLayoutInflater(); builderSingle.setTitle(getString(R.string.choose_toot));
dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(BaseTootActivity.this), false); final DraftsListAdapter draftsListAdapter = new DraftsListAdapter(drafts);
dialogBuilder.setView(dialogView); final int[] ids = new int[drafts.size()];
final AlertDialog alertDialog = dialogBuilder.create(); int i = 0;
for (StoredStatus draft : drafts) {
ids[i] = draft.getId();
i++;
}
builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderSingle.setPositiveButton(R.string.delete_all, (dialog, which) -> {
AlertDialog.Builder builder1 = new AlertDialog.Builder(BaseTootActivity.this, style);
builder1.setTitle(R.string.delete_all);
builder1.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.yes, (dialogConfirm, which1) -> {
new StatusStoredDAO(BaseTootActivity.this, db).removeAllDrafts();
dialogConfirm.dismiss();
dialog.dismiss();
})
.setNegativeButton(R.string.no, (dialogConfirm, which12) -> dialogConfirm.dismiss())
.show();
final DatePicker datePicker = dialogView.findViewById(R.id.date_picker);
final TimePicker timePicker = dialogView.findViewById(R.id.time_picker);
if (android.text.format.DateFormat.is24HourFormat(BaseTootActivity.this))
timePicker.setIs24HourView(true);
Button date_time_cancel = dialogView.findViewById(R.id.date_time_cancel);
final ImageButton date_time_previous = dialogView.findViewById(R.id.date_time_previous);
final ImageButton date_time_next = dialogView.findViewById(R.id.date_time_next);
final ImageButton date_time_set = dialogView.findViewById(R.id.date_time_set);
//Buttons management
date_time_cancel.setOnClickListener(v -> alertDialog.dismiss());
date_time_next.setOnClickListener(v -> {
datePicker.setVisibility(View.GONE);
timePicker.setVisibility(View.VISIBLE);
date_time_previous.setVisibility(View.VISIBLE);
date_time_next.setVisibility(View.GONE);
date_time_set.setVisibility(View.VISIBLE);
}); });
date_time_previous.setOnClickListener(v -> { builderSingle.setAdapter(draftsListAdapter,
datePicker.setVisibility(View.VISIBLE); (dialog, which) -> {
timePicker.setVisibility(View.GONE); int id = ids[which];
date_time_previous.setVisibility(View.GONE); restoreToot(id);
date_time_next.setVisibility(View.VISIBLE);
date_time_set.setVisibility(View.GONE);
});
date_time_set.setOnClickListener(v -> {
int hour, minute;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
hour,
minute);
final long[] time = {calendar.getTimeInMillis()};
if ((time[0] - new Date().getTime()) < 60000) {
Toasty.warning(BaseTootActivity.this, getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builderSingle1 = new AlertDialog.Builder(BaseTootActivity.this, style);
builderSingle1.setTitle(getString(R.string.choose_schedule));
builderSingle1.setNegativeButton(R.string.device_schedule, (dialog, which) -> {
deviceSchedule(time[0]);
dialog.dismiss(); dialog.dismiss();
}); });
builderSingle1.setPositiveButton(R.string.server_schedule, (dialog, which) -> { builderSingle.show();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()); } catch (Exception e) {
String date = sdf.format(calendar.getTime()); Toasty.error(BaseTootActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
serverSchedule(date); }
}); return true;
builderSingle1.show(); } else if (itemId == R.id.action_schedule) {
alertDialog.dismiss(); View dialogView;
} LayoutInflater inflater;
}); if (toot_content.getText().toString().trim().length() == 0) {
alertDialog.show(); Toasty.error(BaseTootActivity.this, getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show();
return true; return true;
default: }
return super.onOptionsItemSelected(item); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(BaseTootActivity.this, style);
inflater = this.getLayoutInflater();
dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(BaseTootActivity.this), false);
dialogBuilder.setView(dialogView);
final AlertDialog alertDialog = dialogBuilder.create();
final DatePicker datePicker = dialogView.findViewById(R.id.date_picker);
final TimePicker timePicker = dialogView.findViewById(R.id.time_picker);
if (DateFormat.is24HourFormat(BaseTootActivity.this))
timePicker.setIs24HourView(true);
Button date_time_cancel = dialogView.findViewById(R.id.date_time_cancel);
final ImageButton date_time_previous = dialogView.findViewById(R.id.date_time_previous);
final ImageButton date_time_next = dialogView.findViewById(R.id.date_time_next);
final ImageButton date_time_set = dialogView.findViewById(R.id.date_time_set);
//Buttons management
date_time_cancel.setOnClickListener(v -> alertDialog.dismiss());
date_time_next.setOnClickListener(v -> {
datePicker.setVisibility(View.GONE);
timePicker.setVisibility(View.VISIBLE);
date_time_previous.setVisibility(View.VISIBLE);
date_time_next.setVisibility(View.GONE);
date_time_set.setVisibility(View.VISIBLE);
});
date_time_previous.setOnClickListener(v -> {
datePicker.setVisibility(View.VISIBLE);
timePicker.setVisibility(View.GONE);
date_time_previous.setVisibility(View.GONE);
date_time_next.setVisibility(View.VISIBLE);
date_time_set.setVisibility(View.GONE);
});
date_time_set.setOnClickListener(v -> {
int hour, minute;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
hour,
minute);
final long[] time = {calendar.getTimeInMillis()};
if ((time[0] - new Date().getTime()) < 60000) {
Toasty.warning(BaseTootActivity.this, getString(R.string.toot_scheduled_date), Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builderSingle1 = new AlertDialog.Builder(BaseTootActivity.this, style);
builderSingle1.setTitle(getString(R.string.choose_schedule));
builderSingle1.setNegativeButton(R.string.device_schedule, (dialog, which) -> {
deviceSchedule(time[0]);
dialog.dismiss();
});
builderSingle1.setPositiveButton(R.string.server_schedule, (dialog, which) -> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
String date = sdf.format(calendar.getTime());
serverSchedule(date);
});
builderSingle1.show();
alertDialog.dismiss();
}
});
alertDialog.show();
return true;
} }
return super.onOptionsItemSelected(item);
} }
private void sendToot(String timestamp, String content_type) { private void sendToot(String timestamp, String content_type) {
@ -2105,17 +2089,17 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
} }
if (timestamp == null) if (timestamp == null)
if (scheduledstatus == null) if (scheduledstatus == null)
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this).execute(); new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this);
else { else {
toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date())); toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date()));
scheduledstatus.setStatus(toot); scheduledstatus.setStatus(toot);
isScheduled = true; isScheduled = true;
new PostActionAsyncTask(BaseTootActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BaseTootActivity.this).execute(); new PostActionAsyncTask(BaseTootActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BaseTootActivity.this);
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this).execute(); new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this);
} }
else { else {
toot.setScheduled_at(timestamp); toot.setScheduled_at(timestamp);
new PostStatusAsyncTask(BaseTootActivity.this, social, accountReply!=null?accountReply:account, toot, BaseTootActivity.this).execute(); new PostStatusAsyncTask(BaseTootActivity.this, social, accountReply != null ? accountReply : account, toot, BaseTootActivity.this);
} }
} }
@ -2278,7 +2262,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
input.setSelection(input.getText().length()); input.setSelection(input.getText().length());
} }
builderInner.setPositiveButton(R.string.validate, (dialog, which) -> { builderInner.setPositiveButton(R.string.validate, (dialog, which) -> {
new UpdateDescriptionAttachmentAsyncTask(BaseTootActivity.this, attachment.getId(), input.getText().toString(), account, BaseTootActivity.this).execute(); new UpdateDescriptionAttachmentAsyncTask(BaseTootActivity.this, attachment.getId(), input.getText().toString(), account, BaseTootActivity.this);
attachment.setDescription(input.getText().toString()); attachment.setDescription(input.getText().toString());
addBorder(); addBorder();
dialog.dismiss(); dialog.dismiss();
@ -2451,7 +2435,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0) if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0)
toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId()); toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId());
toot.setContent(BaseTootActivity.this, tootContent); toot.setContent(BaseTootActivity.this, tootContent);
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this).execute(); new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this);
return; return;
} }
@ -2490,7 +2474,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
} else } else
Toasty.success(BaseTootActivity.this, getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show(); Toasty.success(BaseTootActivity.this, getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show();
} else { } else {
if (apiResponse.getError().getStatusCode() == -33 ) if (apiResponse.getError().getStatusCode() == -33)
Toasty.info(BaseTootActivity.this, getString(R.string.toast_toot_saved_error), Toast.LENGTH_LONG).show(); Toasty.info(BaseTootActivity.this, getString(R.string.toast_toot_saved_error), Toast.LENGTH_LONG).show();
} }
toot_it.setEnabled(true); toot_it.setEnabled(true);
@ -3535,8 +3519,8 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
toot.setIn_reply_to_id(tootReply.getId()); toot.setIn_reply_to_id(tootReply.getId());
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
//TODO: insert should be done with connected account //TODO: insert should be done with connected account
String userId = accountReply!=null?accountReply.getId():account.getId(); String userId = accountReply != null ? accountReply.getId() : account.getId();
String instance = accountReply!=null?accountReply.getInstance():account.getInstance(); String instance = accountReply != null ? accountReply.getInstance() : account.getInstance();
try { try {
if (currentToId == -1) { if (currentToId == -1) {
currentToId = new StatusStoredDAO(BaseTootActivity.this, db).insertStatus(toot, tootReply, userId, instance); currentToId = new StatusStoredDAO(BaseTootActivity.this, db).insertStatus(toot, tootReply, userId, instance);
@ -3727,8 +3711,9 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
protected abstract void displayEmojiPopup(); protected abstract void displayEmojiPopup();
static class asyncPicture extends AsyncTask<Void, Void, Void> { static class asyncPicture {
private final Account account;
String commpressedFilePath; String commpressedFilePath;
WeakReference<Activity> activityWeakReference; WeakReference<Activity> activityWeakReference;
android.net.Uri uriFile; android.net.Uri uriFile;
@ -3736,7 +3721,6 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
UploadServiceSingleBroadcastReceiver uploadReceiver; UploadServiceSingleBroadcastReceiver uploadReceiver;
String filename; String filename;
UpdateAccountInfoAsyncTask.SOCIAL social; UpdateAccountInfoAsyncTask.SOCIAL social;
private final Account account;
asyncPicture(Activity activity, Account account, UpdateAccountInfoAsyncTask.SOCIAL social, android.net.Uri uri, String filename, UploadServiceSingleBroadcastReceiver uploadReceiver) { asyncPicture(Activity activity, Account account, UpdateAccountInfoAsyncTask.SOCIAL social, android.net.Uri uri, String filename, UploadServiceSingleBroadcastReceiver uploadReceiver) {
this.activityWeakReference = new WeakReference<>(activity); this.activityWeakReference = new WeakReference<>(activity);
@ -3745,10 +3729,6 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
this.filename = filename; this.filename = filename;
this.social = social; this.social = social;
this.account = account; this.account = account;
}
@Override
protected void onPreExecute() {
if (uriFile == null) { if (uriFile == null) {
Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show(); Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
error = true; error = true;
@ -3756,52 +3736,52 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
if (activityWeakReference.get().findViewById(R.id.compression_loader) != null) { if (activityWeakReference.get().findViewById(R.id.compression_loader) != null) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.VISIBLE); activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.VISIBLE);
} }
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... voids) { if (error) {
if (error) { return;
return null; }
} commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile);
commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile); Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> {
if (activityWeakReference.get().findViewById(R.id.compression_loader) != null) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE);
}
if (activityWeakReference.get().findViewById(R.id.picture_scrollview) != null) {
activityWeakReference.get().findViewById(R.id.picture_scrollview).setVisibility(View.VISIBLE);
}
if (!error) {
if (commpressedFilePath != null) {
uriFile = Uri.fromFile(new File(commpressedFilePath));
}
ImageButton toot_picture;
Button toot_it;
LinearLayout toot_picture_container;
toot_picture = this.activityWeakReference.get().findViewById(R.id.toot_picture);
toot_it = this.activityWeakReference.get().findViewById(R.id.toot_it);
toot_picture_container = this.activityWeakReference.get().findViewById(R.id.toot_picture_container);
if (toot_picture_container != null) {
toot_picture_container.setVisibility(View.VISIBLE);
}
if (toot_picture != null) {
toot_picture.setEnabled(false);
}
if (toot_it != null) {
toot_it.setEnabled(false);
}
if (filename == null) {
filename = Helper.getFileName(this.activityWeakReference.get(), uriFile);
}
filesMap.put(filename, uriFile);
upload(activityWeakReference.get(), account, social, uriFile, filename, uploadReceiver);
}
};
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
if (activityWeakReference.get().findViewById(R.id.compression_loader) != null) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.GONE);
}
if (activityWeakReference.get().findViewById(R.id.picture_scrollview) != null) {
activityWeakReference.get().findViewById(R.id.picture_scrollview).setVisibility(View.VISIBLE);
}
if (!error) {
if (commpressedFilePath != null) {
uriFile = Uri.fromFile(new File(commpressedFilePath));
}
ImageButton toot_picture;
Button toot_it;
LinearLayout toot_picture_container;
toot_picture = this.activityWeakReference.get().findViewById(R.id.toot_picture);
toot_it = this.activityWeakReference.get().findViewById(R.id.toot_it);
toot_picture_container = this.activityWeakReference.get().findViewById(R.id.toot_picture_container);
if (toot_picture_container != null) {
toot_picture_container.setVisibility(View.VISIBLE);
}
if (toot_picture != null) {
toot_picture.setEnabled(false);
}
if (toot_it != null) {
toot_it.setEnabled(false);
}
if (filename == null) {
filename = Helper.getFileName(this.activityWeakReference.get(), uriFile);
}
filesMap.put(filename, uriFile);
upload(activityWeakReference.get(), account, social, uriFile, filename, uploadReceiver);
}
}
} }
} }

View File

@ -125,7 +125,7 @@ public class BookmarkActivity extends BaseActivity implements OnRetrieveFeedsInt
mainLoader = findViewById(R.id.loader); mainLoader = findViewById(R.id.loader);
textviewNoAction = findViewById(R.id.no_action); textviewNoAction = findViewById(R.id.no_action);
mainLoader.setVisibility(View.VISIBLE); mainLoader.setVisibility(View.VISIBLE);
new RetrieveFeedsAsyncTask(BookmarkActivity.this, RetrieveFeedsAsyncTask.Type.CACHE_BOOKMARKS, null, BookmarkActivity.this).execute(); new RetrieveFeedsAsyncTask(BookmarkActivity.this, RetrieveFeedsAsyncTask.Type.CACHE_BOOKMARKS, null, BookmarkActivity.this);
} }
@ -137,10 +137,10 @@ public class BookmarkActivity extends BaseActivity implements OnRetrieveFeedsInt
finish(); finish();
return true; return true;
case R.id.action_export_bookmarks: case R.id.action_export_bookmarks:
new SyncBookmarksAsyncTask(BookmarkActivity.this, SyncBookmarksAsyncTask.sync.EXPORT, BookmarkActivity.this).execute(); new SyncBookmarksAsyncTask(BookmarkActivity.this, SyncBookmarksAsyncTask.sync.EXPORT, BookmarkActivity.this);
return true; return true;
case R.id.action_import_bookmarks: case R.id.action_import_bookmarks:
new SyncBookmarksAsyncTask(BookmarkActivity.this, SyncBookmarksAsyncTask.sync.IMPORT, BookmarkActivity.this).execute(); new SyncBookmarksAsyncTask(BookmarkActivity.this, SyncBookmarksAsyncTask.sync.IMPORT, BookmarkActivity.this);
return true; return true;
default: default:
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
@ -215,7 +215,7 @@ public class BookmarkActivity extends BaseActivity implements OnRetrieveFeedsInt
lv_status.setAdapter(statusListAdapter); lv_status.setAdapter(statusListAdapter);
statusListAdapter.notifyDataSetChanged(); statusListAdapter.notifyDataSetChanged();
textviewNoAction.setVisibility(View.VISIBLE); textviewNoAction.setVisibility(View.VISIBLE);
new PostActionAsyncTask(BookmarkActivity.this, API.StatusAction.UNBOOKMARK).execute(); new PostActionAsyncTask(BookmarkActivity.this, API.StatusAction.UNBOOKMARK);
dialogConfirm.dismiss(); dialogConfirm.dismiss();
}) })
.setNegativeButton(R.string.no, (dialogConfirm, which) -> dialogConfirm.dismiss()) .setNegativeButton(R.string.no, (dialogConfirm, which) -> dialogConfirm.dismiss())

View File

@ -185,7 +185,7 @@ public class CustomSharingActivity extends BaseActivity implements OnCustomShari
"http://example.net/add?token=YOUR_TOKEN&url=${url}&title=${title}" + "http://example.net/add?token=YOUR_TOKEN&url=${url}&title=${title}" +
"&source=${source}&id=${id}&description=${description}&keywords=${keywords}&creator=${creator}&thumbnailurl=${thumbnailurl}"); "&source=${source}&id=${id}&description=${description}&keywords=${keywords}&creator=${creator}&thumbnailurl=${thumbnailurl}");
encodedCustomSharingURL = encodeCustomSharingURL(); encodedCustomSharingURL = encodeCustomSharingURL();
new CustomSharingAsyncTask(CustomSharingActivity.this, encodedCustomSharingURL, CustomSharingActivity.this).execute(); new CustomSharingAsyncTask(CustomSharingActivity.this, encodedCustomSharingURL, CustomSharingActivity.this);
}); });
} }

View File

@ -171,7 +171,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou
set_profile_description.setEnabled(false); set_profile_description.setEnabled(false);
set_lock_account.setEnabled(false); set_lock_account.setEnabled(false);
set_sensitive_content.setEnabled(false); set_sensitive_content.setEnabled(false);
new RetrieveAccountInfoAsyncTask(EditProfileActivity.this, EditProfileActivity.this).execute(); new RetrieveAccountInfoAsyncTask(EditProfileActivity.this, EditProfileActivity.this);
} }
@ -417,7 +417,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou
newCustomFields.put(key3, val3); newCustomFields.put(key3, val3);
newCustomFields.put(key4, val4); newCustomFields.put(key4, val4);
new UpdateCredentialAsyncTask(EditProfileActivity.this, newCustomFields, profile_username, profile_note, profile_picture, avatarName, header_picture, headerName, profile_privacy, sensitive, EditProfileActivity.this).execute(); new UpdateCredentialAsyncTask(EditProfileActivity.this, newCustomFields, profile_username, profile_note, profile_picture, avatarName, header_picture, headerName, profile_privacy, sensitive, EditProfileActivity.this);
}); });
dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss()); dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
AlertDialog alertDialog = dialogBuilder.create(); AlertDialog alertDialog = dialogBuilder.create();

View File

@ -130,7 +130,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf
statuses = new ArrayList<>(); statuses = new ArrayList<>();
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
new RetrieveFeedsAsyncTask(GroupActivity.this, RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this).execute(); new RetrieveFeedsAsyncTask(GroupActivity.this, RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this);
}); });
final LinearLayoutManager mLayoutManager; final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this); mLayoutManager = new LinearLayoutManager(this);
@ -144,7 +144,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
new RetrieveFeedsAsyncTask(GroupActivity.this, RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this).execute(); new RetrieveFeedsAsyncTask(GroupActivity.this, RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
@ -154,7 +154,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf
} }
} }
}); });
new RetrieveFeedsAsyncTask(GroupActivity.this, RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this).execute(); new RetrieveFeedsAsyncTask(GroupActivity.this, RetrieveFeedsAsyncTask.Type.GNU_GROUP_TIMELINE, groupname, null, max_id, GroupActivity.this);
} }

View File

@ -150,7 +150,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
statuses = new ArrayList<>(); statuses = new ArrayList<>();
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
new RetrieveFeedsAsyncTask(HashTagActivity.this, RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this).execute(); new RetrieveFeedsAsyncTask(HashTagActivity.this, RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this);
}); });
final LinearLayoutManager mLayoutManager; final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this); mLayoutManager = new LinearLayoutManager(this);
@ -164,7 +164,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
new RetrieveFeedsAsyncTask(HashTagActivity.this, RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this).execute(); new RetrieveFeedsAsyncTask(HashTagActivity.this, RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
@ -174,7 +174,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
} }
} }
}); });
new RetrieveFeedsAsyncTask(HashTagActivity.this, RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this).execute(); new RetrieveFeedsAsyncTask(HashTagActivity.this, RetrieveFeedsAsyncTask.Type.TAG, tag, null, max_id, HashTagActivity.this);
} }

View File

@ -95,7 +95,7 @@ public class InstanceActivity extends BaseActivity implements OnRetrieveInstance
instance_container.setVisibility(View.GONE); instance_container.setVisibility(View.GONE);
loader.setVisibility(View.VISIBLE); loader.setVisibility(View.VISIBLE);
setTitle(getString(R.string.action_about_instance)); setTitle(getString(R.string.action_about_instance));
new RetrieveInstanceAsyncTask(InstanceActivity.this, InstanceActivity.this).execute(); new RetrieveInstanceAsyncTask(InstanceActivity.this, InstanceActivity.this);
} }

View File

@ -153,7 +153,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
new ManageListsAsyncTask(ListActivity.this, listId, max_id, null, ListActivity.this).execute(); new ManageListsAsyncTask(ListActivity.this, listId, max_id, null, ListActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
} else { } else {
@ -170,10 +170,10 @@ public class ListActivity extends BaseActivity implements OnListActionInterface
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
MainActivity.countNewStatus = 0; MainActivity.countNewStatus = 0;
new ManageListsAsyncTask(ListActivity.this, listId, null, null, ListActivity.this).execute(); new ManageListsAsyncTask(ListActivity.this, listId, null, null, ListActivity.this);
}); });
new ManageListsAsyncTask(ListActivity.this, listId, null, null, ListActivity.this).execute(); new ManageListsAsyncTask(ListActivity.this, listId, null, null, ListActivity.this);
} }
@ -215,7 +215,7 @@ public class ListActivity extends BaseActivity implements OnListActionInterface
editText.setText(title); editText.setText(title);
dialogBuilder.setPositiveButton(R.string.validate, (dialog, id) -> { dialogBuilder.setPositiveButton(R.string.validate, (dialog, id) -> {
if (editText.getText() != null && editText.getText().toString().trim().length() > 0) if (editText.getText() != null && editText.getText().toString().trim().length() > 0)
new ManageListsAsyncTask(ListActivity.this, ManageListsAsyncTask.action.UPDATE_LIST, null, listId, editText.getText().toString(), editText.getText().toString().trim(), ListActivity.this).execute(); new ManageListsAsyncTask(ListActivity.this, ManageListsAsyncTask.action.UPDATE_LIST, null, listId, editText.getText().toString().trim(), ListActivity.this);
dialog.dismiss(); dialog.dismiss();
}); });
dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss()); dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());

View File

@ -161,7 +161,7 @@ public class LoginActivity extends BaseActivity {
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token);
editor.commit(); editor.commit();
//Update the account with the token; //Update the account with the token;
new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork).execute(); new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -598,7 +598,7 @@ public class LoginActivity extends BaseActivity {
//Update the account with the token; //Update the account with the token;
if (instance != null) { if (instance != null) {
new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork).execute(); new UpdateAccountInfoAsyncTask(LoginActivity.this, token, client_id, client_secret, refresh_token, instance, socialNetwork);
} else { } else {
connectionButton.setEnabled(true); connectionButton.setEnabled(true);
Toasty.error(LoginActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); Toasty.error(LoginActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();

View File

@ -99,7 +99,7 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList
list_title.setText(title); list_title.setText(title);
loader.setVisibility(View.VISIBLE); loader.setVisibility(View.VISIBLE);
new ManageListsAsyncTask(ManageAccountsInListActivity.this, ManageListsAsyncTask.action.GET_LIST_ACCOUNT, null, null, listId, null, ManageAccountsInListActivity.this).execute(); new ManageListsAsyncTask(ManageAccountsInListActivity.this, ManageListsAsyncTask.action.GET_LIST_ACCOUNT, null, listId, null, ManageAccountsInListActivity.this);
search_account.addTextChangedListener(new TextWatcher() { search_account.addTextChangedListener(new TextWatcher() {
@ -119,7 +119,7 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
if (s != null && s.length() > 0) { if (s != null && s.length() > 0) {
new ManageListsAsyncTask(ManageAccountsInListActivity.this, s.toString(), ManageAccountsInListActivity.this).execute(); new ManageListsAsyncTask(ManageAccountsInListActivity.this, s.toString(), ManageAccountsInListActivity.this);
} else { } else {
lv_accounts_search.setVisibility(View.GONE); lv_accounts_search.setVisibility(View.GONE);
lv_accounts_current.setVisibility(View.VISIBLE); lv_accounts_current.setVisibility(View.VISIBLE);

View File

@ -19,8 +19,9 @@ import android.animation.AnimatorListenerAdapter;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html; import android.text.Html;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.Spanned; import android.text.Spanned;
@ -65,7 +66,6 @@ import app.fedilab.android.interfaces.OnPostStatusActionInterface;
import app.fedilab.android.interfaces.OnRetrieveInstanceInterface; import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
import es.dmoral.toasty.Toasty; import es.dmoral.toasty.Toasty;
import static android.os.AsyncTask.THREAD_POOL_EXECUTOR;
/** /**
* Created by Thomas on 13/06/2019. * Created by Thomas on 13/06/2019.
@ -150,7 +150,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
reg_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { reg_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override @Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
new RetrieveInstanceRegAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, itemA[position], MastodonRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new RetrieveInstanceRegAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, itemA[position], MastodonRegisterActivity.this);
} }
@Override @Override
@ -159,7 +159,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
} }
}); });
new RetrieveInstanceRegAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, "general", MastodonRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new RetrieveInstanceRegAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, "general", MastodonRegisterActivity.this);
signup = findViewById(R.id.signup); signup = findViewById(R.id.signup);
EditText username = findViewById(R.id.username); EditText username = findViewById(R.id.username);
@ -198,7 +198,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
accountCreation.setPassword(password.getText().toString().trim()); accountCreation.setPassword(password.getText().toString().trim());
accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim()); accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim());
accountCreation.setUsername(username.getText().toString().trim()); accountCreation.setUsername(username.getText().toString().trim());
new CreateMastodonAccountAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, accountCreation, instance, MastodonRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new CreateMastodonAccountAsyncTask(MastodonRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, accountCreation, instance, MastodonRegisterActivity.this);
}); });
@ -287,7 +287,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
private void checkInstance(Context context, String instance) { private void checkInstance(Context context, String instance) {
new checkRegistration(context, instance).executeOnExecutor(THREAD_POOL_EXECUTOR); new checkRegistration(context, instance);
} }
@Override @Override
@ -337,7 +337,7 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
} }
private static class checkRegistration extends AsyncTask<Void, Void, String> { private static class checkRegistration {
private final String instance; private final String instance;
private final WeakReference<Context> weakReference; private final WeakReference<Context> weakReference;
@ -345,35 +345,35 @@ public class MastodonRegisterActivity extends BaseActivity implements OnRetrieve
checkRegistration(Context context, String instance) { checkRegistration(Context context, String instance) {
this.instance = instance; this.instance = instance;
this.weakReference = new WeakReference<>(context); this.weakReference = new WeakReference<>(context);
doInBackground();
} }
@Override protected void doInBackground() {
protected String doInBackground(Void... params) { new Thread(() -> {
String response = null; String response = null;
try { try {
URL url = new URL("https://" + instance + "/auth/sign_up"); URL url = new URL("https://" + instance + "/auth/sign_up");
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
java.util.Scanner s = new java.util.Scanner(connection.getInputStream()).useDelimiter("\\A"); java.util.Scanner s = new java.util.Scanner(connection.getInputStream()).useDelimiter("\\A");
response = s.hasNext() ? s.next() : ""; response = s.hasNext() ? s.next() : "";
}
} catch (IOException e) {
e.printStackTrace();
} }
} catch (IOException e) { Handler mainHandler = new Handler(Looper.getMainLooper());
e.printStackTrace(); String finalResponse = response;
} Runnable myRunnable = () -> {
return response; if (finalResponse != null && finalResponse.contains("invite_request_attributes")) {
TextView invitation = ((MastodonRegisterActivity) (weakReference.get())).findViewById(R.id.invitation);
if (invitation != null) {
invitation.setVisibility(View.VISIBLE);
}
}
};
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(String result) {
if (result != null && result.contains("invite_request_attributes")) {
TextView invitation = ((MastodonRegisterActivity) (weakReference.get())).findViewById(R.id.invitation);
if (invitation != null) {
invitation.setVisibility(View.VISIBLE);
}
}
}
} }
} }

View File

@ -20,8 +20,9 @@ import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html; import android.text.Html;
import android.text.method.LinkMovementMethod; import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -59,7 +60,6 @@ import app.fedilab.android.interfaces.OnPostStatusActionInterface;
import app.fedilab.android.interfaces.OnRetrieveInstanceInterface; import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
import es.dmoral.toasty.Toasty; import es.dmoral.toasty.Toasty;
import static android.os.AsyncTask.THREAD_POOL_EXECUTOR;
/** /**
* Created by Thomas on 17/08/2019. * Created by Thomas on 17/08/2019.
@ -165,7 +165,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet
accountCreation.setPassword(password.getText().toString().trim()); accountCreation.setPassword(password.getText().toString().trim());
accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim()); accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim());
accountCreation.setUsername(username.getText().toString().trim()); accountCreation.setUsername(username.getText().toString().trim());
new CreateMastodonAccountAsyncTask(MastodonShareRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, accountCreation, instance, MastodonShareRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new CreateMastodonAccountAsyncTask(MastodonShareRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.MASTODON, accountCreation, instance, MastodonShareRegisterActivity.this);
}); });
@ -220,7 +220,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet
private void checkInstance(Context context, String instance) { private void checkInstance(Context context, String instance) {
new checkRegistration(context, instance).executeOnExecutor(THREAD_POOL_EXECUTOR); new checkRegistration(context, instance);
} }
@Override @Override
@ -270,7 +270,7 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet
} }
private static class checkRegistration extends AsyncTask<Void, Void, String> { private static class checkRegistration {
private final String instance; private final String instance;
private final WeakReference<Context> weakReference; private final WeakReference<Context> weakReference;
@ -278,35 +278,34 @@ public class MastodonShareRegisterActivity extends BaseActivity implements OnRet
checkRegistration(Context context, String instance) { checkRegistration(Context context, String instance) {
this.instance = instance; this.instance = instance;
this.weakReference = new WeakReference<>(context); this.weakReference = new WeakReference<>(context);
doInBackground();
} }
@Override protected void doInBackground() {
protected String doInBackground(Void... params) { new Thread(() -> {
String response = null; String response = null;
try { try {
URL url = new URL("https://" + instance + "/auth/sign_up"); URL url = new URL("https://" + instance + "/auth/sign_up");
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
java.util.Scanner s = new java.util.Scanner(connection.getInputStream()).useDelimiter("\\A"); java.util.Scanner s = new java.util.Scanner(connection.getInputStream()).useDelimiter("\\A");
response = s.hasNext() ? s.next() : ""; response = s.hasNext() ? s.next() : "";
}
} catch (IOException e) {
e.printStackTrace();
} }
} catch (IOException e) { Handler mainHandler = new Handler(Looper.getMainLooper());
e.printStackTrace(); String finalResponse = response;
} Runnable myRunnable = () -> {
return response; if (finalResponse != null && finalResponse.contains("invite_request_attributes")) {
} TextView invitation = ((MastodonShareRegisterActivity) (weakReference.get())).findViewById(R.id.invitation);
if (invitation != null) {
@Override invitation.setVisibility(View.VISIBLE);
protected void onPostExecute(String result) { }
}
};
if (result != null && result.contains("invite_request_attributes")) { mainHandler.post(myRunnable);
TextView invitation = ((MastodonShareRegisterActivity) (weakReference.get())).findViewById(R.id.invitation); }).start();
if (invitation != null) {
invitation.setVisibility(View.VISIBLE);
}
}
} }
} }
} }

View File

@ -20,7 +20,6 @@ import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -76,7 +75,6 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
private final int PICK_IMPORT_INSTANCE = 5326; private final int PICK_IMPORT_INSTANCE = 5326;
private boolean flag_loading; private boolean flag_loading;
private AsyncTask<Void, Void, Void> asyncTask;
private DomainsListAdapter domainsListAdapter; private DomainsListAdapter domainsListAdapter;
private String max_id; private String max_id;
private List<String> domains; private List<String> domains;
@ -141,7 +139,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
EditText add_domain = dialogView.findViewById(R.id.add_domain); EditText add_domain = dialogView.findViewById(R.id.add_domain);
dialogBuilder.setPositiveButton(R.string.validate, (dialog, id) -> { dialogBuilder.setPositiveButton(R.string.validate, (dialog, id) -> {
if (add_domain.getText() != null && add_domain.getText().toString().trim().matches("^[\\da-zA-Z.-]+\\.[a-zA-Z.]{2,10}$")) { if (add_domain.getText() != null && add_domain.getText().toString().trim().matches("^[\\da-zA-Z.-]+\\.[a-zA-Z.]{2,10}$")) {
new PostActionAsyncTask(MutedInstanceActivity.this, API.StatusAction.BLOCK_DOMAIN, add_domain.getText().toString().trim(), MutedInstanceActivity.this).execute(); new PostActionAsyncTask(MutedInstanceActivity.this, API.StatusAction.BLOCK_DOMAIN, add_domain.getText().toString().trim(), MutedInstanceActivity.this);
dialog.dismiss(); dialog.dismiss();
} else { } else {
Toasty.error(MutedInstanceActivity.this, getString(R.string.toast_empty_content)).show(); Toasty.error(MutedInstanceActivity.this, getString(R.string.toast_empty_content)).show();
@ -225,7 +223,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).execute(); new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
} else { } else {
@ -240,7 +238,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
firstLoad = true; firstLoad = true;
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).execute(); new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this);
}); });
switch (theme) { switch (theme) {
case Helper.THEME_LIGHT: case Helper.THEME_LIGHT:
@ -263,7 +261,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
break; break;
} }
asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).execute(); new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this);
setTitle(R.string.blocked_domains); setTitle(R.string.blocked_domains);
} }
@ -271,8 +269,6 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
@Override @Override
public void onDestroy() { public void onDestroy() {
super.onDestroy(); super.onDestroy();
if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING)
asyncTask.cancel(true);
} }
@Override @Override

View File

@ -114,7 +114,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
lv_mastohost.setAdapter(mastohostAdapter); lv_mastohost.setAdapter(mastohostAdapter);
new RetrieveRemoteDataAsyncTask(PartnerShipActivity.this, "mastohost", "mastodon.social", PartnerShipActivity.this).execute(); new RetrieveRemoteDataAsyncTask(PartnerShipActivity.this, "mastohost", "mastodon.social", PartnerShipActivity.this);
} }
@Override @Override
@ -142,7 +142,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
mastohostAcct.add(account); mastohostAcct.add(account);
mastohostAdapter.notifyDataSetChanged(); mastohostAdapter.notifyDataSetChanged();
} }
new RetrieveRelationshipAsyncTask(PartnerShipActivity.this, account.getId(), PartnerShipActivity.this).execute(); new RetrieveRelationshipAsyncTask(PartnerShipActivity.this, account.getId(), PartnerShipActivity.this);
} }
} }
@ -152,7 +152,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
super.onResume(); super.onResume();
if (mastohostAcct != null) { if (mastohostAcct != null) {
for (Account account : mastohostAcct) { for (Account account : mastohostAcct) {
new RetrieveRelationshipAsyncTask(PartnerShipActivity.this, account.getId(), PartnerShipActivity.this).execute(); new RetrieveRelationshipAsyncTask(PartnerShipActivity.this, account.getId(), PartnerShipActivity.this);
} }
} }
} }

View File

@ -28,9 +28,10 @@ import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html; import android.text.Html;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
@ -212,7 +213,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
send.setOnClickListener(v -> { send.setOnClickListener(v -> {
String comment = add_comment_write.getText().toString(); String comment = add_comment_write.getText().toString();
if (comment.trim().length() > 0) { if (comment.trim().length() > 0) {
new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.PEERTUBECOMMENT, peertube.getId(), null, comment, PeertubeActivity.this).execute(); new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.PEERTUBECOMMENT, peertube.getId(), null, comment, PeertubeActivity.this);
add_comment_write.setText(""); add_comment_write.setText("");
add_comment_read.setVisibility(View.VISIBLE); add_comment_read.setVisibility(View.VISIBLE);
add_comment_write.setVisibility(View.GONE); add_comment_write.setVisibility(View.GONE);
@ -303,10 +304,10 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
} }
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
new ManagePlaylistsAsyncTask(PeertubeActivity.this, GET_PLAYLIST, null, null, null, PeertubeActivity.this).execute(); new ManagePlaylistsAsyncTask(PeertubeActivity.this, GET_PLAYLIST, null, null, null, PeertubeActivity.this);
} }
new RetrievePeertubeSingleAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).execute(); new RetrievePeertubeSingleAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this);
} }
public void change() { public void change() {
@ -361,52 +362,51 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { int itemId = item.getItemId();
case android.R.id.home: if (itemId == android.R.id.home) {
finish(); finish();
return true; return true;
case R.id.action_comment: } else if (itemId == R.id.action_comment) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { 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(); Toasty.info(PeertubeActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show();
new commentTask(new WeakReference<>(PeertubeActivity.this), peertube).execute(); new commentTask(new WeakReference<>(PeertubeActivity.this), peertube);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
if (!peertube.isCommentsEnabled()) { if (!peertube.isCommentsEnabled()) {
Toasty.info(PeertubeActivity.this, getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show(); Toasty.info(PeertubeActivity.this, getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show();
return true; return true;
}
int style;
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
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(PeertubeActivity.this, style);
builderInner.setTitle(R.string.comment);
EditText input = new EditText(PeertubeActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
builderInner.setView(input);
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.validate, (dialog, which) -> {
String comment = input.getText().toString();
if (comment.trim().length() > 0) {
new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.PEERTUBECOMMENT, peertube.getId(), null, comment, PeertubeActivity.this).execute();
dialog.dismiss();
}
});
builderInner.show();
} }
return true; int style;
default: SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
return super.onOptionsItemSelected(item); int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
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(PeertubeActivity.this, style);
builderInner.setTitle(R.string.comment);
EditText input = new EditText(PeertubeActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
builderInner.setView(input);
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.validate, (dialog, which) -> {
String comment = input.getText().toString();
if (comment.trim().length() > 0) {
new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.PEERTUBECOMMENT, peertube.getId(), null, comment, PeertubeActivity.this);
dialog.dismiss();
}
});
builderInner.show();
}
return true;
} }
return super.onOptionsItemSelected(item);
} }
public FullScreenMediaController.fullscreen getFullscreen() { public FullScreenMediaController.fullscreen getFullscreen() {
@ -434,7 +434,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
peertube = apiResponse.getPeertubes().get(0); peertube = apiResponse.getPeertubes().get(0);
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
new ManagePlaylistsAsyncTask(PeertubeActivity.this, GET_PLAYLIST_FOR_VIDEO, null, peertube.getId(), null, PeertubeActivity.this).execute(); new ManagePlaylistsAsyncTask(PeertubeActivity.this, GET_PLAYLIST_FOR_VIDEO, null, peertube.getId(), null, PeertubeActivity.this);
} }
@ -470,11 +470,11 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
}); });
if (playlistForVideo.contains(playlist.getId())) { if (playlistForVideo.contains(playlist.getId())) {
item1.setTitle(playlist.getDisplayName()); item1.setTitle(playlist.getDisplayName());
new ManagePlaylistsAsyncTask(PeertubeActivity.this, ManagePlaylistsAsyncTask.action.DELETE_VIDEOS, playlist, peertube.getId(), null, PeertubeActivity.this).execute(); new ManagePlaylistsAsyncTask(PeertubeActivity.this, ManagePlaylistsAsyncTask.action.DELETE_VIDEOS, playlist, peertube.getId(), null, PeertubeActivity.this);
playlistForVideo.remove(playlist.getId()); playlistForVideo.remove(playlist.getId());
} else { } else {
item1.setTitle("" + playlist.getDisplayName()); item1.setTitle("" + playlist.getDisplayName());
new ManagePlaylistsAsyncTask(PeertubeActivity.this, ManagePlaylistsAsyncTask.action.ADD_VIDEOS, playlist, peertube.getId(), null, PeertubeActivity.this).execute(); new ManagePlaylistsAsyncTask(PeertubeActivity.this, ManagePlaylistsAsyncTask.action.ADD_VIDEOS, playlist, peertube.getId(), null, PeertubeActivity.this);
playlistForVideo.add(playlist.getId()); playlistForVideo.add(playlist.getId());
} }
return false; return false;
@ -486,7 +486,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
if (peertube.isCommentsEnabled()) { if (peertube.isCommentsEnabled()) {
new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).execute(); new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this);
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
write_comment_container.setVisibility(View.VISIBLE); write_comment_container.setVisibility(View.VISIBLE);
} else { } else {
@ -512,13 +512,13 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
peertube_like_count.setOnClickListener(v -> { peertube_like_count.setOnClickListener(v -> {
String newState = peertube.getMyRating().equals("like") ? "none" : "like"; String newState = peertube.getMyRating().equals("like") ? "none" : "like";
new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.RATEVIDEO, peertube.getId(), null, newState, PeertubeActivity.this).execute(); new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.RATEVIDEO, peertube.getId(), null, newState, PeertubeActivity.this);
peertube.setMyRating(newState); peertube.setMyRating(newState);
changeColor(); changeColor();
}); });
peertube_dislike_count.setOnClickListener(v -> { peertube_dislike_count.setOnClickListener(v -> {
String newState = peertube.getMyRating().equals("dislike") ? "none" : "dislike"; String newState = peertube.getMyRating().equals("dislike") ? "none" : "dislike";
new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.RATEVIDEO, peertube.getId(), null, newState, PeertubeActivity.this).execute(); new PostActionAsyncTask(PeertubeActivity.this, API.StatusAction.RATEVIDEO, peertube.getId(), null, newState, PeertubeActivity.this);
peertube.setMyRating(newState); peertube.setMyRating(newState);
changeColor(); changeColor();
}); });
@ -777,7 +777,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) { public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) {
if (peertube.isCommentsEnabled() && statusAction == API.StatusAction.PEERTUBECOMMENT) if (peertube.isCommentsEnabled() && statusAction == API.StatusAction.PEERTUBECOMMENT)
new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).execute(); new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this);
} }
@ -852,7 +852,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
} }
} }
private static class commentTask extends AsyncTask<Void, Void, app.fedilab.android.client.Entities.Status> { private static class commentTask {
private final WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final Peertube peertube; private final Peertube peertube;
@ -860,40 +860,42 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
commentTask(WeakReference<Context> contextReference, Peertube peertube) { commentTask(WeakReference<Context> contextReference, Peertube peertube) {
this.peertube = peertube; this.peertube = peertube;
this.contextReference = contextReference; this.contextReference = contextReference;
doInBackground();
} }
@Override protected void doInBackground() {
protected app.fedilab.android.client.Entities.Status doInBackground(Void... voids) { new Thread(() -> {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = null;
List<app.fedilab.android.client.Entities.Status> remoteStatuses = null; if (peertube != null) {
if (peertube != null) { APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid());
APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid()); if (search != null && search.getResults() != null) {
if (search != null && search.getResults() != null) { remoteStatuses = search.getResults().getStatuses();
remoteStatuses = search.getResults().getStatuses(); }
} }
} app.fedilab.android.client.Entities.Status remoteStatuse = null;
if (remoteStatuses != null && remoteStatuses.size() > 0) { if (remoteStatuses != null && remoteStatuses.size() > 0) {
return remoteStatuses.get(0); remoteStatuse = remoteStatuses.get(0);
} else { }
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
} app.fedilab.android.client.Entities.Status finalRemoteStatuse = remoteStatuse;
Runnable myRunnable = () -> {
Intent intent = new Intent(contextReference.get(), TootActivity.class);
Bundle b = new Bundle();
if (finalRemoteStatuse == null) {
Toasty.error(contextReference.get(), contextReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
return;
}
if (finalRemoteStatuse.getReblog() != null) {
b.putParcelable("tootReply", finalRemoteStatuse.getReblog());
} else {
b.putParcelable("tootReply", finalRemoteStatuse);
}
intent.putExtras(b);
contextReference.get().startActivity(intent);
};
mainHandler.post(myRunnable);
}).start();
} }
@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

@ -59,7 +59,6 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface;
import es.dmoral.toasty.Toasty; import es.dmoral.toasty.Toasty;
import mabbas007.tagsedittext.TagsEditText; import mabbas007.tagsedittext.TagsEditText;
import static android.os.AsyncTask.THREAD_POOL_EXECUTOR;
import static app.fedilab.android.asynctasks.RetrievePeertubeInformationAsyncTask.peertubeInformation; import static app.fedilab.android.asynctasks.RetrievePeertubeInformationAsyncTask.peertubeInformation;
public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrievePeertubeInterface, OnPostActionInterface { public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrievePeertubeInterface, OnPostActionInterface {
@ -151,7 +150,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
builderInner.setMessage(getString(R.string.delete_video_confirmation)); builderInner.setMessage(getString(R.string.delete_video_confirmation));
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.yes, (dialog, which) -> { builderInner.setPositiveButton(R.string.yes, (dialog, which) -> {
new PostActionAsyncTask(PeertubeEditUploadActivity.this, API.StatusAction.PEERTUBEDELETEVIDEO, videoId, PeertubeEditUploadActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new PostActionAsyncTask(PeertubeEditUploadActivity.this, API.StatusAction.PEERTUBEDELETEVIDEO, videoId, PeertubeEditUploadActivity.this);
dialog.dismiss(); dialog.dismiss();
}); });
builderInner.show(); builderInner.show();
@ -237,7 +236,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
String peertubeInstance = Helper.getLiveInstance(PeertubeEditUploadActivity.this); String peertubeInstance = Helper.getLiveInstance(PeertubeEditUploadActivity.this);
new RetrievePeertubeSingleAsyncTask(PeertubeEditUploadActivity.this, peertubeInstance, videoId, PeertubeEditUploadActivity.this).execute(); new RetrievePeertubeSingleAsyncTask(PeertubeEditUploadActivity.this, peertubeInstance, videoId, PeertubeEditUploadActivity.this);
channels = new LinkedHashMap<>(); channels = new LinkedHashMap<>();
@ -264,7 +263,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
peertube.setUpdate(false); peertube.setUpdate(false);
set_upload_submit.setEnabled(true); set_upload_submit.setEnabled(true);
} else { } else {
new RetrievePeertubeChannelsAsyncTask(PeertubeEditUploadActivity.this, PeertubeEditUploadActivity.this).execute(); new RetrievePeertubeChannelsAsyncTask(PeertubeEditUploadActivity.this, PeertubeEditUploadActivity.this);
} }
languageToSend = peertube.getLanguage(); languageToSend = peertube.getLanguage();
@ -528,7 +527,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
List<String> tags = p_video_tags.getTags(); List<String> tags = p_video_tags.getTags();
peertube.setTags(tags); peertube.setTags(tags);
set_upload_submit.setEnabled(false); set_upload_submit.setEnabled(false);
new PostPeertubeAsyncTask(PeertubeEditUploadActivity.this, peertube, PeertubeEditUploadActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new PostPeertubeAsyncTask(PeertubeEditUploadActivity.this, peertube, PeertubeEditUploadActivity.this);
}); });
set_upload_privacy.setSelection(privacyPosition); set_upload_privacy.setSelection(privacyPosition);

View File

@ -57,8 +57,6 @@ import app.fedilab.android.interfaces.OnPostStatusActionInterface;
import app.fedilab.android.interfaces.OnRetrieveInstanceInterface; import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
import es.dmoral.toasty.Toasty; import es.dmoral.toasty.Toasty;
import static android.os.AsyncTask.THREAD_POOL_EXECUTOR;
/** /**
* Created by Thomas on 04/11/2019. * Created by Thomas on 04/11/2019.
* Register activity class * Register activity class
@ -104,7 +102,7 @@ public class PeertubeRegisterActivity extends BaseActivity implements OnRetrieve
} }
new RetrieveInstanceRegAsyncTask(PeertubeRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.PEERTUBE, null, PeertubeRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new RetrieveInstanceRegAsyncTask(PeertubeRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.PEERTUBE, null, PeertubeRegisterActivity.this);
signup = findViewById(R.id.signup); signup = findViewById(R.id.signup);
EditText username = findViewById(R.id.username); EditText username = findViewById(R.id.username);
@ -143,7 +141,7 @@ public class PeertubeRegisterActivity extends BaseActivity implements OnRetrieve
accountCreation.setPassword(password.getText().toString().trim()); accountCreation.setPassword(password.getText().toString().trim());
accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim()); accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim());
accountCreation.setUsername(username.getText().toString().trim()); accountCreation.setUsername(username.getText().toString().trim());
new CreateMastodonAccountAsyncTask(PeertubeRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.PEERTUBE, accountCreation, instance, PeertubeRegisterActivity.this).executeOnExecutor(THREAD_POOL_EXECUTOR); new CreateMastodonAccountAsyncTask(PeertubeRegisterActivity.this, RetrieveInstanceRegAsyncTask.instanceType.PEERTUBE, accountCreation, instance, PeertubeRegisterActivity.this);
}); });

View File

@ -131,7 +131,7 @@ public class PeertubeUploadActivity extends BaseActivity implements OnRetrievePe
set_upload_submit = findViewById(R.id.set_upload_submit); set_upload_submit = findViewById(R.id.set_upload_submit);
video_title = findViewById(R.id.video_title); video_title = findViewById(R.id.video_title);
new RetrievePeertubeChannelsAsyncTask(PeertubeUploadActivity.this, PeertubeUploadActivity.this).execute(); new RetrievePeertubeChannelsAsyncTask(PeertubeUploadActivity.this, PeertubeUploadActivity.this);
channels = new HashMap<>(); channels = new HashMap<>();
uploadReceiver = new UploadServiceSingleBroadcastReceiver(this); uploadReceiver = new UploadServiceSingleBroadcastReceiver(this);

View File

@ -160,7 +160,7 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) { if (!flag_loading) {
flag_loading = true; flag_loading = true;
new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, max_id, PlaylistsActivity.this).execute(); new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, max_id, PlaylistsActivity.this);
nextElementLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.VISIBLE);
} }
} else { } else {
@ -177,10 +177,10 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
flag_loading = true; flag_loading = true;
swiped = true; swiped = true;
MainActivity.countNewStatus = 0; MainActivity.countNewStatus = 0;
new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).execute(); new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this);
}); });
new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this).execute(); new ManagePlaylistsAsyncTask(PlaylistsActivity.this, GET_LIST_VIDEOS, playlist, null, null, PlaylistsActivity.this);
} }

View File

@ -358,7 +358,7 @@ public class ReorderTimelinesActivity extends BaseActivity implements OnStartDra
break; break;
case LIST: case LIST:
timeline = manageTimelines; timeline = manageTimelines;
new ManageListsAsyncTask(ReorderTimelinesActivity.this, ManageListsAsyncTask.action.DELETE_LIST, null, null, manageTimelines.getListTimeline().getId(), null, ReorderTimelinesActivity.this).execute(); new ManageListsAsyncTask(ReorderTimelinesActivity.this, ManageListsAsyncTask.action.DELETE_LIST, null, manageTimelines.getListTimeline().getId(), null, ReorderTimelinesActivity.this);
new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(timeline); new TimelinesDAO(ReorderTimelinesActivity.this, db).remove(timeline);
refresh_list = true; refresh_list = true;
break; break;

View File

@ -87,7 +87,7 @@ public class SearchResultActivity extends BaseActivity implements OnRetrieveSear
if (b != null) { if (b != null) {
search = b.getString("search"); search = b.getString("search");
if (search != null) if (search != null)
new RetrieveSearchAsyncTask(SearchResultActivity.this, search.trim(), SearchResultActivity.this).execute(); new RetrieveSearchAsyncTask(SearchResultActivity.this, search.trim(), SearchResultActivity.this);
else else
Toasty.error(SearchResultActivity.this, getString(R.string.toast_error_search), Toast.LENGTH_LONG).show(); Toasty.error(SearchResultActivity.this, getString(R.string.toast_error_search), Toast.LENGTH_LONG).show();
} else { } else {

View File

@ -22,7 +22,6 @@ import android.content.res.ColorStateList;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.text.Spannable; import android.text.Spannable;
@ -161,8 +160,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
private String accountId; private String accountId;
private boolean ischannel; private boolean ischannel;
private ScheduledExecutorService scheduledExecutorService; private ScheduledExecutorService scheduledExecutorService;
private AsyncTask<Void, Void, Void> accountAsync;
private AsyncTask<Void, Void, Void> retrieveRelationship;
private action doAction; private action doAction;
private API.StatusAction doActionAccount; private API.StatusAction doActionAccount;
@ -206,7 +203,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
ischannel = b.getBoolean("ischannel", false); ischannel = b.getBoolean("ischannel", false);
peertubeAccount = b.getBoolean("peertubeaccount", false); peertubeAccount = b.getBoolean("peertubeaccount", false);
if (account == null) { if (account == null) {
accountAsync = new RetrieveAccountAsyncTask(ShowAccountActivity.this, accountId, ShowAccountActivity.this).execute(); new RetrieveAccountAsyncTask(ShowAccountActivity.this, accountId, ShowAccountActivity.this);
} }
userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
@ -297,7 +294,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
accountIdRelation = account.getAcct(); accountIdRelation = account.getAcct();
} }
retrieveRelationship = new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, accountIdRelation, ShowAccountActivity.this).execute(); new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, accountIdRelation, ShowAccountActivity.this);
if (account.getId() != null && account.getId().equals(userId) && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED)) { if (account.getId() != null && account.getId().equals(userId) && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED)) {
account_follow.setVisibility(View.GONE); account_follow.setVisibility(View.GONE);
@ -306,7 +303,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
} }
//TODO: add other software that supports identity proofs //TODO: add other software that supports identity proofs
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON) {
new RetrieveIdentityProofAsyncTask(ShowAccountActivity.this, account.getId(), ShowAccountActivity.this).execute(); new RetrieveIdentityProofAsyncTask(ShowAccountActivity.this, account.getId(), ShowAccountActivity.this);
} }
String urlHeader = account.getHeader(); String urlHeader = account.getHeader();
if (urlHeader != null && urlHeader.startsWith("/")) { if (urlHeader != null && urlHeader.startsWith("/")) {
@ -623,11 +620,8 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
account_note.setText(account.getNoteSpan(), TextView.BufferType.SPANNABLE); account_note.setText(account.getNoteSpan(), TextView.BufferType.SPANNABLE);
account_note.setMovementMethod(LinkMovementMethod.getInstance()); account_note.setMovementMethod(LinkMovementMethod.getInstance());
if (!peertubeAccount && tabLayout.getTabAt(0) != null && tabLayout.getTabAt(1) != null && tabLayout.getTabAt(2) != null) { if (!peertubeAccount && tabLayout.getTabAt(0) != null && tabLayout.getTabAt(1) != null && tabLayout.getTabAt(2) != null) {
//noinspection ConstantConditions
tabLayout.getTabAt(0).setText(getString(R.string.status_cnt, Helper.withSuffix(account.getStatuses_count()))); tabLayout.getTabAt(0).setText(getString(R.string.status_cnt, Helper.withSuffix(account.getStatuses_count())));
//noinspection ConstantConditions
tabLayout.getTabAt(1).setText(getString(R.string.following_cnt, Helper.withSuffix(account.getFollowing_count()))); tabLayout.getTabAt(1).setText(getString(R.string.following_cnt, Helper.withSuffix(account.getFollowing_count())));
//noinspection ConstantConditions
tabLayout.getTabAt(2).setText(getString(R.string.followers_cnt, Helper.withSuffix(account.getFollowers_count()))); tabLayout.getTabAt(2).setText(getString(R.string.followers_cnt, Helper.withSuffix(account.getFollowers_count())));
//Allows to filter by long click //Allows to filter by long click
@ -687,28 +681,24 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
return false; return false;
} }
}); });
switch (item.getItemId()) { int itemId = item.getItemId();
case R.id.action_show_pinned: if (itemId == R.id.action_show_pinned) {
showPinned = !showPinned; showPinned = !showPinned;
break; } else if (itemId == R.id.action_show_media) {
case R.id.action_show_media: showMediaOnly = !showMediaOnly;
showMediaOnly = !showMediaOnly; } else if (itemId == R.id.action_show_boosts) {
break; show_boosts = !show_boosts;
case R.id.action_show_boosts: SharedPreferences.Editor editor = sharedpreferences.edit();
show_boosts = !show_boosts; editor.putBoolean(Helper.SHOW_ACCOUNT_BOOSTS, show_boosts);
SharedPreferences.Editor editor = sharedpreferences.edit(); editor.apply();
editor.putBoolean(Helper.SHOW_ACCOUNT_BOOSTS, show_boosts); } else if (itemId == R.id.action_show_replies) {
editor.apply(); SharedPreferences.Editor editor;
break; show_replies = !show_replies;
case R.id.action_show_replies: editor = sharedpreferences.edit();
show_replies = !show_replies; editor.putBoolean(Helper.SHOW_ACCOUNT_REPLIES, show_replies);
editor = sharedpreferences.edit(); editor.apply();
editor.putBoolean(Helper.SHOW_ACCOUNT_REPLIES, show_replies);
editor.apply();
break;
} }
if (tabLayout.getTabAt(0) != null) if (tabLayout.getTabAt(0) != null)
//noinspection ConstantConditions
tabLayout.getTabAt(0).select(); tabLayout.getTabAt(0).select();
PagerAdapter mPagerAdapter1 = new ScreenSlidePagerAdapter(getSupportFragmentManager()); PagerAdapter mPagerAdapter1 = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter1); mPager.setAdapter(mPagerAdapter1);
@ -760,7 +750,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
Toasty.info(ShowAccountActivity.this, getString(R.string.nothing_to_do), Toast.LENGTH_LONG).show(); Toasty.info(ShowAccountActivity.this, getString(R.string.nothing_to_do), Toast.LENGTH_LONG).show();
} else if (doAction == action.FOLLOW) { } else if (doAction == action.FOLLOW) {
account_follow.setEnabled(false); account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.FOLLOW, finalTarget, ShowAccountActivity.this).execute(); new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.FOLLOW, finalTarget, ShowAccountActivity.this);
} else if (doAction == action.UNFOLLOW) { } else if (doAction == action.UNFOLLOW) {
boolean confirm_unfollow = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true); boolean confirm_unfollow = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true);
if (confirm_unfollow) { if (confirm_unfollow) {
@ -770,18 +760,18 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
unfollowConfirm.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); unfollowConfirm.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
unfollowConfirm.setPositiveButton(R.string.yes, (dialog, which) -> { unfollowConfirm.setPositiveButton(R.string.yes, (dialog, which) -> {
account_follow.setEnabled(false); account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNFOLLOW, finalTarget, ShowAccountActivity.this).execute(); new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNFOLLOW, finalTarget, ShowAccountActivity.this);
dialog.dismiss(); dialog.dismiss();
}); });
unfollowConfirm.show(); unfollowConfirm.show();
} else { } else {
account_follow.setEnabled(false); account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNFOLLOW, finalTarget, ShowAccountActivity.this).execute(); new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNFOLLOW, finalTarget, ShowAccountActivity.this);
} }
} else if (doAction == action.UNBLOCK) { } else if (doAction == action.UNBLOCK) {
account_follow.setEnabled(false); account_follow.setEnabled(false);
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNBLOCK, finalTarget, ShowAccountActivity.this).execute(); new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNBLOCK, finalTarget, ShowAccountActivity.this);
} }
}); });
account_follow.setOnLongClickListener(v -> { account_follow.setOnLongClickListener(v -> {
@ -875,7 +865,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if (pins != null && pins.size() > 0) { if (pins != null && pins.size() > 0) {
if (pins.get(0).isPinned()) { if (pins.get(0).isPinned()) {
this.statuses.addAll(pins); this.statuses.addAll(pins);
//noinspection ConstantConditions
tabLayout.getTabAt(3).setText(getString(R.string.pins_cnt, pins.size())); tabLayout.getTabAt(3).setText(getString(R.string.pins_cnt, pins.size()));
statusListAdapter.notifyDataSetChanged(); statusListAdapter.notifyDataSetChanged();
} }
@ -1117,241 +1106,242 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
style = R.style.Dialog; style = R.style.Dialog;
} }
final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
switch (item.getItemId()) { int itemId = item.getItemId();
case R.id.action_follow_instance: if (itemId == R.id.action_follow_instance) {
String finalInstanceName = splitAcct[1]; String finalInstanceName = splitAcct[1];
List<RemoteInstance> remoteInstances = new InstancesDAO(ShowAccountActivity.this, db).getInstanceByName(finalInstanceName); List<RemoteInstance> remoteInstances = new InstancesDAO(ShowAccountActivity.this, db).getInstanceByName(finalInstanceName);
if (remoteInstances != null && remoteInstances.size() > 0) { if (remoteInstances != null && remoteInstances.size() > 0) {
Toasty.info(ShowAccountActivity.this, getString(R.string.toast_instance_already_added), Toast.LENGTH_LONG).show(); Toasty.info(ShowAccountActivity.this, getString(R.string.toast_instance_already_added), Toast.LENGTH_LONG).show();
Intent intent = new Intent(ShowAccountActivity.this, MainActivity.class); Intent intent = new Intent(ShowAccountActivity.this, MainActivity.class);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putInt(Helper.INTENT_ACTION, Helper.SEARCH_INSTANCE); bundle.putInt(Helper.INTENT_ACTION, Helper.SEARCH_INSTANCE);
bundle.putString(Helper.INSTANCE_NAME, finalInstanceName); bundle.putString(Helper.INSTANCE_NAME, finalInstanceName);
intent.putExtras(bundle); intent.putExtras(bundle);
startActivity(intent); startActivity(intent);
return true;
}
new Thread(() -> {
try {
if (!peertubeAccount) {
//Here we can't know if the instance is a Mastodon one or not
try { //Testing Mastodon
new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/timelines/public?local=true", 10, null, null);
} catch (Exception ignored) {
new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/videos/", 10, null, null);
peertubeAccount = true;
}
} else
new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/videos/", 10, null, null);
runOnUiThread(() -> {
if (!peertubeAccount)
new InstancesDAO(ShowAccountActivity.this, db).insertInstance(finalInstanceName, "MASTODON");
else
new InstancesDAO(ShowAccountActivity.this, db).insertInstance(finalInstanceName, "PEERTUBE");
Toasty.success(ShowAccountActivity.this, getString(R.string.toast_instance_followed), Toast.LENGTH_LONG).show();
Intent intent = new Intent(ShowAccountActivity.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putInt(Helper.INTENT_ACTION, Helper.SEARCH_INSTANCE);
bundle.putString(Helper.INSTANCE_NAME, finalInstanceName);
intent.putExtras(bundle);
startActivity(intent);
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toasty.warning(ShowAccountActivity.this, getString(R.string.toast_instance_unavailable), Toast.LENGTH_LONG).show());
}
}).start();
return true;
} else if (itemId == R.id.action_filter) {
AlertDialog.Builder filterTagDialog = new AlertDialog.Builder(ShowAccountActivity.this, style);
Set<String> featuredTagsSet = sharedpreferences.getStringSet(Helper.SET_FEATURED_TAGS, null);
List<String> tags = new ArrayList<>();
if (featuredTagsSet != null) {
tags = new ArrayList<>(featuredTagsSet);
}
tags.add(0, getString(R.string.no_tags));
String[] tagsString = tags.toArray(new String[0]);
List<String> finalTags = tags;
String tag = sharedpreferences.getString(Helper.SET_FEATURED_TAG_ACTION, null);
int checkedposition = 0;
int i = 0;
for (String _t : tags) {
if (_t.equals(tag))
checkedposition = i;
i++;
}
filterTagDialog.setSingleChoiceItems(tagsString, checkedposition, (dialog, item1) -> {
String tag1;
if (item1 == 0) {
tag1 = null;
} else {
tag1 = finalTags.get(item1);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.SET_FEATURED_TAG_ACTION, tag1);
editor.apply();
dialog.dismiss();
});
filterTagDialog.show();
return true;
} else if (itemId == R.id.action_endorse) {
if (relationship != null)
if (relationship.isEndorsed()) {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNENDORSE, account.getId(), ShowAccountActivity.this);
} else {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.ENDORSE, account.getId(), ShowAccountActivity.this);
}
return true;
} else if (itemId == R.id.action_hide_boost) {
if (relationship != null)
if (relationship.isShowing_reblogs()) {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.HIDE_BOOST, account.getId(), ShowAccountActivity.this);
} else {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.SHOW_BOOST, account.getId(), ShowAccountActivity.this);
}
return true;
} else if (itemId == R.id.action_direct_message) {
Intent intent = new Intent(ShowAccountActivity.this, TootActivity.class);
Bundle b = new Bundle();
b.putString("mentionAccount", account.getAcct());
b.putString("visibility", "direct");
intent.putExtras(b);
startActivity(intent);
return true;
} else if (itemId == R.id.action_add_to_list) {
if (timelines != null) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(ShowAccountActivity.this, android.R.layout.select_dialog_item);
boolean hasLists = false;
for (ManageTimelines timeline : timelines) {
if (timeline.getListTimeline() != null) {
arrayAdapter.add(timeline.getListTimeline().getTitle());
hasLists = true;
}
}
if (!hasLists) {
Toasty.info(ShowAccountActivity.this, getString(R.string.action_lists_empty), Toast.LENGTH_SHORT).show();
return true; return true;
} }
new Thread(() -> { AlertDialog.Builder builderSingle = new AlertDialog.Builder(ShowAccountActivity.this, style);
try { builderSingle.setTitle(getString(R.string.action_lists_add_to));
if (!peertubeAccount) { builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
//Here we can't know if the instance is a Mastodon one or not
try { //Testing Mastodon
new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/timelines/public?local=true", 10, null, null);
} catch (Exception ignored) {
new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/videos/", 10, null, null);
peertubeAccount = true;
}
} else
new HttpsConnection(ShowAccountActivity.this, null).get("https://" + finalInstanceName + "/api/v1/videos/", 10, null, null);
runOnUiThread(() -> { builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {
if (!peertubeAccount) String listTitle = arrayAdapter.getItem(which);
new InstancesDAO(ShowAccountActivity.this, db).insertInstance(finalInstanceName, "MASTODON");
else
new InstancesDAO(ShowAccountActivity.this, db).insertInstance(finalInstanceName, "PEERTUBE");
Toasty.success(ShowAccountActivity.this, getString(R.string.toast_instance_followed), Toast.LENGTH_LONG).show();
Intent intent = new Intent(ShowAccountActivity.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putInt(Helper.INTENT_ACTION, Helper.SEARCH_INSTANCE);
bundle.putString(Helper.INSTANCE_NAME, finalInstanceName);
intent.putExtras(bundle);
startActivity(intent);
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toasty.warning(ShowAccountActivity.this, getString(R.string.toast_instance_unavailable), Toast.LENGTH_LONG).show());
}
}).start();
return true;
case R.id.action_filter:
AlertDialog.Builder filterTagDialog = new AlertDialog.Builder(ShowAccountActivity.this, style);
Set<String> featuredTagsSet = sharedpreferences.getStringSet(Helper.SET_FEATURED_TAGS, null);
List<String> tags = new ArrayList<>();
if (featuredTagsSet != null) {
tags = new ArrayList<>(featuredTagsSet);
}
tags.add(0, getString(R.string.no_tags));
String[] tagsString = tags.toArray(new String[0]);
List<String> finalTags = tags;
String tag = sharedpreferences.getString(Helper.SET_FEATURED_TAG_ACTION, null);
int checkedposition = 0;
int i = 0;
for (String _t : tags) {
if (_t.equals(tag))
checkedposition = i;
i++;
}
filterTagDialog.setSingleChoiceItems(tagsString, checkedposition, (dialog, item1) -> {
String tag1;
if (item1 == 0) {
tag1 = null;
} else {
tag1 = finalTags.get(item1);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.SET_FEATURED_TAG_ACTION, tag1);
editor.apply();
dialog.dismiss();
});
filterTagDialog.show();
return true;
case R.id.action_endorse:
if (relationship != null)
if (relationship.isEndorsed()) {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.UNENDORSE, account.getId(), ShowAccountActivity.this).execute();
} else {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.ENDORSE, account.getId(), ShowAccountActivity.this).execute();
}
return true;
case R.id.action_hide_boost:
if (relationship != null)
if (relationship.isShowing_reblogs()) {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.HIDE_BOOST, account.getId(), ShowAccountActivity.this).execute();
} else {
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.SHOW_BOOST, account.getId(), ShowAccountActivity.this).execute();
}
return true;
case R.id.action_direct_message:
Intent intent = new Intent(ShowAccountActivity.this, TootActivity.class);
Bundle b = new Bundle();
b.putString("mentionAccount", account.getAcct());
b.putString("visibility", "direct");
intent.putExtras(b);
startActivity(intent);
return true;
case R.id.action_add_to_list:
if (timelines != null) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(ShowAccountActivity.this, android.R.layout.select_dialog_item);
boolean hasLists = false;
for (ManageTimelines timeline : timelines) { for (ManageTimelines timeline : timelines) {
if (timeline.getListTimeline() != null) { if (timeline.getListTimeline() != null && timeline.getListTimeline().getTitle().equals(listTitle)) {
arrayAdapter.add(timeline.getListTimeline().getTitle()); app.fedilab.android.client.Entities.List list = timeline.getListTimeline();
hasLists = true; if (relationship == null || !relationship.isFollowing()) {
} addToList = list.getId();
} new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.FOLLOW, account.getId(), ShowAccountActivity.this);
if (!hasLists) { } else {
Toasty.info(ShowAccountActivity.this, getString(R.string.action_lists_empty), Toast.LENGTH_SHORT).show(); new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, list.getId(), null, ShowAccountActivity.this);
return true;
}
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderSingle.setTitle(getString(R.string.action_lists_add_to));
builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {
String listTitle = arrayAdapter.getItem(which);
for (ManageTimelines timeline : timelines) {
if (timeline.getListTimeline() != null && timeline.getListTimeline().getTitle().equals(listTitle)) {
app.fedilab.android.client.Entities.List list = timeline.getListTimeline();
if (relationship == null || !relationship.isFollowing()) {
addToList = list.getId();
new PostActionAsyncTask(ShowAccountActivity.this, API.StatusAction.FOLLOW, account.getId(), ShowAccountActivity.this).execute();
} else {
new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, null, list.getId(), null, ShowAccountActivity.this).execute();
}
break;
} }
break;
} }
});
builderSingle.show();
}
return true;
case R.id.action_open_browser:
if (accountUrl != null) {
if (!accountUrl.toLowerCase().startsWith("http://") && !accountUrl.toLowerCase().startsWith("https://"))
accountUrl = "http://" + accountUrl;
Helper.openBrowser(ShowAccountActivity.this, accountUrl);
}
return true;
case R.id.action_mention:
intent = new Intent(ShowAccountActivity.this, TootActivity.class);
b = new Bundle();
b.putString("mentionAccount", account.getAcct());
intent.putExtras(b);
startActivity(intent);
return true;
case R.id.action_mute:
if (relationship.isMuting()) {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(stringArrayConf[4]);
doActionAccount = API.StatusAction.UNMUTE;
} else {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(stringArrayConf[0]);
doActionAccount = API.StatusAction.MUTE;
}
break;
case R.id.action_report:
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(R.string.report_account);
//Text for report
EditText input = new EditText(ShowAccountActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
builderInner.setView(input);
doActionAccount = API.StatusAction.REPORT;
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.yes, (dialog, which) -> {
String comment = null;
if (input.getText() != null)
comment = input.getText().toString();
new PostActionAsyncTask(ShowAccountActivity.this, doActionAccount, account.getId(), null, comment, ShowAccountActivity.this).execute();
dialog.dismiss();
});
builderInner.show();
return true;
case R.id.action_add_notes:
UserNote userNote = new NotesDAO(ShowAccountActivity.this, db).getUserNote(account.getAcct());
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(R.string.note_for_account);
input = new EditText(ShowAccountActivity.this);
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
input.setSingleLine(false);
if (userNote != null) {
input.setText(userNote.getNote());
}
input.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
builderInner.setView(input);
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.validate, (dialog, which) -> {
UserNote userNote1 = new NotesDAO(ShowAccountActivity.this, db).getUserNote(account.getAcct());
if (userNote1 == null) {
userNote1 = new UserNote();
userNote1.setAcct(account.getAcct());
} }
userNote1.setNote(input.getText().toString());
new NotesDAO(ShowAccountActivity.this, db).insertInstance(userNote1);
if (input.getText().toString().trim().length() > 0) {
account_personal_note.setVisibility(View.VISIBLE);
} else {
account_personal_note.setVisibility(View.GONE);
}
dialog.dismiss();
}); });
builderInner.show(); builderSingle.show();
return true; }
case R.id.action_block: return true;
} else if (itemId == R.id.action_open_browser) {
if (accountUrl != null) {
if (!accountUrl.toLowerCase().startsWith("http://") && !accountUrl.toLowerCase().startsWith("https://"))
accountUrl = "http://" + accountUrl;
Helper.openBrowser(ShowAccountActivity.this, accountUrl);
}
return true;
} else if (itemId == R.id.action_mention) {
Intent intent;
Bundle b;
intent = new Intent(ShowAccountActivity.this, TootActivity.class);
b = new Bundle();
b.putString("mentionAccount", account.getAcct());
intent.putExtras(b);
startActivity(intent);
return true;
} else if (itemId == R.id.action_mute) {
if (relationship.isMuting()) {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style); builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
if (relationship.isBlocking()) { builderInner.setTitle(stringArrayConf[4]);
builderInner.setTitle(stringArrayConf[5]); doActionAccount = API.StatusAction.UNMUTE;
doActionAccount = API.StatusAction.UNBLOCK; } else {
} else { builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(stringArrayConf[1]); builderInner.setTitle(stringArrayConf[0]);
doActionAccount = API.StatusAction.BLOCK; doActionAccount = API.StatusAction.MUTE;
}
} else if (itemId == R.id.action_report) {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(R.string.report_account);
//Text for report
EditText input = new EditText(ShowAccountActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
builderInner.setView(input);
doActionAccount = API.StatusAction.REPORT;
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.yes, (dialog, which) -> {
String comment = null;
if (input.getText() != null)
comment = input.getText().toString();
new PostActionAsyncTask(ShowAccountActivity.this, doActionAccount, account.getId(), null, comment, ShowAccountActivity.this);
dialog.dismiss();
});
builderInner.show();
return true;
} else if (itemId == R.id.action_add_notes) {
EditText input;
LinearLayout.LayoutParams lp;
UserNote userNote = new NotesDAO(ShowAccountActivity.this, db).getUserNote(account.getAcct());
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(R.string.note_for_account);
input = new EditText(ShowAccountActivity.this);
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
input.setSingleLine(false);
if (userNote != null) {
input.setText(userNote.getNote());
}
input.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
builderInner.setView(input);
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.validate, (dialog, which) -> {
UserNote userNote1 = new NotesDAO(ShowAccountActivity.this, db).getUserNote(account.getAcct());
if (userNote1 == null) {
userNote1 = new UserNote();
userNote1.setAcct(account.getAcct());
} }
break; userNote1.setNote(input.getText().toString());
case R.id.action_block_instance: new NotesDAO(ShowAccountActivity.this, db).insertInstance(userNote1);
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style); if (input.getText().toString().trim().length() > 0) {
doActionAccount = API.StatusAction.BLOCK_DOMAIN; account_personal_note.setVisibility(View.VISIBLE);
String domain = account.getAcct().split("@")[1]; } else {
builderInner.setMessage(getString(R.string.block_domain_confirm_message, domain)); account_personal_note.setVisibility(View.GONE);
break; }
default: dialog.dismiss();
return true; });
builderInner.show();
return true;
} else if (itemId == R.id.action_block) {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
if (relationship.isBlocking()) {
builderInner.setTitle(stringArrayConf[5]);
doActionAccount = API.StatusAction.UNBLOCK;
} else {
builderInner.setTitle(stringArrayConf[1]);
doActionAccount = API.StatusAction.BLOCK;
}
} else if (itemId == R.id.action_block_instance) {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
doActionAccount = API.StatusAction.BLOCK_DOMAIN;
String domain = account.getAcct().split("@")[1];
builderInner.setMessage(getString(R.string.block_domain_confirm_message, domain));
} else {
return true;
} }
builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); builderInner.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderInner.setPositiveButton(R.string.yes, (dialog, which) -> { builderInner.setPositiveButton(R.string.yes, (dialog, which) -> {
@ -1361,7 +1351,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
} else { } else {
targetedId = account.getId(); targetedId = account.getId();
} }
new PostActionAsyncTask(ShowAccountActivity.this, doActionAccount, targetedId, ShowAccountActivity.this).execute(); new PostActionAsyncTask(ShowAccountActivity.this, doActionAccount, targetedId, ShowAccountActivity.this);
dialog.dismiss(); dialog.dismiss();
}); });
builderInner.show(); builderInner.show();
@ -1381,12 +1371,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if (scheduledExecutorService != null) { if (scheduledExecutorService != null) {
scheduledExecutorService.shutdownNow(); scheduledExecutorService.shutdownNow();
} }
if (accountAsync != null && !accountAsync.isCancelled()) {
accountAsync.cancel(true);
}
if (retrieveRelationship != null && !retrieveRelationship.isCancelled()) {
retrieveRelationship.cancel(true);
}
} }
@Override @Override
@ -1401,7 +1385,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
return; return;
} }
if (addToList != null) { if (addToList != null) {
new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, null, addToList, null, ShowAccountActivity.this).execute(); new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, addToList, null, ShowAccountActivity.this);
} else { } else {
Helper.manageMessageStatusCode(ShowAccountActivity.this, statusCode, statusAction); Helper.manageMessageStatusCode(ShowAccountActivity.this, statusCode, statusAction);
} }
@ -1415,7 +1399,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
} }
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
target = account.getAcct(); target = account.getAcct();
retrieveRelationship = new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, target, ShowAccountActivity.this).execute(); new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, target, ShowAccountActivity.this);
} }
@Override @Override

View File

@ -238,7 +238,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetrieve
if (conversationId != null) if (conversationId != null)
statusIdToFetch = conversationId; statusIdToFetch = conversationId;
new RetrieveContextAsyncTask(ShowConversationActivity.this, expanded, detailsStatus.getVisibility().equals("direct"), statusIdToFetch, ShowConversationActivity.this).execute(); new RetrieveContextAsyncTask(ShowConversationActivity.this, expanded, detailsStatus.getVisibility().equals("direct"), statusIdToFetch, ShowConversationActivity.this);
swipeRefreshLayout.setDistanceToTriggerSync(500); swipeRefreshLayout.setDistanceToTriggerSync(500);
swipeRefreshLayout.setOnRefreshListener(() -> { swipeRefreshLayout.setOnRefreshListener(() -> {
Intent intent = new Intent(ShowConversationActivity.this, ShowConversationActivity.class); Intent intent = new Intent(ShowConversationActivity.this, ShowConversationActivity.class);

View File

@ -76,14 +76,6 @@ public class SlideMediaActivity extends BaseFragmentActivity implements OnDownlo
private int mediaPosition; private int mediaPosition;
private ViewPager mPager; private ViewPager mPager;
private long downloadID; private long downloadID;
private boolean fullscreen;
private TextView media_description;
private Handler handler;
private int minTouch, maxTouch;
private float startX;
private float startY;
private int bgColor;
private final BroadcastReceiver onDownloadComplete = new BroadcastReceiver() { private final BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
@ -109,6 +101,13 @@ public class SlideMediaActivity extends BaseFragmentActivity implements OnDownlo
} }
} }
}; };
private boolean fullscreen;
private TextView media_description;
private Handler handler;
private int minTouch, maxTouch;
private float startX;
private float startY;
private int bgColor;
private MediaSliderFragment mCurrentFragment; private MediaSliderFragment mCurrentFragment;
@Override @Override

View File

@ -29,6 +29,7 @@ import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
@ -213,54 +214,53 @@ public class WebviewActivity extends BaseActivity {
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { int itemId = item.getItemId();
case android.R.id.home: if (itemId == android.R.id.home) {
finish(); finish();
return true; return true;
case R.id.action_block: } else if (itemId == R.id.action_block) {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE); SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK); final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
List<String> domains = mastalabWebViewClient.getDomains(); List<String> domains = mastalabWebViewClient.getDomains();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(WebviewActivity.this, R.layout.domains_blocked); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(WebviewActivity.this, R.layout.domains_blocked);
arrayAdapter.addAll(domains); arrayAdapter.addAll(domains);
int style; int style;
if (theme == Helper.THEME_DARK) { if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark; style = R.style.DialogDark;
} else if (theme == Helper.THEME_BLACK) { } else if (theme == Helper.THEME_BLACK) {
style = R.style.DialogBlack; style = R.style.DialogBlack;
} else { } else {
style = R.style.Dialog; style = R.style.Dialog;
} }
AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this, style); AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this, style);
builder.setTitle(R.string.list_of_blocked_domains); builder.setTitle(R.string.list_of_blocked_domains);
builder.setNegativeButton(R.string.close, (dialog, which) -> dialog.dismiss()); builder.setNegativeButton(R.string.close, (dialog, which) -> dialog.dismiss());
builder.setAdapter(arrayAdapter, (dialog, which) -> { builder.setAdapter(arrayAdapter, (dialog, which) -> {
String strName = arrayAdapter.getItem(which); String strName = arrayAdapter.getItem(which);
assert strName != null; assert strName != null;
Toasty.info(WebviewActivity.this, strName, Toast.LENGTH_LONG).show(); Toasty.info(WebviewActivity.this, strName, Toast.LENGTH_LONG).show();
}); });
builder.show(); builder.show();
return true; return true;
case R.id.action_go: } else if (itemId == R.id.action_go) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
try { try {
startActivity(browserIntent); startActivity(browserIntent);
} catch (Exception e) { } catch (Exception e) {
Toasty.error(WebviewActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); Toasty.error(WebviewActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
} }
return true; return true;
case R.id.action_comment: } else if (itemId == R.id.action_comment) {
Toasty.info(WebviewActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show(); Toasty.info(WebviewActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show();
new connnectAsync(new WeakReference<>(WebviewActivity.this), url, peertubeLinkToFetch).execute(); new connnectAsync(new WeakReference<>(WebviewActivity.this), url, peertubeLinkToFetch);
return true; return true;
default:
return super.onOptionsItemSelected(item);
} }
return super.onOptionsItemSelected(item);
} }
public void setUrl(String newUrl) { public void setUrl(String newUrl) {
@ -297,44 +297,46 @@ public class WebviewActivity extends BaseActivity {
webView.destroy(); webView.destroy();
} }
static class connnectAsync extends AsyncTask<Void, Void, List<app.fedilab.android.client.Entities.Status>> { static class connnectAsync {
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private String url; private final String url;
private String peertubeLinkToFetch; private final String peertubeLinkToFetch;
connnectAsync(WeakReference<Context> contextReference, String url, String peertubeLinkToFetch) { connnectAsync(WeakReference<Context> contextReference, String url, String peertubeLinkToFetch) {
this.contextReference = contextReference; this.contextReference = contextReference;
this.url = url; this.url = url;
this.peertubeLinkToFetch = peertubeLinkToFetch; this.peertubeLinkToFetch = peertubeLinkToFetch;
doInBackground();
} }
@Override protected void doInBackground() {
protected List<app.fedilab.android.client.Entities.Status> doInBackground(Void... voids) { new Thread(() -> {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = null; List<app.fedilab.android.client.Entities.Status> remoteStatuses = null;
if (url != null) { if (url != null) {
APIResponse search = new API(contextReference.get()).search(peertubeLinkToFetch); APIResponse search = new API(contextReference.get()).search(peertubeLinkToFetch);
if (search != null && search.getResults() != null) { if (search != null && search.getResults() != null) {
remoteStatuses = search.getResults().getStatuses(); remoteStatuses = search.getResults().getStatuses();
}
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return remoteStatuses; List<app.fedilab.android.client.Entities.Status> finalRemoteStatuses = remoteStatuses;
} Runnable myRunnable = () -> {
Intent intent = new Intent(contextReference.get(), TootActivity.class);
@Override Bundle b = new Bundle();
protected void onPostExecute(List<app.fedilab.android.client.Entities.Status> remoteStatuses) { if (finalRemoteStatuses == null || finalRemoteStatuses.size() == 0) {
Intent intent = new Intent(contextReference.get(), TootActivity.class); Toasty.error(contextReference.get(), contextReference.get().getString(R.string.toast_error), Toast.LENGTH_LONG).show();
Bundle b = new Bundle(); return;
if (remoteStatuses == null || remoteStatuses.size() == 0) { }
Toasty.error(contextReference.get(), contextReference.get().getString(R.string.toast_error), Toast.LENGTH_LONG).show(); if (finalRemoteStatuses.get(0).getReblog() != null) {
return; b.putParcelable("tootReply", finalRemoteStatuses.get(0).getReblog());
} } else {
if (remoteStatuses.get(0).getReblog() != null) { b.putParcelable("tootReply", finalRemoteStatuses.get(0));
b.putParcelable("tootReply", remoteStatuses.get(0).getReblog()); }
} else { intent.putExtras(b); //Put your id to your next Intent
b.putParcelable("tootReply", remoteStatuses.get(0)); contextReference.get().startActivity(intent);
} };
intent.putExtras(b); //Put your id to your next Intent mainHandler.post(myRunnable);
contextReference.get().startActivity(intent); }).start();
} }
} }
} }

View File

@ -187,7 +187,7 @@ public class WebviewConnectActivity extends BaseActivity {
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token);
editor.commit(); editor.commit();
//Update the account with the token; //Update the account with the token;
new UpdateAccountInfoAsyncTask(WebviewConnectActivity.this, token, clientId, clientSecret, refresh_token, instance, social).execute(); new UpdateAccountInfoAsyncTask(WebviewConnectActivity.this, token, clientId, clientSecret, refresh_token, instance, social);
} catch (JSONException ignored) { } catch (JSONException ignored) {
} }
} catch (Exception ignored) { } catch (Exception ignored) {

View File

@ -105,7 +105,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
cal.add(Calendar.MINUTE, -5); cal.add(Calendar.MINUTE, -5);
Date dateAllowed = cal.getTime(); Date dateAllowed = cal.getTime();
if (lastDateListNameRefresh == null || Helper.stringToDate(WhoToFollowActivity.this, lastDateListNameRefresh).before(dateAllowed)) { if (lastDateListNameRefresh == null || Helper.stringToDate(WhoToFollowActivity.this, lastDateListNameRefresh).before(dateAllowed)) {
new WhoToFollowAsyncTask(WhoToFollowActivity.this, item, WhoToFollowActivity.this).execute(); new WhoToFollowAsyncTask(WhoToFollowActivity.this, item, WhoToFollowActivity.this);
mainLoader.setVisibility(View.VISIBLE); mainLoader.setVisibility(View.VISIBLE);
} else { } else {
String lastList = sharedpreferences.getString(Helper.LAST_LIST_NAME + item, null); String lastList = sharedpreferences.getString(Helper.LAST_LIST_NAME + item, null);
@ -171,7 +171,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
if (val.length > 1) { if (val.length > 1) {
account.setAcct(val[0]); account.setAcct(val[0]);
account.setInstance(val[1]); account.setInstance(val[1]);
new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this).execute(); new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this);
} else { } else {
Toasty.error(WhoToFollowActivity.this, getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show(); Toasty.error(WhoToFollowActivity.this, getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show();
follow_accounts.setEnabled(true); follow_accounts.setEnabled(true);
@ -218,7 +218,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
followedId.add(userId); followedId.add(userId);
if (followedId != null && followedId.size() >= toFollowdId.size()) { if (followedId != null && followedId.size() >= toFollowdId.size()) {
progess_action.setText(getString(R.string.create_list_trunk, item)); progess_action.setText(getString(R.string.create_list_trunk, item));
new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.CREATE_LIST, null, null, null, item, WhoToFollowActivity.this).execute(); new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.CREATE_LIST, null, null, item, WhoToFollowActivity.this);
} else { } else {
Account account = new Account(); Account account = new Account();
assert followedId != null; assert followedId != null;
@ -227,7 +227,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
if (val.length > 1) { if (val.length > 1) {
account.setAcct(val[0]); account.setAcct(val[0]);
account.setInstance(val[1]); account.setInstance(val[1]);
new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this).execute(); new PostActionAsyncTask(WhoToFollowActivity.this, null, account, API.StatusAction.FOLLOW, WhoToFollowActivity.this);
} }
} }
@ -241,7 +241,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
progess_action.setText(R.string.add_account_list_trunk); progess_action.setText(R.string.add_account_list_trunk);
listId = lists.get(0).getId(); listId = lists.get(0).getId();
listTitle = lists.get(0).getTitle(); listTitle = lists.get(0).getTitle();
new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{followedId.get(0)}, null, lists.get(0).getId(), null, WhoToFollowActivity.this).execute(); new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{followedId.get(0)}, lists.get(0).getId(), null, WhoToFollowActivity.this);
accountListId = new ArrayList<>(); accountListId = new ArrayList<>();
} else if (accountListId != null) { } else if (accountListId != null) {
@ -262,7 +262,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
accountListId.add(followedId.get(accountListId.size())); accountListId.add(followedId.get(accountListId.size()));
progess_action.setText(R.string.adding_account_list_trunk); progess_action.setText(R.string.adding_account_list_trunk);
String userIdToAdd = followedId.get(accountListId.size()); String userIdToAdd = followedId.get(accountListId.size());
new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{userIdToAdd}, null, listId, null, WhoToFollowActivity.this).execute(); new ManageListsAsyncTask(WhoToFollowActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{userIdToAdd}, listId, null, WhoToFollowActivity.this);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -31,15 +32,14 @@ import app.fedilab.android.interfaces.OnPostStatusActionInterface;
* Create a Mastodon account * Create a Mastodon account
*/ */
public class CreateMastodonAccountAsyncTask extends AsyncTask<Void, Void, Void> { public class CreateMastodonAccountAsyncTask {
private OnPostStatusActionInterface listener; private final OnPostStatusActionInterface listener;
private final AccountCreation accountCreation;
private final WeakReference<Context> contextReference;
private final String instance;
private final RetrieveInstanceRegAsyncTask.instanceType type;
private APIResponse apiResponse; private APIResponse apiResponse;
private app.fedilab.android.client.Entities.Status status;
private AccountCreation accountCreation;
private WeakReference<Context> contextReference;
private String instance;
private RetrieveInstanceRegAsyncTask.instanceType type;
public CreateMastodonAccountAsyncTask(Context context, RetrieveInstanceRegAsyncTask.instanceType type, AccountCreation accountCreation, String instance, OnPostStatusActionInterface onPostStatusActionInterface) { public CreateMastodonAccountAsyncTask(Context context, RetrieveInstanceRegAsyncTask.instanceType type, AccountCreation accountCreation, String instance, OnPostStatusActionInterface onPostStatusActionInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -47,22 +47,21 @@ public class CreateMastodonAccountAsyncTask extends AsyncTask<Void, Void, Void>
this.accountCreation = accountCreation; this.accountCreation = accountCreation;
this.instance = instance; this.instance = instance;
this.type = type; this.type = type;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (type == RetrieveInstanceRegAsyncTask.instanceType.MASTODON) { if (type == RetrieveInstanceRegAsyncTask.instanceType.MASTODON) {
apiResponse = new API(contextReference.get(), instance, null).createAccount(accountCreation); apiResponse = new API(contextReference.get(), instance, null).createAccount(accountCreation);
} else { } else {
apiResponse = new PeertubeAPI(contextReference.get(), instance, null).createAccount(accountCreation); apiResponse = new PeertubeAPI(contextReference.get(), instance, null).createAccount(accountCreation);
} }
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onPostStatusAction(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onPostStatusAction(apiResponse);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,28 +30,27 @@ import app.fedilab.android.interfaces.OnCustomSharingInterface;
* Custom share status metadata to remote content aggregator * Custom share status metadata to remote content aggregator
*/ */
public class CustomSharingAsyncTask extends AsyncTask<Void, Void, Void> { public class CustomSharingAsyncTask {
private String encodedCustomSharingURL; private final String encodedCustomSharingURL;
private final OnCustomSharingInterface listener;
private final WeakReference<Context> contextReference;
private CustomSharingResponse customSharingResponse; private CustomSharingResponse customSharingResponse;
private OnCustomSharingInterface listener;
private WeakReference<Context> contextReference;
public CustomSharingAsyncTask(Context context, String encodedCustomSharingURL, OnCustomSharingInterface onCustomSharingInterface) { public CustomSharingAsyncTask(Context context, String encodedCustomSharingURL, OnCustomSharingInterface onCustomSharingInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.encodedCustomSharingURL = encodedCustomSharingURL; this.encodedCustomSharingURL = encodedCustomSharingURL;
this.listener = onCustomSharingInterface; this.listener = onCustomSharingInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
customSharingResponse = new CustomSharing(this.contextReference.get()).customShare(encodedCustomSharingURL); customSharingResponse = new CustomSharing(this.contextReference.get()).customShare(encodedCustomSharingURL);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
} Runnable myRunnable = () -> listener.onCustomSharing(customSharingResponse);
mainHandler.post(myRunnable);
@Override }).start();
protected void onPostExecute(Void result) {
listener.onCustomSharing(customSharingResponse);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -28,30 +29,32 @@ import app.fedilab.android.interfaces.OnRetrieveDomainsInterface;
* Delete a blocked instance * Delete a blocked instance
*/ */
public class DeleteDomainsAsyncTask extends AsyncTask<Void, Void, Void> { public class DeleteDomainsAsyncTask {
private OnRetrieveDomainsInterface listener; private final OnRetrieveDomainsInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final String domainName;
private int response; private int response;
private String domainName;
public DeleteDomainsAsyncTask(Context context, String domainName, OnRetrieveDomainsInterface onRetrieveDomainsInterface) { public DeleteDomainsAsyncTask(Context context, String domainName, OnRetrieveDomainsInterface onRetrieveDomainsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveDomainsInterface; this.listener = onRetrieveDomainsInterface;
this.domainName = domainName; this.domainName = domainName;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get()); new Thread(() -> {
response = api.deleteBlockedDomain(domainName); API api = new API(this.contextReference.get());
return null; response = api.deleteBlockedDomain(domainName);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () ->
listener.onRetrieveDomainsDeleted(response);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveDomainsDeleted(response);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -28,40 +29,39 @@ import app.fedilab.android.interfaces.OnRefreshCachedStatusInterface;
* Manage refresh for statuses * Manage refresh for statuses
*/ */
public class ManageCachedStatusAsyncTask extends AsyncTask<Void, Void, Void> { public class ManageCachedStatusAsyncTask {
private OnRefreshCachedStatusInterface listener; private final OnRefreshCachedStatusInterface listener;
private String statusId; private final String statusId;
private final WeakReference<Context> contextReference;
private app.fedilab.android.client.Entities.Status refreshedStatus; private app.fedilab.android.client.Entities.Status refreshedStatus;
private WeakReference<Context> contextReference;
public ManageCachedStatusAsyncTask(Context context, String statusId, OnRefreshCachedStatusInterface onRefreshCachedStatusInterface) { public ManageCachedStatusAsyncTask(Context context, String statusId, OnRefreshCachedStatusInterface onRefreshCachedStatusInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRefreshCachedStatusInterface; this.listener = onRefreshCachedStatusInterface;
this.statusId = statusId; this.statusId = statusId;
doInBackground();
} }
@Override
protected Void doInBackground(Void... params) { protected void doInBackground() {
APIResponse apiResponse = new API(contextReference.get()).getStatusbyIdAndCache(statusId); new Thread(() -> {
if (apiResponse.getStatuses().size() > 0) { APIResponse apiResponse = new API(contextReference.get()).getStatusbyIdAndCache(statusId);
refreshedStatus = apiResponse.getStatuses().get(0); if (apiResponse.getStatuses().size() > 0) {
if (refreshedStatus != null) { refreshedStatus = apiResponse.getStatuses().get(0);
refreshedStatus.setcached(true); if (refreshedStatus != null) {
refreshedStatus.setcached(true);
}
} else {
refreshedStatus = new app.fedilab.android.client.Entities.Status();
refreshedStatus.setId(statusId);
} }
} else { Handler mainHandler = new Handler(Looper.getMainLooper());
refreshedStatus = new app.fedilab.android.client.Entities.Status(); Runnable myRunnable = () -> listener.onRefresh(refreshedStatus);
refreshedStatus.setId(statusId); mainHandler.post(myRunnable);
}).start();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRefresh(refreshedStatus);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -30,41 +31,41 @@ import app.fedilab.android.interfaces.OnFilterActionInterface;
* Async works to manage Filters * Async works to manage Filters
*/ */
public class ManageFiltersAsyncTask extends AsyncTask<Void, Void, Void> { public class ManageFiltersAsyncTask {
private OnFilterActionInterface listener; private final OnFilterActionInterface listener;
private final action apiAction;
private final WeakReference<Context> contextReference;
private final Filters filter;
private APIResponse apiResponse; private APIResponse apiResponse;
private int statusCode; private int statusCode;
private action apiAction;
private WeakReference<Context> contextReference;
private Filters filter;
public ManageFiltersAsyncTask(Context context, action apiAction, Filters filter, OnFilterActionInterface onFilterActionInterface) { public ManageFiltersAsyncTask(Context context, action apiAction, Filters filter, OnFilterActionInterface onFilterActionInterface) {
contextReference = new WeakReference<>(context); contextReference = new WeakReference<>(context);
this.listener = onFilterActionInterface; this.listener = onFilterActionInterface;
this.filter = filter; this.filter = filter;
this.apiAction = apiAction; this.apiAction = apiAction;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
if (apiAction == action.GET_ALL_FILTER) {
apiResponse = new API(contextReference.get()).getFilters();
} else if (apiAction == action.GET_FILTER) {
apiResponse = new API(contextReference.get()).getFilters(filter.getId());
} else if (apiAction == action.CREATE_FILTER) {
apiResponse = new API(contextReference.get()).addFilters(filter);
} else if (apiAction == action.UPDATE_FILTER) {
apiResponse = new API(contextReference.get()).updateFilters(filter);
} else if (apiAction == action.DELETE_FILTER) {
statusCode = new API(contextReference.get()).deleteFilters(filter);
}
return null;
}
@Override new Thread(() -> {
protected void onPostExecute(Void result) { if (apiAction == action.GET_ALL_FILTER) {
listener.onActionDone(this.apiAction, apiResponse, statusCode); apiResponse = new API(contextReference.get()).getFilters();
} else if (apiAction == action.GET_FILTER) {
apiResponse = new API(contextReference.get()).getFilters(filter.getId());
} else if (apiAction == action.CREATE_FILTER) {
apiResponse = new API(contextReference.get()).addFilters(filter);
} else if (apiAction == action.UPDATE_FILTER) {
apiResponse = new API(contextReference.get()).updateFilters(filter);
} else if (apiAction == action.DELETE_FILTER) {
statusCode = new API(contextReference.get()).deleteFilters(filter);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onActionDone(this.apiAction, apiResponse, statusCode);
mainHandler.post(myRunnable);
}).start();
} }
public enum action { public enum action {

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,29 +30,29 @@ import app.fedilab.android.interfaces.OnListActionInterface;
* Async works to manage Lists * Async works to manage Lists
*/ */
public class ManageListsAsyncTask extends AsyncTask<Void, Void, Void> { public class ManageListsAsyncTask {
private OnListActionInterface listener; private final OnListActionInterface listener;
private final action apiAction;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private int statusCode; private int statusCode;
private String targetedId;
private String listId; private String listId;
private String title; private String title;
private String[] accountsId; private String[] accountsId;
private action apiAction;
private WeakReference<Context> contextReference;
private String max_id, since_id; private String max_id, since_id;
private int limit; private int limit;
private String search; private String search;
public ManageListsAsyncTask(Context context, action apiAction, String[] accountsId, String targetedId, String listId, String title, OnListActionInterface onListActionInterface) {
public ManageListsAsyncTask(Context context, action apiAction, String[] accountsId, String listId, String title, OnListActionInterface onListActionInterface) {
contextReference = new WeakReference<>(context); contextReference = new WeakReference<>(context);
this.listener = onListActionInterface; this.listener = onListActionInterface;
this.listId = listId; this.listId = listId;
this.title = title; this.title = title;
this.accountsId = accountsId; this.accountsId = accountsId;
this.apiAction = apiAction; this.apiAction = apiAction;
this.targetedId = targetedId; doInBackground();
} }
public ManageListsAsyncTask(Context context, String listId, String max_id, String since_id, OnListActionInterface onListActionInterface) { public ManageListsAsyncTask(Context context, String listId, String max_id, String since_id, OnListActionInterface onListActionInterface) {
@ -62,6 +63,7 @@ public class ManageListsAsyncTask extends AsyncTask<Void, Void, Void> {
this.since_id = since_id; this.since_id = since_id;
this.limit = 40; this.limit = 40;
this.apiAction = action.GET_LIST_TIMELINE; this.apiAction = action.GET_LIST_TIMELINE;
doInBackground();
} }
public ManageListsAsyncTask(Context context, String search, OnListActionInterface onListActionInterface) { public ManageListsAsyncTask(Context context, String search, OnListActionInterface onListActionInterface) {
@ -69,36 +71,38 @@ public class ManageListsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onListActionInterface; this.listener = onListActionInterface;
this.search = search; this.search = search;
this.apiAction = action.SEARCH_USER; this.apiAction = action.SEARCH_USER;
doInBackground();
} }
@Override
protected Void doInBackground(Void... params) { protected void doInBackground() {
if (apiAction == action.GET_LIST) {
apiResponse = new API(contextReference.get()).getLists(); new Thread(() -> {
} else if (apiAction == action.GET_LIST_TIMELINE) { if (apiAction == action.GET_LIST) {
apiResponse = new API(contextReference.get()).getListTimeline(this.listId, this.max_id, this.since_id, this.limit); apiResponse = new API(contextReference.get()).getLists();
} else if (apiAction == action.GET_LIST_ACCOUNT) { } else if (apiAction == action.GET_LIST_TIMELINE) {
apiResponse = new API(contextReference.get()).getAccountsInList(this.listId, 0); apiResponse = new API(contextReference.get()).getListTimeline(this.listId, this.max_id, this.since_id, this.limit);
} else if (apiAction == action.CREATE_LIST) { } else if (apiAction == action.GET_LIST_ACCOUNT) {
apiResponse = new API(contextReference.get()).createList(this.title); apiResponse = new API(contextReference.get()).getAccountsInList(this.listId, 0);
} else if (apiAction == action.DELETE_LIST) { } else if (apiAction == action.CREATE_LIST) {
statusCode = new API(contextReference.get()).deleteList(this.listId); apiResponse = new API(contextReference.get()).createList(this.title);
} else if (apiAction == action.UPDATE_LIST) { } else if (apiAction == action.DELETE_LIST) {
apiResponse = new API(contextReference.get()).updateList(this.listId, this.title); statusCode = new API(contextReference.get()).deleteList(this.listId);
} else if (apiAction == action.ADD_USERS) { } else if (apiAction == action.UPDATE_LIST) {
apiResponse = new API(contextReference.get()).addAccountToList(this.listId, this.accountsId); apiResponse = new API(contextReference.get()).updateList(this.listId, this.title);
} else if (apiAction == action.DELETE_USERS) { } else if (apiAction == action.ADD_USERS) {
statusCode = new API(contextReference.get()).deleteAccountFromList(this.listId, this.accountsId); apiResponse = new API(contextReference.get()).addAccountToList(this.listId, this.accountsId);
} else if (apiAction == action.SEARCH_USER) { } else if (apiAction == action.DELETE_USERS) {
apiResponse = new API(contextReference.get()).searchAccounts(this.search, 20, true); statusCode = new API(contextReference.get()).deleteAccountFromList(this.listId, this.accountsId);
} } else if (apiAction == action.SEARCH_USER) {
return null; apiResponse = new API(contextReference.get()).searchAccounts(this.search, 20, true);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onActionDone(this.apiAction, apiResponse, statusCode);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onActionDone(this.apiAction, apiResponse, statusCode);
}
public enum action { public enum action {
GET_LIST, GET_LIST,

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -36,16 +37,16 @@ import app.fedilab.android.sqlite.Sqlite;
* Async works to manage Playlists * Async works to manage Playlists
*/ */
public class ManagePlaylistsAsyncTask extends AsyncTask<Void, Void, Void> { public class ManagePlaylistsAsyncTask {
private OnPlaylistActionInterface listener; private final OnPlaylistActionInterface listener;
private final action apiAction;
private final WeakReference<Context> contextReference;
private final String max_id;
private final Playlist playlist;
private final String videoId;
private APIResponse apiResponse; private APIResponse apiResponse;
private int statusCode; private int statusCode;
private action apiAction;
private WeakReference<Context> contextReference;
private String max_id;
private Playlist playlist;
private String videoId;
public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String videoId, String max_id, OnPlaylistActionInterface onPlaylistActionInterface) { public ManagePlaylistsAsyncTask(Context context, action apiAction, Playlist playlist, String videoId, String max_id, OnPlaylistActionInterface onPlaylistActionInterface) {
contextReference = new WeakReference<>(context); contextReference = new WeakReference<>(context);
@ -54,35 +55,37 @@ public class ManagePlaylistsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id; this.max_id = max_id;
this.playlist = playlist; this.playlist = playlist;
this.videoId = videoId; this.videoId = videoId;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); new Thread(() -> {
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(contextReference.get())); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(contextReference.get()));
Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance); SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (apiAction == action.GET_PLAYLIST) { Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance);
apiResponse = new PeertubeAPI(contextReference.get()).getPlayists(account.getUsername()); if (apiAction == action.GET_PLAYLIST) {
} else if (apiAction == action.GET_LIST_VIDEOS) { apiResponse = new PeertubeAPI(contextReference.get()).getPlayists(account.getUsername());
apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(), max_id, null); } else if (apiAction == action.GET_LIST_VIDEOS) {
} else if (apiAction == action.DELETE_PLAYLIST) { apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(), max_id, null);
statusCode = new PeertubeAPI(contextReference.get()).deletePlaylist(playlist.getId()); } else if (apiAction == action.DELETE_PLAYLIST) {
} else if (apiAction == action.ADD_VIDEOS) { statusCode = new PeertubeAPI(contextReference.get()).deletePlaylist(playlist.getId());
statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(), videoId); } else if (apiAction == action.ADD_VIDEOS) {
} else if (apiAction == action.DELETE_VIDEOS) { statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(), videoId);
statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(), videoId); } else if (apiAction == action.DELETE_VIDEOS) {
} else if (apiAction == action.GET_PLAYLIST_FOR_VIDEO) { statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(), videoId);
apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistForVideo(videoId); } else if (apiAction == action.GET_PLAYLIST_FOR_VIDEO) {
} apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistForVideo(videoId);
return null; }
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onActionDone(this.apiAction, apiResponse, statusCode);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onActionDone(this.apiAction, apiResponse, statusCode);
}
public enum action { public enum action {
GET_PLAYLIST, GET_PLAYLIST,

View File

@ -15,12 +15,12 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import app.fedilab.android.client.API; import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Poll; import app.fedilab.android.client.Entities.Poll;
import app.fedilab.android.interfaces.OnPollInterface; import app.fedilab.android.interfaces.OnPollInterface;
@ -29,15 +29,14 @@ import app.fedilab.android.interfaces.OnPollInterface;
* Manage Poll * Manage Poll
*/ */
public class ManagePollAsyncTask extends AsyncTask<Void, Void, Void> { public class ManagePollAsyncTask {
private OnPollInterface listener; private final OnPollInterface listener;
private APIResponse apiResponse; private final app.fedilab.android.client.Entities.Status status;
private app.fedilab.android.client.Entities.Status status; private final int[] choices;
private int[] choices; private final WeakReference<Context> contextReference;
private WeakReference<Context> contextReference; private final type_s type;
private Poll poll; private Poll poll;
private type_s type;
public ManagePollAsyncTask(Context context, type_s type, app.fedilab.android.client.Entities.Status status, int[] choices, OnPollInterface onPollInterface) { public ManagePollAsyncTask(Context context, type_s type, app.fedilab.android.client.Entities.Status status, int[] choices, OnPollInterface onPollInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -45,29 +44,29 @@ public class ManagePollAsyncTask extends AsyncTask<Void, Void, Void> {
this.status = status; this.status = status;
this.choices = choices; this.choices = choices;
this.type = type; this.type = type;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
Poll _poll;
if (status.getReblog() != null)
_poll = status.getReblog().getPoll();
else
_poll = status.getPoll();
if (_poll.getId() == null) new Thread(() -> {
return null; Poll _poll;
if (type == type_s.SUBMIT) { if (status.getReblog() != null)
poll = new API(contextReference.get()).submiteVote(_poll.getId(), choices); _poll = status.getReblog().getPoll();
} else if (type == type_s.REFRESH) { else
poll = new API(contextReference.get()).getPoll(status); _poll = status.getPoll();
}
return null;
}
@Override if (_poll.getId() != null) {
protected void onPostExecute(Void result) { if (type == type_s.SUBMIT) {
listener.onPoll(status, poll); poll = new API(contextReference.get()).submiteVote(_poll.getId(), choices);
} else if (type == type_s.REFRESH) {
poll = new API(contextReference.get()).getPoll(status);
}
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onPoll(status, poll);
mainHandler.post(myRunnable);
}).start();
} }
public enum type_s { public enum type_s {

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock; import android.os.SystemClock;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -41,17 +42,17 @@ import app.fedilab.android.sqlite.StatusCacheDAO;
* Makes actions for post calls * Makes actions for post calls
*/ */
public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> { public class PostActionAsyncTask {
private OnPostActionInterface listener; private final OnPostActionInterface listener;
private final API.StatusAction apiAction;
private final WeakReference<Context> contextReference;
private int statusCode; private int statusCode;
private API.StatusAction apiAction;
private String targetedId, targetedComment; private String targetedId, targetedComment;
private String comment; private String comment;
private app.fedilab.android.client.Entities.Status status; private app.fedilab.android.client.Entities.Status status;
private Account account, remoteAccount; private Account account, remoteAccount;
private app.fedilab.android.client.Entities.Status remoteStatus; private app.fedilab.android.client.Entities.Status remoteStatus;
private WeakReference<Context> contextReference;
private boolean muteNotifications; private boolean muteNotifications;
private Error error; private Error error;
private StoredStatus storedStatus; private StoredStatus storedStatus;
@ -61,6 +62,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onPostActionInterface; this.listener = onPostActionInterface;
this.apiAction = apiAction; this.apiAction = apiAction;
this.storedStatus = storedStatus; this.storedStatus = storedStatus;
doInBackground();
} }
public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface) { public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface) {
@ -68,6 +70,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onPostActionInterface; this.listener = onPostActionInterface;
this.apiAction = apiAction; this.apiAction = apiAction;
this.targetedId = targetedId; this.targetedId = targetedId;
doInBackground();
} }
public PostActionAsyncTask(Context context, Account account, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface) { public PostActionAsyncTask(Context context, Account account, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface) {
@ -76,6 +79,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.apiAction = apiAction; this.apiAction = apiAction;
this.targetedId = targetedId; this.targetedId = targetedId;
this.account = account; this.account = account;
doInBackground();
} }
public PostActionAsyncTask(Context context, Account account, app.fedilab.android.client.Entities.Status remoteStatus, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface) { public PostActionAsyncTask(Context context, Account account, app.fedilab.android.client.Entities.Status remoteStatus, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface) {
@ -84,6 +88,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.apiAction = apiAction; this.apiAction = apiAction;
this.remoteStatus = remoteStatus; this.remoteStatus = remoteStatus;
this.account = account; this.account = account;
doInBackground();
} }
public PostActionAsyncTask(Context context, Account account, Account remoteAccount, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface) { public PostActionAsyncTask(Context context, Account account, Account remoteAccount, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface) {
@ -92,6 +97,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.apiAction = apiAction; this.apiAction = apiAction;
this.remoteAccount = remoteAccount; this.remoteAccount = remoteAccount;
this.account = account; this.account = account;
doInBackground();
} }
public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, app.fedilab.android.client.Entities.Status status, String comment, OnPostActionInterface onPostActionInterface) { public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, app.fedilab.android.client.Entities.Status status, String comment, OnPostActionInterface onPostActionInterface) {
@ -101,6 +107,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.targetedId = targetedId; this.targetedId = targetedId;
this.comment = comment; this.comment = comment;
this.status = status; this.status = status;
doInBackground();
} }
public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, boolean muteNotifications, OnPostActionInterface onPostActionInterface) { public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, boolean muteNotifications, OnPostActionInterface onPostActionInterface) {
@ -109,6 +116,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.apiAction = apiAction; this.apiAction = apiAction;
this.targetedId = targetedId; this.targetedId = targetedId;
this.muteNotifications = muteNotifications; this.muteNotifications = muteNotifications;
doInBackground();
} }
@ -119,6 +127,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.targetedId = targetedId; this.targetedId = targetedId;
this.comment = comment; this.comment = comment;
this.targetedComment = targetedComment; this.targetedComment = targetedComment;
doInBackground();
} }
public PostActionAsyncTask(Context context, API.StatusAction unbookmark) { public PostActionAsyncTask(Context context, API.StatusAction unbookmark) {
@ -126,141 +135,139 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = null; this.listener = null;
this.apiAction = unbookmark; this.apiAction = unbookmark;
this.targetedId = null; this.targetedId = null;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
//Remote action
API api;
if (account != null)
api = new API(contextReference.get(), account.getInstance(), account.getToken());
else
api = new API(contextReference.get());
if (remoteStatus != null) {
String uri;
if (remoteStatus.getReblog() != null) { new Thread(() -> {
if (remoteStatus.getReblog().getUri().startsWith("http")) if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
uri = remoteStatus.getReblog().getUri(); //Remote action
else
uri = remoteStatus.getReblog().getUrl();
} else {
if (remoteStatus.getUri().startsWith("http"))
uri = remoteStatus.getUri();
else
uri = remoteStatus.getUrl();
}
APIResponse search = api.search(uri);
if (search != null && search.getResults() != null) {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = search.getResults().getStatuses();
if (remoteStatuses != null && remoteStatuses.size() > 0) {
app.fedilab.android.client.Entities.Status statusTmp = remoteStatuses.get(0);
this.targetedId = statusTmp.getId();
statusCode = api.postAction(apiAction, targetedId);
}
}
} else if (remoteAccount != null) {
String searchString = remoteAccount.getAcct().contains("@") ? "@" + remoteAccount.getAcct() : "@" + remoteAccount.getAcct() + "@" + Helper.getLiveInstance(contextReference.get());
APIResponse search = api.search(searchString);
if (search != null && search.getResults() != null) {
List<Account> accounts = search.getResults().getAccounts();
if (accounts != null && accounts.size() > 0) {
Account accountTmp = accounts.get(0);
this.targetedId = accountTmp.getId();
statusCode = api.postAction(apiAction, targetedId);
}
}
} else {
if (apiAction == API.StatusAction.REPORT) {
if (status != null) {
statusCode = api.reportAction(status, comment);
} else {
statusCode = api.reportAction(targetedId, comment);
}
} else if (apiAction == API.StatusAction.ADD_REACTION || apiAction == API.StatusAction.REMOVE_REACTION || apiAction == API.StatusAction.ADD_PLEROMA_REACTION || apiAction == API.StatusAction.REMOVE_PLEROMA_REACTION) {
statusCode = api.postAction(apiAction, targetedId, comment);
} else if (apiAction == API.StatusAction.CREATESTATUS)
statusCode = api.statusAction(status);
else if (apiAction == API.StatusAction.UPDATESERVERSCHEDULE) {
api.scheduledAction("PUT", storedStatus.getStatus(), null, storedStatus.getScheduledServerdId());
} else if (apiAction == API.StatusAction.DELETESCHEDULED) {
api.scheduledAction("DELETE", null, null, storedStatus.getScheduledServerdId());
} else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS) {
statusCode = api.muteNotifications(targetedId, muteNotifications);
} else if (apiAction == API.StatusAction.UNBOOKMARK && targetedId == null) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<app.fedilab.android.client.Entities.Status> bookmarks = new StatusCacheDAO(contextReference.get(), db).getAllStatus(StatusCacheDAO.BOOKMARK_CACHE);
for (app.fedilab.android.client.Entities.Status status : bookmarks) {
statusCode = api.postAction(apiAction, status.getId());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
SystemClock.sleep(200);
}
}
new StatusCacheDAO(contextReference.get(), db).removeAllStatus(StatusCacheDAO.BOOKMARK_CACHE);
} else {
statusCode = api.postAction(apiAction, targetedId);
}
}
error = api.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
//Remote action
PeertubeAPI peertubeAPI;
if (account != null)
peertubeAPI = new PeertubeAPI(contextReference.get(), account.getInstance(), account.getToken());
else
peertubeAPI = new PeertubeAPI(contextReference.get());
if (apiAction == API.StatusAction.FOLLOW || apiAction == API.StatusAction.UNFOLLOW)
statusCode = peertubeAPI.postAction(apiAction, targetedId);
else if (apiAction == API.StatusAction.RATEVIDEO)
statusCode = peertubeAPI.postRating(targetedId, comment);
else if (apiAction == API.StatusAction.PEERTUBECOMMENT)
statusCode = peertubeAPI.postComment(targetedId, comment);
else if (apiAction == API.StatusAction.PEERTUBEREPLY)
statusCode = peertubeAPI.postReply(targetedId, comment, targetedComment);
else if (apiAction == API.StatusAction.PEERTUBEDELETECOMMENT) {
statusCode = peertubeAPI.deleteComment(targetedId, comment);
targetedId = comment;
} else if (apiAction == API.StatusAction.PEERTUBEDELETEVIDEO) {
statusCode = peertubeAPI.deleteVideo(targetedId);
}
error = peertubeAPI.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi;
if (account != null)
gnuapi = new GNUAPI(contextReference.get(), account.getInstance(), account.getToken());
else
gnuapi = new GNUAPI(contextReference.get());
if (apiAction == API.StatusAction.REPORT)
statusCode = gnuapi.reportAction(status);
else if (apiAction == API.StatusAction.CREATESTATUS)
statusCode = gnuapi.statusAction(status);
else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS)
statusCode = gnuapi.muteNotifications(targetedId, muteNotifications);
else if (apiAction == API.StatusAction.AUTHORIZE || apiAction == API.StatusAction.REJECT) {
//This part uses the Mastodon API
API api; API api;
if (account != null) if (account != null)
api = new API(contextReference.get(), account.getInstance(), account.getToken()); api = new API(contextReference.get(), account.getInstance(), account.getToken());
else else
api = new API(contextReference.get()); api = new API(contextReference.get());
statusCode = api.postAction(apiAction, targetedId); if (remoteStatus != null) {
} else String uri;
statusCode = gnuapi.postAction(apiAction, targetedId);
error = gnuapi.getError();
}
return null;
}
@Override if (remoteStatus.getReblog() != null) {
protected void onPostExecute(Void result) { if (remoteStatus.getReblog().getUri().startsWith("http"))
if (listener != null) { uri = remoteStatus.getReblog().getUri();
listener.onPostAction(statusCode, apiAction, targetedId, error); else
} uri = remoteStatus.getReblog().getUrl();
} else {
if (remoteStatus.getUri().startsWith("http"))
uri = remoteStatus.getUri();
else
uri = remoteStatus.getUrl();
}
APIResponse search = api.search(uri);
if (search != null && search.getResults() != null) {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = search.getResults().getStatuses();
if (remoteStatuses != null && remoteStatuses.size() > 0) {
app.fedilab.android.client.Entities.Status statusTmp = remoteStatuses.get(0);
this.targetedId = statusTmp.getId();
statusCode = api.postAction(apiAction, targetedId);
}
}
} else if (remoteAccount != null) {
String searchString = remoteAccount.getAcct().contains("@") ? "@" + remoteAccount.getAcct() : "@" + remoteAccount.getAcct() + "@" + Helper.getLiveInstance(contextReference.get());
APIResponse search = api.search(searchString);
if (search != null && search.getResults() != null) {
List<Account> accounts = search.getResults().getAccounts();
if (accounts != null && accounts.size() > 0) {
Account accountTmp = accounts.get(0);
this.targetedId = accountTmp.getId();
statusCode = api.postAction(apiAction, targetedId);
}
}
} else {
if (apiAction == API.StatusAction.REPORT) {
if (status != null) {
statusCode = api.reportAction(status, comment);
} else {
statusCode = api.reportAction(targetedId, comment);
}
} else if (apiAction == API.StatusAction.ADD_REACTION || apiAction == API.StatusAction.REMOVE_REACTION || apiAction == API.StatusAction.ADD_PLEROMA_REACTION || apiAction == API.StatusAction.REMOVE_PLEROMA_REACTION) {
statusCode = api.postAction(apiAction, targetedId, comment);
} else if (apiAction == API.StatusAction.CREATESTATUS)
statusCode = api.statusAction(status);
else if (apiAction == API.StatusAction.UPDATESERVERSCHEDULE) {
api.scheduledAction("PUT", storedStatus.getStatus(), null, storedStatus.getScheduledServerdId());
} else if (apiAction == API.StatusAction.DELETESCHEDULED) {
api.scheduledAction("DELETE", null, null, storedStatus.getScheduledServerdId());
} else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS) {
statusCode = api.muteNotifications(targetedId, muteNotifications);
} else if (apiAction == API.StatusAction.UNBOOKMARK && targetedId == null) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<app.fedilab.android.client.Entities.Status> bookmarks = new StatusCacheDAO(contextReference.get(), db).getAllStatus(StatusCacheDAO.BOOKMARK_CACHE);
for (app.fedilab.android.client.Entities.Status status : bookmarks) {
statusCode = api.postAction(apiAction, status.getId());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
SystemClock.sleep(200);
}
}
new StatusCacheDAO(contextReference.get(), db).removeAllStatus(StatusCacheDAO.BOOKMARK_CACHE);
} else {
statusCode = api.postAction(apiAction, targetedId);
}
}
error = api.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
//Remote action
PeertubeAPI peertubeAPI;
if (account != null)
peertubeAPI = new PeertubeAPI(contextReference.get(), account.getInstance(), account.getToken());
else
peertubeAPI = new PeertubeAPI(contextReference.get());
if (apiAction == API.StatusAction.FOLLOW || apiAction == API.StatusAction.UNFOLLOW)
statusCode = peertubeAPI.postAction(apiAction, targetedId);
else if (apiAction == API.StatusAction.RATEVIDEO)
statusCode = peertubeAPI.postRating(targetedId, comment);
else if (apiAction == API.StatusAction.PEERTUBECOMMENT)
statusCode = peertubeAPI.postComment(targetedId, comment);
else if (apiAction == API.StatusAction.PEERTUBEREPLY)
statusCode = peertubeAPI.postReply(targetedId, comment, targetedComment);
else if (apiAction == API.StatusAction.PEERTUBEDELETECOMMENT) {
statusCode = peertubeAPI.deleteComment(targetedId, comment);
targetedId = comment;
} else if (apiAction == API.StatusAction.PEERTUBEDELETEVIDEO) {
statusCode = peertubeAPI.deleteVideo(targetedId);
}
error = peertubeAPI.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi;
if (account != null)
gnuapi = new GNUAPI(contextReference.get(), account.getInstance(), account.getToken());
else
gnuapi = new GNUAPI(contextReference.get());
if (apiAction == API.StatusAction.REPORT)
statusCode = gnuapi.reportAction(status);
else if (apiAction == API.StatusAction.CREATESTATUS)
statusCode = gnuapi.statusAction(status);
else if (apiAction == API.StatusAction.MUTE_NOTIFICATIONS)
statusCode = gnuapi.muteNotifications(targetedId, muteNotifications);
else if (apiAction == API.StatusAction.AUTHORIZE || apiAction == API.StatusAction.REJECT) {
//This part uses the Mastodon API
API api;
if (account != null)
api = new API(contextReference.get(), account.getInstance(), account.getToken());
else
api = new API(contextReference.get());
statusCode = api.postAction(apiAction, targetedId);
} else
statusCode = gnuapi.postAction(apiAction, targetedId);
error = gnuapi.getError();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onPostAction(statusCode, apiAction, targetedId, error);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -30,14 +31,14 @@ import app.fedilab.android.interfaces.OnAdminActionInterface;
* Makes actions for post admin calls * Makes actions for post admin calls
*/ */
public class PostAdminActionAsyncTask extends AsyncTask<Void, Void, Void> { public class PostAdminActionAsyncTask {
private OnAdminActionInterface listener; private final OnAdminActionInterface listener;
private API.adminAction action; private final API.adminAction action;
private String id; private final String id;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final AdminAction adminAction;
private APIResponse apiResponse; private APIResponse apiResponse;
private AdminAction adminAction;
public PostAdminActionAsyncTask(Context context, API.adminAction action, String id, AdminAction adminAction, OnAdminActionInterface onAdminActionInterface) { public PostAdminActionAsyncTask(Context context, API.adminAction action, String id, AdminAction adminAction, OnAdminActionInterface onAdminActionInterface) {
@ -46,29 +47,26 @@ public class PostAdminActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.action = action; this.action = action;
this.id = id; this.id = id;
this.adminAction = adminAction; this.adminAction = adminAction;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
switch (action) { switch (action) {
case GET_ACCOUNTS: case GET_ACCOUNTS:
case GET_ONE_ACCOUNT: case GET_ONE_ACCOUNT:
case GET_REPORTS: case GET_REPORTS:
case GET_ONE_REPORT: case GET_ONE_REPORT:
apiResponse = new API(contextReference.get()).adminGet(action, id, adminAction); apiResponse = new API(contextReference.get()).adminGet(action, id, adminAction);
break; break;
default: default:
apiResponse = new API(contextReference.get()).adminDo(action, id, adminAction); apiResponse = new API(contextReference.get()).adminDo(action, id, adminAction);
} }
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onAdminAction(apiResponse);
return null; mainHandler.post(myRunnable);
} }).start();
@Override
protected void onPostExecute(Void result) {
listener.onAdminAction(apiResponse);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,31 +30,30 @@ import app.fedilab.android.interfaces.OnPostNotificationsActionInterface;
* Posts to delete one or all notifications * Posts to delete one or all notifications
*/ */
public class PostNotificationsAsyncTask extends AsyncTask<Void, Void, Void> { public class PostNotificationsAsyncTask {
private OnPostNotificationsActionInterface listener; private final OnPostNotificationsActionInterface listener;
private final String targetedId;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private String targetedId;
private WeakReference<Context> contextReference;
public PostNotificationsAsyncTask(Context context, String targetedId, OnPostNotificationsActionInterface onPostNotificationsActionInterface) { public PostNotificationsAsyncTask(Context context, String targetedId, OnPostNotificationsActionInterface onPostNotificationsActionInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onPostNotificationsActionInterface; this.listener = onPostNotificationsActionInterface;
this.targetedId = targetedId; this.targetedId = targetedId;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
if (targetedId != null)
apiResponse = new API(this.contextReference.get()).postNoticationAction(targetedId);
else //Delete all notifications
apiResponse = new API(this.contextReference.get()).postNoticationAction(null);
return null;
}
@Override new Thread(() -> {
protected void onPostExecute(Void result) { if (targetedId != null)
listener.onPostNotificationsAction(apiResponse, targetedId); apiResponse = new API(this.contextReference.get()).postNoticationAction(targetedId);
else //Delete all notifications
apiResponse = new API(this.contextReference.get()).postNoticationAction(null);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onPostNotificationsAction(apiResponse, targetedId);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -30,33 +31,32 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface;
* Update a Peertube video * Update a Peertube video
*/ */
public class PostPeertubeAsyncTask extends AsyncTask<Void, Void, Void> { public class PostPeertubeAsyncTask {
private final OnRetrievePeertubeInterface listener;
private final WeakReference<Context> contextReference;
private final Peertube peertube;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
private Peertube peertube;
public PostPeertubeAsyncTask(Context context, Peertube peertube, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { public PostPeertubeAsyncTask(Context context, Peertube peertube, OnRetrievePeertubeInterface onRetrievePeertubeInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrievePeertubeInterface; this.listener = onRetrievePeertubeInterface;
this.peertube = peertube; this.peertube = peertube;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.updateVideo(peertube); apiResponse = peertubeAPI.updateVideo(peertube);
if (apiResponse != null && apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0) if (apiResponse != null && apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0)
apiResponse.getPeertubes().get(0).setUpdate(true); apiResponse.getPeertubes().get(0).setUpdate(true);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
} Runnable myRunnable = () -> listener.onRetrievePeertube(apiResponse);
mainHandler.post(myRunnable);
@Override }).start();
protected void onPostExecute(Void result) {
listener.onRetrievePeertube(apiResponse);
} }
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
@ -39,14 +40,14 @@ import app.fedilab.android.sqlite.TagsCacheDAO;
* Posts status (live version) - scheduled toots are sent via classic post feature in api * Posts status (live version) - scheduled toots are sent via classic post feature in api
*/ */
public class PostStatusAsyncTask extends AsyncTask<Void, Void, Void> { public class PostStatusAsyncTask {
private OnPostStatusActionInterface listener; private final OnPostStatusActionInterface listener;
private final app.fedilab.android.client.Entities.Status status;
private final Account account;
private final WeakReference<Context> contextReference;
private final UpdateAccountInfoAsyncTask.SOCIAL social;
private APIResponse apiResponse; private APIResponse apiResponse;
private app.fedilab.android.client.Entities.Status status;
private Account account;
private WeakReference<Context> contextReference;
private UpdateAccountInfoAsyncTask.SOCIAL social;
public PostStatusAsyncTask(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, Account account, app.fedilab.android.client.Entities.Status status, OnPostStatusActionInterface onPostStatusActionInterface) { public PostStatusAsyncTask(Context context, UpdateAccountInfoAsyncTask.SOCIAL social, Account account, app.fedilab.android.client.Entities.Status status, OnPostStatusActionInterface onPostStatusActionInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -54,84 +55,86 @@ public class PostStatusAsyncTask extends AsyncTask<Void, Void, Void> {
this.status = status; this.status = status;
this.account = account; this.account = account;
this.social = social; this.social = social;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
boolean isconnected = Helper.isConnectedToInternet(contextReference.get(), Helper.getLiveInstance(contextReference.get())); new Thread(() -> {
if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { boolean isconnected = Helper.isConnectedToInternet(contextReference.get(), Helper.getLiveInstance(contextReference.get()));
if (isconnected) { if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
if (account == null) { if (isconnected) {
apiResponse = new API(this.contextReference.get()).postStatusAction(status); if (account == null) {
apiResponse = new API(this.contextReference.get()).postStatusAction(status);
} else {
apiResponse = new API(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status);
}
} else { } else {
apiResponse = new API(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status); apiResponse = new APIResponse();
Error error = new Error();
error.setError(contextReference.get().getString(R.string.no_internet));
error.setStatusCode(-33);
apiResponse.setError(error);
} }
} else { } else {
apiResponse = new APIResponse(); if (isconnected) {
Error error = new Error(); if (account == null) {
error.setError(contextReference.get().getString(R.string.no_internet)); apiResponse = new GNUAPI(this.contextReference.get()).postStatusAction(status);
error.setStatusCode(-33); } else {
apiResponse.setError(error); apiResponse = new GNUAPI(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status);
} }
} else {
if (isconnected) {
if (account == null) {
apiResponse = new GNUAPI(this.contextReference.get()).postStatusAction(status);
} else { } else {
apiResponse = new GNUAPI(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status); apiResponse = new APIResponse();
Error error = new Error();
error.setError(contextReference.get().getString(R.string.no_internet));
error.setStatusCode(-33);
apiResponse.setError(error);
} }
} else {
apiResponse = new APIResponse();
Error error = new Error();
error.setError(contextReference.get().getString(R.string.no_internet));
error.setStatusCode(-33);
apiResponse.setError(error);
} }
} if (status.getIn_reply_to_id() != null) {
if (status.getIn_reply_to_id() != null) { apiResponse.setTargetedId(status.getIn_reply_to_id());
apiResponse.setTargetedId(status.getIn_reply_to_id()); }
} Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
return null; listener.onPostStatusAction(apiResponse);
} //Search for tag with upper cases to store them locally
Thread thread = new Thread() {
@Override @Override
protected void onPostExecute(Void result) { public void run() {
listener.onPostStatusAction(apiResponse); String content = status.getContent();
//Search for tag with upper cases to store them locally if (content != null && content.length() > 0) {
Thread thread = new Thread() { SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
@Override Matcher matcher = Helper.hashtagPattern.matcher(content);
public void run() { while (matcher.find()) {
String content = status.getContent(); int matchStart = matcher.start(1);
if (content != null && content.length() > 0) { int matchEnd = matcher.end();
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Get cached tags
Matcher matcher = Helper.hashtagPattern.matcher(content); List<String> cachedTag = new TagsCacheDAO(contextReference.get(), db).getAll();
while (matcher.find()) { String tag = content.substring(matchStart, matchEnd);
int matchStart = matcher.start(1); tag = tag.replace("#", "");
int matchEnd = matcher.end(); if (cachedTag == null) {
//Get cached tags new TagsCacheDAO(contextReference.get(), db).insert(tag);
List<String> cachedTag = new TagsCacheDAO(contextReference.get(), db).getAll(); } else {
String tag = content.substring(matchStart, matchEnd); //If cache doesn't contain the tag and the tag has upper case
tag = tag.replace("#", ""); if (!cachedTag.contains(tag) && !tag.toLowerCase().equals(tag)) {
if (cachedTag == null) { new TagsCacheDAO(contextReference.get(), db).insert(tag);
new TagsCacheDAO(contextReference.get(), db).insert(tag); }
} else { }
//If cache doesn't contain the tag and the tag has upper case
if (!cachedTag.contains(tag) && !tag.toLowerCase().equals(tag)) {
new TagsCacheDAO(contextReference.get(), db).insert(tag);
} }
} }
} }
};
thread.start();
if (account != null) {
String key = account.getUsername() + "@" + account.getInstance();
Helper.sleeps.put(key, 30000);
Helper.startStreaming(contextReference.get());
} }
} };
}; mainHandler.post(myRunnable);
thread.start(); }).start();
if (account != null) {
String key = account.getUsername() + "@" + account.getInstance();
Helper.sleeps.put(key, 30000);
Helper.startStreaming(contextReference.get());
}
} }
} }

View File

@ -16,7 +16,6 @@ package app.fedilab.android.asynctasks;
import android.app.Activity; import android.app.Activity;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,22 +28,22 @@ import app.fedilab.android.sqlite.Sqlite;
* Remove an account in db * Remove an account in db
*/ */
public class RemoveAccountAsyncTask extends AsyncTask<Void, Void, Void> { public class RemoveAccountAsyncTask {
private WeakReference<Activity> activityReference; private final WeakReference<Activity> activityReference;
private Account account; private final Account account;
public RemoveAccountAsyncTask(Activity activity, Account account) { public RemoveAccountAsyncTask(Activity activity, Account account) {
activityReference = new WeakReference<>(activity); activityReference = new WeakReference<>(activity);
this.account = account; this.account = account;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(activityReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(activityReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new AccountDAO(activityReference.get(), db).removeUser(account); new AccountDAO(activityReference.get(), db).removeUser(account);
return null; }).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -33,42 +34,43 @@ import app.fedilab.android.interfaces.OnRetrieveAccountInterface;
* Retrieves accounts on the instance * Retrieves accounts on the instance
*/ */
public class RetrieveAccountAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveAccountAsyncTask {
private String targetedId; private final String targetedId;
private final OnRetrieveAccountInterface listener;
private final WeakReference<Context> contextReference;
private Account account; private Account account;
private OnRetrieveAccountInterface listener;
private Error error; private Error error;
private WeakReference<Context> contextReference;
public RetrieveAccountAsyncTask(Context context, String targetedId, OnRetrieveAccountInterface onRetrieveAccountInterface) { public RetrieveAccountAsyncTask(Context context, String targetedId, OnRetrieveAccountInterface onRetrieveAccountInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.targetedId = targetedId; this.targetedId = targetedId;
this.listener = onRetrieveAccountInterface; this.listener = onRetrieveAccountInterface;
doInBackground();
} }
@Override
protected Void doInBackground(Void... params) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
API api = new API(this.contextReference.get());
account = api.getAccount(targetedId);
error = api.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
account = peertubeAPI.getAccount(targetedId);
error = peertubeAPI.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
account = gnuapi.getAccount(targetedId);
error = gnuapi.getError();
}
return null;
}
@Override protected void doInBackground() {
protected void onPostExecute(Void result) {
listener.onRetrieveAccount(account, error); new Thread(() -> {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
API api = new API(this.contextReference.get());
account = api.getAccount(targetedId);
error = api.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
account = peertubeAPI.getAccount(targetedId);
error = peertubeAPI.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
account = gnuapi.getAccount(targetedId);
error = gnuapi.getError();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveAccount(account, error);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -28,29 +29,29 @@ import app.fedilab.android.interfaces.OnRetrieveAccountInterface;
* Verify credential * Verify credential
*/ */
public class RetrieveAccountInfoAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveAccountInfoAsyncTask {
private OnRetrieveAccountInterface listener; private final OnRetrieveAccountInterface listener;
private final WeakReference<Context> contextReference;
private Account account; private Account account;
private API api; private API api;
private WeakReference<Context> contextReference;
public RetrieveAccountInfoAsyncTask(Context context, OnRetrieveAccountInterface onRetrieveAccountInterface) { public RetrieveAccountInfoAsyncTask(Context context, OnRetrieveAccountInterface onRetrieveAccountInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveAccountInterface; this.listener = onRetrieveAccountInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
api = new API(this.contextReference.get());
account = api.verifyCredentials();
return null;
}
@Override new Thread(() -> {
protected void onPostExecute(Void result) { api = new API(this.contextReference.get());
listener.onRetrieveAccount(account, api.getError()); account = api.verifyCredentials();
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveAccount(account, api.getError());
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -31,14 +32,14 @@ import app.fedilab.android.interfaces.OnRetrieveAccountsInterface;
* Retrieves accounts on the instance * Retrieves accounts on the instance
*/ */
public class RetrieveAccountsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveAccountsAsyncTask {
private Type action; private final Type action;
private final OnRetrieveAccountsInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id; private String max_id;
private OnRetrieveAccountsInterface listener;
private String targetedId; private String targetedId;
private WeakReference<Context> contextReference;
private String instance, name; private String instance, name;
public RetrieveAccountsAsyncTask(Context context, String instance, String name, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { public RetrieveAccountsAsyncTask(Context context, String instance, String name, OnRetrieveAccountsInterface onRetrieveAccountsInterface) {
@ -47,6 +48,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask<Void, Void, Void> {
this.name = name; this.name = name;
this.listener = onRetrieveAccountsInterface; this.listener = onRetrieveAccountsInterface;
this.action = Type.CHANNELS; this.action = Type.CHANNELS;
doInBackground();
} }
public RetrieveAccountsAsyncTask(Context context, Type action, String targetedId, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { public RetrieveAccountsAsyncTask(Context context, Type action, String targetedId, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) {
@ -55,6 +57,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveAccountsInterface; this.listener = onRetrieveAccountsInterface;
this.targetedId = targetedId; this.targetedId = targetedId;
doInBackground();
} }
public RetrieveAccountsAsyncTask(Context context, Type action, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { public RetrieveAccountsAsyncTask(Context context, Type action, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) {
@ -62,90 +65,90 @@ public class RetrieveAccountsAsyncTask extends AsyncTask<Void, Void, Void> {
this.action = action; this.action = action;
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveAccountsInterface; this.listener = onRetrieveAccountsInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
API api = null; new Thread(() -> {
GNUAPI gnuapi = null; API api = null;
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) GNUAPI gnuapi = null;
api = new API(this.contextReference.get()); if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
else
gnuapi = new GNUAPI(this.contextReference.get());
switch (action) {
case REBLOGGED:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getRebloggedBy(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getRebloggedBy(targetedId, max_id);
}
break;
case SEARCH:
api = new API(this.contextReference.get()); api = new API(this.contextReference.get());
apiResponse = api.search2(targetedId, API.searchType.ACCOUNTS, max_id); else
break; gnuapi = new GNUAPI(this.contextReference.get());
case FAVOURITED: switch (action) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { case REBLOGGED:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getRebloggedBy(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getRebloggedBy(targetedId, max_id);
}
break;
case SEARCH:
api = new API(this.contextReference.get());
apiResponse = api.search2(targetedId, API.searchType.ACCOUNTS, max_id);
break;
case FAVOURITED:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getFavouritedBy(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getFavouritedBy(targetedId, max_id);
}
break;
case BLOCKED:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getBlocks(max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getBlocks(max_id);
}
break;
case MUTED:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getMuted(max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getMuted(max_id);
}
break;
case FOLLOWING:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getFollowing(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getFollowing(targetedId, max_id);
}
break;
case FOLLOWERS:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getFollowers(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getFollowers(targetedId, max_id);
}
break;
case CHANNELS:
assert api != null; assert api != null;
apiResponse = api.getFavouritedBy(targetedId, max_id); apiResponse = api.getPeertubeChannel(instance, name);
} else { break;
case GROUPS:
assert gnuapi != null; assert gnuapi != null;
apiResponse = gnuapi.getFavouritedBy(targetedId, max_id); apiResponse = gnuapi.getGroups(max_id);
} break;
break; }
case BLOCKED: Handler mainHandler = new Handler(Looper.getMainLooper());
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { Runnable myRunnable = () -> listener.onRetrieveAccounts(apiResponse);
assert api != null; mainHandler.post(myRunnable);
apiResponse = api.getBlocks(max_id); }).start();
} else {
assert gnuapi != null;
apiResponse = gnuapi.getBlocks(max_id);
}
break;
case MUTED:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getMuted(max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getMuted(max_id);
}
break;
case FOLLOWING:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getFollowing(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getFollowing(targetedId, max_id);
}
break;
case FOLLOWERS:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
assert api != null;
apiResponse = api.getFollowers(targetedId, max_id);
} else {
assert gnuapi != null;
apiResponse = gnuapi.getFollowers(targetedId, max_id);
}
break;
case CHANNELS:
assert api != null;
apiResponse = api.getPeertubeChannel(instance, name);
break;
case GROUPS:
assert gnuapi != null;
apiResponse = gnuapi.getGroups(max_id);
break;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveAccounts(apiResponse);
} }
public enum Type { public enum Type {

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,50 +36,55 @@ import app.fedilab.android.sqlite.Sqlite;
* Retrieves accounts which are involved in a conversation * Retrieves accounts which are involved in a conversation
*/ */
public class RetrieveAccountsForReplyAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveAccountsForReplyAsyncTask {
private app.fedilab.android.client.Entities.Status status; private final app.fedilab.android.client.Entities.Status status;
private OnRetrieveAccountsReplyInterface listener; private final OnRetrieveAccountsReplyInterface listener;
private final ArrayList<Account> accounts;
private final WeakReference<Context> contextReference;
private ArrayList<String> addedAccounts; private ArrayList<String> addedAccounts;
private ArrayList<Account> accounts;
private WeakReference<Context> contextReference;
public RetrieveAccountsForReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface) { public RetrieveAccountsForReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.status = status; this.status = status;
this.listener = onRetrieveAccountsReplyInterface; this.listener = onRetrieveAccountsReplyInterface;
this.accounts = new ArrayList<>(); this.accounts = new ArrayList<>();
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
app.fedilab.android.client.Entities.Context statusContext = api.getStatusContext(status.getId());
addedAccounts = new ArrayList<>();
accounts.add(status.getAccount());
addedAccounts.add(status.getAccount().getAcct());
//Retrieves the first toot new Thread(() -> {
if (statusContext.getAncestors().size() > 0) { API api = new API(this.contextReference.get());
statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId()); app.fedilab.android.client.Entities.Context statusContext = api.getStatusContext(status.getId());
} addedAccounts = new ArrayList<>();
if (statusContext != null && statusContext.getDescendants().size() > 0) { accounts.add(status.getAccount());
for (app.fedilab.android.client.Entities.Status status : statusContext.getDescendants()) { addedAccounts.add(status.getAccount().getAcct());
if (canBeAdded(status.getAccount().getAcct())) {
accounts.add(status.getAccount()); //Retrieves the first toot
addedAccounts.add(status.getAccount().getAcct()); if (statusContext.getAncestors().size() > 0) {
statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId());
}
if (statusContext != null && statusContext.getDescendants().size() > 0) {
for (app.fedilab.android.client.Entities.Status status : statusContext.getDescendants()) {
if (canBeAdded(status.getAccount().getAcct())) {
accounts.add(status.getAccount());
addedAccounts.add(status.getAccount().getAcct());
}
} }
} }
} if (statusContext != null && statusContext.getAncestors().size() > 0) {
if (statusContext != null && statusContext.getAncestors().size() > 0) { for (app.fedilab.android.client.Entities.Status status : statusContext.getAncestors()) {
for (app.fedilab.android.client.Entities.Status status : statusContext.getAncestors()) { if (canBeAdded(status.getAccount().getAcct())) {
if (canBeAdded(status.getAccount().getAcct())) { accounts.add(status.getAccount());
accounts.add(status.getAccount()); addedAccounts.add(status.getAccount().getAcct());
addedAccounts.add(status.getAccount().getAcct()); }
} }
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveAccountsReply(accounts);
mainHandler.post(myRunnable);
}).start();
} }
private boolean canBeAdded(String acct) { private boolean canBeAdded(String acct) {
@ -89,10 +95,4 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask<Void, Void, Voi
Account currentAccount = new AccountDAO(this.contextReference.get(), db).getUniqAccount(userId, instance); Account currentAccount = new AccountDAO(this.contextReference.get(), db).getUniqAccount(userId, instance);
return acct != null && !acct.equals(currentAccount.getAcct()) && !addedAccounts.contains(acct); return acct != null && !acct.equals(currentAccount.getAcct()) && !addedAccounts.contains(acct);
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveAccountsReply(accounts);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.Date; import java.util.Date;
@ -32,35 +33,32 @@ import app.fedilab.android.sqlite.StatusCacheDAO;
* Creates charts for an account * Creates charts for an account
*/ */
public class RetrieveChartsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveChartsAsyncTask {
private OnRetrieveChartsInterface listener; private final OnRetrieveChartsInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final Date dateIni;
private final Date dateEnd;
private Charts charts; private Charts charts;
private Date dateIni;
private Date dateEnd;
public RetrieveChartsAsyncTask(Context context, Date dateIni, Date dateEnd, OnRetrieveChartsInterface onRetrieveChartsInterface) { public RetrieveChartsAsyncTask(Context context, Date dateIni, Date dateEnd, OnRetrieveChartsInterface onRetrieveChartsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveChartsInterface; this.listener = onRetrieveChartsInterface;
this.dateIni = dateIni; this.dateIni = dateIni;
this.dateEnd = dateEnd; this.dateEnd = dateEnd;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); charts = new StatusCacheDAO(contextReference.get(), db).getCharts(dateIni, dateEnd);
charts = new StatusCacheDAO(contextReference.get(), db).getCharts(dateIni, dateEnd); Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onCharts(charts);
return null; mainHandler.post(myRunnable);
} }).start();
@Override
protected void onPostExecute(Void result) {
listener.onCharts(charts);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -32,13 +33,13 @@ import app.fedilab.android.interfaces.OnRetrieveContextInterface;
* Retrieves context for a status * Retrieves context for a status
*/ */
public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveContextAsyncTask {
private String statusId; private final String statusId;
private OnRetrieveContextInterface listener; private final OnRetrieveContextInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private boolean expanded; private final boolean expanded;
private boolean directtimeline; private final boolean directtimeline;
private APIResponse apiResponse; private APIResponse apiResponse;
public RetrieveContextAsyncTask(Context context, boolean expanded, boolean directtimeline, String statusId, OnRetrieveContextInterface onRetrieveContextInterface) { public RetrieveContextAsyncTask(Context context, boolean expanded, boolean directtimeline, String statusId, OnRetrieveContextInterface onRetrieveContextInterface) {
@ -47,39 +48,38 @@ public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveContextInterface; this.listener = onRetrieveContextInterface;
this.expanded = expanded; this.expanded = expanded;
this.directtimeline = directtimeline; this.directtimeline = directtimeline;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
apiResponse = new APIResponse(); apiResponse = new APIResponse();
apiResponse.setTargetedId(this.statusId); apiResponse.setTargetedId(this.statusId);
app.fedilab.android.client.Entities.Context statusContext; app.fedilab.android.client.Entities.Context statusContext;
Error error; Error error;
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
statusContext = api.getStatusContext(statusId); statusContext = api.getStatusContext(statusId);
//Retrieves the first toot //Retrieves the first toot
if (expanded && statusContext != null && statusContext.getAncestors() != null && statusContext.getAncestors().size() > 0) { if (expanded && statusContext != null && statusContext.getAncestors() != null && statusContext.getAncestors().size() > 0) {
statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId()); statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId());
}
error = api.getError();
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
statusContext = gnuapi.getStatusContext(statusId, directtimeline);
//Retrieves the first toot
if (expanded && statusContext != null && statusContext.getAncestors() != null && statusContext.getAncestors().size() > 0) {
statusContext = gnuapi.getStatusContext(statusContext.getAncestors().get(0).getId(), directtimeline);
}
error = gnuapi.getError();
} }
error = api.getError(); apiResponse.setError(error);
} else { apiResponse.setContext(statusContext);
GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); Handler mainHandler = new Handler(Looper.getMainLooper());
statusContext = gnuapi.getStatusContext(statusId, directtimeline); Runnable myRunnable = () -> listener.onRetrieveContext(apiResponse);
//Retrieves the first toot mainHandler.post(myRunnable);
if (expanded && statusContext != null && statusContext.getAncestors() != null && statusContext.getAncestors().size() > 0) { }).start();
statusContext = gnuapi.getStatusContext(statusContext.getAncestors().get(0).getId(), directtimeline);
}
error = gnuapi.getError();
}
apiResponse.setError(error);
apiResponse.setContext(statusContext);
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveContext(apiResponse);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,30 +30,29 @@ import app.fedilab.android.interfaces.OnRetrieveDomainsInterface;
* Retrieves blocked instance * Retrieves blocked instance
*/ */
public class RetrieveDomainsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveDomainsAsyncTask {
private OnRetrieveDomainsInterface listener; private final OnRetrieveDomainsInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final String max_id;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
public RetrieveDomainsAsyncTask(Context context, String max_id, OnRetrieveDomainsInterface onRetrieveDomainsInterface) { public RetrieveDomainsAsyncTask(Context context, String max_id, OnRetrieveDomainsInterface onRetrieveDomainsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveDomainsInterface; this.listener = onRetrieveDomainsInterface;
this.max_id = max_id; this.max_id = max_id;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getBlockedDomain(max_id);
return null;
}
@Override new Thread(() -> {
protected void onPostExecute(Void result) { API api = new API(this.contextReference.get());
listener.onRetrieveDomains(apiResponse); apiResponse = api.getBlockedDomain(max_id);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveDomains(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
@ -32,30 +33,30 @@ import app.fedilab.android.sqlite.Sqlite;
* Retrieves emojis * Retrieves emojis
*/ */
public class RetrieveEmojiAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveEmojiAsyncTask {
private String shortcode; private final String shortcode;
private final OnRetrieveEmojiInterface listener;
private final WeakReference<Context> contextReference;
private List<Emojis> emojis; private List<Emojis> emojis;
private OnRetrieveEmojiInterface listener;
private WeakReference<Context> contextReference;
public RetrieveEmojiAsyncTask(Context context, String shortcode, OnRetrieveEmojiInterface onRetrieveEmojiInterface) { public RetrieveEmojiAsyncTask(Context context, String shortcode, OnRetrieveEmojiInterface onRetrieveEmojiInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.shortcode = shortcode; this.shortcode = shortcode;
this.listener = onRetrieveEmojiInterface; this.listener = onRetrieveEmojiInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
emojis = new CustomEmojiDAO(contextReference.get(), db).getEmojiStartingBy(shortcode);
return null;
}
@Override new Thread(() -> {
protected void onPostExecute(Void result) { SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
listener.onRetrieveSearchEmoji(emojis); emojis = new CustomEmojiDAO(contextReference.get(), db).getEmojiStartingBy(shortcode);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveSearchEmoji(emojis);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,32 +30,31 @@ import app.fedilab.android.interfaces.OnRetrieveFeedsAfterBookmarkInterface;
* Retrieves toots younger than the bookmarks * Retrieves toots younger than the bookmarks
*/ */
public class RetrieveFeedsAfterBookmarkAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveFeedsAfterBookmarkAsyncTask {
private final OnRetrieveFeedsAfterBookmarkInterface listener;
private final WeakReference<Context> contextReference;
private final String max_id;
private final boolean fetchMore;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrieveFeedsAfterBookmarkInterface listener;
private WeakReference<Context> contextReference;
private String max_id;
private boolean fetchMore;
public RetrieveFeedsAfterBookmarkAsyncTask(Context context, String max_id, boolean fetchMore, OnRetrieveFeedsAfterBookmarkInterface onRetrieveFeedsAfterBookmarkInterface) { public RetrieveFeedsAfterBookmarkAsyncTask(Context context, String max_id, boolean fetchMore, OnRetrieveFeedsAfterBookmarkInterface onRetrieveFeedsAfterBookmarkInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveFeedsAfterBookmarkInterface; this.listener = onRetrieveFeedsAfterBookmarkInterface;
this.max_id = max_id; this.max_id = max_id;
this.fetchMore = fetchMore; this.fetchMore = fetchMore;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
apiResponse = api.getHomeTimeline(max_id); apiResponse = api.getHomeTimeline(max_id);
apiResponse.setFetchmore(fetchMore); apiResponse.setFetchmore(fetchMore);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
} Runnable myRunnable = () -> listener.onRetrieveFeedsAfterBookmark(apiResponse);
mainHandler.post(myRunnable);
@Override }).start();
protected void onPostExecute(Void result) {
listener.onRetrieveFeedsAfterBookmark(apiResponse);
} }
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@ -47,25 +48,25 @@ import app.fedilab.android.sqlite.TimelinesDAO;
* Retrieves toots on the instance * Retrieves toots on the instance
*/ */
public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveFeedsAsyncTask {
private Type action; private final Type action;
private final String max_id;
private final OnRetrieveFeedsInterface listener;
private final WeakReference<Context> contextReference;
private final boolean fromCahe;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
private OnRetrieveFeedsInterface listener;
private String targetedID; private String targetedID;
private String tag; private String tag;
private boolean showMediaOnly = false; private boolean showMediaOnly = false;
private boolean showPinned = false; private boolean showPinned = false;
private boolean showReply = false; private boolean showReply = false;
private WeakReference<Context> contextReference;
private FilterToots filterToots; private FilterToots filterToots;
private String instanceName, remoteInstance, name; private String instanceName, remoteInstance, name;
private int timelineId; private int timelineId;
private String currentfilter; private String currentfilter;
private String social; private String social;
private boolean fromCahe;
public RetrieveFeedsAsyncTask(Context context, FilterToots filterToots, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, FilterToots filterToots, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -74,6 +75,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface; this.listener = onRetrieveFeedsInterface;
this.filterToots = filterToots; this.filterToots = filterToots;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -82,6 +84,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveFeedsInterface; this.listener = onRetrieveFeedsInterface;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, boolean fromCahe, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, boolean fromCahe, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -90,6 +93,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveFeedsInterface; this.listener = onRetrieveFeedsInterface;
this.fromCahe = fromCahe; this.fromCahe = fromCahe;
doInBackground();
} }
@ -100,6 +104,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface; this.listener = onRetrieveFeedsInterface;
this.instanceName = instanceName; this.instanceName = instanceName;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, Type action, int timelineId, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, Type action, int timelineId, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -109,6 +114,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface; this.listener = onRetrieveFeedsInterface;
this.timelineId = timelineId; this.timelineId = timelineId;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -120,6 +126,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.showMediaOnly = showMediaOnly; this.showMediaOnly = showMediaOnly;
this.showPinned = showPinned; this.showPinned = showPinned;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, boolean showReply, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, boolean showReply, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -132,6 +139,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.showPinned = showPinned; this.showPinned = showPinned;
this.showReply = showReply; this.showReply = showReply;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, Type action, String tag, String targetedID, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, Type action, String tag, String targetedID, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -142,6 +150,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.targetedID = targetedID; this.targetedID = targetedID;
this.tag = tag; this.tag = tag;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, String remoteInstance, String name, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, String remoteInstance, String name, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -152,6 +161,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.name = name; this.name = name;
this.action = Type.REMOTE_INSTANCE; this.action = Type.REMOTE_INSTANCE;
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
public RetrieveFeedsAsyncTask(Context context, RetrieveFeedsParam retrieveFeedsParam, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrieveFeedsAsyncTask(Context context, RetrieveFeedsParam retrieveFeedsParam, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
@ -170,312 +180,314 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.instanceName = retrieveFeedsParam.getInstanceName(); this.instanceName = retrieveFeedsParam.getInstanceName();
this.remoteInstance = retrieveFeedsParam.getRemoteInstance(); this.remoteInstance = retrieveFeedsParam.getRemoteInstance();
this.fromCahe = false; this.fromCahe = false;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (action == null) if (action != null) {
return null; switch (action) {
switch (action) { case HOME:
case HOME: if (this.fromCahe) {
if (this.fromCahe) { apiResponse = api.getHomeTimelineCache(max_id);
apiResponse = api.getHomeTimelineCache(max_id); } else {
} else { apiResponse = api.getHomeTimeline(max_id);
apiResponse = api.getHomeTimeline(max_id);
}
break;
case LOCAL:
apiResponse = api.getPublicTimeline(true, max_id);
break;
case PUBLIC:
apiResponse = api.getPublicTimeline(false, max_id);
break;
case NEWS:
apiResponse = api.getNews(max_id);
break;
case ANNOUNCEMENTS:
apiResponse = api.getAnnouncements();
break;
case SCHEDULED_TOOTS:
apiResponse = api.scheduledAction("GET", null, max_id, null);
break;
case DIRECT:
apiResponse = api.getDirectTimeline(max_id);
break;
case CONVERSATION:
apiResponse = api.getConversationTimeline(max_id);
break;
case REMOTE_INSTANCE_FILTERED:
if (this.social != null && this.social.equals("MASTODON")) {
apiResponse = api.getPublicTimelineTag(this.currentfilter, true, max_id, this.remoteInstance);
if (apiResponse != null) {
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
if (statusesTemp != null) {
for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
status.setType(action);
}
} }
} break;
} else if (this.social != null && this.social.equals("GNU")) { case LOCAL:
GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); apiResponse = api.getPublicTimeline(true, max_id);
apiResponse = gnuapi.searchRemote(this.remoteInstance, currentfilter, max_id); break;
} else { case PUBLIC:
apiResponse = api.searchPeertube(this.remoteInstance, currentfilter); apiResponse = api.getPublicTimeline(false, max_id);
} break;
break; case NEWS:
case REMOTE_INSTANCE: apiResponse = api.getNews(max_id);
if (this.name != null && this.remoteInstance != null) { //For Peertube channels break;
apiResponse = api.getPeertubeChannelVideos(this.remoteInstance, this.name); case ANNOUNCEMENTS:
} else { //For other remote instance apiResponse = api.getAnnouncements();
List<RemoteInstance> remoteInstanceObj = new InstancesDAO(this.contextReference.get(), db).getInstanceByName(this.instanceName); break;
if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MASTODON")) { case SCHEDULED_TOOTS:
apiResponse = api.getPublicTimeline(this.instanceName, true, max_id); apiResponse = api.scheduledAction("GET", null, max_id, null);
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses(); break;
if (statusesTemp != null) { case DIRECT:
for (app.fedilab.android.client.Entities.Status status : statusesTemp) { apiResponse = api.getDirectTimeline(max_id);
status.setType(action); break;
} case CONVERSATION:
} apiResponse = api.getConversationTimeline(max_id);
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MISSKEY")) { break;
apiResponse = api.getMisskey(this.instanceName, max_id); case REMOTE_INSTANCE_FILTERED:
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses(); if (this.social != null && this.social.equals("MASTODON")) {
if (statusesTemp != null) { apiResponse = api.getPublicTimelineTag(this.currentfilter, true, max_id, this.remoteInstance);
for (app.fedilab.android.client.Entities.Status status : statusesTemp) { if (apiResponse != null) {
status.setType(action); List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
} if (statusesTemp != null) {
} for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("NITTER")) { status.setType(action);
apiResponse = api.getNitter(this.instanceName, max_id);
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
if (statusesTemp != null) {
for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
status.setType(action);
}
}
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("PIXELFED")) {
apiResponse = api.getPixelfedTimeline(instanceName, max_id);
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("GNU")) {
apiResponse = api.getGNUTimeline(instanceName, max_id);
} else {
apiResponse = api.getPeertube(this.instanceName, max_id);
}
}
break;
case FAVOURITES:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
apiResponse = api.getFavourites(max_id);
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.getFavourites(max_id);
}
break;
case USER:
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
if (showMediaOnly)
apiResponse = api.getStatusWithMedia(targetedID, max_id);
else if (showPinned)
apiResponse = api.getPinnedStatuses(targetedID, max_id);
else
apiResponse = api.getAccountTLStatuses(targetedID, max_id, !showReply);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
if (showMediaOnly)
apiResponse = gnuapi.getStatusWithMedia(targetedID, max_id);
else if (showPinned)
apiResponse = gnuapi.getPinnedStatuses(targetedID, max_id);
else
apiResponse = gnuapi.getAccountTLStatuses(targetedID, max_id, !showReply);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getVideos(targetedID, max_id);
}
break;
case MYVIDEOS:
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getMyVideos(max_id);
break;
case PEERTUBE_HISTORY:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getMyHistory(max_id);
break;
case CHANNEL:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getVideosChannel(targetedID, max_id);
break;
case ONESTATUS:
apiResponse = api.getStatusbyId(targetedID);
break;
case SEARCH:
if (!tag.contains("_cache_")) {
apiResponse = api.search2(tag, API.searchType.STATUSES, max_id);
} else {
tag = tag.replace("_cache_", "");
apiResponse = new APIResponse();
Results results = new Results();
List<app.fedilab.android.client.Entities.Status> statuses = new TimelineCacheDAO(contextReference.get(), db).search(tag, max_id);
if (statuses != null && statuses.size() > 0) {
apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId());
}
List<app.fedilab.android.client.Entities.Status> statusesNew = null;
if (statuses != null) {
statusesNew = new ArrayList<>();
for (app.fedilab.android.client.Entities.Status status : statuses) {
if (tag != null && !tag.contains("\"")) {
String[] searches = tag.split(" ");
for (String search : searches) {
if (status.getContent().contains(search) || status.getSpoiler_text().contains(search)) {
statusesNew.add(status);
} }
} }
}
} else if (this.social != null && this.social.equals("GNU")) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.searchRemote(this.remoteInstance, currentfilter, max_id);
} else {
apiResponse = api.searchPeertube(this.remoteInstance, currentfilter);
}
break;
case REMOTE_INSTANCE:
if (this.name != null && this.remoteInstance != null) { //For Peertube channels
apiResponse = api.getPeertubeChannelVideos(this.remoteInstance, this.name);
} else { //For other remote instance
List<RemoteInstance> remoteInstanceObj = new InstancesDAO(this.contextReference.get(), db).getInstanceByName(this.instanceName);
if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MASTODON")) {
apiResponse = api.getPublicTimeline(this.instanceName, true, max_id);
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
if (statusesTemp != null) {
for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
status.setType(action);
}
}
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("MISSKEY")) {
apiResponse = api.getMisskey(this.instanceName, max_id);
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
if (statusesTemp != null) {
for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
status.setType(action);
}
}
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("NITTER")) {
apiResponse = api.getNitter(this.instanceName, max_id);
List<app.fedilab.android.client.Entities.Status> statusesTemp = apiResponse.getStatuses();
if (statusesTemp != null) {
for (app.fedilab.android.client.Entities.Status status : statusesTemp) {
status.setType(action);
}
}
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("PIXELFED")) {
apiResponse = api.getPixelfedTimeline(instanceName, max_id);
} else if (remoteInstanceObj != null && remoteInstanceObj.size() > 0 && remoteInstanceObj.get(0).getType().equals("GNU")) {
apiResponse = api.getGNUTimeline(instanceName, max_id);
} else { } else {
statusesNew.addAll(statuses); apiResponse = api.getPeertube(this.instanceName, max_id);
} }
} }
} break;
results.setStatuses(statusesNew); case FAVOURITES:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
apiResponse = api.getFavourites(max_id);
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.getFavourites(max_id);
}
break;
case USER:
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
if (showMediaOnly)
apiResponse = api.getStatusWithMedia(targetedID, max_id);
else if (showPinned)
apiResponse = api.getPinnedStatuses(targetedID, max_id);
else
apiResponse = api.getAccountTLStatuses(targetedID, max_id, !showReply);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
if (showMediaOnly)
apiResponse = gnuapi.getStatusWithMedia(targetedID, max_id);
else if (showPinned)
apiResponse = gnuapi.getPinnedStatuses(targetedID, max_id);
else
apiResponse = gnuapi.getAccountTLStatuses(targetedID, max_id, !showReply);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getVideos(targetedID, max_id);
}
break;
case MYVIDEOS:
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getMyVideos(max_id);
break;
case PEERTUBE_HISTORY:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getMyHistory(max_id);
break;
case CHANNEL:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getVideosChannel(targetedID, max_id);
break;
case ONESTATUS:
apiResponse = api.getStatusbyId(targetedID);
break;
case SEARCH:
apiResponse.setResults(results); if (!tag.contains("_cache_")) {
} apiResponse = api.search2(tag, API.searchType.STATUSES, max_id);
break; } else {
case TAG: tag = tag.replace("_cache_", "");
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { apiResponse = new APIResponse();
ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId); Results results = new Results();
if (manageTimelines != null && manageTimelines.getTagTimeline() != null) { List<app.fedilab.android.client.Entities.Status> statuses = new TimelineCacheDAO(contextReference.get(), db).search(tag, max_id);
boolean isArt = manageTimelines.getTagTimeline().isART(); if (statuses != null && statuses.size() > 0) {
if (isArt) apiResponse.setMax_id(statuses.get(statuses.size() - 1).getId());
apiResponse = api.getCustomArtTimeline(false, manageTimelines.getTagTimeline().getName(), max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone()); }
else List<app.fedilab.android.client.Entities.Status> statusesNew = null;
apiResponse = api.getPublicTimelineTag(manageTimelines.getTagTimeline().getName(), false, max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone()); if (statuses != null) {
} else { statusesNew = new ArrayList<>();
apiResponse = api.getPublicTimelineTag(tag, false, max_id, null, null, null); for (app.fedilab.android.client.Entities.Status status : statuses) {
} if (tag != null && !tag.contains("\"")) {
} else { String[] searches = tag.split(" ");
GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); for (String search : searches) {
apiResponse = gnuapi.search(tag, max_id); if (status.getContent().contains(search) || status.getSpoiler_text().contains(search)) {
statusesNew.add(status);
}
}
} else {
statusesNew.addAll(statuses);
}
}
}
results.setStatuses(statusesNew);
apiResponse.setResults(results);
}
break;
case TAG:
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId);
if (manageTimelines != null && manageTimelines.getTagTimeline() != null) {
boolean isArt = manageTimelines.getTagTimeline().isART();
if (isArt)
apiResponse = api.getCustomArtTimeline(false, manageTimelines.getTagTimeline().getName(), max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone());
else
apiResponse = api.getPublicTimelineTag(manageTimelines.getTagTimeline().getName(), false, max_id, manageTimelines.getTagTimeline().getAny(), manageTimelines.getTagTimeline().getAll(), manageTimelines.getTagTimeline().getNone());
} else {
apiResponse = api.getPublicTimelineTag(tag, false, max_id, null, null, null);
}
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.search(tag, max_id);
}
break;
case ART:
apiResponse = api.getArtTimeline(false, max_id, null, null, null);
break;
case CACHE_BOOKMARKS:
apiResponse = new APIResponse();
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);
}
} else {
statuses = new ArrayList<>();
}
apiResponse.setStatuses(statuses);
break;
case CACHE_BOOKMARKS_PEERTUBE:
apiResponse = new APIResponse();
db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Peertube> peertubes = new PeertubeFavoritesDAO(contextReference.get(), db).getAllPeertube();
apiResponse.setPeertubes(peertubes);
break;
case CACHE_STATUS:
apiResponse = new APIResponse();
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());
} else {
apiResponse.setStatuses(null);
apiResponse.setMax_id(null);
apiResponse.setSince_id(null);
}
break;
case PSUBSCRIPTIONS:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getSubscriptionsTL(max_id);
break;
case POVERVIEW:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getOverviewTL(max_id);
break;
case PTRENDING:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getTrendingTL(max_id);
break;
case PRECENTLYADDED:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getRecentlyAddedTL(max_id);
break;
case PLOCAL:
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);
break;
case PF_REPLIES:
api = new API(this.contextReference.get());
apiResponse = api.getReplies(targetedID, max_id);
apiResponse.setTargetedId(targetedID);
break;
case PF_LOCAL:
api = new API(this.contextReference.get());
apiResponse = api.getPublicTimeline(true, max_id);
break;
case PF_DISCOVER:
api = new API(this.contextReference.get());
apiResponse = api.getDiscoverTimeline(true, max_id);
break;
case HASHTAG:
break;
case GNU_HOME:
GNUAPI gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getHomeTimeline(max_id);
break;
case GNU_LOCAL:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getPublicTimeline(true, max_id);
break;
case GNU_WHOLE:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getPublicTimeline(false, max_id);
break;
case GNU_DM:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getDirectTimeline(max_id);
break;
case GNU_GROUP_TIMELINE:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getGroupTimeline(tag.trim(), max_id);
break;
} }
break; if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
case ART: List<String> bookmarks = new StatusCacheDAO(contextReference.get(), db).getAllStatusId(StatusCacheDAO.BOOKMARK_CACHE);
apiResponse = api.getArtTimeline(false, max_id, null, null, null); if (apiResponse != null && apiResponse.getStatuses() != null && bookmarks != null && apiResponse.getStatuses().size() > 0) {
break; List<app.fedilab.android.client.Entities.Status> statuses = apiResponse.getStatuses();
case CACHE_BOOKMARKS: for (app.fedilab.android.client.Entities.Status status : statuses) {
apiResponse = new APIResponse(); status.setBookmarked(bookmarks.contains(status.getId()));
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);
} }
} else {
statuses = new ArrayList<>();
}
apiResponse.setStatuses(statuses);
break;
case CACHE_BOOKMARKS_PEERTUBE:
apiResponse = new APIResponse();
db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Peertube> peertubes = new PeertubeFavoritesDAO(contextReference.get(), db).getAllPeertube();
apiResponse.setPeertubes(peertubes);
break;
case CACHE_STATUS:
apiResponse = new APIResponse();
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());
} else {
apiResponse.setStatuses(null);
apiResponse.setMax_id(null);
apiResponse.setSince_id(null);
}
break;
case PSUBSCRIPTIONS:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getSubscriptionsTL(max_id);
break;
case POVERVIEW:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getOverviewTL(max_id);
break;
case PTRENDING:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getTrendingTL(max_id);
break;
case PRECENTLYADDED:
peertubeAPI = new PeertubeAPI(this.contextReference.get());
apiResponse = peertubeAPI.getRecentlyAddedTL(max_id);
break;
case PLOCAL:
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);
break;
case PF_REPLIES:
api = new API(this.contextReference.get());
apiResponse = api.getReplies(targetedID, max_id);
apiResponse.setTargetedId(targetedID);
break;
case PF_LOCAL:
api = new API(this.contextReference.get());
apiResponse = api.getPublicTimeline(true, max_id);
break;
case PF_DISCOVER:
api = new API(this.contextReference.get());
apiResponse = api.getDiscoverTimeline(true, max_id);
break;
case HASHTAG:
break;
case GNU_HOME:
GNUAPI gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getHomeTimeline(max_id);
break;
case GNU_LOCAL:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getPublicTimeline(true, max_id);
break;
case GNU_WHOLE:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getPublicTimeline(false, max_id);
break;
case GNU_DM:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getDirectTimeline(max_id);
break;
case GNU_GROUP_TIMELINE:
gnuAPI = new GNUAPI(this.contextReference.get());
apiResponse = gnuAPI.getGroupTimeline(tag.trim(), max_id);
break;
}
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
List<String> bookmarks = new StatusCacheDAO(contextReference.get(), db).getAllStatusId(StatusCacheDAO.BOOKMARK_CACHE);
if (apiResponse != null && apiResponse.getStatuses() != null && bookmarks != null && apiResponse.getStatuses().size() > 0) {
List<app.fedilab.android.client.Entities.Status> statuses = apiResponse.getStatuses();
for (app.fedilab.android.client.Entities.Status status : statuses) {
status.setBookmarked(bookmarks.contains(status.getId()));
} }
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveFeeds(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveFeeds(apiResponse);
}
public enum Type { public enum Type {
HOME, HOME,

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,29 +30,29 @@ import app.fedilab.android.interfaces.OnRetrieveAccountsInterface;
* Retrieves follow requests sent for the authenticated account * Retrieves follow requests sent for the authenticated account
*/ */
public class RetrieveFollowRequestSentAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveFollowRequestSentAsyncTask {
private final String max_id;
private final OnRetrieveAccountsInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
private OnRetrieveAccountsInterface listener;
private WeakReference<Context> contextReference;
public RetrieveFollowRequestSentAsyncTask(Context context, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) { public RetrieveFollowRequestSentAsyncTask(Context context, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveAccountsInterface; this.listener = onRetrieveAccountsInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
apiResponse = new API(this.contextReference.get()).getFollowRequest(max_id);
return null;
}
@Override new Thread(() -> {
protected void onPostExecute(Void result) { apiResponse = new API(this.contextReference.get()).getFollowRequest(max_id);
listener.onRetrieveAccounts(apiResponse); Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveAccounts(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,29 +30,30 @@ import app.fedilab.android.interfaces.OnRetrieveHowToInterface;
* Retrieves how to videos * Retrieves how to videos
*/ */
public class RetrieveHowToAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveHowToAsyncTask {
private final OnRetrieveHowToInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrieveHowToInterface listener;
private WeakReference<Context> contextReference;
public RetrieveHowToAsyncTask(Context context, OnRetrieveHowToInterface onRetrieveHowToInterface) { public RetrieveHowToAsyncTask(Context context, OnRetrieveHowToInterface onRetrieveHowToInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveHowToInterface; this.listener = onRetrieveHowToInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get()); new Thread(() -> {
apiResponse = api.getHowTo(); API api = new API(this.contextReference.get());
return null; apiResponse = api.getHowTo();
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveHowTo(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveHowTo(apiResponse);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,31 +30,31 @@ import app.fedilab.android.interfaces.OnRetrieveIdentityProofInterface;
* Retrieves identity * Retrieves identity
*/ */
public class RetrieveIdentityProofAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveIdentityProofAsyncTask {
private final OnRetrieveIdentityProofInterface listener;
private final WeakReference<Context> contextReference;
private final String userId;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrieveIdentityProofInterface listener;
private WeakReference<Context> contextReference;
private String userId;
public RetrieveIdentityProofAsyncTask(Context context, String userId, OnRetrieveIdentityProofInterface onRetrieveHowToInterface) { public RetrieveIdentityProofAsyncTask(Context context, String userId, OnRetrieveIdentityProofInterface onRetrieveHowToInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveHowToInterface; this.listener = onRetrieveHowToInterface;
this.userId = userId; this.userId = userId;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
apiResponse = api.getIdentityProof(userId); apiResponse = api.getIdentityProof(userId);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onIdentityProof(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onIdentityProof(apiResponse);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,26 +30,27 @@ import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
* Retrieves the current instance * Retrieves the current instance
*/ */
public class RetrieveInstanceAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveInstanceAsyncTask {
private OnRetrieveInstanceInterface listener; private final OnRetrieveInstanceInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private WeakReference<Context> contextReference;
public RetrieveInstanceAsyncTask(Context context, OnRetrieveInstanceInterface onRetrieveInstanceInterface) { public RetrieveInstanceAsyncTask(Context context, OnRetrieveInstanceInterface onRetrieveInstanceInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveInstanceInterface; this.listener = onRetrieveInstanceInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) {
apiResponse = new API(this.contextReference.get()).getInstance(); new Thread(() -> {
return null; apiResponse = new API(this.contextReference.get()).getInstance();
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveInstance(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveInstance(apiResponse);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -30,34 +31,33 @@ import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
* Retrieves instances for registration * Retrieves instances for registration
*/ */
public class RetrieveInstanceRegAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveInstanceRegAsyncTask {
private OnRetrieveInstanceInterface listener; private final OnRetrieveInstanceInterface listener;
private final WeakReference<Context> contextReference;
private final String category;
private final instanceType type;
private APIResponse apiResponse; private APIResponse apiResponse;
private WeakReference<Context> contextReference;
private String category;
private instanceType type;
public RetrieveInstanceRegAsyncTask(Context context, instanceType type, String category, OnRetrieveInstanceInterface onRetrieveInstanceInterface) { public RetrieveInstanceRegAsyncTask(Context context, instanceType type, String category, OnRetrieveInstanceInterface onRetrieveInstanceInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveInstanceInterface; this.listener = onRetrieveInstanceInterface;
this.category = category; this.category = category;
this.type = type; this.type = type;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (type == instanceType.MASTODON) { if (type == instanceType.MASTODON) {
apiResponse = new API(this.contextReference.get()).getInstanceReg(category); apiResponse = new API(this.contextReference.get()).getInstanceReg(category);
} else if (type == instanceType.PEERTUBE) { } else if (type == instanceType.PEERTUBE) {
apiResponse = new PeertubeAPI(this.contextReference.get()).getInstanceReg(); apiResponse = new PeertubeAPI(this.contextReference.get()).getInstanceReg();
} }
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
} Runnable myRunnable = () -> listener.onRetrieveInstance(apiResponse);
mainHandler.post(myRunnable);
@Override }).start();
protected void onPostExecute(Void result) {
listener.onRetrieveInstance(apiResponse);
} }
public enum instanceType { public enum instanceType {

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
@ -32,32 +33,32 @@ import app.fedilab.android.interfaces.OnRetrieveManyRelationshipsInterface;
* Retrieves many relationship between the authenticated user and other accounts * Retrieves many relationship between the authenticated user and other accounts
*/ */
public class RetrieveManyRelationshipsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveManyRelationshipsAsyncTask {
private List<Account> accounts; private final List<Account> accounts;
private OnRetrieveManyRelationshipsInterface listener; private final OnRetrieveManyRelationshipsInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private WeakReference<Context> contextReference;
public RetrieveManyRelationshipsAsyncTask(Context context, List<Account> accounts, OnRetrieveManyRelationshipsInterface onRetrieveManyRelationshipsInterface) { public RetrieveManyRelationshipsAsyncTask(Context context, List<Account> accounts, OnRetrieveManyRelationshipsInterface onRetrieveManyRelationshipsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveManyRelationshipsInterface; this.listener = onRetrieveManyRelationshipsInterface;
this.accounts = accounts; this.accounts = accounts;
doInBackground();
} }
@Override
protected Void doInBackground(Void... params) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
apiResponse = new API(this.contextReference.get()).getRelationship(accounts);
else
apiResponse = new GNUAPI(this.contextReference.get()).getRelationship(accounts);
return null;
}
@Override protected void doInBackground() {
protected void onPostExecute(Void result) { new Thread(() -> {
listener.onRetrieveRelationship(apiResponse); if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
apiResponse = new API(this.contextReference.get()).getRelationship(accounts);
else
apiResponse = new GNUAPI(this.contextReference.get()).getRelationship(accounts);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveRelationship(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,8 +15,9 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html; import android.text.Html;
import android.util.Patterns; import android.util.Patterns;
@ -28,7 +29,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import app.fedilab.android.client.HttpsConnection; import app.fedilab.android.client.HttpsConnection;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnRetrieveMetaDataInterface; import app.fedilab.android.interfaces.OnRetrieveMetaDataInterface;
@ -37,14 +37,18 @@ import app.fedilab.android.interfaces.OnRetrieveMetaDataInterface;
* Retrieves metadata of a remote page * Retrieves metadata of a remote page
*/ */
public class RetrieveMetaDataAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveMetaDataAsyncTask {
private OnRetrieveMetaDataInterface listener; private final OnRetrieveMetaDataInterface listener;
private final String sharedSubject;
private final String sharedText;
private final WeakReference<Context> contextWeakReference;
private final boolean shouldFetchMetaData;
private String url; private String url;
private boolean error = false; private boolean error = false;
private String image, title, description, sharedSubject, sharedText; private String image;
private WeakReference<Context> contextWeakReference; private String title;
private boolean shouldFetchMetaData; private String description;
public RetrieveMetaDataAsyncTask(Context context, boolean shouldFetchMetaData, String sharedSubject, String sharedText, String url, OnRetrieveMetaDataInterface onRetrieveRemoteAccountInterface) { public RetrieveMetaDataAsyncTask(Context context, boolean shouldFetchMetaData, String sharedSubject, String sharedText, String url, OnRetrieveMetaDataInterface onRetrieveRemoteAccountInterface) {
this.url = url; this.url = url;
@ -53,32 +57,33 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask<Void, Void, Void> {
this.sharedSubject = sharedSubject; this.sharedSubject = sharedSubject;
this.contextWeakReference = new WeakReference<>(context); this.contextWeakReference = new WeakReference<>(context);
this.shouldFetchMetaData = shouldFetchMetaData; this.shouldFetchMetaData = shouldFetchMetaData;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (shouldFetchMetaData) if (shouldFetchMetaData) {
return execRetrieveMetaDataInBackground(); execRetrieveMetaDataInBackground();
else }
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveMetaData(error, sharedSubject, sharedText, image, title, description);
mainHandler.post(myRunnable);
}).start();
} }
private Void execRetrieveMetaDataInBackground() {
private void execRetrieveMetaDataInBackground() {
String potentialUrl = ""; String potentialUrl = "";
if (url == null) { if (url == null) {
error = true; error = true;
return null; return;
} }
try { try {
Matcher matcher; Matcher matcher;
if (url.startsWith("www.")) if (url.startsWith("www."))
url = "http://" + url; url = "http://" + url;
matcher = Patterns.WEB_URL.matcher(url);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
matcher = Patterns.WEB_URL.matcher(url);
else
matcher = Helper.urlPattern.matcher(url);
while (matcher.find()) { while (matcher.find()) {
int matchStart = matcher.start(1); int matchStart = matcher.start(1);
int matchEnd = matcher.end(); int matchEnd = matcher.end();
@ -122,12 +127,7 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask<Void, Void, Void> {
} catch (IOException | IndexOutOfBoundsException e) { } catch (IOException | IndexOutOfBoundsException e) {
error = true; error = true;
} }
return null;
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveMetaData(error, sharedSubject, sharedText, image, title, description);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@ -41,13 +42,13 @@ import app.fedilab.android.sqlite.TimelinesDAO;
* Retrieves missing toots since last pause * Retrieves missing toots since last pause
*/ */
public class RetrieveMissingFeedsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveMissingFeedsAsyncTask {
private String since_id; private final String since_id;
private OnRetrieveMissingFeedsInterface listener; private final OnRetrieveMissingFeedsInterface listener;
private List<app.fedilab.android.client.Entities.Status> statuses = new ArrayList<>(); private final List<app.fedilab.android.client.Entities.Status> statuses = new ArrayList<>();
private RetrieveFeedsAsyncTask.Type type; private final RetrieveFeedsAsyncTask.Type type;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private String remoteInstance; private String remoteInstance;
private int timelineId; private int timelineId;
@ -56,6 +57,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.since_id = since_id; this.since_id = since_id;
this.listener = onRetrieveMissingFeedsInterface; this.listener = onRetrieveMissingFeedsInterface;
this.type = type; this.type = type;
doInBackground();
} }
public RetrieveMissingFeedsAsyncTask(Context context, String remoteInstance, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) { public RetrieveMissingFeedsAsyncTask(Context context, String remoteInstance, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) {
@ -64,6 +66,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveMissingFeedsInterface; this.listener = onRetrieveMissingFeedsInterface;
this.type = type; this.type = type;
this.remoteInstance = remoteInstance; this.remoteInstance = remoteInstance;
doInBackground();
} }
public RetrieveMissingFeedsAsyncTask(Context context, int timelineId, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) { public RetrieveMissingFeedsAsyncTask(Context context, int timelineId, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface) {
@ -72,123 +75,126 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveMissingFeedsInterface; this.listener = onRetrieveMissingFeedsInterface;
this.type = type; this.type = type;
this.timelineId = timelineId; this.timelineId = timelineId;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { if (this.contextReference.get() == null) {
if (this.contextReference.get() == null) Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveMissingFeeds(statuses);
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { mainHandler.post(myRunnable);
API api = new API(this.contextReference.get()); return;
List<app.fedilab.android.client.Entities.Status> tempStatus = null; }
APIResponse apiResponse = null; if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
if (type == RetrieveFeedsAsyncTask.Type.HOME) { API api = new API(this.contextReference.get());
apiResponse = api.getHomeTimelineSinceId(since_id); List<app.fedilab.android.client.Entities.Status> tempStatus = null;
} else if (type == RetrieveFeedsAsyncTask.Type.DIRECT) APIResponse apiResponse = null;
apiResponse = api.getDirectTimelineSinceId(since_id); if (type == RetrieveFeedsAsyncTask.Type.HOME) {
else if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION) apiResponse = api.getHomeTimelineSinceId(since_id);
apiResponse = api.getConversationTimelineSinceId(since_id); } else if (type == RetrieveFeedsAsyncTask.Type.DIRECT)
else if (type == RetrieveFeedsAsyncTask.Type.LOCAL) apiResponse = api.getDirectTimelineSinceId(since_id);
apiResponse = api.getPublicTimelineSinceId(true, since_id); else if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION)
else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC) apiResponse = api.getConversationTimelineSinceId(since_id);
apiResponse = api.getPublicTimelineSinceId(false, since_id); else if (type == RetrieveFeedsAsyncTask.Type.LOCAL)
else if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE) apiResponse = api.getPublicTimelineSinceId(true, since_id);
apiResponse = api.getInstanceTimelineSinceId(remoteInstance, since_id); else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC)
else if (type == RetrieveFeedsAsyncTask.Type.TAG) { apiResponse = api.getPublicTimelineSinceId(false, since_id);
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); else if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE)
ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId); apiResponse = api.getInstanceTimelineSinceId(remoteInstance, since_id);
if (manageTimelines != null && manageTimelines.getTagTimeline() != null) { else if (type == RetrieveFeedsAsyncTask.Type.TAG) {
TagTimeline tagTimeline = manageTimelines.getTagTimeline(); SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
boolean isArt = tagTimeline.isART(); ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId);
if (isArt) if (manageTimelines != null && manageTimelines.getTagTimeline() != null) {
apiResponse = api.getCustomArtTimelineSinceId(false, manageTimelines.getTagTimeline().getName(), since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone()); TagTimeline tagTimeline = manageTimelines.getTagTimeline();
else boolean isArt = tagTimeline.isART();
apiResponse = api.getPublicTimelineTagSinceId(manageTimelines.getTagTimeline().getName(), false, since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone()); if (isArt)
} apiResponse = api.getCustomArtTimelineSinceId(false, manageTimelines.getTagTimeline().getName(), since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone());
} else if (type == RetrieveFeedsAsyncTask.Type.ART) else
apiResponse = api.getArtTimelineSinceId(false, since_id, null, null, null); apiResponse = api.getPublicTimelineTagSinceId(manageTimelines.getTagTimeline().getName(), false, since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone());
if (apiResponse != null) { }
if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION) } else if (type == RetrieveFeedsAsyncTask.Type.ART)
tempStatus = apiResponse.getStatuses(); apiResponse = api.getArtTimelineSinceId(false, since_id, null, null, null);
else { if (apiResponse != null) {
List<Conversation> conversations = apiResponse.getConversations(); if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION)
tempStatus = new ArrayList<>(); tempStatus = apiResponse.getStatuses();
if (conversations != null && conversations.size() > 0) { else {
for (Conversation conversation : conversations) { List<Conversation> conversations = apiResponse.getConversations();
app.fedilab.android.client.Entities.Status status = conversation.getLast_status(); tempStatus = new ArrayList<>();
if (status != null) { if (conversations != null && conversations.size() > 0) {
List<String> ppConversation = new ArrayList<>(); for (Conversation conversation : conversations) {
for (Account account : conversation.getAccounts()) app.fedilab.android.client.Entities.Status status = conversation.getLast_status();
ppConversation.add(account.getAvatar()); if (status != null) {
status.setConversationProfilePicture(ppConversation); List<String> ppConversation = new ArrayList<>();
status.setConversationId(conversation.getId()); for (Account account : conversation.getAccounts())
tempStatus.add(status); ppConversation.add(account.getAvatar());
status.setConversationProfilePicture(ppConversation);
status.setConversationId(conversation.getId());
tempStatus.add(status);
}
} }
} }
} }
}
if (tempStatus != null) if (tempStatus != null)
statuses.addAll(0, tempStatus); statuses.addAll(0, tempStatus);
}
if (type == RetrieveFeedsAsyncTask.Type.HOME && statuses.size() > 0) {
MainActivity.lastHomeId = statuses.get(0).getId();
}
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
List<app.fedilab.android.client.Entities.Status> tempStatus = null;
APIResponse apiResponse = null;
if (type == RetrieveFeedsAsyncTask.Type.GNU_HOME) {
apiResponse = gnuapi.getHomeTimelineSinceId(since_id);
} else if (type == RetrieveFeedsAsyncTask.Type.GNU_LOCAL)
apiResponse = gnuapi.getPublicTimelineSinceId(true, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.GNU_WHOLE)
apiResponse = gnuapi.getPublicTimelineSinceId(false, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.GNU_TAG) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<TagTimeline> tagTimelines = new SearchDAO(contextReference.get(), db).getTimelineInfo(remoteInstance);
if (tagTimelines != null && tagTimelines.size() > 0) {
TagTimeline tagTimeline = tagTimelines.get(0);
boolean isArt = tagTimeline.isART();
if (isArt)
apiResponse = gnuapi.getCustomArtTimelineSinceId(false, remoteInstance, since_id, tagTimelines.get(0).getAny(), tagTimelines.get(0).getAll(), tagTimelines.get(0).getNone());
else
apiResponse = gnuapi.getPublicTimelineTagSinceId(remoteInstance, false, since_id, tagTimelines.get(0).getAny(), tagTimelines.get(0).getAll(), tagTimelines.get(0).getNone());
} else {
apiResponse = gnuapi.getPublicTimelineTag(remoteInstance, false, since_id, tagTimelines.get(0).getAny(), tagTimelines.get(0).getAll(), tagTimelines.get(0).getNone());
} }
} if (type == RetrieveFeedsAsyncTask.Type.HOME && statuses.size() > 0) {
if (apiResponse != null) { MainActivity.lastHomeId = statuses.get(0).getId();
if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION) }
tempStatus = apiResponse.getStatuses(); } else {
else { GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
List<Conversation> conversations = apiResponse.getConversations(); List<app.fedilab.android.client.Entities.Status> tempStatus = null;
tempStatus = new ArrayList<>(); APIResponse apiResponse = null;
if (conversations != null && conversations.size() > 0) { if (type == RetrieveFeedsAsyncTask.Type.GNU_HOME) {
for (Conversation conversation : conversations) { apiResponse = gnuapi.getHomeTimelineSinceId(since_id);
app.fedilab.android.client.Entities.Status status = conversation.getLast_status(); } else if (type == RetrieveFeedsAsyncTask.Type.GNU_LOCAL)
if (status != null) { apiResponse = gnuapi.getPublicTimelineSinceId(true, since_id);
List<String> ppConversation = new ArrayList<>(); else if (type == RetrieveFeedsAsyncTask.Type.GNU_WHOLE)
for (Account account : conversation.getAccounts()) apiResponse = gnuapi.getPublicTimelineSinceId(false, since_id);
ppConversation.add(account.getAvatar()); else if (type == RetrieveFeedsAsyncTask.Type.GNU_TAG) {
status.setConversationProfilePicture(ppConversation); SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
status.setConversationId(conversation.getId()); List<TagTimeline> tagTimelines = new SearchDAO(contextReference.get(), db).getTimelineInfo(remoteInstance);
tempStatus.add(status); if (tagTimelines != null && tagTimelines.size() > 0) {
TagTimeline tagTimeline = tagTimelines.get(0);
boolean isArt = tagTimeline.isART();
if (isArt)
apiResponse = gnuapi.getCustomArtTimelineSinceId(false, remoteInstance, since_id, tagTimelines.get(0).getAny(), tagTimelines.get(0).getAll(), tagTimelines.get(0).getNone());
else
apiResponse = gnuapi.getPublicTimelineTagSinceId(remoteInstance, false, since_id, tagTimelines.get(0).getAny(), tagTimelines.get(0).getAll(), tagTimelines.get(0).getNone());
} else {
apiResponse = gnuapi.getPublicTimelineTag(remoteInstance, false, since_id, tagTimelines.get(0).getAny(), tagTimelines.get(0).getAll(), tagTimelines.get(0).getNone());
}
}
if (apiResponse != null) {
if (type != RetrieveFeedsAsyncTask.Type.CONVERSATION)
tempStatus = apiResponse.getStatuses();
else {
List<Conversation> conversations = apiResponse.getConversations();
tempStatus = new ArrayList<>();
if (conversations != null && conversations.size() > 0) {
for (Conversation conversation : conversations) {
app.fedilab.android.client.Entities.Status status = conversation.getLast_status();
if (status != null) {
List<String> ppConversation = new ArrayList<>();
for (Account account : conversation.getAccounts())
ppConversation.add(account.getAvatar());
status.setConversationProfilePicture(ppConversation);
status.setConversationId(conversation.getId());
tempStatus.add(status);
}
} }
} }
} }
if (tempStatus != null)
statuses.addAll(0, tempStatus);
} }
if (tempStatus != null)
statuses.addAll(0, tempStatus);
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveMissingFeeds(statuses);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveMissingFeeds(statuses);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
@ -34,14 +35,14 @@ import app.fedilab.android.interfaces.OnRetrieveMissingNotificationsInterface;
* Retrieves missing notifications since last pause * Retrieves missing notifications since last pause
*/ */
public class RetrieveMissingNotificationsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveMissingNotificationsAsyncTask {
private final OnRetrieveMissingNotificationsInterface listener;
private final WeakReference<Context> contextReference;
private final DisplayNotificationsFragment.Type type;
private String since_id; private String since_id;
private OnRetrieveMissingNotificationsInterface listener;
private WeakReference<Context> contextReference;
private List<Notification> notifications; private List<Notification> notifications;
private DisplayNotificationsFragment.Type type;
private Error error; private Error error;
public RetrieveMissingNotificationsAsyncTask(Context context, DisplayNotificationsFragment.Type type, String since_id, OnRetrieveMissingNotificationsInterface onRetrieveMissingNotifications) { public RetrieveMissingNotificationsAsyncTask(Context context, DisplayNotificationsFragment.Type type, String since_id, OnRetrieveMissingNotificationsInterface onRetrieveMissingNotifications) {
@ -49,30 +50,32 @@ public class RetrieveMissingNotificationsAsyncTask extends AsyncTask<Void, Void,
this.since_id = since_id; this.since_id = since_id;
this.listener = onRetrieveMissingNotifications; this.listener = onRetrieveMissingNotifications;
this.type = type; this.type = type;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get());
API api = new API(this.contextReference.get()); APIResponse apiResponse = api.getNotificationsSince(type, since_id, 40, false);
APIResponse apiResponse = api.getNotificationsSince(type, since_id, 40, false); if (apiResponse == null) {
if (apiResponse == null) { error = new Error();
error = new Error(); error.setError("");
error.setError(""); return;
return null; }
} error = apiResponse.getError();
error = apiResponse.getError(); since_id = apiResponse.getSince_id();
since_id = apiResponse.getSince_id(); notifications = apiResponse.getNotifications();
notifications = apiResponse.getNotifications(); if (notifications != null && notifications.size() > 0) {
if (notifications != null && notifications.size() > 0) { MainActivity.lastNotificationId = notifications.get(0).getId();
MainActivity.lastNotificationId = notifications.get(0).getId(); }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> {
if (error == null) {
listener.onRetrieveMissingNotifications(notifications);
}
};
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
if (error == null)
listener.onRetrieveMissingNotifications(notifications);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.Date; import java.util.Date;
@ -32,15 +33,15 @@ import app.fedilab.android.sqlite.Sqlite;
* Creates charts for notifications of an account * Creates charts for notifications of an account
*/ */
public class RetrieveNotificationChartsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveNotificationChartsAsyncTask {
private OnRetrieveNotificationChartsInterface listener; private final OnRetrieveNotificationChartsInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final Date dateIni;
private final Date dateEnd;
private final String status_id;
private NotificationCharts charts; private NotificationCharts charts;
private Date dateIni;
private Date dateEnd;
private String status_id;
public RetrieveNotificationChartsAsyncTask(Context context, String status_id, Date dateIni, Date dateEnd, OnRetrieveNotificationChartsInterface onRetrieveNotificationChartsInterface) { public RetrieveNotificationChartsAsyncTask(Context context, String status_id, Date dateIni, Date dateEnd, OnRetrieveNotificationChartsInterface onRetrieveNotificationChartsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -48,21 +49,18 @@ public class RetrieveNotificationChartsAsyncTask extends AsyncTask<Void, Void, V
this.dateIni = dateIni; this.dateIni = dateIni;
this.dateEnd = dateEnd; this.dateEnd = dateEnd;
this.status_id = status_id; this.status_id = status_id;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); charts = new NotificationCacheDAO(contextReference.get(), db).getChartsEvolution(status_id, dateIni, dateEnd);
charts = new NotificationCacheDAO(contextReference.get(), db).getChartsEvolution(status_id, dateIni, dateEnd); Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onCharts(charts);
return null; mainHandler.post(myRunnable);
} }).start();
@Override
protected void onPostExecute(Void result) {
listener.onCharts(charts);
} }
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -31,31 +32,26 @@ import app.fedilab.android.sqlite.Sqlite;
* Retrieves notification stats for an account * Retrieves notification stats for an account
*/ */
public class RetrieveNotificationStatsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveNotificationStatsAsyncTask {
private OnRetrieveNotificationStatsInterface listener; private final OnRetrieveNotificationStatsInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private StatisticsNotification statistics; private StatisticsNotification statistics;
public RetrieveNotificationStatsAsyncTask(Context context, OnRetrieveNotificationStatsInterface onRetrieveNotificationStatsInterface) { public RetrieveNotificationStatsAsyncTask(Context context, OnRetrieveNotificationStatsInterface onRetrieveNotificationStatsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveNotificationStatsInterface; this.listener = onRetrieveNotificationStatsInterface;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
statistics = new NotificationCacheDAO(contextReference.get(), db).getStat();
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Handler mainHandler = new Handler(Looper.getMainLooper());
statistics = new NotificationCacheDAO(contextReference.get(), db).getStat(); Runnable myRunnable = () -> listener.onStats(statistics);
mainHandler.post(myRunnable);
return null; }).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onStats(statistics);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -34,17 +35,17 @@ import app.fedilab.android.interfaces.OnRetrieveNotificationsInterface;
* Retrieves notifications on the instance * Retrieves notifications on the instance
*/ */
public class RetrieveNotificationsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveNotificationsAsyncTask {
private final String max_id;
private final Account account;
private final OnRetrieveNotificationsInterface listener;
private final boolean refreshData;
private final WeakReference<Context> contextReference;
private final boolean display;
private final DisplayNotificationsFragment.Type type;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
private Account account;
private OnRetrieveNotificationsInterface listener;
private boolean refreshData;
private WeakReference<Context> contextReference;
private boolean display;
private DisplayNotificationsFragment.Type type;
public RetrieveNotificationsAsyncTask(Context context, DisplayNotificationsFragment.Type type, boolean display, Account account, String max_id, OnRetrieveNotificationsInterface onRetrieveNotificationsInterface) { public RetrieveNotificationsAsyncTask(Context context, DisplayNotificationsFragment.Type type, boolean display, Account account, String max_id, OnRetrieveNotificationsInterface onRetrieveNotificationsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -54,44 +55,41 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask<Void, Void, Void>
this.refreshData = true; this.refreshData = true;
this.display = display; this.display = display;
this.type = type; this.type = type;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { API api;
API api; if (account == null) {
if (account == null) { api = new API(this.contextReference.get());
api = new API(this.contextReference.get()); apiResponse = api.getNotifications(type, max_id, display);
apiResponse = api.getNotifications(type, max_id, display); } else {
} else { if (this.contextReference.get() == null) {
if (this.contextReference.get() == null) { apiResponse.setError(new Error());
apiResponse.setError(new Error()); return;
return null; }
api = new API(this.contextReference.get(), account.getInstance(), account.getToken());
apiResponse = api.getNotificationsSince(type, max_id, display);
} }
api = new API(this.contextReference.get(), account.getInstance(), account.getToken());
apiResponse = api.getNotificationsSince(type, max_id, display);
}
} else {
GNUAPI gnuapi;
if (account == null) {
gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.getNotifications(type, max_id);
} else { } else {
if (this.contextReference.get() == null) { GNUAPI gnuapi;
apiResponse.setError(new Error()); if (account == null) {
return null; gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.getNotifications(type, max_id);
} else {
if (this.contextReference.get() == null) {
apiResponse.setError(new Error());
return;
}
gnuapi = new GNUAPI(this.contextReference.get(), account.getInstance(), account.getToken());
apiResponse = gnuapi.getNotificationsSince(type, max_id);
} }
gnuapi = new GNUAPI(this.contextReference.get(), account.getInstance(), account.getToken());
apiResponse = gnuapi.getNotificationsSince(type, max_id);
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveNotifications(apiResponse, account, refreshData);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveNotifications(apiResponse, account, refreshData);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
@ -34,42 +35,41 @@ import app.fedilab.android.sqlite.Sqlite;
* Retrieves notifications on the instance * Retrieves notifications on the instance
*/ */
public class RetrieveNotificationsCacheAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveNotificationsCacheAsyncTask {
private final String max_id;
private final OnRetrieveCacheNotificationsInterface listener;
private final WeakReference<Context> contextReference;
private final FilterNotifications filterNotifications;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
private OnRetrieveCacheNotificationsInterface listener;
private WeakReference<Context> contextReference;
private FilterNotifications filterNotifications;
public RetrieveNotificationsCacheAsyncTask(Context context, FilterNotifications filterNotifications, String max_id, OnRetrieveCacheNotificationsInterface onRetrieveNotificationsInterface) { public RetrieveNotificationsCacheAsyncTask(Context context, FilterNotifications filterNotifications, String max_id, OnRetrieveCacheNotificationsInterface onRetrieveNotificationsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveNotificationsInterface; this.listener = onRetrieveNotificationsInterface;
this.filterNotifications = filterNotifications; this.filterNotifications = filterNotifications;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Notification> notifications = new NotificationCacheDAO(contextReference.get(), db).getNotificationsFromID(filterNotifications, max_id); List<Notification> notifications = new NotificationCacheDAO(contextReference.get(), db).getNotificationsFromID(filterNotifications, max_id);
apiResponse = new APIResponse(); apiResponse = new APIResponse();
apiResponse.setNotifications(notifications); apiResponse.setNotifications(notifications);
if (notifications != null && notifications.size() > 0) { if (notifications != null && notifications.size() > 0) {
for (Notification notification : notifications) { for (Notification notification : notifications) {
if (notification.getStatus() != null) { if (notification.getStatus() != null) {
app.fedilab.android.client.Entities.Status.fillSpan(contextReference, notification.getStatus()); app.fedilab.android.client.Entities.Status.fillSpan(contextReference, notification.getStatus());
}
} }
apiResponse.setMax_id(notifications.get(notifications.size() - 1).getId());
} }
apiResponse.setMax_id(notifications.get(notifications.size() - 1).getId()); Handler mainHandler = new Handler(Looper.getMainLooper());
} Runnable myRunnable = () -> listener.onRetrieveNotifications(apiResponse);
return null; mainHandler.post(myRunnable);
} }).start();
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveNotifications(apiResponse);
} }
} }

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -35,33 +36,33 @@ import app.fedilab.android.sqlite.Sqlite;
* Retrieves peertube Channels * Retrieves peertube Channels
*/ */
public class RetrievePeertubeChannelsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrievePeertubeChannelsAsyncTask {
private final OnRetrievePeertubeInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
public RetrievePeertubeChannelsAsyncTask(Context context, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { public RetrievePeertubeChannelsAsyncTask(Context context, OnRetrievePeertubeInterface onRetrievePeertubeInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrievePeertubeInterface; this.listener = onRetrievePeertubeInterface;
doInBackground();
} }
@Override
protected Void doInBackground(Void... params) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(contextReference.get()));
Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance);
apiResponse = peertubeAPI.getPeertubeChannel(account.getUsername());
return null;
}
@Override protected void doInBackground() {
protected void onPostExecute(Void result) { new Thread(() -> {
listener.onRetrievePeertubeChannels(apiResponse); PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(contextReference.get()));
Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance);
apiResponse = peertubeAPI.getPeertubeChannel(account.getUsername());
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrievePeertubeChannels(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,6 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,29 +28,27 @@ import app.fedilab.android.client.PeertubeAPI;
* Retrieves peertube informations * Retrieves peertube informations
*/ */
public class RetrievePeertubeInformationAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrievePeertubeInformationAsyncTask {
public static PeertubeInformation peertubeInformation; public static PeertubeInformation peertubeInformation;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
public RetrievePeertubeInformationAsyncTask(Context context) { public RetrievePeertubeInformationAsyncTask(Context context) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
try { try {
peertubeInformation = peertubeAPI.getPeertubeInformation(); peertubeInformation = peertubeAPI.getPeertubeInformation();
} catch (HttpsConnection.HttpsConnectionException e) { } catch (HttpsConnection.HttpsConnectionException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; }).start();
} }
@Override
protected void onPostExecute(Void result) {
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -31,43 +32,43 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeNotificationsInterface;
* Retrieves Peertube notifications on the instance * Retrieves Peertube notifications on the instance
*/ */
public class RetrievePeertubeNotificationsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrievePeertubeNotificationsAsyncTask {
private final String max_id;
private final Account account;
private final OnRetrievePeertubeNotificationsInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
private Account account;
private OnRetrievePeertubeNotificationsInterface listener;
private WeakReference<Context> contextReference;
public RetrievePeertubeNotificationsAsyncTask(Context context, Account account, String max_id, OnRetrievePeertubeNotificationsInterface onRetrievePeertubeNotificationsInterface) { public RetrievePeertubeNotificationsAsyncTask(Context context, Account account, String max_id, OnRetrievePeertubeNotificationsInterface onRetrievePeertubeNotificationsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrievePeertubeNotificationsInterface; this.listener = onRetrievePeertubeNotificationsInterface;
this.account = account; this.account = account;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
PeertubeAPI api; PeertubeAPI api;
if (account == null) { if (account == null) {
api = new PeertubeAPI(this.contextReference.get()); api = new PeertubeAPI(this.contextReference.get());
apiResponse = api.getNotifications(max_id); apiResponse = api.getNotifications(max_id);
} else { } else {
if (this.contextReference.get() == null) { if (this.contextReference.get() == null) {
apiResponse.setError(new Error()); apiResponse.setError(new Error());
return null; return;
}
api = new PeertubeAPI(this.contextReference.get(), account.getInstance(), account.getToken());
apiResponse = api.getNotificationsSince(max_id);
} }
api = new PeertubeAPI(this.contextReference.get(), account.getInstance(), account.getToken()); Handler mainHandler = new Handler(Looper.getMainLooper());
apiResponse = api.getNotificationsSince(max_id); Runnable myRunnable = () -> listener.onRetrievePeertubeNotifications(apiResponse, account);
} mainHandler.post(myRunnable);
return null; }).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrievePeertubeNotifications(apiResponse, account);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,31 +30,31 @@ import app.fedilab.android.interfaces.OnRetrieveFeedsInterface;
* Retrieves peertube search * Retrieves peertube search
*/ */
public class RetrievePeertubeSearchAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrievePeertubeSearchAsyncTask {
private String query, instance; private final String query;
private final String instance;
private final OnRetrieveFeedsInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrieveFeedsInterface listener;
private WeakReference<Context> contextReference;
public RetrievePeertubeSearchAsyncTask(Context context, String instance, String query, OnRetrieveFeedsInterface onRetrieveFeedsInterface) { public RetrievePeertubeSearchAsyncTask(Context context, String instance, String query, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.query = query; this.query = query;
this.listener = onRetrieveFeedsInterface; this.listener = onRetrieveFeedsInterface;
this.instance = instance; this.instance = instance;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get());
API api = new API(this.contextReference.get()); apiResponse = api.searchPeertube(instance, query);
apiResponse = api.searchPeertube(instance, query); Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveFeeds(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveFeeds(apiResponse);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -33,14 +34,14 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface;
* Retrieves peertube single * Retrieves peertube single
*/ */
public class RetrievePeertubeSingleAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrievePeertubeSingleAsyncTask {
private final String videoId;
private final OnRetrievePeertubeInterface listener;
private final WeakReference<Context> contextReference;
private final String instanceName;
private APIResponse apiResponse; private APIResponse apiResponse;
private String videoId;
private OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
private String instanceName;
public RetrievePeertubeSingleAsyncTask(Context context, String instanceName, String videoId, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { public RetrievePeertubeSingleAsyncTask(Context context, String instanceName, String videoId, OnRetrievePeertubeInterface onRetrievePeertubeInterface) {
@ -48,30 +49,30 @@ public class RetrievePeertubeSingleAsyncTask extends AsyncTask<Void, Void, Void>
this.videoId = videoId; this.videoId = videoId;
this.listener = onRetrievePeertubeInterface; this.listener = onRetrievePeertubeInterface;
this.instanceName = instanceName; this.instanceName = instanceName;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
apiResponse = api.getSinglePeertube(this.instanceName, videoId); apiResponse = api.getSinglePeertube(this.instanceName, videoId);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get()); PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
apiResponse = peertubeAPI.getSinglePeertube(this.instanceName, videoId, token); apiResponse = peertubeAPI.getSinglePeertube(this.instanceName, videoId, token);
if (apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0 && apiResponse.getPeertubes().get(0) != null) { if (apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0 && apiResponse.getPeertubes().get(0) != null) {
String rate = new PeertubeAPI(this.contextReference.get()).getRating(videoId); String rate = new PeertubeAPI(this.contextReference.get()).getRating(videoId);
if (rate != null) if (rate != null)
apiResponse.getPeertubes().get(0).setMyRating(rate); apiResponse.getPeertubes().get(0).setMyRating(rate);
}
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrievePeertube(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrievePeertube(apiResponse);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,14 +30,14 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface;
* Retrieves peertube single * Retrieves peertube single
*/ */
public class RetrievePeertubeSingleCommentsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrievePeertubeSingleCommentsAsyncTask {
private final String videoId;
private final OnRetrievePeertubeInterface listener;
private final WeakReference<Context> contextReference;
private final String instanceName;
private APIResponse apiResponse; private APIResponse apiResponse;
private String videoId;
private OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
private String instanceName;
public RetrievePeertubeSingleCommentsAsyncTask(Context context, String instanceName, String videoId, OnRetrievePeertubeInterface onRetrievePeertubeInterface) { public RetrievePeertubeSingleCommentsAsyncTask(Context context, String instanceName, String videoId, OnRetrievePeertubeInterface onRetrievePeertubeInterface) {
@ -44,18 +45,17 @@ public class RetrievePeertubeSingleCommentsAsyncTask extends AsyncTask<Void, Voi
this.videoId = videoId; this.videoId = videoId;
this.listener = onRetrievePeertubeInterface; this.listener = onRetrievePeertubeInterface;
this.instanceName = instanceName; this.instanceName = instanceName;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get());
API api = new API(this.contextReference.get()); apiResponse = api.getSinglePeertubeComments(this.instanceName, videoId);
apiResponse = api.getSinglePeertubeComments(this.instanceName, videoId); Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrievePeertubeComments(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrievePeertubeComments(apiResponse);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -32,44 +33,42 @@ import app.fedilab.android.interfaces.OnRetrieveRelationshipInterface;
* Retrieves relationship between the authenticated user and another account * Retrieves relationship between the authenticated user and another account
*/ */
public class RetrieveRelationshipAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveRelationshipAsyncTask {
private String accountId; private final String accountId;
private final OnRetrieveRelationshipInterface listener;
private final WeakReference<Context> contextReference;
private Relationship relationship; private Relationship relationship;
private OnRetrieveRelationshipInterface listener;
private Error error; private Error error;
private WeakReference<Context> contextReference;
public RetrieveRelationshipAsyncTask(Context context, String accountId, OnRetrieveRelationshipInterface onRetrieveRelationshipInterface) { public RetrieveRelationshipAsyncTask(Context context, String accountId, OnRetrieveRelationshipInterface onRetrieveRelationshipInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveRelationshipInterface; this.listener = onRetrieveRelationshipInterface;
this.accountId = accountId; this.accountId = accountId;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { API api = new API(this.contextReference.get());
API api = new API(this.contextReference.get()); relationship = api.getRelationship(accountId);
relationship = api.getRelationship(accountId); error = api.getError();
error = api.getError(); } else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); relationship = gnuapi.getRelationship(accountId);
relationship = gnuapi.getRelationship(accountId); error = gnuapi.getError();
error = gnuapi.getError(); } else {
} else { PeertubeAPI api = new PeertubeAPI(this.contextReference.get());
PeertubeAPI api = new PeertubeAPI(this.contextReference.get()); relationship = new Relationship();
relationship = new Relationship(); relationship.setFollowing(api.isFollowing(accountId));
relationship.setFollowing(api.isFollowing(accountId)); error = api.getError();
error = api.getError(); }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveRelationship(relationship, error);
} mainHandler.post(myRunnable);
}).start();
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveRelationship(relationship, error);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -30,35 +31,33 @@ import app.fedilab.android.interfaces.OnRetrieveRelationshipQuickReplyInterface;
* Retrieves relationship between the authenticated user and another account * Retrieves relationship between the authenticated user and another account
*/ */
public class RetrieveRelationshipQuickReplyAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveRelationshipQuickReplyAsyncTask {
private app.fedilab.android.client.Entities.Status status; private final app.fedilab.android.client.Entities.Status status;
private final OnRetrieveRelationshipQuickReplyInterface listener;
private final WeakReference<Context> contextReference;
private Relationship relationship; private Relationship relationship;
private OnRetrieveRelationshipQuickReplyInterface listener;
private Error error; private Error error;
private WeakReference<Context> contextReference;
public RetrieveRelationshipQuickReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveRelationshipQuickReplyInterface onRetrieveRelationshipQuickReplyInterface) { public RetrieveRelationshipQuickReplyAsyncTask(Context context, app.fedilab.android.client.Entities.Status status, OnRetrieveRelationshipQuickReplyInterface onRetrieveRelationshipQuickReplyInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveRelationshipQuickReplyInterface; this.listener = onRetrieveRelationshipQuickReplyInterface;
this.status = status; this.status = status;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { API api = new API(this.contextReference.get());
API api = new API(this.contextReference.get()); relationship = api.getRelationship(status.getReblog() != null ? status.getReblog().getAccount().getId() : status.getAccount().getId());
relationship = api.getRelationship(status.getReblog() != null ? status.getReblog().getAccount().getId() : status.getAccount().getId()); error = api.getError();
error = api.getError(); }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onRetrieveRelationshipQuickReply(relationship, status, error);
} mainHandler.post(myRunnable);
}).start();
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveRelationshipQuickReply(relationship, status, error);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -33,12 +34,12 @@ import app.fedilab.android.interfaces.OnRetrieveRemoteAccountInterface;
*/ */
public class RetrieveRemoteDataAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveRemoteDataAsyncTask {
private final OnRetrieveRemoteAccountInterface listener; private final OnRetrieveRemoteAccountInterface listener;
private final String url; private final String url;
private Results results;
private final WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private Results results;
private boolean developerAccount = false; private boolean developerAccount = false;
@ -47,32 +48,32 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask<Void, Void, Void> {
developerAccount = true; developerAccount = true;
this.listener = onRetrieveRemoteAccountInterface; this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
doInBackground();
} }
public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) {
this.url = Helper.instanceWithProtocol(context, instance) + "/@" + username; this.url = Helper.instanceWithProtocol(context, instance) + "/@" + username;
this.listener = onRetrieveRemoteAccountInterface; this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
doInBackground();
} }
public RetrieveRemoteDataAsyncTask(Context context, String url, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) { public RetrieveRemoteDataAsyncTask(Context context, String url, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) {
this.url = url; this.url = url;
this.listener = onRetrieveRemoteAccountInterface; this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
APIResponse apiResponse = api.search(this.url); APIResponse apiResponse = api.search(this.url);
if (apiResponse.getResults() != null) if (apiResponse.getResults() != null)
results = apiResponse.getResults(); results = apiResponse.getResults();
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveRemoteAccount(results, developerAccount);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveRemoteAccount(results, developerAccount);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock; import android.os.SystemClock;
import com.evernote.android.job.JobManager; import com.evernote.android.job.JobManager;
@ -42,66 +43,64 @@ import app.fedilab.android.sqlite.StatusStoredDAO;
* Retrieves scheduled toots for an account * Retrieves scheduled toots for an account
*/ */
public class RetrieveScheduledTootsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveScheduledTootsAsyncTask {
private OnRetrieveScheduledTootsInterface listener; private final OnRetrieveScheduledTootsInterface listener;
private final WeakReference<Context> contextReference;
private final DisplayScheduledTootsFragment.typeOfSchedule type;
private List<StoredStatus> storedStatuses; private List<StoredStatus> storedStatuses;
private WeakReference<Context> contextReference;
private DisplayScheduledTootsFragment.typeOfSchedule type;
public RetrieveScheduledTootsAsyncTask(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, OnRetrieveScheduledTootsInterface onRetrieveScheduledTootsInterface) { public RetrieveScheduledTootsAsyncTask(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, OnRetrieveScheduledTootsInterface onRetrieveScheduledTootsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveScheduledTootsInterface; this.listener = onRetrieveScheduledTootsInterface;
this.type = type; this.type = type;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
//Retrieves job asked by the user //Retrieves job asked by the user
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
storedStatuses = new StatusStoredDAO(this.contextReference.get(), db).getAllScheduled(); storedStatuses = new StatusStoredDAO(this.contextReference.get(), db).getAllScheduled();
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
storedStatuses = new BoostScheduleDAO(this.contextReference.get(), db).getAllScheduled(); storedStatuses = new BoostScheduleDAO(this.contextReference.get(), db).getAllScheduled();
//Retrieves real jobs still waiting //Retrieves real jobs still waiting
Set<JobRequest> jobRequests = null; Set<JobRequest> jobRequests = null;
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT) if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledTootsSyncJob.SCHEDULED_TOOT); jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledTootsSyncJob.SCHEDULED_TOOT);
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST) else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledBoostsSyncJob.SCHEDULED_BOOST); jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledBoostsSyncJob.SCHEDULED_BOOST);
int[] jobIds; int[] jobIds;
if (jobRequests != null && jobRequests.size() > 0) { if (jobRequests != null && jobRequests.size() > 0) {
int i = 0; int i = 0;
jobIds = new int[jobRequests.size()]; jobIds = new int[jobRequests.size()];
for (JobRequest jobRequest : jobRequests) { for (JobRequest jobRequest : jobRequests) {
jobIds[i] = jobRequest.getJobId(); jobIds[i] = jobRequest.getJobId();
i++; i++;
}
} else {
jobIds = new int[]{};
}
if (storedStatuses != null && storedStatuses.size() > 0) {
for (StoredStatus ss : storedStatuses) {
if (!Helper.isJobPresent(jobIds, ss.getJobId())) {
//JobId is fixed to -1 which means an error occured (it was never sent)
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
new StatusStoredDAO(this.contextReference.get(), db).updateJobId(ss.getId(), -1);
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
new BoostScheduleDAO(this.contextReference.get(), db).updateJobId(ss.getId(), -1);
} }
} else {
jobIds = new int[]{};
} }
//Lets time to update db before dispaying
SystemClock.sleep(1000);
}
return null; if (storedStatuses != null && storedStatuses.size() > 0) {
} for (StoredStatus ss : storedStatuses) {
if (!Helper.isJobPresent(jobIds, ss.getJobId())) {
@Override //JobId is fixed to -1 which means an error occured (it was never sent)
protected void onPostExecute(Void result) { if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
listener.onRetrieveScheduledToots(storedStatuses); new StatusStoredDAO(this.contextReference.get(), db).updateJobId(ss.getId(), -1);
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
new BoostScheduleDAO(this.contextReference.get(), db).updateJobId(ss.getId(), -1);
}
}
//Lets time to update db before dispaying
SystemClock.sleep(1000);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveScheduledToots(storedStatuses);
mainHandler.post(myRunnable);
}).start();
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,19 +30,20 @@ import app.fedilab.android.interfaces.OnRetrieveSearcAccountshInterface;
* Retrieves accounts from search (ie: starting with @ when writing a toot) * Retrieves accounts from search (ie: starting with @ when writing a toot)
*/ */
public class RetrieveSearchAccountsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveSearchAccountsAsyncTask {
private String query; private final String query;
private final OnRetrieveSearcAccountshInterface listener;
private final WeakReference<Context> contextReference;
private final boolean following;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrieveSearcAccountshInterface listener;
private WeakReference<Context> contextReference;
private boolean following;
public RetrieveSearchAccountsAsyncTask(Context context, String query, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) { public RetrieveSearchAccountsAsyncTask(Context context, String query, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.query = query; this.query = query;
this.listener = onRetrieveSearcAccountshInterface; this.listener = onRetrieveSearcAccountshInterface;
this.following = false; this.following = false;
doInBackground();
} }
public RetrieveSearchAccountsAsyncTask(Context context, String query, boolean following, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) { public RetrieveSearchAccountsAsyncTask(Context context, String query, boolean following, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) {
@ -49,24 +51,24 @@ public class RetrieveSearchAccountsAsyncTask extends AsyncTask<Void, Void, Void>
this.query = query; this.query = query;
this.listener = onRetrieveSearcAccountshInterface; this.listener = onRetrieveSearcAccountshInterface;
this.following = following; this.following = following;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
API api = new API(this.contextReference.get()); API api = new API(this.contextReference.get());
if (!following) if (!following)
apiResponse = api.searchAccounts(query, 20); apiResponse = api.searchAccounts(query, 20);
else else
apiResponse = new API(contextReference.get()).searchAccounts(query, 20, true); apiResponse = new API(contextReference.get()).searchAccounts(query, 20, true);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
if (!following)
listener.onRetrieveSearchAccounts(apiResponse);
else
listener.onRetrieveContact(apiResponse);
};
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
if (!following)
listener.onRetrieveSearchAccounts(apiResponse);
else
listener.onRetrieveContact(apiResponse);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.List; import java.util.List;
@ -38,12 +39,12 @@ import app.fedilab.android.sqlite.TagsCacheDAO;
* Retrieves accounts and toots from search * Retrieves accounts and toots from search
*/ */
public class RetrieveSearchAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveSearchAsyncTask {
private final OnRetrieveSearchInterface listener;
private final WeakReference<Context> contextReference;
private String query; private String query;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnRetrieveSearchInterface listener;
private WeakReference<Context> contextReference;
private boolean tagsOnly = false; private boolean tagsOnly = false;
private API.searchType type; private API.searchType type;
private String max_id; private String max_id;
@ -52,6 +53,7 @@ public class RetrieveSearchAsyncTask extends AsyncTask<Void, Void, Void> {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.query = query; this.query = query;
this.listener = onRetrieveSearchInterface; this.listener = onRetrieveSearchInterface;
doInBackground();
} }
public RetrieveSearchAsyncTask(Context context, String query, boolean tagsOnly, OnRetrieveSearchInterface onRetrieveSearchInterface) { public RetrieveSearchAsyncTask(Context context, String query, boolean tagsOnly, OnRetrieveSearchInterface onRetrieveSearchInterface) {
@ -59,6 +61,7 @@ public class RetrieveSearchAsyncTask extends AsyncTask<Void, Void, Void> {
this.query = query; this.query = query;
this.listener = onRetrieveSearchInterface; this.listener = onRetrieveSearchInterface;
this.tagsOnly = tagsOnly; this.tagsOnly = tagsOnly;
doInBackground();
} }
public RetrieveSearchAsyncTask(Context context, String query, API.searchType searchType, String max_id, OnRetrieveSearchInterface onRetrieveSearchInterface) { public RetrieveSearchAsyncTask(Context context, String query, API.searchType searchType, String max_id, OnRetrieveSearchInterface onRetrieveSearchInterface) {
@ -67,95 +70,92 @@ public class RetrieveSearchAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveSearchInterface; this.listener = onRetrieveSearchInterface;
this.type = searchType; this.type = searchType;
this.max_id = max_id; this.max_id = max_id;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (query.compareTo("fedilab_trend") == 0) {
apiResponse = new API(this.contextReference.get()).getTrends();
} else if (this.type == null) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api = new API(this.contextReference.get());
String[] split = query.trim().split("@");
if (split.length > 1) {
if (query.compareTo("fedilab_trend") == 0) { String domain;
apiResponse = new API(this.contextReference.get()).getTrends(); String username;
} else if (this.type == null) { if (split.length == 2) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { username = split[0];
API api = new API(this.contextReference.get()); domain = split[1];
String[] split = query.trim().split("@"); } else {
if (split.length > 1) { username = split[1];
domain = split[2];
String domain;
String username;
if (split.length == 2) {
username = split[0];
domain = split[1];
} else {
username = split[1];
domain = split[2];
}
if (domain != null && username != null) {
InstanceNodeInfo node = api.displayNodeInfo(domain);
String url = null;
if (node != null && node.getName() != null) {
switch (node.getName().trim()) {
case "MASTODON":
case "PLEROMA":
url = "https://" + domain + "/@" + username;
break;
case "PEERTUBE":
url = "https://" + domain + "/accounts/" + username;
break;
case "PIXELFED":
url = "https://" + domain + "/" + username;
break;
case "GNU":
case "FRIENDICA":
url = "https://" + domain + "/profile/" + username;
break;
}
} }
if (url != null) if (domain != null && username != null) {
query = url; InstanceNodeInfo node = api.displayNodeInfo(domain);
} String url = null;
if (node != null && node.getName() != null) {
} switch (node.getName().trim()) {
case "MASTODON":
if (!tagsOnly) case "PLEROMA":
apiResponse = api.search(query); url = "https://" + domain + "/@" + username;
else { break;
//search tags only case "PEERTUBE":
apiResponse = api.search(query); url = "https://" + domain + "/accounts/" + username;
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); break;
List<String> cachedTags = new TagsCacheDAO(contextReference.get(), db).getBy(query); case "PIXELFED":
if (apiResponse != null && apiResponse.getResults() != null && apiResponse.getResults().getHashtags() != null) { url = "https://" + domain + "/" + username;
//If cache contains matching tags break;
if (cachedTags != null) { case "GNU":
for (String apiTag : apiResponse.getResults().getHashtags()) { case "FRIENDICA":
//Cache doesn't contain the tags coming from the api (case insensitive) url = "https://" + domain + "/profile/" + username;
if (!Helper.containsCaseInsensitive(apiTag, cachedTags)) { break;
cachedTags.add(apiTag); //It's added
} }
} }
apiResponse.getResults().setHashtags(cachedTags); if (url != null)
query = url;
} }
} else if (cachedTags != null) {
if (apiResponse != null && apiResponse.getResults() == null) { }
apiResponse.setResults(new Results());
apiResponse.getResults().setHashtags(cachedTags); if (!tagsOnly)
apiResponse = api.search(query);
else {
//search tags only
apiResponse = api.search(query);
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<String> cachedTags = new TagsCacheDAO(contextReference.get(), db).getBy(query);
if (apiResponse != null && apiResponse.getResults() != null && apiResponse.getResults().getHashtags() != null) {
//If cache contains matching tags
if (cachedTags != null) {
for (String apiTag : apiResponse.getResults().getHashtags()) {
//Cache doesn't contain the tags coming from the api (case insensitive)
if (!Helper.containsCaseInsensitive(apiTag, cachedTags)) {
cachedTags.add(apiTag); //It's added
}
}
apiResponse.getResults().setHashtags(cachedTags);
}
} else if (cachedTags != null) {
if (apiResponse != null && apiResponse.getResults() == null) {
apiResponse.setResults(new Results());
apiResponse.getResults().setHashtags(cachedTags);
}
} }
} }
} else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.search(query);
} }
} else { } else {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get()); API api = new API(this.contextReference.get());
apiResponse = gnuapi.search(query); apiResponse = api.search2(query, type, max_id);
} }
} else { Handler mainHandler = new Handler(Looper.getMainLooper());
API api = new API(this.contextReference.get()); Runnable myRunnable = () -> listener.onRetrieveSearch(apiResponse);
apiResponse = api.search2(query, type, max_id); mainHandler.post(myRunnable);
} }).start();
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveSearch(apiResponse);
} }
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -31,31 +32,27 @@ import app.fedilab.android.sqlite.StatusCacheDAO;
* Retrieves stats for an account * Retrieves stats for an account
*/ */
public class RetrieveStatsAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveStatsAsyncTask {
private OnRetrieveStatsInterface listener; private final OnRetrieveStatsInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private Statistics statistics; private Statistics statistics;
public RetrieveStatsAsyncTask(Context context, OnRetrieveStatsInterface onRetrieveStatsInterface) { public RetrieveStatsAsyncTask(Context context, OnRetrieveStatsInterface onRetrieveStatsInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveStatsInterface; this.listener = onRetrieveStatsInterface;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
statistics = new StatusCacheDAO(contextReference.get(), db).getStat();
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Handler mainHandler = new Handler(Looper.getMainLooper());
statistics = new StatusCacheDAO(contextReference.get(), db).getStat(); Runnable myRunnable = () -> listener.onStats(statistics);
mainHandler.post(myRunnable);
return null; }).start();
}
@Override
protected void onPostExecute(Void result) {
listener.onStats(statistics);
} }
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -29,36 +30,35 @@ import app.fedilab.android.interfaces.OnRetrieveStoriesInterface;
* Retrieves stories on the instance * Retrieves stories on the instance
*/ */
public class RetrieveStoriesAsyncTask extends AsyncTask<Void, Void, Void> { public class RetrieveStoriesAsyncTask {
private final String max_id;
private final OnRetrieveStoriesInterface listener;
private final WeakReference<Context> contextReference;
private final type typeOfStory;
private APIResponse apiResponse; private APIResponse apiResponse;
private String max_id;
private OnRetrieveStoriesInterface listener;
private WeakReference<Context> contextReference;
private type typeOfStory;
public RetrieveStoriesAsyncTask(Context context, String max_id, type typeOfStory, OnRetrieveStoriesInterface onRetrieveStoriesInterface) { public RetrieveStoriesAsyncTask(Context context, String max_id, type typeOfStory, OnRetrieveStoriesInterface onRetrieveStoriesInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.max_id = max_id; this.max_id = max_id;
this.listener = onRetrieveStoriesInterface; this.listener = onRetrieveStoriesInterface;
this.typeOfStory = typeOfStory; this.typeOfStory = typeOfStory;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
PixelfedAPI pixelfedAPI = new PixelfedAPI(this.contextReference.get()); PixelfedAPI pixelfedAPI = new PixelfedAPI(this.contextReference.get());
if (typeOfStory == type.FRIENDS) { if (typeOfStory == type.FRIENDS) {
apiResponse = pixelfedAPI.getFriendStories(max_id); apiResponse = pixelfedAPI.getFriendStories(max_id);
} else if (typeOfStory == type.ME) { } else if (typeOfStory == type.ME) {
apiResponse = pixelfedAPI.getMyStories(); apiResponse = pixelfedAPI.getMyStories();
} }
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
} Runnable myRunnable = () -> listener.onRetrieveStories(apiResponse);
mainHandler.post(myRunnable);
@Override }).start();
protected void onPostExecute(Void result) {
listener.onRetrieveStories(apiResponse);
} }
public enum type { public enum type {

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock; import android.os.SystemClock;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -37,18 +38,19 @@ import static app.fedilab.android.sqlite.StatusCacheDAO.BOOKMARK_CACHE;
* Sync bookmarks * Sync bookmarks
*/ */
public class SyncBookmarksAsyncTask extends AsyncTask<Void, Void, Void> { public class SyncBookmarksAsyncTask {
private final OnSyncBookmarksInterface listener;
private final WeakReference<Context> contextReference;
private final sync type;
private List<app.fedilab.android.client.Entities.Status> statusList; private List<app.fedilab.android.client.Entities.Status> statusList;
private OnSyncBookmarksInterface listener;
private WeakReference<Context> contextReference;
private sync type;
private String statusId; private String statusId;
public SyncBookmarksAsyncTask(Context context, sync type, OnSyncBookmarksInterface onSyncBookmarksInterface) { public SyncBookmarksAsyncTask(Context context, sync type, OnSyncBookmarksInterface onSyncBookmarksInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.type = type; this.type = type;
this.listener = onSyncBookmarksInterface; this.listener = onSyncBookmarksInterface;
doInBackground();
} }
public SyncBookmarksAsyncTask(Context context, String statusId, OnSyncBookmarksInterface onSyncBookmarksInterface) { public SyncBookmarksAsyncTask(Context context, String statusId, OnSyncBookmarksInterface onSyncBookmarksInterface) {
@ -56,58 +58,57 @@ public class SyncBookmarksAsyncTask extends AsyncTask<Void, Void, Void> {
this.type = sync.REFRESH; this.type = sync.REFRESH;
this.statusId = statusId; this.statusId = statusId;
this.listener = onSyncBookmarksInterface; this.listener = onSyncBookmarksInterface;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (type == sync.IMPORT) { if (type == sync.IMPORT) {
String max_id = null; String max_id = null;
do { do {
APIResponse apiResponse = new API(contextReference.get()).getBookmarks(max_id); APIResponse apiResponse = new API(contextReference.get()).getBookmarks(max_id);
max_id = apiResponse.getMax_id(); max_id = apiResponse.getMax_id();
List<app.fedilab.android.client.Entities.Status> statuses = apiResponse.getStatuses(); List<app.fedilab.android.client.Entities.Status> statuses = apiResponse.getStatuses();
for (app.fedilab.android.client.Entities.Status tmpStatus : statuses) { for (app.fedilab.android.client.Entities.Status tmpStatus : statuses) {
app.fedilab.android.client.Entities.Status status = new StatusCacheDAO(contextReference.get(), db).getStatus(BOOKMARK_CACHE, tmpStatus.getId()); app.fedilab.android.client.Entities.Status status = new StatusCacheDAO(contextReference.get(), db).getStatus(BOOKMARK_CACHE, tmpStatus.getId());
if (status == null) { if (status == null) {
new StatusCacheDAO(contextReference.get(), db).insertStatus(BOOKMARK_CACHE, tmpStatus); new StatusCacheDAO(contextReference.get(), db).insertStatus(BOOKMARK_CACHE, tmpStatus);
}
} }
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
SystemClock.sleep(200);
}
} while (max_id != null);
statusList = new StatusCacheDAO(contextReference.get(), db).getAllStatus(BOOKMARK_CACHE);
} else if (type == sync.EXPORT) {
List<app.fedilab.android.client.Entities.Status> statuses = new StatusCacheDAO(contextReference.get(), db).getAllStatus(BOOKMARK_CACHE);
if (statuses != null) {
for (app.fedilab.android.client.Entities.Status tmpStatus : statuses) {
new API(contextReference.get()).postAction(API.StatusAction.BOOKMARK, tmpStatus.getId());
try { try {
Thread.sleep(200); Thread.sleep(200);
} catch (InterruptedException e) { } catch (InterruptedException e) {
SystemClock.sleep(200); SystemClock.sleep(200);
} }
} while (max_id != null);
statusList = new StatusCacheDAO(contextReference.get(), db).getAllStatus(BOOKMARK_CACHE);
} else if (type == sync.EXPORT) {
List<app.fedilab.android.client.Entities.Status> statuses = new StatusCacheDAO(contextReference.get(), db).getAllStatus(BOOKMARK_CACHE);
if (statuses != null) {
for (app.fedilab.android.client.Entities.Status tmpStatus : statuses) {
new API(contextReference.get()).postAction(API.StatusAction.BOOKMARK, tmpStatus.getId());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
SystemClock.sleep(200);
}
}
} }
statusList = new StatusCacheDAO(contextReference.get(), db).getAllStatus(BOOKMARK_CACHE);
} else {
APIResponse apiResponse = new API(contextReference.get()).getStatusbyIdAndCache(statusId);
app.fedilab.android.client.Entities.Status refreshedStatus = apiResponse.getStatuses().get(0);
new StatusCacheDAO(contextReference.get().getApplicationContext(), db).updateStatus(BOOKMARK_CACHE, refreshedStatus);
statusList = new ArrayList<>();
statusList.add(refreshedStatus);
} }
statusList = new StatusCacheDAO(contextReference.get(), db).getAllStatus(BOOKMARK_CACHE); Handler mainHandler = new Handler(Looper.getMainLooper());
} else { Runnable myRunnable = () -> listener.onRetrieveBookmarks(statusList);
APIResponse apiResponse = new API(contextReference.get()).getStatusbyIdAndCache(statusId); mainHandler.post(myRunnable);
app.fedilab.android.client.Entities.Status refreshedStatus = apiResponse.getStatuses().get(0); }).start();
new StatusCacheDAO(contextReference.get().getApplicationContext(), db).updateStatus(BOOKMARK_CACHE, refreshedStatus);
statusList = new ArrayList<>();
statusList.add(refreshedStatus);
}
return null;
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveBookmarks(statusList);
}
public enum sync { public enum sync {
EXPORT, EXPORT,

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@ -45,14 +46,14 @@ import app.fedilab.android.sqlite.TimelinesDAO;
* Retrieves timelines * Retrieves timelines
*/ */
public class SyncTimelinesAsyncTask extends AsyncTask<Void, Void, Void> { public class SyncTimelinesAsyncTask {
private OnSyncTimelineInterface listener; private final OnSyncTimelineInterface listener;
private int position; private final int position;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private final boolean syncLists;
private List<ManageTimelines> manageTimelines; private List<ManageTimelines> manageTimelines;
private boolean syncLists;
public SyncTimelinesAsyncTask(Context context, int position, boolean syncLists, OnSyncTimelineInterface onSyncTimelineInterface) { public SyncTimelinesAsyncTask(Context context, int position, boolean syncLists, OnSyncTimelineInterface onSyncTimelineInterface) {
@ -60,301 +61,299 @@ public class SyncTimelinesAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onSyncTimelineInterface; this.listener = onSyncTimelineInterface;
this.position = position; this.position = position;
this.syncLists = syncLists; this.syncLists = syncLists;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); manageTimelines = new TimelinesDAO(contextReference.get(), db).getAllTimelines();
manageTimelines = new TimelinesDAO(contextReference.get(), db).getAllTimelines(); //First time that the timeline is created
//First time that the timeline is created int i = 0;
int i = 0; if (manageTimelines == null || manageTimelines.size() == 0) {
if (manageTimelines == null || manageTimelines.size() == 0) { manageTimelines = new ArrayList<>();
manageTimelines = new ArrayList<>(); //Add home TL
//Add home TL ManageTimelines manageHome = new ManageTimelines();
ManageTimelines manageHome = new ManageTimelines(); manageHome.setDisplayed(true);
manageHome.setDisplayed(true); manageHome.setType(ManageTimelines.Type.HOME);
manageHome.setType(ManageTimelines.Type.HOME); manageHome.setPosition(i);
manageHome.setPosition(i); manageTimelines.add(manageHome);
manageTimelines.add(manageHome);
i++;
new TimelinesDAO(contextReference.get(), db).insert(manageHome);
//Add Direct notification TL
ManageTimelines manageNotif = new ManageTimelines();
manageNotif.setDisplayed(true);
manageNotif.setType(ManageTimelines.Type.NOTIFICATION);
manageNotif.setPosition(i);
i++;
manageTimelines.add(manageNotif);
new TimelinesDAO(contextReference.get(), db).insert(manageNotif);
//Add Direct message TL
ManageTimelines manageDirect = new ManageTimelines();
manageDirect.setDisplayed(true);
manageDirect.setType(ManageTimelines.Type.DIRECT);
manageDirect.setPosition(i);
i++;
manageTimelines.add(manageDirect);
new TimelinesDAO(contextReference.get(), db).insert(manageDirect);
//Add Local TL
ManageTimelines manageLocal = new ManageTimelines();
manageLocal.setDisplayed(true);
manageLocal.setType(ManageTimelines.Type.LOCAL);
manageLocal.setPosition(i);
i++;
manageTimelines.add(manageLocal);
new TimelinesDAO(contextReference.get(), db).insert(manageLocal);
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
//Add Public TL
ManageTimelines managePublic = new ManageTimelines();
managePublic.setDisplayed(true);
managePublic.setType(ManageTimelines.Type.PUBLIC);
managePublic.setPosition(i);
i++; i++;
manageTimelines.add(managePublic); new TimelinesDAO(contextReference.get(), db).insert(manageHome);
new TimelinesDAO(contextReference.get(), db).insert(managePublic); //Add Direct notification TL
} ManageTimelines manageNotif = new ManageTimelines();
if (!BuildConfig.lite && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) { manageNotif.setDisplayed(true);
//Add Public ART manageNotif.setType(ManageTimelines.Type.NOTIFICATION);
ManageTimelines manageArt = new ManageTimelines(); manageNotif.setPosition(i);
manageArt.setDisplayed(true);
manageArt.setType(ManageTimelines.Type.ART);
manageArt.setPosition(i);
i++; i++;
manageTimelines.add(manageArt); manageTimelines.add(manageNotif);
new TimelinesDAO(contextReference.get(), db).insert(manageArt); new TimelinesDAO(contextReference.get(), db).insert(manageNotif);
//Add Public PEERTUBE //Add Direct message TL
ManageTimelines managePeertube = new ManageTimelines(); ManageTimelines manageDirect = new ManageTimelines();
managePeertube.setDisplayed(true); manageDirect.setDisplayed(true);
managePeertube.setType(ManageTimelines.Type.PEERTUBE); manageDirect.setType(ManageTimelines.Type.DIRECT);
managePeertube.setPosition(i); manageDirect.setPosition(i);
i++; i++;
manageTimelines.add(managePeertube); manageTimelines.add(manageDirect);
new TimelinesDAO(contextReference.get(), db).insert(managePeertube); new TimelinesDAO(contextReference.get(), db).insert(manageDirect);
} //Add Local TL
ManageTimelines manageLocal = new ManageTimelines();
List<TagTimeline> tagTimelines = new SearchDAO(contextReference.get(), db).getAll(); manageLocal.setDisplayed(true);
if (tagTimelines != null && tagTimelines.size() > 0) { manageLocal.setType(ManageTimelines.Type.LOCAL);
for (TagTimeline ttl : tagTimelines) { manageLocal.setPosition(i);
//Add tag timelines i++;
ManageTimelines manageTagTimeline = new ManageTimelines(); manageTimelines.add(manageLocal);
manageTagTimeline.setDisplayed(true); new TimelinesDAO(contextReference.get(), db).insert(manageLocal);
manageTagTimeline.setType(ManageTimelines.Type.TAG); if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
manageTagTimeline.setPosition(i); //Add Public TL
manageTagTimeline.setTagTimeline(ttl); ManageTimelines managePublic = new ManageTimelines();
manageTimelines.add(manageTagTimeline); managePublic.setDisplayed(true);
new TimelinesDAO(contextReference.get(), db).insert(manageTagTimeline); managePublic.setType(ManageTimelines.Type.PUBLIC);
managePublic.setPosition(i);
i++; i++;
manageTimelines.add(managePublic);
new TimelinesDAO(contextReference.get(), db).insert(managePublic);
} }
} if (!BuildConfig.lite && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) {
List<RemoteInstance> instances = new InstancesDAO(contextReference.get(), db).getAllInstances(); //Add Public ART
if (instances != null && instances.size() > 0) { ManageTimelines manageArt = new ManageTimelines();
for (RemoteInstance ritl : instances) { manageArt.setDisplayed(true);
//Add remote instances manageArt.setType(ManageTimelines.Type.ART);
ManageTimelines manageRemoteTimline = new ManageTimelines(); manageArt.setPosition(i);
manageRemoteTimline.setDisplayed(true);
manageRemoteTimline.setType(ManageTimelines.Type.INSTANCE);
manageRemoteTimline.setPosition(i);
manageRemoteTimline.setRemoteInstance(ritl);
manageTimelines.add(manageRemoteTimline);
new TimelinesDAO(contextReference.get(), db).insert(manageRemoteTimline);
i++; i++;
manageTimelines.add(manageArt);
new TimelinesDAO(contextReference.get(), db).insert(manageArt);
//Add Public PEERTUBE
ManageTimelines managePeertube = new ManageTimelines();
managePeertube.setDisplayed(true);
managePeertube.setType(ManageTimelines.Type.PEERTUBE);
managePeertube.setPosition(i);
i++;
manageTimelines.add(managePeertube);
new TimelinesDAO(contextReference.get(), db).insert(managePeertube);
} }
}
}
List<TagTimeline> tagsInDb = new SearchDAO(contextReference.get(), db).getAll(); List<TagTimeline> tagTimelines = new SearchDAO(contextReference.get(), db).getAll();
List<RemoteInstance> instancesInDb = new InstancesDAO(contextReference.get(), db).getAllInstances(); if (tagTimelines != null && tagTimelines.size() > 0) {
for (TagTimeline ttl : tagTimelines) {
if (tagsInDb != null) { //Add tag timelines
for (TagTimeline tag : tagsInDb) { ManageTimelines manageTagTimeline = new ManageTimelines();
boolean isInDb = false; manageTagTimeline.setDisplayed(true);
ManageTimelines timelines_tmp = null; manageTagTimeline.setType(ManageTimelines.Type.TAG);
for (ManageTimelines manageTimeline : manageTimelines) { manageTagTimeline.setPosition(i);
if (manageTimeline.getTagTimeline() == null) manageTagTimeline.setTagTimeline(ttl);
continue; manageTimelines.add(manageTagTimeline);
if (manageTimeline.getTagTimeline().getId() == tag.getId()) { new TimelinesDAO(contextReference.get(), db).insert(manageTagTimeline);
isInDb = true; i++;
timelines_tmp = manageTimeline;
break;
} }
} }
if (!isInDb) { List<RemoteInstance> instances = new InstancesDAO(contextReference.get(), db).getAllInstances();
ManageTimelines manageTL = new ManageTimelines(); if (instances != null && instances.size() > 0) {
manageTL.setTagTimeline(tag); for (RemoteInstance ritl : instances) {
manageTL.setDisplayed(true); //Add remote instances
manageTL.setType(ManageTimelines.Type.TAG); ManageTimelines manageRemoteTimline = new ManageTimelines();
manageTL.setPosition(manageTimelines.size()); manageRemoteTimline.setDisplayed(true);
new TimelinesDAO(contextReference.get(), db).insert(manageTL); manageRemoteTimline.setType(ManageTimelines.Type.INSTANCE);
} else { manageRemoteTimline.setPosition(i);
//Update list manageRemoteTimline.setRemoteInstance(ritl);
timelines_tmp.setTagTimeline(tag); manageTimelines.add(manageRemoteTimline);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp); new TimelinesDAO(contextReference.get(), db).insert(manageRemoteTimline);
i++;
}
} }
} }
for (ManageTimelines manageTimelines : manageTimelines) { List<TagTimeline> tagsInDb = new SearchDAO(contextReference.get(), db).getAll();
if (manageTimelines.getTagTimeline() == null) List<RemoteInstance> instancesInDb = new InstancesDAO(contextReference.get(), db).getAllInstances();
continue;
boolean shouldBeRemoved = true; if (tagsInDb != null) {
for (TagTimeline tag : tagsInDb) { for (TagTimeline tag : tagsInDb) {
if (tag.getId() == manageTimelines.getTagTimeline().getId()) { boolean isInDb = false;
shouldBeRemoved = false; ManageTimelines timelines_tmp = null;
}
}
if (shouldBeRemoved) {
new TimelinesDAO(contextReference.get(), db).remove(manageTimelines);
}
}
}
if (instancesInDb != null) {
for (RemoteInstance instance : instancesInDb) {
boolean isInDb = false;
ManageTimelines timelines_tmp = null;
for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getRemoteInstance() == null)
continue;
if (manageTimeline.getRemoteInstance().getHost().trim().equals(instance.getHost().trim())) {
isInDb = true;
timelines_tmp = manageTimeline;
break;
}
}
if (!isInDb) {
ManageTimelines manageTL = new ManageTimelines();
manageTL.setRemoteInstance(instance);
manageTL.setDisplayed(true);
manageTL.setType(ManageTimelines.Type.INSTANCE);
manageTL.setPosition(manageTimelines.size());
new TimelinesDAO(contextReference.get(), db).insert(manageTL);
manageTimelines.add(manageTL);
} else {
//Update list
timelines_tmp.setRemoteInstance(instance);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
}
}
for (ManageTimelines manageTimelines : manageTimelines) {
if (manageTimelines.getRemoteInstance() == null)
continue;
boolean shouldBeRemoved = true;
for (RemoteInstance instance : instancesInDb) {
if (instance.getHost().trim().equals(manageTimelines.getRemoteInstance().getHost().trim())) {
shouldBeRemoved = false;
}
}
if (shouldBeRemoved) {
new TimelinesDAO(contextReference.get(), db).remove(manageTimelines);
}
}
}
if (this.syncLists) {
APIResponse apiResponse;
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
List<app.fedilab.android.client.Entities.List> listsAPI;
try {
apiResponse = new API(contextReference.get()).getLists();
listsAPI = apiResponse.getLists();
//Check potential duplicated lists in db
List<ManageTimelines> duplicated_id = new ArrayList<>();
List<String> present_id = new ArrayList<>();
for (ManageTimelines manageTimeline : manageTimelines) { for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getListTimeline() == null) if (manageTimeline.getTagTimeline() == null)
continue; continue;
if (!present_id.contains(manageTimeline.getListTimeline().getId())) { if (manageTimeline.getTagTimeline().getId() == tag.getId()) {
present_id.add(manageTimeline.getListTimeline().getId()); isInDb = true;
} else { timelines_tmp = manageTimeline;
duplicated_id.add(manageTimeline); break;
new TimelinesDAO(contextReference.get(), db).remove(manageTimeline);
} }
} }
manageTimelines.removeAll(duplicated_id); if (!isInDb) {
if (listsAPI != null && listsAPI.size() > 0) { ManageTimelines manageTL = new ManageTimelines();
//Loop through results manageTL.setTagTimeline(tag);
for (app.fedilab.android.client.Entities.List list : listsAPI) { manageTL.setDisplayed(true);
boolean isInDb = false; manageTL.setType(ManageTimelines.Type.TAG);
ManageTimelines timelines_tmp = null; manageTL.setPosition(manageTimelines.size());
for (ManageTimelines manageTimeline : manageTimelines) { new TimelinesDAO(contextReference.get(), db).insert(manageTL);
if (manageTimeline.getListTimeline() == null) } else {
continue; //Update list
if (manageTimeline.getListTimeline().getId().equals(list.getId())) { timelines_tmp.setTagTimeline(tag);
isInDb = true; new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
timelines_tmp = manageTimeline; }
break; }
}
} for (ManageTimelines manageTimelines : manageTimelines) {
//The current list is not registred in the database if (manageTimelines.getTagTimeline() == null)
if (!isInDb) { continue;
ManageTimelines manageTL = new ManageTimelines(); boolean shouldBeRemoved = true;
manageTL.setListTimeline(list); for (TagTimeline tag : tagsInDb) {
manageTL.setDisplayed(true); if (tag.getId() == manageTimelines.getTagTimeline().getId()) {
manageTL.setType(ManageTimelines.Type.LIST); shouldBeRemoved = false;
manageTL.setPosition(manageTimelines.size()); break;
new TimelinesDAO(contextReference.get(), db).insert(manageTL);
manageTimelines.add(manageTL);
} else {
//Update list
timelines_tmp.setListTimeline(list);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
}
} }
ArrayList<ManageTimelines> manageTimelinesToRemove = new ArrayList<>(); }
for (ManageTimelines dbtTimelines : manageTimelines) { if (shouldBeRemoved) {
if (dbtTimelines.getListTimeline() == null) new TimelinesDAO(contextReference.get(), db).remove(manageTimelines);
}
}
}
if (instancesInDb != null) {
for (RemoteInstance instance : instancesInDb) {
boolean isInDb = false;
ManageTimelines timelines_tmp = null;
for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getRemoteInstance() == null)
continue;
if (manageTimeline.getRemoteInstance().getHost().trim().equals(instance.getHost().trim())) {
isInDb = true;
timelines_tmp = manageTimeline;
break;
}
}
if (!isInDb) {
ManageTimelines manageTL = new ManageTimelines();
manageTL.setRemoteInstance(instance);
manageTL.setDisplayed(true);
manageTL.setType(ManageTimelines.Type.INSTANCE);
manageTL.setPosition(manageTimelines.size());
new TimelinesDAO(contextReference.get(), db).insert(manageTL);
manageTimelines.add(manageTL);
} else {
//Update list
timelines_tmp.setRemoteInstance(instance);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
}
}
for (ManageTimelines manageTimelines : manageTimelines) {
if (manageTimelines.getRemoteInstance() == null)
continue;
boolean shouldBeRemoved = true;
for (RemoteInstance instance : instancesInDb) {
if (instance.getHost().trim().equals(manageTimelines.getRemoteInstance().getHost().trim())) {
shouldBeRemoved = false;
}
}
if (shouldBeRemoved) {
new TimelinesDAO(contextReference.get(), db).remove(manageTimelines);
}
}
}
if (this.syncLists) {
APIResponse apiResponse;
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
List<app.fedilab.android.client.Entities.List> listsAPI;
try {
apiResponse = new API(contextReference.get()).getLists();
listsAPI = apiResponse.getLists();
//Check potential duplicated lists in db
List<ManageTimelines> duplicated_id = new ArrayList<>();
List<String> present_id = new ArrayList<>();
for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getListTimeline() == null)
continue; continue;
boolean shouldBeRemoved = true; if (!present_id.contains(manageTimeline.getListTimeline().getId())) {
present_id.add(manageTimeline.getListTimeline().getId());
} else {
duplicated_id.add(manageTimeline);
new TimelinesDAO(contextReference.get(), db).remove(manageTimeline);
}
}
manageTimelines.removeAll(duplicated_id);
if (listsAPI != null && listsAPI.size() > 0) {
//Loop through results
for (app.fedilab.android.client.Entities.List list : listsAPI) { for (app.fedilab.android.client.Entities.List list : listsAPI) {
if (list.getId().equals(dbtTimelines.getListTimeline().getId())) { boolean isInDb = false;
shouldBeRemoved = false; ManageTimelines timelines_tmp = null;
for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getListTimeline() == null)
continue;
if (manageTimeline.getListTimeline().getId().equals(list.getId())) {
isInDb = true;
timelines_tmp = manageTimeline;
break;
}
}
//The current list is not registred in the database
if (!isInDb) {
ManageTimelines manageTL = new ManageTimelines();
manageTL.setListTimeline(list);
manageTL.setDisplayed(true);
manageTL.setType(ManageTimelines.Type.LIST);
manageTL.setPosition(manageTimelines.size());
new TimelinesDAO(contextReference.get(), db).insert(manageTL);
manageTimelines.add(manageTL);
} else {
//Update list
timelines_tmp.setListTimeline(list);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
} }
} }
if (shouldBeRemoved) { ArrayList<ManageTimelines> manageTimelinesToRemove = new ArrayList<>();
new TimelinesDAO(contextReference.get(), db).remove(dbtTimelines); for (ManageTimelines dbtTimelines : manageTimelines) {
manageTimelinesToRemove.add(dbtTimelines); if (dbtTimelines.getListTimeline() == null)
}
}
if (manageTimelinesToRemove.size() > 0) {
manageTimelines.removeAll(manageTimelinesToRemove);
}
} else { //No lists, all are removed if exist in db
ArrayList<ManageTimelines> manageTimelinesToRemove = new ArrayList<>();
if (apiResponse.getError() == null) { //Only done if there is no errors when fetching lists
for (ManageTimelines manageTimelines : manageTimelines) {
if (manageTimelines.getListTimeline() == null)
continue; continue;
new TimelinesDAO(contextReference.get(), db).remove(manageTimelines); boolean shouldBeRemoved = true;
manageTimelinesToRemove.add(manageTimelines); for (app.fedilab.android.client.Entities.List list : listsAPI) {
if (list.getId().equals(dbtTimelines.getListTimeline().getId())) {
shouldBeRemoved = false;
break;
}
}
if (shouldBeRemoved) {
new TimelinesDAO(contextReference.get(), db).remove(dbtTimelines);
manageTimelinesToRemove.add(dbtTimelines);
}
} }
if (manageTimelinesToRemove.size() > 0) { if (manageTimelinesToRemove.size() > 0) {
manageTimelines.removeAll(manageTimelinesToRemove); manageTimelines.removeAll(manageTimelinesToRemove);
} }
} else { //No lists, all are removed if exist in db
ArrayList<ManageTimelines> manageTimelinesToRemove = new ArrayList<>();
if (apiResponse.getError() == null) { //Only done if there is no errors when fetching lists
for (ManageTimelines manageTimelines : manageTimelines) {
if (manageTimelines.getListTimeline() == null)
continue;
new TimelinesDAO(contextReference.get(), db).remove(manageTimelines);
manageTimelinesToRemove.add(manageTimelines);
}
if (manageTimelinesToRemove.size() > 0) {
manageTimelines.removeAll(manageTimelinesToRemove);
}
}
} }
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = Helper.getLiveInstance(contextReference.get());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.LAST_DATE_LIST_FETCH + userId + instance, Helper.dateToString(new Date()));
editor.apply();
} catch (Exception ignored) {
} }
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = Helper.getLiveInstance(contextReference.get());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.LAST_DATE_LIST_FETCH + userId + instance, Helper.dateToString(new Date()));
editor.apply();
} catch (Exception ignored) {
} }
} }
} for (Iterator<ManageTimelines> it = manageTimelines.iterator(); it.hasNext(); ) {
for (Iterator<ManageTimelines> it = manageTimelines.iterator(); it.hasNext(); ) { if (!it.next().isDisplayed()) {
if (!it.next().isDisplayed()) { it.remove();
it.remove(); }
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.syncedTimelines(manageTimelines, position);
} mainHandler.post(myRunnable);
}).start();
@Override
protected void onPostExecute(Void result) {
listener.syncedTimelines(manageTimelines, position);
} }
} }

View File

@ -19,7 +19,8 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -40,12 +41,15 @@ import app.fedilab.android.sqlite.Sqlite;
* Manage the synchronization with the account and update the db * Manage the synchronization with the account and update the db
*/ */
public class UpdateAccountInfoAsyncTask extends AsyncTask<Void, Void, Void> { public class UpdateAccountInfoAsyncTask {
private String token, client_id, client_secret, refresh_token; private final String token;
private final String client_id;
private final String client_secret;
private final String refresh_token;
private final WeakReference<Context> contextReference;
private final SOCIAL social;
private String instance; private String instance;
private WeakReference<Context> contextReference;
private SOCIAL social;
public UpdateAccountInfoAsyncTask(Context context, String token, String client_id, String client_secret, String refresh_token, String instance, SOCIAL social) { public UpdateAccountInfoAsyncTask(Context context, String token, String client_id, String client_secret, String refresh_token, String instance, SOCIAL social) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -55,69 +59,69 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask<Void, Void, Void> {
this.client_id = client_id; this.client_id = client_id;
this.client_secret = client_secret; this.client_secret = client_secret;
this.refresh_token = refresh_token; this.refresh_token = refresh_token;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
Account account; Account account;
if (this.contextReference == null) { if (this.contextReference == null) {
return null; return;
} }
if (social == SOCIAL.MASTODON || social == SOCIAL.PIXELFED || social == SOCIAL.PLEROMA) { if (social == SOCIAL.MASTODON || social == SOCIAL.PIXELFED || social == SOCIAL.PLEROMA) {
account = new API(this.contextReference.get(), instance, null).verifyCredentials(); account = new API(this.contextReference.get(), instance, null).verifyCredentials();
InstanceNodeInfo info = new API(this.contextReference.get(), instance, token).displayNodeInfo(this.instance); InstanceNodeInfo info = new API(this.contextReference.get(), instance, token).displayNodeInfo(this.instance);
if (info != null && info.getName() != null && account != null) if (info != null && info.getName() != null && account != null)
account.setSocial(info.getName().toUpperCase()); account.setSocial(info.getName().toUpperCase());
} else if (social == SOCIAL.PEERTUBE) { } else if (social == SOCIAL.PEERTUBE) {
account = new PeertubeAPI(this.contextReference.get(), instance, token).verifyCredentials(); account = new PeertubeAPI(this.contextReference.get(), instance, token).verifyCredentials();
if (account != null) if (account != null)
account.setSocial("PEERTUBE"); account.setSocial("PEERTUBE");
} else { } else {
account = new GNUAPI(this.contextReference.get(), instance, token).verifyCredentials(); account = new GNUAPI(this.contextReference.get(), instance, token).verifyCredentials();
} }
if (account == null) if (account == null)
return null; return;
try { try {
//At the state the instance can be encoded //At the state the instance can be encoded
instance = URLDecoder.decode(instance, "utf-8"); instance = URLDecoder.decode(instance, "utf-8");
} catch (UnsupportedEncodingException ignored) { } catch (UnsupportedEncodingException ignored) {
} }
SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
account.setToken(token); account.setToken(token);
account.setClient_id(client_id); account.setClient_id(client_id);
account.setClient_secret(client_secret); account.setClient_secret(client_secret);
account.setRefresh_token(refresh_token); account.setRefresh_token(refresh_token);
account.setInstance(instance); account.setInstance(instance);
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
boolean userExists = new AccountDAO(this.contextReference.get(), db).userExist(account); boolean userExists = new AccountDAO(this.contextReference.get(), db).userExist(account);
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId()); editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putBoolean(Helper.PREF_IS_MODERATOR, account.isModerator()); editor.putBoolean(Helper.PREF_IS_MODERATOR, account.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin()); editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin());
editor.putString(Helper.PREF_INSTANCE, instance); editor.putString(Helper.PREF_INSTANCE, instance);
editor.apply(); editor.apply();
if (userExists) if (userExists)
new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account); new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account);
else { else {
if (account.getUsername() != null && account.getCreated_at() != null) if (account.getUsername() != null && account.getCreated_at() != null)
new AccountDAO(this.contextReference.get(), db).insertAccount(account); new AccountDAO(this.contextReference.get(), db).insertAccount(account);
} }
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
if (this.contextReference.get() != null) {
Intent mainActivity = new Intent(this.contextReference.get(), MainActivity.class);
mainActivity.putExtra(Helper.INTENT_ACTION, Helper.ADD_USER_INTENT);
this.contextReference.get().startActivity(mainActivity);
((Activity) this.contextReference.get()).finish();
}
};
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
if (this.contextReference.get() != null) {
Intent mainActivity = new Intent(this.contextReference.get(), MainActivity.class);
mainActivity.putExtra(Helper.INTENT_ACTION, Helper.ADD_USER_INTENT);
this.contextReference.get().startActivity(mainActivity);
((Activity) this.contextReference.get()).finish();
}
}
public enum SOCIAL { public enum SOCIAL {
MASTODON, MASTODON,

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -39,70 +40,67 @@ import static app.fedilab.android.activities.BaseMainActivity.social;
* Manage the synchronization with the authenticated account and update the db not * Manage the synchronization with the authenticated account and update the db not
*/ */
public class UpdateAccountInfoByIDAsyncTask extends AsyncTask<Void, Void, Void> { public class UpdateAccountInfoByIDAsyncTask {
private OnUpdateAccountInfoInterface listener; private final OnUpdateAccountInfoInterface listener;
private WeakReference<Context> contextReference; private final WeakReference<Context> contextReference;
private Account accountOld; private final Account accountOld;
public UpdateAccountInfoByIDAsyncTask(Context context, Account account, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface) { public UpdateAccountInfoByIDAsyncTask(Context context, Account account, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.listener = onUpdateAccountInfoInterface; this.listener = onUpdateAccountInfoInterface;
this.accountOld = account; this.accountOld = account;
doInBackground();
} }
@Override
protected Void doInBackground(Void... params) {
protected void doInBackground() {
Account account = null; new Thread(() -> {
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { Account account = null;
account = new API(this.contextReference.get()).verifyCredentials(); if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { account = new API(this.contextReference.get()).verifyCredentials();
account.setSocial("PIXELFED"); if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
account.setSocial("PIXELFED");
}
} else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
account = new PeertubeAPI(this.contextReference.get()).verifyCredentials();
account.setSocial("PEERTUBE");
} else if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
account = new GNUAPI(this.contextReference.get()).verifyCredentials();
} }
} else if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) { if (account == null)
account = new PeertubeAPI(this.contextReference.get()).verifyCredentials(); return;
account.setSocial("PEERTUBE"); account.setInstance(Helper.getLiveInstance(contextReference.get()));
} else if (social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) { SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
account = new GNUAPI(this.contextReference.get()).verifyCredentials(); if (accountOld != null) {
} account.setInstance(accountOld.getInstance());
if (account == null) account.setToken(accountOld.getToken());
return null; account.setRefresh_token(accountOld.getRefresh_token());
account.setInstance(Helper.getLiveInstance(contextReference.get())); account.setClient_id(accountOld.getClient_id());
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); account.setClient_secret(accountOld.getClient_secret());
if (accountOld != null) { new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account);
account.setInstance(accountOld.getInstance()); }
account.setToken(accountOld.getToken()); if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
account.setRefresh_token(accountOld.getRefresh_token()); new API(contextReference.get()).refreshToken(account);
account.setClient_id(accountOld.getClient_id()); }
account.setClient_secret(accountOld.getClient_secret()); if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account); try {
} APIResponse response = new API(contextReference.get()).getCustomEmoji();
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) { if (response != null && response.getEmojis() != null && response.getEmojis().size() > 0) {
new API(contextReference.get()).refreshToken(account); new CustomEmojiDAO(contextReference.get(), db).removeAll();
} for (Emojis emojis : response.getEmojis()) {
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) { if (emojis.isVisible_in_picker()) {
try { new CustomEmojiDAO(contextReference.get(), db).insertEmoji(emojis);
APIResponse response = new API(contextReference.get()).getCustomEmoji(); }
if (response != null && response.getEmojis() != null && response.getEmojis().size() > 0) {
new CustomEmojiDAO(contextReference.get(), db).removeAll();
for (Emojis emojis : response.getEmojis()) {
if (emojis.isVisible_in_picker()) {
new CustomEmojiDAO(contextReference.get(), db).insertEmoji(emojis);
} }
} }
} catch (Exception ignored) {
} }
} catch (Exception ignored) {
} }
} Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> listener.onUpdateAccountInfo(false);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onUpdateAccountInfo(false);
}
} }

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -31,16 +32,20 @@ import app.fedilab.android.interfaces.OnUpdateCredentialInterface;
* Update account credential * Update account credential
*/ */
public class UpdateCredentialAsyncTask extends AsyncTask<Void, Void, Void> { public class UpdateCredentialAsyncTask {
private String display_name, note, avatarName, headerName; private final String display_name;
private boolean senstive; private final String note;
private ByteArrayInputStream avatar, header; private final String avatarName;
private API.accountPrivacy privacy; private final String headerName;
private final boolean senstive;
private final ByteArrayInputStream avatar;
private final ByteArrayInputStream header;
private final API.accountPrivacy privacy;
private final OnUpdateCredentialInterface listener;
private final WeakReference<Context> contextReference;
private final HashMap<String, String> customFields;
private APIResponse apiResponse; private APIResponse apiResponse;
private OnUpdateCredentialInterface listener;
private WeakReference<Context> contextReference;
private HashMap<String, String> customFields;
public UpdateCredentialAsyncTask(Context context, HashMap<String, String> customFields, String display_name, String note, ByteArrayInputStream avatar, String avatarName, ByteArrayInputStream header, String headerName, API.accountPrivacy privacy, boolean senstive, OnUpdateCredentialInterface onUpdateCredentialInterface) { public UpdateCredentialAsyncTask(Context context, HashMap<String, String> customFields, String display_name, String note, ByteArrayInputStream avatar, String avatarName, ByteArrayInputStream header, String headerName, API.accountPrivacy privacy, boolean senstive, OnUpdateCredentialInterface onUpdateCredentialInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -54,17 +59,15 @@ public class UpdateCredentialAsyncTask extends AsyncTask<Void, Void, Void> {
this.headerName = headerName; this.headerName = headerName;
this.customFields = customFields; this.customFields = customFields;
this.senstive = senstive; this.senstive = senstive;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
apiResponse = new API(this.contextReference.get()).updateCredential(display_name, note, avatar, avatarName, header, headerName, privacy, customFields, senstive); apiResponse = new API(this.contextReference.get()).updateCredential(display_name, note, avatar, avatarName, header, headerName, privacy, customFields, senstive);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onUpdateCredential(apiResponse);
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onUpdateCredential(apiResponse);
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
@ -30,14 +31,15 @@ import app.fedilab.android.interfaces.OnRetrieveAttachmentInterface;
* Updates media description * Updates media description
*/ */
public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask<Void, Void, Void> { public class UpdateDescriptionAttachmentAsyncTask {
private OnRetrieveAttachmentInterface listener; private final OnRetrieveAttachmentInterface listener;
private final String mediaId;
private final String description;
private final Account account;
private final WeakReference<Context> contextReference;
private Attachment attachment; private Attachment attachment;
private String mediaId, description;
private Account account;
private API api; private API api;
private WeakReference<Context> contextReference;
public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, Account account, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface) { public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, Account account, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
@ -45,21 +47,19 @@ public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask<Void, Void,
this.description = description; this.description = description;
this.mediaId = mediaId; this.mediaId = mediaId;
this.account = account; this.account = account;
doInBackground();
} }
@Override protected void doInBackground() {
protected Void doInBackground(Void... params) { new Thread(() -> {
if (account == null) if (account == null)
api = new API(this.contextReference.get()); api = new API(this.contextReference.get());
else else
api = new API(this.contextReference.get(), account.getInstance(), account.getToken()); api = new API(this.contextReference.get(), account.getInstance(), account.getToken());
attachment = api.updateDescription(mediaId, description); attachment = api.updateDescription(mediaId, description);
return null; Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveAttachment(attachment, null, api.getError());
mainHandler.post(myRunnable);
}).start();
} }
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveAttachment(attachment, null, api.getError());
}
} }

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks; package app.fedilab.android.asynctasks;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask; import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@ -31,47 +32,46 @@ import app.fedilab.android.interfaces.OnRetrieveWhoToFollowInterface;
* Retrieves who to follow list * Retrieves who to follow list
*/ */
public class WhoToFollowAsyncTask extends AsyncTask<Void, Void, Void> { public class WhoToFollowAsyncTask {
private String name; private final String name;
private final OnRetrieveWhoToFollowInterface listener;
private final WeakReference<Context> contextReference;
private List<String> response; private List<String> response;
private OnRetrieveWhoToFollowInterface listener;
private WeakReference<Context> contextReference;
public WhoToFollowAsyncTask(Context context, String name, OnRetrieveWhoToFollowInterface onRetrieveWhoToFollowInterface) { public WhoToFollowAsyncTask(Context context, String name, OnRetrieveWhoToFollowInterface onRetrieveWhoToFollowInterface) {
this.contextReference = new WeakReference<>(context); this.contextReference = new WeakReference<>(context);
this.name = name; this.name = name;
this.listener = onRetrieveWhoToFollowInterface; this.listener = onRetrieveWhoToFollowInterface;
doInBackground();
} }
protected void doInBackground() {
@Override new Thread(() -> {
protected Void doInBackground(Void... params) { API api = new API(this.contextReference.get());
API api = new API(this.contextReference.get()); if (name != null)
if (name != null) response = api.getCommunitywikiList(name);
response = api.getCommunitywikiList(name); else
else response = api.getCommunitywikiList();
response = api.getCommunitywikiList(); Handler mainHandler = new Handler(Looper.getMainLooper());
return null; Runnable myRunnable = () -> {
} if (name == null)
listener.onRetrieveWhoToFollowList(response);
@Override else {
protected void onPostExecute(Void result) { List<TrunkAccount> trunkAccounts = null;
if (name == null) if (response != null) {
listener.onRetrieveWhoToFollowList(response); trunkAccounts = new ArrayList<>();
else { for (String res : response) {
List<TrunkAccount> trunkAccounts = null; TrunkAccount trunkAccount = new TrunkAccount();
if (response != null) { trunkAccount.setAcct(res);
trunkAccounts = new ArrayList<>(); trunkAccounts.add(trunkAccount);
for (String res : response) { }
TrunkAccount trunkAccount = new TrunkAccount(); }
trunkAccount.setAcct(res); listener.onRetrieveWhoToFollowAccount(trunkAccounts);
trunkAccounts.add(trunkAccount);
} }
} };
listener.onRetrieveWhoToFollowAccount(trunkAccounts); mainHandler.post(myRunnable);
} }).start();
} }
} }

View File

@ -113,7 +113,7 @@ public class API {
private Account account; private Account account;
private Context context; private final Context context;
private Results results; private Results results;
private Attachment attachment; private Attachment attachment;
private List<Account> accounts; private List<Account> accounts;
@ -1082,11 +1082,7 @@ public class API {
} catch (Exception e) { } catch (Exception e) {
status.setFavourited(false); status.setFavourited(false);
} }
if (resobj.has("bookmarked") && !resobj.isNull("bookmarked")) { status.setBookmarked(resobj.has("bookmarked") && !resobj.isNull("bookmarked"));
status.setBookmarked(true);
} else {
status.setBookmarked(false);
}
try { try {
resobj.getJSONObject("renoteId"); resobj.getJSONObject("renoteId");
if (!resobj.getJSONObject("renoteId").toString().equals("null")) if (!resobj.getJSONObject("renoteId").toString().equals("null"))

View File

@ -34,7 +34,7 @@ import app.fedilab.android.client.Entities.Error;
public class CustomSharing { public class CustomSharing {
private Context context; private final Context context;
private CustomSharingResponse customSharingResponse; private CustomSharingResponse customSharingResponse;
private Error CustomSharingError; private Error CustomSharingError;

View File

@ -69,7 +69,7 @@ public class GNUAPI {
private Account account; private Account account;
private Context context; private final Context context;
private List<Account> accounts; private List<Account> accounts;
private List<Status> statuses; private List<Status> statuses;
private int tootPerPage, accountPerPage, notificationPerPage; private int tootPerPage, accountPerPage, notificationPerPage;

View File

@ -22,8 +22,8 @@ import app.fedilab.android.helper.Helper;
public class CustomStreamFetcher implements DataFetcher<InputStream> { public class CustomStreamFetcher implements DataFetcher<InputStream> {
private GlideUrl url; private final GlideUrl url;
private WeakReference<Context> contextWeakReference; private final WeakReference<Context> contextWeakReference;
CustomStreamFetcher(Context context, GlideUrl url) { CustomStreamFetcher(Context context, GlideUrl url) {
this.contextWeakReference = new WeakReference<>(context); this.contextWeakReference = new WeakReference<>(context);

View File

@ -80,12 +80,12 @@ public class HttpsConnection {
private HttpsURLConnection httpsURLConnection; private HttpsURLConnection httpsURLConnection;
private HttpURLConnection httpURLConnection; private HttpURLConnection httpURLConnection;
private String since_id, max_id; private String since_id, max_id;
private Context context; private final Context context;
private int CHUNK_SIZE = 4096; private final int CHUNK_SIZE = 4096;
private SharedPreferences sharedpreferences; private final SharedPreferences sharedpreferences;
private Proxy proxy; private Proxy proxy;
private String instance; private final String instance;
private String USER_AGENT; private final String USER_AGENT;
public HttpsConnection(Context context, String instance) { public HttpsConnection(Context context, String instance) {
@ -1373,8 +1373,8 @@ public class HttpsConnection {
public class HttpsConnectionException extends Exception { public class HttpsConnectionException extends Exception {
private int statusCode; private final int statusCode;
private String message; private final String message;
HttpsConnectionException(int statusCode, String message) { HttpsConnectionException(int statusCode, String message) {
this.statusCode = statusCode; this.statusCode = statusCode;

View File

@ -65,7 +65,7 @@ public class PeertubeAPI {
private Account account; private Account account;
private Context context; private final Context context;
private int tootPerPage; private int tootPerPage;
private int actionCode; private int actionCode;
private String instance; private String instance;

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