Skip to content

Commit

Permalink
Merge pull request RocketChat#259 from WideChat/develop_pwa
Browse files Browse the repository at this point in the history
catchup with pwa branch
  • Loading branch information
ear-dev authored May 8, 2020
2 parents 01c6389 + d06be60 commit aa43de2
Show file tree
Hide file tree
Showing 12 changed files with 66 additions and 50 deletions.
3 changes: 1 addition & 2 deletions app/lib/client/methods/sendMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor';
import s from 'underscore.string';
import toastr from 'toastr';

import { ChatMessage, CachedChatMessage, ChatRoom, ChatSubscription } from '../../../models';
import { ChatMessage, ChatRoom, ChatSubscription } from '../../../models';
import { settings } from '../../../settings';
import { callbacks } from '../../../callbacks';
import { promises } from '../../../promises/client';
Expand Down Expand Up @@ -34,7 +34,6 @@ Meteor.methods({
message = callbacks.run('beforeSaveMessage', message);
promises.run('onClientMessageReceived', message).then(function(message) {
ChatMessage.insert(message);
CachedChatMessage.save();
ChatRoom.setLastMessage(message.rid, message);
ChatSubscription.setLastMessage(message.rid, message);
return callbacks.run('afterSaveMessage', message);
Expand Down
24 changes: 15 additions & 9 deletions app/models/client/models/ChatMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { CachedCollection } from '../../../ui-cached-collection';
import { CachedChatSubscription } from './CachedChatSubscription';
import { ChatSubscription } from './ChatSubscription';
import { getConfig } from '../../../ui-utils/client/config';
import { cleanMessagesAtStartup } from '../../../utils';
import { cleanMessagesAtStartup, triggerOfflineMsgs } from '../../../utils';
import { renderMessageBody } from '../../../ui-utils/client/lib/renderMessageBody';
import { promises } from '../../../promises/client';
import { callbacks } from '../../../callbacks';
Expand All @@ -17,14 +17,18 @@ export const ChatMessage = CachedChatMessage.collection;

let timeout;

ChatMessage.find().observe({
added: CachedChatMessage.save,
changed: CachedChatMessage.save,
removed: CachedChatMessage.save,
});

ChatMessage.setReactions = function(messageId, reactions, tempActions) {
this.update({ _id: messageId }, { $set: { temp: true, tempActions, reactions } });
return CachedChatMessage.save();
return this.update({ _id: messageId }, { $set: { temp: true, tempActions, reactions } });
};

ChatMessage.unsetReactions = function(messageId, tempActions) {
this.update({ _id: messageId }, { $unset: { reactions: 1 }, $set: { temp: true, tempActions } });
return CachedChatMessage.save();
return this.update({ _id: messageId }, { $unset: { reactions: 1 }, $set: { temp: true, tempActions } });
};

ChatMessage.setProgress = function(messageId, upload) {
Expand Down Expand Up @@ -90,14 +94,18 @@ function upsertMessageBulk({ msgs, subscription }, collection = ChatMessage) {

const messagePreFetch = () => {
let messagesFetched = false;
if (Meteor.status().status !== 'connected') {
clearTimeout(timeout);
timeout = setTimeout(cleanMessagesAtStartup, 3000);
}
Tracker.autorun(() => {
if (!messagesFetched && CachedChatSubscription.ready.get()) {
const status = Meteor.status();
if (status.status !== 'connected') {
clearTimeout(timeout);
timeout = setTimeout(cleanMessagesAtStartup, 3000);
return;
}
clearTimeout(timeout);
triggerOfflineMsgs();
messagesFetched = true;
const subscriptions = ChatSubscription.find(
{
Expand Down Expand Up @@ -125,8 +133,6 @@ const messagePreFetch = () => {
});
});
});
clearTimeout(timeout);
cleanMessagesAtStartup(false);
}
});
};
Expand Down
6 changes: 5 additions & 1 deletion app/reactions/client/methods/setReaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import { callbacks } from '../../../callbacks';
import { emoji } from '../../../emoji';

Meteor.methods({
setReaction(reaction, messageId) {
setReaction(reaction, messageId, shouldReact, offlineTrigerred = false) {
if (!Meteor.userId()) {
throw new Meteor.Error(203, 'User_logged_out');
}

if (offlineTrigerred) {
return;
}

const user = Meteor.user();

const message = Messages.findOne({ _id: messageId });
Expand Down
3 changes: 1 addition & 2 deletions app/ui-utils/client/lib/RoomHistoryManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { readMessage } from './readMessages';
import { renderMessageBody } from './renderMessageBody';
import { getConfig } from '../config';
import { call } from './callMethod';
import { ChatMessage, ChatSubscription, ChatRoom, CachedChatMessage } from '../../../models';
import { ChatMessage, ChatSubscription, ChatRoom } from '../../../models';

export const normalizeThreadMessage = (message) => {
if (message.msg) {
Expand Down Expand Up @@ -340,7 +340,6 @@ export const RoomHistoryManager = new class {
retain.forEach((message) => {
ChatMessage.insert(message);
});
CachedChatMessage.save();
if (this.histories[rid]) {
this.histories[rid].hasMore.set(true);
this.histories[rid].isLoading.set(false);
Expand Down
4 changes: 1 addition & 3 deletions app/ui-utils/client/lib/RoomManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { mainReady } from './mainReady';
import { roomTypes } from '../../../utils';
import { callbacks } from '../../../callbacks';
import { Notifications } from '../../../notifications';
import { CachedChatRoom, ChatMessage, ChatSubscription, CachedChatSubscription, CachedChatMessage } from '../../../models';
import { CachedChatRoom, ChatMessage, ChatSubscription, CachedChatSubscription } from '../../../models';
import { CachedCollectionManager } from '../../../ui-cached-collection';
import { getConfig } from '../config';
import { ROOM_DATA_STREAM } from '../../../utils/stream/constants';
Expand All @@ -27,7 +27,6 @@ const onDeleteMessageStream = (msg) => {

// remove thread refenrece from deleted message
ChatMessage.update({ tmid: msg._id }, { $unset: { tmid: 1 } }, { multi: true });
CachedChatMessage.save();
};
const onDeleteMessageBulkStream = ({ rid, ts, excludePinned, ignoreDiscussion, users }) => {
const query = { rid, ts };
Expand All @@ -41,7 +40,6 @@ const onDeleteMessageBulkStream = ({ rid, ts, excludePinned, ignoreDiscussion, u
query['u.username'] = { $in: users };
}
ChatMessage.remove(query);
CachedChatMessage.save();
};

export const RoomManager = new function() {
Expand Down
14 changes: 9 additions & 5 deletions app/ui/client/lib/fileUpload.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,11 +305,14 @@ export const fileUpload = async (files, input, { rid, tmid }) => {
}

const uploads = upload;
uploads.percentage = Math.round(progress * 100) || 0;
uploads.percentage = Math.round(progress) || 0;
ChatMessage.setProgress(msgData.id, uploads);
},
error() {
ChatMessage.setProgress(msgData.id, upload);
error(error) {
const uploads = upload;
uploads.error = (error.xhr && error.xhr.responseJSON && error.xhr.responseJSON.error) || error.message;
uploads.percentage = 0;
ChatMessage.setProgress(msg._id, uploads);
},
});

Expand All @@ -325,8 +328,9 @@ export const fileUpload = async (files, input, { rid, tmid }) => {
});

try {
await promise;
offlineFile && SWCache.removeFromCache(offlineFile);
const res = await promise;

if (typeof res === 'object' && res.success && offlineFile) { SWCache.removeFromCache(offlineFile); }
} catch (error) {
const uploads = upload;
uploads.error = (error.xhr && error.xhr.responseJSON && error.xhr.responseJSON.error) || error.message;
Expand Down
3 changes: 1 addition & 2 deletions app/ui/client/lib/sendOfflineFileMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import toastr from 'toastr';

import { ChatMessage, CachedChatMessage } from '../../../models';
import { ChatMessage } from '../../../models';
import { settings } from '../../../settings';
import { callbacks } from '../../../callbacks';
import { promises } from '../../../promises/client';
Expand Down Expand Up @@ -98,7 +98,6 @@ export const sendOfflineFileMessage = (roomId, msgData, file, meta, callback) =>
message = callbacks.run('beforeSaveMessage', message);
promises.run('onClientMessageReceived', message).then(function(message) {
ChatMessage.insert(message);
CachedChatMessage.save();
return callbacks.run('afterSaveMessage', message);
});
});
Expand Down
2 changes: 1 addition & 1 deletion app/utils/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export { templateVarHandler } from '../lib/templateVarHandler';
export { APIClient } from './lib/RestApiClient';
export { canDeleteMessage } from './lib/canDeleteMessage';
export { SWCache } from './lib/swCache';
export { cleanMessagesAtStartup } from './lib/offlineMessages';
export { cleanMessagesAtStartup, triggerOfflineMsgs } from './lib/offlineMessages';
export { mime } from '../lib/mimeTypes';
export { secondsToHHMMSS } from '../lib/timeConverter';
export { isMobile } from './lib/isMobile';
Expand Down
38 changes: 22 additions & 16 deletions app/utils/client/lib/offlineMessages.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,20 @@ const action = {
msg.msg && data.append('msg', msg.msg);
msg.tmid && data.append('tmid', msg.tmid);
data.append('file', file, msg.file.name);

const { xhr, promise } = APIClient.upload(`v1/rooms.upload/${ msg.rid }`, {}, data, {
progress(progress) {
if (progress === 100) {
return;
}
const uploads = upload;
uploads.percentage = Math.round(progress * 100) || 0;
uploads.percentage = Math.round(progress) || 0;
ChatMessage.setProgress(msg._id, uploads);
},
error() {
ChatMessage.setProgress(msg._id, upload);
error(error) {
const uploads = upload;
uploads.error = (error.xhr && error.xhr.responseJSON && error.xhr.responseJSON.error) || error.message;
uploads.percentage = 0;
ChatMessage.setProgress(msg._id, uploads);
},
});

Expand All @@ -68,8 +70,9 @@ const action = {
});

try {
await promise;
SWCache.removeFromCache(msg.file);
const res = await promise;

if (typeof res === 'object' && res.success) { SWCache.removeFromCache(msg.file); }
} catch (error) {
const uploads = upload;
uploads.error = (error.xhr && error.xhr.responseJSON && error.xhr.responseJSON.error) || error.message;
Expand All @@ -80,14 +83,14 @@ const action = {

update: (msg) => {
msg.editedAt = new Date();
call('updateMessage', msg);
call('updateMessage', msg, true);
},

react: ({ _id }, reaction) => {
call('setReaction', reaction, _id);
call('setReaction', reaction, _id, undefined, true);
},

delete: ({ _id }) => call('deleteMessage', { _id }),
delete: ({ _id }) => call('deleteMessage', { _id }, true),
};

function trigger(msg) {
Expand Down Expand Up @@ -115,10 +118,14 @@ function trigger(msg) {
}
}

function triggerOfflineMsgs(messages) {
const tempMsgs = messages.filter((msg) => msg.temp);
tempMsgs.forEach((msg) => trigger(msg));
}
export const triggerOfflineMsgs = () => {
localforage.getItem('chatMessage').then((value) => {
if (value && value.records) {
const tempMsgs = value.records.filter((msg) => msg.temp);
tempMsgs.forEach((msg) => trigger(msg));
}
});
};

const retainMessages = (rid, messages) => {
const roomMsgs = messages.filter((msg) => rid === msg.rid);
Expand All @@ -138,14 +145,13 @@ function clearOldMessages({ records: messages, ...value }) {
value.updatedAt = new Date();
localforage.setItem('chatMessage', value).then(() => {
CachedChatMessage.loadFromCache();
triggerOfflineMsgs(retain);
});
}

export const cleanMessagesAtStartup = (offline = true) => {
export const cleanMessagesAtStartup = () => {
localforage.getItem('chatMessage').then((value) => {
if (value && value.records) {
offline ? clearOldMessages(value) : triggerOfflineMsgs(value.records);
clearOldMessages(value);
}
});
};
8 changes: 3 additions & 5 deletions client/methods/deleteMessage.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';

import { ChatMessage, CachedChatMessage } from '../../app/models/client';
import { ChatMessage } from '../../app/models/client';
import { canDeleteMessage, SWCache } from '../../app/utils/client';

Meteor.methods({
deleteMessage(msg) {
if (!Meteor.userId()) {
deleteMessage(msg, offlineTriggered = false) {
if (!Meteor.userId() || offlineTriggered) {
return false;
}

Expand All @@ -26,7 +26,6 @@ Meteor.methods({
_id: message._id,
'u._id': Meteor.userId(),
});
CachedChatMessage.save();
if (message.file) {
SWCache.removeFromCache(message.file);
Session.set(`uploading-cancel-${ message.file._id }`, true);
Expand All @@ -38,7 +37,6 @@ Meteor.methods({
_id: message._id,
'u._id': Meteor.userId(),
}, { $set: messageObject, $unset: { reactions: 1, file: 1, attachments: 1 } });
CachedChatMessage.save();
}
},
});
7 changes: 3 additions & 4 deletions client/methods/updateMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import moment from 'moment';
import toastr from 'toastr';

import { t } from '../../app/utils';
import { ChatMessage, CachedChatMessage } from '../../app/models';
import { ChatMessage } from '../../app/models';
import { hasAtLeastOnePermission } from '../../app/authorization';
import { settings } from '../../app/settings';
import { callbacks } from '../../app/callbacks';

Meteor.methods({
updateMessage(message) {
if (!Meteor.userId()) {
updateMessage(message, offlineTriggered = false) {
if (!Meteor.userId() || offlineTriggered) {
return false;
}

Expand Down Expand Up @@ -81,7 +81,6 @@ Meteor.methods({
_id: message._id,
'u._id': Meteor.userId(),
}, { $set: messageObject });
CachedChatMessage.save();
});
},
});
4 changes: 4 additions & 0 deletions public/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ self.addEventListener('activate', (event) => {
});

self.addEventListener('fetch', (event) => {
if (event.request.method === 'POST') {
return;
}

const requestToFetch = event.request.clone();
event.respondWith(
caches.match(event.request.clone()).then((cached) => {
Expand Down

0 comments on commit aa43de2

Please sign in to comment.