Skip to content

Commit

Permalink
Added proper API syncing for DMS and group messages
Browse files Browse the repository at this point in the history
  • Loading branch information
f-r00t committed Feb 28, 2024
1 parent 0f51cee commit a5f9a8c
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 56 deletions.
34 changes: 31 additions & 3 deletions src/Database.js
Original file line number Diff line number Diff line change
Expand Up @@ -1634,20 +1634,48 @@ export async function removeBoard(board) {

}

export async function getLatestBoardMessage() {
export async function getLatestGroupMessage() {

const [data] = await database.executeSql(
`SELECT
timestamp
FROM
boards_message_db
privateboards_messages_db
ORDER BY
timestamp
DESC
LIMIT
1`
);
console.log('Got ' + data.rows.length + " board messages");

let timestamp = 0;
if (data && data.rows && data.rows.length) {

for (let i = 0; i < data.rows.length; i++) {
const item = data.rows.item(i);
timestamp = item.timestamp;
return timestamp;
}

}
return timestamp;

}

export async function getLatestMessage() {

const [data] = await database.executeSql(
`SELECT
timestamp
FROM
message_db
ORDER BY
timestamp
DESC
LIMIT
1`
);

let timestamp = 0;
if (data && data.rows && data.rows.length) {

Expand Down
6 changes: 6 additions & 0 deletions src/Globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ class globals {

this.speakerOn = true;

this.notificationQueue = [];

this.lastMessageTimestamp = 0;

this.lastDMTimestamp = 0;

}

reset() {
Expand Down
99 changes: 51 additions & 48 deletions src/HuginUtilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import * as NaclSealed from 'tweetnacl-sealed-box';

import Identicon from 'identicon.js';

import { savePreferencesToDatabase, getGroupName, saveGroupMessage, groupMessageExists, getGroupKey, getLatestBoardMessage, getHistory, getLatestMessages, saveToDatabase, loadPayeeDataFromDatabase, saveMessage, saveBoardsMessage, savePayeeToDatabase, messageExists, boardsMessageExists } from './Database';
import { savePreferencesToDatabase, getGroupName, saveGroupMessage, groupMessageExists, getGroupKey, getLatestGroupMessage, getHistory, getLatestMessages, saveToDatabase, loadPayeeDataFromDatabase, saveMessage, saveBoardsMessage, savePayeeToDatabase, messageExists, getLatestMessage } from './Database';

/**
* Save wallet in background
Expand Down Expand Up @@ -459,79 +459,80 @@ export async function sendMessageWithHuginAPI(payload_hex) {

}

export async function cacheSync(silent=true, latest_board_message_timestamp=0, first=true, page=1) {
export async function cacheSync(latest_board_message_timestamp=0, first=true, page=1) {

return;
console.log('Global timestamp', Globals.lastMessageTimestamp);

if(first) {
latest_board_message_timestamp = await getLatestBoardMessage();
latest_board_message_timestamp = parseInt(await getLatestGroupMessage()) + 1;
}

if (Globals.lastMessageTimestamp > latest_board_message_timestamp) latest_board_message_timestamp = Globals.lastMessageTimestamp;

let cacheURL = Globals.preferences.cache ? Globals.preferences.cache : Config.defaultCache;

fetch(`${cacheURL}/api/v1/posts?from=${latest_board_message_timestamp}&to=${Date.now() / 1000}&size=50&page=` + page)
fetch(`${cacheURL}/api/v1/posts-encrypted-group?from=${parseInt(latest_board_message_timestamp/1000)}&to=${parseInt(Date.now()/1000)}&size=50&page=` + page)
.then((response) => response.json())
.then(async (json) => {

const items = json.posts;

const items = json.encrypted_group_posts;

for (item in items) {

if (items[item].time < latest_board_message_timestamp) {
return;
}
if (await groupMessageExists(items[item].tx_timestamp)) continue;

const fromMyself = items[item].key == Globals.wallet.getPrimaryAddress() ? true : false;
let groupMessage = await getGroupMessage({
sb: items[item].tx_sb,
t: items[item].tx_timestamp,
hash: items[item].tx_hash
});

const message = items[item].message;
const address = items[item].key;
const signature = items[item].signature;
const board = items[item].board;
const timestamp = items[item].time;
const nickname = items[item].nickname;
const reply = items[item].reply_tx_hash;
const hash = items[item].tx_hash;
const sent = fromMyself ? true : false;
}
if (json.current_page < json.total_pages) {
cacheSync(latest_board_message_timestamp, false, page+1);
} else {
Globals.lastMessageTimestamp = items.slice(-1)[0].created_at + 1;
}
})

if (await boardsMessageExists(hash)) {
continue;
return;
}
}

if (fromMyself) {
silent = true;
} else {
silent = false;
}
export async function cacheSyncDMs(latest_board_message_timestamp=0, first=true, page=1) {

saveBoardsMessage(message, address, signature, board, timestamp, nickname, reply, hash, sent, silent);
console.log('Global timestamp', Globals.lastDMTimestamp);

if (!nickname) {
nickname = 'Anonymous';
}
if(first) {
latest_board_message_timestamp = parseInt(await getLatestMessage()) + 1;
}

if (Globals.lastDMTimestamp > latest_board_message_timestamp) latest_board_message_timestamp = Globals.lastDMTimestamp;

let cacheURL = Globals.preferences.cache ? Globals.preferences.cache : Config.defaultCache;

console.log(`${cacheURL}/api/v1/posts-encrypted?from=${parseInt(latest_board_message_timestamp/1000)}&to=${parseInt(Date.now()/1000)}&size=50&page=` + page);
fetch(`${cacheURL}/api/v1/posts-encrypted?from=${parseInt(latest_board_message_timestamp/1000)}&to=${parseInt(Date.now()/1000)}&size=50&page=` + page)
.then((response) => response.json())
.then(async (json) => {
console.log(json);
const items = json.encrypted_posts;

for (item in items) {

if (await messageExists(items[item].tx_timestamp)) continue;

const subscriptionList = Globals.boardsSubscriptions.filter(sub => {
return sub.board == board;
})
let dirtified_json = "000000000000000000000000000000000000000000000000000000000000000000" + JSON.stringify({
box: items[item].tx_box,
t: items[item].tx_timestamp,
hash: items[item].tx_hash
});

if (latest_board_message_timestamp != 0 && !fromMyself && subscriptionList.length > 0 ) {
PushNotification.localNotification({
title: nickname + ' in ' + board,//'Incoming transaction received!',
//message: `You were sent ${prettyPrintAmount(transaction.totalAmount(), Config)}`,
message: message,
data: timestamp,
userInfo: board,
// largeIconUrl: get_avatar(payload_json.from, 64),
});
}
let message = await getMessage(dirtified_json);

}
if (json.current_page != json.total_pages) {
cacheSync(silent, latest_board_message_timestamp, false, page+1);
if (json.current_page < json.total_pages) {
cacheSyncDMs(latest_board_message_timestamp, false, page+1);
} else {
Globals.lastDMTimestamp = items.slice(-1)[0].created_at + 1;
}
})

Expand Down Expand Up @@ -741,6 +742,8 @@ export async function getExtra(hash){

async function getGroupMessage(tx) {

console.log('Trying to decrypt', tx);

let decryptBox = false;

const groups = Globals.groups;
Expand Down
42 changes: 37 additions & 5 deletions src/MainScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import Config from './Config';

import { Styles } from './Styles';
import { handleURI, toastPopUp, prettyPrintAmountMainScreen } from './Utilities';
import { getBestCache, cacheSync, getKeyPair, getMessage, getExtra, optimizeMessages, intToRGB, hashCode, get_avatar, sendMessage } from './HuginUtilities';
import { getBestCache, cacheSync, cacheSyncDMs, getKeyPair, getMessage, getExtra, optimizeMessages, intToRGB, hashCode, get_avatar, sendMessage } from './HuginUtilities';
import { ProgressBar } from './ProgressBar';
import { getKnownTransactions, deleteKnownTransaction, saveKnownTransaction, getUnreadMessages, boardsMessageExists, getBoardsMessage, savePreferencesToDatabase, saveToDatabase, loadPayeeDataFromDatabase } from './Database';
import { Globals, initGlobals } from './Globals';
Expand Down Expand Up @@ -97,6 +97,8 @@ async function init(navigation) {
if (Globals.backgroundSyncMessagesTimer === undefined) {
Globals.backgroundSyncMessagesTimer = setInterval(function() {
backgroundSyncMessages(navigation);
//cacheSync(false);

}, 10000);
}

Expand Down Expand Up @@ -1050,11 +1052,41 @@ async function backgroundSyncMessages(navigation) {
console.log('Commencing message sync.');
}
Globals.syncingMessages = true;
console.log(Globals.preferences);
if (Globals.preferences.cacheEnabled == "true") {

cacheSync();

try {
cacheSyncDMs();

if (Globals.notificationQueue.length > 2) {

PushNotification.localNotification({
title: "New messages received!",
message: `You've received ${Globals.notificationQueue.length} new messages.`
});

cacheSync(false);
} else if (0 < Globals.notificationQueue.length && Globals.notificationQueue.length <= 2) {
for (n in Globals.notificationQueue) {
PushNotification.localNotification({
title: Globals.notificationQueue[n].title,
message: Globals.notificationQueue[n].message,
data: Globals.notificationQueue[n].data,
userInfo: Globals.notificationQueue[n].userInfo,
largeIconUrl: Globals.notificationQueue[n].largeIconUrl,
});
}
}
Globals.notificationQueue = [];
Globals.syncingMessages = false;
Globals.knownTXs = await getKnownTransactions();
return;

}



try {

const daemonInfo = Globals.wallet.getDaemonConnectionInfo();
let knownTXs = await getKnownTransactions();
Expand Down Expand Up @@ -1100,11 +1132,11 @@ async function backgroundSyncMessages(navigation) {
} catch (err) {

}
await saveKnownTransaction(thisHash);
saveKnownTransaction(thisHash);
if (Globals.knownTXs.indexOf(thisHash) === -1) Globals.knownTXs.push(thisHash);

} else {
await saveKnownTransaction(thisHash);
saveKnownTransaction(thisHash);
if (Globals.knownTXs.indexOf(thisHash) === -1) Globals.knownTXs.push(thisHash);
continue;
}
Expand Down

0 comments on commit a5f9a8c

Please sign in to comment.