aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/thedevstack/conversationsplus/utils
diff options
context:
space:
mode:
authorsteckbrief <steckbrief@chefmail.de>2015-05-03 22:25:46 +0200
committerlookshe <github@lookshe.org>2015-06-19 09:46:40 +0200
commit7382e3af9769f76fe4e19934a59e45a3f9858332 (patch)
treec37cdb03dfaeaccde7c8dd7c79887bf0de278f83 /src/main/java/de/thedevstack/conversationsplus/utils
parentb3b4a2902e37fb072e800f5dff0392755f5d4501 (diff)
renaming eu.siacs.conversations to de.thedevstack.conversationsplus
"renaming eu.siacs.conversations to de.thedevstack.conversationsplus" package renaming completed
Diffstat (limited to 'src/main/java/de/thedevstack/conversationsplus/utils')
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/CryptoHelper.java124
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/DNSHelper.java183
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHandler.java46
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHelper.java119
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/ExifHelper.java161
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/GeoHelper.java71
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/OnPhoneContactsLoadedListener.java9
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/PRNGFixes.java327
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/PhoneHelper.java107
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/UIHelper.java366
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/XmlHelper.java12
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/Xmlns.java8
-rw-r--r--src/main/java/de/thedevstack/conversationsplus/utils/XmppUri.java85
13 files changed, 1618 insertions, 0 deletions
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/CryptoHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/CryptoHelper.java
new file mode 100644
index 00000000..115ac190
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/CryptoHelper.java
@@ -0,0 +1,124 @@
+package de.thedevstack.conversationsplus.utils;
+
+import java.security.SecureRandom;
+import java.text.Normalizer;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+import de.thedevstack.conversationsplus.Config;
+
+public final class CryptoHelper {
+ public static final String FILETRANSFER = "?FILETRANSFERv1:";
+ private final static char[] hexArray = "0123456789abcdef".toCharArray();
+ private final static char[] vowels = "aeiou".toCharArray();
+ private final static char[] consonants = "bcdfghjklmnpqrstvwxyz".toCharArray();
+ final public static byte[] ONE = new byte[] { 0, 0, 0, 1 };
+
+ public static String bytesToHex(byte[] bytes) {
+ char[] hexChars = new char[bytes.length * 2];
+ for (int j = 0; j < bytes.length; j++) {
+ int v = bytes[j] & 0xFF;
+ hexChars[j * 2] = hexArray[v >>> 4];
+ hexChars[j * 2 + 1] = hexArray[v & 0x0F];
+ }
+ return new String(hexChars);
+ }
+
+ public static byte[] hexToBytes(String hexString) {
+ int len = hexString.length();
+ byte[] array = new byte[len / 2];
+ for (int i = 0; i < len; i += 2) {
+ array[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
+ .digit(hexString.charAt(i + 1), 16));
+ }
+ return array;
+ }
+
+ public static String hexToString(final String hexString) {
+ return new String(hexToBytes(hexString));
+ }
+
+ public static byte[] concatenateByteArrays(byte[] a, byte[] b) {
+ byte[] result = new byte[a.length + b.length];
+ System.arraycopy(a, 0, result, 0, a.length);
+ System.arraycopy(b, 0, result, a.length, b.length);
+ return result;
+ }
+
+ public static String randomMucName(SecureRandom random) {
+ return randomWord(3, random) + "." + randomWord(7, random);
+ }
+
+ private static String randomWord(int lenght, SecureRandom random) {
+ StringBuilder builder = new StringBuilder(lenght);
+ for (int i = 0; i < lenght; ++i) {
+ if (i % 2 == 0) {
+ builder.append(consonants[random.nextInt(consonants.length)]);
+ } else {
+ builder.append(vowels[random.nextInt(vowels.length)]);
+ }
+ }
+ return builder.toString();
+ }
+
+ /**
+ * Escapes usernames or passwords for SASL.
+ */
+ public static String saslEscape(final String s) {
+ final StringBuilder sb = new StringBuilder((int) (s.length() * 1.1));
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ switch (c) {
+ case ',':
+ sb.append("=2C");
+ break;
+ case '=':
+ sb.append("=3D");
+ break;
+ default:
+ sb.append(c);
+ break;
+ }
+ }
+ return sb.toString();
+ }
+
+ public static String saslPrep(final String s) {
+ return Normalizer.normalize(s, Normalizer.Form.NFKC);
+ }
+
+ public static String prettifyFingerprint(String fingerprint) {
+ StringBuilder builder = new StringBuilder(fingerprint);
+ builder.insert(8, " ");
+ builder.insert(17, " ");
+ builder.insert(26, " ");
+ builder.insert(35, " ");
+ return builder.toString();
+ }
+
+ public static String[] getOrderedCipherSuites(final String[] platformSupportedCipherSuites) {
+ final Collection<String> cipherSuites = new LinkedHashSet<>(Arrays.asList(Config.ENABLED_CIPHERS));
+ final List<String> platformCiphers = Arrays.asList(platformSupportedCipherSuites);
+ cipherSuites.retainAll(platformCiphers);
+ cipherSuites.addAll(platformCiphers);
+ filterWeakCipherSuites(cipherSuites);
+ return cipherSuites.toArray(new String[cipherSuites.size()]);
+ }
+
+ private static void filterWeakCipherSuites(final Collection<String> cipherSuites) {
+ final Iterator<String> it = cipherSuites.iterator();
+ while (it.hasNext()) {
+ String cipherName = it.next();
+ // remove all ciphers with no or very weak encryption or no authentication
+ for (String weakCipherPattern : Config.WEAK_CIPHER_PATTERNS) {
+ if (cipherName.contains(weakCipherPattern)) {
+ it.remove();
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/DNSHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/DNSHelper.java
new file mode 100644
index 00000000..1eedfdfd
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/DNSHelper.java
@@ -0,0 +1,183 @@
+package de.thedevstack.conversationsplus.utils;
+
+import de.measite.minidns.Client;
+import de.measite.minidns.DNSMessage;
+import de.measite.minidns.Record;
+import de.measite.minidns.Record.TYPE;
+import de.measite.minidns.Record.CLASS;
+import de.measite.minidns.record.SRV;
+import de.measite.minidns.record.A;
+import de.measite.minidns.record.AAAA;
+import de.measite.minidns.record.Data;
+import de.measite.minidns.util.NameUtil;
+import de.thedevstack.conversationsplus.Config;
+import de.thedevstack.conversationsplus.xmpp.jid.Jid;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.SocketTimeoutException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Random;
+import java.util.TreeMap;
+
+import android.os.Bundle;
+import android.util.Log;
+
+public class DNSHelper {
+ protected static Client client = new Client();
+
+ public static Bundle getSRVRecord(final Jid jid) throws IOException {
+ final String host = jid.getDomainpart();
+ String dns[] = client.findDNS();
+
+ if (dns != null) {
+ for (String dnsserver : dns) {
+ InetAddress ip = InetAddress.getByName(dnsserver);
+ Bundle b = queryDNS(host, ip);
+ if (b.containsKey("values")) {
+ return b;
+ } else if (b.containsKey("error")
+ && "nosrv".equals(b.getString("error", null))) {
+ return b;
+ }
+ }
+ }
+ return queryDNS(host, InetAddress.getByName("8.8.8.8"));
+ }
+
+ public static Bundle queryDNS(String host, InetAddress dnsServer) {
+ Bundle bundle = new Bundle();
+ try {
+ String qname = "_xmpp-client._tcp." + host;
+ Log.d(Config.LOGTAG,
+ "using dns server: " + dnsServer.getHostAddress()
+ + " to look up " + host);
+ DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN,
+ dnsServer.getHostAddress());
+
+ // How should we handle priorities and weight?
+ // Wikipedia has a nice article about priorities vs. weights:
+ // https://en.wikipedia.org/wiki/SRV_record#Provisioning_for_high_service_availability
+
+ // we bucket the SRV records based on priority, pick per priority
+ // a random order respecting the weight, and dump that priority by
+ // priority
+
+ TreeMap<Integer, ArrayList<SRV>> priorities = new TreeMap<>();
+ TreeMap<String, ArrayList<String>> ips4 = new TreeMap<>();
+ TreeMap<String, ArrayList<String>> ips6 = new TreeMap<>();
+
+ for (Record[] rrset : new Record[][] { message.getAnswers(),
+ message.getAdditionalResourceRecords() }) {
+ for (Record rr : rrset) {
+ Data d = rr.getPayload();
+ if (d instanceof SRV
+ && NameUtil.idnEquals(qname, rr.getName())) {
+ SRV srv = (SRV) d;
+ if (!priorities.containsKey(srv.getPriority())) {
+ priorities.put(srv.getPriority(),
+ new ArrayList<SRV>(2));
+ }
+ priorities.get(srv.getPriority()).add(srv);
+ }
+ if (d instanceof A) {
+ A arecord = (A) d;
+ if (!ips4.containsKey(rr.getName())) {
+ ips4.put(rr.getName(), new ArrayList<String>(3));
+ }
+ ips4.get(rr.getName()).add(arecord.toString());
+ }
+ if (d instanceof AAAA) {
+ AAAA aaaa = (AAAA) d;
+ if (!ips6.containsKey(rr.getName())) {
+ ips6.put(rr.getName(), new ArrayList<String>(3));
+ }
+ ips6.get(rr.getName()).add("[" + aaaa.toString() + "]");
+ }
+ }
+ }
+
+ Random rnd = new Random();
+ ArrayList<SRV> result = new ArrayList<>(
+ priorities.size() * 2 + 1);
+ for (ArrayList<SRV> s : priorities.values()) {
+
+ // trivial case
+ if (s.size() <= 1) {
+ result.addAll(s);
+ continue;
+ }
+
+ long totalweight = 0l;
+ for (SRV srv : s) {
+ totalweight += srv.getWeight();
+ }
+
+ while (totalweight > 0l && s.size() > 0) {
+ long p = (rnd.nextLong() & 0x7fffffffffffffffl)
+ % totalweight;
+ int i = 0;
+ while (p > 0) {
+ p -= s.get(i++).getPriority();
+ }
+ i--;
+ // remove is expensive, but we have only a few entries
+ // anyway
+ SRV srv = s.remove(i);
+ totalweight -= srv.getWeight();
+ result.add(srv);
+ }
+
+ Collections.shuffle(s, rnd);
+ result.addAll(s);
+
+ }
+
+ if (result.size() == 0) {
+ bundle.putString("error", "nosrv");
+ return bundle;
+ }
+ ArrayList<Bundle> values = new ArrayList<>();
+ for (SRV srv : result) {
+ if (ips6.containsKey(srv.getName())) {
+ values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips6));
+ }
+ if (ips4.containsKey(srv.getName())) {
+ values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips4));
+ }
+ values.add(createNamePortBundle(srv.getName(),srv.getPort(),null));
+ }
+ bundle.putParcelableArrayList("values", values);
+ } catch (SocketTimeoutException e) {
+ bundle.putString("error", "timeout");
+ } catch (Exception e) {
+ bundle.putString("error", "unhandled");
+ }
+ return bundle;
+ }
+
+ private static Bundle createNamePortBundle(String name, int port, TreeMap<String, ArrayList<String>> ips) {
+ Bundle namePort = new Bundle();
+ namePort.putString("name", name);
+ namePort.putInt("port", port);
+ if (ips!=null) {
+ ArrayList<String> ip = ips.get(name);
+ Collections.shuffle(ip, new Random());
+ namePort.putString("ip", ip.get(0));
+ }
+ return namePort;
+ }
+
+ final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
+
+ public static String bytesToHex(byte[] bytes) {
+ char[] hexChars = new char[bytes.length * 2];
+ for (int j = 0; j < bytes.length; j++) {
+ int v = bytes[j] & 0xFF;
+ hexChars[j * 2] = hexArray[v >>> 4];
+ hexChars[j * 2 + 1] = hexArray[v & 0x0F];
+ }
+ return new String(hexChars);
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHandler.java b/src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHandler.java
new file mode 100644
index 00000000..256287f1
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHandler.java
@@ -0,0 +1,46 @@
+package de.thedevstack.conversationsplus.utils;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.Thread.UncaughtExceptionHandler;
+
+import android.content.Context;
+
+public class ExceptionHandler implements UncaughtExceptionHandler {
+
+ private UncaughtExceptionHandler defaultHandler;
+ private Context context;
+
+ public ExceptionHandler(Context context) {
+ this.context = context;
+ this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
+ }
+
+ @Override
+ public void uncaughtException(Thread thread, Throwable ex) {
+ Writer result = new StringWriter();
+ PrintWriter printWriter = new PrintWriter(result);
+ ex.printStackTrace(printWriter);
+ String stacktrace = result.toString();
+ printWriter.close();
+ try {
+ OutputStream os = context.openFileOutput("stacktrace.txt",
+ Context.MODE_PRIVATE);
+ os.write(stacktrace.getBytes());
+ os.flush();
+ os.close();
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ this.defaultHandler.uncaughtException(thread, ex);
+ }
+
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHelper.java
new file mode 100644
index 00000000..492c65d2
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/ExceptionHelper.java
@@ -0,0 +1,119 @@
+package de.thedevstack.conversationsplus.utils;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.List;
+
+import de.thedevstack.conversationsplus.Config;
+import de.thedevstack.conversationsplus.R;
+import de.thedevstack.conversationsplus.entities.Account;
+import de.thedevstack.conversationsplus.entities.Conversation;
+import de.thedevstack.conversationsplus.entities.Message;
+import de.thedevstack.conversationsplus.services.XmppConnectionService;
+import de.thedevstack.conversationsplus.xmpp.jid.InvalidJidException;
+import de.thedevstack.conversationsplus.xmpp.jid.Jid;
+
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.SharedPreferences;
+import android.content.DialogInterface.OnClickListener;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.preference.PreferenceManager;
+import android.text.format.DateUtils;
+import android.util.Log;
+
+public class ExceptionHelper {
+ public static void init(Context context) {
+ if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof ExceptionHandler)) {
+ Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(
+ context));
+ }
+ }
+
+ public static void checkForCrash(Context context,
+ final XmppConnectionService service) {
+ try {
+ final SharedPreferences preferences = PreferenceManager
+ .getDefaultSharedPreferences(context);
+ boolean neverSend = preferences.getBoolean("never_send", false);
+ if (neverSend) {
+ return;
+ }
+ List<Account> accounts = service.getAccounts();
+ Account account = null;
+ for (int i = 0; i < accounts.size(); ++i) {
+ if (!accounts.get(i).isOptionSet(Account.OPTION_DISABLED)) {
+ account = accounts.get(i);
+ break;
+ }
+ }
+ if (account == null) {
+ return;
+ }
+ final Account finalAccount = account;
+ FileInputStream file = context.openFileInput("stacktrace.txt");
+ InputStreamReader inputStreamReader = new InputStreamReader(file);
+ BufferedReader stacktrace = new BufferedReader(inputStreamReader);
+ final StringBuilder report = new StringBuilder();
+ PackageManager pm = context.getPackageManager();
+ PackageInfo packageInfo = null;
+ try {
+ packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
+ report.append("Version: " + packageInfo.versionName + '\n');
+ report.append("Last Update: "
+ + DateUtils.formatDateTime(context,
+ packageInfo.lastUpdateTime,
+ DateUtils.FORMAT_SHOW_TIME
+ | DateUtils.FORMAT_SHOW_DATE) + '\n');
+ } catch (NameNotFoundException e) {
+ }
+ String line;
+ while ((line = stacktrace.readLine()) != null) {
+ report.append(line);
+ report.append('\n');
+ }
+ file.close();
+ context.deleteFile("stacktrace.txt");
+ AlertDialog.Builder builder = new AlertDialog.Builder(context);
+ builder.setTitle(context.getString(R.string.crash_report_title));
+ builder.setMessage(context.getText(R.string.crash_report_message));
+ builder.setPositiveButton(context.getText(R.string.send_now),
+ new OnClickListener() {
+
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+
+ Log.d(Config.LOGTAG, "using account="
+ + finalAccount.getJid().toBareJid()
+ + " to send in stack trace");
+ Conversation conversation = null;
+ try {
+ conversation = service.findOrCreateConversation(finalAccount,
+ Jid.fromString("bugs@siacs.eu"), false);
+ } catch (final InvalidJidException ignored) {
+ }
+ Message message = new Message(conversation, report
+ .toString(), Message.ENCRYPTION_NONE);
+ service.sendMessage(message);
+ }
+ });
+ builder.setNegativeButton(context.getText(R.string.send_never),
+ new OnClickListener() {
+
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ preferences.edit().putBoolean("never_send", true)
+ .apply();
+ }
+ });
+ builder.create().show();
+ } catch (final IOException ignored) {
+ }
+
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/ExifHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/ExifHelper.java
new file mode 100644
index 00000000..13aff60d
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/ExifHelper.java
@@ -0,0 +1,161 @@
+/*
+ * 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 de.thedevstack.conversationsplus.utils;
+
+import android.util.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+public class ExifHelper {
+ private static final String TAG = "CameraExif";
+
+ public static int getOrientation(InputStream is) {
+ if (is == null) {
+ return 0;
+ }
+
+ byte[] buf = new byte[8];
+ int length = 0;
+
+ // ISO/IEC 10918-1:1993(E)
+ while (read(is, buf, 2) && (buf[0] & 0xFF) == 0xFF) {
+ int marker = buf[1] & 0xFF;
+
+ // Check if the marker is a padding.
+ if (marker == 0xFF) {
+ continue;
+ }
+
+ // Check if the marker is SOI or TEM.
+ if (marker == 0xD8 || marker == 0x01) {
+ continue;
+ }
+ // Check if the marker is EOI or SOS.
+ if (marker == 0xD9 || marker == 0xDA) {
+ return 0;
+ }
+
+ // Get the length and check if it is reasonable.
+ if (!read(is, buf, 2)) {
+ return 0;
+ }
+ length = pack(buf, 0, 2, false);
+ if (length < 2) {
+ Log.e(TAG, "Invalid length");
+ return 0;
+ }
+ length -= 2;
+
+ // Break if the marker is EXIF in APP1.
+ if (marker == 0xE1 && length >= 6) {
+ if (!read(is, buf, 6)) return 0;
+ length -= 6;
+ if (pack(buf, 0, 4, false) == 0x45786966 &&
+ pack(buf, 4, 2, false) == 0) {
+ break;
+ }
+ }
+
+ // Skip other markers.
+ try {
+ is.skip(length);
+ } catch (IOException ex) {
+ return 0;
+ }
+ length = 0;
+ }
+
+ // JEITA CP-3451 Exif Version 2.2
+ if (length > 8) {
+ int offset = 0;
+ byte[] jpeg = new byte[length];
+ if (!read(is, jpeg, length)) {
+ return 0;
+ }
+
+ // Identify the byte order.
+ int tag = pack(jpeg, offset, 4, false);
+ if (tag != 0x49492A00 && tag != 0x4D4D002A) {
+ Log.e(TAG, "Invalid byte order");
+ return 0;
+ }
+ boolean littleEndian = (tag == 0x49492A00);
+
+ // Get the offset and check if it is reasonable.
+ int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
+ if (count < 10 || count > length) {
+ Log.e(TAG, "Invalid offset");
+ return 0;
+ }
+ offset += count;
+ length -= count;
+
+ // Get the count and go through all the elements.
+ count = pack(jpeg, offset - 2, 2, littleEndian);
+ while (count-- > 0 && length >= 12) {
+ // Get the tag and check if it is orientation.
+ tag = pack(jpeg, offset, 2, littleEndian);
+ if (tag == 0x0112) {
+ // We do not really care about type and count, do we?
+ int orientation = pack(jpeg, offset + 8, 2, littleEndian);
+ switch (orientation) {
+ case 1:
+ return 0;
+ case 3:
+ return 180;
+ case 6:
+ return 90;
+ case 8:
+ return 270;
+ }
+ Log.i(TAG, "Unsupported orientation");
+ return 0;
+ }
+ offset += 12;
+ length -= 12;
+ }
+ }
+
+ Log.i(TAG, "Orientation not found");
+ return 0;
+ }
+
+ private static int pack(byte[] bytes, int offset, int length,
+ boolean littleEndian) {
+ int step = 1;
+ if (littleEndian) {
+ offset += length - 1;
+ step = -1;
+ }
+
+ int value = 0;
+ while (length-- > 0) {
+ value = (value << 8) | (bytes[offset] & 0xFF);
+ offset += step;
+ }
+ return value;
+ }
+
+ private static boolean read(InputStream is, byte[] buf, int length) {
+ try {
+ return is.read(buf, 0, length) == length;
+ } catch (IOException ex) {
+ return false;
+ }
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/GeoHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/GeoHelper.java
new file mode 100644
index 00000000..87c16f8c
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/GeoHelper.java
@@ -0,0 +1,71 @@
+package de.thedevstack.conversationsplus.utils;
+
+import android.content.Intent;
+import android.net.Uri;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import de.thedevstack.conversationsplus.entities.Conversation;
+import de.thedevstack.conversationsplus.entities.Message;
+
+public class GeoHelper {
+ private static Pattern GEO_URI = Pattern.compile("geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?", Pattern.CASE_INSENSITIVE);
+
+ public static boolean isGeoUri(String body) {
+ return body != null && GEO_URI.matcher(body).matches();
+ }
+
+ public static ArrayList<Intent> createGeoIntentsFromMessage(Message message) {
+ final ArrayList<Intent> intents = new ArrayList();
+ Matcher matcher = GEO_URI.matcher(message.getBody());
+ if (!matcher.matches()) {
+ return intents;
+ }
+ double latitude;
+ double longitude;
+ try {
+ latitude = Double.parseDouble(matcher.group(1));
+ if (latitude > 90.0 || latitude < -90.0) {
+ return intents;
+ }
+ longitude = Double.parseDouble(matcher.group(2));
+ if (longitude > 180.0 || longitude < -180.0) {
+ return intents;
+ }
+ } catch (NumberFormatException nfe) {
+ return intents;
+ }
+ final Conversation conversation = message.getConversation();
+ String label;
+ if (conversation.getMode() == Conversation.MODE_SINGLE && message.getStatus() == Message.STATUS_RECEIVED) {
+ try {
+ label = "(" + URLEncoder.encode(message.getConversation().getName(), "UTF-8") + ")";
+ } catch (UnsupportedEncodingException e) {
+ label = "";
+ }
+ } else {
+ label = "";
+ }
+
+ Intent locationPluginIntent = new Intent("eu.siacs.conversations.location.show");
+ locationPluginIntent.putExtra("latitude",latitude);
+ locationPluginIntent.putExtra("longitude",longitude);
+ if (conversation.getMode() == Conversation.MODE_SINGLE && message.getStatus() == Message.STATUS_RECEIVED) {
+ locationPluginIntent.putExtra("name",conversation.getName());
+ }
+ intents.add(locationPluginIntent);
+
+ Intent geoIntent = new Intent(Intent.ACTION_VIEW);
+ geoIntent.setData(Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude) + "?q=" + String.valueOf(latitude) + "," + String.valueOf(longitude) + label));
+ intents.add(geoIntent);
+
+ Intent httpIntent = new Intent(Intent.ACTION_VIEW);
+ httpIntent.setData(Uri.parse("https://maps.google.com/maps?q=loc:"+String.valueOf(latitude) + "," + String.valueOf(longitude) +label));
+ intents.add(httpIntent);
+ return intents;
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/OnPhoneContactsLoadedListener.java b/src/main/java/de/thedevstack/conversationsplus/utils/OnPhoneContactsLoadedListener.java
new file mode 100644
index 00000000..e701d62b
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/OnPhoneContactsLoadedListener.java
@@ -0,0 +1,9 @@
+package de.thedevstack.conversationsplus.utils;
+
+import java.util.List;
+
+import android.os.Bundle;
+
+public interface OnPhoneContactsLoadedListener {
+ public void onPhoneContactsLoaded(List<Bundle> phoneContacts);
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/PRNGFixes.java b/src/main/java/de/thedevstack/conversationsplus/utils/PRNGFixes.java
new file mode 100644
index 00000000..78776aeb
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/PRNGFixes.java
@@ -0,0 +1,327 @@
+package de.thedevstack.conversationsplus.utils;
+
+import android.os.Build;
+import android.os.Process;
+import android.util.Log;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.SecureRandomSpi;
+import java.security.Security;
+
+/**
+ * Fixes for the output of the default PRNG having low entropy.
+ *
+ * The fixes need to be applied via {@link #apply()} before any use of Java
+ * Cryptography Architecture primitives. A good place to invoke them is in the
+ * application's {@code onCreate}.
+ */
+public final class PRNGFixes {
+
+ private static final int VERSION_CODE_JELLY_BEAN = 16;
+ private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18;
+ private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = getBuildFingerprintAndDeviceSerial();
+
+ /** Hidden constructor to prevent instantiation. */
+ private PRNGFixes() {
+ }
+
+ /**
+ * Applies all fixes.
+ *
+ * @throws SecurityException
+ * if a fix is needed but could not be applied.
+ */
+ public static void apply() {
+ applyOpenSSLFix();
+ installLinuxPRNGSecureRandom();
+ }
+
+ /**
+ * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the
+ * fix is not needed.
+ *
+ * @throws SecurityException
+ * if the fix is needed but could not be applied.
+ */
+ private static void applyOpenSSLFix() throws SecurityException {
+ if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN)
+ || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) {
+ // No need to apply the fix
+ return;
+ }
+
+ try {
+ // Mix in the device- and invocation-specific seed.
+ Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
+ .getMethod("RAND_seed", byte[].class)
+ .invoke(null, generateSeed());
+
+ // Mix output of Linux PRNG into OpenSSL's PRNG
+ int bytesRead = (Integer) Class
+ .forName(
+ "org.apache.harmony.xnet.provider.jsse.NativeCrypto")
+ .getMethod("RAND_load_file", String.class, long.class)
+ .invoke(null, "/dev/urandom", 1024);
+ if (bytesRead != 1024) {
+ throw new IOException(
+ "Unexpected number of bytes read from Linux PRNG: "
+ + bytesRead);
+ }
+ } catch (Exception e) {
+ throw new SecurityException("Failed to seed OpenSSL PRNG", e);
+ }
+ }
+
+ /**
+ * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the
+ * default. Does nothing if the implementation is already the default or if
+ * there is not need to install the implementation.
+ *
+ * @throws SecurityException
+ * if the fix is needed but could not be applied.
+ */
+ private static void installLinuxPRNGSecureRandom() throws SecurityException {
+ if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) {
+ // No need to apply the fix
+ return;
+ }
+
+ // Install a Linux PRNG-based SecureRandom implementation as the
+ // default, if not yet installed.
+ Provider[] secureRandomProviders = Security
+ .getProviders("SecureRandom.SHA1PRNG");
+ if ((secureRandomProviders == null)
+ || (secureRandomProviders.length < 1)
+ || (!LinuxPRNGSecureRandomProvider.class
+ .equals(secureRandomProviders[0].getClass()))) {
+ Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
+ }
+
+ // Assert that new SecureRandom() and
+ // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
+ // by the Linux PRNG-based SecureRandom implementation.
+ SecureRandom rng1 = new SecureRandom();
+ if (!LinuxPRNGSecureRandomProvider.class.equals(rng1.getProvider()
+ .getClass())) {
+ throw new SecurityException(
+ "new SecureRandom() backed by wrong Provider: "
+ + rng1.getProvider().getClass());
+ }
+
+ SecureRandom rng2;
+ try {
+ rng2 = SecureRandom.getInstance("SHA1PRNG");
+ } catch (NoSuchAlgorithmException e) {
+ throw new SecurityException("SHA1PRNG not available", e);
+ }
+ if (!LinuxPRNGSecureRandomProvider.class.equals(rng2.getProvider()
+ .getClass())) {
+ throw new SecurityException(
+ "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
+ + " Provider: " + rng2.getProvider().getClass());
+ }
+ }
+
+ /**
+ * {@code Provider} of {@code SecureRandom} engines which pass through all
+ * requests to the Linux PRNG.
+ */
+ private static class LinuxPRNGSecureRandomProvider extends Provider {
+
+ public LinuxPRNGSecureRandomProvider() {
+ super("LinuxPRNG", 1.0,
+ "A Linux-specific random number provider that uses"
+ + " /dev/urandom");
+ // Although /dev/urandom is not a SHA-1 PRNG, some apps
+ // explicitly request a SHA1PRNG SecureRandom and we thus need to
+ // prevent them from getting the default implementation whose output
+ // may have low entropy.
+ put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName());
+ put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
+ }
+ }
+
+ /**
+ * {@link SecureRandomSpi} which passes all requests to the Linux PRNG (
+ * {@code /dev/urandom}).
+ */
+ public static class LinuxPRNGSecureRandom extends SecureRandomSpi {
+
+ /*
+ * IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed
+ * are passed through to the Linux PRNG (/dev/urandom). Instances of
+ * this class seed themselves by mixing in the current time, PID, UID,
+ * build fingerprint, and hardware serial number (where available) into
+ * Linux PRNG.
+ *
+ * Concurrency: Read requests to the underlying Linux PRNG are
+ * serialized (on sLock) to ensure that multiple threads do not get
+ * duplicated PRNG output.
+ */
+
+ private static final File URANDOM_FILE = new File("/dev/urandom");
+
+ private static final Object sLock = new Object();
+
+ /**
+ * Input stream for reading from Linux PRNG or {@code null} if not yet
+ * opened.
+ *
+ * @GuardedBy("sLock")
+ */
+ private static DataInputStream sUrandomIn;
+
+ /**
+ * Output stream for writing to Linux PRNG or {@code null} if not yet
+ * opened.
+ *
+ * @GuardedBy("sLock")
+ */
+ private static OutputStream sUrandomOut;
+
+ /**
+ * Whether this engine instance has been seeded. This is needed because
+ * each instance needs to seed itself if the client does not explicitly
+ * seed it.
+ */
+ private boolean mSeeded;
+
+ @Override
+ protected void engineSetSeed(byte[] bytes) {
+ try {
+ OutputStream out;
+ synchronized (sLock) {
+ out = getUrandomOutputStream();
+ }
+ out.write(bytes);
+ out.flush();
+ } catch (IOException e) {
+ // On a small fraction of devices /dev/urandom is not writable.
+ // Log and ignore.
+ Log.w(PRNGFixes.class.getSimpleName(),
+ "Failed to mix seed into " + URANDOM_FILE);
+ } finally {
+ mSeeded = true;
+ }
+ }
+
+ @Override
+ protected void engineNextBytes(byte[] bytes) {
+ if (!mSeeded) {
+ // Mix in the device- and invocation-specific seed.
+ engineSetSeed(generateSeed());
+ }
+
+ try {
+ DataInputStream in;
+ synchronized (sLock) {
+ in = getUrandomInputStream();
+ }
+ synchronized (in) {
+ in.readFully(bytes);
+ }
+ } catch (IOException e) {
+ throw new SecurityException("Failed to read from "
+ + URANDOM_FILE, e);
+ }
+ }
+
+ @Override
+ protected byte[] engineGenerateSeed(int size) {
+ byte[] seed = new byte[size];
+ engineNextBytes(seed);
+ return seed;
+ }
+
+ private DataInputStream getUrandomInputStream() {
+ synchronized (sLock) {
+ if (sUrandomIn == null) {
+ // NOTE: Consider inserting a BufferedInputStream between
+ // DataInputStream and FileInputStream if you need higher
+ // PRNG output performance and can live with future PRNG
+ // output being pulled into this process prematurely.
+ try {
+ sUrandomIn = new DataInputStream(new FileInputStream(
+ URANDOM_FILE));
+ } catch (IOException e) {
+ throw new SecurityException("Failed to open "
+ + URANDOM_FILE + " for reading", e);
+ }
+ }
+ return sUrandomIn;
+ }
+ }
+
+ private OutputStream getUrandomOutputStream() throws IOException {
+ synchronized (sLock) {
+ if (sUrandomOut == null) {
+ sUrandomOut = new FileOutputStream(URANDOM_FILE);
+ }
+ return sUrandomOut;
+ }
+ }
+ }
+
+ /**
+ * Generates a device- and invocation-specific seed to be mixed into the
+ * Linux PRNG.
+ */
+ private static byte[] generateSeed() {
+ try {
+ ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
+ DataOutputStream seedBufferOut = new DataOutputStream(seedBuffer);
+ seedBufferOut.writeLong(System.currentTimeMillis());
+ seedBufferOut.writeLong(System.nanoTime());
+ seedBufferOut.writeInt(Process.myPid());
+ seedBufferOut.writeInt(Process.myUid());
+ seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
+ seedBufferOut.close();
+ return seedBuffer.toByteArray();
+ } catch (IOException e) {
+ throw new SecurityException("Failed to generate seed", e);
+ }
+ }
+
+ /**
+ * Gets the hardware serial number of this device.
+ *
+ * @return serial number or {@code null} if not available.
+ */
+ private static String getDeviceSerialNumber() {
+ // We're using the Reflection API because Build.SERIAL is only available
+ // since API Level 9 (Gingerbread, Android 2.3).
+ try {
+ return (String) Build.class.getField("SERIAL").get(null);
+ } catch (Exception ignored) {
+ return null;
+ }
+ }
+
+ private static byte[] getBuildFingerprintAndDeviceSerial() {
+ StringBuilder result = new StringBuilder();
+ String fingerprint = Build.FINGERPRINT;
+ if (fingerprint != null) {
+ result.append(fingerprint);
+ }
+ String serial = getDeviceSerialNumber();
+ if (serial != null) {
+ result.append(serial);
+ }
+ try {
+ return result.toString().getBytes("UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException("UTF-8 encoding not supported");
+ }
+ }
+} \ No newline at end of file
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/PhoneHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/PhoneHelper.java
new file mode 100644
index 00000000..b49e2183
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/PhoneHelper.java
@@ -0,0 +1,107 @@
+package de.thedevstack.conversationsplus.utils;
+
+import java.util.List;
+import java.util.concurrent.RejectedExecutionException;
+
+import android.content.Context;
+import android.content.CursorLoader;
+import android.content.Loader;
+import android.content.Loader.OnLoadCompleteListener;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Bundle;
+import android.provider.ContactsContract;
+import android.provider.ContactsContract.Profile;
+
+public class PhoneHelper {
+
+ public static void loadPhoneContacts(Context context,final List<Bundle> phoneContacts, final OnPhoneContactsLoadedListener listener) {
+ final String[] PROJECTION = new String[] { ContactsContract.Data._ID,
+ ContactsContract.Data.DISPLAY_NAME,
+ ContactsContract.Data.PHOTO_URI,
+ ContactsContract.Data.LOOKUP_KEY,
+ ContactsContract.CommonDataKinds.Im.DATA };
+
+ final String SELECTION = "(" + ContactsContract.Data.MIMETYPE + "=\""
+ + ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE
+ + "\") AND (" + ContactsContract.CommonDataKinds.Im.PROTOCOL
+ + "=\"" + ContactsContract.CommonDataKinds.Im.PROTOCOL_JABBER
+ + "\")";
+
+ CursorLoader mCursorLoader = new CursorLoader(context,
+ ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION, null,
+ null);
+ mCursorLoader.registerListener(0, new OnLoadCompleteListener<Cursor>() {
+
+ @Override
+ public void onLoadComplete(Loader<Cursor> arg0, Cursor cursor) {
+ if (cursor == null) {
+ return;
+ }
+ while (cursor.moveToNext()) {
+ Bundle contact = new Bundle();
+ contact.putInt("phoneid", cursor.getInt(cursor
+ .getColumnIndex(ContactsContract.Data._ID)));
+ contact.putString(
+ "displayname",
+ cursor.getString(cursor
+ .getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));
+ contact.putString("photouri", cursor.getString(cursor
+ .getColumnIndex(ContactsContract.Data.PHOTO_URI)));
+ contact.putString("lookup", cursor.getString(cursor
+ .getColumnIndex(ContactsContract.Data.LOOKUP_KEY)));
+
+ contact.putString(
+ "jid",
+ cursor.getString(cursor
+ .getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA)));
+ phoneContacts.add(contact);
+ }
+ if (listener != null) {
+ listener.onPhoneContactsLoaded(phoneContacts);
+ }
+ cursor.close();
+ }
+ });
+ try {
+ mCursorLoader.startLoading();
+ } catch (RejectedExecutionException e) {
+ if (listener != null) {
+ listener.onPhoneContactsLoaded(phoneContacts);
+ }
+ }
+ }
+
+ public static Uri getSefliUri(Context context) {
+ String[] mProjection = new String[] { Profile._ID, Profile.PHOTO_URI };
+ Cursor mProfileCursor = context.getContentResolver().query(
+ Profile.CONTENT_URI, mProjection, null, null, null);
+
+ if (mProfileCursor == null || mProfileCursor.getCount() == 0) {
+ return null;
+ } else {
+ mProfileCursor.moveToFirst();
+ String uri = mProfileCursor.getString(1);
+ mProfileCursor.close();
+ if (uri == null) {
+ return null;
+ } else {
+ return Uri.parse(uri);
+ }
+ }
+ }
+
+ public static String getVersionName(Context context) {
+ final String packageName = context == null ? null : context.getPackageName();
+ if (packageName != null) {
+ try {
+ return context.getPackageManager().getPackageInfo(packageName, 0).versionName;
+ } catch (final PackageManager.NameNotFoundException e) {
+ return "unknown";
+ }
+ } else {
+ return "unknown";
+ }
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/UIHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/UIHelper.java
new file mode 100644
index 00000000..bda3f770
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/UIHelper.java
@@ -0,0 +1,366 @@
+package de.thedevstack.conversationsplus.utils;
+
+import java.net.URLConnection;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+
+import de.thedevstack.conversationsplus.Config;
+import de.thedevstack.conversationsplus.R;
+import de.thedevstack.conversationsplus.entities.Contact;
+import de.thedevstack.conversationsplus.entities.Conversation;
+import de.thedevstack.conversationsplus.entities.Downloadable;
+import de.thedevstack.conversationsplus.entities.Message;
+import de.thedevstack.conversationsplus.xmpp.jid.Jid;
+
+import android.content.Context;
+import android.text.format.DateFormat;
+import android.text.format.DateUtils;
+import android.text.Spannable.Factory;
+import android.text.style.ImageSpan;
+import android.text.Spannable;
+import android.util.Pair;
+
+public class UIHelper {
+ private static final int SHORT_DATE_FLAGS = DateUtils.FORMAT_SHOW_DATE
+ | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
+ private static final int FULL_DATE_FLAGS = DateUtils.FORMAT_SHOW_TIME
+ | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE;
+
+ public static String readableTimeDifference(Context context, long time) {
+ return readableTimeDifference(context, time, false);
+ }
+
+ public static String readableTimeDifferenceFull(Context context, long time) {
+ return readableTimeDifference(context, time, true);
+ }
+
+ private static String readableTimeDifference(Context context, long time,
+ boolean fullDate) {
+ if (time == 0) {
+ return context.getString(R.string.just_now);
+ }
+ Date date = new Date(time);
+ long difference = (System.currentTimeMillis() - time) / 1000;
+ if (difference < 60) {
+ return context.getString(R.string.just_now);
+ } else if (difference < 60 * 2) {
+ return context.getString(R.string.minute_ago);
+ } else if (difference < 60 * 15) {
+ return context.getString(R.string.minutes_ago,
+ Math.round(difference / 60.0));
+ } else if (today(date)) {
+ java.text.DateFormat df = DateFormat.getTimeFormat(context);
+ return df.format(date);
+ } else {
+ if (fullDate) {
+ return DateUtils.formatDateTime(context, date.getTime(),
+ FULL_DATE_FLAGS);
+ } else {
+ return DateUtils.formatDateTime(context, date.getTime(),
+ SHORT_DATE_FLAGS);
+ }
+ }
+ }
+
+ private static boolean today(Date date) {
+ return sameDay(date,new Date(System.currentTimeMillis()));
+ }
+
+ public static boolean sameDay(long timestamp1, long timestamp2) {
+ return sameDay(new Date(timestamp1),new Date(timestamp2));
+ }
+
+ private static boolean sameDay(Date a, Date b) {
+ Calendar cal1 = Calendar.getInstance();
+ Calendar cal2 = Calendar.getInstance();
+ cal1.setTime(a);
+ cal2.setTime(b);
+ return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
+ && cal1.get(Calendar.DAY_OF_YEAR) == cal2
+ .get(Calendar.DAY_OF_YEAR);
+ }
+
+ public static String lastseen(Context context, long time) {
+ if (time == 0) {
+ return context.getString(R.string.never_seen);
+ }
+ long difference = (System.currentTimeMillis() - time) / 1000;
+ if (difference < 60) {
+ return context.getString(R.string.last_seen_now);
+ } else if (difference < 60 * 2) {
+ return context.getString(R.string.last_seen_min);
+ } else if (difference < 60 * 60) {
+ return context.getString(R.string.last_seen_mins,
+ Math.round(difference / 60.0));
+ } else if (difference < 60 * 60 * 2) {
+ return context.getString(R.string.last_seen_hour);
+ } else if (difference < 60 * 60 * 24) {
+ return context.getString(R.string.last_seen_hours,
+ Math.round(difference / (60.0 * 60.0)));
+ } else if (difference < 60 * 60 * 48) {
+ return context.getString(R.string.last_seen_day);
+ } else {
+ return context.getString(R.string.last_seen_days,
+ Math.round(difference / (60.0 * 60.0 * 24.0)));
+ }
+ }
+
+ public static final Map<Pattern, Integer> ANDROID_EMOTICONS = new HashMap<Pattern, Integer>();
+
+ private static final Factory spannableFactory = Spannable.Factory
+ .getInstance();
+
+ static {
+ addPattern(ANDROID_EMOTICONS, ":)", R.drawable.emo_im_happy);
+ addPattern(ANDROID_EMOTICONS, ":-)", R.drawable.emo_im_happy);
+ addPattern(ANDROID_EMOTICONS, ":(", R.drawable.emo_im_sad);
+ addPattern(ANDROID_EMOTICONS, ":-(", R.drawable.emo_im_sad);
+ addPattern(ANDROID_EMOTICONS, ";)", R.drawable.emo_im_winking);
+ addPattern(ANDROID_EMOTICONS, ";-)", R.drawable.emo_im_winking);
+ addPattern(ANDROID_EMOTICONS, ":P",
+ R.drawable.emo_im_tongue_sticking_out);
+ addPattern(ANDROID_EMOTICONS, ":-P",
+ R.drawable.emo_im_tongue_sticking_out);
+ addPattern(ANDROID_EMOTICONS, "=-O", R.drawable.emo_im_surprised);
+ addPattern(ANDROID_EMOTICONS, ":*", R.drawable.emo_im_kissing);
+ addPattern(ANDROID_EMOTICONS, ":-*", R.drawable.emo_im_kissing);
+ addPattern(ANDROID_EMOTICONS, ":O", R.drawable.emo_im_wtf);
+ addPattern(ANDROID_EMOTICONS, ":-O", R.drawable.emo_im_wtf);
+ addPattern(ANDROID_EMOTICONS, "B)", R.drawable.emo_im_cool);
+ addPattern(ANDROID_EMOTICONS, "B-)", R.drawable.emo_im_cool);
+ addPattern(ANDROID_EMOTICONS, "8)", R.drawable.emo_im_cool);
+ addPattern(ANDROID_EMOTICONS, "8-)", R.drawable.emo_im_cool);
+ addPattern(ANDROID_EMOTICONS, ":$", R.drawable.emo_im_money_mouth);
+ addPattern(ANDROID_EMOTICONS, ":-$", R.drawable.emo_im_money_mouth);
+ addPattern(ANDROID_EMOTICONS, ":-!", R.drawable.emo_im_foot_in_mouth);
+ addPattern(ANDROID_EMOTICONS, ":-[", R.drawable.emo_im_embarrassed);
+ addPattern(ANDROID_EMOTICONS, "O:)", R.drawable.emo_im_angel);
+ addPattern(ANDROID_EMOTICONS, "O:-)", R.drawable.emo_im_angel);
+ addPattern(ANDROID_EMOTICONS, ":\\", R.drawable.emo_im_undecided);
+ addPattern(ANDROID_EMOTICONS, ":-\\", R.drawable.emo_im_undecided);
+ addPattern(ANDROID_EMOTICONS, ":'(", R.drawable.emo_im_crying);
+ addPattern(ANDROID_EMOTICONS, ":D", R.drawable.emo_im_laughing);
+ addPattern(ANDROID_EMOTICONS, ":-D", R.drawable.emo_im_laughing);
+ addPattern(ANDROID_EMOTICONS, "O_o", R.drawable.emo_im_wtf);
+ addPattern(ANDROID_EMOTICONS, "o_O", R.drawable.emo_im_wtf);
+ addPattern(ANDROID_EMOTICONS, ">:O", R.drawable.emo_im_yelling);
+ addPattern(ANDROID_EMOTICONS, ">:0", R.drawable.emo_im_yelling);
+ addPattern(ANDROID_EMOTICONS, ":S", R.drawable.emo_im_lips_are_sealed);
+ addPattern(ANDROID_EMOTICONS, ":-S", R.drawable.emo_im_lips_are_sealed);
+ addPattern(ANDROID_EMOTICONS, "<3", R.drawable.emo_im_heart);
+ }
+
+ private static void addPattern(Map<Pattern, Integer> map, String smile,
+ int resource) {
+ map.put(Pattern.compile(Pattern.quote(smile)), resource);
+ }
+
+ private static boolean getSmiledText(Context context, Spannable spannable) {
+ boolean hasChanges = false;
+ Map<Pattern, Integer> emoticons = ANDROID_EMOTICONS;
+ for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
+ Matcher matcher = entry.getKey().matcher(spannable);
+ while (matcher.find()) {
+ boolean set = true;
+ for (ImageSpan span : spannable.getSpans(matcher.start(),
+ matcher.end(), ImageSpan.class))
+ if (spannable.getSpanStart(span) >= matcher.start()
+ && spannable.getSpanEnd(span) <= matcher.end())
+ spannable.removeSpan(span);
+ else {
+ set = false;
+ break;
+ }
+ if (set) {
+ spannable.setSpan(new ImageSpan(context, entry.getValue()),
+ matcher.start(), matcher.end(),
+ Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
+ hasChanges = true;
+ }
+ }
+ }
+ return hasChanges;
+ }
+
+ private final static class EmoticonPattern {
+ Pattern pattern;
+ String replacement;
+
+ EmoticonPattern(String ascii, int unicode) {
+ this.pattern = Pattern.compile("(?<=(^|\\s))" + ascii
+ + "(?=(\\s|$))");
+ this.replacement = new String(new int[] { unicode, }, 0, 1);
+ }
+
+ String replaceAll(String body) {
+ return pattern.matcher(body).replaceAll(replacement);
+ }
+ }
+
+ private static final EmoticonPattern[] patterns = new EmoticonPattern[] {
+ new EmoticonPattern(":-?D", 0x1f600),
+ new EmoticonPattern("\\^\\^", 0x1f601),
+ new EmoticonPattern(":'D", 0x1f602),
+ new EmoticonPattern("\\]-?D", 0x1f608),
+ new EmoticonPattern(";-?\\)", 0x1f609),
+ new EmoticonPattern(":-?\\)", 0x1f60a),
+ new EmoticonPattern("[B8]-?\\)", 0x1f60e),
+ new EmoticonPattern(":-?\\|", 0x1f610),
+ new EmoticonPattern(":-?[/\\\\]", 0x1f615),
+ new EmoticonPattern(":-?\\*", 0x1f617),
+ new EmoticonPattern(":-?[Ppb]", 0x1f61b),
+ new EmoticonPattern(":-?\\(", 0x1f61e),
+ new EmoticonPattern(":-?[0Oo]", 0x1f62e),
+ new EmoticonPattern("\\\\o/", 0x1F631), };
+
+ public static String transformAsciiEmoticonsToUtf8(String body) {
+ if (body != null) {
+ for (EmoticonPattern p : patterns) {
+ body = p.replaceAll(body);
+ }
+ }
+ return body;
+ }
+
+ public static Spannable transformAsciiEmoticons(Context context, String body) {
+ Spannable spannable;
+ if (Config.UTF8_EMOTICONS) {
+ spannable = spannableFactory.newSpannable(transformAsciiEmoticonsToUtf8(body));
+ }
+ else {
+ spannable = spannableFactory.newSpannable(body);
+ getSmiledText(context, spannable);
+ }
+ return spannable;
+ }
+
+ public static int getColorForName(String name) {
+ if (name.isEmpty()) {
+ return 0xFF202020;
+ }
+ int colors[] = {0xFFe91e63, 0xFF9c27b0, 0xFF673ab7, 0xFF3f51b5,
+ 0xFF5677fc, 0xFF03a9f4, 0xFF00bcd4, 0xFF009688, 0xFFff5722,
+ 0xFF795548, 0xFF607d8b};
+ return colors[(int) ((name.hashCode() & 0xffffffffl) % colors.length)];
+ }
+
+ public static Pair<String,Boolean> getMessagePreview(final Context context, final Message message) {
+ final Downloadable d = message.getDownloadable();
+ if (d != null ) {
+ switch (d.getStatus()) {
+ case Downloadable.STATUS_CHECKING:
+ return new Pair<>(context.getString(R.string.checking_image),true);
+ case Downloadable.STATUS_DOWNLOADING:
+ return new Pair<>(context.getString(R.string.receiving_x_file,
+ getFileDescriptionString(context,message),
+ d.getProgress()),true);
+ case Downloadable.STATUS_OFFER:
+ case Downloadable.STATUS_OFFER_CHECK_FILESIZE:
+ return new Pair<>(context.getString(R.string.x_file_offered_for_download,
+ getFileDescriptionString(context,message)),true);
+ case Downloadable.STATUS_DELETED:
+ return new Pair<>(context.getString(R.string.file_deleted),true);
+ case Downloadable.STATUS_FAILED:
+ return new Pair<>(context.getString(R.string.file_transmission_failed),true);
+ case Downloadable.STATUS_UPLOADING:
+ if (message.getStatus() == Message.STATUS_OFFERED) {
+ return new Pair<>(context.getString(R.string.offering_x_file,
+ getFileDescriptionString(context, message)), true);
+ } else {
+ return new Pair<>(context.getString(R.string.sending_x_file,
+ getFileDescriptionString(context, message)), true);
+ }
+ default:
+ return new Pair<>("",false);
+ }
+ } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
+ return new Pair<>(context.getString(R.string.encrypted_message_received),true);
+ } else if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
+ if (message.getStatus() == Message.STATUS_RECEIVED) {
+ return new Pair<>(context.getString(R.string.received_x_file,
+ getFileDescriptionString(context, message)), true);
+ } else {
+ return new Pair<>(getFileDescriptionString(context,message),true);
+ }
+ } else {
+ if (message.getBody().startsWith(Message.ME_COMMAND)) {
+ return new Pair<>(message.getBody().replaceAll("^" + Message.ME_COMMAND,
+ UIHelper.getMessageDisplayName(message) + " "), false);
+ } else if (GeoHelper.isGeoUri(message.getBody())) {
+ if (message.getStatus() == Message.STATUS_RECEIVED) {
+ return new Pair<>(context.getString(R.string.received_location),true);
+ } else {
+ return new Pair<>(context.getString(R.string.location), true);
+ }
+ } else{
+ return new Pair<>(message.getBody(), false);
+ }
+ }
+ }
+
+ public static String getFileDescriptionString(final Context context, final Message message) {
+ if (message.getType() == Message.TYPE_IMAGE) {
+ return context.getString(R.string.image);
+ }
+ final String path = message.getRelativeFilePath();
+ if (path == null) {
+ return "";
+ }
+ final String mime;
+ try {
+ mime = URLConnection.guessContentTypeFromName(path.replace("#",""));
+ } catch (final StringIndexOutOfBoundsException ignored) {
+ return context.getString(R.string.file);
+ }
+ if (mime == null) {
+ return context.getString(R.string.file);
+ } else if (mime.startsWith("audio/")) {
+ return context.getString(R.string.audio);
+ } else if(mime.startsWith("video/")) {
+ return context.getString(R.string.video);
+ } else if (mime.startsWith("image/")) {
+ return context.getString(R.string.image);
+ } else if (mime.contains("pdf")) {
+ return context.getString(R.string.pdf_document) ;
+ } else if (mime.contains("application/vnd.android.package-archive")) {
+ return context.getString(R.string.apk) ;
+ } else if (mime.contains("vcard")) {
+ return context.getString(R.string.vcard) ;
+ } else {
+ return mime;
+ }
+ }
+
+ public static String getMessageDisplayName(final Message message) {
+ if (message.getStatus() == Message.STATUS_RECEIVED) {
+ if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
+ return getDisplayedMucCounterpart(message.getCounterpart());
+ } else {
+ final Contact contact = message.getContact();
+ return contact != null ? contact.getDisplayName() : "";
+ }
+ } else {
+ if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
+ return getDisplayedMucCounterpart(message.getConversation().getJid());
+ } else {
+ final Jid jid = message.getConversation().getAccount().getJid();
+ return jid.hasLocalpart() ? jid.getLocalpart() : jid.toDomainJid().toString();
+ }
+ }
+ }
+
+ private static String getDisplayedMucCounterpart(final Jid counterpart) {
+ if (counterpart==null) {
+ return "";
+ } else if (!counterpart.isBareJid()) {
+ return counterpart.getResourcepart().trim();
+ } else {
+ return counterpart.toString().trim();
+ }
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/XmlHelper.java b/src/main/java/de/thedevstack/conversationsplus/utils/XmlHelper.java
new file mode 100644
index 00000000..1287f73f
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/XmlHelper.java
@@ -0,0 +1,12 @@
+package de.thedevstack.conversationsplus.utils;
+
+public class XmlHelper {
+ public static String encodeEntities(String content) {
+ content = content.replace("&", "&amp;");
+ content = content.replace("<", "&lt;");
+ content = content.replace(">", "&gt;");
+ content = content.replace("\"", "&quot;");
+ content = content.replace("'", "&apos;");
+ return content;
+ }
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/Xmlns.java b/src/main/java/de/thedevstack/conversationsplus/utils/Xmlns.java
new file mode 100644
index 00000000..80718dec
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/Xmlns.java
@@ -0,0 +1,8 @@
+package de.thedevstack.conversationsplus.utils;
+
+public final class Xmlns {
+ public static final String BLOCKING = "urn:xmpp:blocking";
+ public static final String ROSTER = "jabber:iq:roster";
+ public static final String REGISTER = "jabber:iq:register";
+ public static final String BYTE_STREAMS = "http://jabber.org/protocol/bytestreams";
+}
diff --git a/src/main/java/de/thedevstack/conversationsplus/utils/XmppUri.java b/src/main/java/de/thedevstack/conversationsplus/utils/XmppUri.java
new file mode 100644
index 00000000..5d3a2694
--- /dev/null
+++ b/src/main/java/de/thedevstack/conversationsplus/utils/XmppUri.java
@@ -0,0 +1,85 @@
+package de.thedevstack.conversationsplus.utils;
+
+import android.net.Uri;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+
+import de.thedevstack.conversationsplus.xmpp.jid.InvalidJidException;
+import de.thedevstack.conversationsplus.xmpp.jid.Jid;
+
+public class XmppUri {
+
+ protected String jid;
+ protected boolean muc;
+ protected String fingerprint;
+
+ public XmppUri(String uri) {
+ try {
+ parse(Uri.parse(uri));
+ } catch (IllegalArgumentException e) {
+ try {
+ jid = Jid.fromString(uri).toBareJid().toString();
+ } catch (InvalidJidException e2) {
+ jid = null;
+ }
+ }
+ }
+
+ public XmppUri(Uri uri) {
+ parse(uri);
+ }
+
+ protected void parse(Uri uri) {
+ String scheme = uri.getScheme();
+ if ("xmpp".equalsIgnoreCase(scheme)) {
+ // sample: xmpp:jid@foo.com
+ muc = "join".equalsIgnoreCase(uri.getQuery());
+ if (uri.getAuthority() != null) {
+ jid = uri.getAuthority();
+ } else {
+ jid = uri.getSchemeSpecificPart().split("\\?")[0];
+ }
+ fingerprint = parseFingerprint(uri.getQuery());
+ } else if ("imto".equalsIgnoreCase(scheme)) {
+ // sample: imto://xmpp/jid@foo.com
+ try {
+ jid = URLDecoder.decode(uri.getEncodedPath(), "UTF-8").split("/")[1];
+ } catch (final UnsupportedEncodingException ignored) {
+ jid = null;
+ }
+ } else {
+ try {
+ jid = Jid.fromString(uri.toString()).toBareJid().toString();
+ } catch (final InvalidJidException ignored) {
+ jid = null;
+ }
+ }
+ }
+
+ protected String parseFingerprint(String query) {
+ if (query == null) {
+ return null;
+ } else {
+ final String NEEDLE = "otr-fingerprint=";
+ int index = query.indexOf(NEEDLE);
+ if (index >= 0 && query.length() >= (NEEDLE.length() + index + 40)) {
+ return query.substring(index + NEEDLE.length(), index + NEEDLE.length() + 40);
+ } else {
+ return null;
+ }
+ }
+ }
+
+ public Jid getJid() {
+ try {
+ return this.jid == null ? null :Jid.fromString(this.jid.toLowerCase());
+ } catch (InvalidJidException e) {
+ return null;
+ }
+ }
+
+ public String getFingerprint() {
+ return this.fingerprint;
+ }
+}