Skip to content

Commit

Permalink
feature: load older messages
Browse files Browse the repository at this point in the history
  • Loading branch information
ifedapoolarewaju committed Jun 3, 2018
1 parent 04931df commit 44863b7
Show file tree
Hide file tree
Showing 7 changed files with 112 additions and 23 deletions.
1 change: 0 additions & 1 deletion browser/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
}
}


ul {
padding-left: 0;
}
Expand Down
23 changes: 22 additions & 1 deletion browser/js/funcs.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,32 @@ function setActive (el) {
document.querySelector('.emojis').classList.add('hide');
}

function getMsgDirection (message) {
if (message._params.accountId == window.loggedInUserId) return 'outward';
else return 'inward';
}

function scrollToChatBottom () {
let msgContainer = document.querySelector('.chat .messages');
let msgContainer = document.querySelector(CHAT_WINDOW_SELECTOR);
msgContainer.scrollTop = msgContainer.scrollHeight;
}

function conditionedScrollToBottom () {
if (!window.gettingOlderMessages) {
return scrollToChatBottom
}
}

function loadOlderMsgsOnScrollTop() {
let msgContainer = document.querySelector(CHAT_WINDOW_SELECTOR);
msgContainer.onscroll = (e) => {
if (e.target.scrollTop < 10 && !window.gettingOlderMessages) {
ipcRenderer.send('getOlderMessages', window.currentChatId);
window.gettingOlderMessages = true;
}
}
}

function getMsgPreview (chat_) {
var msgPreview = chat_.items[0]._params.text || 'Media message';
return truncate(msgPreview, 25);
Expand Down
5 changes: 4 additions & 1 deletion browser/js/globals.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
const electron = require('electron');
const { Menu, MenuItem } = electron.remote
const { Menu, MenuItem } = electron.remote;
const ipcRenderer = electron.ipcRenderer;
const DUMMY_CHAT_ID = 'fake id';
const MSG_INPUT_SELECTOR = '.new-message form textarea';
const CHAT_WINDOW_SELECTOR = '.chat .messages';
const URL_REGEX = new RegExp(/(http:\/\/|https:\/\/)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, 'i');

window.chats = [];
window.chatsHash = {};
window.unreadChats = {};
window.chat = {};
window.olderMessages = [];
window.chatUsers = {};
window.currentChatId = null;
window.notifiedChatId = null;
window.loggedInUserId = null;
window.loggedInUser = null;
window.shouldSendSeenFlags = true;
window.shouldNotify = false;
window.gettingOlderMessages = false;
12 changes: 11 additions & 1 deletion browser/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ function getLoggedInUser () {
}

function getChat (id) {
if (window.currentChatId !== id) {
window.olderMessages = []
}
window.currentChatId = id;
ipcRenderer.send('getChat', id);
}
Expand Down Expand Up @@ -41,7 +44,14 @@ document.addEventListener('DOMContentLoaded', () => {
getIsSeenText(chat_) != getIsSeenText(window.chat)
)

if (isNewMessage && isCurrentChat(chat_)) renderChat(chat_);
if (isNewMessage && isCurrentChat(chat_) && !window.gettingOlderMessages) renderChat(chat_);
});

ipcRenderer.on('olderMessages', (_, messages) => {
window.olderMessages = window.olderMessages.concat(messages)
renderOlderMessages(messages);
// reset the value only after all is done. So don't move this up
window.gettingOlderMessages = false;
});

ipcRenderer.on('searchResult', (evt, users) => {
Expand Down
36 changes: 26 additions & 10 deletions browser/js/renderers.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ function renderMessageAsPost (container, message) {
if (post.images) {
// carousels have nested arrays before getting to image url
var img = dom(`<img src="${post.images[0].url || post.images[0][0].url}">`);
img.onload = () => scrollToChatBottom();
img.onload = conditionedScrollToBottom();
container.appendChild(img);
}

Expand Down Expand Up @@ -73,7 +73,7 @@ function renderMessageAsUserStory (container, message) {
if (message._params.reelShare.media.image_versions2) {
var url = message._params.reelShare.media.image_versions2.candidates[0].url
var img = dom(`<img src="${url}">`);
img.onload = () => scrollToChatBottom();
img.onload = conditionedScrollToBottom();
container.appendChild(img);

container.addEventListener('click', () => {
Expand All @@ -94,7 +94,7 @@ function renderMessageAsUserStory (container, message) {
function renderMessageAsImage (container, message) {
var url = typeof message === 'string' ? message : message._params.media[0].url
var img = dom(`<img src="${url}">`);
img.onload = () => scrollToChatBottom();
img.onload = conditionedScrollToBottom();
container.appendChild(img);
container.classList.add('ig-media');

Expand All @@ -118,7 +118,7 @@ function renderMessageAsLink (container, message) {
const text = message.link._params.text;
if (link.image && link.image.url) {
var img = dom(`<img src="${link.image.url}">`);
img.onload = () => scrollToChatBottom();
img.onload = conditionedScrollToBottom();
container.appendChild(img);
}
// replace all contained links with anchor tags
Expand Down Expand Up @@ -177,7 +177,10 @@ function renderChatList (chatList) {
chatList.forEach((chat_) => {
var msgPreview = getMsgPreview(chat_);
var usernames = getUsernames(chat_, true);
var thumbnail = chat_.accounts[0]._params.picture;
let thumbnail = '';
if (chat_.accounts[0]) {
thumbnail = chat_.accounts[0]._params.picture;
}
var li = renderChatListItem(usernames, msgPreview, thumbnail, chat_.id);

registerChatUser(chat_);
Expand Down Expand Up @@ -211,27 +214,40 @@ function renderChatHeader (chat_) {
function renderChat (chat_) {
window.chat = chat_;

var msgContainer = document.querySelector('.chat .messages');
var msgContainer = document.querySelector(CHAT_WINDOW_SELECTOR);
msgContainer.innerHTML = '';
renderChatHeader(chat_);
var messages = chat_.items.slice().reverse();
// load older messages if they exist too
messages = window.olderMessages.slice().reverse().concat(messages);
messages.forEach((message) => {
if (message._params.accountId == window.loggedInUserId) var direction = 'outward';
else var direction = 'inward';

var div = renderMessage(message, direction,
var div = renderMessage(message, getMsgDirection(message),
message._params.created, message._params.type
);
msgContainer.appendChild(div);
})
renderMessageSeenText(msgContainer, chat_);
scrollToChatBottom();
loadOlderMsgsOnScrollTop();

addSubmitHandler(chat_);
addAttachmentSender(chat_);
document.querySelector(MSG_INPUT_SELECTOR).focus();
}

function renderOlderMessages (messages) {
const msgContainer = document.querySelector(CHAT_WINDOW_SELECTOR);
const domPostion = msgContainer.firstChild;
messages.forEach((message) => {
var div = renderMessage(message, getMsgDirection(message),
message._params.created, message._params.type
);
msgContainer.prepend(div);
});
// scroll back to dom position before the older messages were rendered
domPostion.scrollIntoView();
}

function renderMessageSeenText (container, chat_) {
container.appendChild(dom(`<div class="seen italic outward"><p>${getIsSeenText(chat_)}</p></div>`));
}
Expand Down
26 changes: 26 additions & 0 deletions main/instagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,32 @@ exports.getChat = function (session, chatId) {
})
}

exports.getOlderMessages = function (session, thread, chatId) {
return new Promise((resolve, reject) => {
const needsNewThread = !thread || thread.threadId !== chatId
if (needsNewThread) {
thread = new Client.Feed.ThreadItems(session, chatId)
}

if (!needsNewThread && !thread.isMoreAvailable()) {
// there aren't any older messages
resolve({thread, messages: []})
}

thread.get().then((messages) => {
if (needsNewThread) {
if (thread.isMoreAvailable()) {
// get the next 20 because the first 20 messages already were fetched with #getChat
return thread.get().then((messages) => resolve({ thread, messages }))
}
// there aren't any older messages
messages = []
}
resolve({thread, messages})
}).catch(reject)
})
}

exports.sendNewChatMessage = function (session, message, recipients) {
return new Promise((resolve, reject) => {
Client.Thread.configureText(session, recipients, message).then(resolve).catch(reject)
Expand Down
32 changes: 23 additions & 9 deletions main/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,13 @@ function getChatList () {
}

let timeoutObj;
let messagesThread;
function getChat (evt, id) {
// used to get older messages, see #getOlderMessages
if (messagesThread && messagesThread.threadId != id) {
messagesThread = null
}

instagram.getChat(session, id).then((chat) => {
mainWindow.webContents.send('chat', chat);

Expand Down Expand Up @@ -118,13 +124,13 @@ electron.ipcMain.on('login', (evt, data) => {
})
})

electron.ipcMain.on('logout', (evt, data) => {
electron.ipcMain.on('logout', () => {
instagram.logout()
session = null
createWindow()
})

electron.ipcMain.on('getLoggedInUser', (evt) => {
electron.ipcMain.on('getLoggedInUser', () => {
instagram.getLoggedInUser(session).then((user) => {
mainWindow.webContents.send('loggedInUser', user);
})
Expand All @@ -134,41 +140,49 @@ electron.ipcMain.on('getChatList', getChatList)

electron.ipcMain.on('getChat', getChat)

electron.ipcMain.on('message', (evt, data) => {
electron.ipcMain.on('getOlderMessages', (_, id) => {
instagram.getOlderMessages(session, messagesThread, id)
.then((data) => {
messagesThread = data.thread
mainWindow.webContents.send('olderMessages', data.messages)
})
})

electron.ipcMain.on('message', (_, data) => {
if (data.isNewChat) {
instagram.sendNewChatMessage(session, data.message, data.users).then((chat) => getChat(null, chat[0].id))
} else {
instagram.sendMessage(session, data.message, data.chatId)
}
})

electron.ipcMain.on('upload', (evt, data) => {
electron.ipcMain.on('upload', (_, data) => {
instagram.uploadFile(session, data.filePath, data.recipients)
.then((chat) => {
if (data.isNewChat) getChat(null, chat[0].id)
})
})

electron.ipcMain.on('searchUsers', (evt, search) => {
electron.ipcMain.on('searchUsers', (_, search) => {
instagram.searchUsers(session, search).then((users) => {
mainWindow.webContents.send('searchResult', users);
})
})

electron.ipcMain.on('markAsRead', (evt, thread) => {
electron.ipcMain.on('markAsRead', (_, thread) => {
instagram.seen(session, thread)
})

electron.ipcMain.on('increase-badge-count', (evt) => {
electron.ipcMain.on('increase-badge-count', (_) => {
app.setBadgeCount(app.getBadgeCount() + 1);
})

electron.ipcMain.on('getUnfollowers', (evt) => {
electron.ipcMain.on('getUnfollowers', (_) => {
instagram.getUnfollowers(session).then((users) => {
mainWindow.webContents.send('unfollowers', users)
})
})

electron.ipcMain.on('unfollow', (evt, userId) => {
electron.ipcMain.on('unfollow', (_, userId) => {
instagram.unfollow(session, userId)
})

0 comments on commit 44863b7

Please sign in to comment.