Skip to content
This repository has been archived by the owner on Nov 11, 2019. It is now read-only.

Commit

Permalink
Merge pull request #6 from RocketChat/new-freddie
Browse files Browse the repository at this point in the history
converted to js, added multiples rooms, etc...
  • Loading branch information
ggazzo authored May 30, 2017
2 parents d402047 + d6e52aa commit bb0515d
Show file tree
Hide file tree
Showing 5 changed files with 122 additions and 56 deletions.
7 changes: 2 additions & 5 deletions matrix.org/hubot-freddie/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Next, you must edit the `external-scripts.json` file to load Freddie:

# Home Server Application Service Registration

In the `node_modules/hubot-freddie` directory:
In the `node_modules/hubot-freddie` directory:

```
npm install
Expand Down Expand Up @@ -82,7 +82,4 @@ HOMESERVER_SENDER_LOCAL | the local user on the Home Server that will create new
INCOMING_PORT | the port at which this bot will listen to incoming messages from the Home Server
ROCKETCHAT_USER_PREFIX | the prefix added to the Rocket.Chat user name when messages are sent on his/her behalf to the Home Server
WRITABLE_CONFIG_PATH | the absolute path of the directory where the bot's Matrix bridge can find the `rocketchat-registration.yaml` Application Service configuration file, this file **must** be identical to the one registered with the Home Server




ROOM_MAP | a list of rooms to map, use `ID_ROCKETCHAT=ID_MATRIX,...,...` same as `HOMESERVER_ROOM_ID` `ROCKETCHAT_ROOM_ID`
58 changes: 58 additions & 0 deletions matrix.org/hubot-freddie/src/bridge.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'use strict';
module.exports = (HomeServerDomain, RocketChatUserPrefix, HomeServerURL) => {
const handleMatrixMessage = (event, robot, matrix, rocketRoomId, matrixRoomId) => {
console.log('[handleMatrixMessage]');
const msgpayload = { channel: rocketRoomId, alias: event.user_id, msg: event.content.body };
return getUserFromMatrix(event.user_id, matrix).then(function (data) {
if(data.avatar) {
msgpayload.avatar = data.avatar;
}
if(data.displayname) {
msgpayload.alias = `${data.displayname}:${HomeServerDomain}`
}
return msgpayload
}, (e) => {
console.error(e);
return msgpayload
})
.then(msgpayload => {
console.log(`Sending "${ msgpayload.msg }" to Matrix:${ matrixRoomId }`);
robot.adapter.customMessage(msgpayload);
});
}
function getUserFromMatrix(userId, matrix) {
console.log('[getUserFromMatrix]')
const intent = matrix.getBridge().getIntent();
// send the message coming in from the HS into Rocket.Chat room
return intent.client.getProfileInfo(userId).then(function(data){
console.log('[getUserFromMatrix] SUCCESS')
const regex = new RegExp(`(mxc:\/\/)(${escapeRegExp(HomeServerDomain)}\/.*)`, 'g');
const str = data.avatar_url;
const subst = `${HomeServerURL}/_matrix/media/v1/thumbnail/$2?width=96&height=96&method=crop`;
return { avatar: (str || '').replace(regex, subst) || '', displayname: data.displayname}
}, error => {
console.log('[getUserFromMatrix] ERROR')
console.error(error);
throw error;
});
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
const getMaps = (params) => {
let tmp = params.HomeServerRoomID && params.RocketChatRoomID ? `${ params.RocketChatRoomID }=${ params.HomeServerRoomID }` : '';
console.log(tmp);
if (process.env['ROOM_MAP']){
tmp += (tmp? ',': '') + process.env['ROOM_MAP']
}
console.log(tmp);
return tmp.split(',').map(val => val.split('='))
}
const handleRocketChatMessage = (msg, matrixRoomId, matrix) => {
// send the received Rocket.Chat message into the paired HS
const intent = matrix.getBridge().getIntent(RocketChatUserPrefix + msg.message.user.name.toLowerCase() + ":" + HomeServerDomain );
console.log(`Sending "${ msg.message.text }" to Matrix:${ matrixRoomId }`);
return intent.sendText(matrixRoomId, msg.message.text);
}
return {maps: getMaps, handleMatrixMessage, handleRocketChatMessage};
}
32 changes: 0 additions & 32 deletions matrix.org/hubot-freddie/src/hubot-freddy.coffee

This file was deleted.

35 changes: 35 additions & 0 deletions matrix.org/hubot-freddie/src/hubot-freddy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';
const matrixBridge = require('./matrix/matrixbridge');
const HomeServerURL = process.env['HOMESERVER_URL'] || 'http://0.0.0.0:8008';
const HomeServerDomain = process.env['HOMESERVER_DOMAIN'] || '0.0.0.0';
const HomeServerRoomID = process.env['HOMESERVER_ROOM_ID'] || '!WKVTQyzUAjcsqmTGjA:35.185.41.10,'; // HomeServer federated room id
const RocketChatRoomID = process.env['ROCKETCHAT_ROOM_ID'] || 'WIJbAHNEdgMNavYM5'; // Rocket.Chat federated room id
const HomeServerSenderLocal = process.env['HOMESERVER_SENDER_LOCAL'] || 'rcbot';
const IncomingPort = process.env['INCOMING_PORT'] || 8089;
const RocketChatUserPrefix = process.env['ROCKETCHAT_USER_PREFIX'] || '@rocketchat_'; // user name prefix for Rocket.Chat users
const WritableConfigPath = process.env['WRITABLE_CONFIG_PATH'] || './config'; // path of directory to write configuarion file

const bridgeHelpers = require('./bridge')(HomeServerDomain, RocketChatUserPrefix, HomeServerURL)
const handleMatrixMessage = bridgeHelpers.handleMatrixMessage;
const handleRocketChatMessage = bridgeHelpers.handleRocketChatMessage;
const ROOM_MAP = bridgeHelpers.maps({HomeServerRoomID: HomeServerRoomID, RocketChatRoomID: RocketChatRoomID});


module.exports = function(robot) {

const regFileFullPath = WritableConfigPath + '/' + 'rocketchat-registration.yaml';
// start the matrix bridge and pass in our request handler
matrixBridge.run(IncomingPort, { hsurl : HomeServerURL, domain: HomeServerDomain, registration: regFileFullPath}, {
onMessage:(event, rocketRoomId, matrixRoomId) => {
handleMatrixMessage(event, robot, matrixBridge, rocketRoomId, matrixRoomId)
}
}, ROOM_MAP).then(() => {
// messages coming from Rocket.Chat room(s) monitored
robot.hear(/.*/, (msg) => {
const room = ROOM_MAP.findIndex((ids) => msg.message.room == ids[0])
if(room < 0 ) { return }
return handleRocketChatMessage(msg, ROOM_MAP[room][1], matrixBridge)
})
ROOM_MAP.forEach(ids => console.log(`Mapping Rocketchat(${ ids[0] }) <==> Matrix(${ ids[1] })`))
});
};
46 changes: 27 additions & 19 deletions matrix.org/hubot-freddie/src/matrix/matrixbridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,35 @@ var AppServiceRegistration = require("matrix-appservice-bridge").AppServiceRegis
var localbridge;

var bridge = {
run: function(port, config, eventHanlder) {
localbridge = new Bridge({
homeserverUrl: config.hsurl,
domain: config.domain,
registration: config.registration,
controller: {
onUserQuery: function(queriedUser) {
return {}; // auto-provision users with no additonal data
},

onEvent: eventHanlder
run: function (port, config, eventHandler, mapRoom ) {
localbridge = new Bridge({
homeserverUrl: config.hsurl,
domain: config.domain,
registration: config.registration,
controller: {
onUserQuery: function(queriedUser) {
return {}; // auto-provision users with no additonal data
},
onEvent: (request, context) => {
const event = request.getData();
if (event.type !== "m.room.message" || !event.content) {
return;
}
const room = mapRoom.findIndex((ids) => event.room_id == ids[1])
console.log(room,mapRoom, event.room_id);
if(room > -1) {
eventHandler.onMessage(event, mapRoom[room][0], mapRoom[room][1])
}
}
});
console.log("Matrix-side listening on port %s", port);
localbridge.run(port, config);
},
}
});
console.log("Matrix-side listening on port %s", port);
return localbridge.run(port, config);
},
getBridge: function() {
return localbridge;
}
};
return localbridge;
}
};


module.exports = bridge;

0 comments on commit bb0515d

Please sign in to comment.