From 575329586f13286dcceb4c639c22e102d0b2d585 Mon Sep 17 00:00:00 2001 From: Thomas Date: Fri, 27 Jan 2023 18:19:24 +0100 Subject: [PATCH] Some fixes --- app/src/debug/res/xml/compose_shortcuts.xml | 2 +- app/src/fdroid/res/xml/compose_shortcuts.xml | 2 +- app/src/main/AndroidManifest.xml | 1 - .../app/fedilab/android/BaseMainActivity.java | 1513 +++++++++-------- .../mastodon/helper/MastodonHelper.java | 16 +- .../activities/PeertubeMainActivity.java | 39 +- .../drawable/ic_baseline_add_comment_24.xml | 3 +- .../playstore/res/xml/compose_shortcuts.xml | 2 +- 8 files changed, 812 insertions(+), 766 deletions(-) diff --git a/app/src/debug/res/xml/compose_shortcuts.xml b/app/src/debug/res/xml/compose_shortcuts.xml index 19ed0e0a..fb29a811 100644 --- a/app/src/debug/res/xml/compose_shortcuts.xml +++ b/app/src/debug/res/xml/compose_shortcuts.xml @@ -1,9 +1,9 @@ - { + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(activity); + boolean singleBar = sharedpreferences.getBoolean(activity.getString(R.string.SET_USE_SINGLE_TOPBAR), false); + BottomNavigationView bottomNavigationView = activity.findViewById(R.id.bottom_nav_view); + TabLayout tabLayout = activity.findViewById(R.id.tabLayout); + ViewPager viewPager = activity.findViewById(R.id.view_pager); + + if (bottomNavigationView != null && tabLayout != null && viewPager != null) { + if (!singleBar) { + bottomNavigationView.setSelectedItemId(R.id.nav_notifications); + } else { + int position = 0; + for (int i = 0; i < tabLayout.getTabCount(); i++) { + TabLayout.Tab tab = tabLayout.getTabAt(i); + if (tab != null && tab.getTag() != null && tab.getTag().equals(Timeline.TimeLineEnum.NOTIFICATION.getValue())) { + break; + } + position++; + } + viewPager.setCurrentItem(position); + } + } + }, 1000); + intent.removeExtra(Helper.INTENT_ACTION); } - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); - if (!Helper.isLoggedIn(BaseMainActivity.this)) { - //It is not, the user is redirected to the login page - Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); - startActivity(myIntent); - finish(); + @SuppressLint("ApplySharedPref") + public static void mamageNewIntent(Activity activity, Intent intent) { + if (intent == null) return; - } else { - BaseMainActivity.currentToken = sharedpreferences.getString(Helper.PREF_USER_TOKEN, null); - } - String software = sharedpreferences.getString(PREF_USER_SOFTWARE, null); - - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - ActivityResultLauncher permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { - if (!isGranted) { - ActivityCompat.requestPermissions(BaseMainActivity.this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE); - } - }); - permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS); - } - NavHeaderMainBinding headerMainBinding = NavHeaderMainBinding.inflate(getLayoutInflater()); - currentAccount = null; - //Update account details - new Thread(() -> { - try { - if (currentToken == null) { - currentToken = sharedpreferences.getString(Helper.PREF_USER_TOKEN, null); - } - currentAccount = new Account(BaseMainActivity.this).getConnectedAccount(); - } catch (DBException e) { - e.printStackTrace(); - } - if (currentAccount != null && currentAccount.peertube_account != null) { - //It is a peertube user - Intent myIntent = new Intent(this, PeertubeMainActivity.class); - startActivity(myIntent); - finish(); + String action = intent.getAction(); + String type = intent.getType(); + Bundle extras = intent.getExtras(); + String userIdIntent, instanceIntent, urlOfMessage; + if (action != null && action.equalsIgnoreCase("app.fedilab.android.shorcut.compose")) { + if (!activity.isFinishing()) { + CrossActionHelper.doCrossAction(activity, CrossActionHelper.TypeOfCrossAction.COMPOSE, null, null); + intent.replaceExtras(new Bundle()); + intent.setAction(""); + intent.setData(null); + intent.setFlags(0); return; } - //If the attached account is null, the app will fetch remote instance to get up-to-date values - if (currentAccount != null && currentAccount.mastodon_account == null && currentAccount.peertube_account == null) { - OkHttpClient okHttpClient = new OkHttpClient.Builder() - .readTimeout(60, TimeUnit.SECONDS) - .connectTimeout(60, TimeUnit.SECONDS) - .callTimeout(60, TimeUnit.SECONDS) - .proxy(Helper.getProxy(getApplication().getApplicationContext())) - .build(); - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + MainActivity.currentInstance + "/api/v1/") - .addConverterFactory(GsonConverterFactory.create(Helper.getDateBuilder())) - .client(okHttpClient) - .build(); - MastodonAccountsService mastodonAccountsService = retrofit.create(MastodonAccountsService.class); - retrofit2.Call accountCall = mastodonAccountsService.verify_credentials(MainActivity.currentToken); - if (accountCall != null) { + } + if (extras != null && extras.containsKey(Helper.INTENT_ACTION)) { + userIdIntent = extras.getString(Helper.PREF_USER_ID); //Id of the account in the intent + instanceIntent = extras.getString(Helper.PREF_USER_INSTANCE); + urlOfMessage = extras.getString(Helper.PREF_MESSAGE_URL); + if (extras.getInt(Helper.INTENT_ACTION) == Helper.NOTIFICATION_INTENT) { + if (userIdIntent != null && instanceIntent != null && userIdIntent.equals(currentUserID) && instanceIntent.equals(currentInstance)) { + openNotifications(activity, intent); + } else { try { - retrofit2.Response accountResponse = accountCall.execute(); - if (accountResponse.isSuccessful()) { - currentAccount.mastodon_account = accountResponse.body(); - } - } catch (Exception e) { + BaseAccount account = new Account(activity).getUniqAccount(userIdIntent, instanceIntent); + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(activity); + headerMenuOpen = false; + Toasty.info(activity, activity.getString(R.string.toast_account_changed, "@" + account.mastodon_account.acct + "@" + account.instance), Toasty.LENGTH_LONG).show(); + BaseMainActivity.currentToken = account.token; + BaseMainActivity.currentUserID = account.user_id; + api = account.api; + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(PREF_USER_TOKEN, account.token); + editor.putString(PREF_USER_SOFTWARE, account.software); + editor.commit(); + Intent mainActivity = new Intent(activity, MainActivity.class); + mainActivity.putExtra(Helper.INTENT_ACTION, Helper.OPEN_NOTIFICATION); + activity.startActivity(mainActivity); + activity.finish(); + } catch (DBException e) { e.printStackTrace(); } } - } - Handler mainHandler = new Handler(Looper.getMainLooper()); - Runnable myRunnable = () -> { - if (currentAccount == null || (currentAccount.mastodon_account == null && currentAccount.peertube_account == null)) { - //It is not, the user is redirected to the login page - if (currentAccount != null) { - try { - Helper.removeAccount(BaseMainActivity.this); - } catch (DBException e) { - Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); - startActivity(myIntent); - finish(); - e.printStackTrace(); + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.OPEN_NOTIFICATION) { + openNotifications(activity, intent); + } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.OPEN_WITH_ANOTHER_ACCOUNT) { + CrossActionHelper.fetchRemoteStatus(activity, MainActivity.currentAccount, urlOfMessage, new CrossActionHelper.Callback() { + @Override + public void federatedStatus(Status status) { + if (status != null) { + Intent intent = new Intent(activity, ContextActivity.class); + intent.putExtra(Helper.ARG_STATUS, status); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intent); } - } else { - Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); - startActivity(myIntent); - finish(); - } - return; - } - bottomMenu = new BottomMenu(BaseMainActivity.this).hydrate(currentAccount, binding.bottomNavView); - if (currentAccount.mastodon_account.locked) { - binding.navView.getMenu().findItem(R.id.nav_follow_requests).setVisible(true); - } - if (currentAccount.admin) { - binding.navView.getMenu().findItem(R.id.nav_administration).setVisible(true); - } - if (bottomMenu != null) { - //ManageClick on bottom menu items - if (binding.bottomNavView.findViewById(R.id.nav_home) != null) { - binding.bottomNavView.findViewById(R.id.nav_home).setOnLongClickListener(view -> { - int position = BottomMenu.getPosition(bottomMenu, R.id.nav_home); - if (position >= 0) { - manageFilters(position); - } - return false; - }); } - if (binding.bottomNavView.findViewById(R.id.nav_local) != null) { - binding.bottomNavView.findViewById(R.id.nav_local).setOnLongClickListener(view -> { - int position = BottomMenu.getPosition(bottomMenu, R.id.nav_local); - if (position >= 0) { - manageFilters(position); - } - return false; - }); + + @Override + public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { + } - if (binding.bottomNavView.findViewById(R.id.nav_public) != null) { - binding.bottomNavView.findViewById(R.id.nav_public).setOnLongClickListener(view -> { - int position = BottomMenu.getPosition(bottomMenu, R.id.nav_public); - if (position >= 0) { - manageFilters(position); - } - return false; - }); + }); + } + } else if (Intent.ACTION_SEND.equals(action) && type != null) { + if ("text/plain".equals(type)) { + final String[] url = {null}; + String sharedSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); + String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); + //SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); + //boolean shouldRetrieveMetaData = sharedpreferences.getBoolean(getString(R.string.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL), true); + if (sharedText != null) { + /* Some apps don't send the URL as the first part of the EXTRA_TEXT, + the BBC News app being one such, in this case find where the URL + is and strip that out into sharedText. + */ + Matcher matcher; + matcher = Patterns.WEB_URL.matcher(sharedText); + int count = 0; + while (matcher.find()) { + int matchStart = matcher.start(1); + int matchEnd = matcher.end(); + if (matchStart < matchEnd && sharedText.length() >= matchEnd) { + url[0] = sharedText.substring(matchStart, matchEnd); + count++; + } } - binding.bottomNavView.setOnItemSelectedListener(item -> { - int itemId = item.getItemId(); - int position = BottomMenu.getPosition(bottomMenu, itemId); - if (position >= 0) { - if (binding.viewPager.getCurrentItem() == position) { - scrollToTop(); - binding.bottomNavView.removeBadge(itemId); - } else { - binding.viewPager.setCurrentItem(position, false); + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(activity); + boolean fetchSharedMedia = sharedpreferences.getBoolean(activity.getString(R.string.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL), true); + boolean fetchShareContent = sharedpreferences.getBoolean(activity.getString(R.string.SET_SHARE_DETAILS), true); + if (url[0] != null && count == 1 && (fetchShareContent || fetchSharedMedia)) { + String originalUrl = url[0]; + new Thread(() -> { + if (!url[0].matches("^https?://.*")) url[0] = "http://" + url[0]; + Matcher matcherPattern = Patterns.WEB_URL.matcher(url[0]); + String potentialUrl = null; + while (matcherPattern.find()) { + int matchStart = matcherPattern.start(1); + int matchEnd = matcherPattern.end(); + if (matchStart < matchEnd && url[0].length() >= matchEnd) + potentialUrl = url[0].substring(matchStart, matchEnd); } - } - return true; - }); - } + // If we actually have a URL then make use of it. + if (potentialUrl != null && potentialUrl.length() > 0) { - currentInstance = currentAccount.instance; - currentUserID = currentAccount.user_id; - show_boosts = sharedpreferences.getBoolean(getString(R.string.SET_SHOW_BOOSTS) + currentUserID + currentInstance, true); - show_replies = sharedpreferences.getBoolean(getString(R.string.SET_SHOW_REPLIES) + currentUserID + currentInstance, true); - show_dms = sharedpreferences.getBoolean(getString(R.string.SET_SHOW_DMS) + currentUserID + currentInstance, true); - regex_home = sharedpreferences.getString(getString(R.string.SET_FILTER_REGEX_HOME) + currentUserID + currentInstance, null); - regex_local = sharedpreferences.getString(getString(R.string.SET_FILTER_REGEX_LOCAL) + currentUserID + currentInstance, null); - regex_public = sharedpreferences.getString(getString(R.string.SET_FILTER_REGEX_PUBLIC) + currentUserID + currentInstance, null); - show_art_nsfw = sharedpreferences.getBoolean(getString(R.string.SET_ART_WITH_NSFW) + currentUserID + currentInstance, false); + try { + OkHttpClient client = new OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .proxy(Helper.getProxy(activity.getApplication().getApplicationContext())) + .readTimeout(10, TimeUnit.SECONDS).build(); + Request request = new Request.Builder() + .url(potentialUrl) + .build(); + client.newCall(request).enqueue(new Callback() { + @Override + public void onFailure(@NonNull Call call, @NonNull IOException e) { + e.printStackTrace(); + activity.runOnUiThread(() -> Toasty.warning(activity, activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show()); + } - binding.profilePicture.setOnClickListener(v -> binding.drawerLayout.openDrawer(GravityCompat.START)); - Helper.loadPP(BaseMainActivity.this, binding.profilePicture, currentAccount); - headerMainBinding.accountAcc.setText(String.format("%s@%s", currentAccount.mastodon_account.username, currentAccount.instance)); - if (currentAccount.mastodon_account.display_name == null || currentAccount.mastodon_account.display_name.isEmpty()) { - currentAccount.mastodon_account.display_name = currentAccount.mastodon_account.acct; - } - if (!isFinishing()) { - headerMainBinding.accountName.setText( - currentAccount.mastodon_account.getSpanDisplayName(BaseMainActivity.this, - new WeakReference<>(headerMainBinding.accountName)), - TextView.BufferType.SPANNABLE); - } - float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.1f); - headerMainBinding.accountName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); - headerMainBinding.accountAcc.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); - Helper.loadPP(BaseMainActivity.this, headerMainBinding.accountProfilePicture, currentAccount, false); - MastodonHelper.loadProfileMediaMastodon(BaseMainActivity.this, headerMainBinding.backgroundImage, currentAccount.mastodon_account, MastodonHelper.MediaAccountType.HEADER); - headerMainBinding.backgroundImage.setAlpha(0.5f); - /* - * Some general data are loaded when the app starts such; - * - Pinned timelines (in app feature) - * - Instance info (for limits) - * - Emoji for picker - * - Filters for timelines + @Override + public void onResponse(@NonNull Call call, @NonNull final Response response) { + if (response.isSuccessful()) { + try { + String data = response.body().string(); + Document html = Jsoup.parse(data); - */ + Element titleEl = html.selectFirst("meta[property='og:title']"); + Element descriptionEl = html.selectFirst("meta[property='og:description']"); + Element imageUrlEl = html.selectFirst("meta[property='og:image']"); - //Update pinned timelines - new ViewModelProvider(BaseMainActivity.this).get(TopBarVM.class).getDBPinned() - .observe(this, pinned -> { - this.pinned = pinned; - //Initialize the slug of the first fragment - //First it's taken from db (last stored values) - PinnedTimelineHelper.redrawTopBarPinned(BaseMainActivity.this, binding, pinned, bottomMenu, null); - //Fetch remote lists for the authenticated account and update them - new ViewModelProvider(BaseMainActivity.this).get(TimelinesVM.class).getLists(currentInstance, currentToken) - .observe(this, mastodonLists -> - PinnedTimelineHelper.redrawTopBarPinned(BaseMainActivity.this, binding, pinned, bottomMenu, mastodonLists) - ); - }); + String title = ""; + String description = ""; - //Update emoji in db for the current instance - new ViewModelProvider(BaseMainActivity.this).get(InstancesVM.class).getEmoji(currentInstance); - //Retrieve instance info - new ViewModelProvider(BaseMainActivity.this).get(InstancesVM.class).getInstance(currentInstance) - .observe(BaseMainActivity.this, instance -> { - instanceInfo = instance.info; - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(getString(R.string.INSTANCE_INFO) + MainActivity.currentInstance, Instance.serialize(instanceInfo)); - editor.apply(); - }); - //Retrieve filters - new ViewModelProvider(BaseMainActivity.this).get(FiltersVM.class).getFilters(currentInstance, currentToken) - .observe(BaseMainActivity.this, filters -> mainFilters = filters); - new ViewModelProvider(BaseMainActivity.this).get(AccountsVM.class).getConnectedAccount(currentInstance, currentToken) - .observe(BaseMainActivity.this, mastodonAccount -> { - //Initialize static var - if (mastodonAccount != null && currentAccount != null) { - currentAccount.mastodon_account = mastodonAccount; - displayReleaseNotesIfNeeded(BaseMainActivity.this, false); - new Thread(() -> { - try { - //Update account in db - new Account(BaseMainActivity.this).insertOrUpdate(currentAccount); - } catch (DBException e) { - e.printStackTrace(); - } - }).start(); - } - }); + if (titleEl != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + title = Html.fromHtml(titleEl.attr("content"), Html.FROM_HTML_MODE_LEGACY).toString(); + } else { + title = Html.fromHtml(titleEl.attr("content")).toString(); + } + } - }; - mainHandler.post(myRunnable); - }).start(); - filteredAccounts = new ArrayList<>(); - mamageNewIntent(getIntent()); - filterFetched = false; - networkStateReceiver = new NetworkStateReceiver(); - networkStateReceiver.addListener(this); - binding = ActivityMainBinding.inflate(getLayoutInflater()); - setContentView(binding.getRoot()); - setSupportActionBar(binding.toolbar); - ActionBar actionBar = getSupportActionBar(); - //Remove title - if (actionBar != null) { - actionBar.setDisplayShowTitleEnabled(false); - } - rateThisApp(); + if (descriptionEl != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + description = Html.fromHtml(descriptionEl.attr("content"), Html.FROM_HTML_MODE_LEGACY).toString(); + } else { + description = Html.fromHtml(descriptionEl.attr("content")).toString(); + } + } - binding.compose.setOnClickListener(v -> startActivity(new Intent(this, ComposeActivity.class))); - binding.compose.setOnLongClickListener(view -> { - CrossActionHelper.doCrossAction(BaseMainActivity.this, CrossActionHelper.TypeOfCrossAction.COMPOSE, null, null); - return false; - }); - headerMenuOpen = false; + String imageUrl = ""; + if (imageUrlEl != null) { + imageUrl = imageUrlEl.attr("content"); + } - PushHelper.startStreaming(BaseMainActivity.this); + StringBuilder titleBuilder = new StringBuilder(); - // Passing each menu ID as a set of Ids because each - // menu should be considered as top level destinations. - mAppBarConfiguration = new AppBarConfiguration.Builder() - .setOpenableLayout(binding.drawerLayout) - .build(); + if (!originalUrl.trim().equalsIgnoreCase(sharedText.trim())) { + // If the shared text is not just the URL, add it to the top + String toAppend = sharedText.replaceAll("\\s*" + Pattern.quote(originalUrl) + "\\s*", ""); + titleBuilder.append(toAppend); + } + if (title.length() > 0) { + // OG title fetched from source + if (titleBuilder.length() > 0) + titleBuilder.append("\n\n"); + titleBuilder.append(title); + } - binding.navView.addHeaderView(headerMainBinding.getRoot()); - binding.navView.setNavigationItemSelectedListener(menuItem -> { - int id = menuItem.getItemId(); - if (id == R.id.nav_drafts) { - Intent intent = new Intent(this, DraftActivity.class); - startActivity(intent); - } else if (id == R.id.nav_reorder) { - Intent intent = new Intent(this, ReorderTimelinesActivity.class); - startActivity(intent); - } else if (id == R.id.nav_interactions) { - Intent intent = new Intent(this, ActionActivity.class); - startActivity(intent); - } else if (id == R.id.nav_filter) { - Intent intent = new Intent(this, FilterActivity.class); - startActivity(intent); - } else if (id == R.id.nav_list) { - Intent intent = new Intent(this, MastodonListActivity.class); - startActivity(intent); - } else if (id == R.id.nav_followed_tags) { - Intent intent = new Intent(this, FollowedTagActivity.class); - startActivity(intent); - } else if (id == R.id.nav_settings) { - Intent intent = new Intent(this, SettingsActivity.class); - startActivity(intent); - } else if (id == R.id.nav_scheduled) { - Intent intent = new Intent(this, ScheduledActivity.class); - startActivity(intent); - } else if (id == R.id.nav_follow_requests) { - Intent intent = new Intent(this, FollowRequestActivity.class); - startActivity(intent); - } else if (id == R.id.nav_administration) { - Intent intent = new Intent(this, AdminActionActivity.class); - startActivity(intent); - } else if (id == R.id.nav_about) { - Intent intent = new Intent(this, AboutActivity.class); - startActivity(intent); - } else if (id == R.id.nav_release_notes) { - displayReleaseNotesIfNeeded(BaseMainActivity.this, true); - } else if (id == R.id.nav_partnership) { - Intent intent = new Intent(this, PartnerShipActivity.class); - startActivity(intent); - } else if (id == R.id.nav_announcements) { - Intent intent = new Intent(this, AnnouncementActivity.class); - startActivity(intent); - } else if (id == R.id.nav_trends) { - Intent intent = new Intent(this, TrendsActivity.class); - startActivity(intent); - } else if (id == R.id.nav_suggestions) { - Intent intent = new Intent(this, SuggestionActivity.class); - startActivity(intent); - } else if (id == R.id.nav_directory) { - Intent intent = new Intent(this, DirectoryActivity.class); - startActivity(intent); - } else if (id == R.id.nav_cache) { - Intent intent = new Intent(BaseMainActivity.this, CacheActivity.class); - startActivity(intent); - } else if (id == R.id.nav_about_instance) { - (new InstanceActivity()).show(getSupportFragmentManager(), null); - } - binding.drawerLayout.close(); - return false; - }); + String finalImage = imageUrl; + String finalTitle = titleBuilder.toString(); + String finalDescription = description; - headerMainBinding.instanceInfo.setOnClickListener(v -> (new InstanceHealthActivity()).show(getSupportFragmentManager(), null)); - headerMainBinding.accountProfilePicture.setOnClickListener(v -> { - Intent intent = new Intent(BaseMainActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, currentAccount.mastodon_account); - intent.putExtras(b); - ActivityOptionsCompat options = ActivityOptionsCompat - .makeSceneTransitionAnimation(BaseMainActivity.this, headerMainBinding.instanceInfoContainer, getString(R.string.activity_porfile_pp)); - startActivity(intent, options.toBundle()); - }); + activity.runOnUiThread(() -> { + Bundle b = new Bundle(); + b.putString(Helper.ARG_SHARE_URL, url[0]); + if (fetchSharedMedia) { + b.putString(Helper.ARG_SHARE_URL_MEDIA, finalImage); + } + b.putString(Helper.ARG_SHARE_TITLE, finalTitle); + b.putString(Helper.ARG_SHARE_DESCRIPTION, finalDescription); + b.putString(Helper.ARG_SHARE_SUBJECT, sharedSubject); + b.putString(Helper.ARG_SHARE_CONTENT, sharedText); + CrossActionHelper.doCrossShare(activity, b); + }); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + activity.runOnUiThread(() -> Toasty.warning(activity, activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show()); + } + } + }); + } catch (IndexOutOfBoundsException e) { + Toasty.warning(activity, activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + } - headerMainBinding.accountAcc.setOnClickListener(v -> headerMainBinding.changeAccount.callOnClick()); - headerMainBinding.changeAccount.setOnClickListener(v -> { - headerMenuOpen = !headerMenuOpen; - manageDrawerMenu(BaseMainActivity.this, binding.navView, headerMainBinding); - }); + } + }).start(); + } else { + Bundle b = new Bundle(); + b.putString(Helper.ARG_SHARE_TITLE, sharedSubject); + b.putString(Helper.ARG_SHARE_DESCRIPTION, sharedText); + CrossActionHelper.doCrossShare(activity, b); + } - headerMainBinding.headerOptionInfo.setOnClickListener(v -> headerOptionInfoClick(BaseMainActivity.this, headerMainBinding, getSupportFragmentManager())); - //Toolbar search - binding.toolbarSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - //Hide keyboard - InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(binding.toolbarSearch.getWindowToken(), 0); - query = query.replaceAll("^#+", ""); - Intent intent; - intent = new Intent(BaseMainActivity.this, SearchResultTabActivity.class); - intent.putExtra(Helper.ARG_SEARCH_KEYWORD, query); - startActivity(intent); - binding.toolbarSearch.setQuery("", false); - binding.toolbarSearch.setIconified(true); - return false; + } + } else if (type.startsWith("image/") || type.startsWith("video/")) { + Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); + if (imageUri != null) { + Bundle b = new Bundle(); + List uris = new ArrayList<>(); + uris.add(imageUri); + Helper.createAttachmentFromUri(activity, uris, attachments -> { + b.putSerializable(Helper.ARG_MEDIA_ATTACHMENTS, new ArrayList<>(attachments)); + CrossActionHelper.doCrossShare(activity, b); + }); + } else { + Toasty.warning(activity, activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + } } - - @Override - public boolean onQueryTextChange(String newText) { - String pattern = "^(@[\\w_-]+@[a-z0-9.\\-]+|@[\\w_-]+)"; - final Pattern mentionPattern = Pattern.compile(pattern); - String patternTag = "^#([\\w-]{2,})$"; - final Pattern tagPattern = Pattern.compile(patternTag); - Matcher matcherMention, matcherTag; - matcherMention = mentionPattern.matcher(newText); - matcherTag = tagPattern.matcher(newText); - if (newText.trim().isEmpty()) { - binding.toolbarSearch.setSuggestionsAdapter(null); - } - if (matcherMention.matches()) { - String[] from = new String[]{SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1}; - int[] to = new int[]{R.id.account_pp, R.id.account_un}; - String searchGroup = matcherMention.group(); - AccountsVM accountsVM = new ViewModelProvider(BaseMainActivity.this).get(AccountsVM.class); - MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, - SearchManager.SUGGEST_COLUMN_ICON_1, - SearchManager.SUGGEST_COLUMN_TEXT_1}); - accountsVM.searchAccounts(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, searchGroup, 5, false, false) - .observe(BaseMainActivity.this, accounts -> { - if (accounts == null) { - return; - } - AccountsSearchTopBarAdapter cursorAdapter = new AccountsSearchTopBarAdapter(BaseMainActivity.this, accounts, R.layout.drawer_account_search, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); - binding.toolbarSearch.setSuggestionsAdapter(cursorAdapter); - new Thread(() -> { - int i = 0; - for (app.fedilab.android.mastodon.client.entities.api.Account account : accounts) { - FutureTarget futureTarget = Glide - .with(BaseMainActivity.this.getApplicationContext()) - .load(account.avatar_static) - .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL); - File cacheFile; - try { - cacheFile = futureTarget.get(); - cursor.addRow(new String[]{String.valueOf(i), cacheFile.getAbsolutePath(), "@" + account.acct}); - i++; - } catch (ExecutionException | InterruptedException e) { - e.printStackTrace(); - } - } - runOnUiThread(() -> cursorAdapter.changeCursor(cursor)); - }).start(); - - }); - } else if (matcherTag.matches()) { - SearchVM searchVM = new ViewModelProvider(BaseMainActivity.this).get(SearchVM.class); - String[] from = new String[]{SearchManager.SUGGEST_COLUMN_TEXT_1}; - int[] to = new int[]{R.id.tag_name}; - String searchGroup = matcherTag.group(); - MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, - SearchManager.SUGGEST_COLUMN_TEXT_1}); - searchVM.search(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, searchGroup, null, - "hashtags", false, true, false, 0, - null, null, 10).observe(BaseMainActivity.this, - results -> { - if (results == null || results.hashtags == null) { - return; - } - TagSearchTopBarAdapter cursorAdapter = new TagSearchTopBarAdapter(BaseMainActivity.this, results.hashtags, R.layout.drawer_tag_search, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); - binding.toolbarSearch.setSuggestionsAdapter(cursorAdapter); - int i = 0; - for (Tag tag : results.hashtags) { - cursor.addRow(new String[]{String.valueOf(i), "#" + tag.name}); - i++; - } - runOnUiThread(() -> cursorAdapter.changeCursor(cursor)); - }); + } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { + if (type.startsWith("image/") || type.startsWith("video/")) { + ArrayList imageList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); + if (imageList != null) { + Bundle b = new Bundle(); + Helper.createAttachmentFromUri(activity, imageList, attachments -> { + b.putSerializable(Helper.ARG_MEDIA_ATTACHMENTS, new ArrayList<>(attachments)); + CrossActionHelper.doCrossShare(activity, b); + }); + } else { + Toasty.warning(activity, activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show(); } - return false; } - }); - binding.toolbarSearch.setOnCloseListener(() -> { - binding.tabLayout.setVisibility(View.VISIBLE); - return false; - }); + } else if (Intent.ACTION_VIEW.equals(action)) { + String url = intent.getDataString(); + if (url == null) { + intent.replaceExtras(new Bundle()); + intent.setAction(""); + intent.setData(null); + intent.setFlags(0); + return; + } + Matcher matcher; + matcher = Patterns.WEB_URL.matcher(url); + boolean isUrl = false; + while (matcher.find()) { + isUrl = true; + } + if (!isUrl) { + intent.replaceExtras(new Bundle()); + intent.setAction(""); + intent.setData(null); + intent.setFlags(0); + return; + } + //Here we know that the intent contains a valid URL + if (!url.contains("medium.com")) { + Pattern link = Pattern.compile("https?://([\\da-z.-]+[à-ü]?\\.[a-z.]{2,10})/(@[\\w._-]*[0-9]*)(/[0-9]+)?$"); + Matcher matcherLink; + matcherLink = link.matcher(url); + if (matcherLink.find()) { + if (currentAccount == null) { + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(activity); + if (currentToken == null || currentToken.trim().isEmpty()) { + currentToken = sharedpreferences.getString(Helper.PREF_USER_TOKEN, null); + } + try { + currentAccount = new Account(activity).getConnectedAccount(); + } catch (DBException e) { + e.printStackTrace(); + } + } + if (matcherLink.group(3) != null && Objects.requireNonNull(matcherLink.group(3)).length() > 0) { //It's a toot + CrossActionHelper.fetchRemoteStatus(activity, currentAccount, url, new CrossActionHelper.Callback() { + @Override + public void federatedStatus(Status status) { + if (status != null) { + Intent intent = new Intent(activity, ContextActivity.class); + intent.putExtra(Helper.ARG_STATUS, status); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intent); + } else { + Toasty.error(activity, activity.getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); + } + } - binding.toolbarSearch.setOnSearchClickListener(v -> binding.tabLayout.setVisibility(View.VISIBLE)); - //For receiving data from other activities - LocalBroadcastManager.getInstance(BaseMainActivity.this).registerReceiver(broadcast_data, new IntentFilter(Helper.BROADCAST_DATA)); - LocalBroadcastManager.getInstance(BaseMainActivity.this) - .registerReceiver(broadcast_error_message, - new IntentFilter(Helper.INTENT_COMPOSE_ERROR_MESSAGE)); - if (emojis == null || !emojis.containsKey(BaseMainActivity.currentInstance) || emojis.get(BaseMainActivity.currentInstance) == null) { - new Thread(() -> { - try { - emojis.put(currentInstance, new EmojiInstance(BaseMainActivity.this).getEmojiList(BaseMainActivity.currentInstance)); - } catch (DBException e) { - e.printStackTrace(); - } - }).start(); - } - fetchRecentAccounts(BaseMainActivity.this, headerMainBinding); - } + @Override + public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { + } + }); + } else {//It's an account + CrossActionHelper.fetchRemoteAccount(activity, currentAccount, matcherLink.group(2) + "@" + matcherLink.group(1), new CrossActionHelper.Callback() { + @Override + public void federatedStatus(Status status) { + } - /** - * Open notifications tab when coming from a notification device - * - * @param intent - Intent intent that will be cancelled - */ - private void openNotifications(Intent intent) { - final Handler handler = new Handler(); - handler.postDelayed(() -> { - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); - boolean singleBar = sharedpreferences.getBoolean(getString(R.string.SET_USE_SINGLE_TOPBAR), false); - if (!singleBar) { - binding.bottomNavView.setSelectedItemId(R.id.nav_notifications); - } else { - int position = 0; - for (int i = 0; i < binding.tabLayout.getTabCount(); i++) { - TabLayout.Tab tab = binding.tabLayout.getTabAt(i); - if (tab != null && tab.getTag() != null && tab.getTag().equals(Timeline.TimeLineEnum.NOTIFICATION.getValue())) { - break; + @Override + public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { + if (account != null) { + Intent intent = new Intent(activity, ProfileActivity.class); + Bundle b = new Bundle(); + b.putSerializable(Helper.ARG_ACCOUNT, account); + intent.putExtras(b); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.startActivity(intent); + } else { + Toasty.error(activity, activity.getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); + } + } + }); } - position++; + } else { + Helper.forwardToBrowser(activity, intent); } - binding.viewPager.setCurrentItem(position); + } else { + Helper.forwardToBrowser(activity, intent); } - }, 1000); - intent.removeExtra(Helper.INTENT_ACTION); + } + intent.replaceExtras(new Bundle()); + intent.setAction(""); + intent.setData(null); + intent.setFlags(0); } + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + mamageNewIntent(BaseMainActivity.this, intent); + } - @SuppressLint("ApplySharedPref") - private void mamageNewIntent(Intent intent) { - if (intent == null) - return; - String action = intent.getAction(); - String type = intent.getType(); - Bundle extras = intent.getExtras(); - String userIdIntent, instanceIntent, urlOfMessage; - if (action != null && action.equalsIgnoreCase("app.fedilab.android.shorcut.compose")) { - CrossActionHelper.doCrossAction(BaseMainActivity.this, CrossActionHelper.TypeOfCrossAction.COMPOSE, null, null); - intent.replaceExtras(new Bundle()); - intent.setAction(""); - intent.setData(null); - intent.setFlags(0); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); + if (!Helper.isLoggedIn(BaseMainActivity.this)) { + //It is not, the user is redirected to the login page + Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); + startActivity(myIntent); + finish(); return; + } else { + BaseMainActivity.currentToken = sharedpreferences.getString(Helper.PREF_USER_TOKEN, null); } - if (extras != null && extras.containsKey(Helper.INTENT_ACTION)) { - userIdIntent = extras.getString(Helper.PREF_USER_ID); //Id of the account in the intent - instanceIntent = extras.getString(Helper.PREF_USER_INSTANCE); - urlOfMessage = extras.getString(Helper.PREF_MESSAGE_URL); - if (extras.getInt(Helper.INTENT_ACTION) == Helper.NOTIFICATION_INTENT) { - if (userIdIntent != null && instanceIntent != null && userIdIntent.equals(currentUserID) && instanceIntent.equals(currentInstance)) { - openNotifications(intent); - } else { - try { - BaseAccount account = new Account(BaseMainActivity.this).getUniqAccount(userIdIntent, instanceIntent); - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); - headerMenuOpen = false; - Toasty.info(BaseMainActivity.this, getString(R.string.toast_account_changed, "@" + account.mastodon_account.acct + "@" + account.instance), Toasty.LENGTH_LONG).show(); - BaseMainActivity.currentToken = account.token; - BaseMainActivity.currentUserID = account.user_id; - api = account.api; - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(PREF_USER_TOKEN, account.token); - editor.putString(PREF_USER_SOFTWARE, account.software); - editor.commit(); - Intent mainActivity = new Intent(this, MainActivity.class); - mainActivity.putExtra(Helper.INTENT_ACTION, Helper.OPEN_NOTIFICATION); - startActivity(mainActivity); - finish(); - } catch (DBException e) { - e.printStackTrace(); - } - } - } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.OPEN_NOTIFICATION) { - openNotifications(intent); - } else if (extras.getInt(Helper.INTENT_ACTION) == Helper.OPEN_WITH_ANOTHER_ACCOUNT) { - CrossActionHelper.fetchRemoteStatus(BaseMainActivity.this, MainActivity.currentAccount, urlOfMessage, new CrossActionHelper.Callback() { - @Override - public void federatedStatus(Status status) { - if (status != null) { - Intent intent = new Intent(BaseMainActivity.this, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } + String software = sharedpreferences.getString(PREF_USER_SOFTWARE, null); - @Override - public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { - } - }); - } - } else if (Intent.ACTION_SEND.equals(action) && type != null) { - if ("text/plain".equals(type)) { - final String[] url = {null}; - String sharedSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); - String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); - //SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); - //boolean shouldRetrieveMetaData = sharedpreferences.getBoolean(getString(R.string.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL), true); - if (sharedText != null) { - /* Some apps don't send the URL as the first part of the EXTRA_TEXT, - the BBC News app being one such, in this case find where the URL - is and strip that out into sharedText. - */ - Matcher matcher; - matcher = Patterns.WEB_URL.matcher(sharedText); - int count = 0; - while (matcher.find()) { - int matchStart = matcher.start(1); - int matchEnd = matcher.end(); - if (matchStart < matchEnd && sharedText.length() >= matchEnd) { - url[0] = sharedText.substring(matchStart, matchEnd); - count++; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + ActivityResultLauncher permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { + if (!isGranted) { + ActivityCompat.requestPermissions(BaseMainActivity.this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE); + } + }); + permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS); + } + NavHeaderMainBinding headerMainBinding = NavHeaderMainBinding.inflate(getLayoutInflater()); + currentAccount = null; + //Update account details + new Thread(() -> { + try { + if (currentToken == null) { + currentToken = sharedpreferences.getString(PREF_USER_TOKEN, null); + } + currentAccount = new Account(BaseMainActivity.this).getConnectedAccount(); + } catch (DBException e) { + e.printStackTrace(); + } + if (currentAccount != null && currentAccount.peertube_account != null) { + //It is a peertube user + Intent intent = getIntent(); + Intent myIntent = new Intent(this, PeertubeMainActivity.class); + if (intent.getExtras() != null) { + Bundle currentExtra = myIntent.getExtras(); + if (currentExtra == null) { + currentExtra = new Bundle(); + } + Bundle bundleToForward = intent.getExtras(); + currentExtra.putAll(bundleToForward); + myIntent.putExtras(currentExtra); + } + if (intent.getAction() != null) { + myIntent.setAction(intent.getAction()); + } + startActivity(myIntent); + finish(); + return; + } + //If the attached account is null, the app will fetch remote instance to get up-to-date values + if (currentAccount != null && currentAccount.mastodon_account == null) { + OkHttpClient okHttpClient = new OkHttpClient.Builder() + .readTimeout(60, TimeUnit.SECONDS) + .connectTimeout(60, TimeUnit.SECONDS) + .callTimeout(60, TimeUnit.SECONDS) + .proxy(Helper.getProxy(getApplication().getApplicationContext())) + .build(); + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://" + MainActivity.currentInstance + "/api/v1/") + .addConverterFactory(GsonConverterFactory.create(Helper.getDateBuilder())) + .client(okHttpClient) + .build(); + MastodonAccountsService mastodonAccountsService = retrofit.create(MastodonAccountsService.class); + retrofit2.Call accountCall = mastodonAccountsService.verify_credentials(MainActivity.currentToken); + if (accountCall != null) { + try { + retrofit2.Response accountResponse = accountCall.execute(); + if (accountResponse.isSuccessful()) { + currentAccount.mastodon_account = accountResponse.body(); } + } catch (Exception e) { + e.printStackTrace(); } - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); - boolean fetchSharedMedia = sharedpreferences.getBoolean(getString(R.string.SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL), true); - boolean fetchShareContent = sharedpreferences.getBoolean(getString(R.string.SET_SHARE_DETAILS), true); - if (url[0] != null && count == 1 && (fetchShareContent || fetchSharedMedia)) { - String originalUrl = url[0]; - new Thread(() -> { - if (!url[0].matches("^https?://.*")) url[0] = "http://" + url[0]; - Matcher matcherPattern = Patterns.WEB_URL.matcher(url[0]); - String potentialUrl = null; - while (matcherPattern.find()) { - int matchStart = matcherPattern.start(1); - int matchEnd = matcherPattern.end(); - if (matchStart < matchEnd && url[0].length() >= matchEnd) - potentialUrl = url[0].substring(matchStart, matchEnd); + } + } + Handler mainHandler = new Handler(Looper.getMainLooper()); + Runnable myRunnable = () -> { + if (currentAccount == null || (currentAccount.mastodon_account == null && currentAccount.peertube_account == null)) { + //It is not, the user is redirected to the login page + if (currentAccount != null) { + try { + Helper.removeAccount(BaseMainActivity.this); + } catch (DBException e) { + Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); + startActivity(myIntent); + finish(); + e.printStackTrace(); + } + } else { + Intent myIntent = new Intent(BaseMainActivity.this, LoginActivity.class); + startActivity(myIntent); + finish(); + } + return; + } + bottomMenu = new BottomMenu(BaseMainActivity.this).hydrate(currentAccount, binding.bottomNavView); + if (currentAccount.mastodon_account.locked) { + binding.navView.getMenu().findItem(R.id.nav_follow_requests).setVisible(true); + } + if (currentAccount.admin) { + binding.navView.getMenu().findItem(R.id.nav_administration).setVisible(true); + } + if (bottomMenu != null) { + //ManageClick on bottom menu items + if (binding.bottomNavView.findViewById(R.id.nav_home) != null) { + binding.bottomNavView.findViewById(R.id.nav_home).setOnLongClickListener(view -> { + int position = BottomMenu.getPosition(bottomMenu, R.id.nav_home); + if (position >= 0) { + manageFilters(position); } - // If we actually have a URL then make use of it. - if (potentialUrl != null && potentialUrl.length() > 0) { + return false; + }); + } + if (binding.bottomNavView.findViewById(R.id.nav_local) != null) { + binding.bottomNavView.findViewById(R.id.nav_local).setOnLongClickListener(view -> { + int position = BottomMenu.getPosition(bottomMenu, R.id.nav_local); + if (position >= 0) { + manageFilters(position); + } + return false; + }); + } + if (binding.bottomNavView.findViewById(R.id.nav_public) != null) { + binding.bottomNavView.findViewById(R.id.nav_public).setOnLongClickListener(view -> { + int position = BottomMenu.getPosition(bottomMenu, R.id.nav_public); + if (position >= 0) { + manageFilters(position); + } + return false; + }); + } + binding.bottomNavView.setOnItemSelectedListener(item -> { + int itemId = item.getItemId(); + int position = BottomMenu.getPosition(bottomMenu, itemId); + if (position >= 0) { + if (binding.viewPager.getCurrentItem() == position) { + scrollToTop(); + binding.bottomNavView.removeBadge(itemId); + } else { + binding.viewPager.setCurrentItem(position, false); + } + } + return true; + }); + } + currentInstance = currentAccount.instance; + currentUserID = currentAccount.user_id; - try { - OkHttpClient client = new OkHttpClient.Builder() - .connectTimeout(10, TimeUnit.SECONDS) - .writeTimeout(10, TimeUnit.SECONDS) - .proxy(Helper.getProxy(getApplication().getApplicationContext())) - .readTimeout(10, TimeUnit.SECONDS).build(); - Request request = new Request.Builder() - .url(potentialUrl) - .build(); - client.newCall(request).enqueue(new Callback() { - @Override - public void onFailure(@NonNull Call call, @NonNull IOException e) { - e.printStackTrace(); - runOnUiThread(() -> Toasty.warning(BaseMainActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show()); - } + show_boosts = sharedpreferences.getBoolean(getString(R.string.SET_SHOW_BOOSTS) + currentUserID + currentInstance, true); + show_replies = sharedpreferences.getBoolean(getString(R.string.SET_SHOW_REPLIES) + currentUserID + currentInstance, true); + show_dms = sharedpreferences.getBoolean(getString(R.string.SET_SHOW_DMS) + currentUserID + currentInstance, true); + regex_home = sharedpreferences.getString(getString(R.string.SET_FILTER_REGEX_HOME) + currentUserID + currentInstance, null); + regex_local = sharedpreferences.getString(getString(R.string.SET_FILTER_REGEX_LOCAL) + currentUserID + currentInstance, null); + regex_public = sharedpreferences.getString(getString(R.string.SET_FILTER_REGEX_PUBLIC) + currentUserID + currentInstance, null); + show_art_nsfw = sharedpreferences.getBoolean(getString(R.string.SET_ART_WITH_NSFW) + currentUserID + currentInstance, false); - @Override - public void onResponse(@NonNull Call call, @NonNull final Response response) { - if (response.isSuccessful()) { - try { - String data = response.body().string(); - Document html = Jsoup.parse(data); + binding.profilePicture.setOnClickListener(v -> binding.drawerLayout.openDrawer(GravityCompat.START)); + Helper.loadPP(BaseMainActivity.this, binding.profilePicture, currentAccount); + headerMainBinding.accountAcc.setText(String.format("%s@%s", currentAccount.mastodon_account.username, currentAccount.instance)); + if (currentAccount.mastodon_account.display_name == null || currentAccount.mastodon_account.display_name.isEmpty()) { + currentAccount.mastodon_account.display_name = currentAccount.mastodon_account.acct; + } + if (!isFinishing()) { + headerMainBinding.accountName.setText( + currentAccount.mastodon_account.getSpanDisplayName(BaseMainActivity.this, + new WeakReference<>(headerMainBinding.accountName)), + TextView.BufferType.SPANNABLE); + } + float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.1f); + headerMainBinding.accountName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); + headerMainBinding.accountAcc.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18 * 1.1f / scale); + Helper.loadPP(BaseMainActivity.this, headerMainBinding.accountProfilePicture, currentAccount, false); + MastodonHelper.loadProfileMediaMastodon(BaseMainActivity.this, headerMainBinding.backgroundImage, currentAccount.mastodon_account, MastodonHelper.MediaAccountType.HEADER); + headerMainBinding.backgroundImage.setAlpha(0.5f); + /* + * Some general data are loaded when the app starts such; + * - Pinned timelines (in app feature) + * - Instance info (for limits) + * - Emoji for picker + * - Filters for timelines - Element titleEl = html.selectFirst("meta[property='og:title']"); - Element descriptionEl = html.selectFirst("meta[property='og:description']"); - Element imageUrlEl = html.selectFirst("meta[property='og:image']"); + */ - String title = ""; - String description = ""; + //Update pinned timelines + new ViewModelProvider(BaseMainActivity.this).get(TopBarVM.class).getDBPinned() + .observe(this, pinned -> { + this.pinned = pinned; + //Initialize the slug of the first fragment + //First it's taken from db (last stored values) + PinnedTimelineHelper.redrawTopBarPinned(BaseMainActivity.this, binding, pinned, bottomMenu, null); + //Fetch remote lists for the authenticated account and update them + new ViewModelProvider(BaseMainActivity.this).get(TimelinesVM.class).getLists(currentInstance, currentToken) + .observe(this, mastodonLists -> + PinnedTimelineHelper.redrawTopBarPinned(BaseMainActivity.this, binding, pinned, bottomMenu, mastodonLists) + ); + }); - if (titleEl != null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - title = Html.fromHtml(titleEl.attr("content"), Html.FROM_HTML_MODE_LEGACY).toString(); - } else { - title = Html.fromHtml(titleEl.attr("content")).toString(); - } - } + //Update emoji in db for the current instance + new ViewModelProvider(BaseMainActivity.this).get(InstancesVM.class).getEmoji(currentInstance); + //Retrieve instance info + new ViewModelProvider(BaseMainActivity.this).get(InstancesVM.class).getInstance(currentInstance) + .observe(BaseMainActivity.this, instance -> { + instanceInfo = instance.info; + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(getString(R.string.INSTANCE_INFO) + MainActivity.currentInstance, Instance.serialize(instanceInfo)); + editor.apply(); + }); + //Retrieve filters + new ViewModelProvider(BaseMainActivity.this).get(FiltersVM.class).getFilters(currentInstance, currentToken) + .observe(BaseMainActivity.this, filters -> mainFilters = filters); + new ViewModelProvider(BaseMainActivity.this).get(AccountsVM.class).getConnectedAccount(currentInstance, currentToken) + .observe(BaseMainActivity.this, mastodonAccount -> { + //Initialize static var + if (mastodonAccount != null && currentAccount != null) { + currentAccount.mastodon_account = mastodonAccount; + displayReleaseNotesIfNeeded(BaseMainActivity.this, false); + new Thread(() -> { + try { + //Update account in db + new Account(BaseMainActivity.this).insertOrUpdate(currentAccount); + } catch (DBException e) { + e.printStackTrace(); + } + }).start(); + } + }); + mamageNewIntent(this, getIntent()); - if (descriptionEl != null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - description = Html.fromHtml(descriptionEl.attr("content"), Html.FROM_HTML_MODE_LEGACY).toString(); - } else { - description = Html.fromHtml(descriptionEl.attr("content")).toString(); - } - } + }; + mainHandler.post(myRunnable); + }).start(); + filteredAccounts = new ArrayList<>(); - String imageUrl = ""; - if (imageUrlEl != null) { - imageUrl = imageUrlEl.attr("content"); - } + filterFetched = false; + networkStateReceiver = new NetworkStateReceiver(); + networkStateReceiver.addListener(this); + binding = ActivityMainBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + setSupportActionBar(binding.toolbar); + ActionBar actionBar = getSupportActionBar(); + //Remove title + if (actionBar != null) { + actionBar.setDisplayShowTitleEnabled(false); + } + rateThisApp(); + + binding.compose.setOnClickListener(v -> startActivity(new Intent(this, ComposeActivity.class))); + binding.compose.setOnLongClickListener(view -> { + CrossActionHelper.doCrossAction(BaseMainActivity.this, CrossActionHelper.TypeOfCrossAction.COMPOSE, null, null); + return false; + }); + headerMenuOpen = false; + + PushHelper.startStreaming(BaseMainActivity.this); + + // Passing each menu ID as a set of Ids because each + // menu should be considered as top level destinations. + mAppBarConfiguration = new AppBarConfiguration.Builder() + .setOpenableLayout(binding.drawerLayout) + .build(); + + + binding.navView.addHeaderView(headerMainBinding.getRoot()); + binding.navView.setNavigationItemSelectedListener(menuItem -> { + int id = menuItem.getItemId(); + if (id == R.id.nav_drafts) { + Intent intent = new Intent(this, DraftActivity.class); + startActivity(intent); + } else if (id == R.id.nav_reorder) { + Intent intent = new Intent(this, ReorderTimelinesActivity.class); + startActivity(intent); + } else if (id == R.id.nav_interactions) { + Intent intent = new Intent(this, ActionActivity.class); + startActivity(intent); + } else if (id == R.id.nav_filter) { + Intent intent = new Intent(this, FilterActivity.class); + startActivity(intent); + } else if (id == R.id.nav_list) { + Intent intent = new Intent(this, MastodonListActivity.class); + startActivity(intent); + } else if (id == R.id.nav_followed_tags) { + Intent intent = new Intent(this, FollowedTagActivity.class); + startActivity(intent); + } else if (id == R.id.nav_settings) { + Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + } else if (id == R.id.nav_scheduled) { + Intent intent = new Intent(this, ScheduledActivity.class); + startActivity(intent); + } else if (id == R.id.nav_follow_requests) { + Intent intent = new Intent(this, FollowRequestActivity.class); + startActivity(intent); + } else if (id == R.id.nav_administration) { + Intent intent = new Intent(this, AdminActionActivity.class); + startActivity(intent); + } else if (id == R.id.nav_about) { + Intent intent = new Intent(this, AboutActivity.class); + startActivity(intent); + } else if (id == R.id.nav_release_notes) { + displayReleaseNotesIfNeeded(BaseMainActivity.this, true); + } else if (id == R.id.nav_partnership) { + Intent intent = new Intent(this, PartnerShipActivity.class); + startActivity(intent); + } else if (id == R.id.nav_announcements) { + Intent intent = new Intent(this, AnnouncementActivity.class); + startActivity(intent); + } else if (id == R.id.nav_trends) { + Intent intent = new Intent(this, TrendsActivity.class); + startActivity(intent); + } else if (id == R.id.nav_suggestions) { + Intent intent = new Intent(this, SuggestionActivity.class); + startActivity(intent); + } else if (id == R.id.nav_directory) { + Intent intent = new Intent(this, DirectoryActivity.class); + startActivity(intent); + } else if (id == R.id.nav_cache) { + Intent intent = new Intent(BaseMainActivity.this, CacheActivity.class); + startActivity(intent); + } else if (id == R.id.nav_about_instance) { + (new InstanceActivity()).show(getSupportFragmentManager(), null); + } + binding.drawerLayout.close(); + return false; + }); - StringBuilder titleBuilder = new StringBuilder(); + headerMainBinding.instanceInfo.setOnClickListener(v -> (new InstanceHealthActivity()).show(getSupportFragmentManager(), null)); + headerMainBinding.accountProfilePicture.setOnClickListener(v -> { + Intent intent = new Intent(BaseMainActivity.this, ProfileActivity.class); + Bundle b = new Bundle(); + b.putSerializable(Helper.ARG_ACCOUNT, currentAccount.mastodon_account); + intent.putExtras(b); + ActivityOptionsCompat options = ActivityOptionsCompat + .makeSceneTransitionAnimation(BaseMainActivity.this, headerMainBinding.instanceInfoContainer, getString(R.string.activity_porfile_pp)); + startActivity(intent, options.toBundle()); + }); - if (!originalUrl.trim().equalsIgnoreCase(sharedText.trim())) { - // If the shared text is not just the URL, add it to the top - String toAppend = sharedText.replaceAll("\\s*" + Pattern.quote(originalUrl) + "\\s*", ""); - titleBuilder.append(toAppend); - } + headerMainBinding.accountAcc.setOnClickListener(v -> headerMainBinding.changeAccount.callOnClick()); + headerMainBinding.changeAccount.setOnClickListener(v -> { + headerMenuOpen = !headerMenuOpen; + manageDrawerMenu(BaseMainActivity.this, binding.navView, headerMainBinding); + }); - if (title.length() > 0) { - // OG title fetched from source - if (titleBuilder.length() > 0) - titleBuilder.append("\n\n"); - titleBuilder.append(title); - } + headerMainBinding.headerOptionInfo.setOnClickListener(v -> headerOptionInfoClick(BaseMainActivity.this, headerMainBinding, getSupportFragmentManager())); - String finalImage = imageUrl; - String finalTitle = titleBuilder.toString(); - String finalDescription = description; + //Toolbar search + binding.toolbarSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit(String query) { + //Hide keyboard + InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(binding.toolbarSearch.getWindowToken(), 0); + query = query.replaceAll("^#+", ""); + Intent intent; + intent = new Intent(BaseMainActivity.this, SearchResultTabActivity.class); + intent.putExtra(Helper.ARG_SEARCH_KEYWORD, query); + startActivity(intent); + binding.toolbarSearch.setQuery("", false); + binding.toolbarSearch.setIconified(true); + return false; + } - runOnUiThread(() -> { - Bundle b = new Bundle(); - b.putString(Helper.ARG_SHARE_URL, url[0]); - if (fetchSharedMedia) { - b.putString(Helper.ARG_SHARE_URL_MEDIA, finalImage); - } - b.putString(Helper.ARG_SHARE_TITLE, finalTitle); - b.putString(Helper.ARG_SHARE_DESCRIPTION, finalDescription); - b.putString(Helper.ARG_SHARE_SUBJECT, sharedSubject); - b.putString(Helper.ARG_SHARE_CONTENT, sharedText); - CrossActionHelper.doCrossShare(BaseMainActivity.this, b); - }); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - runOnUiThread(() -> Toasty.warning(BaseMainActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show()); - } - } - }); - } catch (IndexOutOfBoundsException e) { - Toasty.warning(BaseMainActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + @Override + public boolean onQueryTextChange(String newText) { + String pattern = "^(@[\\w_-]+@[a-z0-9.\\-]+|@[\\w_-]+)"; + final Pattern mentionPattern = Pattern.compile(pattern); + String patternTag = "^#([\\w-]{2,})$"; + final Pattern tagPattern = Pattern.compile(patternTag); + Matcher matcherMention, matcherTag; + matcherMention = mentionPattern.matcher(newText); + matcherTag = tagPattern.matcher(newText); + if (newText.trim().isEmpty()) { + binding.toolbarSearch.setSuggestionsAdapter(null); + } + if (matcherMention.matches()) { + String[] from = new String[]{SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1}; + int[] to = new int[]{R.id.account_pp, R.id.account_un}; + String searchGroup = matcherMention.group(); + AccountsVM accountsVM = new ViewModelProvider(BaseMainActivity.this).get(AccountsVM.class); + MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, + SearchManager.SUGGEST_COLUMN_ICON_1, + SearchManager.SUGGEST_COLUMN_TEXT_1}); + accountsVM.searchAccounts(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, searchGroup, 5, false, false) + .observe(BaseMainActivity.this, accounts -> { + if (accounts == null) { + return; } + AccountsSearchTopBarAdapter cursorAdapter = new AccountsSearchTopBarAdapter(BaseMainActivity.this, accounts, R.layout.drawer_account_search, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); + binding.toolbarSearch.setSuggestionsAdapter(cursorAdapter); + new Thread(() -> { + int i = 0; + for (app.fedilab.android.mastodon.client.entities.api.Account account : accounts) { + FutureTarget futureTarget = Glide + .with(BaseMainActivity.this.getApplicationContext()) + .load(account.avatar_static) + .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL); + File cacheFile; + try { + cacheFile = futureTarget.get(); + cursor.addRow(new String[]{String.valueOf(i), cacheFile.getAbsolutePath(), "@" + account.acct}); + i++; + } catch (ExecutionException | InterruptedException e) { + e.printStackTrace(); + } + } + runOnUiThread(() -> cursorAdapter.changeCursor(cursor)); + }).start(); - } - }).start(); - } else { - Bundle b = new Bundle(); - b.putString(Helper.ARG_SHARE_TITLE, sharedSubject); - b.putString(Helper.ARG_SHARE_DESCRIPTION, sharedText); - CrossActionHelper.doCrossShare(BaseMainActivity.this, b); - } - - - } - } else if (type.startsWith("image/") || type.startsWith("video/")) { - Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); - if (imageUri != null) { - Bundle b = new Bundle(); - List uris = new ArrayList<>(); - uris.add(imageUri); - Helper.createAttachmentFromUri(BaseMainActivity.this, uris, attachments -> { - b.putSerializable(Helper.ARG_MEDIA_ATTACHMENTS, new ArrayList<>(attachments)); - CrossActionHelper.doCrossShare(BaseMainActivity.this, b); - }); - } else { - Toasty.warning(BaseMainActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); - } - } - } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { - if (type.startsWith("image/") || type.startsWith("video/")) { - ArrayList imageList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); - if (imageList != null) { - Bundle b = new Bundle(); - Helper.createAttachmentFromUri(BaseMainActivity.this, imageList, attachments -> { - b.putSerializable(Helper.ARG_MEDIA_ATTACHMENTS, new ArrayList<>(attachments)); - CrossActionHelper.doCrossShare(BaseMainActivity.this, b); - }); - } else { - Toasty.warning(BaseMainActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show(); + }); + } else if (matcherTag.matches()) { + SearchVM searchVM = new ViewModelProvider(BaseMainActivity.this).get(SearchVM.class); + String[] from = new String[]{SearchManager.SUGGEST_COLUMN_TEXT_1}; + int[] to = new int[]{R.id.tag_name}; + String searchGroup = matcherTag.group(); + MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, + SearchManager.SUGGEST_COLUMN_TEXT_1}); + searchVM.search(BaseMainActivity.currentInstance, BaseMainActivity.currentToken, searchGroup, null, + "hashtags", false, true, false, 0, + null, null, 10).observe(BaseMainActivity.this, + results -> { + if (results == null || results.hashtags == null) { + return; + } + TagSearchTopBarAdapter cursorAdapter = new TagSearchTopBarAdapter(BaseMainActivity.this, results.hashtags, R.layout.drawer_tag_search, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); + binding.toolbarSearch.setSuggestionsAdapter(cursorAdapter); + int i = 0; + for (Tag tag : results.hashtags) { + cursor.addRow(new String[]{String.valueOf(i), "#" + tag.name}); + i++; + } + runOnUiThread(() -> cursorAdapter.changeCursor(cursor)); + }); } + return false; } - } else if (Intent.ACTION_VIEW.equals(action)) { - String url = intent.getDataString(); - - if (url == null) { - intent.replaceExtras(new Bundle()); - intent.setAction(""); - intent.setData(null); - intent.setFlags(0); - return; - } - Matcher matcher; - matcher = Patterns.WEB_URL.matcher(url); - boolean isUrl = false; - while (matcher.find()) { - isUrl = true; - } - if (!isUrl) { - intent.replaceExtras(new Bundle()); - intent.setAction(""); - intent.setData(null); - intent.setFlags(0); - return; - } - //Here we know that the intent contains a valid URL - if (!url.contains("medium.com")) { - Pattern link = Pattern.compile("https?://([\\da-z.-]+[à-ü]?\\.[a-z.]{2,10})/(@[\\w._-]*[0-9]*)(/[0-9]+)?$"); - Matcher matcherLink; - matcherLink = link.matcher(url); - if (matcherLink.find()) { - if (currentAccount == null) { - SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(BaseMainActivity.this); - if (currentToken == null || currentToken.trim().isEmpty()) { - currentToken = sharedpreferences.getString(Helper.PREF_USER_TOKEN, null); - } - try { - currentAccount = new Account(BaseMainActivity.this).getConnectedAccount(); - } catch (DBException e) { - e.printStackTrace(); - } - } - if (matcherLink.group(3) != null && Objects.requireNonNull(matcherLink.group(3)).length() > 0) { //It's a toot - CrossActionHelper.fetchRemoteStatus(BaseMainActivity.this, currentAccount, url, new CrossActionHelper.Callback() { - @Override - public void federatedStatus(Status status) { - if (status != null) { - Intent intent = new Intent(BaseMainActivity.this, ContextActivity.class); - intent.putExtra(Helper.ARG_STATUS, status); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } else { - Toasty.error(BaseMainActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); - } - } + }); + binding.toolbarSearch.setOnCloseListener(() -> { + binding.tabLayout.setVisibility(View.VISIBLE); + return false; + }); - @Override - public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { - } - }); - } else {//It's an account - CrossActionHelper.fetchRemoteAccount(BaseMainActivity.this, currentAccount, matcherLink.group(2) + "@" + matcherLink.group(1), new CrossActionHelper.Callback() { - @Override - public void federatedStatus(Status status) { - } - @Override - public void federatedAccount(app.fedilab.android.mastodon.client.entities.api.Account account) { - if (account != null) { - Intent intent = new Intent(BaseMainActivity.this, ProfileActivity.class); - Bundle b = new Bundle(); - b.putSerializable(Helper.ARG_ACCOUNT, account); - intent.putExtras(b); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } else { - Toasty.error(BaseMainActivity.this, getString(R.string.toast_error), Toasty.LENGTH_SHORT).show(); - } - } - }); - } - } else { - Helper.forwardToBrowser(BaseMainActivity.this, intent); + binding.toolbarSearch.setOnSearchClickListener(v -> binding.tabLayout.setVisibility(View.VISIBLE)); + //For receiving data from other activities + LocalBroadcastManager.getInstance(BaseMainActivity.this).registerReceiver(broadcast_data, new IntentFilter(Helper.BROADCAST_DATA)); + LocalBroadcastManager.getInstance(BaseMainActivity.this) + .registerReceiver(broadcast_error_message, + new IntentFilter(Helper.INTENT_COMPOSE_ERROR_MESSAGE)); + if (emojis == null || !emojis.containsKey(BaseMainActivity.currentInstance) || emojis.get(BaseMainActivity.currentInstance) == null) { + new Thread(() -> { + try { + emojis.put(currentInstance, new EmojiInstance(BaseMainActivity.this).getEmojiList(BaseMainActivity.currentInstance)); + } catch (DBException e) { + e.printStackTrace(); } - } else { - Helper.forwardToBrowser(BaseMainActivity.this, intent); - } + }).start(); } - intent.replaceExtras(new Bundle()); - intent.setAction(""); - intent.setData(null); - intent.setFlags(0); + fetchRecentAccounts(BaseMainActivity.this, headerMainBinding); } private void manageFilters(int position) { diff --git a/app/src/main/java/app/fedilab/android/mastodon/helper/MastodonHelper.java b/app/src/main/java/app/fedilab/android/mastodon/helper/MastodonHelper.java index a5a31444..c7dfa1df 100644 --- a/app/src/main/java/app/fedilab/android/mastodon/helper/MastodonHelper.java +++ b/app/src/main/java/app/fedilab/android/mastodon/helper/MastodonHelper.java @@ -248,12 +248,16 @@ public class MastodonHelper { String targetedUrl = disableGif ? (type == MediaAccountType.AVATAR ? account.avatar_static : account.header_static) : (type == MediaAccountType.AVATAR ? account.avatar : account.header); if (targetedUrl != null) { if (disableGif || (!targetedUrl.endsWith(".gif"))) { - Glide.with(activity != null ? activity : context) - .asDrawable() - .load(targetedUrl) - .thumbnail(0.1f) - .placeholder(placeholder) - .into(view); + try { + Glide.with(activity != null ? activity : context) + .asDrawable() + .load(targetedUrl) + .thumbnail(0.1f) + .placeholder(placeholder) + .into(view); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } } else { Glide.with(activity != null ? activity : context) .asGif() diff --git a/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java b/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java index f6bd26c2..6ded2da5 100644 --- a/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java +++ b/app/src/main/java/app/fedilab/android/peertube/activities/PeertubeMainActivity.java @@ -17,9 +17,11 @@ package app.fedilab.android.peertube.activities; import static app.fedilab.android.BaseMainActivity.currentAccount; import static app.fedilab.android.BaseMainActivity.currentInstance; import static app.fedilab.android.BaseMainActivity.currentToken; +import static app.fedilab.android.BaseMainActivity.currentUserID; import static app.fedilab.android.BaseMainActivity.fetchRecentAccounts; import static app.fedilab.android.BaseMainActivity.headerMenuOpen; import static app.fedilab.android.BaseMainActivity.headerOptionInfoClick; +import static app.fedilab.android.BaseMainActivity.mamageNewIntent; import static app.fedilab.android.BaseMainActivity.manageDrawerMenu; import static app.fedilab.android.mastodon.helper.Helper.PREF_USER_ID; import static app.fedilab.android.mastodon.helper.Helper.PREF_USER_INSTANCE; @@ -201,6 +203,15 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { currentToken = sharedpreferences.getString(app.fedilab.android.mastodon.helper.Helper.PREF_USER_TOKEN, null); } currentAccount = new Account(PeertubeMainActivity.this).getConnectedAccount(); + if (currentAccount == null) { + if (currentUserID == null) { + currentUserID = sharedpreferences.getString(PREF_USER_ID, null); + } + if (currentInstance == null) { + currentInstance = sharedpreferences.getString(PREF_USER_INSTANCE, null); + } + currentAccount = new Account(PeertubeMainActivity.this).getUniqAccount(currentUserID, currentInstance); + } } catch (DBException e) { e.printStackTrace(); } @@ -211,7 +222,6 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { finish(); return; } - //If the attached account is null, the app will fetch remote instance to get up-to-date values if (currentAccount != null && currentAccount.peertube_account == null) { try { @@ -221,7 +231,6 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { e.printStackTrace(); } } - Handler mainHandler = new Handler(Looper.getMainLooper()); Runnable myRunnable = () -> { headerMainBinding.accountAcc.setText(String.format("%s@%s", currentAccount.peertube_account.getUsername(), currentAccount.instance)); @@ -240,6 +249,13 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { headerMenuOpen = !headerMenuOpen; manageDrawerMenu(PeertubeMainActivity.this, binding.drawerNavView, headerMainBinding); }); + if (Helper.isLoggedIn()) { + binding.navView.inflateMenu(R.menu.bottom_nav_menu_connected_peertube); + refreshToken(); + + } else { + binding.navView.inflateMenu(R.menu.bottom_nav_menu); + } }; mainHandler.post(myRunnable); }).start(); @@ -353,13 +369,7 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { setTitleCustom(R.string.title_home); - if (Helper.isLoggedIn()) { - binding.navView.inflateMenu(R.menu.bottom_nav_menu_connected_peertube); - refreshToken(); - } else { - binding.navView.inflateMenu(R.menu.bottom_nav_menu); - } peertubeInformation = new PeertubeInformation(); peertubeInformation.setCategories(new LinkedHashMap<>()); peertubeInformation.setLanguages(new LinkedHashMap<>()); @@ -396,8 +406,9 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { getSupportFragmentManager(), android.R.id.content, new FragmentLoginPickInstancePeertube(), null, null, FragmentLoginPickInstancePeertube.class.getName()); } - + mamageNewIntent(PeertubeMainActivity.this, getIntent()); fetchRecentAccounts(PeertubeMainActivity.this, headerMainBinding); + } public DisplayVideosFragment getSubscriptionFragment() { @@ -656,8 +667,18 @@ public class PeertubeMainActivity extends PeertubeBaseMainActivity { recreate(); } } + mamageNewIntent(PeertubeMainActivity.this, intent); } + /*public static void mamageNewIntent(Activity activity, + Intent intent) { + if (intent == null) + return; + String action = intent.getAction(); + if (action != null && action.equalsIgnoreCase("app.fedilab.android.shorcut.compose")) { + CrossActionHelper.doCrossAction(activity, CrossActionHelper.TypeOfCrossAction.COMPOSE, null, null); + } + }*/ @SuppressLint("ApplySharedPref") private void showRadioButtonDialog() { diff --git a/app/src/main/res/drawable/ic_baseline_add_comment_24.xml b/app/src/main/res/drawable/ic_baseline_add_comment_24.xml index e1b7c688..457ed71f 100644 --- a/app/src/main/res/drawable/ic_baseline_add_comment_24.xml +++ b/app/src/main/res/drawable/ic_baseline_add_comment_24.xml @@ -1,10 +1,9 @@ diff --git a/app/src/playstore/res/xml/compose_shortcuts.xml b/app/src/playstore/res/xml/compose_shortcuts.xml index 1357bfe7..881ed1f7 100644 --- a/app/src/playstore/res/xml/compose_shortcuts.xml +++ b/app/src/playstore/res/xml/compose_shortcuts.xml @@ -1,9 +1,9 @@