/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // TODO: This component is enormous! There's several things which could stand-alone: // - Aux component // - Search results component // - Drag and drop // - File uploading - uploadFile() // - Timeline component (alllll the logic in getEventTiles()) var React = require("react"); var ReactDOM = require("react-dom"); var q = require("q"); var classNames = require("classnames"); var Matrix = require("matrix-js-sdk"); var MatrixClientPeg = require("../../MatrixClientPeg"); var ContentMessages = require("../../ContentMessages"); var WhoIsTyping = require("../../WhoIsTyping"); var Modal = require("../../Modal"); var sdk = require('../../index'); var CallHandler = require('../../CallHandler'); var TabComplete = require("../../TabComplete"); var MemberEntry = require("../../TabCompleteEntries").MemberEntry; var CommandEntry = require("../../TabCompleteEntries").CommandEntry; var Resend = require("../../Resend"); var SlashCommands = require("../../SlashCommands"); var dis = require("../../dispatcher"); var Tinter = require("../../Tinter"); var PAGINATE_SIZE = 20; var INITIAL_SIZE = 20; var SEND_READ_RECEIPT_DELAY = 2000; var DEBUG_SCROLL = false; if (DEBUG_SCROLL) { // using bind means that we get to keep useful line numbers in the console var debuglog = console.log.bind(console); } else { var debuglog = function () {}; } module.exports = React.createClass({ displayName: 'RoomView', propTypes: { ConferenceHandler: React.PropTypes.any }, /* properties in RoomView objects include: * * eventNodes: a map from event id to DOM node representing that event */ getInitialState: function() { var room = this.props.roomId ? MatrixClientPeg.get().getRoom(this.props.roomId) : null; return { room: room, messageCap: INITIAL_SIZE, editingRoomSettings: false, uploadingRoomSettings: false, numUnreadMessages: 0, draggingFile: false, searching: false, searchResults: null, syncState: MatrixClientPeg.get().getSyncState(), hasUnsentMessages: this._hasUnsentMessages(room), callState: null, guestsCanJoin: false, readMarkerEventId: room.getEventReadUpTo(MatrixClientPeg.get().credentials.userId), readMarkerGhostEventId: undefined } }, componentWillMount: function() { this.dispatcherRef = dis.register(this.onAction); MatrixClientPeg.get().on("Room.timeline", this.onRoomTimeline); MatrixClientPeg.get().on("Room.name", this.onRoomName); MatrixClientPeg.get().on("Room.accountData", this.onRoomAccountData); MatrixClientPeg.get().on("Room.receipt", this.onRoomReceipt); MatrixClientPeg.get().on("RoomMember.typing", this.onRoomMemberTyping); MatrixClientPeg.get().on("RoomState.members", this.onRoomStateMember); MatrixClientPeg.get().on("sync", this.onSyncStateChange); // xchat-style tab complete, add a colon if tab // completing at the start of the text this.tabComplete = new TabComplete({ allowLooping: false, autoEnterTabComplete: true, onClickCompletes: true, onStateChange: (isCompleting) => { this.forceUpdate(); } }); // if this is an unknown room then we're in one of three states: // - This is a room we can peek into (search engine) (we can /peek) // - This is a room we can publicly join or were invited to. (we can /join) // - This is a room we cannot join at all. (no action can help us) // We can't try to /join because this may implicitly accept invites (!) // We can /peek though. If it fails then we present the join UI. If it // succeeds then great, show the preview (but we still may be able to /join!). if (!this.state.room) { console.log("Attempting to peek into room %s", this.props.roomId); MatrixClientPeg.get().peekInRoom(this.props.roomId).done(() => { // we don't need to do anything - JS SDK will emit Room events // which will update the UI. We *do* however need to know if we // can join the room so we can fiddle with the UI appropriately. var peekedRoom = MatrixClientPeg.get().getRoom(this.props.roomId); if (!peekedRoom) { return; } var guestAccessEvent = peekedRoom.currentState.getStateEvents("m.room.guest_access", ""); if (!guestAccessEvent) { return; } if (guestAccessEvent.getContent().guest_access === "can_join") { this.setState({ guestsCanJoin: true }); } }, function(err) { console.error("Failed to peek into room: %s", err); }); } }, componentWillUnmount: function() { // set a boolean to say we've been unmounted, which any pending // promises can use to throw away their results. // // (We could use isMounted, but facebook have deprecated that.) this.unmounted = true; if (this.refs.messagePanel) { // disconnect the D&D event listeners from the message panel. This // is really just for hygiene - the messagePanel is going to be // deleted anyway, so it doesn't matter if the event listeners // don't get cleaned up. var messagePanel = ReactDOM.findDOMNode(this.refs.messagePanel); messagePanel.removeEventListener('drop', this.onDrop); messagePanel.removeEventListener('dragover', this.onDragOver); messagePanel.removeEventListener('dragleave', this.onDragLeaveOrEnd); messagePanel.removeEventListener('dragend', this.onDragLeaveOrEnd); } dis.unregister(this.dispatcherRef); if (MatrixClientPeg.get()) { MatrixClientPeg.get().removeListener("Room.timeline", this.onRoomTimeline); MatrixClientPeg.get().removeListener("Room.name", this.onRoomName); MatrixClientPeg.get().removeListener("Room.accountData", this.onRoomAccountData); MatrixClientPeg.get().removeListener("Room.receipt", this.onRoomReceipt); MatrixClientPeg.get().removeListener("RoomMember.typing", this.onRoomMemberTyping); MatrixClientPeg.get().removeListener("RoomState.members", this.onRoomStateMember); MatrixClientPeg.get().removeListener("sync", this.onSyncStateChange); } window.removeEventListener('resize', this.onResize); Tinter.tint(); // reset colourscheme }, onAction: function(payload) { switch (payload.action) { case 'message_send_failed': case 'message_sent': this.setState({ hasUnsentMessages: this._hasUnsentMessages(this.state.room) }); case 'message_resend_started': this.setState({ room: MatrixClientPeg.get().getRoom(this.props.roomId) }); this.forceUpdate(); break; case 'notifier_enabled': case 'upload_failed': case 'upload_started': case 'upload_finished': this.forceUpdate(); break; case 'call_state': // don't filter out payloads for room IDs other than props.room because // we may be interested in the conf 1:1 room if (!payload.room_id) { return; } var call = CallHandler.getCallForRoom(payload.room_id); var callState; if (call) { // Call state has changed so we may be loading video elements // which will obscure the message log. // scroll to bottom this.scrollToBottom(); callState = call.call_state; } else { callState = "ended"; } // possibly remove the conf call notification if we're now in // the conf this._updateConfCallNotification(); this.setState({ callState: callState }); break; case 'user_activity': case 'user_activity_end': // we could treat user_activity_end differently and not // send receipts for messages that have arrived between // the actual user activity and the time they stopped // being active, but let's see if this is actually // necessary. this.sendReadReceipt(); break; } }, onSyncStateChange: function(state, prevState) { if (state === "SYNCING" && prevState === "SYNCING") { return; } this.setState({ syncState: state }); }, // MatrixRoom still showing the messages from the old room? // Set the key to the room_id. Sadly you can no longer get at // the key from inside the component, or we'd check this in code. /*componentWillReceiveProps: function(props) { },*/ onRoomTimeline: function(ev, room, toStartOfTimeline) { if (this.unmounted) return; // ignore anything that comes in whilst paginating: we get one // event for each new matrix event so this would cause a huge // number of UI updates. Just update the UI when the paginate // call returns. if (this.state.paginating) return; // no point handling anything while we're waiting for the join to finish: // we'll only be showing a spinner. if (this.state.joining) return; if (room.roomId != this.props.roomId) return; var currentUnread = this.state.numUnreadMessages; if (!toStartOfTimeline && (ev.getSender() !== MatrixClientPeg.get().credentials.userId)) { // update unread count when scrolled up if (!this.state.searchResults && this.refs.messagePanel && this.refs.messagePanel.isAtBottom()) { currentUnread = 0; } else { currentUnread += 1; } } this.setState({ room: MatrixClientPeg.get().getRoom(this.props.roomId), numUnreadMessages: currentUnread }); }, onRoomName: function(room) { if (room.roomId == this.props.roomId) { this.setState({ room: room }); } }, updateTint: function() { var room = MatrixClientPeg.get().getRoom(this.props.roomId); if (!room) return; var color_scheme_event = room.getAccountData("org.matrix.room.color_scheme"); var color_scheme = {}; if (color_scheme_event) { color_scheme = color_scheme_event.getContent(); // XXX: we should validate the event } Tinter.tint(color_scheme.primary_color, color_scheme.secondary_color); }, onRoomAccountData: function(room, event) { if (room.roomId == this.props.roomId) { if (event.getType === "org.matrix.room.color_scheme") { var color_scheme = event.getContent(); // XXX: we should validate the event Tinter.tint(color_scheme.primary_color, color_scheme.secondary_color); } } }, onRoomReceipt: function(receiptEvent, room) { if (room.roomId == this.props.roomId) { var readMarkerEventId = this.state.room.getEventReadUpTo(MatrixClientPeg.get().credentials.userId); var readMarkerGhostEventId = this.state.readMarkerGhostEventId; if (this.state.readMarkerEventId !== undefined && this.state.readMarkerEventId != readMarkerEventId) { readMarkerGhostEventId = this.state.readMarkerEventId; } // if the event after the one referenced in the read receipt if sent by us, do nothing since // this is a temporary period before the synthesized receipt for our own message arrives var readMarkerGhostEventIndex; for (var i = 0; i < room.timeline.length; ++i) { if (room.timeline[i].getId() == readMarkerGhostEventId) { readMarkerGhostEventIndex = i; break; } } if (readMarkerGhostEventIndex + 1 < room.timeline.length) { var nextEvent = room.timeline[readMarkerGhostEventIndex + 1]; if (nextEvent.sender && nextEvent.sender.userId == MatrixClientPeg.get().credentials.userId) { readMarkerGhostEventId = undefined; } } this.setState({ readMarkerEventId: readMarkerEventId, readMarkerGhostEventId: readMarkerGhostEventId, }); } }, onRoomMemberTyping: function(ev, member) { this.forceUpdate(); }, onRoomStateMember: function(ev, state, member) { if (member.roomId === this.props.roomId) { // a member state changed in this room, refresh the tab complete list this._updateTabCompleteList(this.state.room); } if (!this.props.ConferenceHandler) { return; } if (member.roomId !== this.props.roomId || member.userId !== this.props.ConferenceHandler.getConferenceUserIdForRoom(member.roomId)) { return; } this._updateConfCallNotification(); }, _hasUnsentMessages: function(room) { return this._getUnsentMessages(room).length > 0; }, _getUnsentMessages: function(room) { if (!room) { return []; } // TODO: It would be nice if the JS SDK provided nicer constant-time // constructs rather than O(N) (N=num msgs) on this. return room.timeline.filter(function(ev) { return ev.status === Matrix.EventStatus.NOT_SENT; }); }, _updateConfCallNotification: function() { var room = MatrixClientPeg.get().getRoom(this.props.roomId); if (!room || !this.props.ConferenceHandler) { return; } var confMember = room.getMember( this.props.ConferenceHandler.getConferenceUserIdForRoom(this.props.roomId) ); if (!confMember) { return; } var confCall = this.props.ConferenceHandler.getConferenceCallForRoom(confMember.roomId); // A conf call notification should be displayed if there is an ongoing // conf call but this cilent isn't a part of it. this.setState({ displayConfCallNotification: ( (!confCall || confCall.call_state === "ended") && confMember.membership === "join" ) }); }, componentDidMount: function() { if (this.refs.messagePanel) { this._initialiseMessagePanel(); } var call = CallHandler.getCallForRoom(this.props.roomId); var callState = call ? call.call_state : "ended"; this.setState({ callState: callState }); this._updateConfCallNotification(); window.addEventListener('resize', this.onResize); this.onResize(); this._updateTabCompleteList(this.state.room); }, _updateTabCompleteList: function(room) { if (!room || !this.tabComplete) { return; } this.tabComplete.setCompletionList( MemberEntry.fromMemberList(room.getJoinedMembers()).concat( CommandEntry.fromCommands(SlashCommands.getCommandList()) ) ); }, _initialiseMessagePanel: function() { var messagePanel = ReactDOM.findDOMNode(this.refs.messagePanel); this.refs.messagePanel.initialised = true; messagePanel.addEventListener('drop', this.onDrop); messagePanel.addEventListener('dragover', this.onDragOver); messagePanel.addEventListener('dragleave', this.onDragLeaveOrEnd); messagePanel.addEventListener('dragend', this.onDragLeaveOrEnd); this.scrollToBottom(); this.sendReadReceipt(); this.updateTint(); }, componentDidUpdate: function() { // we need to initialise the messagepanel if we've just joined the // room. TODO: we really really ought to factor out messagepanel to a // separate component to avoid this ridiculous dance. if (!this.refs.messagePanel) return; if (!this.refs.messagePanel.initialised) { this._initialiseMessagePanel(); } }, _paginateCompleted: function() { debuglog("paginate complete"); // we might have switched rooms since the paginate started - just bin // the results if so. if (this.unmounted) return; this.setState({ room: MatrixClientPeg.get().getRoom(this.props.roomId), paginating: false, }); }, onSearchResultsFillRequest: function(backwards) { if (!backwards) return q(false); if (this.state.searchResults.next_batch) { debuglog("requesting more search results"); var searchPromise = MatrixClientPeg.get().backPaginateRoomEventsSearch( this.state.searchResults); return this._handleSearchResult(searchPromise); } else { debuglog("no more search results"); return q(false); } }, // set off a pagination request. onMessageListFillRequest: function(backwards) { if (!backwards) return q(false); // Either wind back the message cap (if there are enough events in the // timeline to do so), or fire off a pagination request. if (this.state.messageCap < this.state.room.timeline.length) { var cap = Math.min(this.state.messageCap + PAGINATE_SIZE, this.state.room.timeline.length); debuglog("winding back message cap to", cap); this.setState({messageCap: cap}); return q(true); } else if(this.state.room.oldState.paginationToken) { var cap = this.state.messageCap + PAGINATE_SIZE; debuglog("starting paginate to cap", cap); this.setState({messageCap: cap, paginating: true}); return MatrixClientPeg.get().scrollback(this.state.room, PAGINATE_SIZE). finally(this._paginateCompleted).then(true); } }, // return true if there's more messages in the backlog which we aren't displaying _canPaginate: function() { return (this.state.messageCap < this.state.room.timeline.length) || this.state.room.oldState.paginationToken; }, onResendAllClick: function() { var eventsToResend = this._getUnsentMessages(this.state.room); eventsToResend.forEach(function(event) { Resend.resend(event); }); }, onJoinButtonClicked: function(ev) { var self = this; MatrixClientPeg.get().joinRoom(this.props.roomId).then(function() { self.setState({ joining: false, room: MatrixClientPeg.get().getRoom(self.props.roomId) }); }, function(error) { self.setState({ joining: false, joinError: error }); var msg = error.message ? error.message : JSON.stringify(error); var ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createDialog(ErrorDialog, { title: "Failed to join room", description: msg }); }); this.setState({ joining: true }); }, onMessageListScroll: function(ev) { if (this.state.numUnreadMessages != 0 && this.refs.messagePanel.isAtBottom()) { this.setState({numUnreadMessages: 0}); } }, onDragOver: function(ev) { ev.stopPropagation(); ev.preventDefault(); ev.dataTransfer.dropEffect = 'none'; var items = ev.dataTransfer.items; if (items.length == 1) { if (items[0].kind == 'file') { this.setState({ draggingFile : true }); ev.dataTransfer.dropEffect = 'copy'; } } }, onDrop: function(ev) { ev.stopPropagation(); ev.preventDefault(); this.setState({ draggingFile : false }); var files = ev.dataTransfer.files; if (files.length == 1) { this.uploadFile(files[0]); } }, onDragLeaveOrEnd: function(ev) { ev.stopPropagation(); ev.preventDefault(); this.setState({ draggingFile : false }); }, uploadFile: function(file) { var self = this; ContentMessages.sendContentToRoom( file, this.props.roomId, MatrixClientPeg.get() ).done(undefined, function(error) { var ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createDialog(ErrorDialog, { title: "Failed to upload file", description: error.toString() }); }); }, getWhoIsTypingString: function() { return WhoIsTyping.whoIsTypingString(this.state.room); }, onSearch: function(term, scope) { this.setState({ searchTerm: term, searchScope: scope, searchResults: {}, searchHighlights: [], }); // if we already have a search panel, we need to tell it to forget // about its scroll state. if (this.refs.searchResultsPanel) { this.refs.searchResultsPanel.resetScrollState(); } // make sure that we don't end up showing results from // an aborted search by keeping a unique id. // // todo: should cancel any previous search requests. this.searchId = new Date().getTime(); var filter; if (scope === "Room") { filter = { // XXX: it's unintuitive that the filter for searching doesn't have the same shape as the v2 filter API :( rooms: [ this.props.roomId ] }; } debuglog("sending search request"); var searchPromise = MatrixClientPeg.get().searchRoomEvents({ filter: filter, term: term, }); this._handleSearchResult(searchPromise).done(); }, _handleSearchResult: function(searchPromise) { var self = this; // keep a record of the current search id, so that if the search terms // change before we get a response, we can ignore the results. var localSearchId = this.searchId; this.setState({ searchInProgress: true, }); return searchPromise.then(function(results) { debuglog("search complete"); if (self.unmounted || !self.state.searching || self.searchId != localSearchId) { console.error("Discarding stale search results"); return; } // postgres on synapse returns us precise details of the strings // which actually got matched for highlighting. // // In either case, we want to highlight the literal search term // whether it was used by the search engine or not. var highlights = results.highlights; if (highlights.indexOf(self.state.searchTerm) < 0) { highlights = highlights.concat(self.state.searchTerm); } // For overlapping highlights, // favour longer (more specific) terms first highlights = highlights.sort(function(a, b) { return b.length - a.length }); self.setState({ searchHighlights: highlights, searchResults: results, }); }, function(error) { var ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createDialog(ErrorDialog, { title: "Search failed", description: error.toString() }); }).finally(function() { self.setState({ searchInProgress: false }); }); }, getSearchResultTiles: function() { var EventTile = sdk.getComponent('rooms.EventTile'); var SearchResultTile = sdk.getComponent('rooms.SearchResultTile'); var cli = MatrixClientPeg.get(); // XXX: todo: merge overlapping results somehow? // XXX: why doesn't searching on name work? if (this.state.searchResults.results === undefined) { // awaiting results return []; } var ret = []; if (!this.state.searchResults.next_batch) { if (this.state.searchResults.results.length == 0) { ret.push(