add delay send mms. add group send to individual recipients - sms and mms. add immediate show messages in convo, not wait for sent. new qktransaction that replaces android/smsmms transaction with mods for quik. lots of code cleanups and removing superfluous code. some bug fixes.

This commit is contained in:
gavine99
2025-04-10 16:59:35 +10:00
parent 6f70c8e932
commit 2810b56cd0
375 changed files with 20297 additions and 3161 deletions
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2012 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 com.android.internal.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Denotes that the class, method or field has its visibility relaxed so
* that unit tests can access it.
* <p/>
* The <code>visibility</code> argument can be used to specific what the original
* visibility should have been if it had not been made public or package-private for testing.
* The default is to consider the element private.
*/
@Retention(RetentionPolicy.SOURCE)
public @interface VisibleForTesting {
/**
* Intended visibility if the element had not been made public or package-private for
* testing.
*/
enum Visibility {
/**
* The element should be considered protected.
*/
PROTECTED,
/**
* The element should be considered package-private.
*/
PACKAGE,
/**
* The element should be considered private.
*/
PRIVATE
}
/**
* Intended visibility if the element had not been made public or package-private for testing.
* If not specified, one should assume the element originally intended to be private.
*/
Visibility visibility() default Visibility.PRIVATE;
}
@@ -0,0 +1,94 @@
/*
* 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 com.android.internal.net;
import android.app.PendingIntent;
import android.net.NetworkInfo;
import android.os.Parcel;
import android.os.Parcelable;
import timber.log.Timber;
/**
* A simple container used to carry information of the ongoing legacy VPN.
* Internal use only.
*
* @hide
*/
public class LegacyVpnInfo implements Parcelable {
private static final String TAG = "LegacyVpnInfo";
public static final int STATE_DISCONNECTED = 0;
public static final int STATE_INITIALIZING = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public static final int STATE_TIMEOUT = 4;
public static final int STATE_FAILED = 5;
public String key;
public int state = -1;
public PendingIntent intent;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(key);
out.writeInt(state);
out.writeParcelable(intent, flags);
}
public static final Parcelable.Creator<LegacyVpnInfo> CREATOR =
new Parcelable.Creator<LegacyVpnInfo>() {
@Override
public LegacyVpnInfo createFromParcel(Parcel in) {
LegacyVpnInfo info = new LegacyVpnInfo();
info.key = in.readString();
info.state = in.readInt();
info.intent = in.readParcelable(null);
return info;
}
@Override
public LegacyVpnInfo[] newArray(int size) {
return new LegacyVpnInfo[size];
}
};
/**
* Return best matching {@link LegacyVpnInfo} state based on given
* {@link NetworkInfo}.
*/
public static int stateFromNetworkInfo(NetworkInfo info) {
switch (info.getDetailedState()) {
case CONNECTING:
return STATE_CONNECTING;
case CONNECTED:
return STATE_CONNECTED;
case DISCONNECTED:
return STATE_DISCONNECTED;
case FAILED:
return STATE_FAILED;
default:
Timber.w("Unhandled state " + info.getDetailedState()
+ " ; treating as disconnected");
return STATE_DISCONNECTED;
}
}
}
@@ -0,0 +1,115 @@
/*
* 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 com.android.internal.net;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.util.Preconditions;
import java.util.List;
/**
* A simple container used to carry information in VpnBuilder, VpnDialogs,
* and com.android.server.connectivity.Vpn. Internal use only.
*
* @hide
*/
public class VpnConfig implements Parcelable {
public static final String SERVICE_INTERFACE = "android.net.VpnService";
public static final String DIALOGS_PACKAGE = "com.android.vpndialogs";
public static final String LEGACY_VPN = "[Legacy VPN]";
public static Intent getIntentForConfirmation() {
Intent intent = new Intent();
intent.setClassName(DIALOGS_PACKAGE, DIALOGS_PACKAGE + ".ConfirmDialog");
return intent;
}
public static PendingIntent getIntentForStatusPanel(Context context, VpnConfig config) {
Preconditions.checkNotNull(config);
Intent intent = new Intent();
intent.setClassName(DIALOGS_PACKAGE, DIALOGS_PACKAGE + ".ManageDialog");
intent.putExtra("config", config);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_MUTABLE);
}
public String user;
public String interfaze;
public String session;
public int mtu = -1;
public String addresses;
public String routes;
public List<String> dnsServers;
public List<String> searchDomains;
public PendingIntent configureIntent;
public long startTime = -1;
public boolean legacy;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(user);
out.writeString(interfaze);
out.writeString(session);
out.writeInt(mtu);
out.writeString(addresses);
out.writeString(routes);
out.writeStringList(dnsServers);
out.writeStringList(searchDomains);
out.writeParcelable(configureIntent, flags);
out.writeLong(startTime);
out.writeInt(legacy ? 1 : 0);
}
public static final Parcelable.Creator<VpnConfig> CREATOR =
new Parcelable.Creator<VpnConfig>() {
@Override
public VpnConfig createFromParcel(Parcel in) {
VpnConfig config = new VpnConfig();
config.user = in.readString();
config.interfaze = in.readString();
config.session = in.readString();
config.mtu = in.readInt();
config.addresses = in.readString();
config.routes = in.readString();
config.dnsServers = in.createStringArrayList();
config.searchDomains = in.createStringArrayList();
config.configureIntent = in.readParcelable(null);
config.startTime = in.readLong();
config.legacy = in.readInt() != 0;
return config;
}
@Override
public VpnConfig[] newArray(int size) {
return new VpnConfig[size];
}
};
}
@@ -0,0 +1,202 @@
/*
* 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 com.android.internal.net;
import android.os.Parcel;
import android.os.Parcelable;
import timber.log.Timber;
import java.nio.charset.Charset;
/**
* Parcel-like entity class for VPN profiles. To keep things simple, all
* fields are package private. Methods are provided for serialization, so
* storage can be implemented easily. Two rules are set for this class.
* First, all fields must be kept non-null. Second, always make a copy
* using clone() before modifying.
*
* @hide
*/
public class VpnProfile implements Cloneable, Parcelable {
private static final String TAG = "VpnProfile";
// Match these constants with R.array.vpn_types.
public static final int TYPE_PPTP = 0;
public static final int TYPE_L2TP_IPSEC_PSK = 1;
public static final int TYPE_L2TP_IPSEC_RSA = 2;
public static final int TYPE_IPSEC_XAUTH_PSK = 3;
public static final int TYPE_IPSEC_XAUTH_RSA = 4;
public static final int TYPE_IPSEC_HYBRID_RSA = 5;
public static final int TYPE_MAX = 5;
// Entity fields.
public final String key; // -1
public String name = ""; // 0
public int type = TYPE_PPTP; // 1
public String server = ""; // 2
public String username = ""; // 3
public String password = ""; // 4
public String dnsServers = ""; // 5
public String searchDomains = ""; // 6
public String routes = ""; // 7
public boolean mppe = true; // 8
public String l2tpSecret = ""; // 9
public String ipsecIdentifier = "";// 10
public String ipsecSecret = ""; // 11
public String ipsecUserCert = ""; // 12
public String ipsecCaCert = ""; // 13
public String ipsecServerCert = "";// 14
// Helper fields.
public boolean saveLogin = false;
public VpnProfile(String key) {
this.key = key;
}
public VpnProfile(Parcel in) {
key = in.readString();
name = in.readString();
type = in.readInt();
server = in.readString();
username = in.readString();
password = in.readString();
dnsServers = in.readString();
searchDomains = in.readString();
routes = in.readString();
mppe = in.readInt() != 0;
l2tpSecret = in.readString();
ipsecIdentifier = in.readString();
ipsecSecret = in.readString();
ipsecUserCert = in.readString();
ipsecCaCert = in.readString();
ipsecServerCert = in.readString();
saveLogin = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(key);
out.writeString(name);
out.writeInt(type);
out.writeString(server);
out.writeString(username);
out.writeString(password);
out.writeString(dnsServers);
out.writeString(searchDomains);
out.writeString(routes);
out.writeInt(mppe ? 1 : 0);
out.writeString(l2tpSecret);
out.writeString(ipsecIdentifier);
out.writeString(ipsecSecret);
out.writeString(ipsecUserCert);
out.writeString(ipsecCaCert);
out.writeString(ipsecServerCert);
out.writeInt(saveLogin ? 1 : 0);
}
public static VpnProfile decode(String key, byte[] value) {
try {
if (key == null) {
return null;
}
String[] values = new String(value, Charset.forName("UTF-8")).split("\0", -1);
// There can be 14 or 15 values in ICS MR1.
if (values.length < 14 || values.length > 15) {
return null;
}
VpnProfile profile = new VpnProfile(key);
profile.name = values[0];
profile.type = Integer.valueOf(values[1]);
if (profile.type < 0 || profile.type > TYPE_MAX) {
return null;
}
profile.server = values[2];
profile.username = values[3];
profile.password = values[4];
profile.dnsServers = values[5];
profile.searchDomains = values[6];
profile.routes = values[7];
profile.mppe = Boolean.valueOf(values[8]);
profile.l2tpSecret = values[9];
profile.ipsecIdentifier = values[10];
profile.ipsecSecret = values[11];
profile.ipsecUserCert = values[12];
profile.ipsecCaCert = values[13];
profile.ipsecServerCert = (values.length > 14) ? values[14] : "";
profile.saveLogin = !profile.username.isEmpty() || !profile.password.isEmpty();
return profile;
} catch (Exception e) {
// ignore
}
return null;
}
public byte[] encode() {
StringBuilder builder = new StringBuilder(name);
builder.append('\0').append(type);
builder.append('\0').append(server);
builder.append('\0').append(saveLogin ? username : "");
builder.append('\0').append(saveLogin ? password : "");
builder.append('\0').append(dnsServers);
builder.append('\0').append(searchDomains);
builder.append('\0').append(routes);
builder.append('\0').append(mppe);
builder.append('\0').append(l2tpSecret);
builder.append('\0').append(ipsecIdentifier);
builder.append('\0').append(ipsecSecret);
builder.append('\0').append(ipsecUserCert);
builder.append('\0').append(ipsecCaCert);
builder.append('\0').append(ipsecServerCert);
return builder.toString().getBytes(Charset.forName("UTF-8"));
}
/**
* Test if profile is valid for lockdown, which requires IPv4 address for
* both server and DNS. Server hostnames would require using DNS before
* connection.
*/
public boolean isValidLockdownProfile() {
try {
return true;
} catch (IllegalArgumentException e) {
Timber.w("Invalid address", e);
return false;
}
}
public static final Creator<VpnProfile> CREATOR = new Creator<VpnProfile>() {
@Override
public VpnProfile createFromParcel(Parcel in) {
return new VpnProfile(in);
}
@Override
public VpnProfile[] newArray(int size) {
return new VpnProfile[size];
}
};
@Override
public int describeContents() {
return 0;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013 Jacob Klinker
* Copyright (C) 2006 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.
@@ -14,19 +14,23 @@
* limitations under the License.
*/
package com.klinker.android.send_message
package com.android.internal.telephony;
/**
* Class to house all of the settings that can be used to send a message
* {@hide}
*/
class Settings @JvmOverloads constructor(
// MMS options
var mmsc: String? = "",
var proxy: String? = "",
var port: String? = "0",
var agent: String? = "",
var userProfileUrl: String? = "",
var uaProfTagName: String? = "",
@SuppressWarnings("serial")
public class EncodeException extends Exception {
public EncodeException() {
super();
}
public EncodeException(String s) {
super(s);
}
public EncodeException(char c) {
super("Unencodable char: '" + c + "'");
}
}
// SMS options
var stripUnicode: Boolean = false)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,518 @@
/*
* Copyright (C) 2006 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 com.android.internal.telephony;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import java.io.UnsupportedEncodingException;
/**
* Various methods, useful for dealing with SIM data.
*/
public class IccUtils {
static final String LOG_TAG = "IccUtils";
/**
* Many fields in GSM SIM's are stored as nibble-swizzled BCD
* <p/>
* Assumes left-justified field that may be padded right with 0xf
* values.
* <p/>
* Stops on invalid BCD value, returning string so far
*/
public static String
bcdToString(byte[] data, int offset, int length) {
StringBuilder ret = new StringBuilder(length * 2);
for (int i = offset; i < offset + length; i++) {
int v;
v = data[i] & 0xf;
if (v > 9) break;
ret.append((char) ('0' + v));
v = (data[i] >> 4) & 0xf;
// Some PLMNs have 'f' as high nibble, ignore it
if (v == 0xf) continue;
if (v > 9) break;
ret.append((char) ('0' + v));
}
return ret.toString();
}
/**
* Decode cdma byte into String.
*/
public static String
cdmaBcdToString(byte[] data, int offset, int length) {
StringBuilder ret = new StringBuilder(length);
int count = 0;
for (int i = offset; count < length; i++) {
int v;
v = data[i] & 0xf;
if (v > 9) v = 0;
ret.append((char) ('0' + v));
if (++count == length) break;
v = (data[i] >> 4) & 0xf;
if (v > 9) v = 0;
ret.append((char) ('0' + v));
++count;
}
return ret.toString();
}
/**
* Decodes a GSM-style BCD byte, returning an int ranging from 0-99.
* <p/>
* In GSM land, the least significant BCD digit is stored in the most
* significant nibble.
* <p/>
* Out-of-range digits are treated as 0 for the sake of the time stamp,
* because of this:
* <p/>
* TS 23.040 section 9.2.3.11
* "if the MS receives a non-integer value in the SCTS, it shall
* assume the digit is set to 0 but shall store the entire field
* exactly as received"
*/
public static int
gsmBcdByteToInt(byte b) {
int ret = 0;
// treat out-of-range BCD values as 0
if ((b & 0xf0) <= 0x90) {
ret = (b >> 4) & 0xf;
}
if ((b & 0x0f) <= 0x09) {
ret += (b & 0xf) * 10;
}
return ret;
}
/**
* Decodes a CDMA style BCD byte like {@link gsmBcdByteToInt}, but
* opposite nibble format. The least significant BCD digit
* is in the least significant nibble and the most significant
* is in the most significant nibble.
*/
public static int
cdmaBcdByteToInt(byte b) {
int ret = 0;
// treat out-of-range BCD values as 0
if ((b & 0xf0) <= 0x90) {
ret = ((b >> 4) & 0xf) * 10;
}
if ((b & 0x0f) <= 0x09) {
ret += (b & 0xf);
}
return ret;
}
/**
* Decodes a string field that's formatted like the EF[ADN] alpha
* identifier
* <p/>
* From TS 51.011 10.5.1:
* Coding:
* this alpha tagging shall use either
* - the SMS default 7 bit coded alphabet as defined in
* TS 23.038 [12] with bit 8 set to 0. The alpha identifier
* shall be left justified. Unused bytes shall be set to 'FF'; or
* - one of the UCS2 coded options as defined in annex B.
* <p/>
* Annex B from TS 11.11 V8.13.0:
* 1) If the first octet in the alpha string is '80', then the
* remaining octets are 16 bit UCS2 characters ...
* 2) if the first octet in the alpha string is '81', then the
* second octet contains a value indicating the number of
* characters in the string, and the third octet contains an
* 8 bit number which defines bits 15 to 8 of a 16 bit
* base pointer, where bit 16 is set to zero and bits 7 to 1
* are also set to zero. These sixteen bits constitute a
* base pointer to a "half page" in the UCS2 code space, to be
* used with some or all of the remaining octets in the string.
* The fourth and subsequent octets contain codings as follows:
* If bit 8 of the octet is set to zero, the remaining 7 bits
* of the octet contain a GSM Default Alphabet character,
* whereas if bit 8 of the octet is set to one, then the
* remaining seven bits are an offset value added to the
* 16 bit base pointer defined earlier...
* 3) If the first octet of the alpha string is set to '82', then
* the second octet contains a value indicating the number of
* characters in the string, and the third and fourth octets
* contain a 16 bit number which defines the complete 16 bit
* base pointer to a "half page" in the UCS2 code space...
*/
public static String
adnStringFieldToString(byte[] data, int offset, int length) {
if (length == 0) {
return "";
}
if (length >= 1) {
if (data[offset] == (byte) 0x80) {
int ucslen = (length - 1) / 2;
String ret = null;
try {
ret = new String(data, offset + 1, ucslen * 2, "utf-16be");
} catch (UnsupportedEncodingException ex) {
Log.e(LOG_TAG, "implausible UnsupportedEncodingException",
ex);
}
if (ret != null) {
// trim off trailing FFFF characters
ucslen = ret.length();
while (ucslen > 0 && ret.charAt(ucslen - 1) == '\uFFFF')
ucslen--;
return ret.substring(0, ucslen);
}
}
}
boolean isucs2 = false;
char base = '\0';
int len = 0;
if (length >= 3 && data[offset] == (byte) 0x81) {
len = data[offset + 1] & 0xFF;
if (len > length - 3)
len = length - 3;
base = (char) ((data[offset + 2] & 0xFF) << 7);
offset += 3;
isucs2 = true;
} else if (length >= 4 && data[offset] == (byte) 0x82) {
len = data[offset + 1] & 0xFF;
if (len > length - 4)
len = length - 4;
base = (char) (((data[offset + 2] & 0xFF) << 8) |
(data[offset + 3] & 0xFF));
offset += 4;
isucs2 = true;
}
if (isucs2) {
StringBuilder ret = new StringBuilder();
while (len > 0) {
// UCS2 subset case
if (data[offset] < 0) {
ret.append((char) (base + (data[offset] & 0x7F)));
offset++;
len--;
}
// GSM character set case
int count = 0;
while (count < len && data[offset + count] >= 0)
count++;
ret.append(GsmAlphabet.gsm8BitUnpackedToString(data,
offset, count));
offset += count;
len -= count;
}
return ret.toString();
}
Resources resource = Resources.getSystem();
String defaultCharset = "";
return GsmAlphabet.gsm8BitUnpackedToString(data, offset, length, defaultCharset.trim());
}
static int
hexCharToInt(char c) {
if (c >= '0' && c <= '9') return (c - '0');
if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
throw new RuntimeException("invalid hex char '" + c + "'");
}
/**
* Converts a hex String to a byte array.
*
* @param s A string of hexadecimal characters, must be an even number of
* chars long
* @return byte array representation
* @throws RuntimeException on invalid format
*/
public static byte[]
hexStringToBytes(String s) {
byte[] ret;
if (s == null) return null;
int sz = s.length();
ret = new byte[sz / 2];
for (int i = 0; i < sz; i += 2) {
ret[i / 2] = (byte) ((hexCharToInt(s.charAt(i)) << 4)
| hexCharToInt(s.charAt(i + 1)));
}
return ret;
}
/**
* Converts a byte array into a String of hexadecimal characters.
*
* @param bytes an array of bytes
* @return hex string representation of bytes array
*/
public static String
bytesToHexString(byte[] bytes) {
if (bytes == null) return null;
StringBuilder ret = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int b;
b = 0x0f & (bytes[i] >> 4);
ret.append("0123456789abcdef".charAt(b));
b = 0x0f & bytes[i];
ret.append("0123456789abcdef".charAt(b));
}
return ret.toString();
}
/**
* Convert a TS 24.008 Section 10.5.3.5a Network Name field to a string
* "offset" points to "octet 3", the coding scheme byte
* empty string returned on decode error
*/
public static String
networkNameToString(byte[] data, int offset, int length) {
String ret;
if ((data[offset] & 0x80) != 0x80 || length < 1) {
return "";
}
switch ((data[offset] >>> 4) & 0x7) {
case 0:
// SMS character set
int countSeptets;
int unusedBits = data[offset] & 7;
countSeptets = (((length - 1) * 8) - unusedBits) / 7;
ret = GsmAlphabet.gsm7BitPackedToString(data, offset + 1, countSeptets);
break;
case 1:
// UCS2
try {
ret = new String(data,
offset + 1, length - 1, "utf-16");
} catch (UnsupportedEncodingException ex) {
ret = "";
Log.e(LOG_TAG, "implausible UnsupportedEncodingException", ex);
}
break;
// unsupported encoding
default:
ret = "";
break;
}
// "Add CI"
// "The MS should add the letters for the Country's Initials and
// a separator (e.g. a space) to the text string"
if ((data[offset] & 0x40) != 0) {
// FIXME(mkf) add country initials here
}
return ret;
}
/**
* Convert a TS 131.102 image instance of code scheme '11' into Bitmap
*
* @param data The raw data
* @param length The length of image body
* @return The bitmap
*/
public static Bitmap parseToBnW(byte[] data, int length) {
int valueIndex = 0;
int width = data[valueIndex++] & 0xFF;
int height = data[valueIndex++] & 0xFF;
int numOfPixels = width * height;
int[] pixels = new int[numOfPixels];
int pixelIndex = 0;
int bitIndex = 7;
byte currentByte = 0x00;
while (pixelIndex < numOfPixels) {
// reassign data and index for every byte (8 bits).
if (pixelIndex % 8 == 0) {
currentByte = data[valueIndex++];
bitIndex = 7;
}
pixels[pixelIndex++] = bitToRGB((currentByte >> bitIndex--) & 0x01);
}
;
if (pixelIndex != numOfPixels) {
Log.e(LOG_TAG, "parse end and size error");
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
}
private static int bitToRGB(int bit) {
if (bit == 1) {
return Color.WHITE;
} else {
return Color.BLACK;
}
}
/**
* a TS 131.102 image instance of code scheme '11' into color Bitmap
*
* @param data The raw data
* @param length the length of image body
* @param transparency with or without transparency
* @return The color bitmap
*/
public static Bitmap parseToRGB(byte[] data, int length,
boolean transparency) {
int valueIndex = 0;
int width = data[valueIndex++] & 0xFF;
int height = data[valueIndex++] & 0xFF;
int bits = data[valueIndex++] & 0xFF;
int colorNumber = data[valueIndex++] & 0xFF;
int clutOffset = ((data[valueIndex++] & 0xFF) << 8)
| (data[valueIndex++] & 0xFF);
int[] colorIndexArray = getCLUT(data, clutOffset, colorNumber);
if (true == transparency) {
colorIndexArray[colorNumber - 1] = Color.TRANSPARENT;
}
int[] resultArray = null;
if (0 == (8 % bits)) {
resultArray = mapTo2OrderBitColor(data, valueIndex,
(width * height), colorIndexArray, bits);
} else {
resultArray = mapToNon2OrderBitColor(data, valueIndex,
(width * height), colorIndexArray, bits);
}
return Bitmap.createBitmap(resultArray, width, height,
Bitmap.Config.RGB_565);
}
private static int[] mapTo2OrderBitColor(byte[] data, int valueIndex,
int length, int[] colorArray, int bits) {
if (0 != (8 % bits)) {
Log.e(LOG_TAG, "not event number of color");
return mapToNon2OrderBitColor(data, valueIndex, length, colorArray,
bits);
}
int mask = 0x01;
switch (bits) {
case 1:
mask = 0x01;
break;
case 2:
mask = 0x03;
break;
case 4:
mask = 0x0F;
break;
case 8:
mask = 0xFF;
break;
}
int[] resultArray = new int[length];
int resultIndex = 0;
int run = 8 / bits;
while (resultIndex < length) {
byte tempByte = data[valueIndex++];
for (int runIndex = 0; runIndex < run; ++runIndex) {
int offset = run - runIndex - 1;
resultArray[resultIndex++] = colorArray[(tempByte >> (offset * bits))
& mask];
}
}
return resultArray;
}
private static int[] mapToNon2OrderBitColor(byte[] data, int valueIndex,
int length, int[] colorArray, int bits) {
if (0 == (8 % bits)) {
Log.e(LOG_TAG, "not odd number of color");
return mapTo2OrderBitColor(data, valueIndex, length, colorArray,
bits);
}
int[] resultArray = new int[length];
// TODO fix me:
return resultArray;
}
private static int[] getCLUT(byte[] rawData, int offset, int number) {
if (null == rawData) {
return null;
}
int[] result = new int[number];
int endIndex = offset + (number * 3); // 1 color use 3 bytes
int valueIndex = offset;
int colorIndex = 0;
int alpha = 0xff << 24;
do {
result[colorIndex++] = alpha
| ((rawData[valueIndex++] & 0xFF) << 16)
| ((rawData[valueIndex++] & 0xFF) << 8)
| ((rawData[valueIndex++] & 0xFF));
} while (valueIndex < endIndex);
return result;
}
}
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2012 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 com.android.internal.telephony;
/**
* SMS Constants and must be the same as the corresponding
* deprecated version in SmsMessage.
*
* @hide
*/
public class SmsConstants {
/**
* User data text encoding code unit size
*/
public static final int ENCODING_UNKNOWN = 0;
public static final int ENCODING_7BIT = 1;
public static final int ENCODING_8BIT = 2;
public static final int ENCODING_16BIT = 3;
/**
* The maximum number of payload septets per message
*/
public static final int MAX_USER_DATA_SEPTETS = 160;
/**
* The maximum number of payload septets per message if a user data header
* is present. This assumes the header only contains the
* CONCATENATED_8_BIT_REFERENCE element.
*/
public static final int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153;
/**
* This value is not defined in global standard. Only in Korea, this is used.
*/
public static final int ENCODING_KSC5601 = 4;
/**
* The maximum number of payload bytes per message
*/
public static final int MAX_USER_DATA_BYTES = 140;
/**
* The maximum number of payload bytes per message if a user data header
* is present. This assumes the header only contains the
* CONCATENATED_8_BIT_REFERENCE element.
*/
public static final int MAX_USER_DATA_BYTES_WITH_HEADER = 134;
/**
* SMS Class enumeration.
* See TS 23.038.
*/
public enum MessageClass {
UNKNOWN, CLASS_0, CLASS_1, CLASS_2, CLASS_3;
}
/**
* Indicates a 3GPP format SMS message.
*
* @hide pending API council approval
*/
public static final String FORMAT_3GPP = "3gpp";
/**
* Indicates a 3GPP2 format SMS message.
*
* @hide pending API council approval
*/
public static final String FORMAT_3GPP2 = "3gpp2";
}
@@ -0,0 +1,243 @@
/*
* Copyright (C) 2006 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 com.android.internal.util;
import java.lang.reflect.Array;
// XXX these should be changed to reflect the actual memory allocator we use.
// it looks like right now objects want to be powers of 2 minus 8
// and the array size eats another 4 bytes
/**
* ArrayUtils contains some methods that you can call to find out
* the most efficient increments by which to grow arrays.
*/
public class ArrayUtils {
private static Object[] EMPTY = new Object[0];
private static final int CACHE_SIZE = 73;
private static Object[] sCache = new Object[CACHE_SIZE];
private ArrayUtils() { /* cannot be instantiated */ }
public static int idealByteArraySize(int need) {
for (int i = 4; i < 32; i++)
if (need <= (1 << i) - 12)
return (1 << i) - 12;
return need;
}
public static int idealBooleanArraySize(int need) {
return idealByteArraySize(need);
}
public static int idealShortArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealCharArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealIntArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealFloatArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealObjectArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealLongArraySize(int need) {
return idealByteArraySize(need * 8) / 8;
}
/**
* Checks if the beginnings of two byte arrays are equal.
*
* @param array1 the first byte array
* @param array2 the second byte array
* @param length the number of bytes to check
* @return true if they're equal, false otherwise
*/
public static boolean equals(byte[] array1, byte[] array2, int length) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length < length || array2.length < length) {
return false;
}
for (int i = 0; i < length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Returns an empty array of the specified type. The intent is that
* it will return the same empty array every time to avoid reallocation,
* although this is not guaranteed.
*/
@SuppressWarnings("unchecked")
public static <T> T[] emptyArray(Class<T> kind) {
if (kind == Object.class) {
return (T[]) EMPTY;
}
int bucket = ((System.identityHashCode(kind) / 8) & 0x7FFFFFFF) % CACHE_SIZE;
Object cache = sCache[bucket];
if (cache == null || cache.getClass().getComponentType() != kind) {
cache = Array.newInstance(kind, 0);
sCache[bucket] = cache;
// Log.e("cache", "new empty " + kind.getName() + " at " + bucket);
}
return (T[]) cache;
}
/**
* Checks that value is present as at least one of the elements of the array.
*
* @param array the array to check in
* @param value the value to check for
* @return true if the value is present in the array
*/
public static <T> boolean contains(T[] array, T value) {
for (T element : array) {
if (element == null) {
if (value == null) return true;
} else {
if (value != null && element.equals(value)) return true;
}
}
return false;
}
public static boolean contains(int[] array, int value) {
for (int element : array) {
if (element == value) {
return true;
}
}
return false;
}
public static long total(long[] array) {
long total = 0;
for (long value : array) {
total += value;
}
return total;
}
/**
* Appends an element to a copy of the array and returns the copy.
*
* @param array The original array, or null to represent an empty array.
* @param element The element to add.
* @return A new array that contains all of the elements of the original array
* with the specified element added at the end.
*/
@SuppressWarnings("unchecked")
public static <T> T[] appendElement(Class<T> kind, T[] array, T element) {
final T[] result;
final int end;
if (array != null) {
end = array.length;
result = (T[]) Array.newInstance(kind, end + 1);
System.arraycopy(array, 0, result, 0, end);
} else {
end = 0;
result = (T[]) Array.newInstance(kind, 1);
}
result[end] = element;
return result;
}
/**
* Removes an element from a copy of the array and returns the copy.
* If the element is not present, then the original array is returned unmodified.
*
* @param array The original array, or null to represent an empty array.
* @param element The element to remove.
* @return A new array that contains all of the elements of the original array
* except the first copy of the specified element removed. If the specified element
* was not present, then returns the original array. Returns null if the result
* would be an empty array.
*/
@SuppressWarnings("unchecked")
public static <T> T[] removeElement(Class<T> kind, T[] array, T element) {
if (array != null) {
final int length = array.length;
for (int i = 0; i < length; i++) {
if (array[i] == element) {
if (length == 1) {
return null;
}
T[] result = (T[]) Array.newInstance(kind, length - 1);
System.arraycopy(array, 0, result, 0, i);
System.arraycopy(array, i + 1, result, i, length - i - 1);
return result;
}
}
}
return array;
}
public static int[] appendInt(int[] cur, int val) {
if (cur == null) {
return new int[]{val};
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
return cur;
}
}
int[] ret = new int[N + 1];
System.arraycopy(cur, 0, ret, 0, N);
ret[N] = val;
return ret;
}
public static int[] removeInt(int[] cur, int val) {
if (cur == null) {
return null;
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
int[] ret = new int[N - 1];
if (i > 0) {
System.arraycopy(cur, 0, ret, 0, i);
}
if (i < (N - 1)) {
System.arraycopy(cur, i + 1, ret, i, N - i - 1);
}
return ret;
}
}
return cur;
}
}
@@ -0,0 +1,62 @@
/*
* Copyright (C) 2007 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 com.android.internal.util;
import java.util.Arrays;
/**
* Object utility methods.
*/
public class Objects {
/**
* Determines whether two possibly-null objects are equal. Returns:
* <p/>
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are
* equal according to {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
* <p/>
* <p>This assumes that any non-null objects passed to this function conform
* to the {@code equals()} contract.
*/
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Generates a hash code for multiple values. The hash code is generated by
* calling {@link Arrays#hashCode(Object[])}.
* <p/>
* <p>This is useful for implementing {@link Object#hashCode()}. For example,
* in an object that has three properties, {@code x}, {@code y}, and
* {@code z}, one could write:
* <pre>
* public int hashCode() {
* return Objects.hashCode(getX(), getY(), getZ());
* }</pre>
*
* <b>Warning</b>: When a single object is supplied, the returned hash code
* does not equal the hash code of that object.
*/
public static int hashCode(Object... objects) {
return Arrays.hashCode(objects);
}
}
@@ -0,0 +1,69 @@
/*
* 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 com.android.internal.util;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state.
*/
public class Preconditions {
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
}
+14 -8
View File
@@ -16,22 +16,28 @@
package com.android.mms;
import android.content.Context;
import android.content.res.XmlResourceParser;
import java.io.IOException;
import com.klinker.android.send_message.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import timber.log.Timber;
import java.io.IOException;
public class MmsConfig {
private static final String TAG = "MmsConfig";
private static final boolean DEBUG = true;
private static final boolean LOCAL_LOGV = false;
private static final boolean LOCAL_LOGV = true;
public static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile";
public static final String DEFAULT_USER_AGENT = "Android-Mms/2.0";
private static final String MMS_APP_PACKAGE = "com.android.mms";
private static final String SMS_PROMO_DISMISSED_KEY = "sms_promo_dismissed_key";
private static final int MAX_IMAGE_HEIGHT = 480;
private static final int MAX_IMAGE_WIDTH = 640;
private static final int MAX_TEXT_LENGTH = 2000;
@@ -296,11 +302,11 @@ public class MmsConfig {
}
}
} catch (XmlPullParserException e) {
Timber.e(e, "loadMmsSettings caught ");
Timber.e("loadMmsSettings caught ", e);
} catch (NumberFormatException e) {
Timber.e(e, "loadMmsSettings caught ");
Timber.e("loadMmsSettings caught ", e);
} catch (IOException e) {
Timber.e(e, "loadMmsSettings caught ");
Timber.e("loadMmsSettings caught ", e);
} finally {
parser.close();
}
View File
View File
View File
+2 -2
View File
@@ -17,12 +17,12 @@
package com.android.mms.dom;
import java.util.Vector;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import java.util.Vector;
public class NamedNodeMapImpl implements NamedNodeMap {
private Vector<Node> mNodes = new Vector<Node>();
+4 -3
View File
@@ -17,7 +17,9 @@
package com.android.mms.dom;
import com.android.mms.dom.events.EventTargetImpl;
import java.util.NoSuchElementException;
import java.util.Vector;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
@@ -29,8 +31,7 @@ import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import java.util.NoSuchElementException;
import java.util.Vector;
import com.android.mms.dom.events.EventTargetImpl;
public abstract class NodeImpl implements Node, EventTarget {
private Node mParentNode;
+2 -2
View File
@@ -17,11 +17,11 @@
package com.android.mms.dom;
import java.util.ArrayList;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
public class NodeListImpl implements NodeList {
private ArrayList<Node> mSearchNodes;
private ArrayList<Node> mStaticNodes;
View File
+7 -3
View File
@@ -16,15 +16,19 @@
package com.android.mms.dom.events;
import com.android.mms.logs.LogTag;
import java.util.ArrayList;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import timber.log.Timber;
import java.util.ArrayList;
public class EventTargetImpl implements EventTarget {
private static final String TAG = LogTag.TAG;
private ArrayList<EventListenerEntry> mListenerEntries;
private EventTarget mNodeTarget;
@@ -96,7 +100,7 @@ public class EventTargetImpl implements EventTarget {
catch (Exception e) {
// Any exceptions thrown inside an EventListener will
// not stop propagation of the event
Timber.w(e, "Catched EventListener exception");
Timber.w("Catched EventListener exception", e);
}
}
}
@@ -17,7 +17,8 @@
package com.android.mms.dom.smil;
import com.android.mms.dom.NodeListImpl;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -27,7 +28,7 @@ import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
import com.android.mms.dom.NodeListImpl;
public abstract class ElementParallelTimeContainerImpl extends ElementTimeContainerImpl
implements ElementParallelTimeContainer {
@@ -17,14 +17,15 @@
package com.android.mms.dom.smil;
import com.android.mms.dom.NodeListImpl;
import java.util.ArrayList;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import java.util.ArrayList;
import com.android.mms.dom.NodeListImpl;
public abstract class ElementSequentialTimeContainerImpl extends
ElementTimeContainerImpl implements ElementSequentialTimeContainer {
+7 -3
View File
@@ -16,16 +16,20 @@
package com.android.mms.dom.smil;
import com.android.mms.logs.LogTag;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import timber.log.Timber;
import java.util.ArrayList;
public abstract class ElementTimeImpl implements ElementTime {
private static final String TAG = LogTag.TAG;
private static final String FILL_REMOVE_ATTRIBUTE = "remove";
private static final String FILL_FREEZE_ATTRIBUTE = "freeze";
@@ -129,7 +133,7 @@ public abstract class ElementTimeImpl implements ElementTime {
getEndConstraints()));
} catch (IllegalArgumentException e) {
// Ignore badly formatted times
Timber.e(e, "Malformed time value.");
Timber.e("Malformed time value.", e);
}
}
}
+3 -2
View File
@@ -16,8 +16,6 @@
package com.android.mms.dom.smil;
import com.android.mms.dom.DocumentImpl;
import com.android.mms.dom.events.EventImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -31,6 +29,9 @@ import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.TimeList;
import com.android.mms.dom.DocumentImpl;
import com.android.mms.dom.events.EventImpl;
public class SmilDocumentImpl extends DocumentImpl implements SMILDocument, DocumentEvent {
/*
* The sequential time container cannot be initialized here because the real container
+2 -1
View File
@@ -17,10 +17,11 @@
package com.android.mms.dom.smil;
import com.android.mms.dom.ElementImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILElement;
import com.android.mms.dom.ElementImpl;
public class SmilElementImpl extends ElementImpl implements SMILElement {
/**
* This constructor is used by the factory methods of the SmilDocument.
@@ -17,11 +17,12 @@
package com.android.mms.dom.smil;
import com.android.mms.layout.LayoutManager;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.SMILRootLayoutElement;
import com.android.mms.layout.LayoutManager;
public class SmilLayoutElementImpl extends SmilElementImpl implements
SMILLayoutElement {
SmilLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
+8 -2
View File
@@ -16,20 +16,26 @@
package com.android.mms.dom.smil;
import com.android.mms.dom.events.EventImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILMediaElement;
import org.w3c.dom.smil.TimeList;
import timber.log.Timber;
public class SmilMediaElementImpl extends SmilElementImpl implements SMILMediaElement {
import com.android.mms.logs.LogTag;
import com.android.mms.dom.events.EventImpl;
public class SmilMediaElementImpl extends SmilElementImpl implements
SMILMediaElement {
public final static String SMIL_MEDIA_START_EVENT = "SmilMediaStart";
public final static String SMIL_MEDIA_END_EVENT = "SmilMediaEnd";
public final static String SMIL_MEDIA_PAUSE_EVENT = "SmilMediaPause";
public final static String SMIL_MEDIA_SEEK_EVENT = "SmilMediaSeek";
private final static String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
ElementTime mElementTime = new ElementTimeImpl(this) {
+2 -2
View File
@@ -17,6 +17,8 @@
package com.android.mms.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
@@ -27,8 +29,6 @@ import org.w3c.dom.smil.SMILParElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class SmilParElementImpl extends SmilElementImpl implements SMILParElement {
public final static String SMIL_SLIDE_START_EVENT = "SmilSlideStart";
public final static String SMIL_SLIDE_END_EVENT = "SmilSlideEnd";
@@ -0,0 +1,762 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.dom.smil;
import com.android.mms.logs.LogTag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import timber.log.Timber;
/**
* The SmilPlayer is responsible for playing, stopping, pausing and resuming a SMIL tree.
* <li>It creates a whole timeline before playing.</li>
* <li>The player runs in a different thread which intends not to block the main thread.</li>
*/
public class SmilPlayer implements Runnable {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private static final int TIMESLICE = 200;
private static enum SmilPlayerState {
INITIALIZED,
PLAYING,
PLAYED,
PAUSED,
STOPPED,
}
private static enum SmilPlayerAction {
NO_ACTIVE_ACTION,
RELOAD,
STOP,
PAUSE,
START,
NEXT,
PREV
}
public static final String MEDIA_TIME_UPDATED_EVENT = "mediaTimeUpdated";
private static final Comparator<TimelineEntry> sTimelineEntryComparator =
new Comparator<TimelineEntry>() {
public int compare(TimelineEntry o1, TimelineEntry o2) {
return Double.compare(o1.getOffsetTime(), o2.getOffsetTime());
}
};
private static SmilPlayer sPlayer;
private long mCurrentTime;
private int mCurrentElement;
private int mCurrentSlide;
private ArrayList<TimelineEntry> mAllEntries;
private ElementTime mRoot;
private Thread mPlayerThread;
private SmilPlayerState mState = SmilPlayerState.INITIALIZED;
private SmilPlayerAction mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
private ArrayList<ElementTime> mActiveElements;
private Event mMediaTimeUpdatedEvent;
private static ArrayList<TimelineEntry> getParTimeline(
ElementParallelTimeContainer par, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
// Set my begin at first
TimeList myBeginList = par.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, par, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = par.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, par, TimelineEntry.ACTION_END);
maxOffset = endOffset;
NodeList children = par.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
}
Collections.sort(timeline, sTimelineEntryComparator);
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = par.getActiveChildrenAt(
(float) (endOffset - offset) * 1000);
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getSeqTimeline(
ElementSequentialTimeContainer seq, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
double orgOffset = offset;
// Set my begin at first
TimeList myBeginList = seq.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, seq, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = seq.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, seq, TimelineEntry.ACTION_END);
maxOffset = endOffset;
// Get children's timelines
NodeList children = seq.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
// Since the child timeline has been sorted, the offset of the last one is the biggest.
offset = childTimeline.get(childTimeline.size() - 1).getOffsetTime();
}
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = seq.getActiveChildrenAt(
(float) (endOffset - orgOffset));
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getTimeline(ElementTime element,
double offset, double maxOffset) {
if (element instanceof ElementParallelTimeContainer) {
return getParTimeline((ElementParallelTimeContainer) element, offset, maxOffset);
} else if (element instanceof ElementSequentialTimeContainer) {
return getSeqTimeline((ElementSequentialTimeContainer) element, offset, maxOffset);
} else {
// Not ElementTimeContainer here
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
TimeList beginList = element.getBegin();
for (int i = 0; i < beginList.getLength(); ++i) {
Time begin = beginList.item(i);
if (begin.getResolved()) {
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(beginOffset,
element, TimelineEntry.ACTION_BEGIN);
timeline.add(entry);
}
}
}
TimeList endList = element.getEnd();
for (int i = 0; i < endList.getLength(); ++i) {
Time end = endList.item(i);
if (end.getResolved()) {
double endOffset = end.getResolvedOffset() + offset;
if (endOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(endOffset,
element, TimelineEntry.ACTION_END);
timeline.add(entry);
}
}
}
Collections.sort(timeline, sTimelineEntryComparator);
return timeline;
}
}
private SmilPlayer() {
// Private constructor
}
public static SmilPlayer getPlayer() {
if (sPlayer == null) {
sPlayer = new SmilPlayer();
}
return sPlayer;
}
public synchronized boolean isPlayingState() {
return mState == SmilPlayerState.PLAYING;
}
public synchronized boolean isPlayedState() {
return mState == SmilPlayerState.PLAYED;
}
public synchronized boolean isPausedState() {
return mState == SmilPlayerState.PAUSED;
}
public synchronized boolean isStoppedState() {
return mState == SmilPlayerState.STOPPED;
}
private synchronized boolean isPauseAction() {
return mAction == SmilPlayerAction.PAUSE;
}
private synchronized boolean isStartAction() {
return mAction == SmilPlayerAction.START;
}
private synchronized boolean isStopAction() {
return mAction == SmilPlayerAction.STOP;
}
private synchronized boolean isReloadAction() {
return mAction == SmilPlayerAction.RELOAD;
}
private synchronized boolean isNextAction() {
return mAction == SmilPlayerAction.NEXT;
}
private synchronized boolean isPrevAction() {
return mAction == SmilPlayerAction.PREV;
}
public synchronized void init(ElementTime root) {
mRoot = root;
mAllEntries = getTimeline(mRoot, 0, Long.MAX_VALUE);
mMediaTimeUpdatedEvent = ((DocumentEvent) mRoot).createEvent("Event");
mMediaTimeUpdatedEvent.initEvent(MEDIA_TIME_UPDATED_EVENT, false, false);
mActiveElements = new ArrayList<ElementTime>();
}
public synchronized void play() {
if (!isPlayingState()) {
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mPlayerThread = new Thread(this, "SmilPlayer thread");
mState = SmilPlayerState.PLAYING;
mPlayerThread.start();
} else {
Timber.w("Error State: Playback is playing!");
}
}
public synchronized void pause() {
if (isPlayingState()) {
mAction = SmilPlayerAction.PAUSE;
notifyAll();
} else {
Timber.w("Error State: Playback is not playing!");
}
}
public synchronized void start() {
if (isPausedState()) {
resumeActiveElements();
mAction = SmilPlayerAction.START;
notifyAll();
} else if (isPlayedState()) {
play();
} else {
Timber.w("Error State: Playback can not be started!");
}
}
public synchronized void stop() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.STOP;
notifyAll();
} else if (isPlayedState()) {
actionStop();
}
}
public synchronized void stopWhenReload() {
endActiveElements();
}
public synchronized void reload() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.RELOAD;
notifyAll();
} else if (isPlayedState()) {
actionReload();
}
}
public synchronized void next() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.NEXT;
notifyAll();
}
}
public synchronized void prev() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.PREV;
notifyAll();
}
}
private synchronized boolean isBeginOfSlide(TimelineEntry entry) {
return (TimelineEntry.ACTION_BEGIN == entry.getAction())
&& (entry.getElement() instanceof SmilParElementImpl);
}
private synchronized void reloadActiveSlide() {
mActiveElements.clear();
beginSmilDocument();
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
actionEntry(entry);
}
seekActiveMedia();
}
private synchronized void beginSmilDocument() {
TimelineEntry entry = mAllEntries.get(0);
actionEntry(entry);
}
private synchronized double getOffsetTime(ElementTime element) {
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
if (element.equals(entry.getElement())) {
return entry.getOffsetTime() * 1000; // in ms
}
}
return -1;
}
private synchronized void seekActiveMedia() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (element instanceof SmilParElementImpl) {
return;
}
double offset = getOffsetTime(element);
if ((offset >= 0) && (offset <= mCurrentTime)) {
if (LOCAL_LOGV) {
Timber.v("[SEEK] " + " at " + mCurrentTime
+ " " + element);
}
element.seekElement( (float) (mCurrentTime - offset) );
}
}
}
private synchronized void waitForEntry(long interval)
throws InterruptedException {
if (LOCAL_LOGV) {
Timber.v("Waiting for " + interval + "ms.");
}
long overhead = 0;
while (interval > 0) {
long startAt = System.currentTimeMillis();
long sleep = Math.min(interval, TIMESLICE);
if (overhead < sleep) {
wait(sleep - overhead);
mCurrentTime += sleep;
} else {
sleep = 0;
mCurrentTime += overhead;
}
if (isStopAction() || isReloadAction() || isPauseAction() || isNextAction() ||
isPrevAction()) {
return;
}
((EventTarget) mRoot).dispatchEvent(mMediaTimeUpdatedEvent);
interval -= TIMESLICE;
overhead = System.currentTimeMillis() - startAt - sleep;
}
}
public synchronized int getDuration() {
if ((mAllEntries != null) && !mAllEntries.isEmpty()) {
return (int) mAllEntries.get(mAllEntries.size() - 1).mOffsetTime * 1000;
}
return 0;
}
public synchronized int getCurrentPosition() {
return (int) mCurrentTime;
}
private synchronized void endActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Timber.v("[STOP] " + " at " + mCurrentTime
+ " " + element);
}
element.endElement();
}
}
private synchronized void pauseActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Timber.v("[PAUSE] " + " at " + mCurrentTime
+ " " + element);
}
element.pauseElement();
}
}
private synchronized void resumeActiveElements() {
int size = mActiveElements.size();
for (int i = 0; i < size; i++) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Timber.v("[RESUME] " + " at " + mCurrentTime
+ " " + element);
}
element.resumeElement();
}
}
private synchronized void waitForWakeUp() {
try {
while ( !(isStartAction() || isStopAction() || isReloadAction() ||
isNextAction() || isPrevAction()) ) {
wait(TIMESLICE);
}
if (isStartAction()) {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
mState = SmilPlayerState.PLAYING;
}
} catch (InterruptedException e) {
Timber.e("Unexpected InterruptedException.", e);
}
}
private synchronized void actionEntry(TimelineEntry entry) {
switch (entry.getAction()) {
case TimelineEntry.ACTION_BEGIN:
if (LOCAL_LOGV) {
Timber.v("[START] " + " at " + mCurrentTime + " "
+ entry.getElement());
}
entry.getElement().beginElement();
mActiveElements.add(entry.getElement());
break;
case TimelineEntry.ACTION_END:
if (LOCAL_LOGV) {
Timber.v("[STOP] " + " at " + mCurrentTime + " "
+ entry.getElement());
}
entry.getElement().endElement();
mActiveElements.remove(entry.getElement());
break;
default:
break;
}
}
private synchronized TimelineEntry reloadCurrentEntry() {
// Check if the position is less than size of all entries
if (mCurrentElement < mAllEntries.size()) {
return mAllEntries.get(mCurrentElement);
} else {
return null;
}
}
private void stopCurrentSlide() {
HashSet<TimelineEntry> skippedEntries = new HashSet<TimelineEntry>();
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
// Stop any started entries, and skip the not started entries until
// meeting the end of slide
TimelineEntry entry = mAllEntries.get(i);
int action = entry.getAction();
if (entry.getElement() instanceof SmilParElementImpl &&
action == TimelineEntry.ACTION_END) {
actionEntry(entry);
mCurrentElement = i;
break;
} else if (action == TimelineEntry.ACTION_END && !skippedEntries.contains(entry)) {
actionEntry(entry);
} else if (action == TimelineEntry.ACTION_BEGIN) {
skippedEntries.add(entry);
}
}
}
private TimelineEntry loadNextSlide() {
TimelineEntry entry;
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
// No slide, finish play back
mCurrentElement++;
entry = null;
if (mCurrentElement < totalEntries) {
entry = mAllEntries.get(mCurrentElement);
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
}
return entry;
}
private TimelineEntry loadPrevSlide() {
int skippedSlides = 1;
int latestBeginEntryIndex = -1;
for (int i = mCurrentSlide; i >= 0; i--) {
TimelineEntry entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
latestBeginEntryIndex = i;
if (0 == skippedSlides-- ) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
}
if (latestBeginEntryIndex != -1) {
mCurrentElement = latestBeginEntryIndex;
mCurrentSlide = latestBeginEntryIndex;
return mAllEntries.get(mCurrentElement);
}
return null;
}
private synchronized TimelineEntry actionNext() {
stopCurrentSlide();
return loadNextSlide();
}
private synchronized TimelineEntry actionPrev() {
stopCurrentSlide();
return loadPrevSlide();
}
private synchronized void actionPause() {
pauseActiveElements();
mState = SmilPlayerState.PAUSED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionStop() {
endActiveElements();
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mState = SmilPlayerState.STOPPED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionReload() {
reloadActiveSlide();
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
public void run() {
if (isStoppedState()) {
return;
}
if (LOCAL_LOGV) {
dumpAllEntries();
}
// Play the Element by following the timeline
int size = mAllEntries.size();
for (mCurrentElement = 0; mCurrentElement < size; mCurrentElement++) {
TimelineEntry entry = mAllEntries.get(mCurrentElement);
if (isBeginOfSlide(entry)) {
mCurrentSlide = mCurrentElement;
}
long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
while (offset > mCurrentTime) {
try {
waitForEntry(offset - mCurrentTime);
} catch (InterruptedException e) {
Timber.e("Unexpected InterruptedException.", e);
}
while (isPauseAction() || isStopAction() || isReloadAction() || isNextAction() ||
isPrevAction()) {
if (isPauseAction()) {
actionPause();
waitForWakeUp();
}
if (isStopAction()) {
actionStop();
return;
}
if (isReloadAction()) {
actionReload();
entry = reloadCurrentEntry();
if (entry == null)
return;
if (isPausedState()) {
mAction = SmilPlayerAction.PAUSE;
}
}
if (isNextAction()) {
TimelineEntry nextEntry = actionNext();
if (nextEntry != null) {
entry = nextEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
if (isPrevAction()) {
TimelineEntry prevEntry = actionPrev();
if (prevEntry != null) {
entry = prevEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
}
}
mCurrentTime = offset;
actionEntry(entry);
}
mState = SmilPlayerState.PLAYED;
}
private static final class TimelineEntry {
final static int ACTION_BEGIN = 0;
final static int ACTION_END = 1;
private final double mOffsetTime;
private final ElementTime mElement;
private final int mAction;
public TimelineEntry(double offsetTime, ElementTime element, int action) {
mOffsetTime = offsetTime;
mElement = element;
mAction = action;
}
public double getOffsetTime() {
return mOffsetTime;
}
public ElementTime getElement() {
return mElement;
}
public int getAction() {
return mAction;
}
public String toString() {
return "Type = " + mElement + " offset = " + getOffsetTime() + " action = " + getAction();
}
}
private void dumpAllEntries() {
if (LOCAL_LOGV) {
for (TimelineEntry entry : mAllEntries) {
Timber.v("[Entry] "+ entry);
}
}
}
}
@@ -16,9 +16,12 @@
package com.android.mms.dom.smil;
import com.android.mms.logs.LogTag;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
import timber.log.Timber;
public class SmilRegionElementImpl extends SmilElementImpl implements
@@ -44,6 +47,8 @@ public class SmilRegionElementImpl extends SmilElementImpl implements
private static final String RIGHT_ATTRIBUTE_NAME = "right";
private static final String BOTTOM_ATTRIBUTE_NAME = "bottom";
private static final String FIT_ATTRIBUTE_NAME = "fit";
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) {
View File
+2 -2
View File
@@ -17,11 +17,11 @@
package com.android.mms.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class TimeListImpl implements TimeList {
private final ArrayList<Time> mTimes;
@@ -0,0 +1,94 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.dom.smil.parser;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.smil.SMILDocument;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import timber.log.Timber;
import com.android.mms.logs.LogTag;
import com.android.mms.dom.smil.SmilDocumentImpl;
public class SmilContentHandler extends DefaultHandler {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private SMILDocument mSmilDocument;
private Node mCurrentNode;
/**
* Resets this handler.
*
*/
public void reset() {
mSmilDocument = new SmilDocumentImpl();
mCurrentNode = mSmilDocument;
}
/**
* Returns the SMILDocument.
* @return The SMILDocument instance
*/
public SMILDocument getSmilDocument() {
return mSmilDocument;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (LOCAL_LOGV) {
Timber.v("SmilContentHandler.startElement. Creating element " + localName);
}
Element element = mSmilDocument.createElement(localName);
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
if (LOCAL_LOGV) {
Timber.v("Attribute " + i +
" lname = " + attributes.getLocalName(i) +
" value = " + attributes.getValue(i));
}
element.setAttribute(attributes.getLocalName(i),
attributes.getValue(i));
}
}
if (LOCAL_LOGV) {
Timber.v("Appending " + localName + " to " + mCurrentNode.getNodeName());
}
mCurrentNode.appendChild(element);
mCurrentNode = element;
}
@Override
public void endElement(String uri, String localName, String qName) {
if (LOCAL_LOGV) {
Timber.v("SmilContentHandler.endElement. localName " + localName);
}
mCurrentNode = mCurrentNode.getParentNode();
}
@Override
public void characters(char[] ch, int start, int length) {
if (LOCAL_LOGV) {
Timber.v("SmilContentHandler.characters. ch = " + new String(ch, start, length));
}
}
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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 com.android.mms.dom.smil.parser;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.smil.SMILDocument;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import com.google.android.mms.MmsException;
public class SmilXmlParser {
private XMLReader mXmlReader;
private SmilContentHandler mContentHandler;
public SmilXmlParser() throws MmsException {
//FIXME: Now we don't have the SAXParser wrapped inside,
// use the Driver class temporarily.
System.setProperty("org.xml.sax.driver", "org.xmlpull.v1.sax2.Driver");
try {
mXmlReader = XMLReaderFactory.createXMLReader();
mContentHandler = new SmilContentHandler();
mXmlReader.setContentHandler(mContentHandler);
} catch (SAXException e) {
throw new MmsException(e);
}
}
public SMILDocument parse(InputStream in) throws IOException, SAXException {
mContentHandler.reset();
mXmlReader.parse(new InputSource(in));
SMILDocument doc = mContentHandler.getSmilDocument();
validateDocument(doc);
return doc;
}
private void validateDocument(SMILDocument doc) {
/*
* Calling getBody() will create "smil", "head", and "body" elements if they
* are not present. It will also initialize the SequentialTimeElementContainer
* member of SMILDocument, which could not be set on creation of the document.
* @see com.android.mms.dom.smil.SmilDocumentImpl#getBody()
*/
doc.getBody();
/*
* Calling getLayout() will create "layout" element if it is not present.
* @see com.android.mms.dom.smil.SmilDocumentImpl#getLayout()
*/
doc.getLayout();
}
}
@@ -16,13 +16,6 @@
package com.android.mms.dom.smil.parser;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import timber.log.Timber;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
@@ -30,7 +23,16 @@ import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import timber.log.Timber;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
public class SmilXmlSerializer {
private static final String TAG = "SmilXmlSerializer";
public static void serialize(SMILDocument smilDoc, OutputStream out) {
try {
@@ -39,9 +41,9 @@ public class SmilXmlSerializer {
writeElement(writer, smilDoc.getDocumentElement());
writer.flush();
} catch (UnsupportedEncodingException e) {
Timber.e(e, "exception thrown");
Timber.e("exception thrown", e);
} catch (IOException e) {
Timber.e(e, "exception thrown");
Timber.e("exception thrown", e);
}
}
@@ -16,10 +16,14 @@
package com.android.mms.layout;
import com.android.mms.logs.LogTag;
import android.content.Context;
import timber.log.Timber;
public class HVGALayoutParameters implements LayoutParameters {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private int mType = -1;
+3
View File
@@ -16,6 +16,8 @@
package com.android.mms.layout;
import com.android.mms.logs.LogTag;
import android.content.Context;
import android.content.res.Configuration;
import timber.log.Timber;
@@ -24,6 +26,7 @@ import timber.log.Timber;
* MMS presentation layout management.
*/
public class LayoutManager {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
@@ -0,0 +1,84 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.logs;
import timber.log.Timber;
public class LogTag {
public static final String TAG = "Mms";
public static final String TRANSACTION = TAG;
public static final String APP = TAG;
public static final String THREAD_CACHE = TAG;
public static final String THUMBNAIL_CACHE = TAG;
public static final String PDU_CACHE = TAG;
public static final String WIDGET = TAG;
public static final String CONTACT = TAG;
/**
* Log tag for enabling/disabling StrictMode violation log.
* To enable: adb shell setprop log.tag.Mms:strictmode DEBUG
*/
public static final String STRICT_MODE_TAG = TAG;
public static final boolean VERBOSE = false;
public static final boolean SEVERE_WARNING = true; // Leave this true
private static final boolean SHOW_SEVERE_WARNING_DIALOG = false; // Set to false before ship
public static final boolean DEBUG_SEND = false; // Set to false before ship
public static final boolean DEBUG_DUMP = false; // Set to false before ship
public static final boolean ALLOW_DUMP_IN_LOGS = false; // Set to false before ship
private static String prettyArray(String[] array) {
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder("[");
int len = array.length-1;
for (int i = 0; i < len; i++) {
sb.append(array[i]);
sb.append(", ");
}
sb.append(array[len]);
sb.append("]");
return sb.toString();
}
private static String logFormat(String format, Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof String[]) {
args[i] = prettyArray((String[])args[i]);
}
}
String s = String.format(format, args);
s = "[" + Thread.currentThread().getId() + "] " + s;
return s;
}
public static void debug(String format, Object... args) {
Timber.d(logFormat(format, args));
}
public static void warn(String format, Object... args) {
Timber.w(logFormat(format, args));
}
public static void error(String format, Object... args) {
Timber.e(logFormat(format, args));
}
}
@@ -0,0 +1,242 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* 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 com.android.mms.service_alt;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.NetworkUtilsHelper;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony;
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 com.android.mms.service_alt.exception.ApnException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* APN settings used for MMS transactions
*/
public class ApnSettings {
private static final String TAG = "ApnSettings";
// MMSC URL
private final String mServiceCenter;
// MMSC proxy address
private final String mProxyAddress;
// MMSC proxy port
private final int mProxyPort;
// Debug text for this APN: a concatenation of interesting columns of this APN
private final String mDebugText;
private static final String[] APN_PROJECTION = {
Telephony.Carriers.TYPE,
Telephony.Carriers.MMSC,
Telephony.Carriers.MMSPROXY,
Telephony.Carriers.MMSPORT,
Telephony.Carriers.NAME,
Telephony.Carriers.APN,
Telephony.Carriers.BEARER,
Telephony.Carriers.PROTOCOL,
Telephony.Carriers.ROAMING_PROTOCOL,
Telephony.Carriers.AUTH_TYPE,
Telephony.Carriers.MVNO_TYPE,
Telephony.Carriers.MVNO_MATCH_DATA,
Telephony.Carriers.PROXY,
Telephony.Carriers.PORT,
Telephony.Carriers.SERVER,
Telephony.Carriers.USER,
Telephony.Carriers.PASSWORD,
};
private static final int COLUMN_TYPE = 0;
private static final int COLUMN_MMSC = 1;
private static final int COLUMN_MMSPROXY = 2;
private static final int COLUMN_MMSPORT = 3;
private static final int COLUMN_NAME = 4;
private static final int COLUMN_APN = 5;
private static final int COLUMN_BEARER = 6;
private static final int COLUMN_PROTOCOL = 7;
private static final int COLUMN_ROAMING_PROTOCOL = 8;
private static final int COLUMN_AUTH_TYPE = 9;
private static final int COLUMN_MVNO_TYPE = 10;
private static final int COLUMN_MVNO_MATCH_DATA = 11;
private static final int COLUMN_PROXY = 12;
private static final int COLUMN_PORT = 13;
private static final int COLUMN_SERVER = 14;
private static final int COLUMN_USER = 15;
private static final int COLUMN_PASSWORD = 16;
/**
* Load APN settings from system
*
* @param context
* @param apnName the optional APN name to match
*/
public static ApnSettings load(Context context, String apnName, int subId)
throws ApnException {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String mmsc = sharedPrefs.getString("mmsc_url", "");
if (!TextUtils.isEmpty(mmsc)) {
String mmsProxy = sharedPrefs.getString("mms_proxy", "");
String mmsPort = sharedPrefs.getString("mms_port", "");
return new ApnSettings(mmsc, mmsProxy, parsePort(mmsPort), "Default from settings");
}
Timber.v("ApnSettings: apnName " + apnName);
// TODO: CURRENT semantics is currently broken in telephony. Revive this when it is fixed.
//String selection = Telephony.Carriers.CURRENT + " IS NOT NULL";
String selection = null;
String[] selectionArgs = null;
apnName = apnName != null ? apnName.trim() : null;
if (!TextUtils.isEmpty(apnName)) {
//selection += " AND " + Telephony.Carriers.APN + "=?";
selection = Telephony.Carriers.APN + "=?";
selectionArgs = new String[]{ apnName };
}
Cursor cursor = null;
try {
cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "/subId/" + subId),
APN_PROJECTION,
selection,
selectionArgs,
null/*sortOrder*/);
if (cursor != null) {
String mmscUrl = null;
String proxyAddress = null;
int proxyPort = -1;
while (cursor.moveToNext()) {
// Read values from APN settings
if (isValidApnType(
cursor.getString(COLUMN_TYPE), "mms")) {
mmscUrl = trimWithNullCheck(cursor.getString(COLUMN_MMSC));
if (TextUtils.isEmpty(mmscUrl)) {
continue;
}
mmscUrl = NetworkUtilsHelper.trimV4AddrZeros(mmscUrl);
try {
new URI(mmscUrl);
} catch (URISyntaxException e) {
throw new ApnException("Invalid MMSC url " + mmscUrl);
}
proxyAddress = trimWithNullCheck(cursor.getString(COLUMN_MMSPROXY));
if (!TextUtils.isEmpty(proxyAddress)) {
proxyAddress = NetworkUtilsHelper.trimV4AddrZeros(proxyAddress);
final String portString =
trimWithNullCheck(cursor.getString(COLUMN_MMSPORT));
if (portString != null) {
try {
proxyPort = Integer.parseInt(portString);
} catch (NumberFormatException e) {
Timber.e("Invalid port " + portString);
throw new ApnException("Invalid port " + portString);
}
}
}
return new ApnSettings(
mmscUrl, proxyAddress, proxyPort, getDebugText(cursor));
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return new ApnSettings("", "", 80, "Failed to find APNs :(");
}
private static String getDebugText(Cursor cursor) {
final StringBuilder sb = new StringBuilder();
sb.append("APN [");
for (int i = 0; i < cursor.getColumnCount(); i++) {
final String name = cursor.getColumnName(i);
final String value = cursor.getString(i);
if (TextUtils.isEmpty(value)) {
continue;
}
if (i > 0) {
sb.append(' ');
}
sb.append(name).append('=').append(value);
}
sb.append("]");
return sb.toString();
}
private static String trimWithNullCheck(String value) {
return value != null ? value.trim() : null;
}
public ApnSettings(String mmscUrl, String proxyAddr, int proxyPort, String debugText) {
mServiceCenter = mmscUrl;
mProxyAddress = proxyAddr;
mProxyPort = proxyPort;
mDebugText = debugText;
}
public String getMmscUrl() {
return mServiceCenter;
}
public String getProxyAddress() {
return mProxyAddress;
}
public int getProxyPort() {
return mProxyPort;
}
public boolean isProxySet() {
return !TextUtils.isEmpty(mProxyAddress);
}
private static boolean isValidApnType(String types, String requestType) {
// If APN type is unspecified, assume APN_TYPE_ALL.
if (TextUtils.isEmpty(types)) {
return true;
}
for (String type : types.split(",")) {
type = type.trim();
if (type.equals(requestType) || type.equals("*")) {
return true;
}
}
return false;
}
private static int parsePort(String port) {
if (TextUtils.isEmpty(port)) {
return 80;
} else {
return Integer.parseInt(port);
}
}
public String toString() {
return mDebugText;
}
}
+125 -28
View File
@@ -27,7 +27,9 @@ import android.os.Binder;
import android.os.Bundle;
import android.provider.Telephony;
import android.text.TextUtils;
import timber.log.Timber;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders;
@@ -38,30 +40,29 @@ import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Transaction;
import timber.log.Timber;
/**
* Request to download an MMS
*/
public class DownloadRequest extends MmsRequest {
private static final String TAG = "DownloadRequest";
private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
static final String[] PROJECTION = new String[]{
static final String[] PROJECTION = new String[] {
Telephony.Mms.CONTENT_LOCATION
};
// The indexes of the columns which must be consistent with above PROJECTION.
static final int COLUMN_CONTENT_LOCATION = 0;
static final int COLUMN_CONTENT_LOCATION = 0;
private final String mLocationUrl;
private final PendingIntent mDownloadedIntent;
private final Uri mContentUri;
public DownloadRequest(RequestManager manager, int subId, String locationUrl,
Uri contentUri, PendingIntent downloadedIntent, String creator,
Bundle configOverrides, Context context) throws MmsException {
Uri contentUri, PendingIntent downloadedIntent, String creator,
Bundle configOverrides, Context context) throws MmsException {
super(manager, subId, creator, configOverrides);
if (locationUrl == null) {
@@ -74,6 +75,44 @@ public class DownloadRequest extends MmsRequest {
mContentUri = contentUri;
}
@Override
protected byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException {
final MmsHttpClient mmsHttpClient = netMgr.getOrCreateHttpClient();
if (mmsHttpClient == null) {
Timber.e("MMS network is not ready!");
throw new MmsHttpException(0/*statusCode*/, "MMS network is not ready");
}
return mmsHttpClient.execute(
mLocationUrl,
null/*pud*/,
MmsHttpClient.METHOD_GET,
apn.isProxySet(),
apn.getProxyAddress(),
apn.getProxyPort(),
mMmsConfig);
}
@Override
protected PendingIntent getPendingIntent() {
return mDownloadedIntent;
}
@Override
protected int getQueueType() {
return 1;
}
@Override
protected Uri persistIfRequired(Context context, int result, byte[] response) {
if (!mRequestManager.getAutoPersistingPref()) {
notifyOfDownload(context);
return null;
}
return persist(context, response, mMmsConfig, mLocationUrl, mSubId, mCreator);
}
public static Uri persist(Context context, byte[] response, MmsConfig.Overridden mmsConfig,
String locationUrl, int subId, String creator) {
// Let any mms apps running as secondary user know that a new mms has been downloaded.
@@ -130,19 +169,20 @@ public class DownloadRequest extends MmsRequest {
// }
// Store the downloaded message
final PduPersister persister = PduPersister.getPduPersister(context);
final Uri messageUri = persister.persist(pdu, Telephony.Mms.Inbox.CONTENT_URI, PduPersister.DUMMY_THREAD_ID, true, true, null);
final Uri messageUri = persister.persist(
pdu,
Telephony.Mms.Inbox.CONTENT_URI,
true/*createThreadId*/,
true/*groupMmsEnabled*/,
null/*preOpenedFiles*/,
subId);
if (messageUri == null) {
Timber.e("DownloadRequest.persistIfRequired: can not persist message");
return null;
}
// Update some of the properties of the message
final ContentValues values = new ContentValues();
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
try {
values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
}
values.put(Telephony.Mms.READ, 0);
values.put(Telephony.Mms.SEEN, 0);
if (!TextUtils.isEmpty(creator)) {
@@ -154,30 +194,52 @@ public class DownloadRequest extends MmsRequest {
}
try {
context.getContentResolver().update(messageUri, values, null, null);
} catch (SQLiteException e) {
// On MIUI and a couple other devices, the above call will fail and say `no such column: sub_id`
// If before making that call, we check to see if the sub_id column is available for messageUri, we will
// find that it is available, and yet the update call will still fail. So - there's no way we can know
// in advance that it will fail, and we have to just try again
if (values.containsKey(Telephony.Mms.SUBSCRIPTION_ID)) {
values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception e) {
}
try {
int rowsUpdated = SqliteWrapper.update(
context,
context.getContentResolver(),
messageUri,
values,
null/*where*/,
null/*selectionArg*/);
if (rowsUpdated != 1) {
Timber.e("DownloadRequest.persistIfRequired: can not update message");
}
} catch (SQLiteException ex) {
// if the exception says no such column like sub_id, ignore this value and try update
if (ex.getMessage().contains("no such column: sub_id")) {
// ignore this column and proceed.
values.remove(Telephony.Mms.SUBSCRIPTION_ID);
context.getContentResolver().update(messageUri, values, null, null);
int rowsUpdated = SqliteWrapper.update(context, context.getContentResolver(), messageUri,
values, null/*where*/, null/*selectionArg*/);
Timber.i("DownloadRequest.persistIfRequired: updated " + rowsUpdated + " message without sub_id info");
} else {
throw e;
throw ex;
}
}
// Delete the corresponding NotificationInd
SqliteWrapper.delete(context, context.getContentResolver(), Telephony.Mms.CONTENT_URI, LOCATION_SELECTION,
new String[]{Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND), locationUrl});
SqliteWrapper.delete(context,
context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
locationUrl
});
return messageUri;
} catch (MmsException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not persist message");
Timber.e("DownloadRequest.persistIfRequired: can not persist message", e);
} catch (SQLiteException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not update message");
Timber.e("DownloadRequest.persistIfRequired: can not update message", e);
} catch (RuntimeException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not parse response");
Timber.e("DownloadRequest.persistIfRequired: can not parse response", e);
} finally {
Binder.restoreCallingIdentity(identity);
}
@@ -227,6 +289,41 @@ public class DownloadRequest extends MmsRequest {
// }
}
/**
* Transfer the received response to the caller (for download requests write to content uri)
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
*/
@Override
protected boolean transferResponse(Intent fillIn, final byte[] response) {
return mRequestManager.writePduToContentUri(mContentUri, response);
}
@Override
protected boolean prepareForHttpRequest() {
return true;
}
/**
* Try downloading via the carrier app.
*
* @param context The context
* @param carrierMessagingServicePackage The carrier messaging service handling the download
*/
public void tryDownloadingByCarrierApp(Context context, String carrierMessagingServicePackage) {
// final CarrierDownloadManager carrierDownloadManger = new CarrierDownloadManager();
// final CarrierDownloadCompleteCallback downloadCallback =
// new CarrierDownloadCompleteCallback(context, carrierDownloadManger);
// carrierDownloadManger.downloadMms(context, carrierMessagingServicePackage,
// downloadCallback);
}
@Override
protected void revokeUriPermission(Context context) {
context.revokeUriPermission(mContentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
private String getContentLocation(Context context, Uri uri)
throws MmsException {
Cursor cursor = android.database.sqlite.SqliteWrapper.query(context, context.getContentResolver(),
@@ -249,10 +346,10 @@ public class DownloadRequest extends MmsRequest {
private static Long getId(Context context, String location) {
String selection = Telephony.Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[]{location};
String[] selectionArgs = new String[] { location };
Cursor c = android.database.sqlite.SqliteWrapper.query(
context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI, new String[]{Telephony.Mms._ID},
Telephony.Mms.CONTENT_URI, new String[] { Telephony.Mms._ID },
selection, selectionArgs, null);
if (c != null) {
try {
+33 -16
View File
@@ -24,8 +24,9 @@ import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.klinker.android.send_message.R;
import timber.log.Timber;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
@@ -44,6 +45,7 @@ import java.util.concurrent.ConcurrentHashMap;
* 4. Add key/value for relevant mms_config.xml of a specific carrier (mcc/mnc)
*/
public class MmsConfig {
private static final String TAG = "MmsConfig";
private static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile";
@@ -336,11 +338,16 @@ public class MmsConfig {
final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
mUserAgent = telephonyManager.getMmsUserAgent();
mUaProfUrl = telephonyManager.getMmsUAProfUrl();
// defaults for nexus 6, seems to work well.
//mUserAgent = "nexus6";
//mUaProfUrl = "http://uaprof.motorola.com/phoneconfig/nexus6/Profile/nexus6.rdf";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mUserAgent = telephonyManager.getMmsUserAgent();
mUaProfUrl = telephonyManager.getMmsUAProfUrl();
// defaults for nexus 6, seems to work well.
//mUserAgent = "nexus6";
//mUaProfUrl = "http://uaprof.motorola.com/phoneconfig/nexus6/Profile/nexus6.rdf";
} else {
mUserAgent = "Android Messaging";
mUaProfUrl = "http://www.gstatic.com/android/hangouts/hangouts_mms_ua_profile.xml";
}
}
private void loadFromResources(Context context) {
@@ -551,11 +558,15 @@ public class MmsConfig {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
try {
Method method = telephonyManager.getClass().getMethod("getLine1NumberForSubscriber", int.class);
return (String) method.invoke(telephonyManager, subId);
} catch (Exception e) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
return telephonyManager.getLine1Number();
} else {
try {
Method method = telephonyManager.getClass().getMethod("getLine1NumberForSubscriber", int.class);
return (String) method.invoke(telephonyManager, subId);
} catch (Exception e) {
return telephonyManager.getLine1Number();
}
}
}
@@ -577,15 +588,21 @@ public class MmsConfig {
String nai = "";
try {
Method method = telephonyManager.getClass().getMethod("getNai", int.class);
Method getSlotId = SubscriptionManager.class.getMethod("getSlotId", int.class);
nai = (String) method.invoke(telephonyManager, getSlotId.invoke(null, subId));
} catch (Exception e) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai");
} else {
try {
Method method = telephonyManager.getClass().getMethod("getNai", int.class);
Method getSlotId = SubscriptionManager.class.getMethod("getSlotId", int.class);
nai = (String) method.invoke(telephonyManager, getSlotId.invoke(null, subId));
} catch (Exception e) {
nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai");
}
}
Timber.v("MmsConfig.getNai: nai=" + nai);
if (Timber_isLoggable(TAG, Log.VERBOSE)) {
Timber.v("MmsConfig.getNai: nai=" + nai);
}
if (!TextUtils.isEmpty(nai)) {
String naiSuffix = getNaiSuffix();
+45 -37
View File
@@ -37,6 +37,7 @@ import java.util.Map;
*
*/
public class MmsConfigManager {
private static final String TAG = "MmsConfigManager";
private static volatile MmsConfigManager sInstance = new MmsConfigManager();
@@ -73,19 +74,24 @@ public class MmsConfigManager {
public void init(final Context context) {
mContext = context;
mSubscriptionManager = SubscriptionManager.from(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mSubscriptionManager = SubscriptionManager.from(context);
// TODO: When this object "finishes" we should unregister.
IntentFilter intentFilterLoaded = new IntentFilter("LOADED");
// TODO: When this object "finishes" we should unregister.
IntentFilter intentFilterLoaded =
new IntentFilter("LOADED");
try {
context.registerReceiver(mReceiver, intentFilterLoaded);
} catch (Exception e) {
try {
context.registerReceiver(mReceiver, intentFilterLoaded);
} catch (Exception e) {
}
load(context);
} else {
load(context);
}
load(context);
// TODO: When this object "finishes" we should unregister by invoking
// SubscriptionManager.getInstance(mContext).unregister(mOnSubscriptionsChangedListener);
// This is not strictly necessary because it will be unregistered if the
@@ -146,37 +152,39 @@ public class MmsConfigManager {
*
*/
private void load(Context context) {
List<SubscriptionInfo> subs = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subs == null || subs.size() < 1) {
Timber.e("MmsConfigManager.load -- empty getActiveSubInfoList");
return;
}
// Load all the mms_config.xml files in a separate map and then swap with the
// real map at the end so we don't block anyone sync'd on the real map.
final Map<Integer, MmsConfig> newConfigMap = new ArrayMap<Integer, MmsConfig>();
for (SubscriptionInfo sub : subs) {
Configuration configuration = new Configuration();
if (sub.getMcc() == 0 && sub.getMnc() == 0) {
Configuration config = mContext.getResources().getConfiguration();
configuration.mcc = config.mcc;
configuration.mnc = config.mnc;
Timber.i("MmsConfigManager.load -- no mcc/mnc for sub: " + sub +
" using mcc/mnc from main context: " + configuration.mcc + "/" +
configuration.mnc);
} else {
Timber.i("MmsConfigManager.load -- mcc/mnc for sub: " + sub);
configuration.mcc = sub.getMcc();
configuration.mnc = sub.getMnc();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> subs = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subs == null || subs.size() < 1) {
Timber.e("MmsConfigManager.load -- empty getActiveSubInfoList");
return;
}
Context subContext = context.createConfigurationContext(configuration);
// Load all the mms_config.xml files in a separate map and then swap with the
// real map at the end so we don't block anyone sync'd on the real map.
final Map<Integer, MmsConfig> newConfigMap = new ArrayMap<Integer, MmsConfig>();
for (SubscriptionInfo sub : subs) {
Configuration configuration = new Configuration();
if (sub.getMcc() == 0 && sub.getMnc() == 0) {
Configuration config = mContext.getResources().getConfiguration();
configuration.mcc = config.mcc;
configuration.mnc = config.mnc;
Timber.i("MmsConfigManager.load -- no mcc/mnc for sub: " + sub +
" using mcc/mnc from main context: " + configuration.mcc + "/" +
configuration.mnc);
} else {
Timber.i("MmsConfigManager.load -- mcc/mnc for sub: " + sub);
int subId = sub.getSubscriptionId();
newConfigMap.put(subId, new MmsConfig(subContext, subId));
}
synchronized (mSubIdConfigMap) {
mSubIdConfigMap.clear();
mSubIdConfigMap.putAll(newConfigMap);
configuration.mcc = sub.getMcc();
configuration.mnc = sub.getMnc();
}
Context subContext = context.createConfigurationContext(configuration);
int subId = sub.getSubscriptionId();
newConfigMap.put(subId, new MmsConfig(subContext, subId));
}
synchronized (mSubIdConfigMap) {
mSubIdConfigMap.clear();
mSubIdConfigMap.putAll(newConfigMap);
}
}
}
@@ -16,9 +16,10 @@
package com.android.mms.service_alt;
import android.content.ContentValues;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.ContentValues;
import timber.log.Timber;
import java.io.IOException;
@@ -27,6 +28,7 @@ import java.io.IOException;
* XML processor for mms_config.xml
*/
public class MmsConfigXmlProcessor {
private static final String TAG = "MmsConfigXmlProcessor";
public interface MmsConfigHandler {
public void process(String key, String value, String type);
@@ -91,9 +93,9 @@ public class MmsConfigXmlProcessor {
processMmsConfig();
}
} catch (IOException e) {
Timber.e(e, "MmsConfigXmlProcessor: I/O failure " + e);
Timber.e("MmsConfigXmlProcessor: I/O failure " + e, e);
} catch (XmlPullParserException e) {
Timber.e(e, "MmsConfigXmlProcessor: parsing failure " + e);
Timber.e("MmsConfigXmlProcessor: parsing failure " + e, e);
}
}
@@ -131,7 +133,7 @@ public class MmsConfigXmlProcessor {
}
return mLogStringBuilder.toString();
} catch (XmlPullParserException e) {
Timber.e(e, "xmlParserDebugContext: " + e);
Timber.e("xmlParserDebugContext: " + e, e);
}
}
return "Unknown";
+56 -14
View File
@@ -18,6 +18,8 @@ package com.android.mms.service_alt;
import android.content.Context;
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 com.android.mms.service_alt.exception.MmsHttpException;
import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.ConnectionSpec;
@@ -28,11 +30,7 @@ import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.huc.HttpURLConnectionImpl;
import com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl;
import timber.log.Timber;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
@@ -55,11 +53,15 @@ import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
/**
* MMS HTTP client for sending and downloading MMS messages
*/
public class MmsHttpClient {
private static final String TAG = "MmsHttpClient";
public static final String METHOD_POST = "POST";
public static final String METHOD_GET = "GET";
@@ -116,7 +118,7 @@ public class MmsHttpClient {
public byte[] execute(String urlString, byte[] pdu, String method, boolean isProxySet,
String proxyHost, int proxyPort, MmsConfig.Overridden mmsConfig)
throws MmsHttpException {
Timber.d("HTTP: " + method + " " + urlString
Timber.d("HTTP: " + method + " " + redactUrlForNonVerbose(urlString)
+ (isProxySet ? (", proxy=" + proxyHost + ":" + proxyPort) : "")
+ ", PDU size=" + (pdu != null ? pdu.length : 0));
checkMethod(method);
@@ -165,22 +167,29 @@ public class MmsHttpClient {
connection.setRequestProperty(HEADER_CONTENT_TYPE,
HEADER_VALUE_CONTENT_TYPE_WITHOUT_CHARSET);
}
logHttpHeaders(connection.getRequestProperties());
if (Timber_isLoggable(TAG, Log.VERBOSE)) {
logHttpHeaders(connection.getRequestProperties());
}
connection.setFixedLengthStreamingMode(pdu.length);
// Sending request body
final OutputStream out = new BufferedOutputStream(connection.getOutputStream());
final OutputStream out =
new BufferedOutputStream(connection.getOutputStream());
out.write(pdu);
out.flush();
out.close();
} else if (METHOD_GET.equals(method)) {
logHttpHeaders(connection.getRequestProperties());
if (Timber_isLoggable(TAG, Log.VERBOSE)) {
logHttpHeaders(connection.getRequestProperties());
}
connection.setRequestMethod(METHOD_GET);
}
// Get response
final int responseCode = connection.getResponseCode();
final String responseMessage = connection.getResponseMessage();
Timber.d("HTTP: " + responseCode + " " + responseMessage);
logHttpHeaders(connection.getHeaderFields());
if (Timber_isLoggable(TAG, Log.VERBOSE)) {
logHttpHeaders(connection.getHeaderFields());
}
if (responseCode / 100 != 2) {
throw new MmsHttpException(responseCode, responseMessage);
}
@@ -197,13 +206,15 @@ public class MmsHttpClient {
+ (responseBody != null ? responseBody.length : 0));
return responseBody;
} catch (MalformedURLException e) {
Timber.e(e, "HTTP: invalid URL " + urlString);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL " + urlString, e);
final String redactedUrl = redactUrlForNonVerbose(urlString);
Timber.e("HTTP: invalid URL " + redactedUrl, e);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL " + redactedUrl, e);
} catch (ProtocolException e) {
Timber.e(e, "HTTP: invalid URL protocol " + urlString);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL protocol " + urlString, e);
final String redactedUrl = redactUrlForNonVerbose(urlString);
Timber.e("HTTP: invalid URL protocol " + redactedUrl, e);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL protocol " + redactedUrl, e);
} catch (IOException e) {
Timber.e(e, "HTTP: IO failure");
Timber.e("HTTP: IO failure", e);
throw new MmsHttpException(0/*statusCode*/, e);
} finally {
if (connection != null) {
@@ -449,4 +460,35 @@ public class MmsHttpClient {
}
}
}
/**
* Redact the URL for non-VERBOSE logging. Replace url with only the host part and the length
* of the input URL string.
*
* @param urlString
* @return
*/
public static String redactUrlForNonVerbose(String urlString) {
if (Timber_isLoggable(TAG, Log.VERBOSE)) {
// Don't redact for VERBOSE level logging
return urlString;
}
if (TextUtils.isEmpty(urlString)) {
return urlString;
}
String protocol = "http";
String host = "";
try {
final URL url = new URL(urlString);
protocol = url.getProtocol();
host = url.getHost();
} catch (MalformedURLException e) {
// Ignore
}
// Print "http://host[length]"
final StringBuilder sb = new StringBuilder();
sb.append(protocol).append("://").append(host)
.append("[").append(urlString.length()).append("]");
return sb.toString();
}
}
+19 -10
View File
@@ -20,20 +20,22 @@ import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.NetworkInfo;
import android.net.SSLCertificateSocketFactory;
import android.os.Build;
import android.os.SystemClock;
import timber.log.Timber;
import com.android.mms.service_alt.exception.MmsNetworkException;
import com.squareup.okhttp.ConnectionPool;
import timber.log.Timber;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
private static final String TAG = "MmsNetworkManager";
// Timeout used to call ConnectivityManager.requestNetwork
private static final int NETWORK_REQUEST_TIMEOUT_MILLIS = 60 * 1000;
// Wait timeout for this class, a little bit longer than the above timeout
@@ -87,11 +89,18 @@ public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
mSubId = subId;
if (!MmsRequest.useWifi(context)) {
mNetworkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.setNetworkSpecifier(Integer.toString(mSubId))
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mNetworkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.setNetworkSpecifier(Integer.toString(mSubId))
.build();
} else {
mNetworkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.build();
}
} else {
mNetworkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
@@ -196,7 +205,7 @@ public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
connectivityManager.requestNetwork(
mNetworkRequest, mNetworkCallback);
} catch (SecurityException e) {
Timber.e(e, "permission exception... skipping it for testing purposes");
Timber.e("permission exception... skipping it for testing purposes", e);
permissionError = true;
}
}
@@ -213,7 +222,7 @@ public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
try {
connectivityManager.unregisterNetworkCallback(callback);
} catch (Exception e) {
Timber.e(e, "couldn't unregister");
Timber.e("couldn't unregister", e);
}
}
resetLocked();
+290
View File
@@ -16,18 +16,34 @@
package com.android.mms.service_alt;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.service.carrier.CarrierMessagingService;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import timber.log.Timber;
import com.klinker.android.send_message.Utils;
import com.android.mms.service_alt.exception.ApnException;
import com.android.mms.service_alt.exception.MmsHttpException;
/**
* Base class for MMS requests. This has the common logic of sending/downloading MMS.
*/
public abstract class MmsRequest {
private static final String TAG = "MmsRequest";
private static final int RETRY_TIMES = 3;
/**
* Interface for certain functionalities from MmsService
@@ -73,6 +89,8 @@ public abstract class MmsRequest {
// MMS config overrides
protected Bundle mMmsConfigOverrides;
private boolean mobileDataEnabled;
public MmsRequest(RequestManager requestManager, int subId, String creator,
Bundle configOverrides) {
mRequestManager = requestManager;
@@ -86,6 +104,192 @@ public abstract class MmsRequest {
return mSubId;
}
private boolean ensureMmsConfigLoaded() {
if (mMmsConfig == null) {
final MmsConfig config;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
// Not yet retrieved from mms config manager. Try getting it.
config = MmsConfigManager.getInstance().getMmsConfigBySubId(mSubId);
} else {
config = MmsConfigManager.getInstance().getMmsConfig();
}
if (config != null) {
mMmsConfig = new MmsConfig.Overridden(config, mMmsConfigOverrides);
}
}
return mMmsConfig != null;
}
private static boolean inAirplaneMode(final Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
private static boolean isMobileDataEnabled(final Context context, final int subId) {
final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return Utils.isDataEnabled(telephonyManager, subId);
}
private static boolean isDataNetworkAvailable(final Context context, final int subId) {
return !inAirplaneMode(context) && isMobileDataEnabled(context, subId);
}
/**
* Execute the request
*
* @param context The context
* @param networkManager The network manager to use
*/
public void execute(Context context, MmsNetworkManager networkManager) {
int result = SmsManager.MMS_ERROR_UNSPECIFIED;
int httpStatusCode = 0;
byte[] response = null;
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean isWifiEnabled = wifi.isWifiEnabled();
if (!useWifi(context)) {
wifi.setWifiEnabled(false);
}
mobileDataEnabled = Utils.isMobileDataEnabled(context);
Timber.v("mobile data enabled: " + mobileDataEnabled);
if (!mobileDataEnabled && !useWifi(context)) {
Timber.v("mobile data not enabled, so forcing it to enable");
Utils.setMobileDataEnabled(context, true);
}
if (!ensureMmsConfigLoaded()) { // Check mms config
Timber.e("MmsRequest: mms config is not loaded yet");
result = SmsManager.MMS_ERROR_CONFIGURATION_ERROR;
} else if (!prepareForHttpRequest()) { // Prepare request, like reading pdu data from user
Timber.e("MmsRequest: failed to prepare for request");
result = SmsManager.MMS_ERROR_IO_ERROR;
} else if (!isDataNetworkAvailable(context, mSubId)) {
Timber.e("MmsRequest: in airplane mode or mobile data disabled");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
result = SmsManager.MMS_ERROR_NO_DATA_NETWORK;
} else {
result = 8;
}
} else { // Execute
long retryDelaySecs = 2;
// Try multiple times of MMS HTTP request
for (int i = 0; i < RETRY_TIMES; i++) {
try {
try {
networkManager.acquireNetwork();
} catch (Exception e) {
Timber.e("error acquiring network", e);
}
final String apnName = networkManager.getApnName();
try {
ApnSettings apn = null;
try {
apn = ApnSettings.load(context, apnName, mSubId);
} catch (ApnException e) {
// If no APN could be found, fall back to trying without the APN name
if (apnName == null) {
// If the APN name was already null then don't need to retry
throw (e);
}
Timber.i("MmsRequest: No match with APN name:"
+ apnName + ", try with no name");
apn = ApnSettings.load(context, null, mSubId);
}
Timber.i("MmsRequest: using " + apn.toString());
response = doHttp(context, networkManager, apn);
result = Activity.RESULT_OK;
// Success
break;
} finally {
networkManager.releaseNetwork();
}
} catch (ApnException e) {
Timber.e("MmsRequest: APN failure", e);
result = SmsManager.MMS_ERROR_INVALID_APN;
break;
// } catch (MmsNetworkException e) {
// Timber.e("MmsRequest: MMS network acquiring failure", e);
// result = SmsManager.MMS_ERROR_UNABLE_CONNECT_MMS;
// // Retry
} catch (MmsHttpException e) {
Timber.e("MmsRequest: HTTP or network I/O failure", e);
result = SmsManager.MMS_ERROR_HTTP_FAILURE;
httpStatusCode = e.getStatusCode();
// Retry
} catch (Exception e) {
Timber.e("MmsRequest: unexpected failure", e);
result = SmsManager.MMS_ERROR_UNSPECIFIED;
break;
}
try {
Thread.sleep(retryDelaySecs * 1000, 0/*nano*/);
} catch (InterruptedException e) {
}
retryDelaySecs <<= 1;
}
}
if (!mobileDataEnabled) {
Timber.v("setting mobile data back to disabled");
Utils.setMobileDataEnabled(context, false);
}
if (!useWifi(context)) {
wifi.setWifiEnabled(isWifiEnabled);
}
processResult(context, result, response, httpStatusCode);
}
/**
* Process the result of the completed request, including updating the message status
* in database and sending back the result via pending intents.
* @param context The context
* @param result The result code of execution
* @param response The response body
* @param httpStatusCode The optional http status code in case of http failure
*/
public void processResult(Context context, int result, byte[] response, int httpStatusCode) {
final Uri messageUri = persistIfRequired(context, result, response);
// Return MMS HTTP request result via PendingIntent
final PendingIntent pendingIntent = getPendingIntent();
if (pendingIntent != null) {
boolean succeeded = true;
// Extra information to send back with the pending intent
Intent fillIn = new Intent();
if (response != null) {
succeeded = transferResponse(fillIn, response);
}
if (messageUri != null) {
fillIn.putExtra("uri", messageUri.toString());
}
if (result == SmsManager.MMS_ERROR_HTTP_FAILURE && httpStatusCode != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
fillIn.putExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, httpStatusCode);
} else {
fillIn.putExtra("android.telephony.extra.MMS_HTTP_STATUS", httpStatusCode);
}
}
try {
if (!succeeded) {
result = SmsManager.MMS_ERROR_IO_ERROR;
}
pendingIntent.send(context, result, fillIn);
} catch (PendingIntent.CanceledException e) {
Timber.e("MmsRequest: sending pending intent canceled", e);
}
}
revokeUriPermission(context);
}
/**
* are we set up to use wifi? if so, send mms over it.
*/
@@ -102,4 +306,90 @@ public abstract class MmsRequest {
return false;
}
/**
* Returns true if sending / downloading using the carrier app has failed and completes the
* action using platform API's, otherwise false.
*/
protected boolean maybeFallbackToRegularDelivery(int carrierMessagingAppResult) {
if (carrierMessagingAppResult
== CarrierMessagingService.SEND_STATUS_RETRY_ON_CARRIER_NETWORK
|| carrierMessagingAppResult
== CarrierMessagingService.DOWNLOAD_STATUS_RETRY_ON_CARRIER_NETWORK) {
Timber.d("Sending/downloading MMS by IP failed.");
mRequestManager.addSimRequest(MmsRequest.this);
return true;
} else {
return false;
}
}
/**
* Converts from {@code carrierMessagingAppResult} to a platform result code.
*/
protected static int toSmsManagerResult(int carrierMessagingAppResult) {
switch (carrierMessagingAppResult) {
case CarrierMessagingService.SEND_STATUS_OK:
return Activity.RESULT_OK;
case CarrierMessagingService.SEND_STATUS_RETRY_ON_CARRIER_NETWORK:
return SmsManager.MMS_ERROR_RETRY;
default:
return SmsManager.MMS_ERROR_UNSPECIFIED;
}
}
/**
* Making the HTTP request to MMSC
*
* @param context The context
* @param netMgr The current {@link MmsNetworkManager}
* @param apn The APN setting
* @return The HTTP response data
* @throws MmsHttpException If any network error happens
*/
protected abstract byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException;
/**
* @return The PendingIntent associate with the MMS sending invocation
*/
protected abstract PendingIntent getPendingIntent();
/**
* @return The queue should be used by this request, 0 is sending and 1 is downloading
*/
protected abstract int getQueueType();
/**
* Persist message into telephony if required (i.e. when auto-persisting is on or
* the calling app is non-default sms app for sending)
*
* @param context The context
* @param result The result code of execution
* @param response The response body
* @return The persisted URI of the message or null if we don't persist or fail
*/
protected abstract Uri persistIfRequired(Context context, int result, byte[] response);
/**
* Prepare to make the HTTP request - will download message for sending
* @return true if preparation succeeds (and request can proceed) else false
*/
protected abstract boolean prepareForHttpRequest();
/**
* Transfer the received response to the caller
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
* @return true if response transfer succeeds else false
*/
protected abstract boolean transferResponse(Intent fillIn, byte[] response);
/**
* Revoke the content URI permission granted by the MMS app to the phone package.
*
* @param context The context
*/
protected abstract void revokeUriPermission(Context context);
}
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* 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 com.android.mms.service_alt;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.util.Log; import timber.log.Timber; // inserted with sed
import com.android.mms.transaction.NotificationTransaction;
import com.google.android.mms.MmsException;
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.Settings;
public class MmsRequestManager implements MmsRequest.RequestManager {
private static final String TAG = "MmsRequestManager";
private Context context;
private byte[] pduData;
public MmsRequestManager(Context context) {
this(context, null);
}
public MmsRequestManager(Context context, byte[] pduData) {
this.context = context;
this.pduData = pduData;
}
@Override
public void addSimRequest(MmsRequest request) {
// Do nothing, this will not be invoked ever.
}
@Override
public boolean getAutoPersistingPref() {
return NotificationTransaction.allowAutoDownload(context);
}
@Override
public byte[] readPduFromContentUri(Uri contentUri, int maxSize) {
return pduData;
}
@Override
public boolean writePduToContentUri(Uri contentUri, byte[] response) {
if (response == null || response.length < 1) {
Timber.e("empty response");
return false;
}
try {
// Parse M-Retrieve.conf
RetrieveConf retrieveConf = (RetrieveConf) new PduParser(response).parse();
if (null == retrieveConf) {
throw new MmsException("Invalid M-Retrieve.conf PDU.");
}
Uri msgUri;
boolean group;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
// Store M-Retrieve.conf into Inbox
PduPersister persister = PduPersister.getPduPersister(context);
msgUri = persister.persist(retrieveConf, Telephony.Mms.Inbox.CONTENT_URI, true,
group, null, subId);
// Use local time instead of PDU time
ContentValues values = new ContentValues();
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
values.put(Telephony.Mms.MESSAGE_SIZE, response.length);
try {
// Store PDU time as sent time for received message
values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception e) {
}
SqliteWrapper.update(context, context.getContentResolver(),
msgUri, values, null, null);
// Send ACK to the Proxy-Relay to indicate we have fetched the
// MM successfully.
// Don't mark the transaction as failed if we failed to send it.
// sendAcknowledgeInd(retrieveConf);
} catch (Throwable t) {
Timber.e(TAG, "error", t);
}
return false;
}
}
+4 -1
View File
@@ -18,10 +18,11 @@ package com.android.mms.service_alt;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import timber.log.Timber;
import com.android.i18n.phonenumbers.NumberParseException;
import com.android.i18n.phonenumbers.PhoneNumberUtil;
import com.android.i18n.phonenumbers.Phonenumber;
import timber.log.Timber;
import java.lang.reflect.Method;
import java.util.Locale;
@@ -31,6 +32,8 @@ import java.util.Locale;
*/
public class PhoneUtils {
private static final String TAG = "PhoneUtils";
/**
* Get a canonical national format phone number. If parsing fails, just return the
* original number.
@@ -0,0 +1,231 @@
/*
* Copyright (C) 2015 Jacob Klinker
*
* 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 com.android.mms.service_alt;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.text.TextUtils;
import timber.log.Timber;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.google.android.mms.pdu_alt.GenericPdu;
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.SendConf;
import com.google.android.mms.pdu_alt.SendReq;
import com.google.android.mms.util_alt.SqliteWrapper;
/**
* Request to send an MMS
*/
public class SendRequest extends MmsRequest {
private static final String TAG = "SendRequest";
private final Uri mPduUri;
private byte[] mPduData;
private final String mLocationUrl;
private final PendingIntent mSentIntent;
public SendRequest(RequestManager manager, int subId, Uri contentUri, String locationUrl,
PendingIntent sentIntent, String creator, Bundle configOverrides) {
super(manager, subId, creator, configOverrides);
mPduUri = contentUri;
mPduData = null;
mLocationUrl = locationUrl;
mSentIntent = sentIntent;
}
@Override
protected byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException {
final MmsHttpClient mmsHttpClient = netMgr.getOrCreateHttpClient();
if (mmsHttpClient == null) {
Timber.e("MMS network is not ready!");
throw new MmsHttpException(0/*statusCode*/, "MMS network is not ready");
}
return mmsHttpClient.execute(
mLocationUrl != null ? mLocationUrl : apn.getMmscUrl(),
mPduData,
MmsHttpClient.METHOD_POST,
apn.isProxySet(),
apn.getProxyAddress(),
apn.getProxyPort(),
mMmsConfig);
}
@Override
protected PendingIntent getPendingIntent() {
return mSentIntent;
}
@Override
protected int getQueueType() {
return 0;
}
@Override
protected Uri persistIfRequired(Context context, int result, byte[] response) {
Timber.d("SendRequest.persistIfRequired");
if (mPduData == null) {
Timber.e("SendRequest.persistIfRequired: empty PDU");
return null;
}
final long identity = Binder.clearCallingIdentity();
try {
final boolean supportContentDisposition = mMmsConfig.getSupportMmsContentDisposition();
// Persist the request PDU first
GenericPdu pdu = (new PduParser(mPduData, supportContentDisposition)).parse();
if (pdu == null) {
Timber.e("SendRequest.persistIfRequired: can't parse input PDU");
return null;
}
if (!(pdu instanceof SendReq)) {
Timber.d("SendRequest.persistIfRequired: not SendReq");
return null;
}
// final PduPersister persister = PduPersister.getPduPersister(context);
// final Uri messageUri = persister.persist(
// pdu,
// Telephony.Mms.Sent.CONTENT_URI,
// true/*createThreadId*/,
// true/*groupMmsEnabled*/,
// null/*preOpenedFiles*/);
// if (messageUri == null) {
// Timber.e("SendRequest.persistIfRequired: can not persist message");
// return null;
// }
// Update the additional columns based on the send result
final ContentValues values = new ContentValues();
SendConf sendConf = null;
if (response != null && response.length > 0) {
pdu = (new PduParser(response, supportContentDisposition)).parse();
if (pdu != null && pdu instanceof SendConf) {
sendConf = (SendConf) pdu;
}
}
if (result != Activity.RESULT_OK
|| sendConf == null
|| sendConf.getResponseStatus() != PduHeaders.RESPONSE_STATUS_OK) {
// Since we can't persist a message directly into FAILED box,
// we have to update the column after we persist it into SENT box.
// The gap between the state change is tiny so I would not expect
// it to cause any serious problem
// TODO: we should add a "failed" URI for this in MmsProvider?
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_FAILED);
} else {
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT);
}
if (sendConf != null) {
values.put(Telephony.Mms.RESPONSE_STATUS, sendConf.getResponseStatus());
Timber.v("response status: " + sendConf.getResponseStatus());
values.put(Telephony.Mms.MESSAGE_ID,
PduPersister.toIsoString(sendConf.getMessageId()));
}
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
values.put(Telephony.Mms.READ, 1);
values.put(Telephony.Mms.SEEN, 1);
if (!TextUtils.isEmpty(mCreator)) {
values.put(Telephony.Mms.CREATOR, mCreator);
}
if (SubscriptionIdChecker.getInstance(context).canUseSubscriptionId()) {
values.put(Telephony.Mms.SUBSCRIPTION_ID, mSubId);
}
if (SqliteWrapper.update(context, context.getContentResolver(), mPduUri, values,
null/*where*/, null/*selectionArg*/) != 1) {
Timber.e("SendRequest.persistIfRequired: failed to update message");
}
return mPduUri;
// } catch (MmsException e) {
// Timber.e("SendRequest.persistIfRequired: can not persist message", e);
} catch (RuntimeException e) {
Timber.e("SendRequest.persistIfRequired: unexpected parsing failure", e);
} finally {
Binder.restoreCallingIdentity(identity);
}
return null;
}
/**
* Read the pdu from the file descriptor and cache pdu bytes in request
* @return true if pdu read successfully
*/
private boolean readPduFromContentUri() {
if (mPduData != null) {
return true;
}
final int bytesTobeRead = mMmsConfig.getMaxMessageSize();
mPduData = mRequestManager.readPduFromContentUri(mPduUri, bytesTobeRead);
return (mPduData != null);
}
/**
* Transfer the received response to the caller (for send requests the pdu is small and can
* just include bytes as extra in the "returned" intent).
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
*/
@Override
protected boolean transferResponse(Intent fillIn, byte[] response) {
// SendConf pdus are always small and can be included in the intent
if (response != null) {
fillIn.putExtra(SmsManager.EXTRA_MMS_DATA, response);
}
return true;
}
/**
* Read the data from the file descriptor if not yet done
* @return whether data successfully read
*/
@Override
protected boolean prepareForHttpRequest() {
return readPduFromContentUri();
}
/**
* Try sending via the carrier app
*
* @param context the context
* @param carrierMessagingServicePackage the carrier messaging service sending the MMS
*/
public void trySendingByCarrierApp(Context context, String carrierMessagingServicePackage) {
// final CarrierSendManager carrierSendManger = new CarrierSendManager();
// final CarrierSendCompleteCallback sendCallback = new CarrierSendCompleteCallback(
// context, carrierSendManger);
// carrierSendManger.sendMms(context, carrierMessagingServicePackage, sendCallback);
}
@Override
protected void revokeUriPermission(Context context) {
try {
context.revokeUriPermission(mPduUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (NullPointerException e) {
Timber.e("error revoking permissions", e);
}
}
}
@@ -6,34 +6,38 @@ import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Build;
import android.provider.Telephony;
import com.google.android.mms.util_alt.SqliteWrapper;
import timber.log.Timber;
class SubscriptionIdChecker {
import com.google.android.mms.util_alt.SqliteWrapper;
public class SubscriptionIdChecker {
private static final String TAG = "SubscriptionIdChecker";
private static SubscriptionIdChecker sInstance;
private boolean mCanUseSubscriptionId = false;
// I met a device which does not have Telephony.Mms.SUBSCRIPTION_ID event if it's API Level is 22.
private void check(Context context) {
Cursor c = null;
try {
c = SqliteWrapper.query(context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
new String[]{Telephony.Mms.SUBSCRIPTION_ID}, null, null, null);
if (c != null) {
mCanUseSubscriptionId = true;
}
} catch (SQLiteException e) {
Timber.e("SubscriptionIdChecker.check() fail");
} finally {
if (c != null) {
c.close();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Cursor c = null;
try {
c = SqliteWrapper.query(context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
new String[]{Telephony.Mms.SUBSCRIPTION_ID}, null, null, null);
if (c != null) {
mCanUseSubscriptionId = true;
}
} catch (SQLiteException e) {
Timber.e("SubscriptionIdChecker.check() fail");
} finally {
if (c != null) {
c.close();
}
}
}
}
static synchronized SubscriptionIdChecker getInstance(Context context) {
public static synchronized SubscriptionIdChecker getInstance(Context context) {
if (sInstance == null) {
sInstance = new SubscriptionIdChecker();
sInstance.check(context);
@@ -41,7 +45,7 @@ class SubscriptionIdChecker {
return sInstance;
}
boolean canUseSubscriptionId() {
public boolean canUseSubscriptionId() {
return mCanUseSubscriptionId;
}
}
@@ -16,6 +16,8 @@
package com.android.mms.transaction;
import com.android.mms.logs.LogTag;
import android.content.Context;
import android.util.Config;
import timber.log.Timber;
@@ -24,6 +26,7 @@ import timber.log.Timber;
* Default retry scheme, based on specs.
*/
public class DefaultRetryScheme extends AbstractRetryScheme {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
+15 -33
View File
@@ -1,27 +1,27 @@
package com.android.mms.transaction;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.text.TextUtils;
import com.android.mms.MmsConfig;
import timber.log.Timber;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.MmsReceivedReceiver;
import com.klinker.android.send_message.SmsManagerFactory;
import timber.log.Timber;
import java.io.File;
import java.util.Random;
import java.util.UUID;
@@ -32,6 +32,7 @@ import java.util.concurrent.ConcurrentHashMap;
* We should manage to call SMSManager.downloadMultimediaMessage().
*/
public class DownloadManager {
private static final String TAG = "DownloadManager";
private static DownloadManager ourInstance = new DownloadManager();
private static final ConcurrentHashMap<String, MmsDownloadReceiver> mMap = new ConcurrentHashMap<>();
@@ -43,16 +44,12 @@ public class DownloadManager {
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void downloadMultimediaMessage(final Context context, final String location, Uri uri, boolean byPush, int subscriptionId) {
if (location == null || mMap.get(location) != null) {
return;
}
// TransactionService can keep uri and location in memory while SmsManager download Mms.
if (!isNotificationExist(context, location)) {
return;
}
MmsDownloadReceiver receiver = new MmsDownloadReceiver();
mMap.put(location, receiver);
@@ -60,7 +57,7 @@ public class DownloadManager {
context.getApplicationContext().registerReceiver(receiver, new IntentFilter(receiver.mAction));
Timber.v("receiving with system method");
final String fileName = "download." + String.valueOf(Math.abs(new Random().nextLong())) + ".dat";
final String fileName = "download." + Math.abs(new Random().nextLong()) + ".dat";
File mDownloadFile = new File(context.getCacheDir(), fileName);
Uri contentUri = (new Uri.Builder())
.authority(context.getPackageName() + ".MmsFileProvider")
@@ -72,14 +69,19 @@ public class DownloadManager {
download.putExtra(MmsReceivedReceiver.EXTRA_LOCATION_URL, location);
download.putExtra(MmsReceivedReceiver.EXTRA_TRIGGER_PUSH, byPush);
download.putExtra(MmsReceivedReceiver.EXTRA_URI, uri);
download.putExtra(MmsReceivedReceiver.SUBSCRIPTION_ID, subscriptionId);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, download, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
final SmsManager smsManager = SmsManagerFactory.INSTANCE.createSmsManager(subscriptionId);
final SmsManager smsManager = SmsManagerFactory.createSmsManager(subscriptionId);
Bundle configOverrides = new Bundle();
String httpParams = MmsConfig.getHttpParams();
if (!TextUtils.isEmpty(httpParams)) {
configOverrides.putString(SmsManager.MMS_CONFIG_HTTP_PARAMS, httpParams);
} else {
// this doesn't seem to always work...
// configOverrides = smsManager.getCarrierConfigValues();
}
grantUriPermission(context, contentUri);
@@ -105,7 +107,7 @@ public class DownloadManager {
context.unregisterReceiver(this);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MMS DownloadReceiver");
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "smsmms:download-mms-lock");
wakeLock.acquire(60 * 1000);
Intent newIntent = (Intent) intent.clone();
@@ -119,24 +121,4 @@ public class DownloadManager {
mMap.remove(location);
}
}
private static boolean isNotificationExist(Context context, String location) {
String selection = Telephony.Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[] { location };
Cursor c = SqliteWrapper.query(
context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI, new String[] { Telephony.Mms._ID },
selection, selectionArgs, null);
if (c != null) {
try {
if (c.getCount() > 0) {
return true;
}
} finally {
c.close();
}
}
return false;
}
}
+42 -27
View File
@@ -16,12 +16,13 @@
package com.android.mms.transaction;
import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Config;
import com.android.mms.MmsConfig;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
@@ -33,16 +34,19 @@ import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import timber.log.Timber;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Config;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
import com.android.mms.MmsConfig;
public class HttpUtils {
private static final String TAG = LogTag.TRANSACTION;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
@@ -93,16 +97,19 @@ public class HttpUtils {
throw new IllegalArgumentException("URL must not be null.");
}
Timber.v("httpConnection: params list");
Timber.v("\ttoken\t\t= " + token);
Timber.v("\turl\t\t= " + url);
Timber.v("\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST"
: ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
Timber.v("\tisProxySet\t= " + isProxySet);
Timber.v("\tproxyHost\t= " + proxyHost);
Timber.v("\tproxyPort\t= " + proxyPort);
// TODO Print out binary data more readable.
//Timber.v("\tpdu\t\t= " + Arrays.toString(pdu));
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("httpConnection: params list");
Timber.v("\ttoken\t\t= " + token);
Timber.v("\turl\t\t= " + url);
Timber.v("\tmethod\t\t= "
+ ((method == HTTP_POST_METHOD) ? "POST"
: ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
Timber.v("\tisProxySet\t= " + isProxySet);
Timber.v("\tproxyHost\t= " + proxyHost);
Timber.v("\tproxyPort\t= " + proxyPort);
// TODO Print out binary data more readable.
//Timber.v("\tpdu\t\t= " + Arrays.toString(pdu));
}
AndroidHttpClient client = null;
@@ -150,7 +157,10 @@ public class HttpUtils {
String xWapProfileTagName = MmsConfig.getUaProfTagName();
String xWapProfileUrl = MmsConfig.getUaProfUrl();
if (xWapProfileUrl != null) {
Timber.d("[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.d(LogTag.TRANSACTION,
"[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
}
req.addHeader(xWapProfileTagName, xWapProfileUrl);
}
}
@@ -224,7 +234,8 @@ public class HttpUtils {
bytesRead = dis.read(tempBody, offset, bytesTobeRead);
} catch (IOException e) {
readError = true;
Timber.e("httpConnection: error reading input stream" + e.getMessage());
Timber.e("httpConnection: error reading input stream"
+ e.getMessage());
break;
}
if (bytesRead > 0) {
@@ -237,7 +248,8 @@ public class HttpUtils {
// bytesRead will be -1 if the data was read till the eof
body = new byte[offset];
System.arraycopy(tempBody, 0, body, 0, offset);
Timber.v("httpConnection: Chunked response length [" + Integer.toString(offset) + "]");
Timber.v("httpConnection: Chunked response length ["
+ Integer.toString(offset) + "]");
} else {
Timber.e("httpConnection: Response entity too large or empty");
}
@@ -293,7 +305,10 @@ public class HttpUtils {
// set the socket timeout
int soTimeout = MmsConfig.getHttpSocketTimeout();
Timber.d("[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, " + ", UA=" + userAgent);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.DEBUG)) {
Timber.d("[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, "
+ ", UA=" + userAgent);
}
HttpConnectionParams.setSoTimeout(params, soTimeout);
return client;
}
@@ -0,0 +1,33 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.transaction;
import com.google.android.mms.MmsException;
public interface MessageSender {
public static final String RECIPIENTS_SEPARATOR = ";";
/**
* Send the message through MMS or SMS protocol.
* @param token The token to identify the sending progress.
*
* @return True if the message was sent through MMS or false if it was
* sent through SMS.
* @throws com.google.android.mms.MmsException Error occurred while sending the message.
*/
boolean sendMessage(long token) throws MmsException;
}
@@ -27,7 +27,9 @@ import android.net.Uri;
import android.provider.Telephony.Sms;
import android.provider.Telephony.Sms.Inbox;
import android.telephony.SmsMessage;
import timber.log.Timber;
import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
/**
* Service that gets started by the MessageStatusReceiver when a message status report is
@@ -35,6 +37,7 @@ import timber.log.Timber;
*/
public class MessageStatusService extends IntentService {
private static final String[] ID_PROJECTION = new String[] { Sms._ID };
private static final String LOG_TAG = LogTag.TAG;
private static final Uri STATUS_URI = Uri.parse("content://sms/status");
public MessageStatusService() {
@@ -86,8 +89,10 @@ public class MessageStatusService extends IntentService {
boolean isStatusReport = message.isStatusReportMessage();
ContentValues contentValues = new ContentValues(2);
log("updateMessageStatus: msgUrl=" + messageUri + ", status=" + status
+ ", isStatusReport=" + isStatusReport);
if (Timber_isLoggable(LogTag.TAG, Log.DEBUG)) {
log("updateMessageStatus: msgUrl=" + messageUri + ", status=" + status +
", isStatusReport=" + isStatusReport);
}
contentValues.put(Sms.STATUS, status);
contentValues.put(Inbox.DATE_SENT, System.currentTimeMillis());
@@ -103,10 +108,10 @@ public class MessageStatusService extends IntentService {
}
private void error(String message) {
Timber.e("[MessageStatusReceiver] " + message);
Log.e(LOG_TAG, "[MessageStatusReceiver] " + message);
}
private void log(String message) {
Timber.d("[MessageStatusReceiver] " + message);
Log.d(LOG_TAG, "[MessageStatusReceiver] " + message);
}
}
@@ -0,0 +1,189 @@
/*
* Copyright 2014 Jacob Klinker
*
* 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 com.android.mms.transaction;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.InvalidHeaderValueException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadRecInd;
import com.google.android.mms.pdu_alt.SendReq;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.send_message.Settings;
public class MmsMessageSender implements MessageSender {
private static final String TAG = LogTag.TAG;
private final Context mContext;
private final Uri mMessageUri;
private final long mMessageSize;
// Default preference values
private static final boolean DEFAULT_DELIVERY_REPORT_MODE = false;
private static final boolean DEFAULT_READ_REPORT_MODE = false;
private static final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
private static final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private static final String DEFAULT_MESSAGE_CLASS = PduHeaders.MESSAGE_CLASS_PERSONAL_STR;
private static final String DELIVERY_REPORT_PREFERENCE = "delivery_reports";
private static final String READ_REPORT_PREFERENCE = "read_reports";
public MmsMessageSender(Context context, Uri location, long messageSize) {
mContext = context;
mMessageUri = location;
mMessageSize = messageSize;
if (mMessageUri == null) {
throw new IllegalArgumentException("Null message URI.");
}
}
public boolean sendMessage(long token) throws MmsException {
// Load the MMS from the message uri
if (Timber_isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("sendMessage uri: " + mMessageUri);
}
PduPersister p = PduPersister.getPduPersister(mContext);
GenericPdu pdu = p.load(mMessageUri);
if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_SEND_REQ) {
throw new MmsException("Invalid message: " + pdu.getMessageType());
}
SendReq sendReq = (SendReq) pdu;
// Update headers.
updatePreferencesHeaders(sendReq);
// MessageClass.
sendReq.setMessageClass(DEFAULT_MESSAGE_CLASS.getBytes());
// Update the 'date' field of the message before sending it.
sendReq.setDate(System.currentTimeMillis() / 1000L);
sendReq.setMessageSize(mMessageSize);
p.updateHeaders(mMessageUri, sendReq);
long messageId = ContentUris.parseId(mMessageUri);
// Move the message into MMS Outbox.
if (!mMessageUri.toString().startsWith(Mms.Draft.CONTENT_URI.toString())) {
// If the message is already in the outbox (most likely because we created a "primed"
// message in the outbox when the user hit send), then we have to manually put an
// entry in the pending_msgs table which is where TransacationService looks for
// messages to send. Normally, the entry in pending_msgs is created by the trigger:
// insert_mms_pending_on_update, when a message is moved from drafts to the outbox.
ContentValues values = new ContentValues(7);
values.put(PendingMessages.PROTO_TYPE, MmsSms.MMS_PROTO);
values.put(PendingMessages.MSG_ID, messageId);
values.put(PendingMessages.MSG_TYPE, pdu.getMessageType());
values.put(PendingMessages.ERROR_TYPE, 0);
values.put(PendingMessages.ERROR_CODE, 0);
values.put(PendingMessages.RETRY_INDEX, 0);
values.put(PendingMessages.DUE_TIME, 0);
SqliteWrapper.insert(mContext, mContext.getContentResolver(),
PendingMessages.CONTENT_URI, values);
} else {
p.move(mMessageUri, Mms.Outbox.CONTENT_URI);
}
// Start MMS transaction service
try {
SendingProgressTokenManager.put(messageId, token);
mContext.startService(new Intent(mContext, TransactionService.class));
} catch (Exception e) {
throw new MmsException("transaction service not registered in manifest");
}
return true;
}
// Update the headers which are stored in SharedPreferences.
private void updatePreferencesHeaders(SendReq sendReq) throws MmsException {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
// Expiry.
sendReq.setExpiry(DEFAULT_EXPIRY_TIME);
// Priority.
sendReq.setPriority(DEFAULT_PRIORITY);
// Delivery report.
boolean dr = prefs.getBoolean(DELIVERY_REPORT_PREFERENCE,
DEFAULT_DELIVERY_REPORT_MODE);
sendReq.setDeliveryReport(dr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO);
// Read report.
boolean rr = prefs.getBoolean(READ_REPORT_PREFERENCE,
// default to delivery report value if read report not available
prefs.getBoolean(DELIVERY_REPORT_PREFERENCE,
DEFAULT_READ_REPORT_MODE));
sendReq.setReadReport(rr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO);
}
public static void sendReadRec(Context context, String to, String messageId, int status) {
EncodedStringValue[] sender = new EncodedStringValue[1];
sender[0] = new EncodedStringValue(to);
try {
final ReadRecInd readRec = new ReadRecInd(
new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()),
messageId.getBytes(),
PduHeaders.CURRENT_MMS_VERSION,
status,
sender);
readRec.setDate(System.currentTimeMillis() / 1000);
boolean group;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
PduPersister.getPduPersister(context).persist(readRec, Mms.Outbox.CONTENT_URI, true,
group, null, subId);
context.startService(new Intent(context, TransactionService.class));
} catch (InvalidHeaderValueException e) {
Timber.e("Invalide header value", e);
} catch (MmsException e) {
Timber.e("Persist message failed", e);
}
}
}
@@ -15,10 +15,12 @@
*/
package com.android.mms.transaction;
import com.android.mms.logs.LogTag;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import timber.log.Timber;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
/**
* MmsPushOutboxMessages listens for MMS_SEND_OUTBOX_MSG intent .
@@ -29,13 +31,16 @@ import timber.log.Timber;
*/
public class MmsPushOutboxMessages extends BroadcastReceiver {
private static final String INTENT_MMS_SEND_OUTBOX_MSG = "android.intent.action.MMS_SEND_OUTBOX_MSG";
private static final String TAG = LogTag.TAG;
@Override
public void onReceive(Context context, Intent intent) {
Timber.v("Received the MMS_SEND_OUTBOX_MSG intent: " + intent);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Received the MMS_SEND_OUTBOX_MSG intent: " + intent);
}
String action = intent.getAction();
if(action.equalsIgnoreCase(INTENT_MMS_SEND_OUTBOX_MSG)){
Timber.d("Now waking up the MMS service");
Log.d(TAG,"Now waking up the MMS service");
context.startService(new Intent(context, TransactionService.class));
}
}
@@ -22,9 +22,12 @@ import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Telephony.Mms;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.android.mms.logs.LogTag;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
/**
* MmsSystemEventReceiver receives the
@@ -36,14 +39,24 @@ import timber.log.Timber;
* </ul>
*/
public class MmsSystemEventReceiver extends BroadcastReceiver {
private static final String TAG = LogTag.TAG;
private static ConnectivityManager mConnMgr = null;
public static void wakeUpService(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("wakeUpService: start transaction service ...");
}
context.startService(new Intent(context, TransactionService.class));
}
}
@Override
public void onReceive(Context context, Intent intent) {
Timber.v("Intent received: " + intent);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Intent received: " + intent);
}
if (!Utils.isDefaultSmsApp(context)) {
Timber.v("not default sms app, cancelling");
@@ -72,14 +85,18 @@ public class MmsSystemEventReceiver extends BroadcastReceiver {
//Utils.setMobileDataEnabled(context, true);
return;
}
NetworkInfo mmsNetworkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
if (mmsNetworkInfo == null) {
return;
}
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
Timber.v("TYPE_MOBILE_MMS available = " + available + ", isConnected = " + isConnected);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
@@ -29,6 +29,7 @@ import android.provider.Telephony.Mms.Inbox;
import android.provider.Telephony.Threads;
import android.telephony.TelephonyManager;
import com.android.mms.logs.LogTag;
import com.android.mms.MmsConfig;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException;
@@ -40,12 +41,13 @@ 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 timber.log.Timber;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Settings;
import java.io.IOException;
import timber.log.Timber;
import static com.android.mms.transaction.TransactionState.FAILED;
import static com.android.mms.transaction.TransactionState.INITIALIZED;
import static com.android.mms.transaction.TransactionState.SUCCESS;
@@ -71,6 +73,8 @@ import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_UNRECOGNIZED;
* in case the client is in immediate retrieve mode.
*/
public class NotificationTransaction extends Transaction implements Runnable {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private Uri mUri;
@@ -88,7 +92,7 @@ public class NotificationTransaction extends Transaction implements Runnable {
mNotificationInd = (NotificationInd)
PduPersister.getPduPersister(context).load(mUri);
} catch (MmsException e) {
Timber.e(e, "Failed to load NotificationInd from: " + uriString);
Timber.e("Failed to load NotificationInd from: " + uriString, e);
throw new IllegalArgumentException();
}
@@ -110,10 +114,20 @@ public class NotificationTransaction extends Transaction implements Runnable {
try {
// Save the pdu. If we can start downloading the real pdu immediately, don't allow
// persist() to create a thread for the notificationInd because it causes UI jank.
mUri = PduPersister.getPduPersister(context).persist(ind, Inbox.CONTENT_URI,
PduPersister.DUMMY_THREAD_ID, !allowAutoDownload(mContext), true, null);
boolean group;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("group_message", true);
}
mUri = PduPersister.getPduPersister(context).persist(
ind, Inbox.CONTENT_URI, !allowAutoDownload(mContext),
group, null, subId);
} catch (MmsException e) {
Timber.e(e, "Failed to save NotificationInd in constructor.");
Timber.e("Failed to save NotificationInd in constructor.", e);
throw new IllegalArgumentException();
}
@@ -184,18 +198,20 @@ public class NotificationTransaction extends Transaction implements Runnable {
} else {
// Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI, PduPersister.DUMMY_THREAD_ID,
true, true, null);
RetrieveConf retrieveConf = (RetrieveConf) pdu;
Uri uri = p.persist(pdu, Inbox.CONTENT_URI, true,
com.klinker.android.send_message.Transaction.settings.getGroup(), null, com.klinker.android.send_message.Transaction.settings.getSubscriptionId());
// Use local time instead of PDU time
ContentValues values = new ContentValues(2);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
try {
// Store PDU time as sent time for received message
RetrieveConf retrieveConf = (RetrieveConf) pdu;
values.put(Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
} catch (Exception e) {
}
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
@@ -237,7 +253,7 @@ public class NotificationTransaction extends Transaction implements Runnable {
sendNotifyRespInd(status);
} catch (Throwable t) {
Timber.e(t, "error");
Timber.e("error", t);
} finally {
mTransactionState.setContentUri(mUri);
if (!autoDownload) {
View File
@@ -19,7 +19,9 @@ package com.android.mms.transaction;
import android.content.Context;
import android.content.Intent;
import com.klinker.android.send_message.BroadcastUtils;
import org.apache.http.entity.ByteArrayEntity;
import java.io.IOException;
+159 -37
View File
@@ -21,15 +21,25 @@ import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import android.telephony.SmsManager;
import android.text.TextUtils;
import com.android.mms.MmsConfig;
import com.android.mms.logs.LogTag;
import com.android.mms.service_alt.DownloadRequest;
import com.android.mms.service_alt.MmsNetworkManager;
import com.android.mms.service_alt.MmsRequestManager;
import com.google.android.mms.ContentType;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.DeliveryInd;
@@ -39,6 +49,11 @@ 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.ReadOrigInd;
import timber.log.Timber; import android.util.Log;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Settings;
import com.klinker.android.send_message.SmsManagerFactory;
import com.klinker.android.send_message.Utils;
import java.util.HashSet;
@@ -46,8 +61,6 @@ import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import timber.log.Timber;
import static android.provider.Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION;
import static android.provider.Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION;
import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_DELIVERY_IND;
@@ -59,19 +72,25 @@ import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_READ_ORIG_I
* TransactionService by passing the push-data to it.
*/
public class PushReceiver extends BroadcastReceiver {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = true;
static final String[] PROJECTION = new String[]{Mms.CONTENT_LOCATION, Mms.LOCKED};
static final String[] PROJECTION = new String[] {
Mms.CONTENT_LOCATION,
Mms.LOCKED
};
static final int COLUMN_CONTENT_LOCATION = 0;
static final int COLUMN_CONTENT_LOCATION = 0;
private static Set<String> downloadedUrls = new HashSet<String>();
private static final ExecutorService PUSH_RECEIVER_EXECUTOR = Executors.newSingleThreadExecutor();
private class ReceivePushTask extends AsyncTask<Intent, Void, Void> {
private class ReceivePushTask extends AsyncTask<Intent,Void,Void> {
private Context mContext;
private PendingResult pendingResult;
private ReceivePushTask(Context context, PendingResult pendingResult) {
ReceivePushTask(Context context, PendingResult pendingResult) {
mContext = context;
this.pendingResult = pendingResult;
}
@@ -86,7 +105,7 @@ public class PushReceiver extends BroadcastReceiver {
PduParser parser = new PduParser(pushData);
GenericPdu pdu = parser.parse();
if (pdu == null) {
if (null == pdu) {
Timber.e("Invalid PUSH data");
return null;
}
@@ -94,7 +113,8 @@ public class PushReceiver extends BroadcastReceiver {
PduPersister p = PduPersister.getPduPersister(mContext);
ContentResolver cr = mContext.getContentResolver();
int type = pdu.getMessageType();
long threadId;
long threadId = -1;
int subId = intent.getIntExtra("subscription", Settings.DEFAULT_SUBSCRIPTION_ID);
try {
switch (type) {
@@ -107,8 +127,16 @@ public class PushReceiver extends BroadcastReceiver {
break;
}
Uri uri = p.persist(pdu, Uri.parse("content://mms/inbox"),
PduPersister.DUMMY_THREAD_ID, true, true, null);
boolean group;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("group_message", true);
}
Uri uri = p.persist(pdu, Uri.parse("content://mms/inbox"), true,
group, null, subId);
// Update thread ID for ReadOrigInd & DeliveryInd.
ContentValues values = new ContentValues(1);
values.put(Mms.THREAD_ID, threadId);
@@ -118,12 +146,22 @@ public class PushReceiver extends BroadcastReceiver {
case MESSAGE_TYPE_NOTIFICATION_IND: {
NotificationInd nInd = (NotificationInd) pdu;
if (MmsConfig.getTransIdEnabled()) {
byte[] contentLocation = nInd.getContentLocation();
boolean appendTransactionId = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Bundle configOverrides = SmsManagerFactory.createSmsManager(subId).getCarrierConfigValues();
appendTransactionId = configOverrides.getBoolean(SmsManager.MMS_CONFIG_APPEND_TRANSACTION_ID);
if (appendTransactionId) {
Timber.v("appending the transaction ID, based on the SMS manager overrides");
}
}
if (MmsConfig.getTransIdEnabled() || appendTransactionId) {
byte [] contentLocation = nInd.getContentLocation();
if ('=' == contentLocation[contentLocation.length - 1]) {
byte[] transactionId = nInd.getTransactionId();
byte[] contentLocationWithId = new byte[contentLocation.length
+ transactionId.length];
byte [] transactionId = nInd.getTransactionId();
byte [] contentLocationWithId = new byte [contentLocation.length
+ transactionId.length];
System.arraycopy(contentLocation, 0, contentLocationWithId,
0, contentLocation.length);
System.arraycopy(transactionId, 0, contentLocationWithId,
@@ -136,10 +174,30 @@ public class PushReceiver extends BroadcastReceiver {
// Save the pdu. If we can start downloading the real pdu immediately,
// don't allow persist() to create a thread for the notificationInd
// because it causes UI jank.
Uri uri = p.persist(pdu, Inbox.CONTENT_URI,
PduPersister.DUMMY_THREAD_ID, true, true, null);
boolean group;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("group_message", true);
}
Uri uri = p.persist(pdu, Inbox.CONTENT_URI,
!NotificationTransaction.allowAutoDownload(mContext),
group,
null,
subId);
String location;
try {
location = getContentLocation(mContext, uri);
} catch (MmsException ex) {
location = p.getContentLocationFromPduHeader(pdu);
if (TextUtils.isEmpty(location)) {
throw ex;
}
}
String location = getContentLocation(mContext, uri);
if (downloadedUrls.contains(location)) {
Timber.v("already added this download, don't download again");
return null;
@@ -147,10 +205,52 @@ public class PushReceiver extends BroadcastReceiver {
downloadedUrls.add(location);
}
int subId = intent.getIntExtra("subscription", Utils.getDefaultSubscriptionId());
DownloadManager.getInstance().downloadMultimediaMessage(mContext, location, uri, true, subId);
} else {
Timber.v("Skip downloading duplicate message: " + new String(nInd.getContentLocation()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Timber.v("receiving on a lollipop+ device");
boolean useSystem = true;
if (com.klinker.android.send_message.Transaction.settings != null) {
useSystem = com.klinker.android.send_message.Transaction.settings
.getUseSystemSending();
} else {
useSystem = PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean("system_mms_sending", useSystem);
}
if (useSystem) {
DownloadManager.getInstance().downloadMultimediaMessage(mContext, location, uri, true, subId);
} else {
Timber.v("receiving with lollipop method");
MmsRequestManager requestManager = new MmsRequestManager(mContext);
DownloadRequest request = new DownloadRequest(requestManager,
Utils.getDefaultSubscriptionId(),
location, uri, null, null,
null, mContext);
MmsNetworkManager manager = new MmsNetworkManager(mContext, Utils.getDefaultSubscriptionId());
request.execute(mContext, manager);
}
} else {
if (NotificationTransaction.allowAutoDownload(mContext)) {
// Start service to finish the notification transaction.
Intent svc = new Intent(mContext, TransactionService.class);
svc.putExtra(TransactionBundle.URI, uri.toString());
svc.putExtra(TransactionBundle.TRANSACTION_TYPE,
Transaction.NOTIFICATION_TRANSACTION);
svc.putExtra(TransactionBundle.LOLLIPOP_RECEIVING,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
mContext.startService(svc);
} else {
Intent notificationBroadcast = new Intent(com.klinker.android.send_message.Transaction.NOTIFY_OF_MMS);
notificationBroadcast.putExtra("receive_through_stock", true);
BroadcastUtils.sendExplicitBroadcast(
mContext,
notificationBroadcast,
com.klinker.android.send_message.Transaction.NOTIFY_OF_MMS);
}
}
} else if (LOCAL_LOGV) {
Timber.v("Skip downloading duplicate message: "
+ new String(nInd.getContentLocation()));
}
break;
}
@@ -158,19 +258,23 @@ public class PushReceiver extends BroadcastReceiver {
Timber.e("Received unrecognized PDU.");
}
} catch (MmsException e) {
Timber.e(e, "Failed to save the data from PUSH: type=" + type);
Timber.e("Failed to save the data from PUSH: type=" + type, e);
} catch (RuntimeException e) {
Timber.e(e, "Unexpected RuntimeException.");
Timber.e("Unexpected RuntimeException.", e);
}
Timber.v("PUSH Intent processed.");
if (LOCAL_LOGV) {
Timber.v("PUSH Intent processed.");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
pendingResult.finish();
public void onPostExecute(Void result) {
if (pendingResult != null) {
pendingResult.finish();
}
}
}
@@ -179,16 +283,33 @@ public class PushReceiver extends BroadcastReceiver {
Timber.v(intent.getAction() + " " + intent.getType());
if ((intent.getAction().equals(WAP_PUSH_DELIVER_ACTION) || intent.getAction().equals(WAP_PUSH_RECEIVED_ACTION))
&& ContentType.MMS_MESSAGE.equals(intent.getType())) {
Timber.v("Received PUSH Intent: " + intent);
if (LOCAL_LOGV) {
Timber.v("Received PUSH Intent: " + intent);
}
MmsConfig.init(context);
new ReceivePushTask(context, goAsync()).executeOnExecutor(PUSH_RECEIVER_EXECUTOR, intent);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
if ((!sharedPrefs.getBoolean("receive_with_stock", false) && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && sharedPrefs.getBoolean("override", true))
|| Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
MmsConfig.init(context);
new ReceivePushTask(context, null).executeOnExecutor(PUSH_RECEIVER_EXECUTOR, intent);
Timber.v(context.getPackageName() + " received and aborted");
Log.v("mms_receiver", context.getPackageName() + " received and aborted");
} else {
clearAbortBroadcast();
Intent notificationBroadcast = new Intent(com.klinker.android.send_message.Transaction.NOTIFY_OF_MMS);
notificationBroadcast.putExtra("receive_through_stock", true);
BroadcastUtils.sendExplicitBroadcast(
context,
notificationBroadcast,
com.klinker.android.send_message.Transaction.NOTIFY_OF_MMS);
Log.v("mms_receiver", context.getPackageName() + " received and not aborted");
}
}
}
public static String getContentLocation(Context context, Uri uri) throws MmsException {
public static String getContentLocation(Context context, Uri uri)
throws MmsException {
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, PROJECTION, null, null, null);
@@ -228,8 +349,8 @@ public class PushReceiver extends BroadcastReceiver {
// sb.append(')');
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
Mms.CONTENT_URI, new String[]{Mms.THREAD_ID},
sb.toString(), null, null);
Mms.CONTENT_URI, new String[] { Mms.THREAD_ID },
sb.toString(), null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
@@ -245,15 +366,16 @@ public class PushReceiver extends BroadcastReceiver {
return -1;
}
private static boolean isDuplicateNotification(Context context, NotificationInd nInd) {
private static boolean isDuplicateNotification(
Context context, NotificationInd nInd) {
byte[] rawLocation = nInd.getContentLocation();
if (rawLocation != null) {
String location = new String(rawLocation);
String selection = Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[]{location};
String[] selectionArgs = new String[] { location };
Cursor cursor = SqliteWrapper.query(
context, context.getContentResolver(),
Mms.CONTENT_URI, new String[]{Mms._ID},
Mms.CONTENT_URI, new String[] { Mms._ID },
selection, selectionArgs, null);
if (cursor != null) {
try {
+10 -6
View File
@@ -16,18 +16,20 @@
package com.android.mms.transaction;
import java.io.IOException;
import android.content.Context;
import android.net.Uri;
import android.provider.Telephony.Mms.Sent;
import timber.log.Timber;
import com.android.mms.logs.LogTag;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadRecInd;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import java.io.IOException;
/**
* The ReadRecTransaction is responsible for sending read report
@@ -41,6 +43,8 @@ import java.io.IOException;
* </ul>
*/
public class ReadRecTransaction extends Transaction implements Runnable{
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private Thread mThread;
@@ -88,15 +92,15 @@ public class ReadRecTransaction extends Transaction implements Runnable{
mTransactionState.setContentUri(uri);
} catch (IOException e) {
if (LOCAL_LOGV) {
Timber.v(e, "Failed to send M-Read-Rec.Ind.");
Timber.v("Failed to send M-Read-Rec.Ind.", e);
}
} catch (MmsException e) {
if (LOCAL_LOGV) {
Timber.v(e, "Failed to load message from Outbox.");
Timber.v("Failed to load message from Outbox.", e);
}
} catch (RuntimeException e) {
if (LOCAL_LOGV) {
Timber.e(e, "Unexpected RuntimeException.");
Timber.e("Unexpected RuntimeException.", e);
}
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
+34 -13
View File
@@ -16,15 +16,20 @@
package com.android.mms.transaction;
import java.io.IOException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import android.text.TextUtils;
import timber.log.Timber;
import com.android.mms.logs.LogTag;
import com.android.mms.MmsConfig;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException;
@@ -35,12 +40,9 @@ 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.klinker.android.send_message.Settings;
import com.klinker.android.send_message.Utils;
import java.io.IOException;
import timber.log.Timber;
/**
* The RetrieveTransaction is responsible for retrieving multimedia
* messages (M-Retrieve.conf) from the MMSC server. It:
@@ -55,7 +57,9 @@ import timber.log.Timber;
* </ul>
*/
public class RetrieveTransaction extends Transaction implements Runnable {
private static final boolean LOCAL_LOGV = false;
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = true;
private final Uri mUri;
private final String mContentLocation;
@@ -124,6 +128,11 @@ public class RetrieveTransaction extends Transaction implements Runnable {
}
public void run() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// DownloadRequest request = new DownloadRequest(mContentLocation, mUri, null, null, null);
// MmsNetworkManager manager = new MmsNetworkManager(mContext);
// request.execute(mContext, manager);
// } else {
try {
// Change the downloading state of the M-Notification.ind.
DownloadManager.init(mContext.getApplicationContext());
@@ -146,19 +155,31 @@ public class RetrieveTransaction extends Transaction implements Runnable {
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mUri);
} else {
boolean group;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
try {
group = com.klinker.android.send_message.Transaction.settings.getGroup();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} catch (Exception e) {
group = PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("group_message", true);
}
// Store M-Retrieve.conf into Inbox
PduPersister persister = PduPersister.getPduPersister(mContext);
msgUri = persister.persist(retrieveConf, Inbox.CONTENT_URI,
PduPersister.DUMMY_THREAD_ID, true, true, null);
msgUri = persister.persist(retrieveConf, Inbox.CONTENT_URI, true,
group, null, subId);
// Use local time instead of PDU time
ContentValues values = new ContentValues(3);
ContentValues values = new ContentValues();
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
try {
values.put(Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
}
values.put(Mms.MESSAGE_SIZE, resp.length);
try {
// Store PDU time as sent time for received message
values.put(Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception e) {
}
SqliteWrapper.update(mContext, mContext.getContentResolver(),
msgUri, values, null, null);
@@ -181,7 +202,7 @@ public class RetrieveTransaction extends Transaction implements Runnable {
// Don't mark the transaction as failed if we failed to send it.
sendAcknowledgeInd(retrieveConf);
} catch (Throwable t) {
Timber.e(t, "error");
Timber.e("error", t);
if ("HTTP error: Not Found".equals(t.getMessage())) {
// Delete the expired M-Notification.ind.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
+21 -13
View File
@@ -31,15 +31,19 @@ import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import com.android.mms.logs.LogTag;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduPersister;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.R;
import timber.log.Timber;
public class RetryScheduler implements Observer {
private static final boolean LOCAL_LOGV = false;
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = true;
private final Context mContext;
private final ContentResolver mContentResolver;
@@ -68,7 +72,9 @@ public class RetryScheduler implements Observer {
try {
Transaction t = (Transaction) observable;
Timber.v("[RetryScheduler] update " + observable);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("[RetryScheduler] update " + observable);
}
// We are only supposed to handle M-Notification.ind, M-Send.req
// and M-ReadRec.ind.
@@ -143,11 +149,6 @@ public class RetryScheduler implements Observer {
case PduHeaders.RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND:
errorString = R.string.service_message_not_found;
break;
case PduHeaders.RESPONSE_STATUS_ERROR_CONTENT_NOT_ACCEPTED:
case PduHeaders.RESPONSE_STATUS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED:
errorString = R.string.service_message_content_not_accepted;
break;
}
if (errorString != 0) {
DownloadManager.init(mContext.getApplicationContext());
@@ -172,8 +173,10 @@ public class RetryScheduler implements Observer {
if ((retryIndex < scheme.getRetryLimit()) && retry) {
long retryAt = current + scheme.getWaitingInterval();
Timber.v("scheduleRetry: retry for " + uri + " is scheduled at "
+ (retryAt - System.currentTimeMillis()) + "ms from now");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("scheduleRetry: retry for " + uri + " is scheduled at "
+ (retryAt - System.currentTimeMillis()) + "ms from now");
}
values.put(PendingMessages.DUE_TIME, retryAt);
@@ -296,7 +299,9 @@ public class RetryScheduler implements Observer {
cursor.close();
}
if (retrieveStatus != 0) {
Timber.v("Retrieve status is: " + retrieveStatus);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Retrieve status is: " + retrieveStatus);
}
}
return retrieveStatus;
}
@@ -314,12 +319,15 @@ public class RetryScheduler implements Observer {
Intent service = new Intent(TransactionService.ACTION_ONALARM,
null, context, TransactionService.class);
PendingIntent operation = PendingIntent.getService(
context, 0, service, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
context, 0, service, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE);
AlarmManager am = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
am.set(AlarmManager.RTC, retryAt, operation);
Timber.v("Next retry is scheduled at" + (retryAt - System.currentTimeMillis()) + "ms from now");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Next retry is scheduled at"
+ (retryAt - System.currentTimeMillis()) + "ms from now");
}
}
} finally {
cursor.close();
+11 -5
View File
@@ -25,6 +25,8 @@ import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Sent;
import android.text.TextUtils;
import com.android.mms.logs.LogTag;
import com.android.mms.util.RateController;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.pdu_alt.EncodedStringValue;
@@ -34,9 +36,9 @@ import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.SendConf;
import com.google.android.mms.pdu_alt.SendReq;
import timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import java.util.Arrays;
@@ -54,6 +56,8 @@ import java.util.Arrays;
* </ul>
*/
public class SendTransaction extends Transaction implements Runnable {
private static final String TAG = LogTag.TAG;
private Thread mThread;
public final Uri mSendReqURI;
@@ -113,9 +117,11 @@ public class SendTransaction extends Transaction implements Runnable {
new PduComposer(mContext, sendReq).make());
SendingProgressTokenManager.remove(tokenKey);
String respStr = new String(response);
builder.append("[SendTransaction] run: send mms msg (" + mId + "), resp=" + respStr);
Timber.d("[SendTransaction] run: send mms msg (" + mId + "), resp=" + respStr);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
String respStr = new String(response);
builder.append("[SendTransaction] run: send mms msg (" + mId + "), resp=" + respStr);
Timber.d("[SendTransaction] run: send mms msg (" + mId + "), resp=" + respStr);
}
SendConf conf = (SendConf) new PduParser(response).parse();
if (conf == null) {
@@ -161,7 +167,7 @@ public class SendTransaction extends Transaction implements Runnable {
mTransactionState.setState(TransactionState.SUCCESS);
mTransactionState.setContentUri(uri);
} catch (Throwable t) {
Timber.e(t, "error");
Timber.e("error", t);
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
mTransactionState.setState(TransactionState.FAILED);
+6 -2
View File
@@ -16,15 +16,19 @@
package com.android.mms.transaction;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.MmsException;
import com.klinker.android.send_message.Utils;
import java.io.IOException;
/**
* Transaction is an abstract class for notification transaction, send transaction
* and other transactions described in MMS spec.
+337 -86
View File
@@ -26,7 +26,10 @@ import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
@@ -35,11 +38,18 @@ import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import android.text.TextUtils;
import android.widget.Toast;
import com.android.mms.logs.LogTag;
import com.android.mms.service_alt.DownloadRequest;
import com.android.mms.service_alt.MmsNetworkManager;
import com.android.mms.service_alt.MmsRequestManager;
import com.android.mms.util.DownloadManager;
import com.android.mms.util.RateController;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu;
@@ -47,20 +57,15 @@ import com.google.android.mms.pdu_alt.NotificationInd;
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 timber.log.Timber; import android.util.Log; import static com.klinker.android.timberworkarounds.TimberExtensionsKt.Timber_isLoggable; // inserted with sed
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.R;
import com.klinker.android.send_message.Settings;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import java.io.IOException;
import java.util.ArrayList;
import android.net.Network;
import android.net.NetworkRequest;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.os.Build;
/**
* The TransactionService of the MMS Client is responsible for handling requests
* to initiate client-transactions sent from:
@@ -89,6 +94,7 @@ import android.os.Build;
* </ul>
*/
public class TransactionService extends Service implements Observer {
private static final String TAG = LogTag.TAG;
/**
* Used to identify notification intents broadcasted by the
@@ -173,7 +179,9 @@ public class TransactionService extends Service implements Observer {
@Override
public void onCreate() {
Timber.v("Creating TransactionService");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Creating TransactionService");
}
if (!Utils.isDefaultSmsApp(this)) {
Timber.v("not default app, so exiting");
@@ -204,6 +212,33 @@ public class TransactionService extends Service implements Observer {
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (intent != null) {
// if (intent.getBooleanExtra(TransactionBundle.LOLLIPOP_RECEIVING, false)) {
// lollipopReceiving = true;
// new Thread(new Runnable() {
// @Override
// public void run() {
// Timber.v("starting receiving with new lollipop method");
// try { Thread.sleep(60000); } catch (Exception e) { }
// Timber.v("done sleeping, lets try and grab the message");
// Uri contentUri = Uri.parse(intent.getStringExtra(TransactionBundle.URI));
// String downloadLocation = null;
// Cursor locationQuery = getContentResolver().query(contentUri, new String[]{Telephony.Mms.CONTENT_LOCATION, Telephony.Mms._ID}, null, null, "date desc");
//
// if (locationQuery != null && locationQuery.moveToFirst()) {
// Timber.v("grabbing content location url");
// downloadLocation = locationQuery.getString(locationQuery.getColumnIndex(Telephony.Mms.CONTENT_LOCATION));
// }
//
// Timber.v("creating request with url: " + downloadLocation);
// DownloadRequest request = new DownloadRequest(downloadLocation, contentUri, null, null, null);
// MmsNetworkManager manager = new MmsNetworkManager(TransactionService.this);
// request.execute(TransactionService.this, manager);
// stopSelf();
// }
// }).start();
// return START_NOT_STICKY;
// }
if (mServiceHandler == null) {
initServiceHandler();
}
@@ -234,10 +269,12 @@ public class TransactionService extends Service implements Observer {
} catch (Exception e) {
mobileDataEnabled = true;
}
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (!mobileDataEnabled) {
Utils.setMobileDataEnabled(this, true);
}
if (mConnMgr == null) {
endMmsConnectivity();
stopSelf(serviceId);
@@ -246,8 +283,11 @@ public class TransactionService extends Service implements Observer {
boolean noNetwork = !isNetworkAvailable();
Timber.v("onNewIntent: serviceId: " + serviceId + ": " + intent.getExtras() + " intent=" + intent);
Timber.v(" networkAvailable=" + !noNetwork);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: serviceId: " + serviceId + ": " + intent.getExtras() +
" intent=" + intent);
Timber.v(" networkAvailable=" + !noNetwork);
}
String action = intent.getAction();
if (ACTION_ONALARM.equals(action) || ACTION_ENABLE_AUTO_RETRIEVE.equals(action) ||
@@ -259,10 +299,14 @@ public class TransactionService extends Service implements Observer {
try {
int count = cursor.getCount();
Timber.v("onNewIntent: cursor.count=" + count + " action=" + action);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: cursor.count=" + count + " action=" + action);
}
if (count == 0) {
Timber.v("onNewIntent: no pending messages. Stopping service.");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: no pending messages. Stopping service.");
}
RetryScheduler.setRetryAlarm(this);
stopSelfIfIdle(serviceId);
return;
@@ -276,28 +320,139 @@ public class TransactionService extends Service implements Observer {
int msgType = cursor.getInt(columnIndexOfMsgType);
int transactionType = getTransactionType(msgType);
try {
Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI,
cursor.getLong(columnIndexOfMsgId));
com.android.mms.transaction.DownloadManager.getInstance().
downloadMultimediaMessage(this, PushReceiver.getContentLocation(this, uri), uri, false, Utils.getDefaultSubscriptionId());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
boolean useSystem = true;
int subId = Settings.DEFAULT_SUBSCRIPTION_ID;
if (com.klinker.android.send_message.Transaction.settings != null) {
useSystem = com.klinker.android.send_message.Transaction.settings
.getUseSystemSending();
subId = com.klinker.android.send_message.Transaction.settings.getSubscriptionId();
} else {
useSystem = PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("system_mms_sending", useSystem);
}
// can't handle many messages at once.
break;
} catch (MmsException e) {
e.printStackTrace();
if (useSystem) {
try {
Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI,
cursor.getLong(columnIndexOfMsgId));
com.android.mms.transaction.DownloadManager.getInstance().
downloadMultimediaMessage(this, PushReceiver.getContentLocation(this, uri), uri, false, subId);
// can't handle many messages at once.
break;
} catch (MmsException e) {
e.printStackTrace();
}
} else {
try {
Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI,
cursor.getLong(columnIndexOfMsgId));
MmsRequestManager requestManager = new MmsRequestManager(this);
DownloadRequest request = new DownloadRequest(requestManager,
Utils.getDefaultSubscriptionId(),
PushReceiver.getContentLocation(this, uri), uri, null, null,
null, this);
MmsNetworkManager manager = new MmsNetworkManager(this, Utils.getDefaultSubscriptionId());
request.execute(this, manager);
// can't handle many messages at once.
break;
} catch (Exception e) {
e.printStackTrace();
}
}
continue;
}
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: msgType=" + msgType + " transactionType=" +
transactionType);
}
if (noNetwork) {
onNetworkUnavailable(serviceId, transactionType);
return;
}
switch (transactionType) {
case -1:
break;
case Transaction.RETRIEVE_TRANSACTION:
// If it's a transiently failed transaction,
// we should retry it in spite of current
// downloading mode. If the user just turned on the auto-retrieve
// option, we also retry those messages that don't have any errors.
int failureType = cursor.getInt(
cursor.getColumnIndexOrThrow(
PendingMessages.ERROR_TYPE));
try {
DownloadManager.init(this);
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = downloadManager.isAuto();
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: failureType=" + failureType +
" action=" + action + " isTransientFailure:" +
isTransientFailure(failureType) + " autoDownload=" +
autoDownload);
}
if (!autoDownload) {
// If autodownload is turned off, don't process the
// transaction.
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: skipping - autodownload off");
}
// Re-enable "download" button if auto-download is off
Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI,
cursor.getLong(columnIndexOfMsgId));
downloadManager.markState(uri,
DownloadManager.STATE_SKIP_RETRYING);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
// Logic is twisty. If there's no failure or the failure
// is a non-permanent failure, we want to process the transaction.
// Otherwise, break out and skip processing this transaction.
if (!(failureType == MmsSms.NO_ERROR ||
isTransientFailure(failureType))) {
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: skipping - permanent error");
}
break;
}
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: falling through and processing");
}
// fall-through
default:
Uri uri = ContentUris.withAppendedId(
Mms.CONTENT_URI,
cursor.getLong(columnIndexOfMsgId));
TransactionBundle args = new TransactionBundle(
transactionType, uri.toString());
// FIXME: We use the same startId for all MMs.
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: launchTransaction uri=" + uri);
}
launchTransaction(serviceId, args, false);
break;
}
}
} finally {
cursor.close();
}
} else {
Timber.v("onNewIntent: no pending messages. Stopping service.");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: no pending messages. Stopping service.");
}
RetryScheduler.setRetryAlarm(this);
stopSelfIfIdle(serviceId);
}
} else {
Timber.v("onNewIntent: launch transaction...");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNewIntent: launch transaction...");
}
// For launching NotificationTransaction and test purpose.
TransactionBundle args = new TransactionBundle(intent.getExtras());
launchTransaction(serviceId, args, noNetwork);
@@ -307,7 +462,9 @@ public class TransactionService extends Service implements Observer {
private void stopSelfIfIdle(int startId) {
synchronized (mProcessing) {
if (mProcessing.isEmpty() && mPending.isEmpty()) {
Timber.v("stopSelfIfIdle: STOP!");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("stopSelfIfIdle: STOP!");
}
stopSelf(startId);
}
@@ -342,12 +499,16 @@ public class TransactionService extends Service implements Observer {
msg.arg1 = serviceId;
msg.obj = txnBundle;
Timber.v("launchTransaction: sending message " + msg);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("launchTransaction: sending message " + msg);
}
mServiceHandler.sendMessage(msg);
}
private void onNetworkUnavailable(int serviceId, int transactionType) {
Timber.v("onNetworkUnavailable: sid=" + serviceId + ", type=" + transactionType);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("onNetworkUnavailable: sid=" + serviceId + ", type=" + transactionType);
}
int toastType = TOAST_NONE;
if (transactionType == Transaction.RETRIEVE_TRANSACTION) {
@@ -363,7 +524,9 @@ public class TransactionService extends Service implements Observer {
@Override
public void onDestroy() {
Timber.v("Destroying TransactionService");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Destroying TransactionService");
}
if (!mPending.isEmpty()) {
Timber.w("TransactionService exiting with transaction still pending");
}
@@ -395,23 +558,31 @@ public class TransactionService extends Service implements Observer {
Transaction transaction = (Transaction) observable;
int serviceId = transaction.getServiceId();
Timber.v("update transaction " + serviceId);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("update transaction " + serviceId);
}
try {
synchronized (mProcessing) {
mProcessing.remove(transaction);
if (mPending.size() > 0) {
Timber.v("update: handle next pending transaction...");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("update: handle next pending transaction...");
}
Message msg = mServiceHandler.obtainMessage(
EVENT_HANDLE_NEXT_PENDING_TRANSACTION,
transaction.getConnectionSettings());
mServiceHandler.sendMessage(msg);
}
else if (mProcessing.isEmpty()) {
Timber.v("update: endMmsConnectivity");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("update: endMmsConnectivity");
}
endMmsConnectivity();
} else {
Timber.v("update: mProcessing is not empty");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("update: mProcessing is not empty");
}
}
}
@@ -422,7 +593,9 @@ public class TransactionService extends Service implements Observer {
switch (result) {
case TransactionState.SUCCESS:
Timber.v("Transaction complete: " + serviceId);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Transaction complete: " + serviceId);
}
intent.putExtra(STATE_URI, state.getContentUri());
@@ -446,14 +619,21 @@ public class TransactionService extends Service implements Observer {
}
break;
case TransactionState.FAILED:
Timber.v("Transaction failed: " + serviceId);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Transaction failed: " + serviceId);
}
break;
default:
Timber.v("Transaction state unknown: " + serviceId + " " + result);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Transaction state unknown: " +
serviceId + " " + result);
}
break;
}
Timber.v("update: broadcast transaction result " + result);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("update: broadcast transaction result " + result);
}
// Broadcast the result of the transaction.
BroadcastUtils.sendExplicitBroadcast(this, intent, TRANSACTION_COMPLETED_ACTION);
} finally {
@@ -465,10 +645,8 @@ public class TransactionService extends Service implements Observer {
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// Use a unique tag with a prefix followed by a colon for better debugging
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myapp:MMSConnectivity");
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "android-smsmms:MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
@@ -489,8 +667,9 @@ public class TransactionService extends Service implements Observer {
}
protected int beginMmsConnectivity() throws IOException {
Timber.v("beginMmsConnectivity");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("beginMmsConnectivity");
}
// Take a wake lock so we don't fall asleep before the message is downloaded.
createWakeLock();
@@ -510,13 +689,12 @@ public class TransactionService extends Service implements Observer {
// Request the mobile network for MMS connectivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
NetworkRequest.Builder builder = new NetworkRequest.Builder();
// Specify MMS capability and cellular transport
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
NetworkRequest networkRequest = builder.build();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.build();
mConnMgr.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
@Override
@@ -538,7 +716,6 @@ public class TransactionService extends Service implements Observer {
@Override
public void onLost(Network network) {
Timber.e("beginMmsConnectivity: Mobile network for MMS lost");
// Handle losing the network if needed
}
});
@@ -551,13 +728,19 @@ public class TransactionService extends Service implements Observer {
throw new IOException("Cannot establish MMS connectivity");
}
protected void endMmsConnectivity() {
try {
Timber.v("endMmsConnectivity");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("endMmsConnectivity");
}
// cancel timer for renewal of lease
mServiceHandler.removeMessages(EVENT_CONTINUE_MMS_CONNECTIVITY);
// if (mConnMgr != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// mConnMgr.stopUsingNetworkFeature(
// ConnectivityManager.TYPE_MOBILE,
// "enableMMS");
// }
} finally {
releaseWakeLock();
}
@@ -603,7 +786,9 @@ public class TransactionService extends Service implements Observer {
*/
@Override
public void handleMessage(Message msg) {
Timber.v("Handling incoming message: " + msg + " = " + decodeMessage(msg));
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Handling incoming message: " + msg + " = " + decodeMessage(msg));
}
Transaction transaction = null;
@@ -623,7 +808,9 @@ public class TransactionService extends Service implements Observer {
}
}
Timber.v("handle EVENT_CONTINUE_MMS_CONNECTIVITY event...");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("handle EVENT_CONTINUE_MMS_CONNECTIVITY event...");
}
try {
int result = beginMmsConnectivity();
@@ -649,8 +836,10 @@ public class TransactionService extends Service implements Observer {
TransactionBundle args = (TransactionBundle) msg.obj;
TransactionSettings transactionSettings;
Timber.v("EVENT_TRANSACTION_REQUEST MmscUrl=" +
args.getMmscUrl() + " proxy port: " + args.getProxyAddress());
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("EVENT_TRANSACTION_REQUEST MmscUrl=" +
args.getMmscUrl() + " proxy port: " + args.getProxyAddress());
}
// Set the connection settings for this transaction.
// If these have not been set in args, load the default settings.
@@ -665,8 +854,10 @@ public class TransactionService extends Service implements Observer {
int transactionType = args.getTransactionType();
Timber.v("handle EVENT_TRANSACTION_REQUEST: transactionType=" +
transactionType + " " + decodeTransactionType(transactionType));
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("handle EVENT_TRANSACTION_REQUEST: transactionType=" +
transactionType + " " + decodeTransactionType(transactionType));
}
// Create appropriate transaction
switch (transactionType) {
@@ -699,13 +890,29 @@ public class TransactionService extends Service implements Observer {
TransactionService.this, serviceId,
transactionSettings, args.getUri());
Uri u = Uri.parse(args.getUri());
com.android.mms.transaction.DownloadManager.getInstance().
downloadMultimediaMessage(TransactionService.this,
((RetrieveTransaction) transaction).getContentLocation(TransactionService.this, u), u, false, Utils.getDefaultSubscriptionId());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Uri u = Uri.parse(args.getUri());
com.android.mms.transaction.DownloadManager.getInstance().
downloadMultimediaMessage(TransactionService.this,
((RetrieveTransaction) transaction).getContentLocation(TransactionService.this, u), u, false, Settings.DEFAULT_SUBSCRIPTION_ID);
return;
}
break;
case Transaction.SEND_TRANSACTION:
transaction = new SendTransaction(
TransactionService.this, serviceId,
transactionSettings, args.getUri());
break;
case Transaction.READREC_TRANSACTION:
transaction = new ReadRecTransaction(
TransactionService.this, serviceId,
transactionSettings, args.getUri());
break;
default:
Timber.w("Invalid transaction type: " + serviceId);
transaction = null;
return;
}
if (!processTransaction(transaction)) {
@@ -713,9 +920,11 @@ public class TransactionService extends Service implements Observer {
return;
}
Timber.v("Started processing of incoming message: " + msg);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Started processing of incoming message: " + msg);
}
} catch (Exception ex) {
Timber.w(ex, "Exception occurred while handling message: " + msg);
Timber.w("Exception occurred while handling message: " + msg, ex);
if (transaction != null) {
try {
@@ -726,7 +935,7 @@ public class TransactionService extends Service implements Observer {
}
}
} catch (Throwable t) {
Timber.e(t, "Unexpected Throwable.");
Timber.e("Unexpected Throwable.", t);
} finally {
// Set transaction to null to allow stopping the
// transaction service.
@@ -735,7 +944,9 @@ public class TransactionService extends Service implements Observer {
}
} finally {
if (transaction == null) {
Timber.v("Transaction was null. Stopping self: " + serviceId);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Transaction was null. Stopping self: " + serviceId);
}
endMmsConnectivity();
stopSelf(serviceId);
}
@@ -774,7 +985,9 @@ public class TransactionService extends Service implements Observer {
public void processPendingTransaction(Transaction transaction,
TransactionSettings settings) {
Timber.v("processPendingTxn: transaction=" + transaction);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("processPendingTxn: transaction=" + transaction);
}
int numProcessTransaction = 0;
synchronized (mProcessing) {
@@ -795,20 +1008,27 @@ public class TransactionService extends Service implements Observer {
try {
int serviceId = transaction.getServiceId();
Timber.v("processPendingTxn: process " + serviceId);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("processPendingTxn: process " + serviceId);
}
if (processTransaction(transaction)) {
Timber.v("Started deferred processing of transaction " + transaction);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Started deferred processing of transaction "
+ transaction);
}
} else {
transaction = null;
stopSelf(serviceId);
}
} catch (IOException e) {
Timber.w(e, e.getMessage());
Timber.w(e.getMessage(), e);
}
} else {
if (numProcessTransaction == 0) {
Timber.v("processPendingTxn: no more transaction, endMmsConnectivity");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("processPendingTxn: no more transaction, endMmsConnectivity");
}
endMmsConnectivity();
}
}
@@ -827,13 +1047,18 @@ public class TransactionService extends Service implements Observer {
synchronized (mProcessing) {
for (Transaction t : mPending) {
if (t.isEquivalent(transaction)) {
Timber.v("Transaction already pending: " + transaction.getServiceId());
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Transaction already pending: " +
transaction.getServiceId());
}
return true;
}
}
for (Transaction t : mProcessing) {
if (t.isEquivalent(transaction)) {
Timber.v("Duplicated transaction: " + transaction.getServiceId());
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Duplicated transaction: " + transaction.getServiceId());
}
return true;
}
}
@@ -844,12 +1069,16 @@ public class TransactionService extends Service implements Observer {
* to defer processing the transaction until
* connectivity is established.
*/
Timber.v("processTransaction: call beginMmsConnectivity...");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("processTransaction: call beginMmsConnectivity...");
}
int connectivityResult = beginMmsConnectivity();
if (connectivityResult == 1) {
mPending.add(transaction);
Timber.v("processTransaction: connResult=APN_REQUEST_STARTED, " +
"defer transaction pending MMS connectivity");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("processTransaction: connResult=APN_REQUEST_STARTED, " +
"defer transaction pending MMS connectivity");
}
return true;
}
// If there is already a transaction in processing list, because of the previous
@@ -858,19 +1087,26 @@ public class TransactionService extends Service implements Observer {
// to the Processing list. But Processing list is never traversed to
// resend, resulting in transaction not completed/sent.
if (mProcessing.size() > 0) {
Timber.v("Adding transaction to 'mPending' list: " + transaction);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Adding transaction to 'mPending' list: " + transaction);
}
mPending.add(transaction);
return true;
} else {
Timber.v("Adding transaction to 'mProcessing' list: " + transaction);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Adding transaction to 'mProcessing' list: " + transaction);
}
mProcessing.add(transaction);
}
}
// Set a timer to keep renewing our "lease" on the MMS connection
sendMessageDelayed(obtainMessage(EVENT_CONTINUE_MMS_CONNECTIVITY), APN_EXTENSION_WAIT);
sendMessageDelayed(obtainMessage(EVENT_CONTINUE_MMS_CONNECTIVITY),
APN_EXTENSION_WAIT);
Timber.v("processTransaction: starting transaction " + transaction);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("processTransaction: starting transaction " + transaction);
}
// Attach to transaction and process it
transaction.attach(TransactionService.this);
@@ -890,7 +1126,9 @@ public class TransactionService extends Service implements Observer {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Timber.w("ConnectivityBroadcastReceiver.onReceive() action: " + action);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.w("ConnectivityBroadcastReceiver.onReceive() action: " + action);
}
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
return;
@@ -901,7 +1139,9 @@ public class TransactionService extends Service implements Observer {
if (mConnMgr != null && Utils.isMobileDataEnabled(context)) {
mmsNetworkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
} else {
Timber.v("mConnMgr is null, bail");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("mConnMgr is null, bail");
}
}
/*
@@ -910,17 +1150,24 @@ public class TransactionService extends Service implements Observer {
* transaction, if any.
*/
Timber.v("Handle ConnectivityBroadcastReceiver.onReceive(): " + mmsNetworkInfo);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("Handle ConnectivityBroadcastReceiver.onReceive(): " + mmsNetworkInfo);
}
// Check availability of the mobile network.
if (mmsNetworkInfo == null) {
Timber.v("mms type is null or mobile data is turned off, bail");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("mms type is null or mobile data is turned off, bail");
}
} else {
// This is a very specific fix to handle the case where the phone receives an
// incoming call during the time we're trying to setup the mms connection.
// When the call ends, restart the process of mms connectivity.
if ("2GVoiceCallEnded".equals(mmsNetworkInfo.getReason())) {
Timber.v(" reason is " + "2GVoiceCallEnded" + ", retrying mms connectivity");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v(" reason is " + "2GVoiceCallEnded" +
", retrying mms connectivity");
}
renewMmsConnectivity();
return;
}
@@ -942,11 +1189,15 @@ public class TransactionService extends Service implements Observer {
}
mServiceHandler.processPendingTransaction(null, settings);
} else {
Timber.v(" TYPE_MOBILE_MMS not connected, bail");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v(" TYPE_MOBILE_MMS not connected, bail");
}
// Retry mms connectivity once it's possible to connect
if (mmsNetworkInfo.isAvailable()) {
Timber.v(" retrying mms connectivity for it's available");
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v(" retrying mms connectivity for it's available");
}
renewMmsConnectivity();
}
}
+109 -13
View File
@@ -20,10 +20,13 @@ import android.content.Context;
import android.net.NetworkUtilsHelper;
import android.provider.Telephony;
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 com.android.mms.MmsConfig;
import com.klinker.android.send_message.Transaction;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import com.android.mms.logs.LogTag;
/**
* Container of transaction settings. Instances of this class are contained
@@ -31,10 +34,25 @@ import timber.log.Timber;
* settings or of the MMS Client.
*/
public class TransactionSettings {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = true;
private static final boolean LOCAL_LOGV = false;
private String mServiceCenter;
private String mProxyAddress;
private int mProxyPort = -1;
private static final String[] APN_PROJECTION = {
Telephony.Carriers.TYPE, // 0
Telephony.Carriers.MMSC, // 1
Telephony.Carriers.MMSPROXY, // 2
Telephony.Carriers.MMSPORT // 3
};
private static final int COLUMN_TYPE = 0;
private static final int COLUMN_MMSC = 1;
private static final int COLUMN_MMSPROXY = 2;
private static final int COLUMN_MMSPORT = 3;
/**
* Constructor that uses the default settings of the MMS Client.
*
@@ -42,27 +60,50 @@ public class TransactionSettings {
*/
public TransactionSettings(Context context, String apnName) {
Timber.v("TransactionSettings: apnName: " + apnName);
if (Transaction.Companion.getSettings() == null) {
Transaction.Companion.setSettings(Utils.getDefaultSendSettings(context));
// String selection = "current" + " IS NOT NULL";
// String[] selectionArgs = null;
// if (!TextUtils.isEmpty(apnName)) {
// selection += " AND " + "apn" + "=?";
// selectionArgs = new String[]{ apnName.trim() };
// }
//
// Cursor cursor;
//
// try {
// cursor = SqliteWrapper.query(context, context.getContentResolver(),
// Telephony.Carriers.CONTENT_URI,
// APN_PROJECTION, selection, selectionArgs, null);
//
// Timber.v("TransactionSettings looking for apn: " + selection + " returned: " +
// (cursor == null ? "null cursor" : (cursor.getCount() + " hits")));
// } catch (SecurityException e) {
// Timber.e("exception thrown", e);
// cursor = null;
// }
//
// if (cursor == null) {
// Timber.e("Apn is not found in Database!");
if (Transaction.settings == null) {
Transaction.settings = Utils.getDefaultSendSettings(context);
}
mServiceCenter = NetworkUtilsHelper.trimV4AddrZeros(Transaction.Companion.getSettings().getMmsc());
mProxyAddress = NetworkUtilsHelper.trimV4AddrZeros(Transaction.Companion.getSettings().getProxy());
mServiceCenter = NetworkUtilsHelper.trimV4AddrZeros(Transaction.settings.getMmsc());
mProxyAddress = NetworkUtilsHelper.trimV4AddrZeros(Transaction.settings.getProxy());
// Set up the agent, profile url and tag name to be used in the mms request if they are attached in settings
String agent = Transaction.Companion.getSettings().getAgent();
String agent = Transaction.settings.getAgent();
if (agent != null && !agent.trim().equals("")) {
MmsConfig.setUserAgent(agent);
Timber.v("set user agent");
}
String uaProfUrl = Transaction.Companion.getSettings().getUserProfileUrl();
String uaProfUrl = Transaction.settings.getUserProfileUrl();
if (uaProfUrl != null && !uaProfUrl.trim().equals("")) {
MmsConfig.setUaProfUrl(uaProfUrl);
Timber.v("set user agent profile url");
}
String uaProfTagName = Transaction.Companion.getSettings().getUaProfTagName();
String uaProfTagName = Transaction.settings.getUaProfTagName();
if (uaProfTagName != null && !uaProfTagName.trim().equals("")) {
MmsConfig.setUaProfTagName(uaProfTagName);
Timber.v("set user agent profile tag name");
@@ -70,11 +111,51 @@ public class TransactionSettings {
if (isProxySet()) {
try {
mProxyPort = Integer.parseInt(Transaction.Companion.getSettings().getPort());
mProxyPort = Integer.parseInt(Transaction.settings.getPort());
} catch (NumberFormatException e) {
Timber.e(e, "could not get proxy: " + Transaction.Companion.getSettings().getPort());
Timber.e("could not get proxy: " + Transaction.settings.getPort(), e);
}
}
// }
// boolean sawValidApn = false;
// try {
// while (cursor.moveToNext() && TextUtils.isEmpty(mServiceCenter)) {
// // Read values from APN settings
// if (isValidApnType(cursor.getString(COLUMN_TYPE), "mms")) {
// sawValidApn = true;
//
// String mmsc = cursor.getString(COLUMN_MMSC);
// if (mmsc == null) {
// continue;
// }
//
// mServiceCenter = NetworkUtils.trimV4AddrZeros(mmsc.trim());
// mProxyAddress = NetworkUtils.trimV4AddrZeros(
// cursor.getString(COLUMN_MMSPROXY));
// if (isProxySet()) {
// String portString = cursor.getString(COLUMN_MMSPORT);
// try {
// mProxyPort = Integer.parseInt(portString);
// } catch (NumberFormatException e) {
// if (TextUtils.isEmpty(portString)) {
// Timber.w("mms port not set!");
// } else {
// Timber.e("Bad port number format: " + portString, e);
// }
// }
// }
// }
// }
// } finally {
// cursor.close();
// }
//
// Timber.v("APN setting: MMSC: " + mServiceCenter + " looked for: " + selection);
//
// if (sawValidApn && TextUtils.isEmpty(mServiceCenter)) {
// Timber.e("Invalid APN setting: MMSC is empty");
// }
}
/**
@@ -91,9 +172,11 @@ public class TransactionSettings {
mProxyAddress = proxyAddr;
mProxyPort = proxyPort;
Timber.v("TransactionSettings: " + mServiceCenter
+ " proxyAddress: " + mProxyAddress
+ " proxyPort: " + mProxyPort);
if (Timber_isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Timber.v("TransactionSettings: " + mServiceCenter +
" proxyAddress: " + mProxyAddress +
" proxyPort: " + mProxyPort);
}
}
public String getMmscUrl() {
@@ -112,4 +195,17 @@ public class TransactionSettings {
return (mProxyAddress != null) && (mProxyAddress.trim().length() != 0);
}
static private boolean isValidApnType(String types, String requestType) {
// If APN type is unspecified, assume APN_TYPE_ALL.
if (TextUtils.isEmpty(types)) {
return true;
}
for (String t : types.split(",")) {
if (t.equals(requestType) || t.equals("*")) {
return true;
}
}
return false;
}
}
+10 -5
View File
@@ -26,7 +26,11 @@ import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import com.android.mms.logs.LogTag;
import timber.log.Timber; import android.util.Log;
import android.widget.Toast;
import com.android.internal.telephony.TelephonyProperties;
import com.android.mms.service_alt.SystemPropertiesProxy;
import com.google.android.mms.MmsException;
@@ -34,10 +38,11 @@ import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.PduPersister;
import com.klinker.android.send_message.R;
import timber.log.Timber;
public class DownloadManager {
private static final boolean LOCAL_LOGV = false;
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = true;
public static final int DEFERRED_MASK = 0x04;
@@ -142,7 +147,7 @@ public class DownloadManager {
return;
}
} catch(MmsException e) {
Timber.e(e, e.getMessage());
Timber.e(e.getMessage(), e);
return;
}
@@ -154,7 +159,7 @@ public class DownloadManager {
Toast.makeText(mContext, getMessage(uri),
Toast.LENGTH_LONG).show();
} catch (MmsException e) {
Timber.e(e, e.getMessage());
Timber.e(e.getMessage(), e);
}
}
});
@@ -177,7 +182,7 @@ public class DownloadManager {
try {
Toast.makeText(mContext, errStr, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Timber.e("Caught an exception in showErrorCodeToast");
Log.e(TAG,"Caught an exception in showErrorCodeToast");
}
}
});
@@ -0,0 +1,36 @@
package com.android.mms.util;
import java.util.concurrent.CopyOnWriteArrayList;
public class ExternalLogger {
private static final CopyOnWriteArrayList<LoggingListener> sListener = new CopyOnWriteArrayList<LoggingListener>();
public interface LoggingListener {
void onLogException(String tag, Throwable e);
void onLogMessage(String tag, String message);
}
private ExternalLogger(){}
public static void addListener(LoggingListener listener) {
sListener.add(listener);
}
public static void removeListener(LoggingListener listener) {
sListener.remove(listener);
}
public static void logException(String tag, Throwable e) {
for (LoggingListener listener: sListener) {
listener.onLogException(tag, e);
}
}
public static void logMessage(String tag, String message) {
for (LoggingListener listener: sListener) {
listener.onLogMessage(tag, message);
}
}
}
+4
View File
@@ -24,9 +24,13 @@ import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.provider.Telephony.Mms.Rate;
import com.android.mms.logs.LogTag;
import timber.log.Timber;
public class RateController {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private static final int RATE_LIMIT = 100;
@@ -16,11 +16,14 @@
package com.android.mms.util;
import timber.log.Timber;
import java.util.HashMap;
import com.android.mms.logs.LogTag;
import timber.log.Timber;
public class SendingProgressTokenManager {
private static final String TAG = LogTag.TAG;
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private static final HashMap<Object, Long> TOKEN_POOL;
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2007 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 com.google.android.collect;
import java.util.*;
/**
* Provides static methods for creating mutable {@code Set} instances easily and
* other static methods for working with Sets.
*/
public class Sets {
/**
* Creates an empty {@code HashSet} instance.
* <p/>
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#noneOf} instead.
* <p/>
* <p><b>Note:</b> if you only need an <i>immutable</i> empty Set,
* use {@link Collections#emptySet} instead.
*
* @return a newly-created, initially-empty {@code HashSet}
*/
public static <K> HashSet<K> newHashSet() {
return new HashSet<K>();
}
/**
* Creates a {@code HashSet} instance containing the given elements.
* <p/>
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
* <p/>
* <p>{@code Set<Base> set = Sets.newHashSet(sub1, sub2);}
* <p/>
* <p>where {@code sub1} and {@code sub2} are references to subtypes of {@code
* Base}, not of {@code Base} itself. To get around this, you must use:
* <p/>
* <p>{@code Set<Base> set = Sets.<Base>newHashSet(sub1, sub2);}
*
* @param elements the elements that the set should contain
* @return a newly-created {@code HashSet} containing those elements (minus
* duplicates)
*/
public static <E> HashSet<E> newHashSet(E... elements) {
int capacity = elements.length * 4 / 3 + 1;
HashSet<E> set = new HashSet<E>(capacity);
Collections.addAll(set, elements);
return set;
}
/**
* Creates an empty {@code SortedSet} instance.
*
* @return a newly-created, initially-empty {@code SortedSet}.
*/
public static <E> SortedSet<E> newSortedSet() {
return new TreeSet<E>();
}
/**
* Creates a {@code SortedSet} instance containing the given elements.
*
* @param elements the elements that the set should contain
* @return a newly-created {@code SortedSet} containing those elements (minus
* duplicates)
*/
public static <E> SortedSet<E> newSortedSet(E... elements) {
SortedSet<E> set = new TreeSet<E>();
Collections.addAll(set, elements);
return set;
}
}
@@ -0,0 +1,17 @@
package com.google.android.mms;
public class APN {
public String MMSCenterUrl = "";
public String MMSPort = "";
public String MMSProxy = "";
public APN(String MMSCenterUrl, String MMSPort, String MMSProxy) {
this.MMSCenterUrl = MMSCenterUrl;
this.MMSPort = MMSPort;
this.MMSProxy = MMSProxy;
}
public APN() {
}
}
@@ -0,0 +1,54 @@
package com.google.android.mms;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class APNHelper {
public APNHelper(final Context context) {
this.context = context;
}
@SuppressWarnings("unchecked")
public List<APN> getMMSApns() {
try {
final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Uri.parse("content://telephony/carriers"), "current"), null, null, null, null);
if (apnCursor == null) {
return Collections.EMPTY_LIST;
} else {
final List<APN> results = new ArrayList<APN>();
if (apnCursor.moveToFirst()) {
do {
final String type = apnCursor.getString(apnCursor.getColumnIndex("type"));
if (!TextUtils.isEmpty(type) && (type.equalsIgnoreCase("*") || type.equalsIgnoreCase("mms"))) {
final String mmsc = apnCursor.getString(apnCursor.getColumnIndex("mmsc"));
final String mmsProxy = apnCursor.getString(apnCursor.getColumnIndex("mmsproxy"));
final String port = apnCursor.getString(apnCursor.getColumnIndex("mmsport"));
final APN apn = new APN();
apn.MMSCenterUrl = mmsc;
apn.MMSProxy = mmsProxy;
apn.MMSPort = port;
results.add(apn);
Toast.makeText(context, mmsc + " " + mmsProxy + " " + port, Toast.LENGTH_LONG).show();
}
} while (apnCursor.moveToNext());
}
apnCursor.close();
return results;
}
} catch (Exception e) {
// insignificant permissions
return Collections.EMPTY_LIST;
}
}
private Context context;
}
View File
@@ -0,0 +1,10 @@
package com.google.android.mms;
import android.net.Uri;
public class MMSPart {
public String Name = "";
public String MimeType = "";
public byte[] Data;
public Uri Path;
}
@@ -1,7 +0,0 @@
package com.google.android.mms
class MMSPart @JvmOverloads constructor(
var name: String = "",
var mimeType: String = "",
var data: ByteArray? = null
)
View File

Some files were not shown because too many files have changed in this diff Show More