Fully migrated to Kotlin

This commit is contained in:
2017-08-25 20:24:25 +02:00
parent 852e38b97d
commit cc18f34161
104 changed files with 5064 additions and 6111 deletions

View File

@@ -1,92 +0,0 @@
/*
* Copyright 2015 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.apps.abit.util;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import ch.dissem.apps.abit.R;
import ch.dissem.bitmessage.entity.Plaintext;
/**
* Helper class to work with Assets.
*/
public class Assets {
public static List<String> readSqlStatements(Context ctx, String name) {
try {
InputStream in = ctx.getAssets().open(name);
Scanner scanner = new Scanner(in, "UTF-8").useDelimiter(";");
List<String> result = new LinkedList<>();
while (scanner.hasNext()) {
String statement = scanner.next().trim();
if (!"".equals(statement)) {
result.add(statement);
}
}
return result;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@DrawableRes
public static int getStatusDrawable(Plaintext.Status status) {
switch (status) {
case RECEIVED:
return 0;
case DRAFT:
return R.drawable.draft;
case PUBKEY_REQUESTED:
return R.drawable.public_key;
case DOING_PROOF_OF_WORK:
return R.drawable.ic_notification_proof_of_work;
case SENT:
return R.drawable.sent;
case SENT_ACKNOWLEDGED:
return R.drawable.sent_acknowledged;
default:
return 0;
}
}
@StringRes
public static int getStatusString(Plaintext.Status status) {
switch (status) {
case RECEIVED:
return R.string.status_received;
case DRAFT:
return R.string.status_draft;
case PUBKEY_REQUESTED:
return R.string.status_public_key;
case DOING_PROOF_OF_WORK:
return R.string.proof_of_work_title;
case SENT:
return R.string.status_sent;
case SENT_ACKNOWLEDGED:
return R.string.status_sent_acknowledged;
default:
return 0;
}
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2015 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.apps.abit.util
import android.content.Context
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
import ch.dissem.apps.abit.R
import ch.dissem.bitmessage.entity.Plaintext
import java.io.IOException
import java.util.*
/**
* Helper class to work with Assets.
*/
object Assets {
fun readSqlStatements(ctx: Context, name: String): List<String> {
try {
val `in` = ctx.assets.open(name)
val scanner = Scanner(`in`, "UTF-8").useDelimiter(";")
val result = LinkedList<String>()
while (scanner.hasNext()) {
val statement = scanner.next().trim { it <= ' ' }
if ("" != statement) {
result.add(statement)
}
}
return result
} catch (e: IOException) {
throw RuntimeException(e)
}
}
@DrawableRes
fun getStatusDrawable(status: Plaintext.Status): Int {
when (status) {
Plaintext.Status.RECEIVED -> return 0
Plaintext.Status.DRAFT -> return R.drawable.draft
Plaintext.Status.PUBKEY_REQUESTED -> return R.drawable.public_key
Plaintext.Status.DOING_PROOF_OF_WORK -> return R.drawable.ic_notification_proof_of_work
Plaintext.Status.SENT -> return R.drawable.sent
Plaintext.Status.SENT_ACKNOWLEDGED -> return R.drawable.sent_acknowledged
else -> return 0
}
}
@StringRes
fun getStatusString(status: Plaintext.Status): Int {
when (status) {
Plaintext.Status.RECEIVED -> return R.string.status_received
Plaintext.Status.DRAFT -> return R.string.status_draft
Plaintext.Status.PUBKEY_REQUESTED -> return R.string.status_public_key
Plaintext.Status.DOING_PROOF_OF_WORK -> return R.string.proof_of_work_title
Plaintext.Status.SENT -> return R.string.status_sent
Plaintext.Status.SENT_ACKNOWLEDGED -> return R.string.status_sent_acknowledged
else -> return 0
}
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2016 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.apps.abit.util;
import java.util.regex.Pattern;
/**
* @author Christian Basler
*/
public class Constants {
public static final String PREFERENCE_WIFI_ONLY = "wifi_only";
public static final String PREFERENCE_TRUSTED_NODE = "trusted_node";
public static final String PREFERENCE_SYNC_TIMEOUT = "sync_timeout";
public static final String PREFERENCE_SERVER_POW = "server_pow";
public static final String PREFERENCE_FULL_NODE = "full_node";
public static final String PREFERENCE_REQUEST_ACK = "request_acknowledgments";
public static final String PREFERENCE_POW_AVERAGE = "average_pow_time_ms";
public static final String PREFERENCE_POW_COUNT = "pow_count";
public static final String BITMESSAGE_URL_SCHEMA = "bitmessage:";
public static final Pattern BITMESSAGE_ADDRESS_PATTERN = Pattern.compile("\\bBM-[a-zA-Z0-9]+\\b");
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2016 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.apps.abit.util
import java.util.regex.Pattern
/**
* @author Christian Basler
*/
object Constants {
const val PREFERENCE_WIFI_ONLY = "wifi_only"
const val PREFERENCE_TRUSTED_NODE = "trusted_node"
const val PREFERENCE_SYNC_TIMEOUT = "sync_timeout"
const val PREFERENCE_SERVER_POW = "server_pow"
const val PREFERENCE_FULL_NODE = "full_node"
const val PREFERENCE_REQUEST_ACK = "request_acknowledgments"
const val PREFERENCE_POW_AVERAGE = "average_pow_time_ms"
const val PREFERENCE_POW_COUNT = "pow_count"
const val BITMESSAGE_URL_SCHEMA = "bitmessage:"
val BITMESSAGE_ADDRESS_PATTERN = Pattern.compile("\\bBM-[a-zA-Z0-9]+\\b")
}

View File

@@ -1,108 +0,0 @@
/*
* Copyright 2015 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.apps.abit.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.IIcon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import ch.dissem.apps.abit.Identicon;
import ch.dissem.apps.abit.R;
import ch.dissem.bitmessage.entity.BitmessageAddress;
import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;
import static android.util.Base64.NO_WRAP;
import static android.util.Base64.URL_SAFE;
import static ch.dissem.apps.abit.util.Constants.BITMESSAGE_URL_SCHEMA;
/**
* Some helper methods to work with drawables.
*/
public class Drawables {
private static final Logger LOG = LoggerFactory.getLogger(Drawables.class);
private static final int QR_CODE_SIZE = 350;
public static MenuItem addIcon(Context ctx, Menu menu, int menuItem, IIcon icon) {
MenuItem item = menu.findItem(menuItem);
item.setIcon(new IconicsDrawable(ctx, icon).colorRes(R.color.colorPrimaryDarkText).actionBar());
return item;
}
public static Bitmap toBitmap(Identicon identicon, int size) {
return toBitmap(identicon, size, size);
}
public static Bitmap toBitmap(Identicon identicon, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
identicon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
identicon.draw(canvas);
return bitmap;
}
public static Bitmap qrCode(BitmessageAddress address) {
StringBuilder link = new StringBuilder();
link.append(BITMESSAGE_URL_SCHEMA);
link.append(address.getAddress());
if (address.getAlias() != null) {
link.append("?label=").append(address.getAlias());
}
if (address.getPubkey() != null) {
link.append(address.getAlias() == null ? '?' : '&');
ByteArrayOutputStream pubkey = new ByteArrayOutputStream();
address.getPubkey().writeUnencrypted(pubkey);
link.append("pubkey=").append(Base64.encodeToString(pubkey.toByteArray(), URL_SAFE | NO_WRAP));
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(link.toString(),
BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, null);
} catch (WriterException e) {
LOG.error(e.getMessage(), e);
return null;
}
int w = result.getWidth();
int h = result.getHeight();
int[] pixels = new int[w * h];
for (int y = 0; y < h; y++) {
int offset = y * w;
for (int x = 0; x < w; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_CODE_SIZE, 0, 0, w, h);
return bitmap;
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2015 Christian Basler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.dissem.apps.abit.util
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color.BLACK
import android.graphics.Color.WHITE
import android.util.Base64
import android.util.Base64.NO_WRAP
import android.util.Base64.URL_SAFE
import android.view.Menu
import android.view.MenuItem
import ch.dissem.apps.abit.Identicon
import ch.dissem.apps.abit.R
import ch.dissem.bitmessage.entity.BitmessageAddress
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
/**
* Some helper methods to work with drawables.
*/
object Drawables {
private val LOG = LoggerFactory.getLogger(Drawables::class.java)
private val QR_CODE_SIZE = 350
fun addIcon(ctx: Context, menu: Menu, menuItem: Int, icon: IIcon): MenuItem {
val item = menu.findItem(menuItem)
item.icon = IconicsDrawable(ctx, icon).colorRes(R.color.colorPrimaryDarkText).actionBar()
return item
}
fun toBitmap(identicon: Identicon, width: Int, height: Int = width): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
identicon.setBounds(0, 0, canvas.width, canvas.height)
identicon.draw(canvas)
return bitmap
}
fun qrCode(address: BitmessageAddress?): Bitmap? {
if (address == null) {
return null
}
val link = StringBuilder()
link.append(Constants.BITMESSAGE_URL_SCHEMA)
link.append(address.address)
if (address.alias != null) {
link.append("?label=").append(address.alias)
}
if (address.pubkey != null) {
link.append(if (address.alias == null) '?' else '&')
val pubkey = ByteArrayOutputStream()
address.pubkey!!.writeUnencrypted(pubkey)
link.append("pubkey=").append(Base64.encodeToString(pubkey.toByteArray(), URL_SAFE or NO_WRAP))
}
val result: BitMatrix
try {
result = MultiFormatWriter().encode(link.toString(),
BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, null)
} catch (e: WriterException) {
LOG.error(e.message, e)
return null
}
val w = result.width
val h = result.height
val pixels = IntArray(w * h)
for (y in 0 until h) {
val offset = y * w
for (x in 0 until w) {
pixels[offset + x] = if (result.get(x, y)) BLACK else WHITE
}
}
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, QR_CODE_SIZE, 0, 0, w, h)
return bitmap
}
}

View File

@@ -1,8 +1,6 @@
package ch.dissem.apps.abit.util
import android.support.annotation.DrawableRes
import android.support.design.widget.FloatingActionButton
import ch.dissem.apps.abit.MainActivity
import ch.dissem.apps.abit.R
import io.github.kobakei.materialfabspeeddial.FabSpeedDial
@@ -12,7 +10,6 @@ import io.github.kobakei.materialfabspeeddial.FabSpeedDialMenu
* Utilities to work with the common floating action button in the main activity
*/
object FabUtils {
@JvmStatic
fun initFab(activity: MainActivity, @DrawableRes drawableRes: Int, menu: FabSpeedDialMenu): FabSpeedDial {
val fab = activity.floatingActionButton
fab.removeAllOnMenuItemClickListeners()
@@ -21,7 +18,7 @@ object FabUtils {
val mainFab = fab.mainFab
mainFab.setImageResource(drawableRes)
fab.setMenu(menu)
fab.addOnStateChangeListener { isOpened ->
fab.addOnStateChangeListener { isOpened: Boolean ->
if (isOpened) {
// It will be turned 45 degrees, which makes an x out of the +
mainFab.setImageResource(R.drawable.ic_action_add)

View File

@@ -1,77 +0,0 @@
package ch.dissem.apps.abit.util;
import android.content.Context;
import android.support.annotation.ColorInt;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.typeface.IIcon;
import ch.dissem.apps.abit.R;
import ch.dissem.bitmessage.entity.valueobject.Label;
/**
* Helper class to help with translating the default labels, getting label colors and so on.
*/
public class Labels {
public static String getText(Label label, Context ctx) {
return getText(label.getType(), label.toString(), ctx);
}
public static String getText(Label.Type type, String alternative, Context ctx) {
if (type == null) {
return alternative;
} else {
switch (type) {
case INBOX:
return ctx.getString(R.string.inbox);
case DRAFT:
return ctx.getString(R.string.draft);
case OUTBOX:
return ctx.getString(R.string.outbox);
case SENT:
return ctx.getString(R.string.sent);
case UNREAD:
return ctx.getString(R.string.unread);
case TRASH:
return ctx.getString(R.string.trash);
case BROADCAST:
return ctx.getString(R.string.broadcasts);
default:
return alternative;
}
}
}
public static IIcon getIcon(Label label) {
if (label.getType() == null) {
return CommunityMaterial.Icon.cmd_label;
}
switch (label.getType()) {
case INBOX:
return GoogleMaterial.Icon.gmd_inbox;
case DRAFT:
return CommunityMaterial.Icon.cmd_file;
case OUTBOX:
return CommunityMaterial.Icon.cmd_inbox_arrow_up;
case SENT:
return CommunityMaterial.Icon.cmd_send;
case BROADCAST:
return CommunityMaterial.Icon.cmd_rss;
case UNREAD:
return GoogleMaterial.Icon.gmd_markunread_mailbox;
case TRASH:
return GoogleMaterial.Icon.gmd_delete;
default:
return CommunityMaterial.Icon.cmd_label;
}
}
@ColorInt
public static int getColor(Label label) {
if (label.getType() == null) {
return label.getColor();
}
return 0xFF000000;
}
}

View File

@@ -0,0 +1,47 @@
package ch.dissem.apps.abit.util
import android.content.Context
import android.support.annotation.ColorInt
import com.mikepenz.community_material_typeface_library.CommunityMaterial
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.typeface.IIcon
import ch.dissem.apps.abit.R
import ch.dissem.bitmessage.entity.valueobject.Label
/**
* Helper class to help with translating the default labels, getting label colors and so on.
*/
object Labels {
fun getText(label: Label, ctx: Context): String = getText(label.type, label.toString(), ctx)!!
fun getText(type: Label.Type?, alternative: String?, ctx: Context) = when (type) {
Label.Type.INBOX -> ctx.getString(R.string.inbox)
Label.Type.DRAFT -> ctx.getString(R.string.draft)
Label.Type.OUTBOX -> ctx.getString(R.string.outbox)
Label.Type.SENT -> ctx.getString(R.string.sent)
Label.Type.UNREAD -> ctx.getString(R.string.unread)
Label.Type.TRASH -> ctx.getString(R.string.trash)
Label.Type.BROADCAST -> ctx.getString(R.string.broadcasts)
else -> alternative
}
fun getIcon(label: Label): IIcon = when (label.type) {
Label.Type.INBOX -> GoogleMaterial.Icon.gmd_inbox
Label.Type.DRAFT -> CommunityMaterial.Icon.cmd_file
Label.Type.OUTBOX -> CommunityMaterial.Icon.cmd_inbox_arrow_up
Label.Type.SENT -> CommunityMaterial.Icon.cmd_send
Label.Type.BROADCAST -> CommunityMaterial.Icon.cmd_rss
Label.Type.UNREAD -> GoogleMaterial.Icon.gmd_markunread_mailbox
Label.Type.TRASH -> GoogleMaterial.Icon.gmd_delete
else -> CommunityMaterial.Icon.cmd_label
}
@ColorInt
fun getColor(label: Label): Int {
return if (label.type == null) {
label.color
} else 0xFF000000.toInt()
}
}

View File

@@ -8,19 +8,14 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import android.support.annotation.RequiresApi
import ch.dissem.apps.abit.MainActivity.updateNodeSwitch
import ch.dissem.apps.abit.MainActivity
import ch.dissem.apps.abit.dialog.FullNodeDialogActivity
import ch.dissem.apps.abit.service.BitmessageService
import ch.dissem.apps.abit.service.StartupNodeOnWifiService
/**
* Created by chrigu on 18.08.17.
*/
object NetworkUtils {
@JvmStatic
@JvmOverloads
fun enableNode(ctx: Context, ask: Boolean = true) {
Preferences.setFullNodeActive(ctx, true)
if (Preferences.isWifiOnly(ctx)) {
@@ -29,7 +24,7 @@ object NetworkUtils {
scheduleNodeStart(ctx)
} else {
ctx.startService(Intent(ctx, BitmessageService::class.java))
updateNodeSwitch()
MainActivity.updateNodeSwitch()
}
} else if (ask) {
val dialogIntent = Intent(ctx, FullNodeDialogActivity::class.java)
@@ -43,23 +38,22 @@ object NetworkUtils {
}
} else {
ctx.startService(Intent(ctx, BitmessageService::class.java))
updateNodeSwitch()
MainActivity.updateNodeSwitch()
}
}
@JvmStatic
fun disableNode(ctx: Context) {
Preferences.setFullNodeActive(ctx, false)
ctx.stopService(Intent(ctx, BitmessageService::class.java))
}
@JvmStatic
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun scheduleNodeStart(ctx: Context) {
val serviceComponent = ComponentName(ctx, StartupNodeOnWifiService::class.java)
val builder = JobInfo.Builder(0, serviceComponent)
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
builder.setBackoffCriteria(0L, JobInfo.BACKOFF_POLICY_LINEAR)
val jobScheduler = ctx.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.schedule(builder.build());
jobScheduler.schedule(builder.build())
}
}

View File

@@ -15,7 +15,6 @@ object PowStats {
var averagePowUnitTime = 0L
var powCount = 0L
@JvmStatic
fun getExpectedPowTimeInMilliseconds(ctx: Context, target: ByteArray): Long {
if (averagePowUnitTime == 0L) {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
@@ -27,7 +26,6 @@ object PowStats {
return (BigInteger.valueOf(averagePowUnitTime) * BigInteger(target) / TWO_POW_64).toLong()
}
@JvmStatic
fun addPow(ctx: Context, time: Long, target: ByteArray) {
val targetBigInt = BigInteger(target)
val powCountBefore = BigInteger.valueOf(powCount)

View File

@@ -21,7 +21,11 @@ import android.preference.PreferenceManager
import ch.dissem.apps.abit.R
import ch.dissem.apps.abit.listener.WifiReceiver
import ch.dissem.apps.abit.notification.ErrorNotification
import ch.dissem.apps.abit.util.Constants.*
import ch.dissem.apps.abit.util.Constants.PREFERENCE_FULL_NODE
import ch.dissem.apps.abit.util.Constants.PREFERENCE_REQUEST_ACK
import ch.dissem.apps.abit.util.Constants.PREFERENCE_SYNC_TIMEOUT
import ch.dissem.apps.abit.util.Constants.PREFERENCE_TRUSTED_NODE
import ch.dissem.apps.abit.util.Constants.PREFERENCE_WIFI_ONLY
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
@@ -33,7 +37,6 @@ import java.net.InetAddress
object Preferences {
private val LOG = LoggerFactory.getLogger(Preferences::class.java)
@JvmStatic
fun useTrustedNode(ctx: Context): Boolean {
val trustedNode = getPreference(ctx, PREFERENCE_TRUSTED_NODE) ?: return false
return trustedNode.trim { it <= ' ' }.isNotEmpty()
@@ -43,7 +46,6 @@ object Preferences {
* Warning, this method might do a network call and therefore can't be called from
* the UI thread.
*/
@JvmStatic
@Throws(IOException::class)
fun getTrustedNode(ctx: Context): InetAddress? {
var trustedNode: String = getPreference(ctx, PREFERENCE_TRUSTED_NODE) ?: return null
@@ -57,7 +59,6 @@ object Preferences {
return InetAddress.getByName(trustedNode)
}
@JvmStatic
fun getTrustedNodePort(ctx: Context): Int {
var trustedNode: String = getPreference(ctx, PREFERENCE_TRUSTED_NODE) ?: return 8444
trustedNode = trustedNode.trim { it <= ' ' }
@@ -69,14 +70,13 @@ object Preferences {
return Integer.parseInt(portString)
} catch (e: NumberFormatException) {
ErrorNotification(ctx)
.setError(R.string.error_invalid_sync_port, portString)
.show()
.setError(R.string.error_invalid_sync_port, portString)
.show()
}
}
return 8444
}
@JvmStatic
fun getTimeoutInSeconds(ctx: Context): Long {
val preference = getPreference(ctx, PREFERENCE_SYNC_TIMEOUT) ?: return 120
return preference.toLong()
@@ -88,53 +88,40 @@ object Preferences {
return preferences.getString(name, null)
}
@JvmStatic
fun isConnectionAllowed(ctx: Context): Boolean {
return !isWifiOnly(ctx) || !WifiReceiver.isConnectedToMeteredNetwork(ctx)
}
fun isConnectionAllowed(ctx: Context) = !isWifiOnly(ctx) || !WifiReceiver.isConnectedToMeteredNetwork(ctx)
@JvmStatic
fun isWifiOnly(ctx: Context): Boolean {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
return preferences.getBoolean(PREFERENCE_WIFI_ONLY, true)
}
@JvmStatic
fun setWifiOnly(ctx: Context, status: Boolean) {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
preferences.edit().putBoolean(PREFERENCE_WIFI_ONLY, status).apply()
}
@JvmStatic
fun isFullNodeActive(ctx: Context): Boolean {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
return preferences.getBoolean(PREFERENCE_FULL_NODE, false)
}
@JvmStatic
fun setFullNodeActive(ctx: Context, status: Boolean) {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
preferences.edit().putBoolean(PREFERENCE_FULL_NODE, status).apply()
}
@JvmStatic
fun getExportDirectory(ctx: Context): File {
return File(ctx.filesDir, "exports")
}
fun getExportDirectory(ctx: Context) = File(ctx.filesDir, "exports")
@JvmStatic
fun requestAcknowledgements(ctx: Context): Boolean {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
return preferences.getBoolean(PREFERENCE_REQUEST_ACK, true)
}
@JvmStatic
fun setRequestAcknowledgements(ctx: Context, status: Boolean) {
val preferences = PreferenceManager.getDefaultSharedPreferences(ctx)
preferences.edit().putBoolean(PREFERENCE_REQUEST_ACK, status).apply()
}
@JvmStatic
fun cleanupExportDirectory(ctx: Context) {
val exportDirectory = getExportDirectory(ctx)
if (exportDirectory.exists()) {

View File

@@ -14,29 +14,27 @@
* limitations under the License.
*/
package ch.dissem.apps.abit.util;
package ch.dissem.apps.abit.util
import java.util.regex.Pattern;
import java.util.regex.Pattern
/**
* @author Christian Basler
*/
public class Strings {
private final static Pattern WHITESPACES = Pattern.compile("\\s+");
object Strings {
private val WHITESPACES = Pattern.compile("\\s+")
private static CharSequence trim(CharSequence string, int length) {
if (string.length() <= length) {
return string;
} else {
return string.subSequence(0, length);
}
private fun trim(string: CharSequence?, length: Int) = if (string == null) {
""
} else if (string.length <= length) {
string
} else {
string.subSequence(0, length)
}
/**
* Trime the string to 200 characters and normalizes all whitespaces by replacing any sequence
* Trim the string to 200 characters and normalizes all whitespaces by replacing any sequence
* of whitespace characters with a single space character.
*/
public static String prepareMessageExtract(CharSequence string) {
return WHITESPACES.matcher(trim(string, 200)).replaceAll(" ");
}
fun prepareMessageExtract(string: CharSequence?) = WHITESPACES.matcher(trim(string, 200)).replaceAll(" ")
}

View File

@@ -1,41 +0,0 @@
package ch.dissem.apps.abit.util;
import java.nio.ByteBuffer;
import java.util.UUID;
/**
* SQLite has no UUID data type, and UUIDs are therefore best saved as BINARY[16]. This class
* takes care of conversion between byte[16] and UUID.
* <p>
* Thanks to Brice Roncace on
* <a href="http://stackoverflow.com/questions/17893609/convert-uuid-to-byte-that-works-when-using-uuid-nameuuidfrombytesb">
* Stack Overflow
* </a>
* for providing the UUID <-> byte[] conversions.
* </p>
*/
public class UuidUtils {
/**
* @param bytes that represent a UUID, or null for a random UUID
* @return the UUID from the given bytes, or a random UUID if bytes is null.
*/
public static UUID asUuid(byte[] bytes) {
if (bytes == null) {
return UUID.randomUUID();
}
ByteBuffer bb = ByteBuffer.wrap(bytes);
long firstLong = bb.getLong();
long secondLong = bb.getLong();
return new UUID(firstLong, secondLong);
}
public static byte[] asBytes(UUID uuid) {
if (uuid == null) {
return null;
}
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
}

View File

@@ -0,0 +1,39 @@
package ch.dissem.apps.abit.util
import java.nio.ByteBuffer
import java.util.UUID
/**
* SQLite has no UUID data type, and UUIDs are therefore best saved as BINARY[16]. This class
* takes care of conversion between byte[16] and UUID.
*
*
* Thanks to Brice Roncace on
* [
* Stack Overflow
](http://stackoverflow.com/questions/17893609/convert-uuid-to-byte-that-works-when-using-uuid-nameuuidfrombytesb) *
* for providing the UUID <-> byte[] conversions.
*
*/
object UuidUtils {
/**
* @param bytes that represent a UUID, or null for a random UUID
* @return the UUID from the given bytes, or a random UUID if bytes is null.
*/
fun asUuid(bytes: ByteArray?): UUID {
if (bytes == null) {
return UUID.randomUUID()
}
val bb = ByteBuffer.wrap(bytes)
val firstLong = bb.long
val secondLong = bb.long
return UUID(firstLong, secondLong)
}
fun asBytes(uuid: UUID): ByteArray {
val bb = ByteBuffer.wrap(ByteArray(16))
bb.putLong(uuid.mostSignificantBits)
bb.putLong(uuid.leastSignificantBits)
return bb.array()
}
}