you've been waiting for this moment for so long

This commit is contained in:
Kuba Szczodrzyński
2019-09-18 22:29:09 +02:00
parent e2c92c3db5
commit 31588731da
758 changed files with 87594 additions and 0 deletions

View File

@ -0,0 +1,199 @@
package pl.szczodrzynski.edziennik.utils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
public class Anim {
public static void expand(View v, Integer duration, Animation.AnimationListener animationListener) {
v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
int targetHeight = v.getMeasuredHeight();
//Log.d("Anim", "targetHeight="+targetHeight);
v.setVisibility(View.VISIBLE);
v.getLayoutParams().height = 0;
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1.0f
? LinearLayout.LayoutParams.WRAP_CONTENT//(int)(targetHeight * interpolatedTime)
: (int)(targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
if (duration == null) {
a.setDuration((long) ((int) (((float) targetHeight) / v.getContext().getResources().getDisplayMetrics().density)));
} else {
a.setDuration((long) duration);
}
if (animationListener != null ) {
a.setAnimationListener(animationListener);
}
v.startAnimation(a);
}
public static void collapse(View v, Integer duration, Animation.AnimationListener animationListener) {
int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1.0f) {
v.setVisibility(View.GONE);
return;
}
v.getLayoutParams().height = initialHeight - ((int) (((float) initialHeight) * interpolatedTime));
v.requestLayout();
}
public boolean willChangeBounds() {
return true;
}
};
if (duration == null) {
a.setDuration((long) ((int) (((float) initialHeight) / v.getContext().getResources().getDisplayMetrics().density)));
} else {
a.setDuration((long) duration);
}
if (animationListener != null ) {
a.setAnimationListener(animationListener);
}
v.startAnimation(a);
}
public static void fadeIn(View v, Integer duration, Animation.AnimationListener animationListener) {
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
fadeIn.setDuration(duration);
fadeIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
v.setVisibility(View.VISIBLE);
if (animationListener != null) {
animationListener.onAnimationStart(animation);
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationRepeat(animation);
}
}
});
v.startAnimation(fadeIn);
}
public static void fadeOut(View v, Integer duration, Animation.AnimationListener animationListener) {
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
fadeOut.setDuration(duration);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationStart(animation);
}
}
@Override
public void onAnimationEnd(Animation animation) {
v.setVisibility(View.INVISIBLE);
if (animationListener != null) {
animationListener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationRepeat(animation);
}
}
});
v.startAnimation(fadeOut);
}
public static void scaleView(View v, Integer duration, Animation.AnimationListener animationListener, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
1f, 1f, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 0f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(duration);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationStart(animation);
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
if (animationListener != null) {
animationListener.onAnimationRepeat(animation);
}
}
});
v.startAnimation(anim);
}
public static class ResizeAnimation extends Animation {
private View mView;
private float mToHeight;
private float mFromHeight;
private float mToWidth;
private float mFromWidth;
private float width;
private float height;
public ResizeAnimation(View v, float fromWidth, float fromHeight, float toWidth, float toHeight) {
mToHeight = toHeight;
mToWidth = toWidth;
mFromHeight = fromHeight;
mFromWidth = fromWidth;
mView = v;
width = v.getWidth();
height = v.getHeight();
setDuration(300);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float height =
(mToHeight - mFromHeight) * interpolatedTime + mFromHeight;
float width = (mToWidth - mFromWidth) * interpolatedTime + mFromWidth;
ViewGroup.LayoutParams p = mView.getLayoutParams();
p.width = (int) (width * this.width);
p.height = (int) (height * this.height);
mView.requestLayout();
}
}
}

View File

@ -0,0 +1,114 @@
package pl.szczodrzynski.edziennik.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
public class BadgeDrawable extends Drawable {
private float mTextSize;
private Paint mBadgePaint;
private Paint mTextPaint;
private Rect mTxtRect = new Rect();
private String mCount = "";
private boolean mTextEnabled = true;
private boolean mWillDraw = false;
public BadgeDrawable(Context context) {
mTextSize = dpToPx(context, 11); //text size
mBadgePaint = new Paint();
mBadgePaint.setColor(Color.RED);
mBadgePaint.setAntiAlias(true);
mBadgePaint.setStyle(Paint.Style.FILL);
mTextPaint = new Paint();
mTextPaint.setColor(Color.WHITE);
mTextPaint.setTypeface(Typeface.DEFAULT);
mTextPaint.setTextSize(mTextSize);
mTextPaint.setAntiAlias(true);
mTextPaint.setTextAlign(Paint.Align.CENTER);
}
private float dpToPx(Context context, float value) {
Resources r = context.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, r.getDisplayMetrics());
return px;
}
@Override
public void draw(Canvas canvas) {
if (!mWillDraw) {
return;
}
Rect bounds = getBounds();
float width = bounds.right - bounds.left;
float height = bounds.bottom - bounds.top;
// Position the badge in the top-right quadrant of the icon.
/*Using Math.max rather than Math.min */
// float radius = ((Math.max(width, height) / 2)) / 2;
float radius = width * 0.15f;
float centerX = (width - radius - 1) +10;
float centerY = radius -5;
if (mTextEnabled) {
if(mCount.length() <= 2){
// Draw badge circle.
canvas.drawCircle(centerX, centerY, radius+13, mBadgePaint);
}
else{
canvas.drawCircle(centerX, centerY, radius+16, mBadgePaint);
}
// Draw badge count text inside the circle.
mTextPaint.getTextBounds(mCount, 0, mCount.length(), mTxtRect);
float textHeight = mTxtRect.bottom - mTxtRect.top;
float textY = centerY + (textHeight / 2f);
if (mCount.length() > 2)
canvas.drawText("99+", centerX, textY, mTextPaint);
else
canvas.drawText(mCount, centerX, textY, mTextPaint);
}
else {
canvas.drawCircle(centerX, centerY, radius+5, mBadgePaint);
}
}
/*
Sets the count (i.e notifications) to display.
*/
public void setCount(String count) {
mCount = count;
// Only draw a badge if there are notifications.
mWillDraw = !count.equalsIgnoreCase("0");
invalidateSelf();
}
@Override
public void setAlpha(int alpha) {
// do nothing
}
public void setTextEnabled(boolean mTextEnabled) {
this.mTextEnabled = mTextEnabled;
}
@Override
public void setColorFilter(ColorFilter cf) {
// do nothing
}
@Override
public int getOpacity() {
return PixelFormat.UNKNOWN;
}
}

View File

@ -0,0 +1,258 @@
package pl.szczodrzynski.edziennik.utils;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.Build;
import androidx.core.graphics.ColorUtils;
import pl.szczodrzynski.edziennik.datamodels.Grade;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Random;
public class Colors {
public static int legibleTextColor(int bgColor){
return (ColorUtils.calculateLuminance(bgColor) > 0.5 ? 0xff000000 : 0xffffffff);
}
private static int hsvToColor(float h, float s, float v) {
float[] hsv = new float[]{h*360, s, v};
return Color.HSVToColor(hsv);
}
public static int stringToColor(String s) {
long seed = 1;
try {
MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(s.getBytes());
byte[] bytes = digest.digest();
for (byte aByte : bytes) {
if (aByte % 7 == 0) {
seed += aByte;
}
if (aByte % 3 == 0) {
seed -= aByte;
}
if (aByte % 4 == 0) {
seed *= aByte;
}
if (aByte % 5 == 0) {
seed /= aByte;
}
}
} catch (Exception e) {
seed = 1234;
//Log.d("StringToColor", "Failed.");
}
//Log.d("StringToColor", "Seed "+seed);
float hue = new Random(seed).nextFloat();
hue += 0.618033988749895f; // golden_ratio_conjugate
hue %= 1.0f;
//Log.d("StringToColor", "Hue "+hue);
return hsvToColor(hue, 0.5f, 0.95f);
}
private static int getRandomNumberInRange(int min, int max, long seed) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random(seed);
return r.nextInt((max - min) + 1) + min;
}
public static final int[] materialColors = {
0xFFE57373, 0xFFEF5350, 0xFFF44336, 0xFFE53935, 0xFFD32F2F, 0xFFC62828, 0xFFFF5252, 0xFFFF1744, 0xFFD50000, 0xFFF06292, 0xFFEC407A, 0xFFE91E63, 0xFFD81B60, 0xFFC2185B, 0xFFAD1457,
0xFFFF4081, 0xFFF50057, 0xFFC51162, 0xFFBA68C8, 0xFFAB47BC, 0xFF9C27B0, 0xFF8E24AA, 0xFF7B1FA2, 0xFF6A1B9A, 0xFFE040FB, 0xFFD500F9, 0xFFAA00FF, 0xFF9575CD, 0xFF7E57C2, 0xFF673AB7,
0xFF5E35B1, 0xFF512DA8, 0xFF4527A0, 0xFF7C4DFF, 0xFF651FFF, 0xFF6200EA, 0xFF7986CB, 0xFF5C6BC0, 0xFF3F51B5, 0xFF3949AB, 0xFF303F9F, 0xFF283593, 0xFF536DFE, 0xFF3D5AFE, 0xFF304FFE,
0xFF64B5F6, 0xFF42A5F5, 0xFF2196F3, 0xFF1E88E5, 0xFF1976D2, 0xFF1565C0, 0xFF448AFF, 0xFF2979FF, 0xFF2962FF, 0xFF4FC3F7, 0xFF29B6F6, 0xFF03A9F4, 0xFF039BE5, 0xFF0288D1, 0xFF0277BD,
0xFF40C4FF, 0xFF00B0FF, 0xFF0091EA, 0xFF4DD0E1, 0xFF26C6DA, 0xFF00BCD4, 0xFF00ACC1, 0xFF0097A7, 0xFF00838F, 0xFF18FFFF, 0xFF00E5FF, 0xFF00B8D4, 0xFF4DB6AC, 0xFF26A69A, 0xFF009688,
0xFF00897B, 0xFF00796B, 0xFF00695C, 0xFF64FFDA, 0xFF1DE9B6, 0xFF00BFA5, 0xFF81C784, 0xFF66BB6A, 0xFF4CAF50, 0xFF43A047, 0xFF388E3C, 0xFF2E7D32, 0xFF69F0AE, 0xFF00E676, 0xFF00C853,
0xFFAED581, 0xFF9CCC65, 0xFF8BC34A, 0xFF7CB342, 0xFF689F38, 0xFF558B2F, 0xFFB2FF59, 0xFF76FF03, 0xFF64DD17, 0xFFDCE775, 0xFFD4E157, 0xFFCDDC39, 0xFFC0CA33, 0xFFAFB42B, 0xFF9E9D24,
0xFFEEFF41, 0xFFC6FF00, 0xFFAEEA00, 0xFFFFF176, 0xFFFFEE58, 0xFFFFEB3B, 0xFFFDD835, 0xFFFBC02D, 0xFFF9A825, 0xFFF57F17, 0xFFFFFF00, 0xFFFFEA00, 0xFFFFD600, 0xFFFFD54F, 0xFFFFCA28,
0xFFFFC107, 0xFFFFB300, 0xFFFFA000, 0xFFFF8F00, 0xFFFF6F00, 0xFFFFD740, 0xFFFFC400, 0xFFFFAB00, 0xFFFFB74D, 0xFFFFA726, 0xFFFF9800, 0xFFFB8C00, 0xFFF57C00, 0xFFEF6C00, 0xFFE65100,
0xFFFFAB40, 0xFFFF9100, 0xFFFF6D00, 0xFFFF8A65, 0xFFFF7043, 0xFFFF5722, 0xFFF4511E, 0xFFE64A19, 0xFFD84315, 0xFFBF360C, 0xFFFF6E40, 0xFFFF3D00, 0xFFDD2C00, 0xFF8D6E63, 0xFF795548,
0xFF6D4C41
};
public static int stringToMaterialColor(String s) {
long seed = 1;
try {
MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(s.getBytes());
byte[] bytes = digest.digest();
for (byte aByte : bytes) {
if (aByte % 7 == 0) {
seed += aByte;
}
if (aByte % 3 == 0) {
seed -= aByte;
}
if (aByte % 4 == 0) {
seed *= aByte;
}
if (aByte % 5 == 0) {
seed /= aByte;
}
}
} catch (Exception e) {
seed = 1234;
}
return materialColors[getRandomNumberInRange(0, materialColors.length-1, seed)];
}
public static int gradeToColor(Grade grade)
{
if (grade.type == Grade.TYPE_BEHAVIOUR) {
return grade.value < 0 ? 0xfff44336 : grade.value > 0 ? 0xff4caf50 : 0xffbdbdbd;
}
else if (grade.type == Grade.TYPE_POINT) {
return Color.parseColor("#"+gradeValueToColorStr(grade.value/grade.valueMax*100));
}
else if (grade.type == Grade.TYPE_DESCRIPTIVE || grade.type == Grade.TYPE_TEXT) {
return grade.color;
}
else {
return Color.parseColor("#"+gradeNameToColorStr(grade.name));
}
}
public static int gradeNameToColor(String grade)
{
return Color.parseColor("#"+gradeNameToColorStr(grade));
}
private static String gradeNameToColorStr(String grade) {
switch (grade.toLowerCase()) {
case "+":
case "++":
case "+++":
return "4caf50";
case "-":
case "-,":
case "-,-,":
case "np":
case "np.":
case "npnp":
case "np,":
case "np,np,":
case "bs":
case "nk":
return "ff7043";
case "1-":
case "1":
case "f":
return "ff0000";
case "1+":
case "ef":
return "ff3d00";
case "2-":
case "2":
case "e":
return "ff9100";
case "2+":
case "de":
return "ffab00";
case "3-":
case "3":
case "d":
return "ffff00";
case "3+":
case "cd":
return "c6ff00";
case "4-":
case "4":
case "c":
return "76ff03";
case "4+":
case "bc":
return "64dd17";
case "5-":
case "5":
case "b":
return "00c853";
case "5+":
case "ab":
return "00bfa5";
case "6-":
case "6":
case "a":
return "2196f3";
case "6+":
case "a+":
return "0091ea";
}
return "bdbdbd";
}
public static int gradeValueToColor(float grade)
{
return Color.parseColor("#"+gradeValueToColorStr(grade));
}
private static String gradeValueToColorStr(float grade) {
if (grade < 30) // 1
return "d50000";
else if (grade < 50) // 2
return "ff5722";
else if (grade < 75) // 3
return "ff9100";
else if (grade < 90) // 4
return "ffd600";
else if (grade < 98) // 5
return "00c853";
else if (grade <= 100) // 6
return "0091ea";
else // 6+
return "2962ff";
}
public static Drawable getAdaptiveBackgroundDrawable(int normalColor, int pressedColor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new RippleDrawable(ColorStateList.valueOf(pressedColor),
null, getRippleMask(normalColor));
} else {
return getStateListDrawable(Color.TRANSPARENT, pressedColor);
}
}
private static Drawable getRippleMask(int color) {
float[] outerRadii = new float[8];
// 3 is radius of final ripple,
// instead of 3 you can give required final radius
Arrays.fill(outerRadii, 3);
RoundRectShape r = new RoundRectShape(outerRadii, null, null);
ShapeDrawable shapeDrawable = new ShapeDrawable(r);
shapeDrawable.getPaint().setColor(color);
return shapeDrawable;
}
private static StateListDrawable getStateListDrawable(
int normalColor, int pressedColor) {
StateListDrawable states = new StateListDrawable();
states.addState(new int[]{android.R.attr.state_pressed},
new ColorDrawable(pressedColor));
states.addState(new int[]{android.R.attr.state_focused},
new ColorDrawable(pressedColor));
states.addState(new int[]{android.R.attr.state_activated},
new ColorDrawable(pressedColor));
states.addState(new int[]{},
new ColorDrawable(normalColor));
return states;
}
}

View File

@ -0,0 +1,166 @@
package pl.szczodrzynski.edziennik.utils;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import java.util.List;
public class PermissionChecker {
private Context mContext;
public PermissionChecker(Context context) {
mContext = context;
}
@TargetApi(Build.VERSION_CODES.M)
public boolean canDrawOverOtherApps() {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(mContext);
}
@TargetApi(Build.VERSION_CODES.M)
public void requestDrawOverOtherApps() {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mContext.startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + mContext.getPackageName())));
}
}
@TargetApi(Build.VERSION_CODES.M)
public Intent intentDrawOverOtherApps() {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + mContext.getPackageName()));
}
return null;
}
public boolean canGetUsageStats() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
int mode = 0;
try {
mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), mContext.getPackageName());
} catch (java.lang.IllegalArgumentException e) {
e.printStackTrace();
}
boolean granted = false;
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = (mContext.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
} else {
granted = (mode == AppOpsManager.MODE_ALLOWED);
}
return granted;
}
else
{
return true;
}
}
public void requestUsageStatsPermission() {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContext.startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}
}
public Intent intentUsageStatsPermission() {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
}
return null;
}
public boolean isAccessibilityEnabled() {
AccessibilityManager am = (AccessibilityManager) mContext
.getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> runningServices = am
.getEnabledAccessibilityServiceList(AccessibilityEvent.TYPES_ALL_MASK);
for (AccessibilityServiceInfo service : runningServices) {
if ("pl.szczodrzynski.topd/.OverlayAccessibilityService".equals(service.getId())) {
return true;
}
}
return false;
}
public void requestAccessibilityService() {
mContext.startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
public Intent intentAccessibilityService() {
return new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
}
public boolean isNotificationListenerEnabled() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
String pkgName = mContext.getPackageName();
final String flat = Settings.Secure.getString(mContext.getContentResolver(),
"enabled_notification_listeners");
if (!TextUtils.isEmpty(flat)) {
final String[] names = flat.split(":");
for (String name : names) {
final ComponentName cn = ComponentName.unflattenFromString(name);
if (cn != null) {
if (TextUtils.equals(pkgName, cn.getPackageName())) {
return true;
}
}
}
}
return false;
}
else
{
return false;
}
}
public void requestNotificationListener() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mContext.startActivity(intentNotificationListener());
}
}
public Intent intentNotificationListener()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
}
return null;
}
public boolean canRequestApkInstall() {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.O || mContext.getPackageManager().canRequestPackageInstalls();
}
public void requestApkInstall() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mContext.startActivity(intentApkInstall());
}
}
public Intent intentApkInstall() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return new Intent("android.settings.MANAGE_UNKNOWN_APP_SOURCES",
Uri.parse("package:" + mContext.getPackageName()));
}
return null;
}
}

View File

@ -0,0 +1,28 @@
package pl.szczodrzynski.edziennik.utils;
import android.content.Context;
import android.view.ViewGroup;
import com.google.android.material.snackbar.Snackbar;
import androidx.core.view.ViewCompat;
import pl.szczodrzynski.edziennik.R;
public class SnackbarHelper {
public static void configSnackbar(Context context, Snackbar snack) {
addMargins(snack);
setRoundBordersBg(context, snack);
ViewCompat.setElevation(snack.getView(), 6f);
}
private static void addMargins(Snackbar snack) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) snack.getView().getLayoutParams();
params.setMargins(12, 12, 12, 12);
snack.getView().setLayoutParams(params);
}
private static void setRoundBordersBg(Context context, Snackbar snackbar) {
snackbar.getView().setBackground(context.getResources().getDrawable(R.drawable.bg_snackbar));
}
}

View File

@ -0,0 +1,51 @@
package pl.szczodrzynski.edziennik.utils;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.style.StrikethroughSpan;
import org.xml.sax.XMLReader;
public class SpannableHtmlTagHandler implements Html.TagHandler {
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equalsIgnoreCase("strike") || tag.equals("s") || tag.equals("del")) {
processStrike(opening, output);
}
}
private void processStrike(boolean opening, Editable output) {
int len = output.length();
if(opening) {
output.setSpan(new StrikethroughSpan(), len, len, Spannable.SPAN_MARK_MARK);
} else {
Object obj = getLast(output, StrikethroughSpan.class);
int where = output.getSpanStart(obj);
output.removeSpan(obj);
if (where != len) {
output.setSpan(new StrikethroughSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private Object getLast(Editable text, Class kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
for(int i = objs.length;i>0;i--) {
if(text.getSpanFlags(objs[i-1]) == Spannable.SPAN_MARK_MARK) {
return objs[i-1];
}
}
return null;
}
}
}

View File

@ -0,0 +1,55 @@
package pl.szczodrzynski.edziennik.utils;
import android.content.Context;
import com.google.android.material.textfield.TextInputEditText;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.core.graphics.drawable.DrawableCompat;
import pl.szczodrzynski.edziennik.R;
public class TextInputDropDown extends TextInputEditText {
public TextInputDropDown(Context context) {
super(context);
create(context);
}
public TextInputDropDown(Context context, AttributeSet attrs) {
super(context, attrs);
create(context);
}
public TextInputDropDown(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
create(context);
}
public void create(Context context) {
Drawable drawable = context.getResources().getDrawable(R.drawable.dropdown_arrow);
Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(wrappedDrawable, Themes.INSTANCE.getPrimaryTextColor(context));
setCompoundDrawablesWithIntrinsicBounds(null, null, wrappedDrawable, null);
setFocusableInTouchMode(false);
setCursorVisible(false);
setLongClickable(false);
setMaxLines(1);
setInputType(0);
setKeyListener(null);
setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
v.setFocusableInTouchMode(false);
}
});
}
public final void setOnClickListener(OnClickListener onClickListener) {
super.setOnClickListener(v -> {
setFocusableInTouchMode(true);
requestFocus();
onClickListener.onClick(v);
});
}
}

View File

@ -0,0 +1,103 @@
package pl.szczodrzynski.edziennik.utils
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import androidx.annotation.StyleRes
import androidx.core.graphics.ColorUtils
import pl.szczodrzynski.edziennik.R
import pl.szczodrzynski.navlib.getColorFromAttr
object Themes {
data class Theme(
val id: Int,
@StringRes val name: Int,
@StyleRes val style: Int,
val isDark: Boolean
)
val themeList = arrayListOf(
Theme(id = 0, name = R.string.theme_light, style = R.style.AppTheme_Light, isDark = false),
Theme(id = 1, name = R.string.theme_dark, style = R.style.AppTheme_Dark, isDark = true),
Theme(id = 2, name = R.string.theme_black, style = R.style.AppTheme_Black, isDark = true),
Theme(id = 3, name = R.string.theme_chocolate, style = R.style.AppTheme_Chocolate, isDark = true),
Theme(id = 4, name = R.string.theme_indigo, style = R.style.AppTheme_Indigo, isDark = true),
Theme(id = 5, name = R.string.theme_light_yellow, style = R.style.AppTheme_LightYellow, isDark = false),
Theme(id = 6, name = R.string.theme_dark_blue, style = R.style.AppTheme_DarkBlue, isDark = true),
Theme(id = 7, name = R.string.theme_blue, style = R.style.AppTheme_Blue, isDark = true),
Theme(id = 8, name = R.string.theme_light_blue, style = R.style.AppTheme_LightBlue, isDark = false),
Theme(id = 9, name = R.string.theme_dark_purple, style = R.style.AppTheme_DarkPurple, isDark = true),
Theme(id = 10, name = R.string.theme_purple, style = R.style.AppTheme_Purple, isDark = true),
Theme(id = 11, name = R.string.theme_light_purple, style = R.style.AppTheme_LightPurple, isDark = false),
Theme(id = 12, name = R.string.theme_dark_red, style = R.style.AppTheme_DarkRed, isDark = true),
Theme(id = 13, name = R.string.theme_red, style = R.style.AppTheme_Red, isDark = true),
Theme(id = 14, name = R.string.theme_light_red, style = R.style.AppTheme_LightRed, isDark = false),
Theme(id = 15, name = R.string.theme_dark_green, style = R.style.AppTheme_DarkGreen, isDark = true),
Theme(id = 16, name = R.string.theme_amber, style = R.style.AppTheme_Amber, isDark = false),
Theme(id = 17, name = R.string.theme_light_green, style = R.style.AppTheme_LightGreen, isDark = false)
)
var theme: Theme = themeList[1]
var themeInt
get() = theme.id
set(value) {
theme = themeList[value]
}
val appThemeNoDisplay: Int
get() = if (theme.isDark) R.style.AppThemeDark_NoDisplay else R.style.AppTheme_NoDisplay
val appTheme: Int
get() = theme.style
val isDark: Boolean
get() = theme.isDark
fun getPrimaryTextColor(context: Context): Int {
return getColorFromAttr(context, android.R.attr.textColorPrimary)
}
fun getSecondaryTextColor(context: Context): Int {
return getColorFromAttr(context, android.R.attr.textColorSecondary)
}
/*public static int getChipColorRes() {
switch (themeInt) {
case THEME_LIGHT:
return R.color.chipBackgroundLight;
default:
case THEME_DARK:
return R.color.chipBackgroundDark;
case THEME_BLACK:
return R.color.chipBackgroundBlack;
case THEME_CHOCOLATE:
return R.color.chipBackgroundChocolate;
case THEME_BLUE:
return R.color.chipBackgroundBlue;
case THEME_PURPLE:
return R.color.chipBackgroundPurple;
case THEME_GREEN:
return R.color.chipBackgroundGreen;
case THEME_AMBER:
return R.color.chipBackgroundAmber;
case THEME_RED:
return R.color.chipBackgroundRed;
}
}*/
fun getThemeName(context: Context): String {
return context.getString(theme.name)
}
fun getThemeNames(context: Context): List<String> {
val list = mutableListOf<String>()
for (theme in themeList) {
list += context.getString(theme.name)
}
return list
}
}

View File

@ -0,0 +1,798 @@
package pl.szczodrzynski.edziennik.utils;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.AttrRes;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import androidx.core.content.FileProvider;
import pl.szczodrzynski.edziennik.App;
public class Utils {
private static final String TAG = "Utils";
public static String bs(@Nullable String s) {
return ns("", s);
}
public static String bs(String prefix, @Nullable String s) {
return ns("", prefix, s);
}
public static String bs(@Nullable String prefix, @Nullable String s, String suffix) {
return ns("", prefix, s, suffix);
}
public static String ns(String ifNull, @Nullable String s) {
return s == null || s.trim().isEmpty() ? ifNull : s;
}
public static String ns(String ifNull, String prefix, @Nullable String s) {
return s == null || s.trim().isEmpty() ? ifNull : prefix+s;
}
public static String ns(String ifNull, @Nullable String prefix, @Nullable String s, String suffix) {
return s == null || s.trim().isEmpty() ? ifNull : (prefix == null ? "" : prefix)+s+suffix;
}
public static boolean contains(@Nullable List<?> list, @NonNull Object o) {
if (list == null)
return false;
return list.contains(o);
/*for (Object o2: list) {
if (o.equals(o2))
return true;
}
return false;*/
}
public static List<String> debugLog = new ArrayList<>();
public static void d(String TAG, String message) {
if (App.devMode) {
Log.d(TAG, message);
debugLog.add(TAG+": "+message);
}
}
public static void c(String TAG, String message) {
if (App.devMode) {
Log.d(TAG, "// " + message);
debugLog.add(TAG+": // "+message);
}
}
/**
* Returns the first set (high) bit position, from right to left.
* @param n the number
* @return a 0-indexed position
*/
public static int rightmostSetBit(int n) {
return (int)((Math.log10(n & -n)) / Math.log10(2));
}
/**
* Returns the last set (high) bit position, from left to right.
* @param n the number
* @return a 0-indexed position
*/
public static int leftmostSetBit(int n) {
return (int)(Math.log(n) / Math.log(2));
}
/**
* Returns number of cells needed for given size of the widget.
*
* @param size Widget size in dp.
* @return Size in number of cells.
*/
public static int getCellsForSize(int size) {
int n = 2;
while (70 * n - 30 < size) {
++n;
}
return n - 1;
}
// EXCEPTION: thread does not change
/*public static void exception(String TAG, Response response, @NonNull Throwable throwable, String initialApiResponse, SyncCallback callback, Context activityContext) {
//d(TAG, "Thread/exception1/"+Thread.currentThread().getName());
if (Thread.currentThread().getName().equals("main")) {
AsyncTask.execute(() -> {
exceptionRun(TAG, response, throwable, initialApiResponse, callback, activityContext, true);
});
}
else {
exceptionRun(TAG, response, throwable, initialApiResponse, callback, activityContext, false);
}
}
private static void exceptionRun(String TAG, Response response, @NonNull Throwable throwable, String initialApiResponse, SyncCallback callback, Context activityContext, boolean finishOnMainThread) {
//d(TAG, "Thread/exception2/"+Thread.currentThread().getName());
String apiResponse = initialApiResponse;
throwable.printStackTrace();
if (response != null) {
//d(TAG, response.code() + " " + response.message());
if (apiResponse == null) {
apiResponse = response.code()+" "+response.message()+"\n";
if (response.raw().body() != null) {
try {
apiResponse += response.raw().body().string();
} catch (Exception e) {
e.printStackTrace();
apiResponse += "Exception while getting response body:\n"+Log.getStackTraceString(e);
}
}
else {
apiResponse += "Response body is null.";
}
}
String apiResponsePrefix = "Request:\n";
apiResponsePrefix += response.request().url().toString()+"\n";
apiResponsePrefix += response.request().headers().toString()+"\n";
apiResponsePrefix += response.request().bodyToString();
apiResponsePrefix += "\n\nResponse:\n";
apiResponse = apiResponsePrefix + apiResponse;
}
if (callback != null) {
String finalApiResponse = apiResponse;
if (!finishOnMainThread) {
exceptionFinish(TAG, response, throwable, finalApiResponse, callback, activityContext);
return;
}
new Handler(activityContext != null ? activityContext.getMainLooper() : Looper.getMainLooper()).post(() -> {
exceptionFinish(TAG, response, throwable, finalApiResponse, callback, activityContext);
});
}
}
private static void exceptionFinish(String TAG, Response response, @NonNull Throwable throwable, String finalApiResponse, SyncCallback callback, Context activityContext) {
//d(TAG, "Thread/exception3/"+Thread.currentThread().getName());
if (throwable instanceof UnknownHostException) {
callback.onError(activityContext, Error.CODE_NO_INTERNET, "", throwable, finalApiResponse);
}
else if (throwable instanceof SSLException) {
callback.onError(activityContext, Error.CODE_SSL_ERROR, "", throwable, finalApiResponse);
}
else if (throwable instanceof SocketTimeoutException) {
callback.onError(activityContext, Error.CODE_TIMEOUT, "", throwable, finalApiResponse);
}
else if (throwable instanceof InterruptedIOException) {
callback.onError(activityContext, Error.CODE_NO_INTERNET, "", throwable, finalApiResponse);
}
else {
if (response != null) {
if (response.code() == 424 || response.code() == 400 || response.code() == 401 || response.code() == 500 || response.code() == 503 || response.code() == 404) {
callback.onError(activityContext, CODE_MAINTENANCE, response.code() + " " + response.message() + " " + throwable.getMessage(), throwable, finalApiResponse);
}
else {
callback.onError(activityContext, CODE_OTHER, response.code() + " " + response.message() + " " + throwable.getMessage(), throwable, finalApiResponse);
}
}
else {
callback.onError(activityContext, CODE_OTHER, throwable.getMessage(), throwable, finalApiResponse);
}
}
}*/
public static String hexFromColorInt(@ColorInt int color) {
return String.format("%06X", (0xFFFFFF & color));
}
public static String getRealPathFromURI(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index;
String result = null;
try {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static int strToInt(String s, int defaultValue)
{
try {
return Integer.parseInt(s);
}
catch (Exception e) {
e.printStackTrace();
return defaultValue;
}
}
public static int strToInt(String s)
{
return Integer.parseInt(s);
}
public static String intToStr(Integer i)
{
return Integer.toString(i);
}
public static int crc16(final byte[] buffer) {
int crc = 0xFFFF;
for (byte aBuffer : buffer) {
crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
crc ^= (aBuffer & 0xff); // byte to int, trunc sign
crc ^= ((crc & 0xff) >> 4);
crc ^= (crc << 12) & 0xffff;
crc ^= ((crc & 0xFF) << 5) & 0xffff;
}
crc &= 0xffff;
return crc+32768;
}
public static long crc32(byte[] buffer) {
CRC32 crc = new CRC32();
crc.update(buffer);
return crc.getValue();
}
public static String toPascalCase(String source) {
return source.toUpperCase().charAt(0)+source.toLowerCase().substring(1);
}
@ColorInt
public static int getAttr(Context context, @AttrRes int resourceId) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(resourceId, typedValue, true);
return typedValue.data;
}
public static int dpToPx(int dp)
{
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
public static int pxToDp(int px)
{
return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}
public static void openGooglePlay(Context context) {
openGooglePlay(context, context.getPackageName());
}
public static void openGooglePlay(Context context, String packageName) {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} catch (android.content.ActivityNotFoundException e) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
public static void openUrl(Context context, String url) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
}
public static String checkAppExists(Context context, String packageName) {
try {
PackageInfo packageInfo;
packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
if (packageInfo != null) {
Log.d(TAG, packageInfo.toString());
Log.d(TAG, packageInfo.packageName+" "+packageInfo.versionName+" "+packageInfo.versionCode);
return packageInfo.versionName;
}
else {
return null;
}
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void copy(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
public static class VulcanRequestEncryptionUtils {
private static final String ALGORITHM_NAME = "SHA1withRSA";
private static final String CERT_TYPE = "pkcs12";
private static final String CONTAINER_NAME = "LoginCert";
private static final String PASSWORD = "CE75EA598C7743AD9B0B7328DED85B06";
public static String signContent(byte[] contents, final InputStream cert) throws IOException, GeneralSecurityException, NullPointerException {
final KeyStore instance = KeyStore.getInstance(CERT_TYPE);
instance.load(cert, PASSWORD.toCharArray());
final PrivateKey privateKey = (PrivateKey) instance.getKey(CONTAINER_NAME, PASSWORD.toCharArray());
final Signature instance2 = Signature.getInstance(ALGORITHM_NAME);
instance2.initSign(privateKey);
instance2.update(contents);
return Base64.encodeToString(instance2.sign(), Base64.DEFAULT).replace("\n", "");
}
}
public static class VulcanQrEncryptionUtils {
private static final String PASSWORD = "tDVS4ykCBBAeN33h";
public static String decode(String content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, ShortBufferException, BadPaddingException, IllegalBlockSizeException {
@SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
byte[] input = Base64.decode(content, Base64.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(PASSWORD.getBytes(), "AES"));
byte[] plainText = new byte[cipher.getOutputSize(input.length)];
int ptLength = cipher.update(input, 0, input.length, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
return new String(plainText);
}
}
public static class AESCrypt
{
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
public static String encrypt(String value, String key) throws Exception
{
Key keyObj = generateKey(key);
Cipher cipher = Cipher.getInstance(AESCrypt.ALGORITHM);
byte[] iv = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keyObj, ivSpec);
byte [] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8"));
String encryptedValue64 = Base64.encodeToString(encryptedByteValue, Base64.DEFAULT);
return encryptedValue64;
}
public static String decrypt(String value, String key) throws Exception
{
Key keyObj = generateKey(key);
Cipher cipher = Cipher.getInstance(AESCrypt.ALGORITHM);
byte[] iv = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keyObj, ivSpec);
byte[] decryptedValue64 = Base64.decode(value, Base64.DEFAULT);
byte [] decryptedByteValue = cipher.doFinal(decryptedValue64);
String decryptedValue = new String(decryptedByteValue,"utf-8");
return decryptedValue;
}
private static Key generateKey(String key) throws Exception
{
Key keyObj = new SecretKeySpec(key.getBytes(),AESCrypt.ALGORITHM);
return keyObj;
}
}
private static String Base64UrlSafe(byte[] data)
{
String enc = Base64.encodeToString(data, Base64.URL_SAFE | Base64.NO_WRAP);
return enc.replace("=", "");
}
private final static char[] hexArray = "0123456789abcdef".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static String HmacSHA512(String message, String secret)
{
try {
Mac sha_HMAC = Mac.getInstance("HmacSHA512");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA512");
sha_HMAC.init(secret_key);
return Base64UrlSafe(sha_HMAC.doFinal(message.getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public static String HmacMD5(String message, String secret)
{
try {
Mac sha_HMAC = Mac.getInstance("HmacMD5");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacMD5");
sha_HMAC.init(secret_key);
return bytesToHex(sha_HMAC.doFinal(message.getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public static String MD5(String message)
{
try {
// Create MD5 Hash
MessageDigest md = java.security.MessageDigest.getInstance("MD5");
return Base64UrlSafe(md.digest(message.getBytes()));
}catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static float getGradeValue(String grade) {
switch (grade) {
case "1-":
return 0.75f;
case "1":
return 1.00f;
case "1+":
return 1.50f;
case "2-":
return 1.75f;
case "2":
return 2.00f;
case "2+":
return 2.50f;
case "3-":
return 2.75f;
case "3":
return 3.00f;
case "3+":
return 3.50f;
case "4-":
return 3.75f;
case "4":
return 4.00f;
case "4+":
return 4.50f;
case "5-":
return 4.75f;
case "5":
return 5.00f;
case "5+":
return 5.50f;
case "6-":
return 5.75f;
case "6":
return 6.00f;
case "6+":
return 6.50f;
}
return 0.00f;
}
public static int getVulcanGradeColor(String name) {
switch (name) {
case "1-":
case "1":
case "1+":
return 0xffd65757;
case "2-":
case "2":
case "2+":
return 0xff9071b3;
case "3-":
case "3":
case "3+":
return 0xffd2ab24;
case "4-":
case "4":
case "4+":
return 0xff50b6d6;
case "5-":
case "5":
case "5+":
return 0xff2cbd92;
case "6-":
case "6":
case "6+":
return 0xff91b43c;
default:
return 0xff3D5F9C;
}
}
public static int getWordGradeValue(String grade) {
switch (grade) {
case "niedostateczny":
return 1;
case "dopuszczający":
return 2;
case "dostateczny":
return 3;
case "dobry":
return 4;
case "bardzo dobry":
return 5;
case "celujący":
return 6;
default:
return 0;
}
}
public static boolean zipFileAtPath(String sourcePath, String toLocation) {
final int BUFFER = 2048;
File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/*
*
* Zips a subfolder
*
*/
private static void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
final int BUFFER = 2048;
File[] fileList = folder.listFiles();
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(out, file, basePathLength);
} else {
byte data[] = new byte[BUFFER];
String unmodifiedFilePath = file.getPath();
String relativePath = unmodifiedFilePath
.substring(basePathLength);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}
/*
* gets the last path component
*
* Example: getLastPathComponent("downloads/example/fileToZip");
* Result: "fileToZip"
*/
public static String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
public static String readableFileSize(long size) {
if(size <= 0) return "0B";
final String[] units = new String[] { "B", "kB", "MB", "GB", "TB", "PB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + units[digitGroups];
}
public static int monthFromName(String name) {
int month = 1;
switch (name) {
case "stycznia":
month = 1;
break;
case "lutego":
month = 2;
break;
case "marca":
month = 3;
break;
case "kwietnia":
month = 4;
break;
case "maja":
month = 5;
break;
case "czerwca":
month = 6;
break;
case "lipca":
month = 7;
break;
case "sierpnia":
month = 8;
break;
case "września":
month = 9;
break;
case "października":
month = 10;
break;
case "listopada":
month = 11;
break;
case "grudnia":
month = 12;
break;
}
return month;
}
private static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
boolean first = true;
while ((line = reader.readLine()) != null) {
if (!(first && !(first = !first)))
sb.append("\n");
sb.append(line);
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (File fl) throws Exception {
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static void openFile(Context context, File file) {
try {
Uri uri = Uri.fromFile(file);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
}
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getExtensionFromFileName(file.toString()));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mimeType == null ? "*/*" : mimeType);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Nie ma aplikacji która otwiera ten typ pliku", Toast.LENGTH_LONG).show();
}
}
private static File storageDir = null;
public static File getStorageDir() {
if (storageDir != null)
return storageDir;
storageDir = Environment.getExternalStoragePublicDirectory("Szkolny.eu");
storageDir.mkdirs();
return storageDir;
}
public static void writeStringToFile(File file, String data) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
public static String getExtensionFromFileName(String fileName) {
return fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
}
public static String getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
return dateFormat.format(date);
}
}