-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathiris.rb
executable file
·1143 lines (938 loc) · 29.8 KB
/
iris.rb
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/env ruby
require 'base64'
require 'digest'
require 'etc'
require 'json'
require 'readline'
require 'set'
require 'tempfile'
require 'time'
# require 'pry' # Only needed for debugging
class NilClass
def presence
self
end
end
class String
def presence
return nil if self.length == 0
self
end
end
class Config
VERSION = '1.1.3'
MESSAGE_FILE = "#{ENV['HOME']}/.iris.messages"
HISTORY_FILE = "#{ENV['HOME']}/.iris.history"
IRIS_SCRIPT = __FILE__
ENV_EDITOR = ENV['EDITOR'].presence || `which nano`.chomp.presence
@@debug_mode = false
def self.hostname
return @hostname if @hostname
hostname = `hostname`.chomp
hostname = 'localhost' if hostname.empty?
components = hostname.split('.')
return @hostname = hostname if components.length == 1
@hostname = components[-2..-1].compact.join('.')
end
def self.author
user = ENV['USER'] || ENV['LOGNAME'] || ENV['USERNAME']
@author ||= "#{user}@#{self.hostname}"
end
def self.find_files
(`ls /home/**/.iris.messages`).split("\n")
end
def self.messagefile_filename
$test_corpus_file || Config::MESSAGE_FILE
end
def self.readfile_filename
"#{messagefile_filename}.read"
end
def self.enable_debug_mode
@@debug_mode = true
end
def self.debug?
@@debug_mode
end
end
class String
COLOR_MAP = {
'n' => '0',
'i' => '1',
'u' => '4',
'v' => '7',
'r' => '31',
'g' => '32',
'y' => '33',
'b' => '34',
'm' => '35',
'c' => '36',
'w' => '37',
}
COLOR_RESET = "\033[0m"
def color_token
if self !~ /\w/
return { '\{' => '|KOPEN|', '\}' => '|KCLOSE|', '}' => COLOR_RESET}[self]
end
tag = self.scan(/\w/).map{ |t| COLOR_MAP[t] }.sort.join(';')
"\033[#{tag}m"
end
def colorize
r = /\\{|{[rgybmcwniuv]+\s|\\}|}/
split = self.split(r, 2)
return self.color_bounded if r.match(self).nil?
newstr = split.first + $&.color_token + split.last
if r.match(newstr).nil?
return (newstr + COLOR_RESET).gsub(/\|KOPEN\|/, '{').gsub(/\|KCLOSE\|/, '}').color_bounded
end
newstr.colorize.color_bounded
end
def decolorize
self.
gsub(/\\{/, '|KOPEN|').
gsub(/\\}/, '|KCLOSE|').
gsub(/{[rgybmcwniuv]+\s|}/, '').
gsub(/\|KOPEN\|/, '{').
gsub(/\|KCLOSE\|/, '}')
end
def wrapped(width = Display::WIDTH)
self.gsub(/.{1,#{width}}(?:\s|\Z|\-)/) {
($& + 5.chr).gsub(/\n\005/,"\n").gsub(/\005/,"\n")
}
end
def pluralize(count)
count == 1 ? self : self + 's'
end
def color_bounded
COLOR_RESET + self.gsub(/\n/, "\n#{COLOR_RESET}") + COLOR_RESET
end
end
class Corpus
def self.load
if $test_corpus_file
@@corpus = IrisFile.load_messages
else
@@corpus = Config.find_files.map { |filepath| IrisFile.load_messages(filepath) }.flatten.sort_by(&:timestamp)
end
@@my_corpus = IrisFile.load_messages.sort_by(&:timestamp)
@@my_read_hashes = IrisFile.load_reads
@@unread_messages = nil
@@all_hash_to_index = @@corpus.reduce({}) { |agg, msg| agg[msg.hash] = @@corpus.index(msg); agg }
@@edited_hashes = @@corpus.map(&:edit_hash).compact
@@topics = @@corpus.select(&:is_topic?)
@@all_parent_hash_to_index = @@corpus.reduce({}) do |agg, msg|
agg[msg.parent] ||= []
agg[msg.parent] << @@corpus.index(msg)
agg
end
end
def self.to_json
@@corpus.to_json
end
def self.edited_hashes
@@edited_hashes
end
def self.topics
@@topics
end
def self.authors
@@corpus.map(&:author).uniq.sort
end
def self.mine
@@my_corpus
end
def self.is_mine?(message)
@@my_corpus.map(&:hash).include? message.hash
end
def self.index_of(message)
@@corpus.map(&:hash).index message.hash
end
def self.topic_index_of(message)
@@topics.map(&:hash).index message.hash
end
def self.find_message_by_hash(hash)
return nil unless hash
index = @@all_hash_to_index[hash]
return nil unless index
@@corpus[index]
end
def self.find_all_by_parent_hash(hash)
return [] unless hash
indexes = @@all_parent_hash_to_index[hash]
return [] unless indexes
indexes.map{ |idx| @@corpus[idx] }.compact.select(&:show_me?)
end
def self.find_topic_by_id(topic_lookup)
return nil unless topic_lookup
index = topic_lookup.to_i - 1
@@topics[index] if index >= 0 && index < @@topics.length
end
def self.find_message_by_id(message_lookup)
return nil unless message_lookup && message_lookup =~ /\AM\d+\Z/
index = message_lookup.gsub(/M/, '').to_i - 1
@@corpus[index] if index >= 0 && index < @@corpus.length
end
def self.find_topic_by_hash(topic_lookup)
return nil unless topic_lookup
find_message_by_hash(topic_lookup)
end
def self.unread_messages
@@unread_messages ||= @@corpus
.select { |message| message.show_me? }
.reject{ |m| @@my_read_hashes.include? m.hash }
.reject{ |m| @@my_corpus.map(&:hash).include? m.hash }
end
def self.unread_topics
@@topics.select do |m|
# Is the topic unread, or are any of its displayable replies unread?
m.unread? ||
find_all_by_parent_hash(m.hash).reduce(false) { |agg, r| agg || r.unread? }
end
end
def self.unread_topics_set
unread_topics.map(&:hash).to_set
end
def self.size
@@corpus.size
end
def self.mark_as_read(hashes)
new_reads = (@@my_read_hashes + hashes).uniq.sort
IrisFile.write_read_file(new_reads.to_json)
Corpus.load
end
end
class IrisFile
def self.load_messages(filepath = nil)
if filepath.nil?
filepath = Config.messagefile_filename
end
return [] unless File.exists?(filepath)
begin
payload = JSON.parse(File.read(filepath))
rescue JSON::ParserError => e
if filepath == Config.messagefile_filename
Display.flowerbox(
'Your message file appears to be corrupt.',
"Could not parse valid JSON from #{filepath}",
'Please fix or delete this message file to use Iris.')
exit(1)
else
Display.say " * Unable to parse #{filepath}, skipping..."
return []
end
rescue Errno::EACCES => e
Display.warn " * Unable to read data from #{filepath}, permission denied. Skipping..."
return []
end
unless payload.is_a?(Array)
if filepath == Config.messagefile_filename
Display.flowerbox(
'Your message file appears to be corrupt.',
"Could not interpret data from #{filepath}",
'(It\'s not a JSON array of messages, as far as I can tell)',
'Please fix or delete this message file to use Iris.')
exit(1)
else
Display.say " * Unable to interpret data from #{filepath}, skipping..."
return []
end
end
uid = File.stat(filepath).uid
begin
username = Etc.getpwuid(uid).name
rescue ArgumentError
Display.warn("'#{filepath}' does not appear to have a valid UID in /etc/passwd, skipping...")
return []
end
payload.map do |message_json|
new_message = Message.load(message_json)
new_message.validate_user(username)
new_message
end
end
def self.load_reads
return [] unless File.exists? Config.readfile_filename
begin
read_array = JSON.parse(File.read(Config.readfile_filename))
rescue JSON::ParserError => e
Display.flowerbox(
'Your read file appears to be corrupt.',
"Could not parse valid JSON from #{Config.readfile_filename}",
'Please fix or delete this read file to use Iris.')
exit(1)
end
unless read_array.is_a?(Array)
Display.flowerbox(
'Your read file appears to be corrupt.',
"Could not interpret data from #{Config.readfile_filename}",
'(It\'s not a JSON array of message hashes, as far as I can tell)',
'Please fix or delete this read file to use Iris.')
exit(1)
end
read_array
end
def self.create_message_file
raise 'Should not try to create message file in test mode!' if $test_corpus_file
raise 'Message file exists; refusing to overwrite!' if File.exists?(Config::MESSAGE_FILE)
File.umask(0122)
File.open(Config::MESSAGE_FILE, 'w') { |f| f.write('[]') }
end
def self.create_read_file
return if File.exists?(Config.readfile_filename)
File.umask(0122)
File.open(Config.readfile_filename, 'w') { |f| f.write('[]') }
end
def self.write_corpus(corpus)
File.write(Config.messagefile_filename, corpus)
end
def self.write_read_file(new_read_hashes)
if $test_corpus_file
File.write("#{$test_corpus_file}.read", new_read_hashes)
else
File.write(Config.readfile_filename, new_read_hashes)
end
end
end
class Message
attr_reader :timestamp, :edit_hash, :author, :parent, :message, :errors, :is_deleted
def initialize(message, parent = nil, author = Config.author, edit_hash = nil, timestamp = Time.now.utc.iso8601, is_deleted = nil)
@message = message
@parent = parent
@author = author
@edit_hash = edit_hash
@timestamp = timestamp
@hash = hash
@is_deleted = is_deleted
@errors = []
end
def self.load(payload)
data = payload if payload.is_a?(Hash)
data = JSON.parse(payload) if payload.is_a?(String)
loaded_message = self.new(data['data']['message'], data['data']['parent'], data['data']['author'], data['edit_hash'], data['data']['timestamp'], data['is_deleted'])
loaded_message.validate_hash(data['hash'])
loaded_message
end
def self.edit(new_text, old_message)
Message.new(new_text, old_message.parent, old_message.author, old_message.hash, old_message.timestamp).save!
end
def is_topic?
parent.nil? && show_me?
end
def delete
@is_deleted = !@is_deleted
replace!
end
def edited?
!(edit_hash.nil? || edit_hash.empty?)
end
# Only show messages that don't have a following, edited message
def show_me?
!Corpus.edited_hashes.include?(hash)
end
def validate_user(username)
@errors << 'Unvalidatable; could not parse username' if username.nil?
@errors << 'Unvalidatable; username is empty' if username.empty?
user_regex = Regexp.new("(.*)@.*$")
author_match = user_regex.match(author)
unless author_match && author_match[1] == username
@errors << "Bad username: got #{author}'s message from #{username}'s message file."
end
end
def validate_hash(test_hash)
if self.hash != test_hash
@errors << "Broken hash: expected '#{hash.chomp}', got '#{test_hash.chomp}'"
end
end
def valid?
@errors.empty?
end
def replace!
new_corpus = Corpus.mine.reject { |message| message.hash == self.hash } << self
IrisFile.write_corpus(JSON.pretty_generate(new_corpus))
Corpus.load
end
def save!
new_corpus = Corpus.mine << self
IrisFile.write_corpus(JSON.pretty_generate(new_corpus))
Corpus.load
end
def hash(payload = nil)
if payload.nil?
return @hash if @hash
payload = unconfirmed_payload.to_json
end
Base64.encode64(Digest::SHA1.digest(payload))
end
def truncated_display_message(length)
if is_deleted
stub = '{r TOPIC DELETED BY AUTHOR}'
else
stub = message.split("\n").first
end
return stub.colorize if stub.decolorize.length <= length
# Colorize the stub, then decolorize to strip out any partial tags
stub.colorize.slice(0, length - 5 - Display.topic_index_width).decolorize + '...'
end
def truncated_message(length)
stub = message.split("\n").first
return stub.colorize if stub.decolorize.length <= length
# Colorize the stub, then decolorize to strip out any partial tags
stub.colorize.slice(0, length - 5 - Display.topic_index_width).decolorize + '...'
end
def latest_topic_timestamp
(replies.map(&:timestamp).max || timestamp || 'UNKNOWN').gsub(/T/, ' ').gsub(/Z/, '')
end
def unread?
Corpus.unread_messages.include? self
end
def topic_status
return '{r X}' unless valid?
unread_count = replies.count(&:unread?)
unread_count += 1 if self.unread?
return ' ' if unread_count == 0
return '*' if unread_count > 9
unread_count.to_s
end
def to_topic_line(index)
head = [Display.print_index(index), topic_status, latest_topic_timestamp, Display.print_author(author)].join(' | ')
message_stub = truncated_display_message(Display::WIDTH - head.decolorize.length - 1)
'| ' + [head, message_stub].join(' | ')
end
def to_display
error_marker = valid? ? nil : '{r ### THIS MESSAGE HAS THE FOLLOWING ERRORS ###}'
error_follower = valid? ? nil : '{r ### THIS MESSAGE MAY BE CORRUPT OR MAY HAVE BEEN TAMPERED WITH ###}'
message_header = "#{leader_text} On #{timestamp}, #{author} #{verb_text}..."
header_bar = (indent_text + message_header + ('-' * (Display::WIDTH)))
header_offset = header_bar.length - header_bar.decolorize.length
header_bar = header_bar[0..Display::WIDTH + header_offset - 1]
bar = indent_text + ('-' * (Display::WIDTH - indent_text.decolorize.length))
if @is_deleted
message_text = nil
else
message_text = message.wrapped(Display::WIDTH - (indent_text.decolorize.length + 1)).split("\n").map{|m| indent_text + m }.join("\n")
end
[
'',
error_marker,
errors,
error_follower,
header_bar,
message_text,
bar
].flatten.compact.join("\n")
end
def to_topic_display
[to_display] + replies.map(&:to_display)
end
# TODO: Is this only used for hashing? Maybe rename.
def to_json(*args)
{
hash: hash,
edit_hash: edit_hash,
is_deleted: is_deleted,
data: unconfirmed_payload
}.to_json
end
def edit_predecessor
return nil unless edit_hash
Corpus.find_message_by_hash(edit_hash)
end
# Find all messages replying to the current topic, including replies to topics
# which have been edited.
def replies
all_replies = Corpus.find_all_by_parent_hash(hash)
all_replies += ((edit_predecessor && edit_predecessor.replies) || [])
all_replies.compact.sort_by{ |reply| Corpus.index_of(reply) }
end
def id
'M' + (Corpus.index_of(self) + 1).to_s
end
def topic_id
return nil unless self.is_topic?
Corpus.topic_index_of(self) + 1
end
private
def status_flag
return '{r (deleted)}' if @is_deleted
'{y (edited)}' if edited?
end
def leader_text
is_topic? ? "{g ***} [#{topic_id}] #{status_flag}" : ["{g ===}", "[#{id}]", status_flag].compact.join(' ')
end
def verb_text
is_topic? ? 'posted' : 'replied'
end
def indent_text
is_topic? ? '' : ' | '
end
def unconfirmed_payload
{
author: author,
parent: parent,
timestamp: timestamp,
message: message,
}
end
end
class Display
MIN_WIDTH = 80
MIN_HEIGHT = 8
WIDTH = [ENV['COLUMNS'].to_i, `tput cols`.chomp.to_i, MIN_WIDTH].compact.max
HEIGHT = [ENV['ROWS'].to_i, `tput lines`.chomp.to_i, MIN_HEIGHT].compact.max
TITLE_WIDTH = WIDTH - 26
def self.permissions_error(filename, file_description, permission_string, mode_string, consequence = nil)
message = [
"Your #{file_description} file has incorrect permissions! Should be \"#{permission_string}\".",
"You can change this from the command line with:",
" chmod #{mode_string} #{filename}",
consequence
].compact
self.flowerbox(message)
end
def self.flowerbox(*lines, box_character: '*', box_thickness: 1)
box_thickness.times do say box_character * WIDTH end
lines.each { |line| say line }
box_thickness.times do say box_character * WIDTH end
end
def self.say(stuff = '')
stuff = stuff.join("\n") if stuff.is_a? Array
puts stuff.colorize
end
def self.warn(stuff = '')
say("{y WARNING: }#{stuff}") if Config.debug?
end
def self.topic_index_width
[Corpus.topics.size.to_s.length, 2].max
end
def self.topic_author_width
Corpus.authors.map(&:length).max || 1
end
def self.print_index(index)
# Left-align
'{w ' + ((' ' * topic_index_width) + index.to_s)[(-topic_index_width)..-1] + '}'
end
def self.print_author(author)
# Right-align
(author.to_s + (' ' * topic_author_width))[0..(topic_author_width - 1)]
end
def self.topic_header
author_head = ('AUTHOR' + (' ' * WIDTH))[0..topic_author_width-1]
'| ' + ['ID', 'U', 'TIMESTAMP ', author_head, 'TITLE'].join(' | ')
end
end
class Interface
ONE_SHOTS = %w{ compose delete edit freshen help info mark_all_read mark_read next quit reset_display topics unread }
CMD_MAP = {
'?' => 'help',
'c' => 'compose',
'clear' => 'reset_display',
'compose' => 'compose',
'd' => 'delete',
'delete' => 'delete',
'e' => 'edit',
'edit' => 'edit',
'f' => 'freshen',
'freshen' => 'freshen',
'h' => 'help',
'help' => 'help',
'i' => 'info',
'info ' => 'info',
'm' => 'mark_read',
'mark' => 'mark_read',
'mark_all_read' => 'mark_all_read',
'n' => 'next',
'next' => 'next',
'q' => 'quit',
'quit' => 'quit',
'r' => 'reply',
'reply' => 'reply',
'reset' => 'reset_display',
't' => 'topics',
'topics' => 'topics',
'u' => 'unread',
'undelete' => 'delete',
'unread' => 'unread',
}
def reset_display
Display.say `tput reset`.chomp
end
def self.info
topic_count = Corpus.topics.size
unread_topic_count = Corpus.unread_topics.size
message_count = Corpus.size
unread_message_count = Corpus.unread_messages.size
author_count = Corpus.authors.size
Display.flowerbox(
"Iris #{Config::VERSION}",
"#{topic_count} #{'topic'.pluralize(topic_count)}, #{unread_topic_count} unread.",
"#{message_count} #{'message'.pluralize(message_count)}, #{unread_message_count} unread.",
"#{author_count} #{'author'.pluralize(author_count)}.",
box_thickness: 0)
end
def info
Display.say
Interface.info
Display.say
end
def self.mark_all_read
Corpus.mark_as_read(Corpus.unread_messages.map(&:hash))
end
def mark_all_read
Display.say "Marking all messages as read..."
Interface.mark_all_read
Display.say "Done!"
end
def compose
Display.say 'Writing a new topic.'
message_text = external_editor()
if message_text.length <= 1
Display.say '{riv Empty message, discarding...}'
else
Message.new(message_text).save!
Display.say 'Topic saved!'
end
end
def next
Display.say
if Corpus.unread_topics.size == 0
Display.say "{gvi You're all caught up! No new topics to read.}"
return
end
message = Corpus.unread_topics.first
Display.say message.to_topic_display
Display.say
Corpus.mark_as_read([message.hash] + message.replies.map(&:hash))
end
def reply(topic_id)
unless topic_id
Display.say "I can't reply to nothing! Include a topic ID to reply to."
return
end
if parent = (Corpus.find_topic_by_id(topic_id) || Corpus.find_topic_by_hash(topic_id))
reply_topic = parent.hash
else
Display.say "Could not reply; unable to find a topic with ID '#{topic_id}'"
return
end
title = Corpus.find_topic_by_hash(parent.hash).truncated_message(Display::TITLE_WIDTH)
Display.say
Display.say "Writing a reply to topic '#{title}'"
message_text = external_editor()
if message_text.length <= 1
Display.say '{riv Empty message, discarding...}'
else
Message.new(message_text, reply_topic).save!
Display.say 'Reply saved!'
end
end
def edit(message_id = nil)
unless message_id
Display.say "I can't edit nothing! Include a message ID to edit."
return
end
message =
Corpus.find_message_by_hash(message_id) ||
Corpus.find_message_by_id(message_id) ||
Corpus.find_topic_by_id(message_id)
unless message
Display.say "Could not edit; unable to find a message with ID '#{message_id}'"
return
end
unless Corpus.is_mine?(message)
Display.say "Message with ID '#{message_id}' belongs to someone else."
Display.say "You can only edit your own messages!"
return
end
title = message.truncated_message(Display::TITLE_WIDTH)
Display.say
Display.say "Editing message '#{title}'"
message_text = external_editor(message.message)
if message_text.length <= 1
Display.say 'Empty message, not updating...'
elsif message_text == message.message
Display.say 'No change made, not updating...'
else
Message.edit(message_text, message)
Display.say 'Message edited!'
end
end
def mark_read(message_id = nil)
unless message_id
Display.say "I'm not a nihilist; I can't do something with nothing! Include a message ID to mark as read."
return
end
message =
Corpus.find_message_by_hash(message_id) ||
Corpus.find_message_by_id(message_id) ||
Corpus.find_topic_by_id(message_id)
unless message
Display.say "Could not mark as read; unable to find a message with ID '#{message_id}'"
return
end
Corpus.mark_as_read([message.hash] + message.replies.map(&:hash))
end
def delete(message_id = nil)
unless message_id
Display.say "I'm not a nihilist; I can't do something with nothing! Include a message ID to delete or undelete."
return
end
message =
Corpus.find_message_by_hash(message_id) ||
Corpus.find_message_by_id(message_id) ||
Corpus.find_topic_by_id(message_id)
unless message
Display.say "Could not delete or undelete; unable to find a message with ID '#{message_id}'"
return
end
unless Corpus.is_mine?(message)
Display.say "Message with ID '#{message_id}' belongs to someone else."
Display.say "You can only delete or undelete your own messages!"
return
end
message.delete
title = message.truncated_message(Display::TITLE_WIDTH)
Display.say
if message.is_deleted
Display.say "{r Deleted message '#{title}' }"
else
Display.say "{y Undeleted message '#{title}' }"
end
end
def external_editor(preload_text = nil)
tf = Tempfile.new('iris')
if preload_text
tf.write(preload_text)
tf.flush
end
raise "No `$EDITOR` environment variable set!" unless Config::ENV_EDITOR
system("#{Config::ENV_EDITOR} #{tf.path}")
tf.rewind
message_text = tf.read
tf.unlink
message_text
end
def handle(line)
tokens = line.split(/\s/)
cmd = tokens.first
cmd = CMD_MAP[cmd] || cmd
return self.send(cmd.to_sym) if ONE_SHOTS.include?(cmd) && tokens.length == 1
return show_topic(cmd) if cmd =~ /^\d+$/
# If we've gotten this far, we must have args. Let's handle 'em.
arg = tokens.last
return reply(arg) if cmd == 'reply'
return edit(arg) if cmd == 'edit'
return delete(arg) if cmd == 'delete'
return mark_read(arg) if cmd == 'mark_read'
Display.say 'Unrecognized command. Type "help" for a list of available commands.'
end
def show_topic(num)
index = num.to_i - 1
# TODO: Paginate here
if index >= 0 && index < Corpus.topics.length
msg = Corpus.topics[index]
Display.say msg.to_topic_display
Display.say
Corpus.mark_as_read([msg.hash] + msg.replies.map(&:hash))
else
Display.say 'Could not find a topic with that ID'
end
end
def quit
exit(0)
end
def self.start(args)
self.new(args)
end
def prompt
"#{Config.author}~> "
end
def initialize(args)
@history_loaded = false
Display.say "Welcome to Iris v#{Config::VERSION}. Type 'help' for a list of commands; Ctrl-D or 'quit' to leave."
unread
while line = readline(prompt) do
handle(line)
end
end
def unread
Display.say
if Corpus.unread_topics.size == 0
Display.say "{gvi You're all caught up! No new topics to read.}"
return
end
Display.say Display.topic_header
# TODO: Paginate here
unread_hashes = Corpus.unread_topics_set
Corpus.topics.each_with_index do |topic, index|
if unread_hashes.include?(topic.hash)
Display.say topic.to_topic_line(index + 1)
end
end
Display.say
end
def topics
Display.say
Display.say Display.topic_header
# TODO: Paginate here
Corpus.topics.each_with_index do |topic, index|
Display.say topic.to_topic_line(index + 1)
end
Display.say
end
def help
Display.flowerbox(
"Iris v#{Config::VERSION} readline interface",
'',
'Commands',
'========',
'READING',
'topics, t - List all topics',
'unread, u - List all topics with unread messages',
'# (topic id) - Read specified topic',
'next, n - Read the next unread topic',
'mark_read #, m # - Mark the associated topic as read',
'mark_all_read - Mark all messages as read',
'help, h, ? - Display this text',
'',
'WRITING',
'compose, c - Add a new topic',
'reply #, r # - Reply to a specific topic',
'edit #, e # - Edit a topic or message',
'delete #, d #, undelete # - Delete {u or undelete} a topic or message',
'',
'SCREEN AND FILE UTILITIES',
'freshen, f - Reload to get any new messages',
'reset, clear - Fix screen in case of text corruption',
'info, i - Display Iris version and message stats',
'quit, q - Quit Iris',
'',
'Full documentation available here:',
'https://github.com/Calamitous/iris/blob/master/README.md',
box_character: '')
end
def freshen
Corpus.load
Display.say 'Reloaded!'
unread
end
def readline(prompt)
if !@history_loaded && File.exist?(Config::HISTORY_FILE)
@history_loaded = true
if File.readable?(Config::HISTORY_FILE)
File.readlines(Config::HISTORY_FILE).each { |l| Readline::HISTORY.push(l.chomp) }
end