diff options
Diffstat (limited to 'src')
32 files changed, 1805 insertions, 355 deletions
diff --git a/src/eu/siacs/conversations/entities/Conversation.java b/src/eu/siacs/conversations/entities/Conversation.java index f8c6a2a6..6eb688ae 100644 --- a/src/eu/siacs/conversations/entities/Conversation.java +++ b/src/eu/siacs/conversations/entities/Conversation.java @@ -45,6 +45,8 @@ public class Conversation extends AbstractEntity { private int status; private long created; private int mode; + + private String nextPresence; private transient List<Message> messages = null; private transient Account account = null; @@ -308,4 +310,12 @@ public class Conversation extends AbstractEntity { public void setContactJid(String jid) { this.contactJid = jid; } + + public void setNextPresence(String presence) { + this.nextPresence = presence; + } + + public String getNextPresence() { + return this.nextPresence; + } } diff --git a/src/eu/siacs/conversations/entities/Message.java b/src/eu/siacs/conversations/entities/Message.java index b91d822d..a1cf32e8 100644 --- a/src/eu/siacs/conversations/entities/Message.java +++ b/src/eu/siacs/conversations/entities/Message.java @@ -9,15 +9,20 @@ public class Message extends AbstractEntity { public static final String TABLENAME = "messages"; + public static final int STATUS_RECIEVING = -1; public static final int STATUS_RECIEVED = 0; public static final int STATUS_UNSEND = 1; public static final int STATUS_SEND = 2; - public static final int STATUS_ERROR = 3; + public static final int STATUS_SEND_FAILED = 3; + public static final int STATUS_SEND_REJECTED = 4; public static final int ENCRYPTION_NONE = 0; public static final int ENCRYPTION_PGP = 1; public static final int ENCRYPTION_OTR = 2; public static final int ENCRYPTION_DECRYPTED = 3; + + public static final int TYPE_TEXT = 0; + public static final int TYPE_IMAGE = 1; public static String CONVERSATION = "conversationUuid"; public static String COUNTERPART = "counterpart"; @@ -25,6 +30,7 @@ public class Message extends AbstractEntity { public static String TIME_SENT = "timeSent"; public static String ENCRYPTION = "encryption"; public static String STATUS = "status"; + public static String TYPE = "type"; protected String conversationUuid; protected String counterpart; @@ -33,6 +39,7 @@ public class Message extends AbstractEntity { protected long timeSent; protected int encryption; protected int status; + protected int type; protected boolean read = true; protected transient Conversation conversation = null; @@ -40,17 +47,17 @@ public class Message extends AbstractEntity { public Message(Conversation conversation, String body, int encryption) { this(java.util.UUID.randomUUID().toString(), conversation.getUuid(), conversation.getContactJid(), body, System.currentTimeMillis(), encryption, - Message.STATUS_UNSEND); + Message.STATUS_UNSEND,TYPE_TEXT); this.conversation = conversation; } public Message(Conversation conversation, String counterpart, String body, int encryption, int status) { - this(java.util.UUID.randomUUID().toString(), conversation.getUuid(),counterpart, body, System.currentTimeMillis(), encryption,status); + this(java.util.UUID.randomUUID().toString(), conversation.getUuid(),counterpart, body, System.currentTimeMillis(), encryption,status,TYPE_TEXT); this.conversation = conversation; } public Message(String uuid, String conversationUUid, String counterpart, - String body, long timeSent, int encryption, int status) { + String body, long timeSent, int encryption, int status, int type) { this.uuid = uuid; this.conversationUuid = conversationUUid; this.counterpart = counterpart; @@ -58,6 +65,7 @@ public class Message extends AbstractEntity { this.timeSent = timeSent; this.encryption = encryption; this.status = status; + this.type = type; } @Override @@ -70,6 +78,7 @@ public class Message extends AbstractEntity { values.put(TIME_SENT, timeSent); values.put(ENCRYPTION, encryption); values.put(STATUS, status); + values.put(TYPE, type); return values; } @@ -108,7 +117,8 @@ public class Message extends AbstractEntity { cursor.getString(cursor.getColumnIndex(BODY)), cursor.getLong(cursor.getColumnIndex(TIME_SENT)), cursor.getInt(cursor.getColumnIndex(ENCRYPTION)), - cursor.getInt(cursor.getColumnIndex(STATUS))); + cursor.getInt(cursor.getColumnIndex(STATUS)), + cursor.getInt(cursor.getColumnIndex(TYPE))); } public void setConversation(Conversation conv) { @@ -150,4 +160,16 @@ public class Message extends AbstractEntity { public void setEncryptedBody(String body) { this.encryptedBody = body; } + + public void setType(int type) { + this.type = type; + } + + public int getType() { + return this.type; + } + + public void setPresence(String presence) { + this.counterpart = this.counterpart.split("/")[0] + "/" + presence; + } } diff --git a/src/eu/siacs/conversations/persistance/DatabaseBackend.java b/src/eu/siacs/conversations/persistance/DatabaseBackend.java index 4c0d6216..852a9315 100644 --- a/src/eu/siacs/conversations/persistance/DatabaseBackend.java +++ b/src/eu/siacs/conversations/persistance/DatabaseBackend.java @@ -23,7 +23,7 @@ public class DatabaseBackend extends SQLiteOpenHelper { private static DatabaseBackend instance = null; private static final String DATABASE_NAME = "history"; - private static final int DATABASE_VERSION = 2; + private static final int DATABASE_VERSION = 3; public DatabaseBackend(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); @@ -50,7 +50,7 @@ public class DatabaseBackend extends SQLiteOpenHelper { + " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, " + Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART + " TEXT, " + Message.BODY + " TEXT, " + Message.ENCRYPTION - + " NUMBER, " + Message.STATUS + " NUMBER," + "FOREIGN KEY(" + + " NUMBER, " + Message.STATUS + " NUMBER," +Message.TYPE +" NUMBER, FOREIGN KEY(" + Message.CONVERSATION + ") REFERENCES " + Conversation.TABLENAME + "(" + Conversation.UUID + ") ON DELETE CASCADE);"); @@ -72,6 +72,10 @@ public class DatabaseBackend extends SQLiteOpenHelper { db.execSQL("update " + Account.TABLENAME + " set " + Account.OPTIONS + " = " + Account.OPTIONS + " | 8"); } + if (oldVersion < 3 && newVersion >= 3) { + //add field type to message + db.execSQL("ALTER TABLE "+Message.TABLENAME+" ADD COLUMN "+Message.TYPE+" NUMBER");; + } } public static synchronized DatabaseBackend getInstance(Context context) { diff --git a/src/eu/siacs/conversations/persistance/FileBackend.java b/src/eu/siacs/conversations/persistance/FileBackend.java new file mode 100644 index 00000000..f7f986f2 --- /dev/null +++ b/src/eu/siacs/conversations/persistance/FileBackend.java @@ -0,0 +1,113 @@ +package eu.siacs.conversations.persistance; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.net.Uri; +import android.util.LruCache; + +import eu.siacs.conversations.entities.Conversation; +import eu.siacs.conversations.entities.Message; +import eu.siacs.conversations.xmpp.jingle.JingleFile; + +public class FileBackend { + + private static int IMAGE_SIZE = 1920; + + private Context context; + private LruCache<String, Bitmap> thumbnailCache; + + public FileBackend(Context context) { + this.context = context; + + int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); + int cacheSize = maxMemory / 8; + thumbnailCache = new LruCache<String, Bitmap>(cacheSize) { + @Override + protected int sizeOf(String key, Bitmap bitmap) { + return bitmap.getByteCount() / 1024; + } + }; + + } + + public JingleFile getJingleFile(Message message) { + Conversation conversation = message.getConversation(); + String prefix = context.getFilesDir().getAbsolutePath(); + String path = prefix + "/" + conversation.getAccount().getJid() + "/" + + conversation.getContactJid(); + String filename = message.getUuid() + ".webp"; + return new JingleFile(path + "/" + filename); + } + + private Bitmap resize(Bitmap originalBitmap, int size) { + int w = originalBitmap.getWidth(); + int h = originalBitmap.getHeight(); + if (Math.max(w, h) > size) { + int scalledW; + int scalledH; + if (w <= h) { + scalledW = (int) (w / ((double) h / size)); + scalledH = size; + } else { + scalledW = size; + scalledH = (int) (h / ((double) w / size)); + } + Bitmap scalledBitmap = Bitmap.createScaledBitmap( + originalBitmap, scalledW, scalledH, true); + return scalledBitmap; + } else { + return originalBitmap; + } + } + + public JingleFile copyImageToPrivateStorage(Message message, Uri image) { + try { + InputStream is = context.getContentResolver() + .openInputStream(image); + JingleFile file = getJingleFile(message); + file.getParentFile().mkdirs(); + file.createNewFile(); + OutputStream os = new FileOutputStream(file); + Bitmap originalBitmap = BitmapFactory.decodeStream(is); + is.close(); + Bitmap scalledBitmap = resize(originalBitmap, IMAGE_SIZE); + boolean success = scalledBitmap.compress(Bitmap.CompressFormat.WEBP,75,os); + if (!success) { + //Log.d("xmppService", "couldnt compress"); + } + os.close(); + return file; + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + public Bitmap getImageFromMessage(Message message) { + return BitmapFactory + .decodeFile(getJingleFile(message).getAbsolutePath()); + } + + public Bitmap getThumbnailFromMessage(Message message, int size) { + Bitmap thumbnail = thumbnailCache.get(message.getUuid()); + if (thumbnail==null) { + Bitmap fullsize = BitmapFactory.decodeFile(getJingleFile(message) + .getAbsolutePath()); + thumbnail = resize(fullsize, size); + this.thumbnailCache.put(message.getUuid(), thumbnail); + } + return thumbnail; + } +} diff --git a/src/eu/siacs/conversations/services/XmppConnectionService.java b/src/eu/siacs/conversations/services/XmppConnectionService.java index 9dbce675..e5974c2d 100644 --- a/src/eu/siacs/conversations/services/XmppConnectionService.java +++ b/src/eu/siacs/conversations/services/XmppConnectionService.java @@ -1,5 +1,6 @@ package eu.siacs.conversations.services; +import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; @@ -27,6 +28,7 @@ import eu.siacs.conversations.entities.MucOptions; import eu.siacs.conversations.entities.MucOptions.OnRenameListener; import eu.siacs.conversations.entities.Presences; import eu.siacs.conversations.persistance.DatabaseBackend; +import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.persistance.OnPhoneContactsMerged; import eu.siacs.conversations.ui.OnAccountListChangedListener; import eu.siacs.conversations.ui.OnConversationListChangedListener; @@ -39,16 +41,17 @@ import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xmpp.OnBindListener; import eu.siacs.conversations.xmpp.OnIqPacketReceived; -import eu.siacs.conversations.xmpp.OnJinglePacketReceived; import eu.siacs.conversations.xmpp.OnMessagePacketReceived; import eu.siacs.conversations.xmpp.OnPresencePacketReceived; import eu.siacs.conversations.xmpp.OnStatusChanged; import eu.siacs.conversations.xmpp.OnTLSExceptionReceived; import eu.siacs.conversations.xmpp.XmppConnection; +import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager; +import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived; +import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.MessagePacket; import eu.siacs.conversations.xmpp.stanzas.PresencePacket; -import eu.siacs.conversations.xmpp.stanzas.jingle.JinglePacket; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; @@ -59,6 +62,7 @@ import android.database.ContentObserver; import android.database.DatabaseUtils; import android.net.ConnectivityManager; import android.net.NetworkInfo; +import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; @@ -73,6 +77,7 @@ public class XmppConnectionService extends Service { protected static final String LOGTAG = "xmppService"; public DatabaseBackend databaseBackend; + private FileBackend fileBackend; public long startDate; @@ -80,10 +85,12 @@ public class XmppConnectionService extends Service { private static final int PING_MIN_INTERVAL = 10; private static final int PING_TIMEOUT = 5; private static final int CONNECT_TIMEOUT = 60; + private static final long CARBON_GRACE_PERIOD = 60000L; private List<Account> accounts; private List<Conversation> conversations = null; - + private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(this); + public OnConversationListChangedListener convChangedListener = null; private int convChangedListenerCount = 0; private OnAccountListChangedListener accountChangedListener = null; @@ -96,6 +103,8 @@ public class XmppConnectionService extends Service { private Random mRandom = new Random(System.currentTimeMillis()); + private long lastCarbonMessageReceived = -CARBON_GRACE_PERIOD; + private ContentObserver contactObserver = new ContentObserver(null) { @Override public void onChange(boolean selfChange) { @@ -115,6 +124,10 @@ public class XmppConnectionService extends Service { MessagePacket packet) { Message message = null; boolean notify = true; + if(getPreferences().getBoolean("notification_grace_period_after_carbon_received", true)){ + notify=(SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > CARBON_GRACE_PERIOD; + } + if ((packet.getType() == MessagePacket.TYPE_CHAT)) { String pgpBody = MessageParser.getPgpBody(packet); if (pgpBody != null) { @@ -138,6 +151,7 @@ public class XmppConnectionService extends Service { service); if (message != null) { if (message.getStatus() == Message.STATUS_SEND) { + lastCarbonMessageReceived = SystemClock.elapsedRealtime(); notify = false; message.getConversation().markRead(); } else { @@ -158,7 +172,8 @@ public class XmppConnectionService extends Service { } } } else if (packet.getType() == MessagePacket.TYPE_ERROR) { - message = MessageParser.parseError(packet, account, service); + MessageParser.parseError(packet, account, service); + return; } else if (packet.getType() == MessagePacket.TYPE_NORMAL) { if (packet.hasChild("x")) { Element x = packet.findChild("x"); @@ -348,6 +363,8 @@ public class XmppConnectionService extends Service { processRosterItems(account, query); mergePhoneContactsWithRoster(null); } + } else { + Log.d(LOGTAG,"iq packet arrived "+packet.toString()); } } }; @@ -356,7 +373,7 @@ public class XmppConnectionService extends Service { @Override public void onJinglePacketReceived(Account account, JinglePacket packet) { - Log.d(LOGTAG,account.getJid()+": jingle packet received"+packet.toString()); + mJingleConnectionManager.deliverPacket(account, packet); } }; @@ -381,6 +398,22 @@ public class XmppConnectionService extends Service { } + public FileBackend getFileBackend() { + return this.fileBackend; + } + + public Message attachImageToConversation(Conversation conversation, String presence, Uri uri) { + Message message = new Message(conversation, "", Message.ENCRYPTION_NONE); + message.setPresence(presence); + message.setType(Message.TYPE_IMAGE); + File file = this.fileBackend.copyImageToPrivateStorage(message, uri); + conversation.getMessages().add(message); + databaseBackend.createMessage(message); + sendMessage(message, null); + return message; + } + + protected Conversation findMuc(String name, Account account) { for (Conversation conversation : this.conversations) { if (conversation.getContactJid().split("/")[0].equals(name) @@ -522,7 +555,8 @@ public class XmppConnectionService extends Service { @Override public void onCreate() { ExceptionHelper.init(getApplicationContext()); - databaseBackend = DatabaseBackend.getInstance(getApplicationContext()); + this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext()); + this.fileBackend = new FileBackend(getApplicationContext()); this.accounts = databaseBackend.getAccounts(); this.getConversations(); @@ -589,8 +623,7 @@ public class XmppConnectionService extends Service { } public XmppConnection createConnection(Account account) { - SharedPreferences sharedPref = PreferenceManager - .getDefaultSharedPreferences(getApplicationContext()); + SharedPreferences sharedPref = getPreferences(); account.setResource(sharedPref.getString("resource", "mobile").toLowerCase(Locale.getDefault())); XmppConnection connection = new XmppConnection(account, this.pm); connection.setOnMessagePacketReceivedListener(this.messageListener); @@ -633,51 +666,55 @@ public class XmppConnectionService extends Service { synchronized public void sendMessage(Message message, String presence) { Account account = message.getConversation().getAccount(); Conversation conv = message.getConversation(); + MessagePacket packet = null; boolean saveInDb = false; boolean addToConversation = false; + boolean send = false; if (account.getStatus() == Account.STATUS_ONLINE) { - MessagePacket packet; - if (message.getEncryption() == Message.ENCRYPTION_OTR) { - if (!conv.hasValidOtrSession()) { - // starting otr session. messages will be send later - conv.startOtrSession(getApplicationContext(), presence,true); - } else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) { - // otr session aleary exists, creating message packet - // accordingly - packet = prepareMessagePacket(account, message, - conv.getOtrSession()); - account.getXmppConnection().sendMessagePacket(packet); - message.setStatus(Message.STATUS_SEND); - } - saveInDb = true; - addToConversation = true; - } else if (message.getEncryption() == Message.ENCRYPTION_PGP) { - message.getConversation().endOtrIfNeeded(); - long keyId = message.getConversation().getContact() - .getPgpKeyId(); - packet = new MessagePacket(); - packet.setType(MessagePacket.TYPE_CHAT); - packet.setFrom(message.getConversation().getAccount() - .getFullJid()); - packet.setTo(message.getCounterpart()); - packet.setBody("This is an XEP-0027 encryted message"); - packet.addChild("x", "jabber:x:encrypted").setContent(message.getEncryptedBody()); - account.getXmppConnection().sendMessagePacket(packet); - message.setStatus(Message.STATUS_SEND); - message.setEncryption(Message.ENCRYPTION_DECRYPTED); - saveInDb = true; - addToConversation = true; + if (message.getType() == Message.TYPE_IMAGE) { + mJingleConnectionManager.createNewConnection(message); } else { - message.getConversation().endOtrIfNeeded(); - // don't encrypt - if (message.getConversation().getMode() == Conversation.MODE_SINGLE) { + if (message.getEncryption() == Message.ENCRYPTION_OTR) { + if (!conv.hasValidOtrSession()) { + // starting otr session. messages will be send later + conv.startOtrSession(getApplicationContext(), presence,true); + } else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) { + // otr session aleary exists, creating message packet + // accordingly + packet = prepareMessagePacket(account, message, + conv.getOtrSession()); + send = true; + message.setStatus(Message.STATUS_SEND); + } + saveInDb = true; + addToConversation = true; + } else if (message.getEncryption() == Message.ENCRYPTION_PGP) { + message.getConversation().endOtrIfNeeded(); + long keyId = message.getConversation().getContact() + .getPgpKeyId(); + packet = new MessagePacket(); + packet.setType(MessagePacket.TYPE_CHAT); + packet.setFrom(message.getConversation().getAccount() + .getFullJid()); + packet.setTo(message.getCounterpart()); + packet.setBody("This is an XEP-0027 encryted message"); + packet.addChild("x", "jabber:x:encrypted").setContent(message.getEncryptedBody()); message.setStatus(Message.STATUS_SEND); + message.setEncryption(Message.ENCRYPTION_DECRYPTED); saveInDb = true; addToConversation = true; + send = true; + } else { + message.getConversation().endOtrIfNeeded(); + // don't encrypt + if (message.getConversation().getMode() == Conversation.MODE_SINGLE) { + message.setStatus(Message.STATUS_SEND); + saveInDb = true; + addToConversation = true; + } + packet = prepareMessagePacket(account, message, null); + send = true; } - - packet = prepareMessagePacket(account, message, null); - account.getXmppConnection().sendMessagePacket(packet); } } else { // account is offline @@ -694,6 +731,9 @@ public class XmppConnectionService extends Service { convChangedListener.onConversationListChanged(); } } + if ((send)&&(packet!=null)) { + account.getXmppConnection().sendMessagePacket(packet); + } } @@ -748,6 +788,7 @@ public class XmppConnectionService extends Service { packet.setTo(message.getCounterpart().split("/")[0]); packet.setFrom(account.getJid()); } + packet.setId(message.getUuid()); return packet; } @@ -1018,12 +1059,10 @@ public class XmppConnectionService extends Service { OnConversationListChangedListener listener) { this.convChangedListener = listener; this.convChangedListenerCount++; - Log.d(LOGTAG,"registered on conv changed in backend ("+convChangedListenerCount+")"); } public void removeOnConversationListChangedListener() { this.convChangedListenerCount--; - Log.d(LOGTAG,"someone on conv changed listener removed listener ("+convChangedListenerCount+")"); if (this.convChangedListenerCount==0) { this.convChangedListener = null; } @@ -1160,8 +1199,7 @@ public class XmppConnectionService extends Service { } public void createContact(Contact contact) { - SharedPreferences sharedPref = PreferenceManager - .getDefaultSharedPreferences(getApplicationContext()); + SharedPreferences sharedPref = getPreferences(); boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true); if (autoGrant) { contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT); @@ -1253,9 +1291,11 @@ public class XmppConnectionService extends Service { public Contact findContact(String uuid) { Contact contact = this.databaseBackend.getContact(uuid); - for (Account account : getAccounts()) { - if (contact.getAccountUuid().equals(account.getUuid())) { - contact.setAccount(account); + if (contact!=null) { + for (Account account : getAccounts()) { + if (contact.getAccountUuid().equals(account.getUuid())) { + contact.setAccount(account); + } } } return contact; @@ -1325,4 +1365,33 @@ public class XmppConnectionService extends Service { } } -}
\ No newline at end of file + + public boolean markMessage(Account account, String recipient, String uuid, int status) { + boolean marked = false; + for(Conversation conversation : getConversations()) { + if (conversation.getContactJid().equals(recipient)&&conversation.getAccount().equals(account)) { + for(Message message : conversation.getMessages()) { + if (message.getUuid().equals(uuid)) { + markMessage(message, status); + marked = true; + break; + } + } + break; + } + } + return marked; + } + + public void markMessage(Message message, int status) { + message.setStatus(status); + databaseBackend.updateMessage(message); + if (convChangedListener!=null) { + convChangedListener.onConversationListChanged(); + } + } + + public SharedPreferences getPreferences() { + return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); + } +} diff --git a/src/eu/siacs/conversations/ui/ContactDetailsActivity.java b/src/eu/siacs/conversations/ui/ContactDetailsActivity.java index 5dc6eb3b..86535ba1 100644 --- a/src/eu/siacs/conversations/ui/ContactDetailsActivity.java +++ b/src/eu/siacs/conversations/ui/ContactDetailsActivity.java @@ -230,7 +230,7 @@ public class ContactDetailsActivity extends XmppActivity { contactJid.setText(contact.getJid()); accountJid.setText(contact.getAccount().getJid()); - UIHelper.prepareContactBadge(this, badge, contact); + UIHelper.prepareContactBadge(this, badge, contact, getApplicationContext()); if (contact.getSystemAccount() == null) { badge.setOnClickListener(onBadgeClick); diff --git a/src/eu/siacs/conversations/ui/ContactsActivity.java b/src/eu/siacs/conversations/ui/ContactsActivity.java index 2e9e55f5..e403450a 100644 --- a/src/eu/siacs/conversations/ui/ContactsActivity.java +++ b/src/eu/siacs/conversations/ui/ContactsActivity.java @@ -381,8 +381,7 @@ public class ContactsActivity extends XmppActivity { contactJid.setText(contact.getJid()); ImageView imageView = (ImageView) view .findViewById(R.id.contact_photo); - imageView.setImageBitmap(UIHelper.getContactPicture(contact, - null, 90, this.getContext())); + imageView.setImageBitmap(UIHelper.getContactPicture(contact, 48, this.getContext(), false)); return view; } }; diff --git a/src/eu/siacs/conversations/ui/ConversationActivity.java b/src/eu/siacs/conversations/ui/ConversationActivity.java index f47e8a8c..6ce31302 100644 --- a/src/eu/siacs/conversations/ui/ConversationActivity.java +++ b/src/eu/siacs/conversations/ui/ConversationActivity.java @@ -1,6 +1,7 @@ package eu.siacs.conversations.ui; import java.util.ArrayList; +import java.util.Hashtable; import java.util.List; import eu.siacs.conversations.R; @@ -22,7 +23,6 @@ import android.graphics.Color; import android.graphics.Typeface; import android.support.v4.widget.SlidingPaneLayout; import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener; -import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; @@ -43,39 +43,43 @@ public class ConversationActivity extends XmppActivity { public static final String VIEW_CONVERSATION = "viewConversation"; public static final String CONVERSATION = "conversationUuid"; public static final String TEXT = "text"; - + public static final String PRESENCE = "eu.siacs.conversations.presence"; + public static final int REQUEST_SEND_MESSAGE = 0x75441; public static final int REQUEST_DECRYPT_PGP = 0x76783; + private static final int ATTACH_FILE = 0x48502; protected SlidingPaneLayout spl; private List<Conversation> conversationList = new ArrayList<Conversation>(); private Conversation selectedConversation = null; private ListView listView; - + private boolean paneShouldBeOpen = true; private boolean useSubject = true; private ArrayAdapter<Conversation> listAdapter; - + private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() { - + @Override public void onConversationListChanged() { runOnUiThread(new Runnable() { - + @Override - public void run() { + public void run() { updateConversationList(); - if(paneShouldBeOpen) { + if (paneShouldBeOpen) { if (conversationList.size() >= 1) { swapConversationFragment(); } else { - startActivity(new Intent(getApplicationContext(), ContactsActivity.class)); + startActivity(new Intent(getApplicationContext(), + ContactsActivity.class)); finish(); } } - ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation"); - if (selectedFragment!=null) { + ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager() + .findFragmentByTag("conversation"); + if (selectedFragment != null) { selectedFragment.updateMessages(); } } @@ -83,19 +87,8 @@ public class ConversationActivity extends XmppActivity { } }; - private DialogInterface.OnClickListener addToRoster = new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - String jid = getSelectedConversation().getContactJid(); - Account account = getSelectedConversation().getAccount(); - String name = jid.split("@")[0]; - Contact contact = new Contact(account, name, jid, null); - xmppConnectionService.createContact(contact); - } - }; protected ConversationActivity activity = this; - + public List<Conversation> getConversationList() { return this.conversationList; } @@ -103,19 +96,19 @@ public class ConversationActivity extends XmppActivity { public Conversation getSelectedConversation() { return this.selectedConversation; } - + public ListView getConversationListView() { return this.listView; } - + public SlidingPaneLayout getSlidingPaneLayout() { return this.spl; } - + public boolean shouldPaneBeOpen() { return paneShouldBeOpen; } - + @Override protected void onCreate(Bundle savedInstanceState) { @@ -141,7 +134,7 @@ public class ConversationActivity extends XmppActivity { return view; } if (!spl.isSlideable()) { - if (conv==getSelectedConversation()) { + if (conv == getSelectedConversation()) { view.setBackgroundColor(0xffdddddd); } else { view.setBackgroundColor(Color.TRANSPARENT); @@ -149,29 +142,34 @@ public class ConversationActivity extends XmppActivity { } else { view.setBackgroundColor(Color.TRANSPARENT); } - TextView convName = (TextView) view.findViewById(R.id.conversation_name); + TextView convName = (TextView) view + .findViewById(R.id.conversation_name); convName.setText(conv.getName(useSubject)); - TextView convLastMsg = (TextView) view.findViewById(R.id.conversation_lastmsg); + TextView convLastMsg = (TextView) view + .findViewById(R.id.conversation_lastmsg); convLastMsg.setText(conv.getLatestMessage().getBody()); - - if(!conv.isRead()) { - convName.setTypeface(null,Typeface.BOLD); - convLastMsg.setTypeface(null,Typeface.BOLD); + + if (!conv.isRead()) { + convName.setTypeface(null, Typeface.BOLD); + convLastMsg.setTypeface(null, Typeface.BOLD); } else { - convName.setTypeface(null,Typeface.NORMAL); - convLastMsg.setTypeface(null,Typeface.NORMAL); + convName.setTypeface(null, Typeface.NORMAL); + convLastMsg.setTypeface(null, Typeface.NORMAL); } - + ((TextView) view.findViewById(R.id.conversation_lastupdate)) - .setText(UIHelper.readableTimeDifference(conv.getLatestMessage().getTimeSent())); - - ImageView imageView = (ImageView) view.findViewById(R.id.conversation_image); - imageView.setImageBitmap(UIHelper.getContactPicture(conv.getContact(), conv.getName(useSubject),200, activity.getApplicationContext())); + .setText(UIHelper.readableTimeDifference(conv + .getLatestMessage().getTimeSent())); + + ImageView imageView = (ImageView) view + .findViewById(R.id.conversation_image); + imageView.setImageBitmap(UIHelper.getContactPicture( + conv, 56, activity.getApplicationContext(), false)); return view; } }; - + listView.setAdapter(this.listAdapter); listView.setOnItemClickListener(new OnItemClickListener() { @@ -182,7 +180,7 @@ public class ConversationActivity extends XmppActivity { paneShouldBeOpen = false; if (selectedConversation != conversationList.get(position)) { selectedConversation = conversationList.get(position); - swapConversationFragment(); //.onBackendConnected(conversationList.get(position)); + swapConversationFragment(); // .onBackendConnected(conversationList.get(position)); } else { spl.closePane(); } @@ -206,13 +204,16 @@ public class ConversationActivity extends XmppActivity { @Override public void onPanelClosed(View arg0) { paneShouldBeOpen = false; - if ((conversationList.size() > 0)&&(getSelectedConversation()!=null)) { + if ((conversationList.size() > 0) + && (getSelectedConversation() != null)) { getActionBar().setDisplayHomeAsUpEnabled(true); - getActionBar().setTitle(getSelectedConversation().getName(useSubject)); + getActionBar().setTitle( + getSelectedConversation().getName(useSubject)); invalidateOptionsMenu(); if (!getSelectedConversation().isRead()) { getSelectedConversation().markRead(); - UIHelper.updateNotification(getApplicationContext(), getConversationList(), null, false); + UIHelper.updateNotification(getApplicationContext(), + getConversationList(), null, false); listView.invalidateViews(); } } @@ -231,29 +232,38 @@ public class ConversationActivity extends XmppActivity { getMenuInflater().inflate(R.menu.conversations, menu); MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security); MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive); - MenuItem menuMucDetails = (MenuItem) menu.findItem(R.id.action_muc_details); - MenuItem menuContactDetails = (MenuItem) menu.findItem(R.id.action_contact_details); - MenuItem menuInviteContacts = (MenuItem) menu.findItem(R.id.action_invite); - - if ((spl.isOpen()&&(spl.isSlideable()))) { + MenuItem menuMucDetails = (MenuItem) menu + .findItem(R.id.action_muc_details); + MenuItem menuContactDetails = (MenuItem) menu + .findItem(R.id.action_contact_details); + MenuItem menuInviteContacts = (MenuItem) menu + .findItem(R.id.action_invite); + MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file); + + if ((spl.isOpen() && (spl.isSlideable()))) { menuArchive.setVisible(false); menuMucDetails.setVisible(false); menuContactDetails.setVisible(false); menuSecure.setVisible(false); menuInviteContacts.setVisible(false); + menuAttach.setVisible(false); } else { - ((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl.isSlideable()); - if (this.getSelectedConversation()!=null) { + ((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl + .isSlideable()); + if (this.getSelectedConversation() != null) { if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) { menuMucDetails.setVisible(true); menuContactDetails.setVisible(false); menuSecure.setVisible(false); menuInviteContacts.setVisible(true); + menuAttach.setVisible(false); } else { menuContactDetails.setVisible(true); menuMucDetails.setVisible(false); menuInviteContacts.setVisible(false); - if (this.getSelectedConversation().getLatestMessage().getEncryption() != Message.ENCRYPTION_NONE) { + menuAttach.setVisible(true); + if (this.getSelectedConversation().getLatestMessage() + .getEncryption() != Message.ENCRYPTION_NONE) { menuSecure.setIcon(R.drawable.ic_action_secure); } } @@ -268,6 +278,21 @@ public class ConversationActivity extends XmppActivity { case android.R.id.home: spl.openPane(); break; + case R.id.action_attach_file: + selectPresence(getSelectedConversation(), new OnPresenceSelected() { + + @Override + public void onPresenceSelected(boolean success, String presence) { + if (success) { + Intent attachFileIntent = new Intent(); + attachFileIntent.setType("image/*"); + attachFileIntent.setAction(Intent.ACTION_GET_CONTENT); + Intent chooser = Intent.createChooser(attachFileIntent, "Attach File"); + startActivityForResult(chooser, ATTACH_FILE); + } + } + }); + break; case R.id.action_add: startActivity(new Intent(this, ContactsActivity.class)); break; @@ -286,22 +311,16 @@ public class ConversationActivity extends XmppActivity { case R.id.action_contact_details: Contact contact = this.getSelectedConversation().getContact(); if (contact != null) { - Intent intent = new Intent(this,ContactDetailsActivity.class); + Intent intent = new Intent(this, ContactDetailsActivity.class); intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT); intent.putExtra("uuid", contact.getUuid()); startActivity(intent); } else { - String jid = getSelectedConversation().getContactJid(); - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(jid); - builder.setMessage("The contact is not in your roster. Would you like to add it."); - builder.setNegativeButton("Cancel", null); - builder.setPositiveButton("Add",addToRoster); - builder.create().show(); + showAddToRosterDialog(getSelectedConversation()); } break; case R.id.action_muc_details: - Intent intent = new Intent(this,MucDetailsActivity.class); + Intent intent = new Intent(this, MucDetailsActivity.class); intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC); intent.putExtra("uuid", getSelectedConversation().getUuid()); startActivity(intent); @@ -310,17 +329,18 @@ public class ConversationActivity extends XmppActivity { Intent inviteIntent = new Intent(getApplicationContext(), ContactsActivity.class); inviteIntent.setAction("invite"); - inviteIntent.putExtra("uuid",selectedConversation.getUuid()); + inviteIntent.putExtra("uuid", selectedConversation.getUuid()); startActivity(inviteIntent); break; case R.id.action_security: final Conversation selConv = getSelectedConversation(); View menuItemView = findViewById(R.id.action_security); PopupMenu popup = new PopupMenu(this, menuItemView); - final ConversationFragment fragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation"); - if (fragment!=null) { + final ConversationFragment fragment = (ConversationFragment) getFragmentManager() + .findFragmentByTag("conversation"); + if (fragment != null) { popup.setOnMenuItemClickListener(new OnMenuItemClickListener() { - + @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { @@ -344,26 +364,31 @@ public class ConversationActivity extends XmppActivity { return true; } }); - popup.inflate(R.menu.encryption_choices); - switch (selConv.nextMessageEncryption) { + popup.inflate(R.menu.encryption_choices); + switch (selConv.nextMessageEncryption) { case Message.ENCRYPTION_NONE: - popup.getMenu().findItem(R.id.encryption_choice_none).setChecked(true); + popup.getMenu().findItem(R.id.encryption_choice_none) + .setChecked(true); break; case Message.ENCRYPTION_OTR: - popup.getMenu().findItem(R.id.encryption_choice_otr).setChecked(true); + popup.getMenu().findItem(R.id.encryption_choice_otr) + .setChecked(true); break; case Message.ENCRYPTION_PGP: - popup.getMenu().findItem(R.id.encryption_choice_pgp).setChecked(true); + popup.getMenu().findItem(R.id.encryption_choice_pgp) + .setChecked(true); break; case Message.ENCRYPTION_DECRYPTED: - popup.getMenu().findItem(R.id.encryption_choice_pgp).setChecked(true); + popup.getMenu().findItem(R.id.encryption_choice_pgp) + .setChecked(true); break; default: - popup.getMenu().findItem(R.id.encryption_choice_none).setChecked(true); + popup.getMenu().findItem(R.id.encryption_choice_none) + .setChecked(true); break; } - popup.show(); - } + popup.show(); + } break; default: @@ -374,10 +399,11 @@ public class ConversationActivity extends XmppActivity { protected ConversationFragment swapConversationFragment() { ConversationFragment selectedFragment = new ConversationFragment(); - + FragmentTransaction transaction = getFragmentManager() .beginTransaction(); - transaction.replace(R.id.selected_conversation, selectedFragment,"conversation"); + transaction.replace(R.id.selected_conversation, selectedFragment, + "conversation"); transaction.commit(); return selectedFragment; } @@ -392,24 +418,25 @@ public class ConversationActivity extends XmppActivity { } return super.onKeyDown(keyCode, event); } - + @Override public void onStart() { super.onStart(); - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + SharedPreferences preferences = PreferenceManager + .getDefaultSharedPreferences(this); this.useSubject = preferences.getBoolean("use_subject_in_muc", true); if (this.xmppConnectionServiceBound) { this.onBackendConnected(); } - if (conversationList.size()>=1) { + if (conversationList.size() >= 1) { onConvChanged.onConversationListChanged(); } } - + @Override protected void onStop() { if (xmppConnectionServiceBound) { - xmppConnectionService.removeOnConversationListChangedListener(); + xmppConnectionService.removeOnConversationListChangedListener(); } super.onStop(); } @@ -417,18 +444,20 @@ public class ConversationActivity extends XmppActivity { @Override void onBackendConnected() { this.registerListener(); - if (conversationList.size()==0) { + if (conversationList.size() == 0) { updateConversationList(); } - if ((getIntent().getAction()!=null)&&(getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) { + if ((getIntent().getAction() != null) + && (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) { if (getIntent().getType().equals( ConversationActivity.VIEW_CONVERSATION)) { handledViewIntent = true; - String convToView = (String) getIntent().getExtras().get(CONVERSATION); + String convToView = (String) getIntent().getExtras().get( + CONVERSATION); - for(int i = 0; i < conversationList.size(); ++i) { + for (int i = 0; i < conversationList.size(); ++i) { if (conversationList.get(i).getUuid().equals(convToView)) { selectedConversation = conversationList.get(i); } @@ -442,46 +471,108 @@ public class ConversationActivity extends XmppActivity { startActivity(new Intent(this, ManageAccountActivity.class)); finish(); } else if (conversationList.size() <= 0) { - //add no history + // add no history startActivity(new Intent(this, ContactsActivity.class)); finish(); } else { spl.openPane(); - //find currently loaded fragment - ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation"); - if (selectedFragment!=null) { + // find currently loaded fragment + ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager() + .findFragmentByTag("conversation"); + if (selectedFragment != null) { selectedFragment.onBackendConnected(); } else { selectedConversation = conversationList.get(0); swapConversationFragment(); } - ExceptionHelper.checkForCrash(this,this.xmppConnectionService); + ExceptionHelper.checkForCrash(this, this.xmppConnectionService); } } } + public void registerListener() { - if (xmppConnectionServiceBound) { - xmppConnectionService.setOnConversationListChangedListener(this.onConvChanged); - } + if (xmppConnectionServiceBound) { + xmppConnectionService + .setOnConversationListChangedListener(this.onConvChanged); + } } @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (resultCode == RESULT_OK) { + protected void onActivityResult(int requestCode, int resultCode, final Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode == RESULT_OK) { if (requestCode == REQUEST_DECRYPT_PGP) { - ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager().findFragmentByTag("conversation"); - if (selectedFragment!=null) { + ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager() + .findFragmentByTag("conversation"); + if (selectedFragment != null) { selectedFragment.hidePgpPassphraseBox(); } + } else if (requestCode == ATTACH_FILE) { + Conversation conversation = getSelectedConversation(); + String presence = conversation.getNextPresence(); + xmppConnectionService.attachImageToConversation(conversation, presence, data.getData()); + } - } - } + } + } public void updateConversationList() { conversationList.clear(); - conversationList.addAll(xmppConnectionService - .getConversations()); + conversationList.addAll(xmppConnectionService.getConversations()); listView.invalidateViews(); } + + public void selectPresence(final Conversation conversation, final OnPresenceSelected listener) { + Contact contact = conversation.getContact(); + if (contact==null) { + showAddToRosterDialog(conversation); + listener.onPresenceSelected(false,null); + } else { + Hashtable<String, Integer> presences = contact.getPresences(); + if (presences.size() == 0) { + listener.onPresenceSelected(false, null); + } else if (presences.size() == 1) { + String presence = (String) presences.keySet().toArray()[0]; + conversation.setNextPresence(presence); + listener.onPresenceSelected(true, presence); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle("Choose Presence"); + final String[] presencesArray = new String[presences.size()]; + presences.keySet().toArray(presencesArray); + builder.setItems(presencesArray, + new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, + int which) { + String presence = presencesArray[which]; + conversation.setNextPresence(presence); + listener.onPresenceSelected(true,presence); + } + }); + builder.create().show(); + } + } + } + + private void showAddToRosterDialog(final Conversation conversation) { + String jid = conversation.getContactJid(); + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(jid); + builder.setMessage(getString(R.string.not_in_roster)); + builder.setNegativeButton(getString(R.string.cancel), null); + builder.setPositiveButton(getString(R.string.add_contact), new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + String jid = conversation.getContactJid(); + Account account = getSelectedConversation().getAccount(); + String name = jid.split("@")[0]; + Contact contact = new Contact(account, name, jid, null); + xmppConnectionService.createContact(contact); + } + }); + builder.create().show(); + } } diff --git a/src/eu/siacs/conversations/ui/ConversationFragment.java b/src/eu/siacs/conversations/ui/ConversationFragment.java index 51caafbd..06ed41e5 100644 --- a/src/eu/siacs/conversations/ui/ConversationFragment.java +++ b/src/eu/siacs/conversations/ui/ConversationFragment.java @@ -33,6 +33,7 @@ import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; +import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -89,7 +90,6 @@ public class ConversationFragment extends Fragment { @Override public void onClick(View v) { - Log.d("gultsch", "clicked to decrypt"); if (askForPassphraseIntent != null) { try { getActivity().startIntentSenderForResult( @@ -97,7 +97,7 @@ public class ConversationFragment extends Fragment { ConversationActivity.REQUEST_DECRYPT_PGP, null, 0, 0, 0); } catch (SendIntentException e) { - Log.d("gultsch", "couldnt fire intent"); + Log.d("xmppService", "couldnt fire intent"); } } } @@ -149,6 +149,8 @@ public class ConversationFragment extends Fragment { public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final DisplayMetrics metrics = getResources().getDisplayMetrics(); + this.inflater = inflater; final View view = inflater.inflate(R.layout.fragment_conversation, @@ -177,19 +179,16 @@ public class ConversationFragment extends Fragment { private static final int SENT = 0; private static final int RECIEVED = 1; - private static final int ERROR = 2; @Override public int getViewTypeCount() { - return 3; + return 2; } @Override public int getItemViewType(int position) { - if (getItem(position).getStatus() == Message.STATUS_RECIEVED) { + if (getItem(position).getStatus() <= Message.STATUS_RECIEVED) { return RECIEVED; - } else if (getItem(position).getStatus() == Message.STATUS_ERROR) { - return ERROR; } else { return SENT; } @@ -210,6 +209,7 @@ public class ConversationFragment extends Fragment { .findViewById(R.id.message_photo); viewHolder.imageView.setImageBitmap(selfBitmap); viewHolder.indicator = (ImageView) view.findViewById(R.id.security_indicator); + viewHolder.image = (ImageView) view.findViewById(R.id.message_image); break; case RECIEVED: view = (View) inflater.inflate( @@ -227,14 +227,6 @@ public class ConversationFragment extends Fragment { } break; - case ERROR: - view = (View) inflater.inflate(R.layout.message_error, - null); - viewHolder.imageView = (ImageView) view - .findViewById(R.id.message_photo); - viewHolder.imageView.setImageBitmap(mBitmapCache - .getError()); - break; default: viewHolder = null; break; @@ -262,40 +254,60 @@ public class ConversationFragment extends Fragment { } } } - String body = item.getBody(); - if (body != null) { - if (item.getEncryption() == Message.ENCRYPTION_PGP) { - viewHolder.messageBody - .setText(getString(R.string.encrypted_message)); - viewHolder.messageBody.setTextColor(0xff33B5E5); - viewHolder.messageBody.setTypeface(null, - Typeface.ITALIC); - viewHolder.indicator.setVisibility(View.VISIBLE); - } else if ((item.getEncryption() == Message.ENCRYPTION_OTR)||(item.getEncryption() == Message.ENCRYPTION_DECRYPTED)) { - viewHolder.messageBody.setText(body.trim()); - viewHolder.messageBody.setTextColor(0xff000000); - viewHolder.messageBody.setTypeface(null, - Typeface.NORMAL); - viewHolder.indicator.setVisibility(View.VISIBLE); - } else { - viewHolder.messageBody.setText(body.trim()); - viewHolder.messageBody.setTextColor(0xff000000); - viewHolder.messageBody.setTypeface(null, - Typeface.NORMAL); - if (item.getStatus() != Message.STATUS_ERROR) { + if (item.getType() == Message.TYPE_IMAGE) { + viewHolder.image.setVisibility(View.VISIBLE); + viewHolder.image.setImageBitmap(activity.xmppConnectionService.getFileBackend().getThumbnailFromMessage(item,(int) (metrics.density * 288))); + viewHolder.messageBody.setVisibility(View.GONE); + } else { + if (viewHolder.image != null) viewHolder.image.setVisibility(View.GONE); + viewHolder.messageBody.setVisibility(View.VISIBLE); + String body = item.getBody(); + if (body != null) { + if (item.getEncryption() == Message.ENCRYPTION_PGP) { + viewHolder.messageBody + .setText(getString(R.string.encrypted_message)); + viewHolder.messageBody.setTextColor(0xff33B5E5); + viewHolder.messageBody.setTypeface(null, + Typeface.ITALIC); + viewHolder.indicator.setVisibility(View.VISIBLE); + } else if ((item.getEncryption() == Message.ENCRYPTION_OTR)||(item.getEncryption() == Message.ENCRYPTION_DECRYPTED)) { + viewHolder.messageBody.setText(body.trim()); + viewHolder.messageBody.setTextColor(0xff333333); + viewHolder.messageBody.setTypeface(null, + Typeface.NORMAL); + viewHolder.indicator.setVisibility(View.VISIBLE); + } else { + viewHolder.messageBody.setText(body.trim()); + viewHolder.messageBody.setTextColor(0xff333333); + viewHolder.messageBody.setTypeface(null, + Typeface.NORMAL); viewHolder.indicator.setVisibility(View.GONE); } + } else { + viewHolder.indicator.setVisibility(View.GONE); } - } else { - viewHolder.indicator.setVisibility(View.GONE); } - if (item.getStatus() == Message.STATUS_UNSEND) { + switch (item.getStatus()) { + case Message.STATUS_UNSEND: viewHolder.time.setTypeface(null, Typeface.ITALIC); + viewHolder.time.setTextColor(0xFF8e8e8e); viewHolder.time.setText("sending\u2026"); - } else { + break; + case Message.STATUS_SEND_FAILED: + viewHolder.time.setText(getString(R.string.send_failed) + " \u00B7 " + UIHelper.readableTimeDifference(item + .getTimeSent())); + viewHolder.time.setTextColor(0xFFe92727); + viewHolder.time.setTypeface(null,Typeface.NORMAL); + break; + case Message.STATUS_SEND_REJECTED: + viewHolder.time.setText(getString(R.string.send_rejected)); + viewHolder.time.setTextColor(0xFFe92727); + viewHolder.time.setTypeface(null,Typeface.NORMAL); + break; + default: viewHolder.time.setTypeface(null, Typeface.NORMAL); - if ((item.getConversation().getMode() == Conversation.MODE_SINGLE) - || (type != RECIEVED)) { + viewHolder.time.setTextColor(0xFF8e8e8e); + if (item.getConversation().getMode() == Conversation.MODE_SINGLE) { viewHolder.time.setText(UIHelper .readableTimeDifference(item.getTimeSent())); } else { @@ -304,6 +316,7 @@ public class ConversationFragment extends Fragment { + UIHelper.readableTimeDifference(item .getTimeSent())); } + break; } return view; } @@ -320,7 +333,7 @@ public class ConversationFragment extends Fragment { boolean showPhoneSelfContactPicture = sharedPref.getBoolean( "show_phone_selfcontact_picture", true); - return UIHelper.getSelfContactPicture(conversation.getAccount(), 200, + return UIHelper.getSelfContactPicture(conversation.getAccount(), 48, showPhoneSelfContactPicture, getActivity()); } @@ -505,7 +518,7 @@ public class ConversationFragment extends Fragment { getActivity()); builder.setTitle("No openPGP key found"); builder.setIconAttribute(android.R.attr.alertDialogIcon); - builder.setMessage("There is no openPGP key assoziated with this contact"); + builder.setMessage("There is no openPGP key associated with this contact"); builder.setNegativeButton("Cancel", null); builder.setPositiveButton("Send plain text", new DialogInterface.OnClickListener() { @@ -585,6 +598,7 @@ public class ConversationFragment extends Fragment { private static class ViewHolder { + protected ImageView image; protected ImageView indicator; protected TextView time; protected TextView messageBody; @@ -600,7 +614,12 @@ public class ConversationFragment extends Fragment { if (bitmaps.containsKey(name)) { return bitmaps.get(name); } else { - Bitmap bm = UIHelper.getContactPicture(contact, name, 200, context); + Bitmap bm; + if (contact != null){ + bm = UIHelper.getContactPicture(contact, 48, context, false); + } else { + bm = UIHelper.getContactPicture(name, 48, context, false); + } bitmaps.put(name, bm); return bm; } diff --git a/src/eu/siacs/conversations/ui/MucDetailsActivity.java b/src/eu/siacs/conversations/ui/MucDetailsActivity.java index bf36f156..c6807c61 100644 --- a/src/eu/siacs/conversations/ui/MucDetailsActivity.java +++ b/src/eu/siacs/conversations/ui/MucDetailsActivity.java @@ -179,7 +179,7 @@ public class MucDetailsActivity extends XmppActivity { role.setText(getReadableRole(contact.getRole())); ImageView imageView = (ImageView) view .findViewById(R.id.contact_photo); - imageView.setImageBitmap(UIHelper.getContactPicture(null,contact.getName(), 90,this.getApplicationContext())); + imageView.setImageBitmap(UIHelper.getContactPicture(contact.getName(), 48,this.getApplicationContext(), false)); membersView.addView(view); } } diff --git a/src/eu/siacs/conversations/ui/OnPresenceSelected.java b/src/eu/siacs/conversations/ui/OnPresenceSelected.java new file mode 100644 index 00000000..7e424b2e --- /dev/null +++ b/src/eu/siacs/conversations/ui/OnPresenceSelected.java @@ -0,0 +1,5 @@ +package eu.siacs.conversations.ui; + +public interface OnPresenceSelected { + public void onPresenceSelected(boolean success, String presence); +} diff --git a/src/eu/siacs/conversations/ui/ShareWithActivity.java b/src/eu/siacs/conversations/ui/ShareWithActivity.java index 51bad721..1bc9fc46 100644 --- a/src/eu/siacs/conversations/ui/ShareWithActivity.java +++ b/src/eu/siacs/conversations/ui/ShareWithActivity.java @@ -81,7 +81,10 @@ public class ShareWithActivity extends XmppActivity { } }); for(final Conversation conversation : convList) { - View view = createContactView(conversation.getName(useSubject), conversation.getLatestMessage().getBody().trim(), UIHelper.getContactPicture(conversation.getContact(),conversation.getName(useSubject), 90,this.getApplicationContext())); + View view = createContactView(conversation.getName(useSubject), + conversation.getLatestMessage().getBody().trim(), + UIHelper.getContactPicture(conversation, 48, + this.getApplicationContext(), false)); view.setOnClickListener(new OnClickListener() { @Override @@ -115,7 +118,8 @@ public class ShareWithActivity extends XmppActivity { for(int i = 0; i < contactsList.size(); ++i) { final Contact con = contactsList.get(i); - View view = createContactView(con.getDisplayName(), con.getJid(), UIHelper.getContactPicture(con,null, 90,this.getApplicationContext())); + View view = createContactView(con.getDisplayName(), con.getJid(), + UIHelper.getContactPicture(con, 48, this.getApplicationContext(), false)); view.setOnClickListener(new OnClickListener() { @Override diff --git a/src/eu/siacs/conversations/utils/ExceptionHelper.java b/src/eu/siacs/conversations/utils/ExceptionHelper.java index c6e857c0..f9cd375e 100644 --- a/src/eu/siacs/conversations/utils/ExceptionHelper.java +++ b/src/eu/siacs/conversations/utils/ExceptionHelper.java @@ -34,6 +34,18 @@ public class ExceptionHelper { 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); @@ -54,20 +66,11 @@ public class ExceptionHelper { @Override public void onClick(DialogInterface dialog, int which) { - 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) { - Log.d("xmppService","using account="+account.getJid()+" to send in stack trace"); - Conversation conversation = service.findOrCreateConversation(account, "bugs@siacs.eu", false); + + Log.d("xmppService","using account="+finalAccount.getJid()+" to send in stack trace"); + Conversation conversation = service.findOrCreateConversation(finalAccount, "bugs@siacs.eu", false); Message message = new Message(conversation, stacktrace.toString(), Message.ENCRYPTION_NONE); service.sendMessage(message, null); - } } }); builder.setNegativeButton(context.getText(R.string.send_never),new OnClickListener() { diff --git a/src/eu/siacs/conversations/utils/MessageParser.java b/src/eu/siacs/conversations/utils/MessageParser.java index 936d0e9a..568386d5 100644 --- a/src/eu/siacs/conversations/utils/MessageParser.java +++ b/src/eu/siacs/conversations/utils/MessageParser.java @@ -149,19 +149,9 @@ public class MessageParser { return new Message(conversation,fullJid, message.findChild("body").getContent(), Message.ENCRYPTION_NONE,status); } - public static Message parseError(MessagePacket packet, Account account, XmppConnectionService service) { - - String[] fromParts = packet.getFrom().split("/"); - Conversation conversation = service.findOrCreateConversation(account, fromParts[0],false); - Element error = packet.findChild("error"); - String errorName = error.getChildren().get(0).getName(); - String displayError; - if (errorName.equals("service-unavailable")) { - displayError = "Contact is offline and does not have offline storage"; - } else { - displayError = errorName.replace("-", " "); - } - return new Message(conversation, packet.getFrom(), displayError, Message.ENCRYPTION_NONE, Message.STATUS_ERROR); + public static void parseError(MessagePacket packet, Account account, XmppConnectionService service) { + String[] fromParts = packet.getFrom().split("/"); + service.markMessage(account, fromParts[0], packet.getId(), Message.STATUS_SEND_FAILED); } public static String getPgpBody(MessagePacket packet) { diff --git a/src/eu/siacs/conversations/utils/PhoneHelper.java b/src/eu/siacs/conversations/utils/PhoneHelper.java index 5c652afe..6355e378 100644 --- a/src/eu/siacs/conversations/utils/PhoneHelper.java +++ b/src/eu/siacs/conversations/utils/PhoneHelper.java @@ -13,18 +13,19 @@ import android.os.Bundle; import android.os.Looper; import android.provider.ContactsContract; import android.provider.ContactsContract.Profile; +import android.provider.MediaStore; public class PhoneHelper { - - public static void loadPhoneContacts(Context context, final OnPhoneContactsLoadedListener listener) { - if (Looper.myLooper()==null) { + + public static void loadPhoneContacts(Context context, + final OnPhoneContactsLoadedListener listener) { + if (Looper.myLooper() == null) { Looper.prepare(); } final Looper mLooper = Looper.myLooper(); final Hashtable<String, Bundle> phoneContacts = new Hashtable<String, Bundle>(); - - final String[] PROJECTION = new String[] { - ContactsContract.Data._ID, + + final String[] PROJECTION = new String[] { ContactsContract.Data._ID, ContactsContract.Data.DISPLAY_NAME, ContactsContract.Data.PHOTO_THUMBNAIL_URI, ContactsContract.Data.LOOKUP_KEY, @@ -35,7 +36,7 @@ public class PhoneHelper { + "\") AND (" + ContactsContract.CommonDataKinds.Im.PROTOCOL + "=\"" + ContactsContract.CommonDataKinds.Im.PROTOCOL_JABBER + "\")"; - + CursorLoader mCursorLoader = new CursorLoader(context, ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION, null, null); @@ -55,14 +56,14 @@ public class PhoneHelper { "photouri", cursor.getString(cursor .getColumnIndex(ContactsContract.Data.PHOTO_THUMBNAIL_URI))); - contact.putString("lookup",cursor.getString(cursor + contact.putString("lookup", cursor.getString(cursor .getColumnIndex(ContactsContract.Data.LOOKUP_KEY))); phoneContacts.put( cursor.getString(cursor .getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA)), contact); } - if (listener!=null) { + if (listener != null) { listener.onPhoneContactsLoaded(phoneContacts); } mLooper.quit(); @@ -71,18 +72,18 @@ public class PhoneHelper { mCursorLoader.startLoading(); } - public static Uri getSefliUri(Activity activity) { + public static Uri getSefliUri(Context context) { String[] mProjection = new String[] { Profile._ID, Profile.PHOTO_THUMBNAIL_URI }; - Cursor mProfileCursor = activity.getContentResolver().query( + Cursor mProfileCursor = context.getContentResolver().query( Profile.CONTENT_URI, mProjection, null, null, null); - if (mProfileCursor.getCount()==0) { + if (mProfileCursor.getCount() == 0) { return null; } else { mProfileCursor.moveToFirst(); String uri = mProfileCursor.getString(1); - if (uri==null) { + if (uri == null) { return null; } else { return Uri.parse(uri); diff --git a/src/eu/siacs/conversations/utils/UIHelper.java b/src/eu/siacs/conversations/utils/UIHelper.java index 73a0494b..f058b9ee 100644 --- a/src/eu/siacs/conversations/utils/UIHelper.java +++ b/src/eu/siacs/conversations/utils/UIHelper.java @@ -12,6 +12,8 @@ import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Message; +import eu.siacs.conversations.entities.MucOptions; +import eu.siacs.conversations.entities.MucOptions.User; import eu.siacs.conversations.ui.ConversationActivity; import eu.siacs.conversations.ui.ManageAccountActivity; @@ -31,6 +33,7 @@ import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; +import android.graphics.Typeface; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.ContactsContract.Contacts; @@ -38,6 +41,7 @@ import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.InboxStyle; import android.support.v4.app.TaskStackBuilder; import android.text.Html; +import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -46,6 +50,10 @@ import android.widget.QuickContactBadge; import android.widget.TextView; public class UIHelper { + private static final int BG_COLOR = 0xFF181818; + private static final int FG_COLOR = 0xFFE5E5E5; + private static final int TRANSPARENT = 0x00000000; + public static String readableTimeDifference(long time) { if (time == 0) { return "just now"; @@ -65,49 +73,235 @@ public class UIHelper { } } - private static Bitmap getUnknownContactPicture(String name, int size) { - String firstLetter = (name.length() > 0) ? name.substring(0, 1).toUpperCase(Locale.US) : " "; + public static int getRealPx(int dp, Context context) { + final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + return ((int) (dp * metrics.density)); + } + private static int getNameColor(String name) { int holoColors[] = { 0xFF1da9da, 0xFFb368d9, 0xFF83b600, 0xFFffa713, 0xFFe92727 }; - int color = holoColors[Math.abs(name.toLowerCase(Locale.getDefault()).hashCode()) % holoColors.length]; + return color; + } + private static Bitmap getUnknownContactPicture(String[] names, int size, int bgColor, int fgColor) { + int tiles = (names.length > 4)? 4 : + (names.length < 1)? 1 : + names.length; Bitmap bitmap = Bitmap .createBitmap(size, size, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); - bitmap.eraseColor(color); + String[] letters = new String[tiles]; + int[] colors = new int[tiles]; + if (names.length < 1) { + letters[0] = "?"; + colors[0] = 0xFFe92727; + } else { + for(int i = 0; i < tiles; ++i) { + letters[i] = (names[i].length() > 0) ? + names[i].substring(0, 1).toUpperCase(Locale.US) : " "; + colors[i] = getNameColor(names[i]); + } - Paint paint = new Paint(); - paint.setColor(0xffe5e5e5); - paint.setTextSize((float) (size * 0.9)); - paint.setAntiAlias(true); - Rect rect = new Rect(); - paint.getTextBounds(firstLetter, 0, 1, rect); - float width = paint.measureText(firstLetter); - canvas.drawText(firstLetter, (size / 2) - (width / 2), (size / 2) - + (rect.height() / 2), paint); + if (names.length > 4) { + letters[3] = "\u2026"; // Unicode ellipsis + colors[3] = 0xFF444444; + } + } + Paint textPaint = new Paint(), tilePaint = new Paint(); + textPaint.setColor(fgColor); + textPaint.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL)); + Rect rect, left, right, topLeft, bottomLeft, topRight, bottomRight; + float width; + + switch(tiles) { + case 1: + bitmap.eraseColor(colors[0]); + + textPaint.setTextSize((float) (size * 0.8)); + textPaint.setAntiAlias(true); + rect = new Rect(); + textPaint.getTextBounds(letters[0], 0, 1, rect); + width = textPaint.measureText(letters[0]); + canvas.drawText(letters[0], (size / 2) - (width / 2), (size / 2) + + (rect.height() / 2), textPaint); + break; + + case 2: + bitmap.eraseColor(bgColor); + + tilePaint.setColor(colors[0]); + left = new Rect(0, 0, (size/2)-1, size); + canvas.drawRect(left, tilePaint); + + tilePaint.setColor(colors[1]); + right = new Rect((size/2)+1, 0, size, size); + canvas.drawRect(right, tilePaint); + + textPaint.setTextSize((float) (size * 0.8*0.5)); + textPaint.setAntiAlias(true); + rect = new Rect(); + textPaint.getTextBounds(letters[0], 0, 1, rect); + width = textPaint.measureText(letters[0]); + canvas.drawText(letters[0], (size / 4) - (width / 2), (size / 2) + + (rect.height() / 2), textPaint); + textPaint.getTextBounds(letters[1], 0, 1, rect); + width = textPaint.measureText(letters[1]); + canvas.drawText(letters[1], (3 * size / 4) - (width / 2), (size / 2) + + (rect.height() / 2), textPaint); + break; + + case 3: + bitmap.eraseColor(bgColor); + + tilePaint.setColor(colors[0]); + left = new Rect(0, 0, (size/2)-1, size); + canvas.drawRect(left, tilePaint); + + tilePaint.setColor(colors[1]); + topRight = new Rect((size/2)+1, 0, size, (size/2 - 1)); + canvas.drawRect(topRight, tilePaint); + + tilePaint.setColor(colors[2]); + bottomRight = new Rect((size/2)+1, (size/2 + 1), size, size); + canvas.drawRect(bottomRight, tilePaint); + + textPaint.setTextSize((float) (size * 0.8*0.5)); + textPaint.setAntiAlias(true); + rect = new Rect(); + + textPaint.getTextBounds(letters[0], 0, 1, rect); + width = textPaint.measureText(letters[0]); + canvas.drawText(letters[0], (size / 4) - (width / 2), (size / 2) + + (rect.height() / 2), textPaint); + + textPaint.getTextBounds(letters[1], 0, 1, rect); + width = textPaint.measureText(letters[1]); + canvas.drawText(letters[1], (3 * size / 4) - (width / 2), (size / 4) + + (rect.height() / 2), textPaint); + + textPaint.getTextBounds(letters[2], 0, 1, rect); + width = textPaint.measureText(letters[2]); + canvas.drawText(letters[2], (3 * size / 4) - (width / 2), (3* size / 4) + + (rect.height() / 2), textPaint); + break; + + case 4: + bitmap.eraseColor(bgColor); + + tilePaint.setColor(colors[0]); + topLeft = new Rect(0, 0, (size/2)-1, (size/2)-1); + canvas.drawRect(topLeft, tilePaint); + + tilePaint.setColor(colors[1]); + bottomLeft = new Rect(0, (size/2)+1, (size/2)-1, size); + canvas.drawRect(bottomLeft, tilePaint); + tilePaint.setColor(colors[2]); + topRight = new Rect((size/2)+1, 0, size, (size/2 - 1)); + canvas.drawRect(topRight, tilePaint); + + tilePaint.setColor(colors[3]); + bottomRight = new Rect((size/2)+1, (size/2 + 1), size, size); + canvas.drawRect(bottomRight, tilePaint); + + textPaint.setTextSize((float) (size * 0.8*0.5)); + textPaint.setAntiAlias(true); + rect = new Rect(); + + textPaint.getTextBounds(letters[0], 0, 1, rect); + width = textPaint.measureText(letters[0]); + canvas.drawText(letters[0], (size / 4) - (width / 2), (size / 4) + + (rect.height() / 2), textPaint); + + textPaint.getTextBounds(letters[1], 0, 1, rect); + width = textPaint.measureText(letters[1]); + canvas.drawText(letters[1], (size / 4) - (width / 2), (3* size / 4) + + (rect.height() / 2), textPaint); + + textPaint.getTextBounds(letters[2], 0, 1, rect); + width = textPaint.measureText(letters[2]); + canvas.drawText(letters[2], (3 * size / 4) - (width / 2), (size / 4) + + (rect.height() / 2), textPaint); + + textPaint.getTextBounds(letters[3], 0, 1, rect); + width = textPaint.measureText(letters[3]); + canvas.drawText(letters[3], (3 * size / 4) - (width / 2), (3* size / 4) + + (rect.height() / 2), textPaint); + break; + } return bitmap; } - - public static Bitmap getContactPicture(Contact contact, String fallback, int size, Context context) { - if (contact==null) { - return getUnknownContactPicture(fallback, size); + + private static Bitmap getUnknownContactPicture(String[] names, int size) { + return getUnknownContactPicture(names, size, UIHelper.BG_COLOR, UIHelper.FG_COLOR); + } + + private static Bitmap getMucContactPicture(Conversation conversation, int size, int bgColor, int fgColor) { + List<User> members = conversation.getMucOptions().getUsers(); + if (members.size() == 0) { + return getUnknownContactPicture(new String[]{conversation.getName(false)}, size, bgColor, fgColor); + } + String[] names = new String[members.size()+1]; + names[0] = conversation.getMucOptions().getNick(); + for(int i = 0; i < members.size(); ++i) { + names[i+1] = members.get(i).getName(); + } + + return getUnknownContactPicture(names, size, bgColor, fgColor); + } + + public static Bitmap getContactPicture(Conversation conversation, int dpSize, Context context, boolean notification) { + if(conversation.getMode() == Conversation.MODE_SINGLE) { + if (conversation.getContact() != null){ + return getContactPicture(conversation.getContact(), dpSize, + context, notification); + } else { + return getContactPicture(conversation.getName(false), dpSize, + context, notification); + } + } else{ + int fgColor = UIHelper.FG_COLOR, + bgColor = (notification) ? + UIHelper.BG_COLOR : UIHelper.TRANSPARENT; + + return getMucContactPicture(conversation, getRealPx(dpSize, context), + bgColor, fgColor); } + } + + public static Bitmap getContactPicture(Contact contact, int dpSize, Context context, boolean notification) { + int fgColor = UIHelper.FG_COLOR, + bgColor = (notification) ? + UIHelper.BG_COLOR : UIHelper.TRANSPARENT; + String uri = contact.getProfilePhoto(); if (uri==null) { - return getUnknownContactPicture(contact.getDisplayName(), size); + return getContactPicture(contact.getDisplayName(), dpSize, + context, notification); } try { - Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(Uri.parse(uri))); - return Bitmap.createScaledBitmap(bm, size, size, false); + Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver() + .openInputStream(Uri.parse(uri))); + return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context), + getRealPx(dpSize, context), false); } catch (FileNotFoundException e) { - return getUnknownContactPicture(contact.getDisplayName(), size); + return getContactPicture(contact.getDisplayName(), dpSize, + context, notification); } } + public static Bitmap getContactPicture(String name, int dpSize, Context context, boolean notification) { + int fgColor = UIHelper.FG_COLOR, + bgColor = (notification) ? + UIHelper.BG_COLOR : UIHelper.TRANSPARENT; + + return getUnknownContactPicture(new String[]{name}, getRealPx(dpSize, context), + bgColor, fgColor); + } + public static Bitmap getErrorPicture(int size) { Bitmap bitmap = Bitmap .createBitmap(size, size, Bitmap.Config.ARGB_8888); @@ -203,7 +397,6 @@ public class UIHelper { } String ringtone = preferences.getString("notification_ringtone", null); - Resources res = context.getResources(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( context); if (unread.size() == 0) { @@ -212,8 +405,8 @@ public class UIHelper { } else if (unread.size() == 1) { Conversation conversation = unread.get(0); targetUuid = conversation.getUuid(); - mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation.getContact(), conversation.getName(useSubject), (int) res - .getDimension(android.R.dimen.notification_large_icon_width), context)); + mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation, 64, + context, true)); mBuilder.setContentTitle(conversation.getName(useSubject)); if (notify) { mBuilder.setTicker(conversation.getLatestMessage().getBody().trim()); @@ -255,12 +448,15 @@ public class UIHelper { mBuilder.setContentText(names.toString()); mBuilder.setStyle(style); } + if ((currentCon!=null)&&(notify)) { + targetUuid=currentCon.getUuid(); + } if (unread.size() != 0) { mBuilder.setSmallIcon(R.drawable.notification); if (notify) { if (vibrate) { int dat = 70; - long[] pattern = {0,3*dat,dat,dat,dat,3*dat,dat,dat}; + long[] pattern = {0,3*dat,dat,dat}; mBuilder.setVibrate(pattern); } mBuilder.setLights(0xffffffff, 2000, 4000); @@ -307,23 +503,13 @@ public class UIHelper { } public static void prepareContactBadge(final Activity activity, - QuickContactBadge badge, final Contact contact) { + QuickContactBadge badge, final Contact contact, Context context) { if (contact.getSystemAccount() != null) { String[] systemAccount = contact.getSystemAccount().split("#"); long id = Long.parseLong(systemAccount[0]); badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1])); - - if (contact.getProfilePhoto() != null) { - badge.setImageURI(Uri.parse(contact.getProfilePhoto())); - } else { - badge.setImageBitmap(UIHelper.getUnknownContactPicture( - contact.getDisplayName(), 400)); - } - } else { - badge.setImageBitmap(UIHelper.getUnknownContactPicture( - contact.getDisplayName(), 400)); } - + badge.setImageBitmap(UIHelper.getContactPicture(contact, 72, context, false)); } public static AlertDialog getVerifyFingerprintDialog( @@ -359,20 +545,20 @@ public class UIHelper { return builder.create(); } - public static Bitmap getSelfContactPicture(Account account, int size, boolean showPhoneSelfContactPicture, Activity activity) { + public static Bitmap getSelfContactPicture(Account account, int size, boolean showPhoneSelfContactPicture, Context context) { if (showPhoneSelfContactPicture) { - Uri selfiUri = PhoneHelper.getSefliUri(activity); + Uri selfiUri = PhoneHelper.getSefliUri(context); if (selfiUri != null) { try { - return BitmapFactory.decodeStream(activity + return BitmapFactory.decodeStream(context .getContentResolver().openInputStream(selfiUri)); } catch (FileNotFoundException e) { - return getUnknownContactPicture(account.getJid(), size); + return getContactPicture(account.getJid(), size, context, false); } } - return getUnknownContactPicture(account.getJid(), size); + return getContactPicture(account.getJid(), size, context, false); } else { - return getUnknownContactPicture(account.getJid(), size); + return getContactPicture(account.getJid(), size, context, false); } } } diff --git a/src/eu/siacs/conversations/xml/Element.java b/src/eu/siacs/conversations/xml/Element.java index 2f1d7ad8..ce1d10ce 100644 --- a/src/eu/siacs/conversations/xml/Element.java +++ b/src/eu/siacs/conversations/xml/Element.java @@ -139,4 +139,8 @@ public class Element { content = content.replace("'","'"); return content; } + + public void clearChildren() { + this.children.clear(); + } } diff --git a/src/eu/siacs/conversations/xmpp/PacketReceived.java b/src/eu/siacs/conversations/xmpp/PacketReceived.java index d9f42459..d4502d73 100644 --- a/src/eu/siacs/conversations/xmpp/PacketReceived.java +++ b/src/eu/siacs/conversations/xmpp/PacketReceived.java @@ -1,5 +1,5 @@ package eu.siacs.conversations.xmpp; -abstract interface PacketReceived { +public abstract interface PacketReceived { } diff --git a/src/eu/siacs/conversations/xmpp/XmppConnection.java b/src/eu/siacs/conversations/xmpp/XmppConnection.java index 1ca7cd8b..0019094c 100644 --- a/src/eu/siacs/conversations/xmpp/XmppConnection.java +++ b/src/eu/siacs/conversations/xmpp/XmppConnection.java @@ -16,9 +16,13 @@ import java.security.cert.CertPathValidatorException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; +import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; @@ -44,11 +48,12 @@ import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Tag; import eu.siacs.conversations.xml.TagWriter; import eu.siacs.conversations.xml.XmlReader; +import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived; +import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.stanzas.AbstractStanza; import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.MessagePacket; import eu.siacs.conversations.xmpp.stanzas.PresencePacket; -import eu.siacs.conversations.xmpp.stanzas.jingle.JinglePacket; import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket; import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket; import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket; @@ -70,8 +75,7 @@ public class XmppConnection implements Runnable { private boolean shouldBind = true; private boolean shouldAuthenticate = true; private Element streamFeatures; - private HashSet<String> discoFeatures = new HashSet<String>(); - private List<String> discoItems = new ArrayList<String>(); + private HashMap<String, List<String>> disco = new HashMap<String, List<String>>(); private String streamId = null; private int smVersion = 3; @@ -644,8 +648,8 @@ public class XmppConnection implements Runnable { tagWriter.writeStanzaAsync(enable); } sendInitialPresence(); - sendServiceDiscoveryInfo(); - sendServiceDiscoveryItems(); + sendServiceDiscoveryInfo(account.getServer()); + sendServiceDiscoveryItems(account.getServer()); if (bindListener !=null) { bindListener.onBind(account); } @@ -654,42 +658,54 @@ public class XmppConnection implements Runnable { }); } - private void sendServiceDiscoveryInfo() { + private void sendServiceDiscoveryInfo(final String server) { IqPacket iq = new IqPacket(IqPacket.TYPE_GET); - iq.setTo(account.getServer()); + iq.setTo(server); iq.query("http://jabber.org/protocol/disco#info"); this.sendIqPacket(iq, new OnIqPacketReceived() { @Override public void onIqPacketReceived(Account account, IqPacket packet) { - List<Element> elements = packet.query().getChildren(); - for (int i = 0; i < elements.size(); ++i) { - if (elements.get(i).getName().equals("feature")) { - discoFeatures.add(elements.get(i).getAttribute( - "var")); - } + List<Element> elements = packet.query().getChildren(); + List<String> features = new ArrayList<String>(); + for (int i = 0; i < elements.size(); ++i) { + if (elements.get(i).getName().equals("feature")) { + features.add(elements.get(i).getAttribute( + "var")); } - if (discoFeatures.contains("urn:xmpp:carbons:2")) { - sendEnableCarbons(); + } + Log.d(LOGTAG,"put "+server+" "+features.toString()); + disco.put(server, features); + + if (account.getServer().equals(server)) { + enableAdvancedStreamFeatures(); } } }); } - private void sendServiceDiscoveryItems() { + + private void enableAdvancedStreamFeatures() { + if (hasFeaturesCarbon()) { + sendEnableCarbons(); + } + } + + private void sendServiceDiscoveryItems(final String server) { IqPacket iq = new IqPacket(IqPacket.TYPE_GET); - iq.setTo(account.getServer()); + iq.setTo(server); iq.query("http://jabber.org/protocol/disco#items"); this.sendIqPacket(iq, new OnIqPacketReceived() { @Override public void onIqPacketReceived(Account account, IqPacket packet) { - List<Element> elements = packet.query().getChildren(); - for (int i = 0; i < elements.size(); ++i) { - if (elements.get(i).getName().equals("item")) { - discoItems.add(elements.get(i).getAttribute( - "jid")); - } + List<Element> elements = packet.query().getChildren(); + for (int i = 0; i < elements.size(); ++i) { + if (elements.get(i).getName().equals("item")) { + String jid = elements.get(i).getAttribute( + "jid"); + sendServiceDiscoveryInfo(jid); } + } } }); } @@ -732,8 +748,10 @@ public class XmppConnection implements Runnable { } public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) { - String id = nextRandomId(); - packet.setAttribute("id", id); + if (packet.getId()==null) { + String id = nextRandomId(); + packet.setAttribute("id", id); + } packet.setFrom(account.getFullJid()); this.sendPacket(packet, callback); } @@ -850,7 +868,26 @@ public class XmppConnection implements Runnable { } public boolean hasFeaturesCarbon() { - return discoFeatures.contains("urn:xmpp:carbons:2"); + return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2"); + } + + public boolean hasDiscoFeature(String server, String feature) { + if (!disco.containsKey(server)) { + return false; + } + return disco.get(server).contains(feature); + } + + public String findDiscoItemByFeature(String feature) { + Iterator<Entry<String, List<String>>> it = this.disco.entrySet().iterator(); + while (it.hasNext()) { + Entry<String, List<String>> pairs = it.next(); + if (pairs.getValue().contains(feature)) { + return pairs.getKey(); + } + it.remove(); + } + return null; } public void r() { @@ -866,15 +903,6 @@ public class XmppConnection implements Runnable { } public String getMucServer() { - for(int i = 0; i < discoItems.size(); ++i) { - if (discoItems.get(i).contains("conference.")) { - return discoItems.get(i); - } else if (discoItems.get(i).contains("conf.")) { - return discoItems.get(i); - } else if (discoItems.get(i).contains("muc.")) { - return discoItems.get(i); - } - } - return null; + return findDiscoItemByFeature("http://jabber.org/protocol/muc"); } } diff --git a/src/eu/siacs/conversations/xmpp/jingle/JingleConnection.java b/src/eu/siacs/conversations/xmpp/jingle/JingleConnection.java new file mode 100644 index 00000000..4551a1ca --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/JingleConnection.java @@ -0,0 +1,362 @@ +package eu.siacs.conversations.xmpp.jingle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import android.util.Log; + +import eu.siacs.conversations.entities.Account; +import eu.siacs.conversations.entities.Conversation; +import eu.siacs.conversations.entities.Message; +import eu.siacs.conversations.services.XmppConnectionService; +import eu.siacs.conversations.xml.Element; +import eu.siacs.conversations.xmpp.OnIqPacketReceived; +import eu.siacs.conversations.xmpp.jingle.stanzas.Content; +import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; +import eu.siacs.conversations.xmpp.jingle.stanzas.Reason; +import eu.siacs.conversations.xmpp.stanzas.IqPacket; + +public class JingleConnection { + + private JingleConnectionManager mJingleConnectionManager; + private XmppConnectionService mXmppConnectionService; + + public static final int STATUS_INITIATED = 0; + public static final int STATUS_ACCEPTED = 1; + public static final int STATUS_TERMINATED = 2; + public static final int STATUS_CANCELED = 3; + public static final int STATUS_FINISHED = 4; + public static final int STATUS_TRANSMITTING = 5; + public static final int STATUS_FAILED = 99; + + private int status = -1; + private Message message; + private String sessionId; + private Account account; + private String initiator; + private String responder; + private List<Element> candidates = new ArrayList<Element>(); + private List<String> candidatesUsedByCounterpart = new ArrayList<String>(); + private HashMap<String, SocksConnection> connections = new HashMap<String, SocksConnection>(); + private Content content = new Content(); + private JingleFile file = null; + + private OnIqPacketReceived responseListener = new OnIqPacketReceived() { + + @Override + public void onIqPacketReceived(Account account, IqPacket packet) { + if (packet.getType() == IqPacket.TYPE_ERROR) { + mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED); + status = STATUS_FAILED; + } + } + }; + + public JingleConnection(JingleConnectionManager mJingleConnectionManager) { + this.mJingleConnectionManager = mJingleConnectionManager; + this.mXmppConnectionService = mJingleConnectionManager.getXmppConnectionService(); + } + + public String getSessionId() { + return this.sessionId; + } + + public String getAccountJid() { + return this.account.getFullJid(); + } + + public String getCounterPart() { + return this.message.getCounterpart(); + } + + public void deliverPacket(JinglePacket packet) { + + if (packet.isAction("session-terminate")) { + Reason reason = packet.getReason(); + if (reason.hasChild("cancel")) { + this.cancel(); + } else if (reason.hasChild("success")) { + this.finish(); + } + } else if (packet.isAction("session-accept")) { + accept(packet); + } else if (packet.isAction("transport-info")) { + transportInfo(packet); + } else { + Log.d("xmppService","packet arrived in connection. action was "+packet.getAction()); + } + } + + public void init(Message message) { + this.message = message; + this.account = message.getConversation().getAccount(); + this.initiator = this.account.getFullJid(); + this.responder = this.message.getCounterpart(); + this.sessionId = this.mJingleConnectionManager.nextRandomId(); + if (this.candidates.size() > 0) { + this.sendInitRequest(); + } else { + this.mJingleConnectionManager.getPrimaryCandidate(account, new OnPrimaryCandidateFound() { + + @Override + public void onPrimaryCandidateFound(boolean success, Element candidate) { + if (success) { + mergeCandidate(candidate); + } + sendInitRequest(); + } + }); + } + + } + + public void init(Account account, JinglePacket packet) { + this.status = STATUS_INITIATED; + Conversation conversation = this.mXmppConnectionService.findOrCreateConversation(account, packet.getFrom().split("/")[0], false); + this.message = new Message(conversation, "receiving image file", Message.ENCRYPTION_NONE); + this.message.setType(Message.TYPE_IMAGE); + this.message.setStatus(Message.STATUS_RECIEVING); + String[] fromParts = packet.getFrom().split("/"); + this.message.setPresence(fromParts[1]); + this.account = account; + this.initiator = packet.getFrom(); + this.responder = this.account.getFullJid(); + this.sessionId = packet.getSessionId(); + this.content = packet.getJingleContent(); + this.mergeCandidates(this.content.getCanditates()); + Element fileOffer = packet.getJingleContent().getFileOffer(); + if (fileOffer!=null) { + this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message); + Element fileSize = fileOffer.findChild("size"); + Element fileName = fileOffer.findChild("name"); + this.file.setExpectedSize(Long.parseLong(fileSize.getContent())); + if (this.file.getExpectedSize()>=this.mJingleConnectionManager.getAutoAcceptFileSize()) { + Log.d("xmppService","auto accepting file from "+packet.getFrom()); + this.sendAccept(); + } else { + Log.d("xmppService","not auto accepting new file offer with size: "+this.file.getExpectedSize()+" allowed size:"+this.mJingleConnectionManager.getAutoAcceptFileSize()); + } + } else { + Log.d("xmppService","no file offer was attached. aborting"); + } + Log.d("xmppService","session Id "+getSessionId()); + } + + private void sendInitRequest() { + JinglePacket packet = this.bootstrapPacket(); + packet.setAction("session-initiate"); + this.content = new Content(); + if (message.getType() == Message.TYPE_IMAGE) { + content.setAttribute("creator", "initiator"); + content.setAttribute("name", "a-file-offer"); + this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message); + content.setFileOffer(this.file); + content.setCandidates(this.mJingleConnectionManager.nextRandomId(),this.candidates); + packet.setContent(content); + Log.d("xmppService",packet.toString()); + account.getXmppConnection().sendIqPacket(packet, this.responseListener); + this.status = STATUS_INITIATED; + } + } + + private void sendAccept() { + this.mJingleConnectionManager.getPrimaryCandidate(this.account, new OnPrimaryCandidateFound() { + + @Override + public void onPrimaryCandidateFound(boolean success, Element candidate) { + if (success) { + if (mergeCandidate(candidate)) { + content.addCandidate(candidate); + } + } + JinglePacket packet = bootstrapPacket(); + packet.setAction("session-accept"); + packet.setContent(content); + account.getXmppConnection().sendIqPacket(packet, new OnIqPacketReceived() { + + @Override + public void onIqPacketReceived(Account account, IqPacket packet) { + if (packet.getType() != IqPacket.TYPE_ERROR) { + status = STATUS_ACCEPTED; + connectWithCandidates(); + } + } + }); + } + }); + + } + + private JinglePacket bootstrapPacket() { + JinglePacket packet = new JinglePacket(); + packet.setFrom(account.getFullJid()); + packet.setTo(this.message.getCounterpart()); //fixme, not right in all cases; + packet.setSessionId(this.sessionId); + packet.setInitiator(this.initiator); + return packet; + } + + private void accept(JinglePacket packet) { + Log.d("xmppService","session-accept: "+packet.toString()); + Content content = packet.getJingleContent(); + this.mergeCandidates(content.getCanditates()); + this.status = STATUS_ACCEPTED; + this.connectWithCandidates(); + IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT); + account.getXmppConnection().sendIqPacket(response, null); + } + + private void transportInfo(JinglePacket packet) { + Content content = packet.getJingleContent(); + String cid = content.getUsedCandidate(); + IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT); + if (cid!=null) { + Log.d("xmppService","candidate used by counterpart:"+cid); + this.candidatesUsedByCounterpart.add(cid); + if (this.connections.containsKey(cid)) { + SocksConnection connection = this.connections.get(cid); + if (connection.isEstablished()) { + if (status!=STATUS_TRANSMITTING) { + this.connect(connection); + } else { + Log.d("xmppService","ignoring canditate used because we are already transmitting"); + } + } else { + Log.d("xmppService","not yet connected. check when callback comes back"); + } + } else { + Log.d("xmppService","candidate not yet in list of connections"); + } + } + account.getXmppConnection().sendIqPacket(response, null); + } + + private void connect(final SocksConnection connection) { + this.status = STATUS_TRANSMITTING; + final OnFileTransmitted callback = new OnFileTransmitted() { + + @Override + public void onFileTransmitted(JingleFile file) { + Log.d("xmppService","sucessfully transmitted file. sha1:"+file.getSha1Sum()); + } + }; + if ((connection.isProxy()&&(connection.getCid().equals(mJingleConnectionManager.getPrimaryCandidateId(account))))) { + Log.d("xmppService","candidate "+connection.getCid()+" was our proxy and needs activation"); + IqPacket activation = new IqPacket(IqPacket.TYPE_SET); + activation.setTo(connection.getJid()); + activation.query("http://jabber.org/protocol/bytestreams").setAttribute("sid", this.getSessionId()); + activation.query().addChild("activate").setContent(this.getResponder()); + this.account.getXmppConnection().sendIqPacket(activation, new OnIqPacketReceived() { + + @Override + public void onIqPacketReceived(Account account, IqPacket packet) { + Log.d("xmppService","activation result: "+packet.toString()); + if (initiator.equals(account.getFullJid())) { + Log.d("xmppService","we were initiating. sending file"); + connection.send(file,callback); + } else { + connection.receive(file,callback); + Log.d("xmppService","we were responding. receiving file"); + } + } + }); + } else { + if (initiator.equals(account.getFullJid())) { + Log.d("xmppService","we were initiating. sending file"); + connection.send(file,callback); + } else { + Log.d("xmppService","we were responding. receiving file"); + connection.receive(file,callback); + } + } + } + + private void finish() { + this.status = STATUS_FINISHED; + this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND); + this.disconnect(); + } + + public void cancel() { + this.disconnect(); + this.status = STATUS_CANCELED; + this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_REJECTED); + } + + private void connectWithCandidates() { + for(Element candidate : this.candidates) { + final SocksConnection socksConnection = new SocksConnection(this,candidate); + connections.put(socksConnection.getCid(), socksConnection); + socksConnection.connect(new OnSocksConnection() { + + @Override + public void failed() { + Log.d("xmppService","socks5 failed"); + } + + @Override + public void established() { + if (candidatesUsedByCounterpart.contains(socksConnection.getCid())) { + if (status!=STATUS_TRANSMITTING) { + connect(socksConnection); + } else { + Log.d("xmppService","ignoring cuz already transmitting"); + } + } else { + sendCandidateUsed(socksConnection.getCid()); + } + } + }); + } + } + + private void disconnect() { + Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator(); + while (it.hasNext()) { + Entry<String, SocksConnection> pairs = it.next(); + pairs.getValue().disconnect(); + it.remove(); + } + } + + private void sendCandidateUsed(String cid) { + JinglePacket packet = bootstrapPacket(); + packet.setAction("transport-info"); + Content content = new Content(); + content.setUsedCandidate(this.content.getTransportId(), cid); + packet.setContent(content); + Log.d("xmppService","send using candidate: "+packet.toString()); + this.account.getXmppConnection().sendIqPacket(packet, responseListener); + } + + public String getInitiator() { + return this.initiator; + } + + public String getResponder() { + return this.responder; + } + + public int getStatus() { + return this.status; + } + + private boolean mergeCandidate(Element candidate) { + for(Element c : this.candidates) { + if (c.getAttribute("host").equals(candidate.getAttribute("host"))&&(c.getAttribute("port").equals(candidate.getAttribute("port")))) { + return false; + } + } + this.candidates.add(candidate); + return true; + } + + private void mergeCandidates(List<Element> canditates) { + for(Element c : canditates) { + this.mergeCandidate(c); + } + } +} diff --git a/src/eu/siacs/conversations/xmpp/jingle/JingleConnectionManager.java b/src/eu/siacs/conversations/xmpp/jingle/JingleConnectionManager.java new file mode 100644 index 00000000..972489d0 --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/JingleConnectionManager.java @@ -0,0 +1,140 @@ +package eu.siacs.conversations.xmpp.jingle; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import android.util.Log; + +import eu.siacs.conversations.entities.Account; +import eu.siacs.conversations.entities.Message; +import eu.siacs.conversations.services.XmppConnectionService; +import eu.siacs.conversations.xml.Element; +import eu.siacs.conversations.xmpp.OnIqPacketReceived; +import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; +import eu.siacs.conversations.xmpp.stanzas.IqPacket; + +public class JingleConnectionManager { + + private XmppConnectionService xmppConnectionService; + + private List<JingleConnection> connections = new ArrayList<JingleConnection>(); // make + // concurrent + + private ConcurrentHashMap<String, Element> primaryCandidates = new ConcurrentHashMap<String, Element>(); + + private SecureRandom random = new SecureRandom(); + + public JingleConnectionManager(XmppConnectionService service) { + this.xmppConnectionService = service; + } + + public void deliverPacket(Account account, JinglePacket packet) { + if (packet.isAction("session-initiate")) { + JingleConnection connection = new JingleConnection(this); + connection.init(account,packet); + connections.add(connection); + } else { + for (JingleConnection connection : connections) { + if (connection.getAccountJid().equals(account.getFullJid()) && connection + .getSessionId().equals(packet.getSessionId()) && connection + .getCounterPart().equals(packet.getFrom())) { + connection.deliverPacket(packet); + return; + } else { + Log.d("xmppService","no match sid:"+connection.getSessionId()+"="+packet.getSessionId()+" counterpart:"+connection.getCounterPart()+"="+packet.getFrom()+" account:"+connection.getAccountJid()+"="+packet.getTo()); + } + } + Log.d("xmppService","delivering packet failed "+packet.toString()); + } + } + + public JingleConnection createNewConnection(Message message) { + JingleConnection connection = new JingleConnection(this); + connection.init(message); + connections.add(connection); + return connection; + } + + public JingleConnection createNewConnection(JinglePacket packet) { + JingleConnection connection = new JingleConnection(this); + connections.add(connection); + return connection; + } + + public XmppConnectionService getXmppConnectionService() { + return this.xmppConnectionService; + } + + public void getPrimaryCandidate(Account account, + final OnPrimaryCandidateFound listener) { + if (!this.primaryCandidates.containsKey(account.getJid())) { + String xmlns = "http://jabber.org/protocol/bytestreams"; + final String proxy = account.getXmppConnection() + .findDiscoItemByFeature(xmlns); + if (proxy != null) { + IqPacket iq = new IqPacket(IqPacket.TYPE_GET); + iq.setTo(proxy); + iq.query(xmlns); + account.getXmppConnection().sendIqPacket(iq, + new OnIqPacketReceived() { + + @Override + public void onIqPacketReceived(Account account, + IqPacket packet) { + Element streamhost = packet + .query() + .findChild("streamhost", + "http://jabber.org/protocol/bytestreams"); + if (streamhost != null) { + Log.d("xmppService", "streamhost found " + + streamhost.toString()); + Element candidate = new Element("candidate"); + candidate.setAttribute("cid", + nextRandomId()); + candidate.setAttribute("host", + streamhost.getAttribute("host")); + candidate.setAttribute("port", + streamhost.getAttribute("port")); + candidate.setAttribute("type", "proxy"); + candidate.setAttribute("jid", proxy); + candidate + .setAttribute("priority", "655360"); + primaryCandidates.put(account.getJid(), + candidate); + listener.onPrimaryCandidateFound(true, + candidate); + } else { + listener.onPrimaryCandidateFound(false, + null); + } + } + }); + } else { + listener.onPrimaryCandidateFound(false, null); + } + + } else { + listener.onPrimaryCandidateFound(true, + this.primaryCandidates.get(account.getJid())); + } + } + + public String getPrimaryCandidateId(Account account) { + if (this.primaryCandidates.containsKey(account.getJid())) { + return this.primaryCandidates.get(account.getJid()).getAttribute("cid"); + } else { + return null; + } + } + + public String nextRandomId() { + return new BigInteger(50, random).toString(32); + } + + public long getAutoAcceptFileSize() { + return this.xmppConnectionService.getPreferences().getLong("auto_accept_file_size", 0); + } +} diff --git a/src/eu/siacs/conversations/xmpp/jingle/JingleFile.java b/src/eu/siacs/conversations/xmpp/jingle/JingleFile.java new file mode 100644 index 00000000..21cbd716 --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/JingleFile.java @@ -0,0 +1,35 @@ +package eu.siacs.conversations.xmpp.jingle; + +import java.io.File; + +public class JingleFile extends File { + + private static final long serialVersionUID = 2247012619505115863L; + + private long expectedSize = 0; + private String sha1sum; + + public JingleFile(String path) { + super(path); + } + + public long getSize() { + return super.length(); + } + + public long getExpectedSize() { + return this.expectedSize; + } + + public void setExpectedSize(long size) { + this.expectedSize = size; + } + + public String getSha1Sum() { + return this.sha1sum; + } + + public void setSha1Sum(String sum) { + this.sha1sum = sum; + } +} diff --git a/src/eu/siacs/conversations/xmpp/jingle/OnFileTransmitted.java b/src/eu/siacs/conversations/xmpp/jingle/OnFileTransmitted.java new file mode 100644 index 00000000..fd5fd2f7 --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/OnFileTransmitted.java @@ -0,0 +1,5 @@ +package eu.siacs.conversations.xmpp.jingle; + +public interface OnFileTransmitted { + public void onFileTransmitted(JingleFile file); +} diff --git a/src/eu/siacs/conversations/xmpp/OnJinglePacketReceived.java b/src/eu/siacs/conversations/xmpp/jingle/OnJinglePacketReceived.java index 6705e309..2aaf62a1 100644 --- a/src/eu/siacs/conversations/xmpp/OnJinglePacketReceived.java +++ b/src/eu/siacs/conversations/xmpp/jingle/OnJinglePacketReceived.java @@ -1,7 +1,8 @@ -package eu.siacs.conversations.xmpp; +package eu.siacs.conversations.xmpp.jingle; import eu.siacs.conversations.entities.Account; -import eu.siacs.conversations.xmpp.stanzas.jingle.JinglePacket; +import eu.siacs.conversations.xmpp.PacketReceived; +import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; public interface OnJinglePacketReceived extends PacketReceived { public void onJinglePacketReceived(Account account, JinglePacket packet); diff --git a/src/eu/siacs/conversations/xmpp/jingle/OnPrimaryCandidateFound.java b/src/eu/siacs/conversations/xmpp/jingle/OnPrimaryCandidateFound.java new file mode 100644 index 00000000..9e00954f --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/OnPrimaryCandidateFound.java @@ -0,0 +1,7 @@ +package eu.siacs.conversations.xmpp.jingle; + +import eu.siacs.conversations.xml.Element; + +public interface OnPrimaryCandidateFound { + public void onPrimaryCandidateFound(boolean success, Element canditate); +} diff --git a/src/eu/siacs/conversations/xmpp/jingle/OnSocksConnection.java b/src/eu/siacs/conversations/xmpp/jingle/OnSocksConnection.java new file mode 100644 index 00000000..88771997 --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/OnSocksConnection.java @@ -0,0 +1,6 @@ +package eu.siacs.conversations.xmpp.jingle; + +public interface OnSocksConnection { + public void failed(); + public void established(); +} diff --git a/src/eu/siacs/conversations/xmpp/jingle/SocksConnection.java b/src/eu/siacs/conversations/xmpp/jingle/SocksConnection.java new file mode 100644 index 00000000..bf7c87ad --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/SocksConnection.java @@ -0,0 +1,212 @@ +package eu.siacs.conversations.xmpp.jingle; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.net.UnknownHostException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +import eu.siacs.conversations.utils.CryptoHelper; +import eu.siacs.conversations.xml.Element; + +import android.util.Log; +import android.widget.Button; + +public class SocksConnection { + private Socket socket; + private String host; + private String jid; + private String cid; + private int port; + private boolean isProxy = false; + private String destination; + private OutputStream outputStream; + private InputStream inputStream; + private boolean isEstablished = false; + + public SocksConnection(JingleConnection jingleConnection, Element candidate) { + this.cid = candidate.getAttribute("cid"); + this.host = candidate.getAttribute("host"); + this.port = Integer.parseInt(candidate.getAttribute("port")); + String type = candidate.getAttribute("type"); + this.jid = candidate.getAttribute("jid"); + this.isProxy = "proxy".equalsIgnoreCase(type); + try { + MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); + StringBuilder destBuilder = new StringBuilder(); + destBuilder.append(jingleConnection.getSessionId()); + destBuilder.append(jingleConnection.getInitiator()); + destBuilder.append(jingleConnection.getResponder()); + mDigest.reset(); + this.destination = CryptoHelper.bytesToHex(mDigest + .digest(destBuilder.toString().getBytes())); + } catch (NoSuchAlgorithmException e) { + + } + } + + public void connect(final OnSocksConnection callback) { + new Thread(new Runnable() { + + @Override + public void run() { + try { + socket = new Socket(host, port); + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); + byte[] login = { 0x05, 0x01, 0x00 }; + byte[] expectedReply = { 0x05, 0x00 }; + byte[] reply = new byte[2]; + outputStream.write(login); + inputStream.read(reply); + if (Arrays.equals(reply, expectedReply)) { + String connect = "" + '\u0005' + '\u0001' + '\u0000' + '\u0003' + + '\u0028' + destination + '\u0000' + '\u0000'; + outputStream.write(connect.getBytes()); + byte[] result = new byte[2]; + inputStream.read(result); + int status = result[1]; + if (status == 0) { + Log.d("xmppService", "established connection with "+host + ":" + port + + "/" + destination); + isEstablished = true; + callback.established(); + } else { + callback.failed(); + } + } else { + socket.close(); + callback.failed(); + } + } catch (UnknownHostException e) { + callback.failed(); + } catch (IOException e) { + callback.failed(); + } + } + }).start(); + + } + + public void send(final JingleFile file, final OnFileTransmitted callback) { + new Thread(new Runnable() { + + @Override + public void run() { + FileInputStream fileInputStream = null; + try { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.reset(); + fileInputStream = new FileInputStream(file); + int count; + byte[] buffer = new byte[8192]; + while ((count = fileInputStream.read(buffer)) > 0) { + outputStream.write(buffer, 0, count); + digest.update(buffer, 0, count); + } + outputStream.flush(); + file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest())); + if (callback!=null) { + callback.onFileTransmitted(file); + } + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + try { + if (fileInputStream != null) { + fileInputStream.close(); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + }).start(); + + } + + public void receive(final JingleFile file, final OnFileTransmitted callback) { + new Thread(new Runnable() { + + @Override + public void run() { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.reset(); + inputStream.skip(45); + file.getParentFile().mkdirs(); + file.createNewFile(); + FileOutputStream fileOutputStream = new FileOutputStream(file); + long remainingSize = file.getExpectedSize(); + byte[] buffer = new byte[8192]; + int count = buffer.length; + while(remainingSize > 0) { + Log.d("xmppService","remaning size:"+remainingSize); + if (remainingSize<=count) { + count = (int) remainingSize; + } + count = inputStream.read(buffer, 0, count); + fileOutputStream.write(buffer, 0, count); + digest.update(buffer, 0, count); + remainingSize-=count; + } + fileOutputStream.flush(); + fileOutputStream.close(); + file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest())); + Log.d("xmppService","transmitted filename was: "+file.getAbsolutePath()); + callback.onFileTransmitted(file); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }).start(); + } + + public boolean isProxy() { + return this.isProxy; + } + + public String getJid() { + return this.jid; + } + + public String getCid() { + return this.cid; + } + + public void disconnect() { + if (this.socket!=null) { + try { + this.socket.close(); + Log.d("xmppService","cloesd socket with "+this.host); + } catch (IOException e) { + Log.d("xmppService","error closing socket with "+this.host); + } + } + } + + public boolean isEstablished() { + return this.isEstablished; + } +} diff --git a/src/eu/siacs/conversations/xmpp/jingle/stanzas/Content.java b/src/eu/siacs/conversations/xmpp/jingle/stanzas/Content.java new file mode 100644 index 00000000..79e04610 --- /dev/null +++ b/src/eu/siacs/conversations/xmpp/jingle/stanzas/Content.java @@ -0,0 +1,98 @@ +package eu.siacs.conversations.xmpp.jingle.stanzas; + +import java.util.ArrayList; +import java.util.List; + +import eu.siacs.conversations.xml.Element; +import eu.siacs.conversations.xmpp.jingle.JingleFile; + +public class Content extends Element { + private Content(String name) { + super(name); + } + + public Content() { + super("content"); + } + + public void setFileOffer(JingleFile actualFile) { + Element description = this.addChild("description", "urn:xmpp:jingle:apps:file-transfer:3"); + Element offer = description.addChild("offer"); + Element file = offer.addChild("file"); + file.addChild("size").setContent(""+actualFile.getSize()); + file.addChild("name").setContent(actualFile.getName()); + } + + public Element getFileOffer() { + Element description = this.findChild("description", "urn:xmpp:jingle:apps:file-transfer:3"); + if (description==null) { + return null; + } + Element offer = description.findChild("offer"); + if (offer==null) { + return null; + } + return offer.findChild("file"); + } + + public void setCandidates(String transportId, List<Element> canditates) { + Element transport = this.findChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + if (transport==null) { + transport = this.addChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + } + transport.setAttribute("sid", transportId); + transport.clearChildren(); + for(Element canditate : canditates) { + transport.addChild(canditate); + } + } + + public List<Element> getCanditates() { + Element transport = this.findChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + if (transport==null) { + return new ArrayList<Element>(); + } else { + return transport.getChildren(); + } + } + + public String getTransportId() { + Element transport = this.findChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + if (transport==null) { + return null; + } + return transport.getAttribute("sid"); + } + + public String getUsedCandidate() { + Element transport = this.findChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + if (transport==null) { + return null; + } + Element usedCandidate = transport.findChild("candidate-used"); + if (usedCandidate==null) { + return null; + } else { + return usedCandidate.getAttribute("cid"); + } + } + + public void setUsedCandidate(String transportId, String cid) { + Element transport = this.findChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + if (transport==null) { + transport = this.addChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + } + transport.setAttribute("sid", transportId); + transport.clearChildren(); + Element usedCandidate = transport.addChild("candidate-used"); + usedCandidate.setAttribute("cid",cid); + } + + public void addCandidate(Element candidate) { + Element transport = this.findChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + if (transport==null) { + transport = this.addChild("transport", "urn:xmpp:jingle:transports:s5b:1"); + } + transport.addChild(candidate); + } +} diff --git a/src/eu/siacs/conversations/xmpp/stanzas/jingle/JinglePacket.java b/src/eu/siacs/conversations/xmpp/jingle/stanzas/JinglePacket.java index 51c60d1f..55700609 100644 --- a/src/eu/siacs/conversations/xmpp/stanzas/jingle/JinglePacket.java +++ b/src/eu/siacs/conversations/xmpp/jingle/stanzas/JinglePacket.java @@ -1,4 +1,4 @@ -package eu.siacs.conversations.xmpp.stanzas.jingle; +package eu.siacs.conversations.xmpp.jingle.stanzas; import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xmpp.stanzas.IqPacket; @@ -6,6 +6,7 @@ import eu.siacs.conversations.xmpp.stanzas.IqPacket; public class JinglePacket extends IqPacket { Content content = null; Reason reason = null; + Element jingle = new Element("jingle"); @Override public Element addChild(Element child) { @@ -22,27 +23,36 @@ public class JinglePacket extends IqPacket { this.reason.setChildren(reasonElement.getChildren()); this.reason.setAttributes(reasonElement.getAttributes()); } - this.build(); - this.findChild("jingle").setAttributes(child.getAttributes()); + this.jingle.setAttributes(child.getAttributes()); } return child; } public JinglePacket setContent(Content content) { this.content = content; - this.build(); return this; } + public Content getJingleContent() { + if (this.content==null) { + this.content = new Content(); + } + return this.content; + } + public JinglePacket setReason(Reason reason) { this.reason = reason; - this.build(); return this; } + public Reason getReason() { + return this.reason; + } + private void build() { this.children.clear(); - Element jingle = addChild("jingle", "urn:xmpp:jingle:1"); + this.jingle.clearChildren(); + this.jingle.setAttribute("xmlns", "urn:xmpp:jingle:1"); if (this.content!=null) { jingle.addChild(this.content); } @@ -50,5 +60,36 @@ public class JinglePacket extends IqPacket { jingle.addChild(this.reason); } this.children.add(jingle); + this.setAttribute("type", "set"); + } + + public String getSessionId() { + return this.jingle.getAttribute("sid"); + } + + public void setSessionId(String sid) { + this.jingle.setAttribute("sid", sid); + } + + @Override + public String toString() { + this.build(); + return super.toString(); + } + + public void setAction(String action) { + this.jingle.setAttribute("action", action); + } + + public String getAction() { + return this.jingle.getAttribute("action"); + } + + public void setInitiator(String initiator) { + this.jingle.setAttribute("initiator", initiator); + } + + public boolean isAction(String action) { + return action.equalsIgnoreCase(this.getAction()); } } diff --git a/src/eu/siacs/conversations/xmpp/stanzas/jingle/Reason.java b/src/eu/siacs/conversations/xmpp/jingle/stanzas/Reason.java index 35b81655..195e0db7 100644 --- a/src/eu/siacs/conversations/xmpp/stanzas/jingle/Reason.java +++ b/src/eu/siacs/conversations/xmpp/jingle/stanzas/Reason.java @@ -1,4 +1,4 @@ -package eu.siacs.conversations.xmpp.stanzas.jingle; +package eu.siacs.conversations.xmpp.jingle.stanzas; import eu.siacs.conversations.xml.Element; diff --git a/src/eu/siacs/conversations/xmpp/stanzas/IqPacket.java b/src/eu/siacs/conversations/xmpp/stanzas/IqPacket.java index 3ab3b6c3..9e288454 100644 --- a/src/eu/siacs/conversations/xmpp/stanzas/IqPacket.java +++ b/src/eu/siacs/conversations/xmpp/stanzas/IqPacket.java @@ -63,5 +63,13 @@ public class IqPacket extends AbstractStanza { return 1000; } } + + public IqPacket generateRespone(int type) { + IqPacket packet = new IqPacket(type); + packet.setFrom(this.getTo()); + packet.setTo(this.getFrom()); + packet.setId(this.getId()); + return packet; + } } diff --git a/src/eu/siacs/conversations/xmpp/stanzas/jingle/Content.java b/src/eu/siacs/conversations/xmpp/stanzas/jingle/Content.java deleted file mode 100644 index ebd212b8..00000000 --- a/src/eu/siacs/conversations/xmpp/stanzas/jingle/Content.java +++ /dev/null @@ -1,13 +0,0 @@ -package eu.siacs.conversations.xmpp.stanzas.jingle; - -import eu.siacs.conversations.xml.Element; - -public class Content extends Element { - private Content(String name) { - super(name); - } - - public Content() { - super("content"); - } -} |