Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lamer-x11 committed Jun 17, 2018
0 parents commit fdb81c9
Show file tree
Hide file tree
Showing 8 changed files with 538 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
session/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Lamer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.PHONY: build
build:
docker build -t sssc dockerfiles/

.PHONY: dev
dev:
docker run -ti --rm -v $(CURDIR):/app sssc ash

60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# SSSC

Simple and Stupid Slack Client

## Features

SSSC is closely modeled after [(ii)](https://tools.suckless.org/ii/) which means that communication is facilitated by an `out` file and an `in` FIFO on the filesystem.

No features other than sending and receiving messages while connected are supported. Retrieval of unread messages may be implemented at a later date, in a separate branch.

Incoming data not handled by SSSC will be printed to stdout as formatted JSON.

## Installation

```
$ yarn install
```

A Slack api token has to be provided as an environment variable called `TOKEN`. There's a Dockerfile included in the repository for convenience.

## Usage

Upon successful connection to Slack a directory with every channel, group and im will be created in the project root like so:

```
session/
'-- your_team_name/
|-- general/
| |-- in
| '-- out
|-- random/
| |-- in
| '-- out
|-- alice/
| |-- in
| '-- out
'-- bob/
|-- in
'-- out
```

To send a message to alice:

```
$ echo "Hi" > ./session/your_team_name/alice/in
```

To keep track of the conversation:

```
$ tail -f ./session/you_team_name/alice/out
```

Incoming messages are formatted as follows:

```
{timestamp} <{username}> {text}
```

It's up to the user to further process this output as needed using his preferred method of text manipulation.
16 changes: 16 additions & 0 deletions dockerfiles/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
FROM mhart/alpine-node:10

RUN apk update

RUN adduser -D -u 1000 dev

RUN apk add --no-cache curl make sudo
RUN echo "dev ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

WORKDIR /app
RUN chown dev:dev /app

ENV HOME /home/dev
USER dev

CMD /usr/bin/node sssc.js
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"dependencies": {
"request": "^2.85.0",
"ws": "^5.1.0"
}
}
151 changes: 151 additions & 0 deletions sssc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
#!/usr/bin/env node

const { spawnSync } = require('child_process')
const request = require('request');
const fs = require('fs');
const WebSocket = require('ws');
const C = require('constants');
const path = require('path');

const SESSION_DIR = path.resolve(__dirname, './session');

if (!fs.existsSync(SESSION_DIR)) {
fs.mkdirSync(SESSION_DIR);
}

const map = {};

callSlackMethod('rtm.start', (data) => {
if (data.ok === false) {
process.stderr.write(JSON.stringify(data, null, 2) + '\n');

return;
}

const userName = data.self.name;
const teamName = data.team.name;

if (!fs.existsSync(`${SESSION_DIR}/${teamName}`)) {
fs.mkdirSync(`${SESSION_DIR}/${teamName}`);
}

map[data.self.id] = data.self.name;
map[data.team.id] = teamName;

for (let i = 0; i < data.users.length; i++) {
map[data.users[i].id] = data.users[i].name;
}

const chats = [].concat(
data.channels,
data.groups,
data.ims.map(im => {
im.name = map[im.user];

return im;
}),
);

const socket = new WebSocket(data.url);
const sendBuffer = {};

for (let i = 0; i < chats.length; i++) {
setupChat(socket, sendBuffer, teamName, chats[i]);
}

socket.on('message', (rawMessage) => {
let message = JSON.parse(rawMessage);

if (message.type === 'message') {
if (message.subtype === 'message_changed') {
const sub = message.message;

sub.text = '(*) ' + sub.text;
sub.channel = message.channel;

message = sub;
}

fs.appendFileSync(
`${SESSION_DIR}/${teamName}/${map[message.channel]}/out`,
`${message.ts} <${map[message.user]}> ${message.text}\n`,
);

return;
}

if (message.type === 'group_joined' || message.type === 'channel_created') {
setupChat(socket, sendBuffer, teamName, message.channel);

return;
}

if (sendBuffer[message.reply_to] !== undefined && message.ok === true) {
fs.appendFileSync(
`${SESSION_DIR}/${teamName}/${map[sendBuffer[message.reply_to]]}/out`,
`${message.ts} <${userName}> ${message.text}\n`,
);

delete sendBuffer[message.reply_to];

return;
}

process.stdout.write(JSON.stringify(message, null, 2));
});
});

function setupChat(socket, sendBuffer, teamName, chat) {
map[chat.id] = chat.name;

if (!fs.existsSync(`${SESSION_DIR}/${teamName}/${chat.name}`)) {
fs.mkdirSync(`${SESSION_DIR}/${teamName}/${chat.name}`);
fs.writeFileSync(`${SESSION_DIR}/${teamName}/${chat.name}/out`, '');
spawnSync('mkfifo', [`${SESSION_DIR}/${teamName}/${chat.name}/in`]);
}

const inFifo = `${SESSION_DIR}/${teamName}/${chat.name}/in`;
const fd = fs.openSync(inFifo, C.O_RDONLY | C.O_NONBLOCK);

setInterval(() => {
const allocSize = 1024;

fs.read(fd, Buffer.alloc(allocSize), 0, allocSize, null, (error, size, buffer) => {
if (size > 0) {
const id = Date.now();

// remove trailing newlines
if (size < allocSize) {
while (size > 0 && buffer[size - 1] === 10) {
--size;
}
}

const text = buffer.slice(0, size).toString();

socket.send(JSON.stringify({id, channel: chat.id, type: 'message', text}));

sendBuffer[String(id)] = chat.id;
}
});
}, 128);
}

function callSlackMethod(apiMethod, callback = (...args) => {}, params = {}) {
// @Incomplete: replace external library with a simple https call
request.get(
{
url: `https://slack.com/api/${apiMethod}`,
qs: Object.assign({}, params, {token: process.env.TOKEN}),
json: true,
},
(error, response, data) => {
if (error !== null) {
console.log(error);
return;
}

callback(data, response);
}
);
}
Loading

0 comments on commit fdb81c9

Please sign in to comment.