Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Maintenance #28

Draft
wants to merge 19 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion pretixprint/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,15 @@
android:logo="@drawable/ic_logo"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">

<meta-data
android:name="android.content.APP_RESTRICTIONS"
android:resource="@xml/app_restrictions" />

<activity
android:name=".ui.MaintenanceActivity"
android:exported="false"
android:label="@string/title_activity_maintenance"
android:theme="@style/AppTheme" />
<activity
android:name=".ui.SystemPrintActivity"
android:exported="false"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package eu.pretix.pretixprint.connections

import android.bluetooth.BluetoothAdapter
import android.annotation.SuppressLint
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.os.Build
Expand All @@ -15,10 +16,13 @@ import eu.pretix.pretixprint.byteprotocols.getProtoClass
import eu.pretix.pretixprint.print.lockManager
import eu.pretix.pretixprint.renderers.renderPages
import io.sentry.Sentry
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeoutException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class BluetoothConnection : ConnectionType {
override val identifier = "bluetooth_printer"
Expand Down Expand Up @@ -56,8 +60,8 @@ class BluetoothConnection : ConnectionType {
}

Log.i("PrintService", "Starting Bluetooth printing")
val adapter = BluetoothAdapter.getDefaultAdapter()
val device = adapter.getRemoteDevice(address)
val bme = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val device = bme.adapter.getRemoteDevice(conf.get("hardware_${type}printer_ip") ?: "")

try {
Log.i("PrintService", "Starting renderPages")
Expand Down Expand Up @@ -85,7 +89,7 @@ class BluetoothConnection : ConnectionType {
try {
connFailure = null
Log.i("PrintService", "Start connection to $address, try $i")
adapter.cancelDiscovery()
bme.adapter.cancelDiscovery()
fallbackSocket.connect()
break
} catch (e: Exception) {
Expand Down Expand Up @@ -135,4 +139,41 @@ class BluetoothConnection : ConnectionType {
throw PrintException(context.applicationContext.getString(R.string.err_generic, e.message))
}
}

@SuppressLint("MissingPermission")
override suspend fun connectAsync(context: Context, type: String): StreamHolder = suspendCancellableCoroutine { cont ->
val conf = PreferenceManager.getDefaultSharedPreferences(context)
val addr = conf.getString("hardware_${type}printer_ip", "")
val fallbackSocket: BluetoothSocket
try {
val bme = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val adapter = bme.adapter
if (adapter == null || !adapter.isEnabled) {
cont.resumeWithException(IllegalStateException("Bluetooth not enabled"))
return@suspendCancellableCoroutine
}
val device = adapter.getRemoteDevice(addr)
if (device.uuids == null) {
cont.resumeWithException(IllegalStateException("Bluetooth device not available"))
return@suspendCancellableCoroutine
}
val socket = device.createInsecureRfcommSocketToServiceRecord(device.uuids.first().uuid)
val clazz = socket.remoteDevice.javaClass
val paramTypes = arrayOf<Class<*>>(Integer.TYPE)
val m = clazz.getMethod("createRfcommSocket", *paramTypes)
fallbackSocket =
m.invoke(socket.remoteDevice, Integer.valueOf(1)) as BluetoothSocket
cont.invokeOnCancellation { fallbackSocket.close() }

fallbackSocket.connect()
} catch (e: Exception) {
cont.resumeWithException(e)
return@suspendCancellableCoroutine
}

val istream = fallbackSocket.inputStream
val ostream = fallbackSocket.outputStream

cont.resume(CloseableStreamHolder(istream, ostream, fallbackSocket))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import org.cups4j.CupsPrinter
import org.cups4j.PrintJob
import java.io.File
import java.io.IOException
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine


class CUPSConnection : ConnectionType {
Expand Down Expand Up @@ -61,4 +63,8 @@ class CUPSConnection : ConnectionType {
}
}
}

override suspend fun connectAsync(context: Context, type: String): StreamHolder = suspendCoroutine { cont ->
cont.resumeWithException(NotImplementedError("raw connection is not available for cups"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package eu.pretix.pretixprint.connections

import android.content.Context
import androidx.preference.PreferenceManager
import java.io.Closeable
import java.io.File
import java.io.InputStream
import java.io.OutputStream

interface ConnectionType {
enum class Input {
Expand All @@ -20,4 +23,20 @@ interface ConnectionType {
fun isConfiguredFor(context: Context, type: String): Boolean {
return !PreferenceManager.getDefaultSharedPreferences(context).getString("hardware_${type}printer_ip", "").isNullOrEmpty()
}
suspend fun connectAsync(context: Context, type: String): StreamHolder
}

open class StreamHolder(val inputStream: InputStream, val outputStream: OutputStream) : Closeable {
override fun close() {
inputStream.close()
outputStream.close()
}
}

class CloseableStreamHolder(inputStream: InputStream, outputStream: OutputStream, private val cs: Closeable):
StreamHolder(inputStream, outputStream) {
override fun close() {
super.close()
cs.close()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import eu.pretix.pretixprint.byteprotocols.*
import eu.pretix.pretixprint.print.lockManager
import eu.pretix.pretixprint.renderers.renderPages
import io.sentry.Sentry
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.util.concurrent.TimeoutException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException


class NetworkConnection : ConnectionType {
Expand Down Expand Up @@ -95,4 +98,22 @@ class NetworkConnection : ConnectionType {
throw PrintException(context.applicationContext.getString(R.string.err_job_io, e.message))
}
}

override suspend fun connectAsync(context: Context, type: String): StreamHolder = suspendCancellableCoroutine { cont ->
val conf = PreferenceManager.getDefaultSharedPreferences(context)
val serverAddr = InetAddress.getByName(conf.getString("hardware_${type}printer_ip", "127.0.0.1"))
val port = Integer.valueOf(conf.getString("hardware_${type}printer_port", "9100")!!)

try {
val socket = Socket(serverAddr, port)
cont.invokeOnCancellation { socket.close() }

val istream = socket.getInputStream()
val ostream = socket.getOutputStream()

cont.resume(CloseableStreamHolder(istream, ostream, socket))
} catch (e: IOException) {
cont.resumeWithException(e)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ val connectionTypes = listOf<ConnectionType>(
CUPSConnection(),
SystemConnection(),
)

fun getConnectionClass(type: String): ConnectionType? {
return connectionTypes.find { it.identifier == type }
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import java.io.IOException
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine


class SunmiInternalConnection : ConnectionType {
Expand Down Expand Up @@ -123,4 +125,8 @@ class SunmiInternalConnection : ConnectionType {
override fun isConfiguredFor(context: Context, type: String): Boolean {
return true
}

override suspend fun connectAsync(context: Context, type: String): StreamHolder = suspendCoroutine { cont ->
cont.resumeWithException(NotImplementedError("raw connection is not available for Sunmi"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import eu.pretix.pretixprint.R
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.math.roundToInt

class SystemConnection : ConnectionType {
Expand All @@ -27,6 +29,10 @@ class SystemConnection : ConnectionType {
return true
}

override suspend fun connectAsync(context: Context, type: String): StreamHolder = suspendCoroutine { cont ->
cont.resumeWithException(NotImplementedError("raw connection is not available for System"))
}

override fun print(
tmpfile: File,
numPages: Int,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ import eu.pretix.pretixprint.byteprotocols.*
import eu.pretix.pretixprint.print.lockManager
import eu.pretix.pretixprint.renderers.renderPages
import io.sentry.Sentry
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.util.concurrent.TimeoutException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.math.min

/*
Expand Down Expand Up @@ -393,7 +396,7 @@ class USBConnection : ConnectionType {
proto.sendUSB(manager, device, futures, conf, type, context)
Log.i("PrintService", "Finished proto.sendUSB()")
}

is SunmiByteProtocol -> {
throw PrintException("Unsupported combination")
}
Expand Down Expand Up @@ -433,4 +436,57 @@ class USBConnection : ConnectionType {
}
Thread.sleep(1000)
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override suspend fun connectAsync(context: Context, type: String): StreamHolder = suspendCancellableCoroutine { cont ->
val conf = PreferenceManager.getDefaultSharedPreferences(context)
val serial = conf.getString("hardware_${type}printer_ip", "0")
val compat = conf.getString("hardware_${type}printer_usbcompat", "false") == "true"

val manager = context.getSystemService(Context.USB_SERVICE) as UsbManager
val devices = mutableMapOf<String, UsbDevice>()

manager.deviceList.forEach {
try {
if (it.value.serialNumber == serial) {
devices[it.key] = it.value
} else if ("${Integer.toHexString(it.value.vendorId)}:${Integer.toHexString(it.value.productId)}" == serial) {
devices[it.key] = it.value
} else if (it.value.deviceName == serial) {
// No longer used, but keep for backwards compatibility
devices[it.key] = it.value
}
} catch (e: SecurityException) {
// On Android 10, USBDevices that have not expressively been granted access to
// will raise an SecurityException upon accessing the Serial Number. We are just
// ignoring those devices.
}
}
if (devices.size != 1) {
cont.resumeWithException(PrintException(context.getString(R.string.err_printer_not_found, serial)))
}

val recv = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
context.unregisterReceiver(this)
if (ACTION_USB_PERMISSION != intent.action) { return }

val device: UsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)!!
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
val ostream = UsbOutputStream(manager, device, compat)
val istream = UsbInputStream(manager, device, compat)

cont.resume(StreamHolder(istream, ostream))
} else {
cont.resumeWithException(PrintException(context.getString(R.string.err_usb_permission_denied)))
}
}
}

val filter = IntentFilter(ACTION_USB_PERMISSION)
context.registerReceiver(recv, filter)
cont.invokeOnCancellation { context.unregisterReceiver(recv) }
val permissionIntent = PendingIntent.getBroadcast(context, 0, Intent(ACTION_USB_PERMISSION), 0)
manager.requestPermission(devices.values.first(), permissionIntent)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import eu.pretix.pretixprint.ui.BluetoothDevicePicker.Companion.EXTRA_FILTER_TYP
import eu.pretix.pretixprint.ui.BluetoothDevicePicker.Companion.EXTRA_NEED_AUTH
import eu.pretix.pretixprint.ui.BluetoothDevicePicker.Companion.FILTER_TYPE_ALL


class BluetoothSettingsFragment : SetupFragment() {
override fun onCreateView(
inflater: LayoutInflater,
Expand All @@ -37,7 +36,7 @@ class BluetoothSettingsFragment : SetupFragment() {
val prefs = PreferenceManager.getDefaultSharedPreferences(requireContext())
val view = inflater.inflate(R.layout.fragment_bluetooth_settings, container, false)

val deviceManager = BluetoothDeviceManager(this.requireContext())
val deviceManager = BluetoothDeviceManager(requireContext())

val teMAC = view.findViewById<TextInputEditText>(R.id.teMAC)

Expand Down
Loading