This commit is contained in:
Profpatsch 2024-04-27 22:10:34 +07:00 committed by GitHub
commit 9dc21b4732
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 139 additions and 110 deletions

View File

@ -136,7 +136,7 @@ public class MainActivity extends AppCompatActivity {
}
ThemeHelper.setDayNightMode(this);
ThemeHelper.setTheme(this, ServiceHelper.getSelectedServiceId(this));
ThemeHelper.setTheme(this, ServiceHelper.getSelectedServiceIdOrFallback(this));
assureCorrectAppLanguage(this);
super.onCreate(savedInstanceState);
@ -203,7 +203,7 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onDrawerOpened(final View drawerView) {
lastService = ServiceHelper.getSelectedServiceId(MainActivity.this);
lastService = ServiceHelper.getSelectedServiceIdOrFallback(MainActivity.this);
}
@Override
@ -211,7 +211,8 @@ public class MainActivity extends AppCompatActivity {
if (servicesShown) {
toggleServices();
}
if (lastService != ServiceHelper.getSelectedServiceId(MainActivity.this)) {
if (lastService
!= ServiceHelper.getSelectedServiceIdOrFallback(MainActivity.this)) {
ActivityCompat.recreate(MainActivity.this);
}
}
@ -228,7 +229,7 @@ public class MainActivity extends AppCompatActivity {
*/
private void addDrawerMenuForCurrentService() throws ExtractionException {
//Tabs
final int currentServiceId = ServiceHelper.getSelectedServiceId(this);
final int currentServiceId = ServiceHelper.getSelectedServiceIdOrFallback(this);
final StreamingService service = NewPipe.getService(currentServiceId);
int kioskMenuItemId = 0;
@ -292,11 +293,11 @@ public class MainActivity extends AppCompatActivity {
private void changeService(final MenuItem item) {
drawerLayoutBinding.navigation.getMenu()
.getItem(ServiceHelper.getSelectedServiceId(this))
.getItem(ServiceHelper.getSelectedServiceIdOrFallback(this))
.setChecked(false);
ServiceHelper.setSelectedServiceId(this, item.getItemId());
drawerLayoutBinding.navigation.getMenu()
.getItem(ServiceHelper.getSelectedServiceId(this))
.getItem(ServiceHelper.getSelectedServiceIdOrFallback(this))
.setChecked(true);
}
@ -318,7 +319,8 @@ public class MainActivity extends AppCompatActivity {
NavigationHelper.openStatisticFragment(getSupportFragmentManager());
break;
default:
final StreamingService currentService = ServiceHelper.getSelectedService(this);
final StreamingService currentService =
ServiceHelper.getSelectedServiceOrFallback(this);
int kioskMenuItemId = 0;
for (final String kioskId : currentService.getKioskList().getAvailableKiosks()) {
if (kioskMenuItemId == item.getItemId()) {
@ -397,7 +399,7 @@ public class MainActivity extends AppCompatActivity {
}
}
drawerLayoutBinding.navigation.getMenu()
.getItem(ServiceHelper.getSelectedServiceId(this))
.getItem(ServiceHelper.getSelectedServiceIdOrFallback(this))
.setChecked(true);
}
@ -468,7 +470,7 @@ public class MainActivity extends AppCompatActivity {
// so it looks like the drawer isn't open when the user returns to MainActivity
mainBinding.getRoot().closeDrawer(GravityCompat.START, false);
try {
final int selectedServiceId = ServiceHelper.getSelectedServiceId(this);
final int selectedServiceId = ServiceHelper.getSelectedServiceIdOrFallback(this);
final String selectedServiceName = NewPipe.getService(selectedServiceId)
.getServiceInfo().getName();
drawerHeaderBinding.drawerHeaderServiceView.setText(selectedServiceName);

View File

@ -62,7 +62,7 @@ class ErrorInfo(
constructor(throwable: Throwable, userAction: UserAction, request: String) :
this(throwable, userAction, SERVICE_NONE, request)
constructor(throwable: Throwable, userAction: UserAction, request: String, serviceId: Int) :
this(throwable, userAction, ServiceHelper.getNameOfServiceById(serviceId), request)
this(throwable, userAction, ServiceHelper.getNameOfServiceByIdOrUnknown(serviceId), request)
constructor(throwable: Throwable, userAction: UserAction, request: String, info: Info?) :
this(throwable, userAction, getInfoServiceName(info), request)
@ -70,7 +70,7 @@ class ErrorInfo(
constructor(throwable: List<Throwable>, userAction: UserAction, request: String) :
this(throwable, userAction, SERVICE_NONE, request)
constructor(throwable: List<Throwable>, userAction: UserAction, request: String, serviceId: Int) :
this(throwable, userAction, ServiceHelper.getNameOfServiceById(serviceId), request)
this(throwable, userAction, ServiceHelper.getNameOfServiceByIdOrUnknown(serviceId), request)
constructor(throwable: List<Throwable>, userAction: UserAction, request: String, info: Info?) :
this(throwable, userAction, getInfoServiceName(info), request)
@ -83,7 +83,7 @@ class ErrorInfo(
throwableList.map { it.stackTraceToString() }.toTypedArray()
private fun getInfoServiceName(info: Info?) =
if (info == null) SERVICE_NONE else ServiceHelper.getNameOfServiceById(info.serviceId)
if (info == null) SERVICE_NONE else ServiceHelper.getNameOfServiceByIdOrUnknown(info.serviceId)
@StringRes
private fun getMessageStringId(

View File

@ -109,7 +109,7 @@ class ErrorPanelHelper(
if (!isNullOrEmpty((errorInfo.throwable as AccountTerminatedException).message)) {
errorServiceInfoTextView.text = context.resources.getString(
R.string.service_provides_reason,
ServiceHelper.getSelectedService(context)?.serviceInfo?.name ?: "<unknown>"
ServiceHelper.getSelectedServiceNameOrUnknown(context)
)
errorServiceInfoTextView.isVisible = true

View File

@ -171,7 +171,7 @@ public class MainFragment extends BaseFragment implements TabLayout.OnTabSelecte
if (item.getItemId() == R.id.action_search) {
try {
NavigationHelper.openSearchFragment(getFM(),
ServiceHelper.getSelectedServiceId(activity), "");
ServiceHelper.getSelectedServiceIdOrFallback(activity), "");
} catch (final Exception e) {
ErrorUtil.showUiErrorSnackbar(this, "Opening search fragment", e);
}

View File

@ -1,6 +1,5 @@
package org.schabi.newpipe.fragments.list.comments;
import static org.schabi.newpipe.util.ServiceHelper.getServiceById;
import android.os.Bundle;
import android.view.LayoutInflater;
@ -23,6 +22,7 @@ import org.schabi.newpipe.util.DeviceUtils;
import org.schabi.newpipe.util.ExtractorHelper;
import org.schabi.newpipe.util.Localization;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.util.ServiceHelper;
import org.schabi.newpipe.util.image.ImageStrategy;
import org.schabi.newpipe.util.image.PicassoHelper;
import org.schabi.newpipe.util.text.TextLinkifier;
@ -107,7 +107,7 @@ public final class CommentRepliesFragment
// setup comment content
TextLinkifier.fromDescription(binding.commentContent, item.getCommentText(),
HtmlCompat.FROM_HTML_MODE_LEGACY, getServiceById(item.getServiceId()),
HtmlCompat.FROM_HTML_MODE_LEGACY, ServiceHelper.getServiceFromInfoItem(item),
item.getUrl(), disposables, null);
return binding.getRoot();

View File

@ -25,7 +25,7 @@ public class DefaultKioskFragment extends KioskFragment {
public void onResume() {
super.onResume();
if (serviceId != ServiceHelper.getSelectedServiceId(requireContext())) {
if (serviceId != ServiceHelper.getSelectedServiceIdOrFallback(requireContext())) {
if (currentWorker != null) {
currentWorker.dispose();
}
@ -36,7 +36,7 @@ public class DefaultKioskFragment extends KioskFragment {
private void updateSelectedDefaultKiosk() {
try {
serviceId = ServiceHelper.getSelectedServiceId(requireContext());
serviceId = ServiceHelper.getSelectedServiceIdOrFallback(requireContext());
final KioskList kioskList = NewPipe.getService(serviceId).getKioskList();
kioskId = kioskList.getDefaultKioskId();

View File

@ -3,7 +3,6 @@ package org.schabi.newpipe.fragments.list.playlist;
import static org.schabi.newpipe.extractor.utils.Utils.isBlank;
import static org.schabi.newpipe.ktx.ViewUtils.animate;
import static org.schabi.newpipe.ktx.ViewUtils.animateHideRecyclerViewAllowingScrolling;
import static org.schabi.newpipe.util.ServiceHelper.getServiceById;
import android.content.Context;
import android.os.Bundle;
@ -52,6 +51,7 @@ import org.schabi.newpipe.util.ExtractorHelper;
import org.schabi.newpipe.util.Localization;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.util.PlayButtonHelper;
import org.schabi.newpipe.util.ServiceHelper;
import org.schabi.newpipe.util.external_communication.ShareUtils;
import org.schabi.newpipe.util.image.PicassoHelper;
import org.schabi.newpipe.util.text.TextEllipsizer;
@ -338,7 +338,7 @@ public class PlaylistFragment extends BaseListInfoFragment<StreamInfoItem, Playl
if (description != null && description != Description.EMPTY_DESCRIPTION
&& !isBlank(description.getContent())) {
final TextEllipsizer ellipsizer = new TextEllipsizer(
headerBinding.playlistDescription, 5, getServiceById(result.getServiceId()));
headerBinding.playlistDescription, 5, ServiceHelper.getServiceFromInfo(result));
ellipsizer.setStateChangeListener(isEllipsized ->
headerBinding.playlistDescriptionReadMore.setText(
Boolean.TRUE.equals(isEllipsized) ? R.string.show_more : R.string.show_less

View File

@ -1,7 +1,5 @@
package org.schabi.newpipe.info_list.holder;
import static org.schabi.newpipe.util.ServiceHelper.getServiceById;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.view.View;
@ -22,6 +20,7 @@ import org.schabi.newpipe.local.history.HistoryRecordManager;
import org.schabi.newpipe.util.DeviceUtils;
import org.schabi.newpipe.util.Localization;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.util.ServiceHelper;
import org.schabi.newpipe.util.external_communication.ShareUtils;
import org.schabi.newpipe.util.image.ImageStrategy;
import org.schabi.newpipe.util.image.PicassoHelper;
@ -122,7 +121,7 @@ public class CommentInfoItemHolder extends InfoItemHolder {
// setup comment content and click listeners to expand/ellipsize it
textEllipsizer.setStreamingService(getServiceById(item.getServiceId()));
textEllipsizer.setStreamingService(ServiceHelper.getServiceFromInfoItem(item));
textEllipsizer.setStreamUrl(item.getUrl());
textEllipsizer.setContent(item.getCommentText());
textEllipsizer.ellipsize();

View File

@ -60,7 +60,8 @@ public class LocalPlaylistStreamItemHolder extends LocalItemHolder {
itemVideoTitleView.setText(item.getStreamEntity().getTitle());
itemAdditionalDetailsView.setText(Localization
.concatenateStrings(item.getStreamEntity().getUploader(),
ServiceHelper.getNameOfServiceById(item.getStreamEntity().getServiceId())));
ServiceHelper.getNameOfServiceByIdOrUnknown(
item.getStreamEntity().getServiceId())));
if (item.getStreamEntity().getDuration() > 0) {
itemDurationView.setText(Localization

View File

@ -76,7 +76,8 @@ public class LocalStatisticStreamItemHolder extends LocalItemHolder {
Localization.shortViewCount(itemBuilder.getContext(), entry.getWatchCount()),
dateTimeFormatter.format(entry.getLatestAccessDate()),
// serviceName
ServiceHelper.getNameOfServiceById(entry.getStreamEntity().getServiceId()));
ServiceHelper.getNameOfServiceByIdOrUnknown(
entry.getStreamEntity().getServiceId()));
}
@Override

View File

@ -40,9 +40,10 @@ public class RemotePlaylistItemHolder extends PlaylistItemHolder {
// Here is where the uploader name is set in the bookmarked playlists library
if (!TextUtils.isEmpty(item.getUploader())) {
itemUploaderView.setText(Localization.concatenateStrings(item.getUploader(),
ServiceHelper.getNameOfServiceById(item.getServiceId())));
ServiceHelper.getNameOfServiceByIdOrUnknown(item.getServiceId())));
} else {
itemUploaderView.setText(ServiceHelper.getNameOfServiceById(item.getServiceId()));
itemUploaderView.setText(
ServiceHelper.getNameOfServiceByIdOrUnknown(item.getServiceId()));
}
PicassoHelper.loadPlaylistThumbnail(item.getThumbnailUrl()).into(itemThumbnailView);

View File

@ -89,7 +89,7 @@ public class SubscriptionsImportFragment extends BaseFragment {
if (supportedSources.isEmpty() && currentServiceId != Constants.NO_SERVICE_ID) {
ErrorUtil.showSnackbar(activity,
new ErrorInfo(new String[]{}, UserAction.SUBSCRIPTION_IMPORT_EXPORT,
ServiceHelper.getNameOfServiceById(currentServiceId),
ServiceHelper.getNameOfServiceByIdOrUnknown(currentServiceId),
"Service does not support importing subscriptions",
R.string.general_error));
activity.finish();

View File

@ -86,7 +86,7 @@ public final class PlayQueueActivity extends AppCompatActivity
protected void onCreate(final Bundle savedInstanceState) {
assureCorrectAppLanguage(this);
super.onCreate(savedInstanceState);
ThemeHelper.setTheme(this, ServiceHelper.getSelectedServiceId(this));
ThemeHelper.setTheme(this, ServiceHelper.getSelectedServiceIdOrFallback(this));
queueControlBinding = ActivityPlayerQueueControlBinding.inflate(getLayoutInflater());
setContentView(queueControlBinding.getRoot());

View File

@ -25,7 +25,7 @@ public class PlayQueueItemBuilder {
holder.itemVideoTitleView.setText(item.getTitle());
}
holder.itemAdditionalDetailsView.setText(Localization.concatenateStrings(item.getUploader(),
ServiceHelper.getNameOfServiceById(item.getServiceId())));
ServiceHelper.getNameOfServiceByIdOrUnknown(item.getServiceId())));
if (item.getDuration() > 0) {
holder.itemDurationView.setText(Localization.getDurationString(item.getDuration()));

View File

@ -1,7 +1,7 @@
package org.schabi.newpipe.settings.tabs;
import static org.schabi.newpipe.settings.tabs.Tab.typeFrom;
import static org.schabi.newpipe.util.ServiceHelper.getNameOfServiceById;
import static org.schabi.newpipe.util.ServiceHelper.getNameOfServiceByIdOrUnknown;
import android.annotation.SuppressLint;
import android.app.Dialog;
@ -385,16 +385,18 @@ public class ChooseTabsFragment extends Fragment {
case DEFAULT_KIOSK:
return getString(R.string.default_kiosk_page_summary);
case KIOSK:
return getNameOfServiceById(((Tab.KioskTab) tab).getKioskServiceId())
return getNameOfServiceByIdOrUnknown(
((Tab.KioskTab) tab).getKioskServiceId())
+ "/" + tab.getTabName(requireContext());
case CHANNEL:
return getNameOfServiceById(((Tab.ChannelTab) tab).getChannelServiceId())
return getNameOfServiceByIdOrUnknown(
((Tab.ChannelTab) tab).getChannelServiceId())
+ "/" + tab.getTabName(requireContext());
case PLAYLIST:
final int serviceId = ((Tab.PlaylistTab) tab).getPlaylistServiceId();
final String serviceName = serviceId == -1
? getString(R.string.local)
: getNameOfServiceById(serviceId);
: getNameOfServiceByIdOrUnknown(serviceId);
return serviceName + "/" + tab.getTabName(requireContext());
default:
return tab.getTabName(requireContext());

View File

@ -505,7 +505,7 @@ public abstract class Tab {
}
private String getDefaultKioskId(final Context context) {
final int kioskServiceId = ServiceHelper.getSelectedServiceId(context);
final int kioskServiceId = ServiceHelper.getSelectedServiceIdOrFallback(context);
String kioskId = "";
try {

View File

@ -7,7 +7,6 @@ import android.content.SharedPreferences;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.preference.PreferenceManager;
@ -16,6 +15,8 @@ import com.grack.nanojson.JsonParser;
import com.grack.nanojson.JsonParserException;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.Info;
import org.schabi.newpipe.extractor.InfoItem;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.ServiceList;
import org.schabi.newpipe.extractor.StreamingService;
@ -32,52 +33,31 @@ public final class ServiceHelper {
@DrawableRes
public static int getIcon(final int serviceId) {
switch (serviceId) {
case 0:
return R.drawable.ic_smart_display;
case 1:
return R.drawable.ic_cloud;
case 2:
return R.drawable.ic_placeholder_media_ccc;
case 3:
return R.drawable.ic_placeholder_peertube;
case 4:
return R.drawable.ic_placeholder_bandcamp;
default:
return R.drawable.ic_circle;
}
return switch (serviceId) {
case 0 -> R.drawable.ic_smart_display;
case 1 -> R.drawable.ic_cloud;
case 2 -> R.drawable.ic_placeholder_media_ccc;
case 3 -> R.drawable.ic_placeholder_peertube;
case 4 -> R.drawable.ic_placeholder_bandcamp;
default -> R.drawable.ic_circle;
};
}
public static String getTranslatedFilterString(final String filter, final Context c) {
switch (filter) {
case "all":
return c.getString(R.string.all);
case "videos":
case "sepia_videos":
case "music_videos":
return c.getString(R.string.videos_string);
case "channels":
return c.getString(R.string.channels);
case "playlists":
case "music_playlists":
return c.getString(R.string.playlists);
case "tracks":
return c.getString(R.string.tracks);
case "users":
return c.getString(R.string.users);
case "conferences":
return c.getString(R.string.conferences);
case "events":
return c.getString(R.string.events);
case "music_songs":
return c.getString(R.string.songs);
case "music_albums":
return c.getString(R.string.albums);
case "music_artists":
return c.getString(R.string.artists);
default:
return filter;
}
return switch (filter) {
case "all" -> c.getString(R.string.all);
case "videos", "sepia_videos", "music_videos" -> c.getString(R.string.videos_string);
case "channels" -> c.getString(R.string.channels);
case "playlists", "music_playlists" -> c.getString(R.string.playlists);
case "tracks" -> c.getString(R.string.tracks);
case "users" -> c.getString(R.string.users);
case "conferences" -> c.getString(R.string.conferences);
case "events" -> c.getString(R.string.events);
case "music_songs" -> c.getString(R.string.songs);
case "music_albums" -> c.getString(R.string.albums);
case "music_artists" -> c.getString(R.string.artists);
default -> filter;
};
}
/**
@ -88,14 +68,11 @@ public final class ServiceHelper {
*/
@StringRes
public static int getImportInstructions(final int serviceId) {
switch (serviceId) {
case 0:
return R.string.import_youtube_instructions;
case 1:
return R.string.import_soundcloud_instructions;
default:
return -1;
}
return switch (serviceId) {
case 0 -> R.string.import_youtube_instructions;
case 1 -> R.string.import_soundcloud_instructions;
default -> -1;
};
}
/**
@ -107,35 +84,53 @@ public final class ServiceHelper {
*/
@StringRes
public static int getImportInstructionsHint(final int serviceId) {
switch (serviceId) {
case 1:
return R.string.import_soundcloud_instructions_hint;
default:
return -1;
if (serviceId == 1) {
return R.string.import_soundcloud_instructions_hint;
}
return -1;
}
public static int getSelectedServiceId(final Context context) {
return Optional.ofNullable(getSelectedService(context))
public static int getSelectedServiceIdOrFallback(final Context context) {
return getSelectedService(context)
.orElse(DEFAULT_FALLBACK_SERVICE)
.getServiceId();
}
@Nullable
public static StreamingService getSelectedService(final Context context) {
public static StreamingService getSelectedServiceOrFallback(final Context context) {
return getSelectedService(context)
.orElse(DEFAULT_FALLBACK_SERVICE);
}
public static Optional<StreamingService> getSelectedService(final Context context) {
final String serviceName = PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.current_service_key),
context.getString(R.string.default_service_value));
try {
return NewPipe.getService(serviceName);
return Optional.of(NewPipe.getService(serviceName));
} catch (final ExtractionException e) {
return null;
return Optional.empty();
}
}
/** Get the name of the selected service.
*
* @param context
* @return The name of the service or {@literal "<unknown>"}
*/
@NonNull
public static String getNameOfServiceById(final int serviceId) {
public static String getSelectedServiceNameOrUnknown(final Context context) {
return getSelectedService(context)
.map(s -> s.getServiceInfo().getName())
.orElse("<unknown>");
}
/** Get the name of the service if it exists.
*
* @param serviceId
* @return The name of the service or {@literal "<unknown>"}
*/
@NonNull
public static String getNameOfServiceByIdOrUnknown(final int serviceId) {
return ServiceList.all().stream()
.filter(s -> s.getServiceId() == serviceId)
.findFirst()
@ -144,17 +139,45 @@ public final class ServiceHelper {
.orElse("<unknown>");
}
/**
* @param serviceId the id of the service
* @return the service corresponding to the provided id
* @throws java.util.NoSuchElementException if there is no service with the provided id
/** Return the service for the given InfoItem.
* <p>
* This should always succeed, except in the (very unlikely) case
* that we remove a service from NewPipeExtractor and the `InfoItem` is deserialized
* from an old version where the service still existed.
* <p>
* NB: this function should exist as member on {@link InfoItem}.
*
* @param infoItem
* @param <Item>
* @return The service.
*/
@NonNull
public static StreamingService getServiceById(final int serviceId) {
return ServiceList.all().stream()
.filter(s -> s.getServiceId() == serviceId)
.findFirst()
.orElseThrow();
public static <Item extends InfoItem> StreamingService getServiceFromInfoItem(
final Item infoItem) {
try {
return NewPipe.getService(infoItem.getServiceId());
} catch (final ExtractionException e) {
throw new AssertionError("InfoItem should never have a bad service id");
}
}
/** Return the service for the given Info.
* <p>
* This should always succeed, except in the (very unlikely) case
* that we remove a service from NewPipeExtractor and the `Info` is deserialized
* from an old version where the service still existed.
* <p>
* NB: this function should exist as member on {@link Info}.
*
* @param info
* @param <Item>
* @return The service.
*/
public static <Item extends Info> StreamingService getServiceFromInfo(final Item info) {
try {
return NewPipe.getService(info.getServiceId());
} catch (final ExtractionException e) {
throw new AssertionError("InfoItem should never have a bad service id");
}
}
public static void setSelectedServiceId(final Context context, final int serviceId) {