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 RelativeLayout loader;
private ImageButton validate;
private DatePickerDialog.OnDateSetListener iniDateSetListener =
private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() {
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() {
public void onDateSet(DatePicker view, int year,
@ -256,7 +256,7 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
chart.setVisibility(View.GONE);
loader.setVisibility(View.VISIBLE);
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")
public static class CustomMarkerView extends MarkerView {
private TextView tvContent;
private final TextView tvContent;
private MPPointF mOffset;
public CustomMarkerView(Context context, int layoutResource) {
@ -423,8 +423,8 @@ public class OwnerChartsActivity extends BaseActivity implements OnRetrieveChart
}
public static class MyXAxisValueFormatter extends ValueFormatter {
private DateFormat mDataFormat;
private Date mDate;
private final DateFormat mDataFormat;
private final Date mDate;
MyXAxisValueFormatter() {
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 View statsDialogView;
private StatisticsNotification statistics;
private DatePickerDialog.OnDateSetListener iniDateSetListener =
private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() {
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() {
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
public void onReceive(Context context, Intent intent) {
max_id = null;
firstLoad = true;
flag_loading = 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(
c1, c2, c1
);
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).execute();
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this);
swipeRefreshLayout.setOnRefreshListener(() -> {
max_id = null;
firstLoad = true;
flag_loading = 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() {
@ -239,7 +239,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) {
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);
}
} else {
@ -288,7 +288,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
.setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss());
dialogBuilder.create().show();
if (statistics == null) {
new RetrieveNotificationStatsAsyncTask(OwnerNotificationActivity.this, OwnerNotificationActivity.this).execute();
new RetrieveNotificationStatsAsyncTask(OwnerNotificationActivity.this, OwnerNotificationActivity.this);
} else {
displayStats();
}
@ -375,7 +375,7 @@ public class OwnerNotificationActivity extends BaseActivity implements OnRetriev
firstLoad = true;
flag_loading = true;
swiped = true;
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this).execute();
new RetrieveNotificationsCacheAsyncTask(OwnerNotificationActivity.this, filterNotifications, null, OwnerNotificationActivity.this);
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 ImageButton validate;
private String status_id;
private DatePickerDialog.OnDateSetListener iniDateSetListener =
private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() {
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() {
public void onDateSet(DatePicker view, int year,
@ -472,7 +472,7 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
chart.setVisibility(View.GONE);
loader.setVisibility(View.VISIBLE);
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")
public static class CustomMarkerView extends MarkerView {
private TextView tvContent;
private final TextView tvContent;
private MPPointF mOffset;
public CustomMarkerView(Context context, int layoutResource) {
@ -510,8 +510,8 @@ public class OwnerNotificationChartsActivity extends BaseActivity implements OnR
}
public class MyXAxisValueFormatter extends ValueFormatter {
private DateFormat mDataFormat;
private Date mDate;
private final DateFormat mDataFormat;
private final Date mDate;
MyXAxisValueFormatter() {
if (status_id == null) {

View File

@ -105,7 +105,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
private Date dateIni, dateEnd;
private View statsDialogView;
private Statistics statistics;
private DatePickerDialog.OnDateSetListener iniDateSetListener =
private final DatePickerDialog.OnDateSetListener iniDateSetListener =
new DatePickerDialog.OnDateSetListener() {
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() {
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
public void onReceive(Context context, Intent intent) {
max_id = null;
firstLoad = true;
flag_loading = 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(
c1, c2, c1
);
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).execute();
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this);
swipeRefreshLayout.setOnRefreshListener(() -> {
max_id = null;
firstLoad = true;
flag_loading = 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() {
@ -248,7 +248,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) {
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);
}
} else {
@ -297,7 +297,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
.setPositiveButton(R.string.close, (dialog, which) -> dialog.dismiss());
dialogBuilder.create().show();
if (statistics == null) {
new RetrieveStatsAsyncTask(OwnerStatusActivity.this, OwnerStatusActivity.this).execute();
new RetrieveStatsAsyncTask(OwnerStatusActivity.this, OwnerStatusActivity.this);
} else {
displayStats();
}
@ -408,7 +408,7 @@ public class OwnerStatusActivity extends BaseActivity implements OnRetrieveFeeds
firstLoad = true;
flag_loading = true;
swiped = true;
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this).execute();
new RetrieveFeedsAsyncTask(OwnerStatusActivity.this, filterToots, null, OwnerStatusActivity.this);
dialog.dismiss();
})
.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());

View File

@ -71,7 +71,7 @@ public class StatusListAdapter extends BaseStatusListAdapter {
} else {
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);
emojiPopup.toggle();

View File

@ -207,11 +207,11 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
lv_ux.setAdapter(accountSearchWebAdapterUxUiDesigners);
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, "mmarif", "mastodon.social", AboutActivity.this).execute();
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "PhotonQyv", "mastodon.xyz", AboutActivity.this).execute();
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "angrytux", "social.tchncs.de", AboutActivity.this).execute();
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "guzzisti", "mastodon.social", AboutActivity.this).execute();
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "apps", "toot.fedilab.app", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "mmarif", "mastodon.social", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "PhotonQyv", "mastodon.xyz", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "angrytux", "social.tchncs.de", AboutActivity.this);
new RetrieveRemoteDataAsyncTask(AboutActivity.this, "guzzisti", "mastodon.social", AboutActivity.this);
} else {
SpannableString name = new SpannableString("@apps@toot.fedilab.app");
name.setSpan(new UnderlineSpan(), 0, name.length(), 0);
@ -272,7 +272,7 @@ public class AboutActivity extends BaseActivity implements OnRetrieveRemoteAccou
accountSearchWebAdapterContributors.notifyDataSetChanged();
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();
if (developers != null) {
for (Account account : developers) {
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this).execute();
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this);
}
}
if (contributors != null) {
for (Account account : contributors) {
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this).execute();
new RetrieveRelationshipAsyncTask(AboutActivity.this, account.getId(), AboutActivity.this);
}
}
if (uxuidesigners != null) {
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);
status.setVisibility(View.GONE);
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;
}
if (report != null) {
@ -156,7 +156,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
Group statuses_group = findViewById(R.id.statuses_group);
statuses_group.setVisibility(View.VISIBLE);
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 -> {
AdminAction adminAction = new AdminAction();
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 -> {
AdminAction adminAction = new AdminAction();
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 -> {
@ -240,7 +240,7 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
adminAction.setType(NONE);
adminAction.setSend_email_notification(email_user.isChecked());
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.setSend_email_notification(email_user.isChecked());
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 {
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.setSend_email_notification(email_user.isChecked());
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 {
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()) {
@ -288,9 +288,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
adminAction.setType(SUSPEND);
adminAction.setSend_email_notification(email_user.isChecked());
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 {
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 -> {
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 {
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()) {
@ -434,9 +434,9 @@ public class AccountReportActivity extends BaseActivity implements OnAdminAction
}
status.setOnClickListener(view -> {
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 {
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;
private static boolean notificationChecked = false;
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, Integer> tagItem = new HashMap<>();
private FloatingActionButton toot, delete_all, add_new;
private TextView toolbarTitle;
private SearchView toolbar_search;
private View headerLayout;
@ -312,7 +312,7 @@ public abstract class BaseMainActivity extends BaseActivity
//This task will allow to instance a static PeertubeInformation class
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
try {
new RetrievePeertubeInformationAsyncTask(BaseMainActivity.this).execute();
new RetrievePeertubeInformationAsyncTask(BaseMainActivity.this);
} catch (Exception ignored) {
}
}
@ -420,7 +420,7 @@ public abstract class BaseMainActivity extends BaseActivity
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) {
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) {
TabLayout.Tab pTabsub = tabLayout.newTab();
@ -709,7 +709,7 @@ public abstract class BaseMainActivity extends BaseActivity
int position = 0;
if (tabLayout != null)
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));
@ -974,7 +974,7 @@ public abstract class BaseMainActivity extends BaseActivity
}
return true;
case R.id.action_cache:
new Helper.CacheTask(BaseMainActivity.this).execute();
new Helper.CacheTask(BaseMainActivity.this);
return true;
case R.id.action_size:
final SharedPreferences sharedpreferences1 = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
@ -1259,7 +1259,7 @@ public abstract class BaseMainActivity extends BaseActivity
int versionCode = BuildConfig.VERSION_CODE;
if (lastReleaseNoteRead != versionCode) { //Need to push release notes
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(
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) {
// Retrieves instance
new RetrieveInstanceAsyncTask(BaseMainActivity.this, BaseMainActivity.this).execute();
new RetrieveInstanceAsyncTask(BaseMainActivity.this, BaseMainActivity.this);
// Retrieves filters
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)) {
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);
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
final Handler handler = new Handler();
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) {
String datesupdate = sharedpreferences.getString(Helper.TRACKING_LAST_UPDATE, null);
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) {
Helper.hideMenuItem(BaseMainActivity.this, navigationView.getMenu());
} 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) {
int position = 0;
boolean refreshList = extras.getBoolean(Helper.REFRESH_LIST_TIMELINE, false);
if (tabLayout != null)
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) {
String url = extras.getString(Helper.SEARCH_URL);
intent.replaceExtras(new Bundle());
@ -1488,7 +1488,7 @@ public abstract class BaseMainActivity extends BaseActivity
if (!isUrl)
return;
//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) {
if ("text/plain".equals(type)) {
@ -1513,7 +1513,7 @@ public abstract class BaseMainActivity extends BaseActivity
if (matchStart < matchEnd && sharedText.length() >= 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/")) {
@ -1575,7 +1575,7 @@ public abstract class BaseMainActivity extends BaseActivity
}
//Here we know that the intent contains a valid URL
if (!url.contains("medium.com")) {
new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this).execute();
new RetrieveRemoteDataAsyncTask(BaseMainActivity.this, url, BaseMainActivity.this);
} else {
forwardToBrowser(intent);
}
@ -2070,7 +2070,7 @@ public abstract class BaseMainActivity extends BaseActivity
if (accounts != null && accounts.size() > 0) {
developers = new ArrayList<>();
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.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
@ -45,6 +44,7 @@ import android.text.Html;
import android.text.InputType;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.util.Patterns;
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 SEND_VOICE_MESSAGE = 1423;
private static final int searchDeep = 15;
public static HashMap<String, Uri> filesMap;
public static boolean autocomplete;
public static Uri photoFileUri = null;
static boolean active = false;
private static final int searchDeep = 15;
private final int PICK_IMAGE = 56556;
private final int TAKE_PHOTO = 56532;
public long currentToId;
@ -399,7 +399,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount).execute();
new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount);
} else {
mt = tPattern.matcher(searchIn);
if (mt.matches()) {
@ -408,7 +408,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAsyncTask(context, search, true, listener).execute();
new RetrieveSearchAsyncTask(context, search, true, listener);
} else {
mt = ePattern.matcher(searchIn);
if (mt.matches()) {
@ -417,7 +417,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji).execute();
new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji);
} else {
toot_content.dismissDropDown();
}
@ -443,8 +443,8 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
ContentResolver cr = activity.getContentResolver();
String mime = cr.getType(inUri);
if ((mime == null || mime.toLowerCase().contains("image")) && isWM) {
String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT+account.getId()+account.getInstance(), null);
if( WMText == null || WMText.trim().length() == 0) {
String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT + account.getId() + account.getInstance(), null);
if (WMText == null || WMText.trim().length() == 0) {
WMText = "@" + account.getUsername() + "@" + account.getInstance();
}
float textSize = 15;
@ -452,16 +452,16 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
mPaint.setTextSize(textSize);
float width = mPaint.measureText(WMText, 0, WMText.length());
try {
Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver() , inUri);
Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), inUri);
int w = backgroundBitmap.getWidth();
int h = backgroundBitmap.getHeight();
float valx = (float)1.0 - ( (Helper.convertDpToPixel(width, activity) + 10) )/(float)w;
if( valx < 0 )
float valx = (float) 1.0 - ((Helper.convertDpToPixel(width, activity) + 10)) / (float) w;
if (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)
.setPositionX(valx)
.setPositionY(valy)
@ -478,11 +478,10 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
.getOutputImage();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
tempInput = new ByteArrayInputStream(bitmapdata);
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -494,7 +493,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
if (suffixPosition > 0) suffix = filename.substring(suffixPosition);
try {
File file;
if( tempInput == null) {
if (tempInput == null) {
tempInput = activity.getContentResolver().openInputStream(inUri);
}
if (fname.startsWith("fedilabins_")) {
@ -520,7 +519,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
uri = FileProvider.getUriForFile(activity,
"app.fedilab.lite.fileProvider",
file);
}else{
} else {
uri = FileProvider.getUriForFile(activity,
"app.fedilab.android.fileProvider",
file);
@ -821,20 +820,11 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
Intent intent;
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
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);
}
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(intent, PICK_IMAGE);
});
@ -850,20 +840,11 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
Intent intent;
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
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);
}
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(intent, PICK_IMAGE);
});
@ -1001,7 +982,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.lite.fileProvider",
photoFile);
}else{
} else {
photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.android.fileProvider",
photoFile);
@ -1089,7 +1070,7 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
uploadReceiver = new UploadServiceSingleBroadcastReceiver(BasePixelfedComposeActivity.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
@ -1170,92 +1151,91 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
style = R.style.Dialog;
}
switch (item.getItemId()) {
case android.R.id.home:
finish();
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
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;
case R.id.action_photo_camera:
dispatchTakePictureIntent();
return true;
case R.id.action_store:
storeToot(true, true);
return true;
case 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;
}
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(BasePixelfedComposeActivity.this, style);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(BasePixelfedComposeActivity.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(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);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.datetime_picker, new LinearLayout(BasePixelfedComposeActivity.this), false);
dialogBuilder.setView(dialogView);
final AlertDialog alertDialog = dialogBuilder.create();
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
hour,
minute);
final long[] time = {calendar.getTimeInMillis()};
final DatePicker datePicker = dialogView.findViewById(R.id.date_picker);
final TimePicker timePicker = dialogView.findViewById(R.id.time_picker);
if (android.text.format.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();
}
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);
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;
}
return super.onOptionsItemSelected(item);
}
@ -1277,17 +1257,17 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
toot.setContent(BasePixelfedComposeActivity.this, tootContent);
if (timestamp == null)
if (scheduledstatus == null)
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this).execute();
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this);
else {
toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date()));
scheduledstatus.setStatus(toot);
isScheduled = true;
new PostActionAsyncTask(BasePixelfedComposeActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BasePixelfedComposeActivity.this).execute();
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this).execute();
new PostActionAsyncTask(BasePixelfedComposeActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BasePixelfedComposeActivity.this);
new PostStatusAsyncTask(BasePixelfedComposeActivity.this, social, account, toot, BasePixelfedComposeActivity.this);
}
else {
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();
String userId = accountReply!=null?accountReply.getId():account.getId();
String instance = accountReply!=null?accountReply.getInstance():account.getInstance();
String userId = accountReply != null ? accountReply.getId() : account.getId();
String instance = accountReply != null ? accountReply.getInstance() : account.getInstance();
try {
if (currentToId == -1) {
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();
static class asyncPicture extends AsyncTask<Void, Void, Void> {
static class asyncPicture {
String commpressedFilePath = null;
WeakReference<Activity> activityWeakReference;
@ -1995,46 +1975,42 @@ public abstract class BasePixelfedComposeActivity extends BaseActivity implement
this.filename = filename;
this.pixelfedStory = pixelfedStory;
this.account = account;
}
@Override
protected void onPreExecute() {
if (uriFile == null) {
Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
error = true;
}
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.VISIBLE);
doInBackground();
}
@Override
protected Void doInBackground(Void... voids) {
if (error) {
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));
protected void doInBackground() {
new Thread(() -> {
if (error) {
return;
}
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);
}
commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
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);
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.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
@ -46,6 +45,7 @@ import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.util.Patterns;
import android.view.LayoutInflater;
@ -97,7 +97,6 @@ import com.github.irshulx.Editor;
import com.github.irshulx.EditorListener;
import com.github.irshulx.models.EditorTextStyle;
import com.watermark.androidwm_light.WatermarkBuilder;
import com.watermark.androidwm_light.bean.WatermarkImage;
import com.watermark.androidwm_light.bean.WatermarkText;
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 REQUEST_CAMERA_PERMISSION_RESULT = 1653;
public static final int SEND_VOICE_MESSAGE = 1423;
private static final int searchDeep = 15;
public static HashMap<String, Uri> filesMap;
public static boolean autocomplete;
public static Uri photoFileUri = null;
static boolean active = false;
private static String instance;
private static final int searchDeep = 15;
private final int PICK_IMAGE = 56556;
private final int TAKE_PHOTO = 56532;
public long currentToId;
@ -472,7 +471,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount).execute();
new RetrieveSearchAccountsAsyncTask(context, search, listenerAccount);
} else {
mt = tPattern.matcher(searchIn);
if (mt.matches()) {
@ -481,7 +480,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAsyncTask(context, search, true, listener).execute();
new RetrieveSearchAsyncTask(context, search, true, listener);
} else {
mt = ePattern.matcher(searchIn);
if (mt.matches()) {
@ -490,7 +489,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji).execute();
new RetrieveEmojiAsyncTask(context, shortcode, listenerEmoji);
} else {
toot_content.dismissDropDown();
}
@ -516,8 +515,8 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
ContentResolver cr = activity.getContentResolver();
String mime = cr.getType(inUri);
if ((mime == null || mime.toLowerCase().contains("image")) && isWM) {
String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT+account.getId()+account.getInstance(), null);
if( WMText == null || WMText.trim().length() == 0) {
String WMText = sharedpreferences.getString(Helper.SET_WATERMARK_TEXT + account.getId() + account.getInstance(), null);
if (WMText == null || WMText.trim().length() == 0) {
WMText = "@" + account.getUsername() + "@" + account.getInstance();
}
@ -526,15 +525,15 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
mPaint.setTextSize(textSize);
float width = mPaint.measureText(WMText, 0, WMText.length());
try {
Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver() , inUri);
Bitmap backgroundBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), inUri);
int w = backgroundBitmap.getWidth();
int h = backgroundBitmap.getHeight();
float valx = (float)1.0 - ( (Helper.convertDpToPixel(width, activity) + 10) )/(float)w;
if( valx < 0 )
float valx = (float) 1.0 - ((Helper.convertDpToPixel(width, activity) + 10)) / (float) w;
if (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)
.setPositionX(valx)
.setPositionY(valy)
@ -551,12 +550,11 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
.getOutputImage();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
tempInput = new ByteArrayInputStream(bitmapdata);
}
catch (Exception e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Uri uri;
@ -567,7 +565,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
if (suffixPosition > 0) suffix = filename.substring(suffixPosition);
try {
File file;
if( tempInput == null) {
if (tempInput == null) {
tempInput = activity.getContentResolver().openInputStream(inUri);
}
if (fname.startsWith("fedilabins_")) {
@ -593,7 +591,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
uri = FileProvider.getUriForFile(activity,
"app.fedilab.lite.fileProvider",
file);
}else{
} else {
uri = FileProvider.getUriForFile(activity,
"app.fedilab.android.fileProvider",
file);
@ -949,7 +947,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, search, BaseTootActivity.this).execute();
new RetrieveSearchAccountsAsyncTask(BaseTootActivity.this, search, BaseTootActivity.this);
} else {
mt = tPattern.matcher(searchIn);
if (mt.matches()) {
@ -958,7 +956,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAsyncTask(BaseTootActivity.this, search, true, BaseTootActivity.this).execute();
new RetrieveSearchAsyncTask(BaseTootActivity.this, search, true, BaseTootActivity.this);
} else {
mt = ePattern.matcher(searchIn);
if (mt.matches()) {
@ -967,7 +965,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
pp_progress.setVisibility(View.VISIBLE);
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);
}
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)
toot_it.setText(R.string.modify);
@ -1231,19 +1229,15 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
popup.getMenuInflater()
.inflate(R.menu.main_content_type, popup.getMenu());
popup.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
case R.id.action_plain_text:
contentType = "text/plain";
break;
case R.id.action_html:
contentType = "text/html";
break;
case R.id.action_markdown:
contentType = "text/markdown";
break;
case R.id.action_bbcode:
contentType = "text/bbcode";
break;
int itemId = item.getItemId();
if (itemId == R.id.action_plain_text) {
contentType = "text/plain";
} else if (itemId == R.id.action_html) {
contentType = "text/html";
} else if (itemId == R.id.action_markdown) {
contentType = "text/markdown";
} else if (itemId == R.id.action_bbcode) {
contentType = "text/bbcode";
}
popup.dismiss();
sendToot(null, contentType);
@ -1265,20 +1259,11 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
Intent intent;
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
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);
}
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
String[] mimetypes = {"image/*", "video/*", "audio/mpeg", "audio/opus", "audio/flac", "audio/wav", "audio/ogg"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(intent, PICK_IMAGE);
});
@ -1545,7 +1530,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.lite.fileProvider",
photoFile);
}else{
} else {
photoFileUri = FileProvider.getUriForFile(this,
"app.fedilab.android.fileProvider",
photoFile);
@ -1634,7 +1619,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
private void prepareUpload(Activity activity, android.net.Uri uri, String filename) {
UploadServiceSingleBroadcastReceiver uploadReceiver = new UploadServiceSingleBroadcastReceiver(BaseTootActivity.this);
uploadReceiver.register(this);
new asyncPicture(activity, account, social, uri, filename, uploadReceiver).execute();
new asyncPicture(activity, account, social, uri, filename, uploadReceiver);
}
@Override
@ -1721,271 +1706,270 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
style = R.style.Dialog;
}
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_view_reply:
AlertDialog.Builder alert = new AlertDialog.Builder(BaseTootActivity.this, style);
alert.setTitle(R.string.toot_reply_content_title);
final TextView input = new TextView(BaseTootActivity.this);
//Set the padding
input.setPadding(30, 30, 30, 30);
alert.setView(input);
String content = tootReply.getContent();
if (tootReply.getReblog() != null)
content = tootReply.getReblog().getContent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY));
else
input.setText(Html.fromHtml(content));
alert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss());
alert.setNegativeButton(R.string.accounts, (dialog, whichButton) -> {
new RetrieveAccountsForReplyAsyncTask(BaseTootActivity.this, tootReply.getReblog() != null ? tootReply.getReblog() : tootReply, BaseTootActivity.this).execute();
dialog.dismiss();
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
return true;
} else if (itemId == R.id.action_view_reply) {
AlertDialog.Builder alert = new AlertDialog.Builder(BaseTootActivity.this, style);
alert.setTitle(R.string.toot_reply_content_title);
final TextView input = new TextView(BaseTootActivity.this);
//Set the padding
input.setPadding(30, 30, 30, 30);
alert.setView(input);
String content = tootReply.getContent();
if (tootReply.getReblog() != null)
content = tootReply.getReblog().getContent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY));
else
input.setText(Html.fromHtml(content));
alert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss());
alert.setNegativeButton(R.string.accounts, (dialog, whichButton) -> {
new RetrieveAccountsForReplyAsyncTask(BaseTootActivity.this, tootReply.getReblog() != null ? tootReply.getReblog() : tootReply, BaseTootActivity.this);
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();
return true;
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();
case R.id.action_poll:
displayPollPopup();
return false;
case R.id.action_translate:
return actionTranslateClick();
case R.id.action_emoji:
if (emojis != null) {
emojis.clear();
emojis = null;
return true;
} else if (itemId == R.id.action_photo_camera) {
dispatchTakePictureIntent();
return true;
} else if (itemId == 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);
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();
return true;
case R.id.action_photo_camera:
dispatchTakePictureIntent();
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();
@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 {
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);
search_account.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_search, 0);
}
}
} 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();
} 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();
});
builderSingle.setAdapter(draftsListAdapter,
(dialog, which) -> {
int id = ids[which];
restoreToot(id);
dialog.dismiss();
});
builderSingle.show();
} catch (Exception e) {
Toasty.error(BaseTootActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
return true;
case R.id.action_schedule:
if (toot_content.getText().toString().trim().length() == 0) {
Toasty.error(BaseTootActivity.this, getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show();
return true;
} else if (itemId == R.id.action_store) {
storeToot(true, true);
return true;
} else if (itemId == R.id.action_tags) {
Intent intentTags = new Intent(BaseTootActivity.this, TagCacheActivity.class);
intentTags.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intentTags);
return true;
} else if (itemId == R.id.action_restore) {
AlertDialog.Builder builderSingle;
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;
}
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();
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();
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 -> {
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]);
builderSingle.setAdapter(draftsListAdapter,
(dialog, which) -> {
int id = ids[which];
restoreToot(id);
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();
builderSingle.show();
} catch (Exception e) {
Toasty.error(BaseTootActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
return true;
} else if (itemId == R.id.action_schedule) {
View dialogView;
LayoutInflater inflater;
if (toot_content.getText().toString().trim().length() == 0) {
Toasty.error(BaseTootActivity.this, getString(R.string.toot_error_no_content), Toast.LENGTH_LONG).show();
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) {
@ -2105,17 +2089,17 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
}
if (timestamp == null)
if (scheduledstatus == null)
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this).execute();
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this);
else {
toot.setScheduled_at(Helper.dateToString(scheduledstatus.getScheduled_date()));
scheduledstatus.setStatus(toot);
isScheduled = true;
new PostActionAsyncTask(BaseTootActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BaseTootActivity.this).execute();
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this).execute();
new PostActionAsyncTask(BaseTootActivity.this, API.StatusAction.DELETESCHEDULED, scheduledstatus, BaseTootActivity.this);
new PostStatusAsyncTask(BaseTootActivity.this, social, account, toot, BaseTootActivity.this);
}
else {
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());
}
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());
addBorder();
dialog.dismiss();
@ -2451,7 +2435,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
if (apiResponse.getStatuses() != null && apiResponse.getStatuses().size() > 0)
toot.setIn_reply_to_id(apiResponse.getStatuses().get(0).getId());
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;
}
@ -2490,7 +2474,7 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
} else
Toasty.success(BaseTootActivity.this, getString(R.string.toot_scheduled), Toast.LENGTH_LONG).show();
} 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();
}
toot_it.setEnabled(true);
@ -3535,8 +3519,8 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
toot.setIn_reply_to_id(tootReply.getId());
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
//TODO: insert should be done with connected account
String userId = accountReply!=null?accountReply.getId():account.getId();
String instance = accountReply!=null?accountReply.getInstance():account.getInstance();
String userId = accountReply != null ? accountReply.getId() : account.getId();
String instance = accountReply != null ? accountReply.getInstance() : account.getInstance();
try {
if (currentToId == -1) {
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();
static class asyncPicture extends AsyncTask<Void, Void, Void> {
static class asyncPicture {
private final Account account;
String commpressedFilePath;
WeakReference<Activity> activityWeakReference;
android.net.Uri uriFile;
@ -3736,7 +3721,6 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
UploadServiceSingleBroadcastReceiver uploadReceiver;
String filename;
UpdateAccountInfoAsyncTask.SOCIAL social;
private final Account account;
asyncPicture(Activity activity, Account account, UpdateAccountInfoAsyncTask.SOCIAL social, android.net.Uri uri, String filename, UploadServiceSingleBroadcastReceiver uploadReceiver) {
this.activityWeakReference = new WeakReference<>(activity);
@ -3745,10 +3729,6 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
this.filename = filename;
this.social = social;
this.account = account;
}
@Override
protected void onPreExecute() {
if (uriFile == null) {
Toasty.error(activityWeakReference.get(), activityWeakReference.get().getString(R.string.toast_error), Toast.LENGTH_SHORT).show();
error = true;
@ -3756,52 +3736,52 @@ public abstract class BaseTootActivity extends BaseActivity implements UploadSta
if (activityWeakReference.get().findViewById(R.id.compression_loader) != null) {
activityWeakReference.get().findViewById(R.id.compression_loader).setVisibility(View.VISIBLE);
}
doInBackground();
}
@Override
protected Void doInBackground(Void... voids) {
if (error) {
return null;
}
commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile);
return null;
protected void doInBackground() {
new Thread(() -> {
if (error) {
return;
}
commpressedFilePath = Helper.compressImagePath(activityWeakReference.get(), uriFile);
Handler mainHandler = new Handler(Looper.getMainLooper());
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);
textviewNoAction = findViewById(R.id.no_action);
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();
return true;
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;
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;
default:
return super.onOptionsItemSelected(item);
@ -215,7 +215,7 @@ public class BookmarkActivity extends BaseActivity implements OnRetrieveFeedsInt
lv_status.setAdapter(statusListAdapter);
statusListAdapter.notifyDataSetChanged();
textviewNoAction.setVisibility(View.VISIBLE);
new PostActionAsyncTask(BookmarkActivity.this, API.StatusAction.UNBOOKMARK).execute();
new PostActionAsyncTask(BookmarkActivity.this, API.StatusAction.UNBOOKMARK);
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}" +
"&source=${source}&id=${id}&description=${description}&keywords=${keywords}&creator=${creator}&thumbnailurl=${thumbnailurl}");
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_lock_account.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(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());
AlertDialog alertDialog = dialogBuilder.create();

View File

@ -130,7 +130,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf
statuses = new ArrayList<>();
firstLoad = 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;
mLayoutManager = new LinearLayoutManager(this);
@ -144,7 +144,7 @@ public class GroupActivity extends BaseActivity implements OnRetrieveFeedsInterf
if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) {
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);
}
@ -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<>();
firstLoad = 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;
mLayoutManager = new LinearLayoutManager(this);
@ -164,7 +164,7 @@ public class HashTagActivity extends BaseActivity implements OnRetrieveFeedsInte
if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) {
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);
}
@ -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);
loader.setVisibility(View.VISIBLE);
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 (!flag_loading) {
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);
}
} else {
@ -170,10 +170,10 @@ public class ListActivity extends BaseActivity implements OnListActionInterface
flag_loading = true;
swiped = true;
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);
dialogBuilder.setPositiveButton(R.string.validate, (dialog, id) -> {
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();
});
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.commit();
//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) {
e.printStackTrace();
}
@ -598,7 +598,7 @@ public class LoginActivity extends BaseActivity {
//Update the account with the token;
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 {
connectionButton.setEnabled(true);
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);
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() {
@ -119,7 +119,7 @@ public class ManageAccountsInListActivity extends BaseActivity implements OnList
@Override
public void afterTextChanged(Editable s) {
if (s != null && s.length() > 0) {
new ManageListsAsyncTask(ManageAccountsInListActivity.this, s.toString(), ManageAccountsInListActivity.this).execute();
new ManageListsAsyncTask(ManageAccountsInListActivity.this, s.toString(), ManageAccountsInListActivity.this);
} else {
lv_accounts_search.setVisibility(View.GONE);
lv_accounts_current.setVisibility(View.VISIBLE);

View File

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

View File

@ -20,7 +20,6 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
@ -76,7 +75,6 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
private final int PICK_IMPORT_INSTANCE = 5326;
private boolean flag_loading;
private AsyncTask<Void, Void, Void> asyncTask;
private DomainsListAdapter domainsListAdapter;
private String max_id;
private List<String> domains;
@ -141,7 +139,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
EditText add_domain = dialogView.findViewById(R.id.add_domain);
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}$")) {
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();
} else {
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 (!flag_loading) {
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);
}
} else {
@ -240,7 +238,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
firstLoad = true;
flag_loading = true;
swiped = true;
asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).execute();
new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this);
});
switch (theme) {
case Helper.THEME_LIGHT:
@ -263,7 +261,7 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
break;
}
asyncTask = new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this).execute();
new RetrieveDomainsAsyncTask(MutedInstanceActivity.this, max_id, MutedInstanceActivity.this);
setTitle(R.string.blocked_domains);
}
@ -271,8 +269,6 @@ public class MutedInstanceActivity extends BaseActivity implements OnRetrieveDom
@Override
public void onDestroy() {
super.onDestroy();
if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING)
asyncTask.cancel(true);
}
@Override

View File

@ -114,7 +114,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
lv_mastohost.setAdapter(mastohostAdapter);
new RetrieveRemoteDataAsyncTask(PartnerShipActivity.this, "mastohost", "mastodon.social", PartnerShipActivity.this).execute();
new RetrieveRemoteDataAsyncTask(PartnerShipActivity.this, "mastohost", "mastodon.social", PartnerShipActivity.this);
}
@Override
@ -142,7 +142,7 @@ public class PartnerShipActivity extends BaseActivity implements OnRetrieveRemot
mastohostAcct.add(account);
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();
if (mastohostAcct != null) {
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.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
@ -212,7 +213,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
send.setOnClickListener(v -> {
String comment = add_comment_write.getText().toString();
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_read.setVisibility(View.VISIBLE);
add_comment_write.setVisibility(View.GONE);
@ -303,10 +304,10 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
}
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() {
@ -361,52 +362,51 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_comment:
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
Toasty.info(PeertubeActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show();
new commentTask(new WeakReference<>(PeertubeActivity.this), peertube).execute();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
if (!peertube.isCommentsEnabled()) {
Toasty.info(PeertubeActivity.this, getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show();
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();
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
return true;
} else if (itemId == R.id.action_comment) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
Toasty.info(PeertubeActivity.this, getString(R.string.retrieve_remote_status), Toast.LENGTH_LONG).show();
new commentTask(new WeakReference<>(PeertubeActivity.this), peertube);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
if (!peertube.isCommentsEnabled()) {
Toasty.info(PeertubeActivity.this, getString(R.string.comment_no_allowed_peertube), Toast.LENGTH_LONG).show();
return true;
}
return true;
default:
return super.onOptionsItemSelected(item);
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);
dialog.dismiss();
}
});
builderInner.show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public FullScreenMediaController.fullscreen getFullscreen() {
@ -434,7 +434,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
peertube = apiResponse.getPeertubes().get(0);
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())) {
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());
} else {
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());
}
return false;
@ -486,7 +486,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
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)
write_comment_container.setVisibility(View.VISIBLE);
} else {
@ -512,13 +512,13 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
peertube_like_count.setOnClickListener(v -> {
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);
changeColor();
});
peertube_dislike_count.setOnClickListener(v -> {
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);
changeColor();
});
@ -777,7 +777,7 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
public void onPostAction(int statusCode, API.StatusAction statusAction, String userId, Error error) {
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 Peertube peertube;
@ -860,40 +860,42 @@ public class PeertubeActivity extends BaseActivity implements OnRetrievePeertube
commentTask(WeakReference<Context> contextReference, Peertube peertube) {
this.peertube = peertube;
this.contextReference = contextReference;
doInBackground();
}
@Override
protected app.fedilab.android.client.Entities.Status doInBackground(Void... voids) {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = null;
if (peertube != null) {
APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid());
if (search != null && search.getResults() != null) {
remoteStatuses = search.getResults().getStatuses();
protected void doInBackground() {
new Thread(() -> {
List<app.fedilab.android.client.Entities.Status> remoteStatuses = null;
if (peertube != null) {
APIResponse search = new API(contextReference.get()).search("https://" + peertube.getAccount().getHost() + "/videos/watch/" + peertube.getUuid());
if (search != null && search.getResults() != null) {
remoteStatuses = search.getResults().getStatuses();
}
}
}
if (remoteStatuses != null && remoteStatuses.size() > 0) {
return remoteStatuses.get(0);
} else {
return null;
}
app.fedilab.android.client.Entities.Status remoteStatuse = null;
if (remoteStatuses != null && remoteStatuses.size() > 0) {
remoteStatuse = remoteStatuses.get(0);
}
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 mabbas007.tagsedittext.TagsEditText;
import static android.os.AsyncTask.THREAD_POOL_EXECUTOR;
import static app.fedilab.android.asynctasks.RetrievePeertubeInformationAsyncTask.peertubeInformation;
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.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
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();
});
builderInner.show();
@ -237,7 +236,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
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<>();
@ -264,7 +263,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
peertube.setUpdate(false);
set_upload_submit.setEnabled(true);
} else {
new RetrievePeertubeChannelsAsyncTask(PeertubeEditUploadActivity.this, PeertubeEditUploadActivity.this).execute();
new RetrievePeertubeChannelsAsyncTask(PeertubeEditUploadActivity.this, PeertubeEditUploadActivity.this);
}
languageToSend = peertube.getLanguage();
@ -528,7 +527,7 @@ public class PeertubeEditUploadActivity extends BaseActivity implements OnRetrie
List<String> tags = p_video_tags.getTags();
peertube.setTags(tags);
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);

View File

@ -57,8 +57,6 @@ import app.fedilab.android.interfaces.OnPostStatusActionInterface;
import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
import es.dmoral.toasty.Toasty;
import static android.os.AsyncTask.THREAD_POOL_EXECUTOR;
/**
* Created by Thomas on 04/11/2019.
* 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);
EditText username = findViewById(R.id.username);
@ -143,7 +141,7 @@ public class PeertubeRegisterActivity extends BaseActivity implements OnRetrieve
accountCreation.setPassword(password.getText().toString().trim());
accountCreation.setPasswordConfirm(password_confirm.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);
video_title = findViewById(R.id.video_title);
new RetrievePeertubeChannelsAsyncTask(PeertubeUploadActivity.this, PeertubeUploadActivity.this).execute();
new RetrievePeertubeChannelsAsyncTask(PeertubeUploadActivity.this, PeertubeUploadActivity.this);
channels = new HashMap<>();
uploadReceiver = new UploadServiceSingleBroadcastReceiver(this);

View File

@ -160,7 +160,7 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) {
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);
}
} else {
@ -177,10 +177,10 @@ public class PlaylistsActivity extends BaseActivity implements OnPlaylistActionI
flag_loading = true;
swiped = true;
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;
case LIST:
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);
refresh_list = true;
break;

View File

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

View File

@ -22,7 +22,6 @@ import android.content.res.ColorStateList;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
@ -161,8 +160,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
private String accountId;
private boolean ischannel;
private ScheduledExecutorService scheduledExecutorService;
private AsyncTask<Void, Void, Void> accountAsync;
private AsyncTask<Void, Void, Void> retrieveRelationship;
private action doAction;
private API.StatusAction doActionAccount;
@ -206,7 +203,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
ischannel = b.getBoolean("ischannel", false);
peertubeAccount = b.getBoolean("peertubeaccount", false);
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);
@ -297,7 +294,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
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)) {
account_follow.setVisibility(View.GONE);
@ -306,7 +303,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
}
//TODO: add other software that supports identity proofs
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();
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.setMovementMethod(LinkMovementMethod.getInstance());
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())));
//noinspection ConstantConditions
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())));
//Allows to filter by long click
@ -687,28 +681,24 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
return false;
}
});
switch (item.getItemId()) {
case R.id.action_show_pinned:
showPinned = !showPinned;
break;
case R.id.action_show_media:
showMediaOnly = !showMediaOnly;
break;
case R.id.action_show_boosts:
show_boosts = !show_boosts;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(Helper.SHOW_ACCOUNT_BOOSTS, show_boosts);
editor.apply();
break;
case R.id.action_show_replies:
show_replies = !show_replies;
editor = sharedpreferences.edit();
editor.putBoolean(Helper.SHOW_ACCOUNT_REPLIES, show_replies);
editor.apply();
break;
int itemId = item.getItemId();
if (itemId == R.id.action_show_pinned) {
showPinned = !showPinned;
} else if (itemId == R.id.action_show_media) {
showMediaOnly = !showMediaOnly;
} else if (itemId == R.id.action_show_boosts) {
show_boosts = !show_boosts;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(Helper.SHOW_ACCOUNT_BOOSTS, show_boosts);
editor.apply();
} else if (itemId == R.id.action_show_replies) {
SharedPreferences.Editor editor;
show_replies = !show_replies;
editor = sharedpreferences.edit();
editor.putBoolean(Helper.SHOW_ACCOUNT_REPLIES, show_replies);
editor.apply();
}
if (tabLayout.getTabAt(0) != null)
//noinspection ConstantConditions
tabLayout.getTabAt(0).select();
PagerAdapter mPagerAdapter1 = new ScreenSlidePagerAdapter(getSupportFragmentManager());
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();
} else if (doAction == action.FOLLOW) {
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) {
boolean confirm_unfollow = sharedpreferences.getBoolean(Helper.SET_UNFOLLOW_VALIDATION, true);
if (confirm_unfollow) {
@ -770,18 +760,18 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
unfollowConfirm.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
unfollowConfirm.setPositiveButton(R.string.yes, (dialog, which) -> {
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();
});
unfollowConfirm.show();
} else {
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) {
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 -> {
@ -875,7 +865,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if (pins != null && pins.size() > 0) {
if (pins.get(0).isPinned()) {
this.statuses.addAll(pins);
//noinspection ConstantConditions
tabLayout.getTabAt(3).setText(getString(R.string.pins_cnt, pins.size()));
statusListAdapter.notifyDataSetChanged();
}
@ -1117,241 +1106,242 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
style = R.style.Dialog;
}
final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
switch (item.getItemId()) {
case R.id.action_follow_instance:
String finalInstanceName = splitAcct[1];
List<RemoteInstance> remoteInstances = new InstancesDAO(ShowAccountActivity.this, db).getInstanceByName(finalInstanceName);
if (remoteInstances != null && remoteInstances.size() > 0) {
Toasty.info(ShowAccountActivity.this, getString(R.string.toast_instance_already_added), 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);
int itemId = item.getItemId();
if (itemId == R.id.action_follow_instance) {
String finalInstanceName = splitAcct[1];
List<RemoteInstance> remoteInstances = new InstancesDAO(ShowAccountActivity.this, db).getInstanceByName(finalInstanceName);
if (remoteInstances != null && remoteInstances.size() > 0) {
Toasty.info(ShowAccountActivity.this, getString(R.string.toast_instance_already_added), 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);
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;
}
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);
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());
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;
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;
builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {
String listTitle = arrayAdapter.getItem(which);
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;
}
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;
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);
} else {
new ManageListsAsyncTask(ShowAccountActivity.this, ManageListsAsyncTask.action.ADD_USERS, new String[]{account.getId()}, list.getId(), null, ShowAccountActivity.this);
}
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();
return true;
case R.id.action_block:
builderSingle.show();
}
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);
if (relationship.isBlocking()) {
builderInner.setTitle(stringArrayConf[5]);
doActionAccount = API.StatusAction.UNBLOCK;
} else {
builderInner.setTitle(stringArrayConf[1]);
doActionAccount = API.StatusAction.BLOCK;
builderInner.setTitle(stringArrayConf[4]);
doActionAccount = API.StatusAction.UNMUTE;
} else {
builderInner = new AlertDialog.Builder(ShowAccountActivity.this, style);
builderInner.setTitle(stringArrayConf[0]);
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;
case 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));
break;
default:
return true;
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();
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.setPositiveButton(R.string.yes, (dialog, which) -> {
@ -1361,7 +1351,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
} else {
targetedId = account.getId();
}
new PostActionAsyncTask(ShowAccountActivity.this, doActionAccount, targetedId, ShowAccountActivity.this).execute();
new PostActionAsyncTask(ShowAccountActivity.this, doActionAccount, targetedId, ShowAccountActivity.this);
dialog.dismiss();
});
builderInner.show();
@ -1381,12 +1371,6 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdownNow();
}
if (accountAsync != null && !accountAsync.isCancelled()) {
accountAsync.cancel(true);
}
if (retrieveRelationship != null && !retrieveRelationship.isCancelled()) {
retrieveRelationship.cancel(true);
}
}
@Override
@ -1401,7 +1385,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
return;
}
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 {
Helper.manageMessageStatusCode(ShowAccountActivity.this, statusCode, statusAction);
}
@ -1415,7 +1399,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt
}
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
target = account.getAcct();
retrieveRelationship = new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, target, ShowAccountActivity.this).execute();
new RetrieveRelationshipAsyncTask(ShowAccountActivity.this, target, ShowAccountActivity.this);
}
@Override

View File

@ -238,7 +238,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetrieve
if (conversationId != null)
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.setOnRefreshListener(() -> {
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 ViewPager mPager;
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() {
@Override
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;
@Override

View File

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

View File

@ -187,7 +187,7 @@ public class WebviewConnectActivity extends BaseActivity {
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token);
editor.commit();
//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 (Exception ignored) {

View File

@ -105,7 +105,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
cal.add(Calendar.MINUTE, -5);
Date dateAllowed = cal.getTime();
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);
} else {
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) {
account.setAcct(val[0]);
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 {
Toasty.error(WhoToFollowActivity.this, getString(R.string.toast_impossible_to_follow), Toast.LENGTH_LONG).show();
follow_accounts.setEnabled(true);
@ -218,7 +218,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
followedId.add(userId);
if (followedId != null && followedId.size() >= toFollowdId.size()) {
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 {
Account account = new Account();
assert followedId != null;
@ -227,7 +227,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
if (val.length > 1) {
account.setAcct(val[0]);
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);
listId = lists.get(0).getId();
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<>();
} else if (accountListId != null) {
@ -262,7 +262,7 @@ public class WhoToFollowActivity extends BaseActivity implements OnRetrieveWhoTo
accountListId.add(followedId.get(accountListId.size()));
progess_action.setText(R.string.adding_account_list_trunk);
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -31,15 +32,14 @@ import app.fedilab.android.interfaces.OnPostStatusActionInterface;
* 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 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) {
this.contextReference = new WeakReference<>(context);
@ -47,22 +47,21 @@ public class CreateMastodonAccountAsyncTask extends AsyncTask<Void, Void, Void>
this.accountCreation = accountCreation;
this.instance = instance;
this.type = type;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (type == RetrieveInstanceRegAsyncTask.instanceType.MASTODON) {
apiResponse = new API(contextReference.get(), instance, null).createAccount(accountCreation);
} else {
apiResponse = new PeertubeAPI(contextReference.get(), instance, null).createAccount(accountCreation);
}
return null;
protected void doInBackground() {
new Thread(() -> {
if (type == RetrieveInstanceRegAsyncTask.instanceType.MASTODON) {
apiResponse = new API(contextReference.get(), instance, null).createAccount(accountCreation);
} else {
apiResponse = new PeertubeAPI(contextReference.get(), instance, null).createAccount(accountCreation);
}
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.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,28 +30,27 @@ import app.fedilab.android.interfaces.OnCustomSharingInterface;
* 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 OnCustomSharingInterface listener;
private WeakReference<Context> contextReference;
public CustomSharingAsyncTask(Context context, String encodedCustomSharingURL, OnCustomSharingInterface onCustomSharingInterface) {
this.contextReference = new WeakReference<>(context);
this.encodedCustomSharingURL = encodedCustomSharingURL;
this.listener = onCustomSharingInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
customSharingResponse = new CustomSharing(this.contextReference.get()).customShare(encodedCustomSharingURL);
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onCustomSharing(customSharingResponse);
protected void doInBackground() {
new Thread(() -> {
customSharingResponse = new CustomSharing(this.contextReference.get()).customShare(encodedCustomSharingURL);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onCustomSharing(customSharingResponse);
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -30,41 +31,41 @@ import app.fedilab.android.interfaces.OnFilterActionInterface;
* 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 int statusCode;
private action apiAction;
private WeakReference<Context> contextReference;
private Filters filter;
public ManageFiltersAsyncTask(Context context, action apiAction, Filters filter, OnFilterActionInterface onFilterActionInterface) {
contextReference = new WeakReference<>(context);
this.listener = onFilterActionInterface;
this.filter = filter;
this.apiAction = apiAction;
doInBackground();
}
@Override
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;
}
protected void doInBackground() {
@Override
protected void onPostExecute(Void result) {
listener.onActionDone(this.apiAction, apiResponse, statusCode);
new Thread(() -> {
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);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onActionDone(this.apiAction, apiResponse, statusCode);
mainHandler.post(myRunnable);
}).start();
}
public enum action {

View File

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

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -36,16 +37,16 @@ import app.fedilab.android.sqlite.Sqlite;
* 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 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) {
contextReference = new WeakReference<>(context);
@ -54,35 +55,37 @@ public class ManagePlaylistsAsyncTask extends AsyncTask<Void, Void, Void> {
this.max_id = max_id;
this.playlist = playlist;
this.videoId = videoId;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
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()));
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance);
if (apiAction == action.GET_PLAYLIST) {
apiResponse = new PeertubeAPI(contextReference.get()).getPlayists(account.getUsername());
} else if (apiAction == action.GET_LIST_VIDEOS) {
apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(), max_id, null);
} else if (apiAction == action.DELETE_PLAYLIST) {
statusCode = new PeertubeAPI(contextReference.get()).deletePlaylist(playlist.getId());
} else if (apiAction == action.ADD_VIDEOS) {
statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(), videoId);
} else if (apiAction == action.DELETE_VIDEOS) {
statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(), videoId);
} else if (apiAction == action.GET_PLAYLIST_FOR_VIDEO) {
apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistForVideo(videoId);
}
return null;
protected void doInBackground() {
new Thread(() -> {
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()));
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(contextReference.get(), db).getUniqAccount(userId, instance);
if (apiAction == action.GET_PLAYLIST) {
apiResponse = new PeertubeAPI(contextReference.get()).getPlayists(account.getUsername());
} else if (apiAction == action.GET_LIST_VIDEOS) {
apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistVideos(playlist.getId(), max_id, null);
} else if (apiAction == action.DELETE_PLAYLIST) {
statusCode = new PeertubeAPI(contextReference.get()).deletePlaylist(playlist.getId());
} else if (apiAction == action.ADD_VIDEOS) {
statusCode = new PeertubeAPI(contextReference.get()).addVideoPlaylist(playlist.getId(), videoId);
} else if (apiAction == action.DELETE_VIDEOS) {
statusCode = new PeertubeAPI(contextReference.get()).deleteVideoPlaylist(playlist.getId(), videoId);
} else if (apiAction == action.GET_PLAYLIST_FOR_VIDEO) {
apiResponse = new PeertubeAPI(contextReference.get()).getPlaylistForVideo(videoId);
}
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 {
GET_PLAYLIST,

View File

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

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
@ -41,17 +42,17 @@ import app.fedilab.android.sqlite.StatusCacheDAO;
* 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 API.StatusAction apiAction;
private String targetedId, targetedComment;
private String comment;
private app.fedilab.android.client.Entities.Status status;
private Account account, remoteAccount;
private app.fedilab.android.client.Entities.Status remoteStatus;
private WeakReference<Context> contextReference;
private boolean muteNotifications;
private Error error;
private StoredStatus storedStatus;
@ -61,6 +62,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onPostActionInterface;
this.apiAction = apiAction;
this.storedStatus = storedStatus;
doInBackground();
}
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.apiAction = apiAction;
this.targetedId = targetedId;
doInBackground();
}
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.targetedId = targetedId;
this.account = account;
doInBackground();
}
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.remoteStatus = remoteStatus;
this.account = account;
doInBackground();
}
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.remoteAccount = remoteAccount;
this.account = account;
doInBackground();
}
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.comment = comment;
this.status = status;
doInBackground();
}
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.targetedId = targetedId;
this.muteNotifications = muteNotifications;
doInBackground();
}
@ -119,6 +127,7 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.targetedId = targetedId;
this.comment = comment;
this.targetedComment = targetedComment;
doInBackground();
}
public PostActionAsyncTask(Context context, API.StatusAction unbookmark) {
@ -126,141 +135,139 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = null;
this.apiAction = unbookmark;
this.targetedId = null;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
protected void doInBackground() {
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) {
if (remoteStatus.getReblog().getUri().startsWith("http"))
uri = remoteStatus.getReblog().getUri();
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
new Thread(() -> {
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());
statusCode = api.postAction(apiAction, targetedId);
} else
statusCode = gnuapi.postAction(apiAction, targetedId);
error = gnuapi.getError();
}
return null;
}
if (remoteStatus != null) {
String uri;
@Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onPostAction(statusCode, apiAction, targetedId, error);
}
if (remoteStatus.getReblog() != null) {
if (remoteStatus.getReblog().getUri().startsWith("http"))
uri = remoteStatus.getReblog().getUri();
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -30,14 +31,14 @@ import app.fedilab.android.interfaces.OnAdminActionInterface;
* Makes actions for post admin calls
*/
public class PostAdminActionAsyncTask extends AsyncTask<Void, Void, Void> {
public class PostAdminActionAsyncTask {
private OnAdminActionInterface listener;
private API.adminAction action;
private String id;
private WeakReference<Context> contextReference;
private final OnAdminActionInterface listener;
private final API.adminAction action;
private final String id;
private final WeakReference<Context> contextReference;
private final AdminAction adminAction;
private APIResponse apiResponse;
private AdminAction adminAction;
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.id = id;
this.adminAction = adminAction;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
switch (action) {
case GET_ACCOUNTS:
case GET_ONE_ACCOUNT:
case GET_REPORTS:
case GET_ONE_REPORT:
apiResponse = new API(contextReference.get()).adminGet(action, id, adminAction);
break;
default:
apiResponse = new API(contextReference.get()).adminDo(action, id, adminAction);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onAdminAction(apiResponse);
protected void doInBackground() {
new Thread(() -> {
switch (action) {
case GET_ACCOUNTS:
case GET_ONE_ACCOUNT:
case GET_REPORTS:
case GET_ONE_REPORT:
apiResponse = new API(contextReference.get()).adminGet(action, id, adminAction);
break;
default:
apiResponse = new API(contextReference.get()).adminDo(action, id, adminAction);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onAdminAction(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
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
*/
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 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) {
this.contextReference = new WeakReference<>(context);
@ -54,84 +55,86 @@ public class PostStatusAsyncTask extends AsyncTask<Void, Void, Void> {
this.status = status;
this.account = account;
this.social = social;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
protected void doInBackground() {
boolean isconnected = Helper.isConnectedToInternet(contextReference.get(), Helper.getLiveInstance(contextReference.get()));
if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
if (isconnected) {
if (account == null) {
apiResponse = new API(this.contextReference.get()).postStatusAction(status);
new Thread(() -> {
boolean isconnected = Helper.isConnectedToInternet(contextReference.get(), Helper.getLiveInstance(contextReference.get()));
if (social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
if (isconnected) {
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 {
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 {
apiResponse = new APIResponse();
Error error = new Error();
error.setError(contextReference.get().getString(R.string.no_internet));
error.setStatusCode(-33);
apiResponse.setError(error);
}
} else {
if (isconnected) {
if (account == null) {
apiResponse = new GNUAPI(this.contextReference.get()).postStatusAction(status);
if (isconnected) {
if (account == null) {
apiResponse = new GNUAPI(this.contextReference.get()).postStatusAction(status);
} else {
apiResponse = new GNUAPI(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status);
}
} 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) {
apiResponse.setTargetedId(status.getIn_reply_to_id());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onPostStatusAction(apiResponse);
//Search for tag with upper cases to store them locally
Thread thread = new Thread() {
@Override
public void run() {
String content = status.getContent();
if (content != null && content.length() > 0) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Matcher matcher = Helper.hashtagPattern.matcher(content);
while (matcher.find()) {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
//Get cached tags
List<String> cachedTag = new TagsCacheDAO(contextReference.get(), db).getAll();
String tag = content.substring(matchStart, matchEnd);
tag = tag.replace("#", "");
if (cachedTag == null) {
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);
if (status.getIn_reply_to_id() != null) {
apiResponse.setTargetedId(status.getIn_reply_to_id());
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
listener.onPostStatusAction(apiResponse);
//Search for tag with upper cases to store them locally
Thread thread = new Thread() {
@Override
public void run() {
String content = status.getContent();
if (content != null && content.length() > 0) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Matcher matcher = Helper.hashtagPattern.matcher(content);
while (matcher.find()) {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
//Get cached tags
List<String> cachedTag = new TagsCacheDAO(contextReference.get(), db).getAll();
String tag = content.substring(matchStart, matchEnd);
tag = tag.replace("#", "");
if (cachedTag == null) {
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());
}
}
};
thread.start();
if (account != null) {
String key = account.getUsername() + "@" + account.getInstance();
Helper.sleeps.put(key, 30000);
Helper.startStreaming(contextReference.get());
}
};
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -33,42 +34,43 @@ import app.fedilab.android.interfaces.OnRetrieveAccountInterface;
* 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 OnRetrieveAccountInterface listener;
private Error error;
private WeakReference<Context> contextReference;
public RetrieveAccountAsyncTask(Context context, String targetedId, OnRetrieveAccountInterface onRetrieveAccountInterface) {
this.contextReference = new WeakReference<>(context);
this.targetedId = targetedId;
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 onPostExecute(Void result) {
listener.onRetrieveAccount(account, error);
protected void doInBackground() {
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -28,29 +29,29 @@ import app.fedilab.android.interfaces.OnRetrieveAccountInterface;
* 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 API api;
private WeakReference<Context> contextReference;
public RetrieveAccountInfoAsyncTask(Context context, OnRetrieveAccountInterface onRetrieveAccountInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveAccountInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
api = new API(this.contextReference.get());
account = api.verifyCredentials();
return null;
}
protected void doInBackground() {
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveAccount(account, api.getError());
new Thread(() -> {
api = new API(this.contextReference.get());
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -31,14 +32,14 @@ import app.fedilab.android.interfaces.OnRetrieveAccountsInterface;
* 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 String max_id;
private OnRetrieveAccountsInterface listener;
private String targetedId;
private WeakReference<Context> contextReference;
private String instance, name;
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.listener = onRetrieveAccountsInterface;
this.action = Type.CHANNELS;
doInBackground();
}
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.listener = onRetrieveAccountsInterface;
this.targetedId = targetedId;
doInBackground();
}
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.max_id = max_id;
this.listener = onRetrieveAccountsInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = null;
GNUAPI gnuapi = null;
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
api = new API(this.contextReference.get());
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:
protected void doInBackground() {
new Thread(() -> {
API api = null;
GNUAPI gnuapi = null;
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
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) {
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());
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;
apiResponse = api.getFavouritedBy(targetedId, max_id);
} else {
apiResponse = api.getPeertubeChannel(instance, name);
break;
case GROUPS:
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;
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);
apiResponse = gnuapi.getGroups(max_id);
break;
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveAccounts(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
public enum Type {

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@ -35,50 +36,55 @@ import app.fedilab.android.sqlite.Sqlite;
* 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 OnRetrieveAccountsReplyInterface listener;
private final app.fedilab.android.client.Entities.Status status;
private final OnRetrieveAccountsReplyInterface listener;
private final ArrayList<Account> accounts;
private final WeakReference<Context> contextReference;
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) {
this.contextReference = new WeakReference<>(context);
this.status = status;
this.listener = onRetrieveAccountsReplyInterface;
this.accounts = new ArrayList<>();
doInBackground();
}
@Override
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());
protected void doInBackground() {
//Retrieves the first toot
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());
new Thread(() -> {
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
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) {
for (app.fedilab.android.client.Entities.Status status : statusContext.getAncestors()) {
if (canBeAdded(status.getAccount().getAcct())) {
accounts.add(status.getAccount());
addedAccounts.add(status.getAccount().getAcct());
if (statusContext != null && statusContext.getAncestors().size() > 0) {
for (app.fedilab.android.client.Entities.Status status : statusContext.getAncestors()) {
if (canBeAdded(status.getAccount().getAcct())) {
accounts.add(status.getAccount());
addedAccounts.add(status.getAccount().getAcct());
}
}
}
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveAccountsReply(accounts);
mainHandler.post(myRunnable);
}).start();
}
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);
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.Date;
@ -32,35 +33,32 @@ import app.fedilab.android.sqlite.StatusCacheDAO;
* Creates charts for an account
*/
public class RetrieveChartsAsyncTask extends AsyncTask<Void, Void, Void> {
public class RetrieveChartsAsyncTask {
private OnRetrieveChartsInterface listener;
private WeakReference<Context> contextReference;
private final OnRetrieveChartsInterface listener;
private final WeakReference<Context> contextReference;
private final Date dateIni;
private final Date dateEnd;
private Charts charts;
private Date dateIni;
private Date dateEnd;
public RetrieveChartsAsyncTask(Context context, Date dateIni, Date dateEnd, OnRetrieveChartsInterface onRetrieveChartsInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveChartsInterface;
this.dateIni = dateIni;
this.dateEnd = dateEnd;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
charts = new StatusCacheDAO(contextReference.get(), db).getCharts(dateIni, dateEnd);
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onCharts(charts);
protected void doInBackground() {
new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
charts = new StatusCacheDAO(contextReference.get(), db).getCharts(dateIni, dateEnd);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onCharts(charts);
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,30 +30,29 @@ import app.fedilab.android.interfaces.OnRetrieveDomainsInterface;
* Retrieves blocked instance
*/
public class RetrieveDomainsAsyncTask extends AsyncTask<Void, Void, Void> {
public class RetrieveDomainsAsyncTask {
private OnRetrieveDomainsInterface listener;
private WeakReference<Context> contextReference;
private final OnRetrieveDomainsInterface listener;
private final WeakReference<Context> contextReference;
private final String max_id;
private APIResponse apiResponse;
private String max_id;
public RetrieveDomainsAsyncTask(Context context, String max_id, OnRetrieveDomainsInterface onRetrieveDomainsInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveDomainsInterface;
this.max_id = max_id;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getBlockedDomain(max_id);
return null;
}
protected void doInBackground() {
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveDomains(apiResponse);
new Thread(() -> {
API api = new API(this.contextReference.get());
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.List;
@ -32,30 +33,30 @@ import app.fedilab.android.sqlite.Sqlite;
* 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 OnRetrieveEmojiInterface listener;
private WeakReference<Context> contextReference;
public RetrieveEmojiAsyncTask(Context context, String shortcode, OnRetrieveEmojiInterface onRetrieveEmojiInterface) {
this.contextReference = new WeakReference<>(context);
this.shortcode = shortcode;
this.listener = onRetrieveEmojiInterface;
doInBackground();
}
@Override
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;
}
protected void doInBackground() {
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveSearchEmoji(emojis);
new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,32 +30,31 @@ import app.fedilab.android.interfaces.OnRetrieveFeedsAfterBookmarkInterface;
* 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 OnRetrieveFeedsAfterBookmarkInterface listener;
private WeakReference<Context> contextReference;
private String max_id;
private boolean fetchMore;
public RetrieveFeedsAfterBookmarkAsyncTask(Context context, String max_id, boolean fetchMore, OnRetrieveFeedsAfterBookmarkInterface onRetrieveFeedsAfterBookmarkInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveFeedsAfterBookmarkInterface;
this.max_id = max_id;
this.fetchMore = fetchMore;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getHomeTimeline(max_id);
apiResponse.setFetchmore(fetchMore);
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveFeedsAfterBookmark(apiResponse);
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
apiResponse = api.getHomeTimeline(max_id);
apiResponse.setFetchmore(fetchMore);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveFeedsAfterBookmark(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
}

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@ -47,25 +48,25 @@ import app.fedilab.android.sqlite.TimelinesDAO;
* 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 String max_id;
private OnRetrieveFeedsInterface listener;
private String targetedID;
private String tag;
private boolean showMediaOnly = false;
private boolean showPinned = false;
private boolean showReply = false;
private WeakReference<Context> contextReference;
private FilterToots filterToots;
private String instanceName, remoteInstance, name;
private int timelineId;
private String currentfilter;
private String social;
private boolean fromCahe;
public RetrieveFeedsAsyncTask(Context context, FilterToots filterToots, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context);
@ -74,6 +75,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface;
this.filterToots = filterToots;
this.fromCahe = false;
doInBackground();
}
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.listener = onRetrieveFeedsInterface;
this.fromCahe = false;
doInBackground();
}
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.listener = onRetrieveFeedsInterface;
this.fromCahe = fromCahe;
doInBackground();
}
@ -100,6 +104,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.listener = onRetrieveFeedsInterface;
this.instanceName = instanceName;
this.fromCahe = false;
doInBackground();
}
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.timelineId = timelineId;
this.fromCahe = false;
doInBackground();
}
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.showPinned = showPinned;
this.fromCahe = false;
doInBackground();
}
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.showReply = showReply;
this.fromCahe = false;
doInBackground();
}
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.tag = tag;
this.fromCahe = false;
doInBackground();
}
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.action = Type.REMOTE_INSTANCE;
this.fromCahe = false;
doInBackground();
}
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.remoteInstance = retrieveFeedsParam.getRemoteInstance();
this.fromCahe = false;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (action == null)
return null;
switch (action) {
case HOME:
if (this.fromCahe) {
apiResponse = api.getHomeTimelineCache(max_id);
} else {
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);
}
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (action != null) {
switch (action) {
case HOME:
if (this.fromCahe) {
apiResponse = api.getHomeTimelineCache(max_id);
} else {
apiResponse = api.getHomeTimeline(max_id);
}
}
} 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 {
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);
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);
}
}
}
} 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 {
statusesNew.addAll(statuses);
apiResponse = api.getPeertube(this.instanceName, max_id);
}
}
}
results.setStatuses(statusesNew);
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:
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);
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 {
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;
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);
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()));
}
}
} 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()));
}
}
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveFeeds(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveFeeds(apiResponse);
}
public enum Type {
HOME,

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,29 +30,29 @@ import app.fedilab.android.interfaces.OnRetrieveAccountsInterface;
* 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 String max_id;
private OnRetrieveAccountsInterface listener;
private WeakReference<Context> contextReference;
public RetrieveFollowRequestSentAsyncTask(Context context, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface) {
this.contextReference = new WeakReference<>(context);
this.max_id = max_id;
this.listener = onRetrieveAccountsInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
apiResponse = new API(this.contextReference.get()).getFollowRequest(max_id);
return null;
}
protected void doInBackground() {
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveAccounts(apiResponse);
new Thread(() -> {
apiResponse = new API(this.contextReference.get()).getFollowRequest(max_id);
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,29 +30,30 @@ import app.fedilab.android.interfaces.OnRetrieveHowToInterface;
* 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 OnRetrieveHowToInterface listener;
private WeakReference<Context> contextReference;
public RetrieveHowToAsyncTask(Context context, OnRetrieveHowToInterface onRetrieveHowToInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveHowToInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getHowTo();
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,31 +30,31 @@ import app.fedilab.android.interfaces.OnRetrieveIdentityProofInterface;
* 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 OnRetrieveIdentityProofInterface listener;
private WeakReference<Context> contextReference;
private String userId;
public RetrieveIdentityProofAsyncTask(Context context, String userId, OnRetrieveIdentityProofInterface onRetrieveHowToInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveHowToInterface;
this.userId = userId;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getIdentityProof(userId);
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
apiResponse = api.getIdentityProof(userId);
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,26 +30,27 @@ import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
* 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 WeakReference<Context> contextReference;
public RetrieveInstanceAsyncTask(Context context, OnRetrieveInstanceInterface onRetrieveInstanceInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveInstanceInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
apiResponse = new API(this.contextReference.get()).getInstance();
return null;
protected void doInBackground() {
new Thread(() -> {
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -30,34 +31,33 @@ import app.fedilab.android.interfaces.OnRetrieveInstanceInterface;
* 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 WeakReference<Context> contextReference;
private String category;
private instanceType type;
public RetrieveInstanceRegAsyncTask(Context context, instanceType type, String category, OnRetrieveInstanceInterface onRetrieveInstanceInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveInstanceInterface;
this.category = category;
this.type = type;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (type == instanceType.MASTODON) {
apiResponse = new API(this.contextReference.get()).getInstanceReg(category);
} else if (type == instanceType.PEERTUBE) {
apiResponse = new PeertubeAPI(this.contextReference.get()).getInstanceReg();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveInstance(apiResponse);
protected void doInBackground() {
new Thread(() -> {
if (type == instanceType.MASTODON) {
apiResponse = new API(this.contextReference.get()).getInstanceReg(category);
} else if (type == instanceType.PEERTUBE) {
apiResponse = new PeertubeAPI(this.contextReference.get()).getInstanceReg();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveInstance(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
public enum instanceType {

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.List;
@ -32,32 +33,32 @@ import app.fedilab.android.interfaces.OnRetrieveManyRelationshipsInterface;
* 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 OnRetrieveManyRelationshipsInterface listener;
private final List<Account> accounts;
private final OnRetrieveManyRelationshipsInterface listener;
private final WeakReference<Context> contextReference;
private APIResponse apiResponse;
private WeakReference<Context> contextReference;
public RetrieveManyRelationshipsAsyncTask(Context context, List<Account> accounts, OnRetrieveManyRelationshipsInterface onRetrieveManyRelationshipsInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveManyRelationshipsInterface;
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 onPostExecute(Void result) {
listener.onRetrieveRelationship(apiResponse);
protected void doInBackground() {
new Thread(() -> {
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.util.Patterns;
@ -28,7 +29,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import app.fedilab.android.client.HttpsConnection;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnRetrieveMetaDataInterface;
@ -37,14 +37,18 @@ import app.fedilab.android.interfaces.OnRetrieveMetaDataInterface;
* 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 boolean error = false;
private String image, title, description, sharedSubject, sharedText;
private WeakReference<Context> contextWeakReference;
private boolean shouldFetchMetaData;
private String image;
private String title;
private String description;
public RetrieveMetaDataAsyncTask(Context context, boolean shouldFetchMetaData, String sharedSubject, String sharedText, String url, OnRetrieveMetaDataInterface onRetrieveRemoteAccountInterface) {
this.url = url;
@ -53,32 +57,33 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask<Void, Void, Void> {
this.sharedSubject = sharedSubject;
this.contextWeakReference = new WeakReference<>(context);
this.shouldFetchMetaData = shouldFetchMetaData;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (shouldFetchMetaData)
return execRetrieveMetaDataInBackground();
else
return null;
protected void doInBackground() {
new Thread(() -> {
if (shouldFetchMetaData) {
execRetrieveMetaDataInBackground();
}
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 = "";
if (url == null) {
error = true;
return null;
return;
}
try {
Matcher matcher;
if (url.startsWith("www."))
url = "http://" + url;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
matcher = Patterns.WEB_URL.matcher(url);
else
matcher = Helper.urlPattern.matcher(url);
matcher = Patterns.WEB_URL.matcher(url);
while (matcher.find()) {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
@ -122,12 +127,7 @@ public class RetrieveMetaDataAsyncTask extends AsyncTask<Void, Void, Void> {
} catch (IOException | IndexOutOfBoundsException e) {
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@ -41,13 +42,13 @@ import app.fedilab.android.sqlite.TimelinesDAO;
* Retrieves missing toots since last pause
*/
public class RetrieveMissingFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
public class RetrieveMissingFeedsAsyncTask {
private String since_id;
private OnRetrieveMissingFeedsInterface listener;
private List<app.fedilab.android.client.Entities.Status> statuses = new ArrayList<>();
private RetrieveFeedsAsyncTask.Type type;
private WeakReference<Context> contextReference;
private final String since_id;
private final OnRetrieveMissingFeedsInterface listener;
private final List<app.fedilab.android.client.Entities.Status> statuses = new ArrayList<>();
private final RetrieveFeedsAsyncTask.Type type;
private final WeakReference<Context> contextReference;
private String remoteInstance;
private int timelineId;
@ -56,6 +57,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask<Void, Void, Void> {
this.since_id = since_id;
this.listener = onRetrieveMissingFeedsInterface;
this.type = type;
doInBackground();
}
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.type = type;
this.remoteInstance = remoteInstance;
doInBackground();
}
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.type = type;
this.timelineId = timelineId;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (this.contextReference.get() == null)
return null;
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api = new API(this.contextReference.get());
List<app.fedilab.android.client.Entities.Status> tempStatus = null;
APIResponse apiResponse = null;
if (type == RetrieveFeedsAsyncTask.Type.HOME) {
apiResponse = api.getHomeTimelineSinceId(since_id);
} else if (type == RetrieveFeedsAsyncTask.Type.DIRECT)
apiResponse = api.getDirectTimelineSinceId(since_id);
else if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION)
apiResponse = api.getConversationTimelineSinceId(since_id);
else if (type == RetrieveFeedsAsyncTask.Type.LOCAL)
apiResponse = api.getPublicTimelineSinceId(true, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC)
apiResponse = api.getPublicTimelineSinceId(false, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE)
apiResponse = api.getInstanceTimelineSinceId(remoteInstance, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.TAG) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId);
if (manageTimelines != null && manageTimelines.getTagTimeline() != null) {
TagTimeline tagTimeline = manageTimelines.getTagTimeline();
boolean isArt = tagTimeline.isART();
if (isArt)
apiResponse = api.getCustomArtTimelineSinceId(false, manageTimelines.getTagTimeline().getName(), since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone());
else
apiResponse = api.getPublicTimelineTagSinceId(manageTimelines.getTagTimeline().getName(), false, since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone());
}
} else if (type == RetrieveFeedsAsyncTask.Type.ART)
apiResponse = api.getArtTimelineSinceId(false, since_id, null, null, null);
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);
protected void doInBackground() {
new Thread(() -> {
if (this.contextReference.get() == null) {
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveMissingFeeds(statuses);
mainHandler.post(myRunnable);
return;
}
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api = new API(this.contextReference.get());
List<app.fedilab.android.client.Entities.Status> tempStatus = null;
APIResponse apiResponse = null;
if (type == RetrieveFeedsAsyncTask.Type.HOME) {
apiResponse = api.getHomeTimelineSinceId(since_id);
} else if (type == RetrieveFeedsAsyncTask.Type.DIRECT)
apiResponse = api.getDirectTimelineSinceId(since_id);
else if (type == RetrieveFeedsAsyncTask.Type.CONVERSATION)
apiResponse = api.getConversationTimelineSinceId(since_id);
else if (type == RetrieveFeedsAsyncTask.Type.LOCAL)
apiResponse = api.getPublicTimelineSinceId(true, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.PUBLIC)
apiResponse = api.getPublicTimelineSinceId(false, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.REMOTE_INSTANCE)
apiResponse = api.getInstanceTimelineSinceId(remoteInstance, since_id);
else if (type == RetrieveFeedsAsyncTask.Type.TAG) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
ManageTimelines manageTimelines = new TimelinesDAO(contextReference.get(), db).getById(timelineId);
if (manageTimelines != null && manageTimelines.getTagTimeline() != null) {
TagTimeline tagTimeline = manageTimelines.getTagTimeline();
boolean isArt = tagTimeline.isART();
if (isArt)
apiResponse = api.getCustomArtTimelineSinceId(false, manageTimelines.getTagTimeline().getName(), since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone());
else
apiResponse = api.getPublicTimelineTagSinceId(manageTimelines.getTagTimeline().getName(), false, since_id, tagTimeline.getAny(), tagTimeline.getAll(), tagTimeline.getNone());
}
} else if (type == RetrieveFeedsAsyncTask.Type.ART)
apiResponse = api.getArtTimelineSinceId(false, since_id, null, null, null);
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 (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 (tempStatus != null)
statuses.addAll(0, tempStatus);
}
}
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 (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 (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);
}
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.List;
@ -34,14 +35,14 @@ import app.fedilab.android.interfaces.OnRetrieveMissingNotificationsInterface;
* 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 OnRetrieveMissingNotificationsInterface listener;
private WeakReference<Context> contextReference;
private List<Notification> notifications;
private DisplayNotificationsFragment.Type type;
private Error error;
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.listener = onRetrieveMissingNotifications;
this.type = type;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
APIResponse apiResponse = api.getNotificationsSince(type, since_id, 40, false);
if (apiResponse == null) {
error = new Error();
error.setError("");
return null;
}
error = apiResponse.getError();
since_id = apiResponse.getSince_id();
notifications = apiResponse.getNotifications();
if (notifications != null && notifications.size() > 0) {
MainActivity.lastNotificationId = notifications.get(0).getId();
}
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
APIResponse apiResponse = api.getNotificationsSince(type, since_id, 40, false);
if (apiResponse == null) {
error = new Error();
error.setError("");
return;
}
error = apiResponse.getError();
since_id = apiResponse.getSince_id();
notifications = apiResponse.getNotifications();
if (notifications != null && notifications.size() > 0) {
MainActivity.lastNotificationId = notifications.get(0).getId();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.Date;
@ -32,15 +33,15 @@ import app.fedilab.android.sqlite.Sqlite;
* Creates charts for notifications of an account
*/
public class RetrieveNotificationChartsAsyncTask extends AsyncTask<Void, Void, Void> {
public class RetrieveNotificationChartsAsyncTask {
private OnRetrieveNotificationChartsInterface listener;
private WeakReference<Context> contextReference;
private final OnRetrieveNotificationChartsInterface listener;
private final WeakReference<Context> contextReference;
private final Date dateIni;
private final Date dateEnd;
private final String status_id;
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) {
this.contextReference = new WeakReference<>(context);
@ -48,21 +49,18 @@ public class RetrieveNotificationChartsAsyncTask extends AsyncTask<Void, Void, V
this.dateIni = dateIni;
this.dateEnd = dateEnd;
this.status_id = status_id;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
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);
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onCharts(charts);
protected void doInBackground() {
new Thread(() -> {
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);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onCharts(charts);
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -34,17 +35,17 @@ import app.fedilab.android.interfaces.OnRetrieveNotificationsInterface;
* 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 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) {
this.contextReference = new WeakReference<>(context);
@ -54,44 +55,41 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask<Void, Void, Void>
this.refreshData = true;
this.display = display;
this.type = type;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api;
if (account == null) {
api = new API(this.contextReference.get());
apiResponse = api.getNotifications(type, max_id, display);
} else {
if (this.contextReference.get() == null) {
apiResponse.setError(new Error());
return null;
protected void doInBackground() {
new Thread(() -> {
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
API api;
if (account == null) {
api = new API(this.contextReference.get());
apiResponse = api.getNotifications(type, max_id, display);
} else {
if (this.contextReference.get() == null) {
apiResponse.setError(new Error());
return;
}
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 {
if (this.contextReference.get() == null) {
apiResponse.setError(new Error());
return null;
GNUAPI gnuapi;
if (account == 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);
}
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.List;
@ -34,42 +35,41 @@ import app.fedilab.android.sqlite.Sqlite;
* 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 String max_id;
private OnRetrieveCacheNotificationsInterface listener;
private WeakReference<Context> contextReference;
private FilterNotifications filterNotifications;
public RetrieveNotificationsCacheAsyncTask(Context context, FilterNotifications filterNotifications, String max_id, OnRetrieveCacheNotificationsInterface onRetrieveNotificationsInterface) {
this.contextReference = new WeakReference<>(context);
this.max_id = max_id;
this.listener = onRetrieveNotificationsInterface;
this.filterNotifications = filterNotifications;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
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);
apiResponse = new APIResponse();
apiResponse.setNotifications(notifications);
if (notifications != null && notifications.size() > 0) {
for (Notification notification : notifications) {
if (notification.getStatus() != null) {
app.fedilab.android.client.Entities.Status.fillSpan(contextReference, notification.getStatus());
protected void doInBackground() {
new Thread(() -> {
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);
apiResponse = new APIResponse();
apiResponse.setNotifications(notifications);
if (notifications != null && notifications.size() > 0) {
for (Notification notification : notifications) {
if (notification.getStatus() != null) {
app.fedilab.android.client.Entities.Status.fillSpan(contextReference, notification.getStatus());
}
}
apiResponse.setMax_id(notifications.get(notifications.size() - 1).getId());
}
apiResponse.setMax_id(notifications.get(notifications.size() - 1).getId());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveNotifications(apiResponse);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveNotifications(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
}

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -35,33 +36,33 @@ import app.fedilab.android.sqlite.Sqlite;
* 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 OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
public RetrievePeertubeChannelsAsyncTask(Context context, OnRetrievePeertubeInterface onRetrievePeertubeInterface) {
this.contextReference = new WeakReference<>(context);
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 onPostExecute(Void result) {
listener.onRetrievePeertubeChannels(apiResponse);
protected void doInBackground() {
new Thread(() -> {
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;
import android.content.Context;
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
@ -29,29 +28,27 @@ import app.fedilab.android.client.PeertubeAPI;
* Retrieves peertube informations
*/
public class RetrievePeertubeInformationAsyncTask extends AsyncTask<Void, Void, Void> {
public class RetrievePeertubeInformationAsyncTask {
public static PeertubeInformation peertubeInformation;
private WeakReference<Context> contextReference;
private final WeakReference<Context> contextReference;
public RetrievePeertubeInformationAsyncTask(Context context) {
this.contextReference = new WeakReference<>(context);
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
try {
peertubeInformation = peertubeAPI.getPeertubeInformation();
} catch (HttpsConnection.HttpsConnectionException e) {
e.printStackTrace();
}
return null;
protected void doInBackground() {
new Thread(() -> {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
try {
peertubeInformation = peertubeAPI.getPeertubeInformation();
} catch (HttpsConnection.HttpsConnectionException e) {
e.printStackTrace();
}
}).start();
}
@Override
protected void onPostExecute(Void result) {
}
}

View File

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

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,31 +30,31 @@ import app.fedilab.android.interfaces.OnRetrieveFeedsInterface;
* 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 OnRetrieveFeedsInterface listener;
private WeakReference<Context> contextReference;
public RetrievePeertubeSearchAsyncTask(Context context, String instance, String query, OnRetrieveFeedsInterface onRetrieveFeedsInterface) {
this.contextReference = new WeakReference<>(context);
this.query = query;
this.listener = onRetrieveFeedsInterface;
this.instance = instance;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.searchPeertube(instance, query);
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
apiResponse = api.searchPeertube(instance, query);
Handler mainHandler = new Handler(Looper.getMainLooper());
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.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -33,14 +34,14 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface;
* 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 String videoId;
private OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
private String instanceName;
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.listener = onRetrievePeertubeInterface;
this.instanceName = instanceName;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
API api = new API(this.contextReference.get());
apiResponse = api.getSinglePeertube(this.instanceName, videoId);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
apiResponse = peertubeAPI.getSinglePeertube(this.instanceName, videoId, token);
if (apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0 && apiResponse.getPeertubes().get(0) != null) {
String rate = new PeertubeAPI(this.contextReference.get()).getRating(videoId);
if (rate != null)
apiResponse.getPeertubes().get(0).setMyRating(rate);
protected void doInBackground() {
new Thread(() -> {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
API api = new API(this.contextReference.get());
apiResponse = api.getSinglePeertube(this.instanceName, videoId);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
PeertubeAPI peertubeAPI = new PeertubeAPI(this.contextReference.get());
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
apiResponse = peertubeAPI.getSinglePeertube(this.instanceName, videoId, token);
if (apiResponse.getPeertubes() != null && apiResponse.getPeertubes().size() > 0 && apiResponse.getPeertubes().get(0) != null) {
String rate = new PeertubeAPI(this.contextReference.get()).getRating(videoId);
if (rate != null)
apiResponse.getPeertubes().get(0).setMyRating(rate);
}
}
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -29,14 +30,14 @@ import app.fedilab.android.interfaces.OnRetrievePeertubeInterface;
* 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 String videoId;
private OnRetrievePeertubeInterface listener;
private WeakReference<Context> contextReference;
private String instanceName;
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.listener = onRetrievePeertubeInterface;
this.instanceName = instanceName;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
apiResponse = api.getSinglePeertubeComments(this.instanceName, videoId);
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
apiResponse = api.getSinglePeertubeComments(this.instanceName, videoId);
Handler mainHandler = new Handler(Looper.getMainLooper());
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -32,44 +33,42 @@ import app.fedilab.android.interfaces.OnRetrieveRelationshipInterface;
* 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 OnRetrieveRelationshipInterface listener;
private Error error;
private WeakReference<Context> contextReference;
public RetrieveRelationshipAsyncTask(Context context, String accountId, OnRetrieveRelationshipInterface onRetrieveRelationshipInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveRelationshipInterface;
this.accountId = accountId;
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());
relationship = api.getRelationship(accountId);
error = api.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
relationship = gnuapi.getRelationship(accountId);
error = gnuapi.getError();
} else {
PeertubeAPI api = new PeertubeAPI(this.contextReference.get());
relationship = new Relationship();
relationship.setFollowing(api.isFollowing(accountId));
error = api.getError();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveRelationship(relationship, error);
protected void doInBackground() {
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());
relationship = api.getRelationship(accountId);
error = api.getError();
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
relationship = gnuapi.getRelationship(accountId);
error = gnuapi.getError();
} else {
PeertubeAPI api = new PeertubeAPI(this.contextReference.get());
relationship = new Relationship();
relationship.setFollowing(api.isFollowing(accountId));
error = api.getError();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveRelationship(relationship, error);
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

@ -15,7 +15,8 @@
package app.fedilab.android.asynctasks;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
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 String url;
private Results results;
private final WeakReference<Context> contextReference;
private Results results;
private boolean developerAccount = false;
@ -47,32 +48,32 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask<Void, Void, Void> {
developerAccount = true;
this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context);
doInBackground();
}
public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) {
this.url = Helper.instanceWithProtocol(context, instance) + "/@" + username;
this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context);
doInBackground();
}
public RetrieveRemoteDataAsyncTask(Context context, String url, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface) {
this.url = url;
this.listener = onRetrieveRemoteAccountInterface;
this.contextReference = new WeakReference<>(context);
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
APIResponse apiResponse = api.search(this.url);
if (apiResponse.getResults() != null)
results = apiResponse.getResults();
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
APIResponse apiResponse = api.search(this.url);
if (apiResponse.getResults() != null)
results = apiResponse.getResults();
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import com.evernote.android.job.JobManager;
@ -42,66 +43,64 @@ import app.fedilab.android.sqlite.StatusStoredDAO;
* 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 WeakReference<Context> contextReference;
private DisplayScheduledTootsFragment.typeOfSchedule type;
public RetrieveScheduledTootsAsyncTask(Context context, DisplayScheduledTootsFragment.typeOfSchedule type, OnRetrieveScheduledTootsInterface onRetrieveScheduledTootsInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onRetrieveScheduledTootsInterface;
this.type = type;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
//Retrieves job asked by the user
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
storedStatuses = new StatusStoredDAO(this.contextReference.get(), db).getAllScheduled();
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
storedStatuses = new BoostScheduleDAO(this.contextReference.get(), db).getAllScheduled();
//Retrieves real jobs still waiting
Set<JobRequest> jobRequests = null;
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledTootsSyncJob.SCHEDULED_TOOT);
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledBoostsSyncJob.SCHEDULED_BOOST);
int[] jobIds;
if (jobRequests != null && jobRequests.size() > 0) {
int i = 0;
jobIds = new int[jobRequests.size()];
for (JobRequest jobRequest : jobRequests) {
jobIds[i] = jobRequest.getJobId();
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);
protected void doInBackground() {
new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
//Retrieves job asked by the user
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
storedStatuses = new StatusStoredDAO(this.contextReference.get(), db).getAllScheduled();
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
storedStatuses = new BoostScheduleDAO(this.contextReference.get(), db).getAllScheduled();
//Retrieves real jobs still waiting
Set<JobRequest> jobRequests = null;
if (type == DisplayScheduledTootsFragment.typeOfSchedule.TOOT)
jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledTootsSyncJob.SCHEDULED_TOOT);
else if (type == DisplayScheduledTootsFragment.typeOfSchedule.BOOST)
jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledBoostsSyncJob.SCHEDULED_BOOST);
int[] jobIds;
if (jobRequests != null && jobRequests.size() > 0) {
int i = 0;
jobIds = new int[jobRequests.size()];
for (JobRequest jobRequest : jobRequests) {
jobIds[i] = jobRequest.getJobId();
i++;
}
} else {
jobIds = new int[]{};
}
//Lets time to update db before dispaying
SystemClock.sleep(1000);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveScheduledToots(storedStatuses);
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);
}
}
//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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
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)
*/
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 OnRetrieveSearcAccountshInterface listener;
private WeakReference<Context> contextReference;
private boolean following;
public RetrieveSearchAccountsAsyncTask(Context context, String query, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface) {
this.contextReference = new WeakReference<>(context);
this.query = query;
this.listener = onRetrieveSearcAccountshInterface;
this.following = false;
doInBackground();
}
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.listener = onRetrieveSearcAccountshInterface;
this.following = following;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
if (!following)
apiResponse = api.searchAccounts(query, 20);
else
apiResponse = new API(contextReference.get()).searchAccounts(query, 20, true);
return null;
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
if (!following)
apiResponse = api.searchAccounts(query, 20);
else
apiResponse = new API(contextReference.get()).searchAccounts(query, 20, true);
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.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.List;
@ -38,12 +39,12 @@ import app.fedilab.android.sqlite.TagsCacheDAO;
* 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 APIResponse apiResponse;
private OnRetrieveSearchInterface listener;
private WeakReference<Context> contextReference;
private boolean tagsOnly = false;
private API.searchType type;
private String max_id;
@ -52,6 +53,7 @@ public class RetrieveSearchAsyncTask extends AsyncTask<Void, Void, Void> {
this.contextReference = new WeakReference<>(context);
this.query = query;
this.listener = onRetrieveSearchInterface;
doInBackground();
}
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.listener = onRetrieveSearchInterface;
this.tagsOnly = tagsOnly;
doInBackground();
}
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.type = searchType;
this.max_id = max_id;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
protected void doInBackground() {
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) {
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) {
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;
}
String domain;
String username;
if (split.length == 2) {
username = split[0];
domain = split[1];
} else {
username = split[1];
domain = split[2];
}
if (url != null)
query = url;
}
}
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
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;
}
}
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 {
GNUAPI gnuapi = new GNUAPI(this.contextReference.get());
apiResponse = gnuapi.search(query);
API api = new API(this.contextReference.get());
apiResponse = api.search2(query, type, max_id);
}
} else {
API api = new API(this.contextReference.get());
apiResponse = api.search2(query, type, max_id);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveSearch(apiResponse);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveSearch(apiResponse);
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

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

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
@ -37,18 +38,19 @@ import static app.fedilab.android.sqlite.StatusCacheDAO.BOOKMARK_CACHE;
* 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 OnSyncBookmarksInterface listener;
private WeakReference<Context> contextReference;
private sync type;
private String statusId;
public SyncBookmarksAsyncTask(Context context, sync type, OnSyncBookmarksInterface onSyncBookmarksInterface) {
this.contextReference = new WeakReference<>(context);
this.type = type;
this.listener = onSyncBookmarksInterface;
doInBackground();
}
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.statusId = statusId;
this.listener = onSyncBookmarksInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (type == sync.IMPORT) {
String max_id = null;
do {
APIResponse apiResponse = new API(contextReference.get()).getBookmarks(max_id);
max_id = apiResponse.getMax_id();
List<app.fedilab.android.client.Entities.Status> statuses = apiResponse.getStatuses();
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());
if (status == null) {
new StatusCacheDAO(contextReference.get(), db).insertStatus(BOOKMARK_CACHE, tmpStatus);
protected void doInBackground() {
new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (type == sync.IMPORT) {
String max_id = null;
do {
APIResponse apiResponse = new API(contextReference.get()).getBookmarks(max_id);
max_id = apiResponse.getMax_id();
List<app.fedilab.android.client.Entities.Status> statuses = apiResponse.getStatuses();
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());
if (status == null) {
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 {
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 {
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);
} 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);
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.onRetrieveBookmarks(statusList);
mainHandler.post(myRunnable);
}).start();
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveBookmarks(statusList);
}
public enum sync {
EXPORT,

View File

@ -17,7 +17,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@ -45,14 +46,14 @@ import app.fedilab.android.sqlite.TimelinesDAO;
* Retrieves timelines
*/
public class SyncTimelinesAsyncTask extends AsyncTask<Void, Void, Void> {
public class SyncTimelinesAsyncTask {
private OnSyncTimelineInterface listener;
private int position;
private WeakReference<Context> contextReference;
private final OnSyncTimelineInterface listener;
private final int position;
private final WeakReference<Context> contextReference;
private final boolean syncLists;
private List<ManageTimelines> manageTimelines;
private boolean syncLists;
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.position = position;
this.syncLists = syncLists;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
manageTimelines = new TimelinesDAO(contextReference.get(), db).getAllTimelines();
//First time that the timeline is created
int i = 0;
if (manageTimelines == null || manageTimelines.size() == 0) {
manageTimelines = new ArrayList<>();
//Add home TL
ManageTimelines manageHome = new ManageTimelines();
manageHome.setDisplayed(true);
manageHome.setType(ManageTimelines.Type.HOME);
manageHome.setPosition(i);
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);
protected void doInBackground() {
new Thread(() -> {
SQLiteDatabase db = Sqlite.getInstance(contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
manageTimelines = new TimelinesDAO(contextReference.get(), db).getAllTimelines();
//First time that the timeline is created
int i = 0;
if (manageTimelines == null || manageTimelines.size() == 0) {
manageTimelines = new ArrayList<>();
//Add home TL
ManageTimelines manageHome = new ManageTimelines();
manageHome.setDisplayed(true);
manageHome.setType(ManageTimelines.Type.HOME);
manageHome.setPosition(i);
manageTimelines.add(manageHome);
i++;
manageTimelines.add(managePublic);
new TimelinesDAO(contextReference.get(), db).insert(managePublic);
}
if (!BuildConfig.lite && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) {
//Add Public ART
ManageTimelines manageArt = new ManageTimelines();
manageArt.setDisplayed(true);
manageArt.setType(ManageTimelines.Type.ART);
manageArt.setPosition(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(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);
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(managePeertube);
new TimelinesDAO(contextReference.get(), db).insert(managePeertube);
}
List<TagTimeline> tagTimelines = new SearchDAO(contextReference.get(), db).getAll();
if (tagTimelines != null && tagTimelines.size() > 0) {
for (TagTimeline ttl : tagTimelines) {
//Add tag timelines
ManageTimelines manageTagTimeline = new ManageTimelines();
manageTagTimeline.setDisplayed(true);
manageTagTimeline.setType(ManageTimelines.Type.TAG);
manageTagTimeline.setPosition(i);
manageTagTimeline.setTagTimeline(ttl);
manageTimelines.add(manageTagTimeline);
new TimelinesDAO(contextReference.get(), db).insert(manageTagTimeline);
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++;
manageTimelines.add(managePublic);
new TimelinesDAO(contextReference.get(), db).insert(managePublic);
}
}
List<RemoteInstance> instances = new InstancesDAO(contextReference.get(), db).getAllInstances();
if (instances != null && instances.size() > 0) {
for (RemoteInstance ritl : instances) {
//Add remote instances
ManageTimelines manageRemoteTimline = new ManageTimelines();
manageRemoteTimline.setDisplayed(true);
manageRemoteTimline.setType(ManageTimelines.Type.INSTANCE);
manageRemoteTimline.setPosition(i);
manageRemoteTimline.setRemoteInstance(ritl);
manageTimelines.add(manageRemoteTimline);
new TimelinesDAO(contextReference.get(), db).insert(manageRemoteTimline);
if (!BuildConfig.lite && (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)) {
//Add Public ART
ManageTimelines manageArt = new ManageTimelines();
manageArt.setDisplayed(true);
manageArt.setType(ManageTimelines.Type.ART);
manageArt.setPosition(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<RemoteInstance> instancesInDb = new InstancesDAO(contextReference.get(), db).getAllInstances();
if (tagsInDb != null) {
for (TagTimeline tag : tagsInDb) {
boolean isInDb = false;
ManageTimelines timelines_tmp = null;
for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getTagTimeline() == null)
continue;
if (manageTimeline.getTagTimeline().getId() == tag.getId()) {
isInDb = true;
timelines_tmp = manageTimeline;
break;
List<TagTimeline> tagTimelines = new SearchDAO(contextReference.get(), db).getAll();
if (tagTimelines != null && tagTimelines.size() > 0) {
for (TagTimeline ttl : tagTimelines) {
//Add tag timelines
ManageTimelines manageTagTimeline = new ManageTimelines();
manageTagTimeline.setDisplayed(true);
manageTagTimeline.setType(ManageTimelines.Type.TAG);
manageTagTimeline.setPosition(i);
manageTagTimeline.setTagTimeline(ttl);
manageTimelines.add(manageTagTimeline);
new TimelinesDAO(contextReference.get(), db).insert(manageTagTimeline);
i++;
}
}
if (!isInDb) {
ManageTimelines manageTL = new ManageTimelines();
manageTL.setTagTimeline(tag);
manageTL.setDisplayed(true);
manageTL.setType(ManageTimelines.Type.TAG);
manageTL.setPosition(manageTimelines.size());
new TimelinesDAO(contextReference.get(), db).insert(manageTL);
} else {
//Update list
timelines_tmp.setTagTimeline(tag);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
List<RemoteInstance> instances = new InstancesDAO(contextReference.get(), db).getAllInstances();
if (instances != null && instances.size() > 0) {
for (RemoteInstance ritl : instances) {
//Add remote instances
ManageTimelines manageRemoteTimline = new ManageTimelines();
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++;
}
}
}
for (ManageTimelines manageTimelines : manageTimelines) {
if (manageTimelines.getTagTimeline() == null)
continue;
boolean shouldBeRemoved = true;
List<TagTimeline> tagsInDb = new SearchDAO(contextReference.get(), db).getAll();
List<RemoteInstance> instancesInDb = new InstancesDAO(contextReference.get(), db).getAllInstances();
if (tagsInDb != null) {
for (TagTimeline tag : tagsInDb) {
if (tag.getId() == manageTimelines.getTagTimeline().getId()) {
shouldBeRemoved = false;
}
}
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<>();
boolean isInDb = false;
ManageTimelines timelines_tmp = null;
for (ManageTimelines manageTimeline : manageTimelines) {
if (manageTimeline.getListTimeline() == null)
if (manageTimeline.getTagTimeline() == null)
continue;
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);
if (manageTimeline.getTagTimeline().getId() == tag.getId()) {
isInDb = true;
timelines_tmp = manageTimeline;
break;
}
}
manageTimelines.removeAll(duplicated_id);
if (listsAPI != null && listsAPI.size() > 0) {
//Loop through results
for (app.fedilab.android.client.Entities.List list : listsAPI) {
boolean isInDb = 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 (!isInDb) {
ManageTimelines manageTL = new ManageTimelines();
manageTL.setTagTimeline(tag);
manageTL.setDisplayed(true);
manageTL.setType(ManageTimelines.Type.TAG);
manageTL.setPosition(manageTimelines.size());
new TimelinesDAO(contextReference.get(), db).insert(manageTL);
} else {
//Update list
timelines_tmp.setTagTimeline(tag);
new TimelinesDAO(contextReference.get(), db).update(timelines_tmp);
}
}
for (ManageTimelines manageTimelines : manageTimelines) {
if (manageTimelines.getTagTimeline() == null)
continue;
boolean shouldBeRemoved = true;
for (TagTimeline tag : tagsInDb) {
if (tag.getId() == manageTimelines.getTagTimeline().getId()) {
shouldBeRemoved = false;
break;
}
ArrayList<ManageTimelines> manageTimelinesToRemove = new ArrayList<>();
for (ManageTimelines dbtTimelines : manageTimelines) {
if (dbtTimelines.getListTimeline() == 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) {
if (manageTimeline.getListTimeline() == null)
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) {
if (list.getId().equals(dbtTimelines.getListTimeline().getId())) {
shouldBeRemoved = false;
boolean isInDb = 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) {
new TimelinesDAO(contextReference.get(), db).remove(dbtTimelines);
manageTimelinesToRemove.add(dbtTimelines);
}
}
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)
ArrayList<ManageTimelines> manageTimelinesToRemove = new ArrayList<>();
for (ManageTimelines dbtTimelines : manageTimelines) {
if (dbtTimelines.getListTimeline() == null)
continue;
new TimelinesDAO(contextReference.get(), db).remove(manageTimelines);
manageTimelinesToRemove.add(manageTimelines);
boolean shouldBeRemoved = true;
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) {
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(); ) {
if (!it.next().isDisplayed()) {
it.remove();
for (Iterator<ManageTimelines> it = manageTimelines.iterator(); it.hasNext(); ) {
if (!it.next().isDisplayed()) {
it.remove();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.syncedTimelines(manageTimelines, position);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> listener.syncedTimelines(manageTimelines, position);
mainHandler.post(myRunnable);
}).start();
}
}

View File

@ -19,7 +19,8 @@ import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.io.UnsupportedEncodingException;
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
*/
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 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) {
this.contextReference = new WeakReference<>(context);
@ -55,69 +59,69 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask<Void, Void, Void> {
this.client_id = client_id;
this.client_secret = client_secret;
this.refresh_token = refresh_token;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
Account account;
if (this.contextReference == null) {
return null;
}
if (social == SOCIAL.MASTODON || social == SOCIAL.PIXELFED || social == SOCIAL.PLEROMA) {
account = new API(this.contextReference.get(), instance, null).verifyCredentials();
InstanceNodeInfo info = new API(this.contextReference.get(), instance, token).displayNodeInfo(this.instance);
if (info != null && info.getName() != null && account != null)
account.setSocial(info.getName().toUpperCase());
} else if (social == SOCIAL.PEERTUBE) {
account = new PeertubeAPI(this.contextReference.get(), instance, token).verifyCredentials();
if (account != null)
account.setSocial("PEERTUBE");
} else {
account = new GNUAPI(this.contextReference.get(), instance, token).verifyCredentials();
}
if (account == null)
return null;
try {
//At the state the instance can be encoded
instance = URLDecoder.decode(instance, "utf-8");
} catch (UnsupportedEncodingException ignored) {
}
SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
account.setToken(token);
account.setClient_id(client_id);
account.setClient_secret(client_secret);
account.setRefresh_token(refresh_token);
account.setInstance(instance);
protected void doInBackground() {
new Thread(() -> {
Account account;
if (this.contextReference == null) {
return;
}
if (social == SOCIAL.MASTODON || social == SOCIAL.PIXELFED || social == SOCIAL.PLEROMA) {
account = new API(this.contextReference.get(), instance, null).verifyCredentials();
InstanceNodeInfo info = new API(this.contextReference.get(), instance, token).displayNodeInfo(this.instance);
if (info != null && info.getName() != null && account != null)
account.setSocial(info.getName().toUpperCase());
} else if (social == SOCIAL.PEERTUBE) {
account = new PeertubeAPI(this.contextReference.get(), instance, token).verifyCredentials();
if (account != null)
account.setSocial("PEERTUBE");
} else {
account = new GNUAPI(this.contextReference.get(), instance, token).verifyCredentials();
}
if (account == null)
return;
try {
//At the state the instance can be encoded
instance = URLDecoder.decode(instance, "utf-8");
} catch (UnsupportedEncodingException ignored) {
}
SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
account.setToken(token);
account.setClient_id(client_id);
account.setClient_secret(client_secret);
account.setRefresh_token(refresh_token);
account.setInstance(instance);
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);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putBoolean(Helper.PREF_IS_MODERATOR, account.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin());
editor.putString(Helper.PREF_INSTANCE, instance);
editor.apply();
if (userExists)
new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account);
else {
if (account.getUsername() != null && account.getCreated_at() != null)
new AccountDAO(this.contextReference.get(), db).insertAccount(account);
}
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);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putBoolean(Helper.PREF_IS_MODERATOR, account.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin());
editor.putString(Helper.PREF_INSTANCE, instance);
editor.apply();
if (userExists)
new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account);
else {
if (account.getUsername() != null && account.getCreated_at() != null)
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 {
MASTODON,

View File

@ -16,7 +16,8 @@ package app.fedilab.android.asynctasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
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
*/
public class UpdateAccountInfoByIDAsyncTask extends AsyncTask<Void, Void, Void> {
public class UpdateAccountInfoByIDAsyncTask {
private OnUpdateAccountInfoInterface listener;
private WeakReference<Context> contextReference;
private Account accountOld;
private final OnUpdateAccountInfoInterface listener;
private final WeakReference<Context> contextReference;
private final Account accountOld;
public UpdateAccountInfoByIDAsyncTask(Context context, Account account, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface) {
this.contextReference = new WeakReference<>(context);
this.listener = onUpdateAccountInfoInterface;
this.accountOld = account;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
Account account = null;
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
account = new API(this.contextReference.get()).verifyCredentials();
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
account.setSocial("PIXELFED");
protected void doInBackground() {
new Thread(() -> {
Account account = null;
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
account = new API(this.contextReference.get()).verifyCredentials();
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) {
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();
}
if (account == null)
return null;
account.setInstance(Helper.getLiveInstance(contextReference.get()));
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (accountOld != null) {
account.setInstance(accountOld.getInstance());
account.setToken(accountOld.getToken());
account.setRefresh_token(accountOld.getRefresh_token());
account.setClient_id(accountOld.getClient_id());
account.setClient_secret(accountOld.getClient_secret());
new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account);
}
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
new API(contextReference.get()).refreshToken(account);
}
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
try {
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);
if (account == null)
return;
account.setInstance(Helper.getLiveInstance(contextReference.get()));
SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get().getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (accountOld != null) {
account.setInstance(accountOld.getInstance());
account.setToken(accountOld.getToken());
account.setRefresh_token(accountOld.getRefresh_token());
account.setClient_id(accountOld.getClient_id());
account.setClient_secret(accountOld.getClient_secret());
new AccountDAO(this.contextReference.get(), db).updateAccountCredential(account);
}
if (social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE || social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
new API(contextReference.get()).refreshToken(account);
}
if (social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
try {
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) {
}
}
return null;
Handler mainHandler = new Handler(Looper.getMainLooper());
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.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.io.ByteArrayInputStream;
import java.lang.ref.WeakReference;
@ -31,16 +32,20 @@ import app.fedilab.android.interfaces.OnUpdateCredentialInterface;
* Update account credential
*/
public class UpdateCredentialAsyncTask extends AsyncTask<Void, Void, Void> {
public class UpdateCredentialAsyncTask {
private String display_name, note, avatarName, headerName;
private boolean senstive;
private ByteArrayInputStream avatar, header;
private API.accountPrivacy privacy;
private final String display_name;
private final String note;
private final String avatarName;
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 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) {
this.contextReference = new WeakReference<>(context);
@ -54,17 +59,15 @@ public class UpdateCredentialAsyncTask extends AsyncTask<Void, Void, Void> {
this.headerName = headerName;
this.customFields = customFields;
this.senstive = senstive;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
apiResponse = new API(this.contextReference.get()).updateCredential(display_name, note, avatar, avatarName, header, headerName, privacy, customFields, senstive);
return null;
protected void doInBackground() {
new Thread(() -> {
apiResponse = new API(this.contextReference.get()).updateCredential(display_name, note, avatar, avatarName, header, headerName, privacy, customFields, senstive);
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
@ -30,14 +31,15 @@ import app.fedilab.android.interfaces.OnRetrieveAttachmentInterface;
* 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 String mediaId, description;
private Account account;
private API api;
private WeakReference<Context> contextReference;
public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, Account account, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface) {
this.contextReference = new WeakReference<>(context);
@ -45,21 +47,19 @@ public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask<Void, Void,
this.description = description;
this.mediaId = mediaId;
this.account = account;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
if (account == null)
api = new API(this.contextReference.get());
else
api = new API(this.contextReference.get(), account.getInstance(), account.getToken());
attachment = api.updateDescription(mediaId, description);
return null;
protected void doInBackground() {
new Thread(() -> {
if (account == null)
api = new API(this.contextReference.get());
else
api = new API(this.contextReference.get(), account.getInstance(), account.getToken());
attachment = api.updateDescription(mediaId, description);
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;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@ -31,47 +32,46 @@ import app.fedilab.android.interfaces.OnRetrieveWhoToFollowInterface;
* 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 OnRetrieveWhoToFollowInterface listener;
private WeakReference<Context> contextReference;
public WhoToFollowAsyncTask(Context context, String name, OnRetrieveWhoToFollowInterface onRetrieveWhoToFollowInterface) {
this.contextReference = new WeakReference<>(context);
this.name = name;
this.listener = onRetrieveWhoToFollowInterface;
doInBackground();
}
@Override
protected Void doInBackground(Void... params) {
API api = new API(this.contextReference.get());
if (name != null)
response = api.getCommunitywikiList(name);
else
response = api.getCommunitywikiList();
return null;
}
@Override
protected void onPostExecute(Void result) {
if (name == null)
listener.onRetrieveWhoToFollowList(response);
else {
List<TrunkAccount> trunkAccounts = null;
if (response != null) {
trunkAccounts = new ArrayList<>();
for (String res : response) {
TrunkAccount trunkAccount = new TrunkAccount();
trunkAccount.setAcct(res);
trunkAccounts.add(trunkAccount);
protected void doInBackground() {
new Thread(() -> {
API api = new API(this.contextReference.get());
if (name != null)
response = api.getCommunitywikiList(name);
else
response = api.getCommunitywikiList();
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
if (name == null)
listener.onRetrieveWhoToFollowList(response);
else {
List<TrunkAccount> trunkAccounts = null;
if (response != null) {
trunkAccounts = new ArrayList<>();
for (String res : response) {
TrunkAccount trunkAccount = new TrunkAccount();
trunkAccount.setAcct(res);
trunkAccounts.add(trunkAccount);
}
}
listener.onRetrieveWhoToFollowAccount(trunkAccounts);
}
}
listener.onRetrieveWhoToFollowAccount(trunkAccounts);
}
};
mainHandler.post(myRunnable);
}).start();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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