1
0
mirror of https://github.com/nerzhul/ownCloud-SMS-App.git synced 2025-06-07 16:06:18 +00:00

SmsBuffer is now working, replace json objects with the SmsBuffer on sync

This commit is contained in:
Loic Blot 2017-08-23 00:28:34 +02:00 committed by Loïc Blot
parent 47c2923d0e
commit 5e6a1fc28e
13 changed files with 313 additions and 142 deletions

View File

@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.5.0)
set (SRC_FILES set (SRC_FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/httpclient.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/httpclient.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/json.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/nativesms.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/nativesms.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/smsbuffer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/smsbuffer.cpp
) )

68
src/main/cpp/json.cpp Normal file
View File

@ -0,0 +1,68 @@
/**
* Copyright (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "json.h"
#include <iomanip>
#include <sstream>
namespace json {
std::string escape_string(const char *str)
{
std::string result;
// Create a sufficient buffer to escape all chars
result.reserve(strlen(str) * 2 + 3);
result += "\"";
for (const char *c = str; *c != 0; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\t':
result += "\\t";
break;
case '\n':
result += "\\n";
break;
case '\f':
result += "\\f";
break;
case '\r':
result += "\\r";
break;
default:
if (is_control_character(*c)) {
std::stringstream oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
} else {
result += *c;
}
break;
}
}
result += "\"";
return result;
}
}

29
src/main/cpp/json.h Normal file
View File

@ -0,0 +1,29 @@
/**
* Copyright (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
namespace json {
static inline bool is_control_character(char ch)
{ return ch > 0 && ch <= 0x1F; }
std::string escape_string(const char *str);
}

View File

@ -16,7 +16,10 @@
*/ */
#include <android/log.h> #include <android/log.h>
#include <cassert>
#include <iomanip>
#include "smsbuffer.h" #include "smsbuffer.h"
#include "json.h"
#define LOG_TAG "SmsBuffer" #define LOG_TAG "SmsBuffer"
const char *SmsBuffer::classPathName = "fr/unix_experience/owncloud_sms/jni/SmsBuffer"; const char *SmsBuffer::classPathName = "fr/unix_experience/owncloud_sms/jni/SmsBuffer";
@ -26,11 +29,21 @@ JNINativeMethod SmsBuffer::methods[] =
{ {
DECL_JNIMETHOD(createNativeObject, "()J") DECL_JNIMETHOD(createNativeObject, "()J")
DECL_JNIMETHOD(deleteNativeObject, "(J)V") DECL_JNIMETHOD(deleteNativeObject, "(J)V")
DECL_JNIMETHOD(push, "(JI)V") DECL_JNIMETHOD(empty, "(J)Z")
DECL_JNIMETHOD(asRawJsonString, "(J)Ljava/lang/String;")
DECL_JNIMETHOD(push,
"(JIIIJLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")
DECL_JNIMETHOD(print, "(J)V") DECL_JNIMETHOD(print, "(J)V")
}; };
DECL_METHODSIZE(SmsBuffer) DECL_METHODSIZE(SmsBuffer)
#define SMSBUFFER_CAST \
SmsBuffer *me = reinterpret_cast<SmsBuffer *>(ptr); \
if (!me) { \
__android_log_print(ANDROID_LOG_FATAL, LOG_TAG, "It's not a SmsBuffer!"); \
assert(false); \
}
jlong SmsBuffer::createNativeObject(JNIEnv *env, jobject self) jlong SmsBuffer::createNativeObject(JNIEnv *env, jobject self)
{ {
return reinterpret_cast<jlong>(new SmsBuffer()); return reinterpret_cast<jlong>(new SmsBuffer());
@ -42,27 +55,25 @@ void SmsBuffer::deleteNativeObject(JNIEnv *env, jobject self, jlong ptr)
delete reinterpret_cast<SmsBuffer *>(ptr); delete reinterpret_cast<SmsBuffer *>(ptr);
} }
SmsBuffer::SmsBuffer()
{
}
void SmsBuffer::reset_buffer() void SmsBuffer::reset_buffer()
{ {
m_buffer.clear(); m_buffer.clear();
m_buffer_empty = true; m_buffer_empty = true;
m_sms_count = 0;
} }
void SmsBuffer::push(JNIEnv *env, jobject self, jlong ptr, jint mailbox_id)
void SmsBuffer::push(JNIEnv *env, jobject self, jlong ptr, jint msg_id, jint mailbox_id, jint type,
jlong date, jstring address, jstring body, jstring read, jstring seen)
{ {
SmsBuffer *me = reinterpret_cast<SmsBuffer *>(ptr); SMSBUFFER_CAST
if (!me) { me->_push(msg_id, mailbox_id, type, date, env->GetStringUTFChars(address, NULL),
__android_log_print(ANDROID_LOG_FATAL, LOG_TAG, "It's not a SmsBuffer!"); env->GetStringUTFChars(body, NULL), env->GetStringUTFChars(read, NULL),
return; env->GetStringUTFChars(seen, NULL));
} }
me->_push(mailbox_id); void SmsBuffer::_push(int msg_id, int mailbox_id, int type,
} long date, const char *address, const char *body, const char *read,
const char *seen)
void SmsBuffer::_push(int mailbox_id)
{ {
// If buffer is not empty, we are joining messages // If buffer is not empty, we are joining messages
if (!m_buffer_empty) { if (!m_buffer_empty) {
@ -71,24 +82,55 @@ void SmsBuffer::_push(int mailbox_id)
// Else, we are starting array // Else, we are starting array
else { else {
m_buffer << "["; m_buffer << "[";
m_buffer_empty = true; m_buffer_empty = false;
} }
m_buffer << "{\"mbox\": " << mailbox_id << "}"; m_buffer << "{\"_id\": " << msg_id << ", "
<< "\"mbox\": " << mailbox_id << ", "
<< "\"type\": " << type << ", "
<< "\"date\": " << date << ", "
<< "\"body\": " << json::escape_string(body) << ", "
<< "\"address\": " << json::escape_string(address) << ", "
<< "\"read\": " << json::escape_string(read) << ", "
<< "\"seen\": " << json::escape_string(seen)
<< "}";
m_sms_count++;
}
jboolean SmsBuffer::empty(JNIEnv *env, jobject self, jlong ptr)
{
SMSBUFFER_CAST
return (jboolean) (me->_empty() ? 1 : 0);
}
bool SmsBuffer::_empty() const
{
return m_buffer_empty;
} }
void SmsBuffer::print(JNIEnv *env, jobject self, jlong ptr) void SmsBuffer::print(JNIEnv *env, jobject self, jlong ptr)
{ {
SmsBuffer *me = reinterpret_cast<SmsBuffer *>(ptr); SMSBUFFER_CAST
if (!me) {
__android_log_print(ANDROID_LOG_FATAL, LOG_TAG, "It's not a SmsBuffer!");
return;
}
me->_print(); me->_print();
} }
void SmsBuffer::_print() void SmsBuffer::_print()
{ {
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "SmsBuffer content: '%s'", m_buffer.str().c_str()); __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "SmsBuffer content: '%s'",
m_buffer.str().c_str());
}
jstring SmsBuffer::asRawJsonString(JNIEnv *env, jobject self, jlong ptr)
{
SMSBUFFER_CAST
std::string result;
me->as_raw_json_string(result);
return env->NewStringUTF(result.c_str());
}
void SmsBuffer::as_raw_json_string(std::string &result)
{
std::stringstream ss;
ss << "{\"smsCount\": " << m_sms_count << ", \"smsDatas\": " << m_buffer.str() << "]}";
result = ss.str();
} }

View File

@ -24,21 +24,46 @@
class SmsBuffer class SmsBuffer
{ {
public: public:
SmsBuffer(); SmsBuffer() = default;
~SmsBuffer() = default;
JNIEXPORT static jlong JNICALL createNativeObject(JNIEnv *env, jobject self); JNIEXPORT static jlong JNICALL createNativeObject(JNIEnv *env, jobject self);
JNIEXPORT static void JNICALL deleteNativeObject(JNIEnv *env, jobject self, jlong ptr); JNIEXPORT static void JNICALL deleteNativeObject(JNIEnv *env, jobject self, jlong ptr);
JNIEXPORT static void JNICALL push(JNIEnv *env, jobject self, jlong ptr, jint mailbox_id); /*
void _push(int mailbox_id); * push method
*/
JNIEXPORT static void JNICALL push(JNIEnv *env, jobject self, jlong ptr, jint msg_id,
jint mailbox_id, jint type, jlong date, jstring address,
jstring body, jstring read, jstring seen);
void _push(int msg_id, int mailbox_id, int type,
long date, const char *address, const char *body, const char *read,
const char *seen);
/*
* empty method
*/
JNIEXPORT static jboolean JNICALL empty(JNIEnv *env, jobject self, jlong ptr);
bool _empty() const;
/*
* print method
*/
JNIEXPORT static void JNICALL print(JNIEnv *env, jobject self, jlong ptr); JNIEXPORT static void JNICALL print(JNIEnv *env, jobject self, jlong ptr);
void _print(); void _print();
/*
* asRawJsonString method
*/
JNIEXPORT static jstring JNICALL asRawJsonString(JNIEnv *env, jobject self, jlong ptr);
void as_raw_json_string(std::string &result);
DECL_JNICLASSATTRS DECL_JNICLASSATTRS
private: private:
void reset_buffer(); void reset_buffer();
std::stringstream m_buffer; std::stringstream m_buffer;
uint32_t m_sms_count{0};
bool m_buffer_empty{true}; bool m_buffer_empty{true};
}; };

View File

@ -44,8 +44,6 @@ import android.view.MenuItem;
import android.view.Window; import android.view.Window;
import android.widget.Toast; import android.widget.Toast;
import org.json.JSONArray;
import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.R;
import fr.unix_experience.owncloud_sms.activities.remote_account.AccountListActivity; import fr.unix_experience.owncloud_sms.activities.remote_account.AccountListActivity;
import fr.unix_experience.owncloud_sms.engine.ASyncSMSSync.SyncTask; import fr.unix_experience.owncloud_sms.engine.ASyncSMSSync.SyncTask;
@ -53,6 +51,7 @@ import fr.unix_experience.owncloud_sms.engine.AndroidSmsFetcher;
import fr.unix_experience.owncloud_sms.engine.ConnectivityMonitor; import fr.unix_experience.owncloud_sms.engine.ConnectivityMonitor;
import fr.unix_experience.owncloud_sms.enums.OCSMSNotificationType; import fr.unix_experience.owncloud_sms.enums.OCSMSNotificationType;
import fr.unix_experience.owncloud_sms.enums.PermissionID; import fr.unix_experience.owncloud_sms.enums.PermissionID;
import fr.unix_experience.owncloud_sms.jni.SmsBuffer;
import fr.unix_experience.owncloud_sms.notifications.OCSMSNotificationUI; import fr.unix_experience.owncloud_sms.notifications.OCSMSNotificationUI;
import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs; import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs;
import fr.unix_experience.owncloud_sms.prefs.PermissionChecker; import fr.unix_experience.owncloud_sms.prefs.PermissionChecker;
@ -212,10 +211,10 @@ public class MainActivity extends AppCompatActivity
} }
// Now fetch messages since last stored date // Now fetch messages since last stored date
JSONArray smsList = new JSONArray(); SmsBuffer smsBuffer = new SmsBuffer();
new AndroidSmsFetcher(ctx).bufferMessagesSinceDate(smsList, (long) 0); new AndroidSmsFetcher(ctx).bufferMessagesSinceDate(smsBuffer, (long) 0);
if (smsList.length() == 0) { if (smsBuffer.empty()) {
Toast.makeText(ctx, ctx.getString(R.string.nothing_to_sync), Toast.LENGTH_SHORT).show(); Toast.makeText(ctx, ctx.getString(R.string.nothing_to_sync), Toast.LENGTH_SHORT).show();
Log.v(MainActivity.TAG, "Finish syncAllMessages(): no sms"); Log.v(MainActivity.TAG, "Finish syncAllMessages(): no sms");
return; return;
@ -225,7 +224,7 @@ public class MainActivity extends AppCompatActivity
OCSMSNotificationUI.notify(ctx, ctx.getString(R.string.sync_title), OCSMSNotificationUI.notify(ctx, ctx.getString(R.string.sync_title),
ctx.getString(R.string.sync_inprogress), OCSMSNotificationType.SYNC.ordinal()); ctx.getString(R.string.sync_inprogress), OCSMSNotificationType.SYNC.ordinal());
} }
new SyncTask(getApplicationContext(), smsList).execute(); new SyncTask(getApplicationContext(), smsBuffer).execute();
Log.v(MainActivity.TAG, "Finish syncAllMessages()"); Log.v(MainActivity.TAG, "Finish syncAllMessages()");
} }

View File

@ -25,8 +25,6 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.util.Log; import android.util.Log;
import org.json.JSONArray;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.R;
@ -34,6 +32,7 @@ import fr.unix_experience.owncloud_sms.engine.ASyncSMSSync;
import fr.unix_experience.owncloud_sms.engine.AndroidSmsFetcher; import fr.unix_experience.owncloud_sms.engine.AndroidSmsFetcher;
import fr.unix_experience.owncloud_sms.engine.ConnectivityMonitor; import fr.unix_experience.owncloud_sms.engine.ConnectivityMonitor;
import fr.unix_experience.owncloud_sms.enums.PermissionID; import fr.unix_experience.owncloud_sms.enums.PermissionID;
import fr.unix_experience.owncloud_sms.jni.SmsBuffer;
import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs; import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs;
import fr.unix_experience.owncloud_sms.prefs.PermissionChecker; import fr.unix_experience.owncloud_sms.prefs.PermissionChecker;
@ -82,14 +81,14 @@ public class ConnectivityChanged extends BroadcastReceiver implements ASyncSMSSy
Log.i(ConnectivityChanged.TAG,"Synced Last:" + lastMessageSynced); Log.i(ConnectivityChanged.TAG,"Synced Last:" + lastMessageSynced);
// Now fetch messages since last stored date // Now fetch messages since last stored date
JSONArray smsList = new JSONArray(); SmsBuffer smsBuffer = new SmsBuffer();
new AndroidSmsFetcher(context).bufferMessagesSinceDate(smsList, lastMessageSynced); new AndroidSmsFetcher(context).bufferMessagesSinceDate(smsBuffer, lastMessageSynced);
AtomicReference<ConnectivityMonitor> cMon = new AtomicReference<>(new ConnectivityMonitor(context)); AtomicReference<ConnectivityMonitor> cMon = new AtomicReference<>(new ConnectivityMonitor(context));
// Synchronize if network is valid and there are SMS // Synchronize if network is valid and there are SMS
if (cMon.get().isValid() && (smsList.length() > 0)) { if (cMon.get().isValid() && !smsBuffer.empty()) {
new SyncTask(context, smsList).execute(); new SyncTask(context, smsBuffer).execute();
} }
} }

View File

@ -23,18 +23,17 @@ import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.util.Log; import android.util.Log;
import org.json.JSONArray;
import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.R;
import fr.unix_experience.owncloud_sms.enums.OCSMSNotificationType; import fr.unix_experience.owncloud_sms.enums.OCSMSNotificationType;
import fr.unix_experience.owncloud_sms.exceptions.OCSyncException; import fr.unix_experience.owncloud_sms.exceptions.OCSyncException;
import fr.unix_experience.owncloud_sms.jni.SmsBuffer;
import fr.unix_experience.owncloud_sms.notifications.OCSMSNotificationUI; import fr.unix_experience.owncloud_sms.notifications.OCSMSNotificationUI;
public interface ASyncSMSSync { public interface ASyncSMSSync {
class SyncTask extends AsyncTask<Void, Void, Void> { class SyncTask extends AsyncTask<Void, Void, Void> {
public SyncTask(Context context, JSONArray smsList) { public SyncTask(Context context, SmsBuffer smsBuffer) {
_context = context; _context = context;
_smsList = smsList; _smsBuffer = smsBuffer;
} }
@Override @Override
@ -49,7 +48,7 @@ public interface ASyncSMSSync {
for (Account element : myAccountList) { for (Account element : myAccountList) {
try { try {
OCSMSOwnCloudClient _client = new OCSMSOwnCloudClient(_context, element); OCSMSOwnCloudClient _client = new OCSMSOwnCloudClient(_context, element);
_client.doPushRequest(_smsList); _client.doPushRequest(_smsBuffer);
OCSMSNotificationUI.cancel(_context); OCSMSNotificationUI.cancel(_context);
} catch (IllegalStateException e) { // Fail to read account data } catch (IllegalStateException e) { // Fail to read account data
OCSMSNotificationUI.notify(_context, _context.getString(R.string.fatal_error), OCSMSNotificationUI.notify(_context, _context.getString(R.string.fatal_error),
@ -66,7 +65,7 @@ public interface ASyncSMSSync {
} }
private final Context _context; private final Context _context;
private final JSONArray _smsList; private final SmsBuffer _smsBuffer;
} }
String TAG = ASyncSMSSync.class.getSimpleName(); String TAG = ASyncSMSSync.class.getSimpleName();

View File

@ -39,13 +39,13 @@ public class AndroidSmsFetcher {
_existingDraftsMessages = null; _existingDraftsMessages = null;
} }
void fetchAllMessages(JSONArray result) { void fetchAllMessages(SmsBuffer result) {
bufferMailboxMessages(result, MailboxID.INBOX); bufferMailboxMessages(result, MailboxID.INBOX);
bufferMailboxMessages(result, MailboxID.SENT); bufferMailboxMessages(result, MailboxID.SENT);
bufferMailboxMessages(result, MailboxID.DRAFTS); bufferMailboxMessages(result, MailboxID.DRAFTS);
} }
private void readMailBox(Cursor c, JSONArray result, MailboxID mbID) { private void readMailBox(Cursor c, SmsBuffer smsBuffer, MailboxID mbID) {
do { do {
JSONObject entry = new JSONObject(); JSONObject entry = new JSONObject();
@ -56,10 +56,15 @@ public class AndroidSmsFetcher {
// Mailbox ID is required by server // Mailbox ID is required by server
entry.put("mbox", mbID.ordinal()); entry.put("mbox", mbID.ordinal());
result.put(entry);
SmsBuffer buf = new SmsBuffer(); smsBuffer.push(entry.getInt("_id"),
buf.push(mbID.ordinal()); mbID.ordinal(),
buf.print(); entry.getInt("type"),
entry.getLong("date"),
entry.getString("address"),
entry.getString("body"),
entry.getString("read"),
entry.getString("seen"));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(AndroidSmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e); Log.e(AndroidSmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e);
@ -68,7 +73,7 @@ public class AndroidSmsFetcher {
while (c.moveToNext()); while (c.moveToNext());
} }
private void bufferMailboxMessages(JSONArray result, MailboxID mbID) { private void bufferMailboxMessages(SmsBuffer smsBuffer, MailboxID mbID) {
if ((_context == null)) { if ((_context == null)) {
return; return;
} }
@ -88,14 +93,14 @@ public class AndroidSmsFetcher {
} }
// Reading mailbox // Reading mailbox
readMailBox(c, result, mbID); readMailBox(c, smsBuffer, mbID);
Log.i(AndroidSmsFetcher.TAG, c.getCount() + " messages read from " + mbID.getURI()); Log.i(AndroidSmsFetcher.TAG, c.getCount() + " messages read from " + mbID.getURI());
c.close(); c.close();
} }
// Used by Content Observer // Used by Content Observer
public JSONArray getLastMessage(MailboxID mbID) { public SmsBuffer getLastMessage(MailboxID mbID) {
if ((_context == null)) { if ((_context == null)) {
return null; return null;
} }
@ -107,8 +112,8 @@ public class AndroidSmsFetcher {
} }
// We create a list of strings to store results // We create a list of strings to store results
JSONArray results = new JSONArray();
JSONObject entry = new JSONObject(); JSONObject entry = new JSONObject();
SmsBuffer results = new SmsBuffer();
try { try {
Integer mboxId = -1; Integer mboxId = -1;
@ -126,7 +131,14 @@ public class AndroidSmsFetcher {
*/ */
entry.put("mbox", (mboxId - 1)); entry.put("mbox", (mboxId - 1));
results.put(entry); results.push(entry.getInt("_id"),
mbID.ordinal(),
entry.getInt("type"),
entry.getLong("date"),
entry.getString("address"),
entry.getString("body"),
entry.getString("read"),
entry.getString("seen"));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(AndroidSmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e); Log.e(AndroidSmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e);
} }
@ -137,14 +149,14 @@ public class AndroidSmsFetcher {
} }
// Used by ConnectivityChanged Event // Used by ConnectivityChanged Event
public void bufferMessagesSinceDate(JSONArray result, Long sinceDate) { public void bufferMessagesSinceDate(SmsBuffer smsBuffer, Long sinceDate) {
bufferMessagesSinceDate(result, MailboxID.INBOX, sinceDate); bufferMessagesSinceDate(smsBuffer, MailboxID.INBOX, sinceDate);
bufferMessagesSinceDate(result, MailboxID.SENT, sinceDate); bufferMessagesSinceDate(smsBuffer, MailboxID.SENT, sinceDate);
bufferMessagesSinceDate(result, MailboxID.DRAFTS, sinceDate); bufferMessagesSinceDate(smsBuffer, MailboxID.DRAFTS, sinceDate);
} }
// Used by ConnectivityChanged Event // Used by ConnectivityChanged Event
private void bufferMessagesSinceDate(JSONArray result, MailboxID mbID, Long sinceDate) { private void bufferMessagesSinceDate(SmsBuffer smsBuffer, MailboxID mbID, Long sinceDate) {
Log.i(AndroidSmsFetcher.TAG, "bufferMessagesSinceDate for " + mbID.toString() + " sinceDate " + sinceDate.toString()); Log.i(AndroidSmsFetcher.TAG, "bufferMessagesSinceDate for " + mbID.toString() + " sinceDate " + sinceDate.toString());
if ((_context == null)) { if ((_context == null)) {
return; return;
@ -159,7 +171,7 @@ public class AndroidSmsFetcher {
} }
// Read Mailbox // Read Mailbox
readMailBox(c, result, mbID); readMailBox(c, smsBuffer, mbID);
Log.i(AndroidSmsFetcher.TAG, c.getCount() + " messages read from " + mbID.getURI()); Log.i(AndroidSmsFetcher.TAG, c.getCount() + " messages read from " + mbID.getURI());
c.close(); c.close();
@ -191,7 +203,7 @@ public class AndroidSmsFetcher {
if (tmpDate > _lastMsgDate) { if (tmpDate > _lastMsgDate) {
_lastMsgDate = tmpDate; _lastMsgDate = tmpDate;
} }
entry.put(colName, c.getString(idx)); entry.put(colName, c.getLong(idx));
break; break;
default: default:
entry.put(colName, c.getString(idx)); entry.put(colName, c.getString(idx));

View File

@ -38,6 +38,7 @@ import java.net.ConnectException;
import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.R;
import fr.unix_experience.owncloud_sms.enums.OCSyncErrorType; import fr.unix_experience.owncloud_sms.enums.OCSyncErrorType;
import fr.unix_experience.owncloud_sms.exceptions.OCSyncException; import fr.unix_experience.owncloud_sms.exceptions.OCSyncException;
import fr.unix_experience.owncloud_sms.jni.SmsBuffer;
import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs; import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -94,17 +95,17 @@ public class OCSMSOwnCloudClient {
} }
} }
public void doPushRequest(JSONArray smsList) throws OCSyncException { public void doPushRequest(SmsBuffer smsBuffer) throws OCSyncException {
/* /*
* If we need other API push, set it here * If we need other API push, set it here
*/ */
switch (_serverAPIVersion) { switch (_serverAPIVersion) {
case 1: case 1:
default: doPushRequestV1(smsList); break; default: doPushRequestV1(smsBuffer); break;
} }
} }
private AndroidSmsFetcher collectMessages(JSONArray smsList) throws OCSyncException { private AndroidSmsFetcher collectMessages(SmsBuffer smsBuffer) throws OCSyncException {
JSONObject smsBoxes = new JSONObject(); JSONObject smsBoxes = new JSONObject();
JSONArray inboxSmsList = null, sentSmsList = null, draftsSmsList = null; JSONArray inboxSmsList = null, sentSmsList = null, draftsSmsList = null;
try { try {
@ -141,33 +142,33 @@ public class OCSMSOwnCloudClient {
fetcher.setExistingSentMessages(sentSmsList); fetcher.setExistingSentMessages(sentSmsList);
fetcher.setExistingDraftsMessages(draftsSmsList); fetcher.setExistingDraftsMessages(draftsSmsList);
fetcher.fetchAllMessages(smsList); fetcher.fetchAllMessages(smsBuffer);
return fetcher; return fetcher;
} }
private void doPushRequestV1(JSONArray smsList) throws OCSyncException { private void doPushRequestV1(SmsBuffer smsBuffer) throws OCSyncException {
// We need to save this date as a step for connectivity change // We need to save this date as a step for connectivity change
Long lastMsgDate = (long) 0; Long lastMsgDate = (long) 0;
if (smsList == null) { if (smsBuffer == null) {
doHttpRequest(_http.getAllSmsIds()); doHttpRequest(_http.getAllSmsIds());
if (_jsonQueryBuffer == null) { if (_jsonQueryBuffer == null) {
return; return;
} }
// Create new JSONArray to get results // Create new JSONArray to get results
smsList = new JSONArray(); smsBuffer = new SmsBuffer();
// Get maximum message date present in smsList to keep a step when connectivity changes // Get maximum message date present in smsList to keep a step when connectivity changes
lastMsgDate = collectMessages(smsList).getLastMessageDate(); lastMsgDate = collectMessages(smsBuffer).getLastMessageDate();
} }
if (smsList.length() == 0) { if (smsBuffer.empty()) {
Log.i(OCSMSOwnCloudClient.TAG, "No new SMS to sync, sync done"); Log.i(OCSMSOwnCloudClient.TAG, "No new SMS to sync, sync done");
return; return;
} }
PostMethod post = createPushRequest(smsList); PostMethod post = createPushRequest(smsBuffer);
if (post == null) { if (post == null) {
Log.e(OCSMSOwnCloudClient.TAG,"Push request for POST is null"); Log.e(OCSMSOwnCloudClient.TAG,"Push request for POST is null");
throw new OCSyncException(R.string.err_sync_craft_http_request, OCSyncErrorType.IO); throw new OCSyncException(R.string.err_sync_craft_http_request, OCSyncErrorType.IO);
@ -196,44 +197,15 @@ public class OCSMSOwnCloudClient {
Log.i(OCSMSOwnCloudClient.TAG, "SMS Push request said: status " + pushStatus + " - " + pushMessage); Log.i(OCSMSOwnCloudClient.TAG, "SMS Push request said: status " + pushStatus + " - " + pushMessage);
} }
private PostMethod createPushRequest(JSONArray smsList) throws OCSyncException { private PostMethod createPushRequest(SmsBuffer smsBuffer) throws OCSyncException {
JSONObject obj = createPushJSONObject(smsList); return _http.pushSms(createJSONRequestEntity(smsBuffer));
if (obj == null) {
return null;
} }
StringRequestEntity ent = createJSONRequestEntity(obj); private StringRequestEntity createJSONRequestEntity(SmsBuffer smsBuffer) throws OCSyncException {
if (ent == null) {
return null;
}
return _http.pushSms(ent);
}
private JSONObject createPushJSONObject(JSONArray smsList) throws OCSyncException {
if (smsList == null) {
Log.e(OCSMSOwnCloudClient.TAG,"NULL SMS List");
throw new OCSyncException(R.string.err_sync_create_json_null_smslist, OCSyncErrorType.IO);
}
JSONObject reqJSON = new JSONObject();
try {
reqJSON.put("smsDatas", smsList);
reqJSON.put("smsCount", smsList.length());
} catch (JSONException e) {
Log.e(OCSMSOwnCloudClient.TAG,"JSON Exception when creating JSON request object");
throw new OCSyncException(R.string.err_sync_create_json_put_smslist, OCSyncErrorType.PARSE);
}
return reqJSON;
}
private StringRequestEntity createJSONRequestEntity(JSONObject obj) throws OCSyncException {
StringRequestEntity requestEntity; StringRequestEntity requestEntity;
try { try {
requestEntity = new StringRequestEntity( requestEntity = new StringRequestEntity(
obj.toString(), smsBuffer.asRawJsonString(),
"application/json", "application/json",
"UTF-8"); "UTF-8");

View File

@ -37,13 +37,39 @@ public class SmsBuffer {
private static native long createNativeObject(); private static native long createNativeObject();
private static native void deleteNativeObject(long handle); private static native void deleteNativeObject(long handle);
public static native void push(long handle, int mbid); /*
public void push(int mbid) { JNI: push method
SmsBuffer.push(mHandle, mbid); */
public static native void push(long handle, int id, int mbid, int type, long date,
String address, String body, String read, String seen);
public void push(int id, int mbid, int type, long date, String address, String body,
String read, String seen) {
SmsBuffer.push(mHandle, id, mbid, type, date, address, body, read, seen);
} }
/*
JNI: Eepty method
*/
public static native boolean empty(long handle);
public boolean empty() {
return SmsBuffer.empty(mHandle);
}
/*
JNI: print method
*/
public static native void print(long handle); public static native void print(long handle);
public void print() { public void print() {
SmsBuffer.print(mHandle); SmsBuffer.print(mHandle);
} }
/*
JNI: asRawJsonString method
*/
public static native String asRawJsonString(long handle);
public String asRawJsonString() {
return SmsBuffer.asRawJsonString(mHandle);
}
} }

View File

@ -25,8 +25,6 @@ import android.database.ContentObserver;
import android.os.Handler; import android.os.Handler;
import android.util.Log; import android.util.Log;
import org.json.JSONArray;
import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.R;
import fr.unix_experience.owncloud_sms.engine.ASyncSMSSync; import fr.unix_experience.owncloud_sms.engine.ASyncSMSSync;
import fr.unix_experience.owncloud_sms.engine.AndroidSmsFetcher; import fr.unix_experience.owncloud_sms.engine.AndroidSmsFetcher;
@ -34,6 +32,7 @@ import fr.unix_experience.owncloud_sms.engine.ConnectivityMonitor;
import fr.unix_experience.owncloud_sms.engine.OCSMSOwnCloudClient; import fr.unix_experience.owncloud_sms.engine.OCSMSOwnCloudClient;
import fr.unix_experience.owncloud_sms.enums.MailboxID; import fr.unix_experience.owncloud_sms.enums.MailboxID;
import fr.unix_experience.owncloud_sms.enums.PermissionID; import fr.unix_experience.owncloud_sms.enums.PermissionID;
import fr.unix_experience.owncloud_sms.jni.SmsBuffer;
import fr.unix_experience.owncloud_sms.prefs.PermissionChecker; import fr.unix_experience.owncloud_sms.prefs.PermissionChecker;
public class SmsObserver extends ContentObserver implements ASyncSMSSync { public class SmsObserver extends ContentObserver implements ASyncSMSSync {
@ -60,7 +59,7 @@ public class SmsObserver extends ContentObserver implements ASyncSMSSync {
} }
AndroidSmsFetcher fetcher = new AndroidSmsFetcher(_context); AndroidSmsFetcher fetcher = new AndroidSmsFetcher(_context);
JSONArray smsList = fetcher.getLastMessage(MailboxID.ALL); SmsBuffer smsList = fetcher.getLastMessage(MailboxID.ALL);
ConnectivityMonitor cMon = new ConnectivityMonitor(_context); ConnectivityMonitor cMon = new ConnectivityMonitor(_context);

View File

@ -29,7 +29,7 @@ import fr.unix_experience.owncloud_sms.enums.MailboxID;
import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs; import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs;
public class SmsDataProvider extends ContentProvider { public class SmsDataProvider extends ContentProvider {
static String messageFields[] = { static String[] messageFields = {
"read", "read",
"date", "date",
"address", "address",
@ -54,7 +54,7 @@ public class SmsDataProvider extends ContentProvider {
public Cursor query(String mailBox) { public Cursor query(String mailBox) {
return query(Uri.parse(mailBox), return query(Uri.parse(mailBox),
new String[] { "read", "date", "address", "seen", "body", "_id", "type", }, SmsDataProvider.messageFields,
null, null, null null, null, null
); );
} }