diff --git a/android-smsmms/src/main/java/android/net/DhcpInfoInternal.java b/android-smsmms/src/main/java/android/net/DhcpInfoInternal.java deleted file mode 100644 index 99ab2fda..00000000 --- a/android-smsmms/src/main/java/android/net/DhcpInfoInternal.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * 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 android.net; - -import android.text.TextUtils; -import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - -/** - * A simple object for retrieving the results of a DHCP request. - * Replaces (internally) the IPv4-only DhcpInfo class. - * - * @hide - */ -public class DhcpInfoInternal { - private final static String TAG = "DhcpInfoInternal"; - public String ipAddress; - public int prefixLength; - - public String dns1; - public String dns2; - - public String serverAddress; - public int leaseDuration; - - /** - * Vendor specific information (from RFC 2132). - */ - public String vendorInfo; - - private Collection mRoutes; - - public DhcpInfoInternal() { - mRoutes = new ArrayList(); - } - - public void addRoute(RouteInfo routeInfo) { - mRoutes.add(routeInfo); - } - - public Collection getRoutes() { - return Collections.unmodifiableCollection(mRoutes); - } - - private int convertToInt(String addr) { - if (addr != null) { - try { - InetAddress inetAddress = NetworkUtilsHelper.numericToInetAddress(addr); - if (inetAddress instanceof Inet4Address) { - return NetworkUtilsHelper.inetAddressToInt(inetAddress); - } - } catch (IllegalArgumentException e) { - } - } - return 0; - } - - public DhcpInfo makeDhcpInfo() { - DhcpInfo info = new DhcpInfo(); - info.ipAddress = convertToInt(ipAddress); - for (RouteInfo route : mRoutes) { - if (route.isDefaultRoute()) { - info.gateway = convertToInt(route.getGateway().getHostAddress()); - break; - } - } - try { - info.netmask = NetworkUtilsHelper.prefixLengthToNetmaskInt(prefixLength); - } catch (IllegalArgumentException e) { - } - info.dns1 = convertToInt(dns1); - info.dns2 = convertToInt(dns2); - info.serverAddress = convertToInt(serverAddress); - info.leaseDuration = leaseDuration; - return info; - } - - public LinkAddress makeLinkAddress() { - if (TextUtils.isEmpty(ipAddress)) { - Log.e(TAG, "makeLinkAddress with empty ipAddress"); - return null; - } - return new LinkAddress(NetworkUtilsHelper.numericToInetAddress(ipAddress), prefixLength); - } - - public LinkProperties makeLinkProperties() { - LinkProperties p = new LinkProperties(); - p.addLinkAddress(makeLinkAddress()); - for (RouteInfo route : mRoutes) { - p.addRoute(route); - } - //if empty, connectivity configures default DNS - if (TextUtils.isEmpty(dns1) == false) { - p.addDns(NetworkUtilsHelper.numericToInetAddress(dns1)); - } else { - Log.d(TAG, "makeLinkProperties with empty dns1!"); - } - if (TextUtils.isEmpty(dns2) == false) { - p.addDns(NetworkUtilsHelper.numericToInetAddress(dns2)); - } else { - Log.d(TAG, "makeLinkProperties with empty dns2!"); - } - return p; - } - - /* Updates the DHCP fields that need to be retained from - * original DHCP request if the DHCP renewal shows them as - * being empty - */ - public void updateFromDhcpRequest(DhcpInfoInternal orig) { - if (orig == null) return; - - if (TextUtils.isEmpty(dns1)) { - dns1 = orig.dns1; - } - - if (TextUtils.isEmpty(dns2)) { - dns2 = orig.dns2; - } - - if (mRoutes.size() == 0) { - for (RouteInfo route : orig.getRoutes()) { - addRoute(route); - } - } - } - - /** - * Test if this DHCP lease includes vendor hint that network link is - * metered, and sensitive to heavy data transfers. - */ - public boolean hasMeteredHint() { - if (vendorInfo != null) { - return vendorInfo.contains("ANDROID_METERED"); - } else { - return false; - } - } - - public String toString() { - String routeString = ""; - for (RouteInfo route : mRoutes) routeString += route.toString() + " | "; - return "addr: " + ipAddress + "/" + prefixLength + - " mRoutes: " + routeString + - " dns: " + dns1 + "," + dns2 + - " dhcpServer: " + serverAddress + - " leaseDuration: " + leaseDuration; - } -} diff --git a/android-smsmms/src/main/java/android/net/NetworkUtilsHelper.java b/android-smsmms/src/main/java/android/net/NetworkUtilsHelper.java index cb3c2d9d..d897ebf8 100644 --- a/android-smsmms/src/main/java/android/net/NetworkUtilsHelper.java +++ b/android-smsmms/src/main/java/android/net/NetworkUtilsHelper.java @@ -58,223 +58,6 @@ public class NetworkUtilsHelper { */ public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES; - /** - * Reset IPv6 or IPv4 sockets that are connected via the named interface. - * - * @param interfaceName is the interface to reset - * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES} - */ - public native static int resetConnections(String interfaceName, int mask); - - /** - * Start the DHCP client daemon, in order to have it request addresses - * for the named interface, and then configure the interface with those - * addresses. This call blocks until it obtains a result (either success - * or failure) from the daemon. - * - * @param interfaceName the name of the interface to configure - * @param ipInfo if the request succeeds, this object is filled in with - * the IP address information. - * @return {@code true} for success, {@code false} for failure - */ - public native static boolean runDhcp(String interfaceName, DhcpInfoInternal ipInfo); - - /** - * Initiate renewal on the Dhcp client daemon. This call blocks until it obtains - * a result (either success or failure) from the daemon. - * - * @param interfaceName the name of the interface to configure - * @param ipInfo if the request succeeds, this object is filled in with - * the IP address information. - * @return {@code true} for success, {@code false} for failure - */ - public native static boolean runDhcpRenew(String interfaceName, DhcpInfoInternal ipInfo); - - /** - * Shut down the DHCP client daemon. - * - * @param interfaceName the name of the interface for which the daemon - * should be stopped - * @return {@code true} for success, {@code false} for failure - */ - public native static boolean stopDhcp(String interfaceName); - - /** - * Release the current DHCP lease. - * - * @param interfaceName the name of the interface for which the lease should - * be released - * @return {@code true} for success, {@code false} for failure - */ - public native static boolean releaseDhcpLease(String interfaceName); - - /** - * Return the last DHCP-related error message that was recorded. - *

NOTE: This string is not localized, but currently it is only - * used in logging. - * - * @return the most recent error message, if any - */ - public native static String getDhcpError(); - - /** - * Convert a IPv4 address from an integer to an InetAddress. - * - * @param hostAddress an int corresponding to the IPv4 address in network byte order - */ - public static InetAddress intToInetAddress(int hostAddress) { - byte[] addressBytes = {(byte) (0xff & hostAddress), - (byte) (0xff & (hostAddress >> 8)), - (byte) (0xff & (hostAddress >> 16)), - (byte) (0xff & (hostAddress >> 24))}; - - try { - return InetAddress.getByAddress(addressBytes); - } catch (UnknownHostException e) { - throw new AssertionError(); - } - } - - /** - * Convert a IPv4 address from an InetAddress to an integer - * - * @param inetAddr is an InetAddress corresponding to the IPv4 address - * @return the IP address as an integer in network byte order - */ - public static int inetAddressToInt(InetAddress inetAddr) - throws IllegalArgumentException { - byte[] addr = inetAddr.getAddress(); - if (addr.length != 4) { - throw new IllegalArgumentException("Not an IPv4 address"); - } - return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | - ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); - } - - /** - * Convert a network prefix length to an IPv4 netmask integer - * - * @param prefixLength - * @return the IPv4 netmask as an integer in network byte order - */ - public static int prefixLengthToNetmaskInt(int prefixLength) - throws IllegalArgumentException { - if (prefixLength < 0 || prefixLength > 32) { - throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); - } - int value = 0xffffffff << (32 - prefixLength); - return Integer.reverseBytes(value); - } - - /** - * Convert a IPv4 netmask integer to a prefix length - * - * @param netmask as an integer in network byte order - * @return the network prefix length - */ - public static int netmaskIntToPrefixLength(int netmask) { - return Integer.bitCount(netmask); - } - - /** - * Create an InetAddress from a string where the string must be a standard - * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure - * but it will throw an IllegalArgumentException in that case. - * - * @param addrString - * @return the InetAddress - * @hide - */ - public static InetAddress numericToInetAddress(String addrString) - throws IllegalArgumentException { - return null; - } - - /** - * Get InetAddress masked with prefixLength. Will never return null. - * - * @param IP address which will be masked with specified prefixLength - * @param prefixLength the prefixLength used to mask the IP - */ - public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { - if (address == null) { - throw new RuntimeException("getNetworkPart doesn't accept null address"); - } - - byte[] array = address.getAddress(); - - if (prefixLength < 0 || prefixLength > array.length * 8) { - throw new RuntimeException("getNetworkPart - bad prefixLength"); - } - - int offset = prefixLength / 8; - int reminder = prefixLength % 8; - byte mask = (byte) (0xFF << (8 - reminder)); - - if (offset < array.length) array[offset] = (byte) (array[offset] & mask); - - offset++; - - for (; offset < array.length; offset++) { - array[offset] = 0; - } - - InetAddress netPart = null; - try { - netPart = InetAddress.getByAddress(array); - } catch (UnknownHostException e) { - throw new RuntimeException("getNetworkPart error - " + e.toString()); - } - return netPart; - } - - /** - * Check if IP address type is consistent between two InetAddress. - * - * @return true if both are the same type. False otherwise. - */ - public static boolean addressTypeMatches(InetAddress left, InetAddress right) { - return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) || - ((left instanceof Inet6Address) && (right instanceof Inet6Address))); - } - - /** - * Convert a 32 char hex string into a Inet6Address. - * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be - * made into an Inet6Address - * - * @param addrHexString a 32 character hex string representing an IPv6 addr - * @return addr an InetAddress representation for the string - */ - public static InetAddress hexToInet6Address(String addrHexString) - throws IllegalArgumentException { - try { - return numericToInetAddress(String.format("%s:%s:%s:%s:%s:%s:%s:%s", - addrHexString.substring(0, 4), addrHexString.substring(4, 8), - addrHexString.substring(8, 12), addrHexString.substring(12, 16), - addrHexString.substring(16, 20), addrHexString.substring(20, 24), - addrHexString.substring(24, 28), addrHexString.substring(28, 32))); - } catch (Exception e) { - Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e); - throw new IllegalArgumentException(e); - } - } - - /** - * Create a string array of host addresses from a collection of InetAddresses - * - * @param addrs a Collection of InetAddresses - * @return an array of Strings containing their host addresses - */ - public static String[] makeStrings(Collection addrs) { - String[] result = new String[addrs.size()]; - int i = 0; - for (InetAddress addr : addrs) { - result[i++] = addr.getHostAddress(); - } - return result; - } - /** * Trim leading zeros from IPv4 address strings * Our base libraries will interpret that as octel.. @@ -303,4 +86,5 @@ public class NetworkUtilsHelper { result = builder.toString(); return result; } + } diff --git a/android-smsmms/src/main/java/android/net/RouteInfo.java b/android-smsmms/src/main/java/android/net/RouteInfo.java deleted file mode 100644 index 2c049ffa..00000000 --- a/android-smsmms/src/main/java/android/net/RouteInfo.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * 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 android.net; - -import android.os.Parcel; -import android.os.Parcelable; -import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed - -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Collection; - -/** - * A simple container for route information. - * - * @hide - */ -public class RouteInfo implements Parcelable { - private static final String TAG = "RouteInfo"; - /** - * The IP destination address for this route. - */ - private final LinkAddress mDestination; - - /** - * The gateway address for this route. - */ - private final InetAddress mGateway; - - private final boolean mIsDefault; - private final boolean mIsHost; - - public RouteInfo(LinkAddress destination, InetAddress gateway) { - if (destination == null) { - if (gateway != null) { - if (gateway instanceof Inet4Address) { - try { - destination = new LinkAddress(Inet4Address.getLocalHost(), 0); - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - Log.e(TAG, "exception thrown", e); - } - } else { - try { - destination = new LinkAddress(Inet6Address.getLocalHost(), 0); - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - Log.e(TAG, "exception thrown", e); - } - } - } else { - // no destination, no gateway. invalid. - throw new RuntimeException("Invalid arguments passed in."); - } - } - if (gateway == null) { - if (destination.getAddress() instanceof Inet4Address) { - try { - gateway = Inet4Address.getLocalHost(); - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - Log.e(TAG, "exception thrown", e); - } - } else { - try { - gateway = Inet6Address.getLocalHost(); - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - Log.e(TAG, "exception thrown", e); - } - } - } - mDestination = new LinkAddress(NetworkUtilsHelper.getNetworkPart(destination.getAddress(), - destination.getNetworkPrefixLength()), destination.getNetworkPrefixLength()); - mGateway = gateway; - mIsDefault = isDefault(); - mIsHost = isHost(); - } - - public RouteInfo(InetAddress gateway) { - this(null, gateway); - } - - public static RouteInfo makeHostRoute(InetAddress host) { - return makeHostRoute(host, null); - } - - public static RouteInfo makeHostRoute(InetAddress host, InetAddress gateway) { - if (host == null) return null; - - if (host instanceof Inet4Address) { - return new RouteInfo(new LinkAddress(host, 32), gateway); - } else { - return new RouteInfo(new LinkAddress(host, 128), gateway); - } - } - - private boolean isHost() { - try { - return (mGateway.equals(Inet4Address.getLocalHost()) || mGateway.equals(Inet6Address.getLocalHost())); - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - return false; - } - } - - private boolean isDefault() { - boolean val = false; - if (mGateway != null) { - if (mGateway instanceof Inet4Address) { - val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0); - } else { - val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0); - } - } - return val; - } - - - public LinkAddress getDestination() { - return mDestination; - } - - public InetAddress getGateway() { - return mGateway; - } - - public boolean isDefaultRoute() { - return mIsDefault; - } - - public boolean isHostRoute() { - return mIsHost; - } - - public String toString() { - String val = ""; - if (mDestination != null) val = mDestination.toString(); - if (mGateway != null) val += " -> " + mGateway.getHostAddress(); - return val; - } - - public int describeContents() { - return 0; - } - - public void writeToParcel(Parcel dest, int flags) { - if (mDestination == null) { - dest.writeByte((byte) 0); - } else { - dest.writeByte((byte) 1); - dest.writeByteArray(mDestination.getAddress().getAddress()); - dest.writeInt(mDestination.getNetworkPrefixLength()); - } - - if (mGateway == null) { - dest.writeByte((byte) 0); - } else { - dest.writeByte((byte) 1); - dest.writeByteArray(mGateway.getAddress()); - } - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - - if (!(obj instanceof RouteInfo)) return false; - - RouteInfo target = (RouteInfo) obj; - - boolean sameDestination = (mDestination == null) ? - target.getDestination() == null - : mDestination.equals(target.getDestination()); - - boolean sameAddress = (mGateway == null) ? - target.getGateway() == null - : mGateway.equals(target.getGateway()); - - return sameDestination && sameAddress - && mIsDefault == target.mIsDefault; - } - - @Override - public int hashCode() { - return (mDestination == null ? 0 : mDestination.hashCode()) - + (mGateway == null ? 0 : mGateway.hashCode()) - + (mIsDefault ? 3 : 7); - } - - public static final Creator CREATOR = - new Creator() { - public RouteInfo createFromParcel(Parcel in) { - InetAddress destAddr = null; - int prefix = 0; - InetAddress gateway = null; - - if (in.readByte() == 1) { - byte[] addr = in.createByteArray(); - prefix = in.readInt(); - - try { - destAddr = InetAddress.getByAddress(addr); - } catch (UnknownHostException e) { - } - } - - if (in.readByte() == 1) { - byte[] addr = in.createByteArray(); - - try { - gateway = InetAddress.getByAddress(addr); - } catch (UnknownHostException e) { - } - } - - LinkAddress dest = null; - - if (destAddr != null) { - dest = new LinkAddress(destAddr, prefix); - } - - return new RouteInfo(dest, gateway); - } - - public RouteInfo[] newArray(int size) { - return new RouteInfo[size]; - } - }; - - private boolean matches(InetAddress destination) { - if (destination == null) return false; - - // if the destination is present and the route is default. - // return true - if (isDefault()) return true; - - // match the route destination and destination with prefix length - InetAddress dstNet = NetworkUtilsHelper.getNetworkPart(destination, - mDestination.getNetworkPrefixLength()); - - return mDestination.getAddress().equals(dstNet); - } - - /** - * Find the route from a Collection of routes that best matches a given address. - * May return null if no routes are applicable. - * - * @param routes a Collection of RouteInfos to chose from - * @param dest the InetAddress your trying to get to - * @return the RouteInfo from the Collection that best fits the given address - */ - public static RouteInfo selectBestRoute(Collection routes, InetAddress dest) { - if ((routes == null) || (dest == null)) return null; - - RouteInfo bestRoute = null; - // pick a longest prefix match under same address type - for (RouteInfo route : routes) { - if (NetworkUtilsHelper.addressTypeMatches(route.mDestination.getAddress(), dest)) { - if ((bestRoute != null) && - (bestRoute.mDestination.getNetworkPrefixLength() >= - route.mDestination.getNetworkPrefixLength())) { - continue; - } - if (route.matches(dest)) bestRoute = route; - } - } - return bestRoute; - } -} diff --git a/data/src/main/java/com/moez/QKSMS/receiver/MmsReceivedReceiver.kt b/data/src/main/java/com/moez/QKSMS/receiver/MmsReceivedReceiver.kt index a30fe15b..4bcee55c 100644 --- a/data/src/main/java/com/moez/QKSMS/receiver/MmsReceivedReceiver.kt +++ b/data/src/main/java/com/moez/QKSMS/receiver/MmsReceivedReceiver.kt @@ -34,39 +34,21 @@ */ package dev.octoshrimpy.quik.receiver -import android.app.PendingIntent import android.content.BroadcastReceiver -import android.content.ContentResolver import android.content.Context import android.content.Intent import android.net.Uri -import android.os.AsyncTask import android.os.Parcelable -import android.provider.Telephony import android.telephony.SmsManager -import androidx.core.net.toUri import androidx.work.OneTimeWorkRequestBuilder import androidx.work.OutOfQuotaPolicy import androidx.work.WorkManager import androidx.work.workDataOf -import com.android.mms.service_alt.DownloadRequest -import com.android.mms.service_alt.MmsConfig -import com.android.mms.service_alt.MmsConfig.Overridden -import com.android.mms.transaction.DownloadManager -import com.google.android.mms.pdu_alt.AcknowledgeInd -import com.google.android.mms.pdu_alt.EncodedStringValue -import com.google.android.mms.pdu_alt.NotificationInd -import com.google.android.mms.pdu_alt.NotifyRespInd -import com.google.android.mms.pdu_alt.PduComposer -import com.google.android.mms.pdu_alt.PduHeaders -import com.google.android.mms.pdu_alt.PduParser -import com.google.android.mms.pdu_alt.PduPersister -import com.google.android.mms.pdu_alt.RetrieveConf -import com.google.android.mms.util_alt.SqliteWrapper -import com.klinker.android.send_message.MmsSentReceiver -import com.klinker.android.send_message.SmsManagerFactory +import com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_FILE_PATH +import com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_LOCATION_URL +import com.klinker.android.send_message.MmsReceivedReceiver.EXTRA_URI +import com.klinker.android.send_message.MmsReceivedReceiver.SUBSCRIPTION_ID import com.klinker.android.send_message.Utils -import dev.octoshrimpy.quik.interactor.ReceiveMms import dev.octoshrimpy.quik.worker.ReceiveMmsWorker import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_FILE_PATH import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_LOCATION_URL @@ -74,237 +56,10 @@ import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_M import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_EXTRA_URI import dev.octoshrimpy.quik.worker.ReceiveMmsWorker.Companion.INPUT_DATA_SUBSCRIPTION_ID import timber.log.Timber -import java.io.File -import java.io.FileInputStream -import java.io.FileNotFoundException -import java.io.FileOutputStream -import java.io.IOException -import java.util.UUID -import java.util.concurrent.ExecutorService -import java.util.concurrent.Executors class MmsReceivedReceiver : BroadcastReceiver() { - companion object { - const val EXTRA_FILE_PATH: String = "file_path" - const val EXTRA_LOCATION_URL: String = "location_url" - const val EXTRA_URI: String = "notification_ind_uri" - const val SUBSCRIPTION_ID: String = "subscription_id" - - private const val LOCATION_SELECTION = - Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?" - - private val RECEIVE_NOTIFICATION_EXECUTOR: ExecutorService = - Executors.newSingleThreadExecutor() - - private fun getNotificationInd(context: Context, extraUri: String) = - PduPersister.getPduPersister(context).load(extraUri.toUri()) as NotificationInd - - fun onReceiveWorker( - context: Context, subscriptionId: Int, filePath: String, locationUrl: String, - mmsHttpStatus: Int, extraUri: String, receiveMms: ReceiveMms - ) { - if (filePath.isEmpty()) { - Timber.e("empty file path") - return - } - - if (locationUrl.isEmpty()) { - Timber.e("empty location url") - return - } - - if (extraUri.isEmpty()) { - Timber.e("empty extra uri") - return - } - - Timber.v(filePath) - - val downloadFile = File(filePath) - try { - // read file into a bytearray - val mmsData = FileInputStream(downloadFile).use { inputStream -> - val fileLength = downloadFile.length().toInt() - ByteArray(fileLength).let { bytes -> - inputStream.read(bytes, 0, fileLength) - bytes - } - } - - Timber.v("response buffered length: ${mmsData.size}") - - if (mmsData.isNotEmpty()) { - val notificationTasks = - getNotificationTasks(context, subscriptionId, extraUri, mmsData) - - // persist message - val messageUri = DownloadRequest.persist( - context, mmsData, Overridden(MmsConfig(context), null), - locationUrl, subscriptionId, null - ) - - // run notifiers to notify back to mmsc - Timber.v("running the common async notifier for download") - for (task in notificationTasks) - task.executeOnExecutor(RECEIVE_NOTIFICATION_EXECUTOR) - - handleHttpError(context, mmsHttpStatus, locationUrl) - - DownloadManager.finishDownload(locationUrl) - - // message is 'raw' received, so do quik app processing - if (messageUri != null) - receiveMms.execute(messageUri) - } - else Timber.e("empty mms data") - } catch (e: FileNotFoundException) { - Timber.e("file not found", e) - } catch (e: IOException) { - Timber.e("io exception", e) - } finally { - downloadFile.delete() - } - } - - private fun handleHttpError(context: Context, mmsHttpStatus: Int, locationUrl: String) { - if ((mmsHttpStatus == 404) || (mmsHttpStatus == 400)) { - // Delete the corresponding NotificationInd - SqliteWrapper.delete( - context, context.contentResolver, Telephony.Mms.CONTENT_URI, - LOCATION_SELECTION, - arrayOf( - PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND.toString(), - locationUrl - ) - ) - } - } - - private abstract class CommonAsyncTask( - protected val mContext: Context, private val subscriptionId: Int, - protected val mNotificationInd: NotificationInd - ) : AsyncTask() { - - fun sendPdu(pduBytes: ByteArray) { - // write pdu bytes to temporary file - val fileName = "send.notify.${UUID.randomUUID()}.dat" - - val contentUri = Uri.Builder() - .authority("${mContext.packageName}.MmsFileProvider") - .path(fileName) - .scheme(ContentResolver.SCHEME_CONTENT) - .build() - - try { - FileOutputStream(File(mContext.cacheDir, fileName)).use { outputStream -> - outputStream.write(pduBytes) - } - Timber.v("notify send file $fileName") - } catch (e: Exception) { - Timber.e("error writing notify send file", e) - } - - val useWapMmsc = com.android.mms.MmsConfig.getNotifyWapMMSC() - if (useWapMmsc) - Timber.v("using content location for wap mmsc") - - SmsManagerFactory.createSmsManager(subscriptionId).sendMultimediaMessage( - mContext, contentUri, - if (useWapMmsc) String(mNotificationInd.contentLocation) - else null, - null, - PendingIntent.getBroadcast( - mContext, 0, - Intent(mContext, MessageSentReceiver::class.java) - .putExtra(MmsSentReceiver.EXTRA_FILE_PATH, fileName) - .putExtra(MessageSentReceiver.EXTRA_IS_NOTIFY, 1), - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE - ) - ) - } - } - - private class NotifyRespTask(context: Context, subscriptionId: Int, ind: NotificationInd) : - CommonAsyncTask(context, subscriptionId, ind) { - override fun doInBackground(vararg params: Void?): Void? { - // Create the M-NotifyResp.ind - Timber.v("create m-notifyresp.ind") - try { - val notifyRespInd = NotifyRespInd( - PduHeaders.CURRENT_MMS_VERSION, - mNotificationInd.transactionId, - PduHeaders.STATUS_RETRIEVED - ) - - // Pack M-NotifyResp.ind and send it - sendPdu(PduComposer(mContext, notifyRespInd).make()) - } catch (e: Exception) { - Timber.e("error creating m-notifyresp.ind", e) - } - - return null - } - } - - private class AcknowledgeIndTask( - context: Context, subscriptionId: Int, ind: NotificationInd, - private val mRetrieveConf: RetrieveConf - ) : CommonAsyncTask(context, subscriptionId, ind) { - override fun doInBackground(vararg params: Void?): Void? { - // Send M-Acknowledge.ind to MMSC if required. - // If the Transaction-ID isn't set in the M-Retrieve.conf, it means - // the MMS proxy-relay doesn't require an ACK. - Timber.v("create m-acknowledge.ind") - mRetrieveConf.transactionId?.let { tranId -> - // Create M-Acknowledge.ind - try { - val acknowledgeInd = AcknowledgeInd(PduHeaders.CURRENT_MMS_VERSION, tranId) - - // insert the 'from' address per spec - acknowledgeInd.from = EncodedStringValue( - Utils.getMyPhoneNumber(mContext).orEmpty() - ) - - // Pack M-Acknowledge.ind and send it - sendPdu(PduComposer(mContext, acknowledgeInd).make()) - } catch (e: Exception) { - Timber.e("error creating m-acknowledge.ind", e) - } - } ?: let { Timber.e("no transaction id for creating m-acknowledge.ind") } - - return null - } - } - - private fun getNotificationTasks( - context: Context, subscriptionId: Int, extraUri: String, mmsData: ByteArray - ): List { - val pdu = PduParser( - mmsData, - Overridden(MmsConfig(context), null).supportMmsContentDisposition - ).parse() - - if (pdu is RetrieveConf) { - try { - Timber.v("create notification tasks") - return getNotificationInd(context, extraUri).let { notificationInd -> - listOf( - AcknowledgeIndTask(context, subscriptionId, notificationInd, pdu), - NotifyRespTask(context, subscriptionId, notificationInd) - ) - } - } catch (e: Exception) { - Timber.e("error get notification tasks", e) - } - } else - Timber.e("MmsReceivedReceiver.sendNotification failed to parse pdu") - - return listOf() - } - } - override fun onReceive(context: Context, intent: Intent) { - Timber.v("mms downloaded, persisting it to the database with worker") + Timber.v("mms downloaded. create worker to process") // start worker with message id as param WorkManager.getInstance(context).enqueue( diff --git a/data/src/main/java/com/moez/QKSMS/worker/InjectionWorkerFactory.kt b/data/src/main/java/com/moez/QKSMS/worker/InjectionWorkerFactory.kt index 4464246e..7fd5667e 100644 --- a/data/src/main/java/com/moez/QKSMS/worker/InjectionWorkerFactory.kt +++ b/data/src/main/java/com/moez/QKSMS/worker/InjectionWorkerFactory.kt @@ -23,17 +23,30 @@ import androidx.work.ListenableWorker import androidx.work.Worker import androidx.work.WorkerFactory import androidx.work.WorkerParameters -import dev.octoshrimpy.quik.interactor.ReceiveMms -import dev.octoshrimpy.quik.interactor.ReceiveSms +import dev.octoshrimpy.quik.blocking.BlockingClient +import dev.octoshrimpy.quik.interactor.UpdateBadge +import dev.octoshrimpy.quik.manager.ActiveConversationManager import dev.octoshrimpy.quik.manager.NotificationManager +import dev.octoshrimpy.quik.manager.ShortcutManager +import dev.octoshrimpy.quik.repository.ConversationRepository +import dev.octoshrimpy.quik.repository.MessageRepository import dev.octoshrimpy.quik.repository.ScheduledMessageRepository +import dev.octoshrimpy.quik.repository.SyncRepository +import dev.octoshrimpy.quik.util.Preferences import javax.inject.Inject class InjectionWorkerFactory @Inject constructor( - private val receiveSms: ReceiveSms, - private val receiveMms: ReceiveMms, + private val conversationRepo: ConversationRepository, + private val blockingClient: BlockingClient, + private val prefs: Preferences, + private val messageRepo: MessageRepository, + private val updateBadge: UpdateBadge, + private val shortcutManager: ShortcutManager, private val scheduledMessageRepository: ScheduledMessageRepository, private val notificationManager: NotificationManager, + private val activeConversationManager: ActiveConversationManager, + private val syncRepo: SyncRepository, + ) : WorkerFactory() { override fun createWorker( appContext: Context, @@ -50,12 +63,24 @@ class InjectionWorkerFactory @Inject constructor( is HousekeepingWorker -> instance.scheduledMessageRepository = scheduledMessageRepository is ReceiveSmsWorker -> { - instance.receiveSms = receiveSms + instance.conversationRepo = conversationRepo + instance.blockingClient = blockingClient + instance.prefs = prefs + instance.messageRepo = messageRepo + instance.shortcutManager = shortcutManager instance.notificationManager = notificationManager + instance.updateBadge = updateBadge } is ReceiveMmsWorker -> { - instance.receiveMms = receiveMms + instance.syncRepo = syncRepo + instance.activeConversationManager = activeConversationManager + instance.conversationRepo = conversationRepo + instance.blockingClient = blockingClient + instance.prefs = prefs + instance.messageRepo = messageRepo + instance.shortcutManager = shortcutManager instance.notificationManager = notificationManager + instance.updateBadge = updateBadge } } diff --git a/data/src/main/java/com/moez/QKSMS/worker/ReceiveMmsWorker.kt b/data/src/main/java/com/moez/QKSMS/worker/ReceiveMmsWorker.kt index 3f12fda6..2d227d76 100644 --- a/data/src/main/java/com/moez/QKSMS/worker/ReceiveMmsWorker.kt +++ b/data/src/main/java/com/moez/QKSMS/worker/ReceiveMmsWorker.kt @@ -18,14 +18,48 @@ */ package dev.octoshrimpy.quik.worker +import android.app.PendingIntent +import android.content.ContentResolver import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Telephony +import androidx.core.net.toUri import androidx.work.ForegroundInfo import androidx.work.Worker import androidx.work.WorkerParameters -import dev.octoshrimpy.quik.interactor.ReceiveMms +import com.android.mms.service_alt.DownloadRequest +import com.android.mms.service_alt.MmsConfig +import com.android.mms.service_alt.MmsConfig.Overridden +import com.android.mms.transaction.DownloadManager +import com.google.android.mms.pdu_alt.AcknowledgeInd +import com.google.android.mms.pdu_alt.EncodedStringValue +import com.google.android.mms.pdu_alt.NotificationInd +import com.google.android.mms.pdu_alt.NotifyRespInd +import com.google.android.mms.pdu_alt.PduComposer +import com.google.android.mms.pdu_alt.PduHeaders +import com.google.android.mms.pdu_alt.PduPersister +import com.google.android.mms.util_alt.SqliteWrapper +import com.klinker.android.send_message.MmsSentReceiver +import com.klinker.android.send_message.SmsManagerFactory +import com.klinker.android.send_message.Utils +import dev.octoshrimpy.quik.blocking.BlockingClient +import dev.octoshrimpy.quik.interactor.UpdateBadge +import dev.octoshrimpy.quik.manager.ActiveConversationManager import dev.octoshrimpy.quik.manager.NotificationManager -import dev.octoshrimpy.quik.receiver.MmsReceivedReceiver +import dev.octoshrimpy.quik.manager.ShortcutManager +import dev.octoshrimpy.quik.receiver.MessageSentReceiver +import dev.octoshrimpy.quik.repository.ConversationRepository +import dev.octoshrimpy.quik.repository.MessageRepository +import dev.octoshrimpy.quik.repository.SyncRepository +import dev.octoshrimpy.quik.util.Preferences import timber.log.Timber +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException +import java.util.UUID import javax.inject.Inject class ReceiveMmsWorker(appContext: Context, workerParams: WorkerParameters) @@ -36,29 +70,281 @@ class ReceiveMmsWorker(appContext: Context, workerParams: WorkerParameters) const val INPUT_DATA_EXTRA_LOCATION_URL = "locationUrl" const val INPUT_DATA_EXTRA_MMS_HTTP_STATUS = "mmsHttpStatus" const val INPUT_DATA_EXTRA_URI = "extraUri" + + private const val LOCATION_SELECTION = + Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?" } - @Inject lateinit var receiveMms: ReceiveMms + @Inject lateinit var activeConversationManager: ActiveConversationManager + @Inject lateinit var conversationRepo: ConversationRepository + @Inject lateinit var blockingClient: BlockingClient + @Inject lateinit var prefs: Preferences + @Inject lateinit var syncRepo: SyncRepository + @Inject lateinit var messageRepo: MessageRepository @Inject lateinit var notificationManager: NotificationManager + @Inject lateinit var updateBadge: UpdateBadge + @Inject lateinit var shortcutManager: ShortcutManager override fun doWork(): Result { Timber.v("started") - MmsReceivedReceiver.onReceiveWorker( - applicationContext, - inputData.getInt(INPUT_DATA_SUBSCRIPTION_ID, -1), - inputData.getString(INPUT_DATA_EXTRA_FILE_PATH) ?: "", - inputData.getString(INPUT_DATA_EXTRA_LOCATION_URL) ?: "", - inputData.getInt(INPUT_DATA_EXTRA_MMS_HTTP_STATUS, 0), - inputData.getString(INPUT_DATA_EXTRA_URI) ?: "", - receiveMms - ) + val subscriptionId = inputData.getInt(INPUT_DATA_SUBSCRIPTION_ID, -1) + val filePath = inputData.getString(INPUT_DATA_EXTRA_FILE_PATH) ?: "" + val locationUrl = inputData.getString(INPUT_DATA_EXTRA_LOCATION_URL) ?: "" + val extraUri = inputData.getString(INPUT_DATA_EXTRA_URI) ?: "" + + if (filePath.isEmpty()) { + Timber.e("empty file path") + return Result.failure(inputData) + } + + if (locationUrl.isEmpty()) { + Timber.e("empty location url") + return Result.failure(inputData) + } + + if (extraUri.isEmpty()) { + Timber.e("empty extra uri") + return Result.failure(inputData) + } + + Timber.v(filePath) + + val downloadFile = File(filePath) + try { + // read file into a bytearray + val mmsData = FileInputStream(downloadFile).use { inputStream -> + val fileLength = downloadFile.length().toInt() + ByteArray(fileLength).let { bytes -> + inputStream.read(bytes, 0, fileLength) + bytes + } + } + + Timber.v("response buffered length: ${mmsData.size}") + + if (mmsData.isNotEmpty()) { + // build notification ind (beware this must be done prior to downloadrequest.persist) + val notificationInd = + PduPersister.getPduPersister(applicationContext).load(extraUri.toUri()) + as NotificationInd + + // persist message + val messageUri = DownloadRequest.persist( + applicationContext, mmsData, + Overridden(MmsConfig(applicationContext), null), + locationUrl, subscriptionId, null + ) + + handleHttpError( + applicationContext, + inputData.getInt(INPUT_DATA_EXTRA_MMS_HTTP_STATUS, 0), + locationUrl + ) + + DownloadManager.finishDownload(locationUrl) + + // if message was persisted ok + if (messageUri != null) { + // Sync the message + val message = syncRepo.syncMessage(messageUri) + ?: return Result.failure(inputData) + + // TODO: Ideally this is done when we're saving the MMS to ContentResolver + // This change can be made once we move the MMS storing code to the Data module + if (activeConversationManager.getActiveConversation() == message.threadId) { + messageRepo.markRead(listOf(message.threadId)) + } + + // Because we use the smsmms library for receiving and storing MMS, we'll need + // to check if it should be blocked after we've pulled it into realm. If it + // turns out that it should be dropped, then delete it + // TODO Don't store blocked messages in the first place + val action = blockingClient.shouldBlock(message.address).blockingGet() + val shouldDrop = prefs.drop.get() + Timber.v("block=$action, drop=$shouldDrop") + + if (action is BlockingClient.Action.Block && shouldDrop) { + messageRepo.deleteMessages(listOf(message.id)) + } else { + when (action) { + is BlockingClient.Action.Block -> { + messageRepo.markRead(listOf(message.threadId)) + conversationRepo.markBlocked( + listOf(message.threadId), + prefs.blockingManager.get(), + action.reason + ) + } + + is BlockingClient.Action.Unblock -> + conversationRepo.markUnblocked(message.threadId) + + else -> Unit + } + + // update the conversation + conversationRepo.updateConversations(listOf(message.threadId)) + val conversation = + conversationRepo.getOrCreateConversation(message.threadId) + ?: return Result.failure(inputData) + + // don't notify (continue) for blocked conversations + if (conversation.blocked) { + Timber.v("no notifications for blocked") + return Result.success(inputData) + } + + // unarchive conversation if necessary + if (conversation.archived) + conversationRepo.markUnarchived(listOf(conversation.id)) + + // unarchive conversation if necessary + if (conversation.archived) { + Timber.v("conversation unarchived") + conversationRepo.markUnarchived(listOf(conversation.id)) + } + + // update/create notification + Timber.v("update/create notification") + notificationManager.update(conversation.id) + + // update shortcuts + Timber.v("update shortcuts") + shortcutManager.updateShortcuts() + shortcutManager.reportShortcutUsed(conversation.id) + + // update the badge and widget + Timber.v("update badge and widget") + updateBadge.execute(Unit) + } + + // send ack to mmsc + sendAcknowledgeInd(applicationContext, subscriptionId, notificationInd) + + // send notify ind to mmsc + sendNotifyRespInd(applicationContext, subscriptionId, notificationInd) + } + } + else Timber.e("empty mms data") + } catch (e: FileNotFoundException) { + Timber.e("file not found: ${e.message}") + } catch (e: IOException) { + Timber.e("io exception: ${e.message}") + } catch (e: Exception) { + Timber.e("mms receive worker exception: ${e.message}") + } finally { + downloadFile.delete() + } Timber.v("finished") return Result.success() } + private fun handleHttpError(context: Context, mmsHttpStatus: Int, locationUrl: String) { + if ((mmsHttpStatus == 404) || (mmsHttpStatus == 400)) { + // Delete the corresponding NotificationInd + SqliteWrapper.delete( + context, context.contentResolver, Telephony.Mms.CONTENT_URI, + LOCATION_SELECTION, + arrayOf( + PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND.toString(), + locationUrl + ) + ) + } + } + + private fun sendResponsePdu( + context: Context, subscriptionId: Int, contentLocation: ByteArray, pduBytes: ByteArray + ) { + // write pdu bytes to temporary file + val fileName = "send.notify.${UUID.randomUUID()}.dat" + + val contentUri = Uri.Builder() + .authority("${context.packageName}.MmsFileProvider") + .path(fileName) + .scheme(ContentResolver.SCHEME_CONTENT) + .build() + + try { + FileOutputStream(File(context.cacheDir, fileName)).use { outputStream -> + outputStream.write(pduBytes) + } + Timber.v("notify send file $fileName") + } catch (e: Exception) { + Timber.e("error writing notify send file", e) + } + + val useWapMmsc = com.android.mms.MmsConfig.getNotifyWapMMSC() + if (useWapMmsc) + Timber.v("using content location for wap mmsc") + + SmsManagerFactory.createSmsManager(subscriptionId).sendMultimediaMessage( + context, contentUri, + if (useWapMmsc) String(contentLocation) else null, + null, + PendingIntent.getBroadcast( + context, 0, + Intent(context, MessageSentReceiver::class.java) + .setData(contentUri) // this is only used to make pending intent unique + .putExtra(MmsSentReceiver.EXTRA_FILE_PATH, fileName) + .putExtra(MessageSentReceiver.EXTRA_IS_NOTIFY, 1), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + ) + } + + private fun sendAcknowledgeInd( + context: Context, subscriptionId: Int, notificationInd: NotificationInd + ) { + Timber.v("create m-acknowledge.ind") + + try { + // if the Transaction-ID isn't set in the M-Retrieve.conf, it means + // the MMS proxy-relay doesn't require an ACK + if (notificationInd.transactionId != null) { + val ackInd = AcknowledgeInd( + PduHeaders.CURRENT_MMS_VERSION, notificationInd.transactionId + ).apply { + // insert the 'from' address per spec + from = EncodedStringValue(Utils.getMyPhoneNumber(context).orEmpty()) + } + + val pdu = PduComposer(context, ackInd).make() + + // pack m-acknowledge.ind and send it + sendResponsePdu(context, subscriptionId, notificationInd.contentLocation, pdu) + } + } catch (e: Exception) { + Timber.e("error creating m-acknowledge.ind", e) + } + } + + private fun sendNotifyRespInd( + context: Context, subscriptionId: Int, notificationInd: NotificationInd + ) { + Timber.v("create m-notifyresp.ind") + + try { + if (notificationInd.transactionId != null) { + val notifyRespInd = NotifyRespInd( + PduHeaders.CURRENT_MMS_VERSION, + notificationInd.transactionId, + PduHeaders.STATUS_RETRIEVED + ) + + val pdu = PduComposer(context, notifyRespInd).make() + + // pack m-notifyresp.ind and send it + sendResponsePdu(context, subscriptionId, notificationInd.contentLocation, pdu) + } + } catch (e: Exception) { + Timber.e("error creating m-notifyresp.ind", e) + } + } + override fun getForegroundInfo() = ForegroundInfo( 0, notificationManager.getForegroundNotificationForWorkersOnOlderAndroids() diff --git a/data/src/main/java/com/moez/QKSMS/worker/ReceiveSmsWorker.kt b/data/src/main/java/com/moez/QKSMS/worker/ReceiveSmsWorker.kt index ecedee37..c246b2f7 100644 --- a/data/src/main/java/com/moez/QKSMS/worker/ReceiveSmsWorker.kt +++ b/data/src/main/java/com/moez/QKSMS/worker/ReceiveSmsWorker.kt @@ -22,8 +22,13 @@ import android.content.Context import androidx.work.ForegroundInfo import androidx.work.Worker import androidx.work.WorkerParameters -import dev.octoshrimpy.quik.interactor.ReceiveSms +import dev.octoshrimpy.quik.blocking.BlockingClient +import dev.octoshrimpy.quik.interactor.UpdateBadge import dev.octoshrimpy.quik.manager.NotificationManager +import dev.octoshrimpy.quik.manager.ShortcutManager +import dev.octoshrimpy.quik.repository.ConversationRepository +import dev.octoshrimpy.quik.repository.MessageRepository +import dev.octoshrimpy.quik.util.Preferences import timber.log.Timber import javax.inject.Inject @@ -33,20 +38,82 @@ class ReceiveSmsWorker(appContext: Context, workerParams: WorkerParameters) const val INPUT_DATA_KEY_MESSAGE_ID = "messageId" } - @Inject lateinit var receiveSms: ReceiveSms + @Inject lateinit var conversationRepo: ConversationRepository + @Inject lateinit var blockingClient: BlockingClient + @Inject lateinit var prefs: Preferences + @Inject lateinit var messageRepo: MessageRepository @Inject lateinit var notificationManager: NotificationManager + @Inject lateinit var updateBadge: UpdateBadge + @Inject lateinit var shortcutManager: ShortcutManager override fun doWork(): Result { Timber.v("started") val messageId = inputData.getLong(INPUT_DATA_KEY_MESSAGE_ID, -1) - if (messageId == -1L) { - Timber.v("failed. message id was -1") + if (messageId < 0) { + Timber.v("failed. message id was {messageId}") return Result.failure(inputData) } - // process the new message - receiveSms.execute(messageId) + val message = messageRepo.getMessage(messageId) ?: return Result.failure(inputData) + + val action = blockingClient.shouldBlock(message.address).blockingGet() + + when { + ((action is BlockingClient.Action.Block) && prefs.drop.get()) -> { + // blocked and 'drop blocked' remove from db and don't continue + Timber.v("address is blocked and drop blocked is on. dropped") + messageRepo.deleteMessages(listOf(message.id)) + return Result.failure(inputData) + } + + action is BlockingClient.Action.Block -> { + // blocked + Timber.v("address is blocked") + messageRepo.markRead(listOf(message.threadId)) + conversationRepo.markBlocked( + listOf(message.threadId), + prefs.blockingManager.get(), + action.reason + ) + } + + action is BlockingClient.Action.Unblock -> { + // unblock + Timber.v("unblock conversation if blocked") + conversationRepo.markUnblocked(message.threadId) + } + } + + // update and fetch conversation + conversationRepo.updateConversations(listOf(message.threadId)) + val conversation = conversationRepo.getOrCreateConversation(message.threadId) + ?: return Result.failure(inputData) + + // don't notify (continue) for blocked conversations + if (conversation.blocked) { + Timber.v("no notifications for blocked") + return Result.failure(inputData) + } + + // unarchive conversation if necessary + if (conversation.archived) { + Timber.v("conversation unarchived") + conversationRepo.markUnarchived(listOf(conversation.id)) + } + + // update/create notification + Timber.v("update/create notification") + notificationManager.update(conversation.id) + + // update shortcuts + Timber.v("update shortcuts") + shortcutManager.updateShortcuts() + shortcutManager.reportShortcutUsed(conversation.id) + + // update the badge and widget + Timber.v("update badge and widget") + updateBadge.execute(Unit) Timber.v("finished") diff --git a/domain/src/main/java/com/moez/QKSMS/interactor/ReceiveMms.kt b/domain/src/main/java/com/moez/QKSMS/interactor/ReceiveMms.kt deleted file mode 100644 index 1f19d78a..00000000 --- a/domain/src/main/java/com/moez/QKSMS/interactor/ReceiveMms.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2017 Moez Bhatti - * - * This file is part of QKSMS. - * - * QKSMS is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * QKSMS is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with QKSMS. If not, see . - */ -package dev.octoshrimpy.quik.interactor - -import android.net.Uri -import dev.octoshrimpy.quik.blocking.BlockingClient -import dev.octoshrimpy.quik.extensions.mapNotNull -import dev.octoshrimpy.quik.manager.ActiveConversationManager -import dev.octoshrimpy.quik.manager.NotificationManager -import dev.octoshrimpy.quik.repository.ConversationRepository -import dev.octoshrimpy.quik.repository.MessageRepository -import dev.octoshrimpy.quik.repository.SyncRepository -import dev.octoshrimpy.quik.util.Preferences -import io.reactivex.Flowable -import timber.log.Timber -import javax.inject.Inject - -class ReceiveMms @Inject constructor( - private val activeConversationManager: ActiveConversationManager, - private val conversationRepo: ConversationRepository, - private val blockingClient: BlockingClient, - private val prefs: Preferences, - private val syncManager: SyncRepository, - private val messageRepo: MessageRepository, - private val notificationManager: NotificationManager, - private val updateBadge: UpdateBadge -) : Interactor() { - - override fun buildObservable(params: Uri): Flowable<*> { - return Flowable.just(params) - .mapNotNull(syncManager::syncMessage) // Sync the message - .doOnNext { message -> - // TODO: Ideally this is done when we're saving the MMS to ContentResolver - // This change can be made once we move the MMS storing code to the Data module - if (activeConversationManager.getActiveConversation() == message.threadId) { - messageRepo.markRead(listOf(message.threadId)) - } - } - .mapNotNull { message -> - // Because we use the smsmms library for receiving and storing MMS, we'll need - // to check if it should be blocked after we've pulled it into realm. If it - // turns out that it should be dropped, then delete it - // TODO Don't store blocked messages in the first place - val action = blockingClient.shouldBlock(message.address).blockingGet() - val shouldDrop = prefs.drop.get() - Timber.v("block=$action, drop=$shouldDrop") - - if (action is BlockingClient.Action.Block && shouldDrop) { - messageRepo.deleteMessages(listOf(message.id)) - return@mapNotNull null - } - - when (action) { - is BlockingClient.Action.Block -> { - messageRepo.markRead(listOf(message.threadId)) - conversationRepo.markBlocked( - listOf(message.threadId), prefs.blockingManager.get(), action.reason - ) - } - is BlockingClient.Action.Unblock -> - conversationRepo.markUnblocked(message.threadId) - else -> Unit - } - - message - } - .doOnNext { message -> - conversationRepo.updateConversations(listOf(message.threadId)) // Update the conversation - } - .mapNotNull { message -> - conversationRepo.getOrCreateConversation(message.threadId) // Map message to conversation - } - .filter { conversation -> !conversation.blocked } // Don't notify for blocked conversations - .doOnNext { conversation -> - // Unarchive conversation if necessary - if (conversation.archived) - conversationRepo.markUnarchived(listOf(conversation.id)) - } - .map { conversation -> conversation.id } // Map to the id because [delay] will put us on the wrong thread - .doOnNext(notificationManager::update) // Update the notification - .flatMap { updateBadge.buildObservable(Unit) } // Update the badge - } - -} \ No newline at end of file diff --git a/domain/src/main/java/com/moez/QKSMS/interactor/ReceiveSms.kt b/domain/src/main/java/com/moez/QKSMS/interactor/ReceiveSms.kt deleted file mode 100644 index 67a91c12..00000000 --- a/domain/src/main/java/com/moez/QKSMS/interactor/ReceiveSms.kt +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2017 Moez Bhatti - * - * This file is part of QKSMS. - * - * QKSMS is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * QKSMS is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with QKSMS. If not, see . - */ -package dev.octoshrimpy.quik.interactor - -import dev.octoshrimpy.quik.blocking.BlockingClient -import dev.octoshrimpy.quik.extensions.mapNotNull -import dev.octoshrimpy.quik.manager.NotificationManager -import dev.octoshrimpy.quik.manager.ShortcutManager -import dev.octoshrimpy.quik.repository.ConversationRepository -import dev.octoshrimpy.quik.repository.MessageRepository -import dev.octoshrimpy.quik.util.Preferences -import io.reactivex.Flowable -import timber.log.Timber -import javax.inject.Inject - -class ReceiveSms @Inject constructor( - private val conversationRepo: ConversationRepository, - private val blockingClient: BlockingClient, - private val prefs: Preferences, - private val messageRepo: MessageRepository, - private val notificationManager: NotificationManager, - private val updateBadge: UpdateBadge, - private val shortcutManager: ShortcutManager -) : Interactor() { - - override fun buildObservable(params: Long): Flowable<*> { - return Flowable.just(params) - .mapNotNull { messageRepo.getMessage(it) } - .mapNotNull { - val action = blockingClient.shouldBlock(it.address).blockingGet() - - when { - ((action is BlockingClient.Action.Block) && prefs.drop.get()) -> { - // blocked and 'drop blocked.' remove from db and don't continue - Timber.v("address is blocked and drop blocked is on. dropped") - messageRepo.deleteMessages(listOf(it.id)) - return@mapNotNull null - } - action is BlockingClient.Action.Block -> { - // blocked - Timber.v("address is blocked") - messageRepo.markRead(listOf(it.threadId)) - conversationRepo.markBlocked( - listOf(it.threadId), - prefs.blockingManager.get(), - action.reason - ) - } - action is BlockingClient.Action.Unblock -> { - // unblock - Timber.v("unblock conversation if blocked") - conversationRepo.markUnblocked(it.threadId) - } - } - - // update and fetch conversation - conversationRepo.updateConversations(listOf(it.threadId)) - conversationRepo.getOrCreateConversation(it.threadId) - } - .mapNotNull { - // don't notify (continue) for blocked conversations - if (it.blocked) { - Timber.v("no notifications for blocked") - return@mapNotNull null - } - - // unarchive conversation if necessary - if (it.archived) { - Timber.v("conversation unarchived") - conversationRepo.markUnarchived(listOf(it.id)) - } - - // update/create notification - Timber.v("update/create notification") - notificationManager.update(it.id) - - // update shortcuts - Timber.v("update shortcuts") - shortcutManager.updateShortcuts() - shortcutManager.reportShortcutUsed(it.id) - - // update the badge and widget - Timber.v("update badge and widget") - updateBadge.buildObservable(Unit) - } - } - -}