-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathslacker.php
executable file
·1308 lines (1078 loc) · 29.6 KB
/
slacker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/php
<?php
/**
* Slacker App
* ===========
*
* Built with love by Burak Kanber of Tidal Labs. Licensed GPLv3 (see
* LICENSE.md) so that this always stays a for-fun project.
*
* Overview
* --------
*
* I'm sorry that all the code is in one file. Most of you don't consider it a
* good pattern. I don't either. But it was this or the alternatives of 1)
* making this a phar with that whole build system or 2) make some kind of
* Make-based build system. So I went with the light and easy option. This lets
* you just copy this single file wherever you want, run it with a php
* interpreter, and it just works.
*
* This file has a little bit of stray application logic (defining constants,
* opening the token file, and bootstrapping the Slack and Slacker objects),
* and several classes for the management of this app:
*
* - Slack - a simple wrapper around the slack API
* - Pane - an abstraction of an ncurses window
* - MenuPane - for the channel/group/im selection pane
* - RoomPane - for displaying room contents
* - Slacker - the application logic class (app loop, input handling, etc)
*
* App Lifecycle and Architecture
* ------------------------------
*
* The app starts by checking for a token in ~/.slack_token. If there's no file
* there, we alert the user, provide instructions, and exit.
*
* Otherwise, we initialize a Slack object, authenticated to the API, and give
* it to a Slacker object. The Slacker object orchestrates the interactions
* between all the components, and the user.
*
* The Pane class manages basic ncurses commands. It also maintains a write
* buffer. We use a buffer so we can check things like "height of the screen to
* be drawn" before drawing it. We use that for scrolling. It's actually pretty
* cool. I should write a blog post about that. It's not novel or anything.
* Just cool for us PHP folks that rarely get to do this. Routine for system
* programmers.
*
* The application loop runs after calling `start()` and will go infinitely.
* The user can exit pressing ESC, and SIGINT (C-c) seems to work fine too.
*
* At some point in the future, we'll also write to a ~/.slack_notification
* file, so that other programs like tmux can listen and display slack
* notifications ie in the status bar.
*
*/
/**
* First thing's first. Check if ncurses is available.
*/
if (!function_exists('ncurses_init')) {
echo <<<EODOC
Slacker: PHP ncurses is not available
=====================================
This app requires the ncurses PHP extension.
On Ubuntu you can try to automatically install dependencies by running
'sudo make ubuntu-dependencies'
For other platforms, or if that doesn't work, check out the README.md for more
information on installation dependencies.
EODOC;
exit;
}
/**
* First thing's second. Get a slack token.
*/
$tokenFile = $_SERVER['HOME']."/.slack_token";
$tokenFilePath = realpath($tokenFile);
if (!file_exists($tokenFilePath)) {
echo <<<EODOC
Slacker CLI App
===============
You need to install a slack API token at {$tokenFile}.
Get the token here: https://api.slack.com/web
Then paste the token into the {$tokenFile} file and restart this program.
EODOC;
exit;
}
$token = file_get_contents($tokenFilePath);
$token = trim($token);
define('SLACK_API', 'https://slack.com/api/');
define('ESCAPE_KEY', 27);
define('ENTER_KEY', 13);
/**
* Prints $str to STDOUT.
*
* Only use this in development. Here's a good pattern:
*
* php slacker.php 2> debug.log
*
*/
function debug($str) {
$stderr = fopen('php://stderr', 'w+');
fwrite($stderr, $str."\n");
fclose($stderr);
}
/**
* The next large section will be defining a bunch of classes. This is sloppy
* and hard to read because I haven't figured out how to make PHARs yet so this
* all needs to be in one file, for now.
*/
/**
* Used for Auth or token errors.
*/
class AuthException extends Exception { }
/**
* Abstracts the Slack API.
*
* Helps maintain and organize data on channels, users, messages, groups, ims,
* etc. Lots of convenience functions for accessing and manipulating this data.
*/
class Slack
{
// API token for the current user and team
private $token;
/**
* These store results of API calls. Most are formatted as assoc arrays
* with the key as the Slack ID of the object.
*
* The exception is the $messages variable, which is a 2D array. The first
* dimension is the channel ID of the messages underneath it.
*/
public $channels;
public $users;
public $messages;
public $groups;
public $ims;
public $me;
// Counter used internally to rate limit channels.info calls
public $channelInfoCounter = 0;
public $groupInfoCounter = 0;
/**
* Constructor takes a Slack token
*/
public function __construct($token)
{
$this->token = $token;
$this->getMe();
}
/**
* Submit a POST request to Slack API
*
* @param $methodName string XMLRPC-style method name for the API function you want
* @param $data array associative array of POST data
*
* @return array|null returns the 'message' portion of the post request
*/
function callPost($methodName, $data)
{
$url = SLACK_API.$methodName;
$data['token'] = $this->token;
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$json = json_decode($result, true);
if ($json && $json['ok'] && $json['message']) {
return $json['message'];
} else {
return null; // not ok
}
}
/**
* Call a GET method from the Slack API
*
* @param $methodName string method name to call
* @param $args array optional query params
*
* @return mixed the results of the call, or null
*/
function callGet($methodName, $args = null)
{
if ($args === null) {
$args = array();
}
$args['token'] = $this->token;
$raw = file_get_contents(
SLACK_API.$methodName.'?'.http_build_query($args)
);
$json = json_decode($raw, true);
return $json;
}
/**
* Fetch and store auth.test info
*/
public function getMe()
{
$response = $this->callGet('auth.test');
if ($response['ok']) {
$this->me = $response;
} else {
throw new AuthException('Auth response was not OK');
}
return $this->me;
}
/**
* Fetch and store groups.info
*
* @param $groupId string group id
*/
public function getGroupInfo($groupId)
{
$response = $this->callGet('groups.info', ['group' => $groupId]);
if ($response && $response['ok'] && $response['group']) {
$this->groups[$groupId] = $response['group'];
}
return $this->groups[$groupId];
}
/**
* Fetch and store channels.info
*
* @param $channelId string channel id
*/
public function getChannelInfo($channelId)
{
$response = $this->callGet('channels.info', ['channel' => $channelId]);
if ($response && $response['ok'] && $response['channel']) {
$this->channels[$channelId] = $response['channel'];
}
return $this->channels[$channelId];
}
/**
* Call getChannelInfo for all channels
*/
public function getAllChannelInfo()
{
foreach ($this->channels as $channelId => $channel) {
$this->getChannelInfo($channelId);
}
}
/**
* Calls getgroupInfo for a different group each time it's called
*
* Used so we can refresh only one group per sample period.
*/
public function getNextGroupInfo()
{
$i = 0;
foreach ($this->groups as $groupId => $group) {
if ($i === $this->groupInfoCounter) {
$this->getGroupInfo($groupId);
break;
}
$i++;
}
$this->groupInfoCounter++;
if ($this->groupInfoCounter > count($this->groups)) {
$this->groupInfoCounter = 0;
}
}
/**
* Calls getChannelInfo for a different channel each time it's called
*
* Used so we can refresh only one channel per sample period.
*/
public function getNextChannelInfo()
{
$i = 0;
foreach ($this->channels as $channelId => $channel) {
if ($i === $this->channelInfoCounter) {
$this->getChannelInfo($channelId);
break;
}
$i++;
}
$this->channelInfoCounter++;
if ($this->channelInfoCounter > count($this->channels)) {
$this->channelInfoCounter = 0;
}
}
/**
* Fetch data from an endpoint, and re-key it into one of the instance
* variables in this class.
*
* This method is used by getChannels, getUsers, etc, to make an API
* request and then re-index the array with their object IDs.
*
* @param $methodName string the method name to call
* @param $parameters array query parameters to pass to the API. Required, but empty array OK
* @param $localVariable string the name of the local instance variable to put the results into ("channels", "users", etc)
* @param $resultVariable string the name of the Slack API response array key to grab results from
*
* @return the instance variable specified by $localVariable
*/
private function _fetchAndStore($methodName, $parameters, $localVariable, $resultVariable)
{
$result = $this->callGet($methodName, $parameters);
$this->{$localVariable} = [];
foreach ($result[$resultVariable] as $item) {
$this->{$localVariable}[$item['id']] = $item;
}
return $this->{$localVariable};
}
/**
* Grab all the channels
*
* Removes channels that you're not a member of from the list. We could
* simply hide these channels from display. But it's fewer lines of code to
* just remove them completely. And removing them completely means they
* don't get refreshed every couple of seconds.
*/
public function getChannels()
{
$this->_fetchAndStore(
'channels.list',
['exclude_archived' => 1],
'channels',
'channels'
);
foreach ($this->channels as $channelId => $channel) {
if (isset($channel['is_member']) && $channel['is_member'] === false) {
unset($this->channels[$channelId]);
}
}
return $this->channels;
}
/**
* Grab all the users from the API
*/
public function getUsers()
{
return $this->_fetchAndStore(
'users.list',
[],
'users',
'members'
);
}
/**
* Grab all the groups from the API
*/
public function getGroups()
{
return $this->_fetchAndStore(
'groups.list',
['exclude_archived' => 1],
'groups',
'groups'
);
}
/**
* Grab all the IMs from the api.
*
* This method does a little more work to clean up the query results. The
* IM objects don't include a 'name' param like the others do, so we fill
* it in from the users list for convenience and normalization.
*/
public function getIms()
{
$this->_fetchAndStore(
'im.list',
[],
'ims',
'ims'
);
foreach ($this->ims as $key => $im) {
if ($im['is_user_deleted']) {
unset($this->ims[$key]);
continue;
}
if (isset($this->users[$im['user']])) {
$userObj = $this->users[$im['user']];
} else {
$userObj = ['name' => 'slackbot'];
}
$userName = $userObj['name'];
$this->ims[$key]['name'] = $userName;
}
return $this->ims;
}
/**
* Find a channel object in our local cache by the channel's name
*
* Only really used for initializing the client to display "General" on startup.
*/
public function getChannelByName($name)
{
foreach ($this->channels as $channel) {
if ($name === $channel['name']) {
return $channel;
}
}
return null;
}
/**
* Fetch messages for a channel from the API
*
* Handles Channels, Groups, and IMs. Stores the messages in our local
* cache. Also manages passing the timestamp for the most-recent message
* we've seen to the API. We also have to do a little work to make sure we
* have the messages in the right order.
*/
public function getMessages($channel)
{
// Translate $channel 'type' to a method name.
if ('Channels' === $channel['type']) {
$methodName = 'channels.history';
} else if ('Groups' === $channel['type']) {
$methodName = 'groups.history';
} else if ('IMs' === $channel['type']) {
$methodName = 'im.history';
} else {
throw new \BadMethodCallException("Channel type not recognized. Should be one of 'Channels', 'Groups', or 'IMs'");
}
// Check if channel has existing messages
$parameters = ['channel' => $channel['id']];
if (isset($this->messages[$channel['id']])) {
$messages = $this->messages[$channel['id']];
$parameters['oldest'] = $messages[0]['ts'];
} else {
$messages = [];
}
$result = $this->callGet(
$methodName,
$parameters
);
$incomingMessages = $result['messages'];
$incomingMessages = array_reverse($incomingMessages);
foreach ($incomingMessages as $incomingMessage) {
array_unshift($messages, $incomingMessage);
}
$this->messages[$channel['id']] = $messages;
return $this->messages[$channel['id']];
}
/**
* Replace Slack message tokens like <@UXORUER> with their human-readable
* counterparts.
*
* This method will replace user tags and channel tags. See here:
* https://api.slack.com/docs/formatting
*
* @param $messageText string text of the message to format
*
* @return string ready-to-display message
*/
public function formatMessage($messageText) {
preg_match_all("/<(.*?)>/", $messageText, $matches);
foreach ($matches[1] as $match) {
$itemId = substr($match, 1);
if (($pipePos = strpos($itemId, '|')) !== false) {
$itemId = substr($itemId, 0, $pipePos);
}
$fullMatch = '<'.$match.'>';
if ('@' === substr($match, 0, 1)) {
// It's a user.
if (isset($this->users[$itemId])) {
$messageText = str_replace(
$fullMatch,
'@'.$this->users[$itemId]['name'],
$messageText
);
}
} else if ('#' === substr($match, 0, 1)) {
// It's a Channel
if (isset($this->channels[$itemId])) {
$messageText = str_replace(
$fullMatch,
'#'.$this->channels[$itemId]['name'],
$messageText
);
}
}
}
return $messageText;
}
}
/**
* Abstracts ncurses windows
*
* Has a few nice conveniences over ncurses. The only "novel" feature of this
* class is the scrolling buffer. We're buffering addstr commands so we can
* figure out how tall the screen would be before writing it. We can then
* manipulate the buffer to make it scroll before writing it to the screen.
*
* Make an instance of this class if you want to make a "window" (what I call a
* "pane") on the screen. This class is much nicer than using the ncurses*
* functions directly.
*/
class Pane
{
public $height;
public $width;
public $y;
public $x;
public $window;
public $isBordered = false;
public $isDirty = true;
public $slack;
public $currentChannel;
public $scrollTop = 0;
private $buffer;
public function __construct($height, $width, $y, $x)
{
$this->y = $y;
$this->x = $x;
$this->window = ncurses_newwin($height, $width, $this->y, $this->x);
ncurses_getmaxyx($this->window, $this->height, $this->width);
}
/**
* Clears the window
*/
public function clear()
{
$this->isDirty = true;
ncurses_werase($this->window);
return $this;
}
/**
* Get stats on the window write buffer.
*
* Returns an assoc array with 'min' (the first line number in the buffer),
* 'max' (highest line number in the buffer, and 'height' (the total height
* of the buffer).
*/
public function bufferStats()
{
$min = 999999999;
$max = 0;
foreach ($this->buffer as $item) {
if ($item['y'] < $min) {
$min = $item['y'];
}
if ($item['y'] > $max) {
$max = $item['y'];
}
}
$height = ($max - $min) + 1;
return ['height' => $height, 'minY' => $min, 'maxY' => $max];
}
/**
* Height of the current buffer
*/
public function bufferHeight()
{
$stats = $this->bufferStats();
return $stats['height'];
}
/**
* Write the buffer to the screen
*
* Also resets the buffer
*/
public function playBuffer()
{
foreach ($this->buffer as $item) {
$this->playBufferItem($item);
}
$this->buffer = [];
return $this;
}
/**
* Write an individual buffer command to the screen
*
* Probably never needs to be called directly
*/
public function playBufferItem($item)
{
// Adjust offset
$item['y'] -= $this->scrollTop;
// Skip this item if it's offscreen
if ($item['y'] < 1) {
return $this;
}
if ($item['y'] >= $this->height-1) {
return $this;
}
$optionMapping = [
'reverse' => NCURSES_A_REVERSE,
'bold' => NCURSES_A_BOLD
];
foreach ($optionMapping as $option => $ncursesAttribute) {
if (isset($item['options'][$option]) && $item['options'][$option]) {
ncurses_wattron($this->window, $ncursesAttribute);
}
}
ncurses_mvwaddstr($this->window, $item['y'], $item['x'], $item['str']);
foreach ($optionMapping as $option => $ncursesAttribute) {
if (isset($item['options'][$option]) && $item['options'][$option]) {
ncurses_wattroff($this->window, $ncursesAttribute);
}
}
return $this;
}
/**
* Write a string to a location on the screen
*
* This method actually adds the command to the buffer for playback later.
* Do not expect this command to write immediately to the screen. That
* happens when playBuffer is called, which happens in draw().
*
* @param $y int column
* @param $x int row
* @param $str string the string to write
* @param $options array additional options. Currently only 'reverse' (for NCURSES_A_REVERSE) is supported.
*
* @return this
*/
public function addStr($y, $x, $str, $options = array())
{
$this->isDirty = true;
$this->buffer[] = ['y' => $y, 'x' => $x, 'str' => $str, 'options' => $options];
return $this;
}
/**
* Commit the buffer to the screen
*
* Also manages the border and refreshing the window
*/
public function draw($force = false)
{
if ($this->isDirty || $force) {
if ($this->isBordered) {
ncurses_wborder($this->window, 0, 0, 0, 0, 0, 0, 0, 0);
}
$this->bufferHeight();
$this->playBuffer();
ncurses_wrefresh($this->window);
}
}
}
/**
* Manages the Channels/IMs/Groups menu
*
* Extends from Pane. This is more of a concrete class than an abstract one:
* it's all about managing that menu. It displays it, and handles the logic for
* selecting and switching rooms.
*/
class MenuPane extends Pane
{
public $highlightedMenuItem = null;
public $highlightedMenuItemData;
/**
* Render a submenu (Channels, IMs, Groups)
*/
public function renderSubmenu($title, $items, $startLineNumber)
{
// Check if we have a highlightedMenuItem set.
if ($this->highlightedMenuItem === null) {
$counter = $startLineNumber + 2;
foreach ($this->slack->channels as $channel) {
if ($channel['name'] === $this->currentChannel['name']) {
$this->highlightedMenuItem = $counter;
}
$counter++;
}
}
// Yes, we're just renaming the variable.
// Why two names? Because $startLineNumber really tells you what the
// variable is for.
$index = $startLineNumber;
// say hi
$this->addStr($index, 2, $title, ['bold' => true]);
$index += 2;
foreach ($items as $item) {
$options = [];
if (
$this->currentChannel['id'] === $item['id']
|| $this->highlightedMenuItem === $index
) {
$options['reverse'] = true;
}
$text = '';
if (isset($item['unread_count_display']) && $item['unread_count_display']) {
$text .= "[".$item['unread_count_display']."] ";
}
$text .= $item['name'];
$this->addStr($index, 2, $text, $options);
if ($this->highlightedMenuItem === $index) {
$this->highlightedMenuItemData = [
'type' => $title,
'id' => $item['id'],
'name' => $item['name']
];
}
$index++;
}
}
public function renderChannels($startLineNumber = 1)
{
$this->renderSubmenu("Channels", $this->slack->channels, $startLineNumber);
return $this;
}
public function renderGroups($startLineNumber = 20)
{
$this->renderSubmenu("Groups", $this->slack->groups, $startLineNumber);
return $this;
}
public function renderIms($startLineNumber = 30)
{
$this->renderSubmenu("IMs", $this->slack->ims, $startLineNumber);
return $this;
}
/**
* Render the whole menu
*
* Does some logic to figure out the spacing, that's all. Otherwise just
* calls the other helper methods.
*/
public function renderMenu()
{
$this->renderChannels(1);
$imStartLine = count($this->slack->channels) + 4;
$this->renderIms($imStartLine);
$groupStartLine = $imStartLine + count($this->slack->ims) + 4;
$this->renderGroups($groupStartLine);
return $this;
}
/**
* Call this to scroll up one item
*/
public function scrollUp()
{
$this->highlightedMenuItem--;
$this->fixScrollTop();
$this->clear()->renderMenu()->draw();
return $this;
}
/**
* Call this to scroll down one item
*/
public function scrollDown()
{
$this->highlightedMenuItem++;
$this->fixScrollTop();
$this->clear()->renderMenu()->draw();
return $this;
}
/**
* Keeps the current highlighted item on-screen
*/
public function fixScrollTop()
{
if ($this->highlightedMenuItem > $this->height - 10) {
$this->scrollTop = 10 - ($this->height - $this->highlightedMenuItem);
}
if ($this->highlightedMenuItem < $this->height - 10) {
$this->scrollTop = 0;
}
}
}
/**
* Manages the chat room view
*
* Concrete class that manages word-wrapping and rendering chat history.
*/
class RoomPane extends Pane
{
/**
* Renders the contents of the room
*
* Does some cool word/line wrapping to make sure we're formatted nicely
* for our window size
*/
public function renderRoom()
{
$availableLines = $this->height - 4;
$availableWidth = $this->width - 10;
$lineNumber = 3;
$messages = $this->slack->messages[$this->currentChannel['id']];
$messages = array_reverse($messages);
$lines = [];
foreach ($messages as $index => $message) {
if (isset($message['user']) && isset($this->slack->users[$message['user']])) {
$user = $this->slack->users[$message['user']];
} else {
$user = null;
}
$messageText = ($user ? $user['name'] : 'bot').': '.$message['text'];
$messageText = $this->slack->formatMessage($messageText);
$messageText = wordwrap($messageText, $availableWidth, "\n\t");
foreach (explode("\n", $messageText) as $line) {
$lines[] = $line;
}
// Blank line below each message
$lines[] = '';
}
// Slice $lines to the last $availableLines
$lines = array_slice($lines, -1*$availableLines, $availableLines);
// Actually writes to the buffer, finally
foreach ($lines as $index => $line) {
$this->addStr($lineNumber, 2, $line);
$lineNumber++;
}
// Print the channel name at the top
$this->addStr(
1,
2,
$this->currentChannel['name'],
['reverse' => true]
);
return $this;
}
}
/**
* The application class
*
* Manages the various Panes in the app, manages the event loop, manages input
* and UX, and other application-level features.
*/
class Slacker
{
public $slack;
/**
* $currentChannel is not always a channel, could be a Group or an IM too
*
* It has a specific format. Looks like this:
*
* [
* 'name' => ...
* 'id' => ...
* 'type' => Groups, Channels, or IMs
* ]
*/
public $currentChannel;
public $paneMain;
public $paneLeft;
public $paneRight;
public $paneInput;
public $running = true;
public $iterations = 0;
// Current contents of the message box