SponsorBlock: Codestyle fixes

This brings the SponsorBlock patches in-line with the NewPipe Codestyle standards.
This commit is contained in:
polymorphicshade 2020-05-14 21:06:30 -06:00
parent c69ce3253f
commit d67a8e1ae2
9 changed files with 125 additions and 81 deletions

View file

@ -32,15 +32,16 @@ import okhttp3.Response;
import okhttp3.ResponseBody;
public class SponsorBlockApiTask extends AsyncTask<String, Void, JSONObject> {
private static final Application app = App.getApp();
private static final String sponsorBlockApiUrl = "https://api.sponsor.ajay.app/api/";
private static final int timeoutPeriod = 30;
private static final Application APP = App.getApp();
private static final String SPONSOR_BLOCK_API_URL = "https://api.sponsor.ajay.app/api/";
private static final int TIMEOUT_PERIOD = 30;
private static final String TAG = SponsorBlockApiTask.class.getSimpleName();
private static final boolean DEBUG = MainActivity.DEBUG;
private OkHttpClient client;
// api methods
public SponsorTimeInfo getVideoSponsorTimes(String url) throws ExecutionException, InterruptedException, JSONException {
public SponsorTimeInfo getVideoSponsorTimes(final String url) throws ExecutionException,
InterruptedException, JSONException {
String videoId = parseIdFromUrl(url);
String apiSuffix = "getVideoSponsorTimes?videoID=" + videoId;
@ -63,35 +64,42 @@ public class SponsorBlockApiTask extends AsyncTask<String, Void, JSONObject> {
return result;
}
public void postVideoSponsorTimes(String url, double startTime, double endTime, String userId) {
if (userId == null) {
userId = getRandomUserId();
}
public void postVideoSponsorTimes(final String url, final double startTime,
final double endTime, final String userId) {
double dStartTime = startTime / 1000.0;
double dEndTime = endTime / 1000.0;
String videoId = parseIdFromUrl(url);
String apiSuffix = "postVideoSponsorTimes?videoID=" + videoId + "&startTime=" + dStartTime + "&endTime=" + dEndTime + "&userID=" + userId;
String apiSuffix = "postVideoSponsorTimes?videoID="
+ videoId
+ "&startTime="
+ dStartTime
+ "&endTime="
+ dEndTime
+ "&userID=" + (userId == null
? getRandomUserId()
: userId);
execute(apiSuffix);
}
// task methods
@Override
protected JSONObject doInBackground(String... strings) {
if (isCancelled() || !isConnected()) return null;
protected JSONObject doInBackground(final String... strings) {
if (isCancelled() || !isConnected()) {
return null;
}
try {
if (client == null) {
client = getUnsafeOkHttpClient()
.newBuilder()
.readTimeout(timeoutPeriod, TimeUnit.SECONDS)
.readTimeout(TIMEOUT_PERIOD, TimeUnit.SECONDS)
.build();
}
Request request = new Request.Builder()
.url(sponsorBlockApiUrl + strings[0])
.url(SPONSOR_BLOCK_API_URL + strings[0])
.build();
Response response = client.newCall(request).execute();
@ -101,9 +109,10 @@ public class SponsorBlockApiTask extends AsyncTask<String, Void, JSONObject> {
? null
: new JSONObject(responseBody.string());
}
catch (Exception ex) {
if (DEBUG) Log.w(TAG, Log.getStackTraceString(ex));
} catch (Exception ex) {
if (DEBUG) {
Log.w(TAG, Log.getStackTraceString(ex));
}
}
return null;
@ -111,26 +120,31 @@ public class SponsorBlockApiTask extends AsyncTask<String, Void, JSONObject> {
// helper methods
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
ConnectivityManager cm =
(ConnectivityManager) APP.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnected();
}
private OkHttpClient getUnsafeOkHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
final TrustManager[] trustAllCerts = new TrustManager[]{
private OkHttpClient getUnsafeOkHttpClient()
throws NoSuchAlgorithmException, KeyManagementException {
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
public void checkClientTrusted(final java.security.cert.X509Certificate[] chain,
final String authType) {
}
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
public void checkServerTrusted(final java.security.cert.X509Certificate[] chain,
final String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
return new java.security.cert.X509Certificate[] {};
}
}
};
@ -147,14 +161,13 @@ public class SponsorBlockApiTask extends AsyncTask<String, Void, JSONObject> {
.build();
}
private String parseIdFromUrl(String youTubeUrl) {
private String parseIdFromUrl(final String youTubeUrl) {
String pattern = "(?<=youtu.be/|watch\\?v=|/videos/|embed/)[^#&?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(youTubeUrl);
if (matcher.find()) {
return matcher.group();
}
else {
} else {
return null;
}
}
@ -171,4 +184,4 @@ public class SponsorBlockApiTask extends AsyncTask<String, Void, JSONObject> {
return salt.toString();
}
}
}

View file

@ -667,7 +667,8 @@ public abstract class BasePlayer implements
simpleExoPlayer.getBufferedPercentage()
);
if (mPrefs.getBoolean(context.getString(R.string.sponsorblock_enable), false) && sponsorTimeInfo != null) {
if (mPrefs.getBoolean(context.getString(R.string.sponsorblock_enable), false)
&& sponsorTimeInfo != null) {
int skipTo = sponsorTimeInfo.getSponsorEndTimeFromProgress(currentProgress);
if (skipTo == 0) {
@ -677,19 +678,24 @@ public abstract class BasePlayer implements
seekTo(skipTo);
if (mPrefs.getBoolean(context.getString(R.string.sponsorblock_notifications), false)) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, context.getString(R.string.notification_channel_id))
.setOngoing(false)
.setSmallIcon(R.drawable.ic_sponsor_block)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(context.getString(R.string.settings_category_sponsorblock))
.setContentText(context.getString(R.string.sponsorblock_skipped_sponsor) + " \uD83D\uDC4D");
NotificationCompat.Builder notificationBuilder = new NotificationCompat
.Builder(context, context.getString(R.string.notification_channel_id))
.setOngoing(false)
.setSmallIcon(R.drawable.ic_sponsor_block)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(context.getString(R.string.settings_category_sponsorblock))
.setContentText(context.getString(R.string.sponsorblock_skipped_sponsor)
+ " \uD83D\uDC4D");
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.getApp());
NotificationManagerCompat notificationManager = NotificationManagerCompat
.from(App.getApp());
notificationManager.notify(0, notificationBuilder.build());
}
if (DEBUG)
Log.d("SPONSOR_BLOCK", "Skipped sponsor: currentProgress = [" + currentProgress + "], skipped to = [" + skipTo + "]");
if (DEBUG) {
Log.d("SPONSOR_BLOCK", "Skipped sponsor: currentProgress = ["
+ currentProgress + "], skipped to = [" + skipTo + "]");
}
}
}
@ -1057,8 +1063,7 @@ public abstract class BasePlayer implements
if (mPrefs.getBoolean(context.getString(R.string.sponsorblock_enable), false)) {
try {
sponsorTimeInfo = new SponsorBlockApiTask().getVideoSponsorTimes(getVideoUrl());
}
catch (Exception e) {
} catch (Exception e) {
Log.e("SPONSOR_BLOCK", "Error getting video sponsor times.", e);
}
}
@ -1598,7 +1603,7 @@ public abstract class BasePlayer implements
return sponsorTimeInfo;
}
public void setSponsorTimeInfo(SponsorTimeInfo sponsorTimeInfo) {
public void setSponsorTimeInfo(final SponsorTimeInfo sponsorTimeInfo) {
this.sponsorTimeInfo = sponsorTimeInfo;
}
}

View file

@ -92,8 +92,8 @@ import org.schabi.newpipe.util.ShareUtils;
import org.schabi.newpipe.util.SponsorTimeInfo;
import org.schabi.newpipe.util.StateSaver;
import org.schabi.newpipe.util.ThemeHelper;
import org.schabi.newpipe.views.FocusOverlayView;
import org.schabi.newpipe.util.TimeFrame;
import org.schabi.newpipe.views.FocusOverlayView;
import org.schabi.newpipe.views.MarkableSeekBar;
import org.schabi.newpipe.views.SeekBarMarker;
@ -596,7 +596,7 @@ public final class MainVideoPlayer extends AppCompatActivity
this.switchBackgroundButton = view.findViewById(R.id.switchBackground);
this.muteButton = view.findViewById(R.id.switchMute);
this.submitSponsorTimesButton = rootView.findViewById(R.id.submitSponsorTimes);
this.submitSponsorTimesButton = view.findViewById(R.id.submitSponsorTimes);
this.submitSponsorTimesButton.setTag(false);
this.submitSponsorTimesButton.setOnLongClickListener(v -> {
onSponsorBlockButtonLongClicked();
@ -837,11 +837,16 @@ public final class MainVideoPlayer extends AppCompatActivity
}
private void onSponsorBlockButtonClicked() {
if (DEBUG) Log.d(TAG, "onSponsorBlockButtonClicked() called");
if (playerImpl.getPlayer() == null) return;
if (DEBUG) {
Log.d(TAG, "onSponsorBlockButtonClicked() called");
}
if (playerImpl.getPlayer() == null) {
return;
}
if ((boolean) submitSponsorTimesButton.getTag()) {
TimeFrame customTimeFrame = new TimeFrame(customSponsorStartTime, simpleExoPlayer.getCurrentPosition());
TimeFrame customTimeFrame =
new TimeFrame(customSponsorStartTime, simpleExoPlayer.getCurrentPosition());
customTimeFrame.tag = "custom";
SponsorTimeInfo sponsorTimeInfo = getSponsorTimeInfo();
@ -853,7 +858,9 @@ public final class MainVideoPlayer extends AppCompatActivity
sponsorTimeInfo.timeFrames.add(customTimeFrame);
SeekBarMarker marker = new SeekBarMarker(customTimeFrame.startTime, customTimeFrame.endTime, (int) simpleExoPlayer.getDuration(), Color.BLUE);
SeekBarMarker marker =
new SeekBarMarker(customTimeFrame.startTime, customTimeFrame.endTime,
(int) simpleExoPlayer.getDuration(), Color.BLUE);
marker.tag = "custom";
MarkableSeekBar markableSeekBar = (MarkableSeekBar) getPlaybackSeekBar();
@ -862,8 +869,7 @@ public final class MainVideoPlayer extends AppCompatActivity
submitSponsorTimesButton.setTag(false);
submitSponsorTimesButton.setImageResource(R.drawable.ic_sponsor_block);
}
else {
} else {
customSponsorStartTime = (int) simpleExoPlayer.getCurrentPosition();
submitSponsorTimesButton.setTag(true);
@ -872,8 +878,12 @@ public final class MainVideoPlayer extends AppCompatActivity
}
private void onSponsorBlockButtonLongClicked() {
if (DEBUG) Log.d(TAG, "onSponsorBlockButtonLongClicked() called");
if (playerImpl.getPlayer() == null) return;
if (DEBUG) {
Log.d(TAG, "onSponsorBlockButtonLongClicked() called");
}
if (playerImpl.getPlayer() == null) {
return;
}
ArrayList<SeekBarMarker> customMarkers = new ArrayList<>();
ArrayList<TimeFrame> customTimeFrames = new ArrayList<>();
@ -901,12 +911,14 @@ public final class MainVideoPlayer extends AppCompatActivity
.Builder(context)
.setMessage("Submit " + customMarkers.size() + " sponsor time segment(s)?")
.setPositiveButton("Yes", (dialog, id) -> {
String username = defaultPreferences.getString(getString(R.string.sponsorblock_username), null);
String username = defaultPreferences
.getString(getString(R.string.sponsorblock_username), null);
for (TimeFrame timeFrame : customTimeFrames) {
try {
new SponsorBlockApiTask().postVideoSponsorTimes(getVideoUrl(), timeFrame.startTime, timeFrame.endTime, username);
}
catch (Exception e) {
new SponsorBlockApiTask()
.postVideoSponsorTimes(getVideoUrl(), timeFrame.startTime,
timeFrame.endTime, username);
} catch (Exception e) {
Log.e("SPONSOR_BLOCK", "Error getting video sponsor times.", e);
}
}
@ -962,7 +974,7 @@ public final class MainVideoPlayer extends AppCompatActivity
} else if (v.getId() == submitSponsorTimesButton.getId()) {
onSponsorBlockButtonClicked();
}else if (v.getId() == closeButton.getId()) {
} else if (v.getId() == closeButton.getId()) {
onPlaybackShutdown();
return;
} else if (v.getId() == kodiButton.getId()) {

View file

@ -648,11 +648,14 @@ public abstract class VideoPlayer extends BasePlayer
MarkableSeekBar markableSeekBar = (MarkableSeekBar) playbackSeekBar;
for (TimeFrame timeFrame : sponsorTimeInfo.timeFrames) {
SeekBarMarker seekBarMarker = new SeekBarMarker(timeFrame.startTime, timeFrame.endTime, (int) simpleExoPlayer.getDuration(), Color.GREEN);
SeekBarMarker seekBarMarker =
new SeekBarMarker(timeFrame.startTime, timeFrame.endTime,
(int) simpleExoPlayer.getDuration(), Color.GREEN);
markableSeekBar.seekBarMarkers.add(seekBarMarker);
markableSeekBar.invalidate();
Log.d("SPONSOR_BLOCK", "Progress bar marker: " + seekBarMarker.percentStart + ", " + seekBarMarker.percentEnd);
Log.d("SPONSOR_BLOCK", "Progress bar marker: "
+ seekBarMarker.percentStart + ", " + seekBarMarker.percentEnd);
}
}

View file

@ -140,16 +140,20 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
return true;
});
Preference sponsorblockStatusPreference = findPreference(getString(R.string.sponsorblock_status));
Preference sponsorblockStatusPreference =
findPreference(getString(R.string.sponsorblock_status));
sponsorblockStatusPreference.setOnPreferenceClickListener((Preference p) -> {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://status.sponsor.ajay.app/"));
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://status.sponsor.ajay.app/"));
startActivity(i);
return true;
});
Preference sponsorblockLeaderboardsPreference = findPreference(getString(R.string.sponsorblock_leaderboards));
Preference sponsorblockLeaderboardsPreference =
findPreference(getString(R.string.sponsorblock_leaderboards));
sponsorblockLeaderboardsPreference.setOnPreferenceClickListener((Preference p) -> {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://api.sponsor.ajay.app/stats"));
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://api.sponsor.ajay.app/stats"));
startActivity(i);
return true;
});

View file

@ -5,23 +5,23 @@ import java.util.ArrayList;
public class SponsorTimeInfo {
public ArrayList<TimeFrame> timeFrames = new ArrayList<>();
public int getSponsorEndTimeFromProgress(int progress) {
public int getSponsorEndTimeFromProgress(final int progress) {
if (timeFrames == null) {
return 0;
}
for (TimeFrame timeFrames : timeFrames) {
if (progress < timeFrames.startTime) {
for (TimeFrame t : timeFrames) {
if (progress < t.startTime) {
continue;
}
if (progress > timeFrames.endTime) {
if (progress > t.endTime) {
continue;
}
return (int) Math.ceil((timeFrames.endTime));
return (int) Math.ceil((t.endTime));
}
return 0;
}
}
}

View file

@ -5,8 +5,8 @@ public class TimeFrame {
public double endTime;
public Object tag;
public TimeFrame(double startTime, double endTime) {
public TimeFrame(final double startTime, final double endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
}
}

View file

@ -15,19 +15,21 @@ public class MarkableSeekBar extends AppCompatSeekBar {
public ArrayList<SeekBarMarker> seekBarMarkers = new ArrayList<>();
private RectF markerRect = new RectF();
public MarkableSeekBar(Context context) {
public MarkableSeekBar(final Context context) {
super(context);
}
public MarkableSeekBar(Context context, AttributeSet attrs) {
public MarkableSeekBar(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public MarkableSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
public MarkableSeekBar(final Context context,
final AttributeSet attrs,
final int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected synchronized void onDraw(Canvas canvas) {
protected synchronized void onDraw(final Canvas canvas) {
super.onDraw(canvas);
Drawable progressDrawable = getProgressDrawable();
@ -39,12 +41,14 @@ public class MarkableSeekBar extends AppCompatSeekBar {
for (int i = 0; i < seekBarMarkers.size(); i++) {
SeekBarMarker marker = seekBarMarkers.get(i);
markerRect.left = width - (float) Math.floor(width * (1.0 - marker.percentStart)) + getPaddingStart();
markerRect.left = width - (float) Math.floor(width * (1.0 - marker.percentStart))
+ getPaddingStart();
markerRect.top = progressDrawableBounds.bottom - height - 1;
markerRect.right = width - (float) Math.ceil(width * (1.0 - marker.percentEnd)) + getPaddingStart();
markerRect.right = width - (float) Math.ceil(width * (1.0 - marker.percentEnd))
+ getPaddingStart();
markerRect.bottom = progressDrawableBounds.bottom;
canvas.drawRect(markerRect, marker.paint);
}
}
}
}

View file

@ -10,7 +10,10 @@ public class SeekBarMarker {
public Paint paint;
public Object tag;
public SeekBarMarker(double startTime, double endTime, int maxTime, int color) {
public SeekBarMarker(final double startTime,
final double endTime,
final int maxTime,
final int color) {
this.startTime = startTime;
this.endTime = endTime;
this.percentStart = Math.round((startTime / maxTime) * 100.0) / 100.0;
@ -19,15 +22,15 @@ public class SeekBarMarker {
initPaint(color);
}
public SeekBarMarker(double percentStart, double percentEnd, int color) {
public SeekBarMarker(final double percentStart, final double percentEnd, final int color) {
this.percentStart = percentStart;
this.percentEnd = percentEnd;
initPaint(color);
}
private void initPaint(int color) {
private void initPaint(final int color) {
this.paint = new Paint();
this.paint.setColor(color);
}
}
}