iris/iris.rb

699 lines
18 KiB
Ruby
Raw Normal View History

#!/usr/bin/env ruby
2018-01-31 05:30:58 +00:00
# MVP: Complete!
# Reading/Status: Complete!
2018-01-31 01:18:34 +00:00
#
# Documentation
# TODO: Add command-line options to README
# TODO: Flesh out technical sections
#
2018-01-31 01:18:34 +00:00
# Tech debt:
2018-02-01 07:27:30 +00:00
# TODO: Reeeeefactor...
# TODO: Flesh out tests
2018-01-31 01:18:34 +00:00
# TODO: Split helptext into separate file?
# TODO: Move all puts into Display class
# TODO: Make all output WIDTH-aware
# TODO: Create struct to firm up message payload
# TODO: Common message file location for the security-conscious?
# TODO: Parse and manage options before instantiating Interface from .start
# TODO: Validate read and history perms on startup
2018-01-31 03:27:07 +00:00
# TODO: Let Message initialization accept params as a hash
# TODO: Add checking for message file format version
2018-01-31 01:18:34 +00:00
#
# Fancify interface:
# TODO: Gracefully handle attempt to "r 1 message"
# TODO: Highlight names for readability
# TODO: Use ENV for rows and cols of display? (No)
2018-01-31 01:18:34 +00:00
# TODO: Pagination?
# TODO: Make nicer topic display
# TODO: Add optional title for topics
2018-01-31 05:30:58 +00:00
# TODO: Add version, filenames, etc. to helptext
# TODO: Add line marker for topics to show if they have replies
2018-02-01 07:27:30 +00:00
# TODO: Add message when no topics are found
# TODO: Add message troubleshooting option, for deep data dive
2018-01-31 01:18:34 +00:00
#
# Features:
2018-01-31 03:27:07 +00:00
# TODO: Add read-only mode if user doesn't want/can't have message file
2018-01-31 01:18:34 +00:00
# TODO: Add user muting
# TODO: Add .mute.iris support?
# TODO: Message deletion
# TODO: Add startup enviro health check
# TODO: Add message editing
# TODO: Add full message corpus dump for backup/debugging
#
# Later/Maybe:
# * ncurses client
# * customizable prompt
# * MOTD
# * Add to default startup script to display read count
require 'time'
require 'base64'
require 'digest'
require 'json'
require 'etc'
2018-01-28 01:16:09 +00:00
require 'readline'
class String
def wrapped(width = Display::WIDTH)
self.gsub(/.{1,#{width}}(?:\s|\Z|\-)/){($& + 5.chr).gsub(/\n\005/,"\n").gsub(/\005/,"\n")}
end
2018-02-07 03:22:08 +00:00
def pluralize(count)
return self if count == 1
self + 's'
end
end
class Config
2018-02-07 15:29:35 +00:00
VERSION = '1.0.2'
2018-01-24 05:13:46 +00:00
MESSAGE_FILE = "#{ENV['HOME']}/.iris.messages"
2018-01-28 01:16:09 +00:00
HISTORY_FILE = "#{ENV['HOME']}/.iris.history"
READ_FILE = "#{ENV['HOME']}/.iris.read"
USER = ENV['USER'] || ENV['LOGNAME'] || ENV['USERNAME']
HOSTNAME = `hostname -d`.chomp
AUTHOR = "#{USER}@#{HOSTNAME}"
2018-01-26 05:59:23 +00:00
def self.find_files
(`ls /home/**/.iris.messages`).split("\n")
end
end
class Corpus
def self.load
@@corpus = Config.find_files.map { |filepath| IrisFile.load_messages(filepath) }.flatten.sort_by(&:timestamp)
@@topics = @@corpus.select{ |m| m.parent == nil }
@@my_corpus = IrisFile.load_messages.sort_by(&:timestamp)
@@my_reads = IrisFile.load_reads
@@all_hash_to_index = @@corpus.reduce({}) { |agg, msg| agg[msg.hash] = @@corpus.index(msg); agg }
@@all_parent_hash_to_index = @@corpus.reduce({}) do |agg, msg|
agg[msg.parent] ||= []
agg[msg.parent] << @@corpus.index(msg)
agg
end
end
def self.all
@@corpus
end
def self.topics
@@topics
end
def self.mine
@@my_corpus
end
def self.find_message_by_hash(hash)
return nil unless hash
index = @@all_hash_to_index[hash]
return nil unless index
all[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| all[idx] }
end
def self.find_topic(topic_lookup)
return nil unless topic_lookup
if topic_id.to_i == 0
# This must be a hash, handle appropriately
msg = find_message_by_hash(topic_id)
msg
else
# This must be an index, handle appropriately
index = topic_id.to_i - 1
return topics[index] if index >= 0 && index < topics.length
end
end
def self.read_hashes
@@my_reads
end
2018-02-07 03:22:08 +00:00
def self.unread_messages
@@corpus.reject{ |m| @@my_reads.include? m.hash }
end
def self.unread_topics
@@topics.reject{ |m| @@my_reads.include? m.hash }
end
def self.size
@@corpus.size
end
end
class IrisFile
def self.load_messages(filepath = Config::MESSAGE_FILE)
2018-01-28 01:15:13 +00:00
# For logger: puts "Checking #{filepath}"
return [] unless File.exists?(filepath)
2018-01-28 01:15:13 +00:00
# For logger: puts "Found, parsing #{filepath}..."
begin
payload = JSON.parse(File.read(filepath))
rescue JSON::ParserError => e
if filepath == Config::MESSAGE_FILE
puts '*' * 80
puts 'Your message file appears to be corrupt.'
puts "Could not parse valid JSON from #{filepath}"
puts 'Please fix or delete this message file to use Iris.'
puts '*' * 80
exit(1)
else
puts " * Unable to parse #{filepath}, skipping..."
return []
end
end
unless payload.is_a?(Array)
if filepath == Config::MESSAGE_FILE
puts '*' * 80
puts 'Your message file appears to be corrupt.'
puts "Could not interpret data from #{filepath}"
puts '(It\'s not a JSON array of messages, as far as I can tell)'
puts 'Please fix or delete this message file to use Iris.'
puts '*' * 80
2018-02-01 07:27:30 +00:00
exit(1)
else
puts " * Unable to interpret data from #{filepath}, skipping..."
return []
end
end
uid = File.stat(filepath).uid
username = Etc.getpwuid(uid).name
payload.map do |message_json|
new_message = Message.load(message_json)
new_message.validate_user(username)
new_message
end
end
2018-01-26 05:59:23 +00:00
def self.load_reads
return [] unless File.exists? Config::READ_FILE
begin
read_array = JSON.parse(File.read(Config::READ_FILE))
rescue JSON::ParserError => e
puts '*' * 80
puts 'Your read file appears to be corrupt.'
puts "Could not parse valid JSON from #{Config::READ_FILE}"
puts 'Please fix or delete this read file to use Iris.'
puts '*' * 80
exit(1)
end
unless read_array.is_a?(Array)
puts '*' * 80
puts 'Your read file appears to be corrupt.'
puts "Could not interpret data from #{Config::READ_FILE}"
puts '(It\'s not a JSON array of message hashes, as far as I can tell)'
puts 'Please fix or delete this read file to use Iris.'
puts '*' * 80
exit(1)
end
read_array
end
def self.create_message_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
raise 'Read file exists; refusing to overwrite!' if File.exists?(Config::READ_FILE)
File.umask(0122)
File.open(Config::READ_FILE, 'w') { |f| f.write('[]') }
end
2018-01-26 05:59:23 +00:00
def self.write_corpus(corpus)
File.write(Config::MESSAGE_FILE, corpus)
end
def self.write_read_file(new_read_hashes)
File.write(Config::READ_FILE, new_read_hashes)
end
2018-01-26 05:59:23 +00:00
end
class Message
2018-01-24 05:13:59 +00:00
FILE_FORMAT = 'v2'
2018-01-31 01:25:56 +00:00
attr_reader :timestamp, :edit_hash, :author, :parent, :message, :errors
2018-01-31 01:25:56 +00:00
def initialize(message, parent = nil, author = Config::AUTHOR, timestamp = Time.now.utc.iso8601, edit_hash = nil)
@parent = parent
@author = author
@timestamp = timestamp
@message = message
2018-01-31 01:25:56 +00:00
@hash = hash
@errors = []
end
def self.load(payload)
data = payload if payload.is_a?(Hash)
data = JSON.parse(payload) if payload.is_a?(String)
2018-01-31 01:25:56 +00:00
loaded_message = self.new(data['data']['message'], data['data']['parent'], data['data']['author'], data['data']['timestamp'], data['edit_hash'])
loaded_message.validate_hash(data['hash'])
loaded_message
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("(.*)@#{Config::HOSTNAME}$")
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)
2018-01-31 01:25:56 +00:00
if self.hash != test_hash
@errors << "Broken hash: expected '#{hash.chomp}', got '#{test_hash.chomp}'"
end
end
def valid?
@errors.empty?
end
def topic?
parent.nil?
end
2018-01-26 05:59:23 +00:00
def save!
new_corpus = Corpus.mine << self
IrisFile.write_corpus(new_corpus.to_json)
Corpus.load
end
2018-01-24 05:13:59 +00:00
def hash(payload = nil)
2018-01-31 01:25:56 +00:00
if payload.nil?
return @hash if @hash
payload = unconfirmed_payload.to_json
end
2018-01-24 05:13:59 +00:00
Base64.encode64(Digest::SHA1.digest(payload))
end
2018-01-28 01:16:09 +00:00
def truncated_message(length)
stub = message.split("\n").first
return stub if stub.length <= length
2018-01-31 05:25:25 +00:00
stub.slice(0, length - 6) + '...'
2018-01-28 01:16:09 +00:00
end
def to_topic_line(index)
error_marker = valid? ? ' ' : 'X'
2018-01-31 05:25:25 +00:00
head = [error_marker, Display.print_index(index), timestamp, Display.print_author(author)].join(' | ')
2018-01-28 01:16:09 +00:00
message_stub = truncated_message(Display::WIDTH - head.length)
[head, message_stub].join(' | ')
end
2018-01-31 01:25:56 +00:00
def to_display
2018-01-31 05:25:25 +00:00
error_marker = valid? ? nil : '### THIS MESSAGE HAS THE FOLLOWING ERRORS ###'
error_follower = valid? ? nil : '### THIS MESSAGE MAY BE CORRUPT OR TAMPERED WITH ###'
bar = indent_text + ('-' * (Display::WIDTH - indent_text.length))
message_text = message.wrapped(Display::WIDTH - (indent_text.length + 1)).split("\n").map{|m| indent_text + m }.join("\n")
2018-01-28 01:16:09 +00:00
[
'',
2018-01-31 01:25:56 +00:00
"#{leader_text} On #{timestamp}, #{author} #{verb_text}...",
error_marker,
errors,
error_follower,
bar,
message_text,
bar
].flatten.compact.join("\n")
2018-01-28 01:16:09 +00:00
end
2018-01-31 01:25:56 +00:00
def to_topic_display
[to_display] + replies.map(&:to_display)
end
2018-01-26 05:59:23 +00:00
def to_json(*args)
2018-01-24 05:13:59 +00:00
{
hash: hash,
edit_hash: edit_hash,
data: unconfirmed_payload
}.to_json
end
def replies
Corpus.find_all_by_parent_hash(hash)
end
private
def leader_text
topic? ? '***' : ' === REPLY==='
end
def verb_text
topic? ? 'posted' : 'replied'
end
def indent_text
topic? ? '' : ' | '
end
def unconfirmed_payload
2018-01-24 05:13:59 +00:00
{
author: author,
parent: parent,
timestamp: timestamp,
message: message,
}
end
end
2018-01-28 01:16:09 +00:00
class Display
MIN_WIDTH = 80
WIDTH = [ENV['COLUMNS'].to_i, `tput cols`.chomp.to_i, MIN_WIDTH].compact.max
2018-01-28 01:16:09 +00:00
def self.topic_index_width
Corpus.topics.size.to_s.length
end
2018-01-31 05:25:25 +00:00
def self.topic_author_width
Corpus.topics.map(&:author).map(&:length).max || 1
2018-01-31 05:25:25 +00:00
end
2018-01-28 01:16:09 +00:00
def self.print_index(index)
2018-01-31 05:25:25 +00:00
# Left-align
2018-01-28 01:16:09 +00:00
((' ' * topic_index_width) + index.to_s)[(-topic_index_width)..-1]
end
2018-01-31 05:25:25 +00:00
def self.print_author(author)
# Right-align
(author.to_s + (' ' * topic_author_width))[0..(topic_author_width - 1)]
end
2018-01-28 01:16:09 +00:00
end
class Interface
2018-01-31 05:27:02 +00:00
ONE_SHOTS = %w{help topics compose quit freshen reset_display reply}
2018-01-28 01:16:09 +00:00
CMD_MAP = {
't' => 'topics',
'topics' => 'topics',
'c' => 'compose',
'compose' => 'compose',
2018-01-28 01:16:09 +00:00
'h' => 'help',
'?' => 'help',
'help' => 'help',
'r' => 'reply',
'reply' => 'reply',
'q' => 'quit',
'quit' => 'quit',
'freshen' => 'freshen',
'f' => 'freshen',
2018-01-31 05:27:02 +00:00
'reset' => 'reset_display',
'clear' => 'reset_display',
2018-01-28 01:16:09 +00:00
}
def browsing_handler(line)
2018-01-31 01:25:56 +00:00
tokens = line.split(/\s/)
cmd = tokens.first
2018-01-28 01:16:09 +00:00
cmd = CMD_MAP[cmd] || cmd
2018-01-31 01:25:56 +00:00
return self.send(cmd.to_sym) if ONE_SHOTS.include?(cmd) && tokens.length == 1
2018-01-28 01:16:09 +00:00
return show_topic(cmd) if cmd =~ /^\d+$/
2018-01-31 01:25:56 +00:00
# We must have args, let's handle 'em
arg = tokens.last
return reply(arg) if cmd == 'reply'
puts 'Unrecognized command. Type "help" for a list of available commands.'
2018-01-31 03:27:23 +00:00
nil
2018-01-31 01:25:56 +00:00
end
2018-01-31 05:27:02 +00:00
def reset_display
puts `tput reset`.chomp
end
2018-01-31 01:25:56 +00:00
def reply(topic_id = nil)
topic_id ||= @reply_topic
unless topic_id
puts "I can't reply to nothing! Include a topic ID or view a topic to reply to."
return
end
if parent = Corpus.find_topic(topic_id)
@reply_topic = parent.hash
else
puts "Could not reply; unable to find a topic with ID '#{topic_id}'"
return
end
@mode = :replying
@text_buffer = ''
title = Corpus.find_topic(parent.hash).truncated_message(80)
puts "Writing a reply to topic '#{title}'. Type a period on a line by itself to end message."
end
def replying_handler(line)
if line !~ /^\.$/
if @text_buffer.empty?
@text_buffer = line
else
@text_buffer = [@text_buffer, line].join("\n")
end
return
end
if @text_buffer.length <= 1
puts 'Empty message, discarding...'
else
Message.new(@text_buffer, @reply_topic).save!
puts 'Reply saved!'
end
@reply_topic = nil
@mode = :browsing
2018-01-31 03:27:23 +00:00
nil
2018-01-28 01:16:09 +00:00
end
def composing_handler(line)
2018-01-28 01:16:09 +00:00
if line !~ /^\.$/
if @text_buffer.empty?
@text_buffer = line
else
@text_buffer = [@text_buffer, line].join("\n")
end
return
end
if @text_buffer.length <= 1
puts 'Empty message, discarding...'
else
Message.new(@text_buffer).save!
puts 'Topic saved!'
end
@mode = :browsing
2018-01-31 03:27:23 +00:00
nil
2018-01-28 01:16:09 +00:00
end
def handle(line)
return browsing_handler(line) if @mode == :browsing
return composing_handler(line) if @mode == :composing
return replying_handler(line) if @mode == :replying
2018-01-28 01:16:09 +00:00
end
def show_topic(num)
index = num.to_i - 1
if index >= 0 && index < Corpus.topics.length
2018-01-31 01:25:56 +00:00
msg = Corpus.topics[index]
@reply_topic = msg.hash
puts msg.to_topic_display
new_reads = (Corpus.read_hashes + [msg.hash] + msg.replies.map(&:hash)).uniq.sort
IrisFile.write_read_file(new_reads.to_json)
Corpus.load
2018-01-28 01:16:09 +00:00
else
puts 'Could not find a topic with that ID'
end
nil
2018-01-28 01:16:09 +00:00
end
def quit
exit(0)
end
2018-01-31 01:20:06 +00:00
def self.start(args)
self.new(args)
2018-01-28 01:16:09 +00:00
end
def prompt
return 'new~> ' if @mode == :composing
2018-01-28 01:16:09 +00:00
return 'reply~> ' if @mode == :replying
"#{Config::AUTHOR}~> "
end
2018-01-31 01:20:06 +00:00
def initialize(args)
2018-01-28 01:16:09 +00:00
Corpus.load
@history_loaded = false
@mode = :browsing
puts "Welcome to Iris v#{Config::VERSION}. Type 'help' for a list of commands; Ctrl-D or 'quit' to leave."
while line = readline(prompt) do
puts handle(line)
end
end
def compose
@mode = :composing
2018-01-28 01:16:09 +00:00
@text_buffer = ''
2018-01-31 01:25:56 +00:00
puts 'Writing a new topic. Type a period on a line by itself to end message.'
2018-01-28 01:16:09 +00:00
end
def topics
Corpus.topics.each_with_index { |topic, index| puts topic.to_topic_line(index + 1) }
nil
end
def help
puts
2018-02-01 07:27:51 +00:00
puts "Iris v#{Config::VERSION} readline interface"
2018-01-28 01:16:09 +00:00
puts
puts 'Commands'
puts '========'
puts 'help, h, ? - Display this text'
puts 'topics, t - List all topics'
puts '# (topic id) - Read specified topic'
puts 'compose, c - Add a new topic'
2018-01-28 01:16:09 +00:00
puts 'reply #, r # - Reply to a specific topic'
puts 'freshen, f - Reload to get any new messages'
2018-01-31 05:27:02 +00:00
puts 'reset, clear - Fix screen in case of text corruption'
2018-01-28 01:16:09 +00:00
puts
end
def freshen
Corpus.load
puts 'Reloaded!'
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
end
if line = Readline.readline(prompt, true)
if File.writable?(Config::HISTORY_FILE)
File.open(Config::HISTORY_FILE) {|f| f.write(line+"\n")}
end
return line
else
return nil
end
end
2018-01-31 01:20:06 +00:00
end
class CLI
2018-02-01 07:27:51 +00:00
def self.puts_help
puts
puts "Iris v#{Config::VERSION} command-line"
puts
puts 'Usage'
puts '========'
puts "#{__FILE__} [options]"
puts
puts 'Options'
puts '========'
puts '--help, -h - Display this text.'
puts '--version, -v - Display the current version of Iris.'
puts '--stats, -s - Display data about the system.'
puts '--interactive, -i - Enter interactive mode (default)'
puts
puts 'If no options are provided, Iris will enter interactive mode.'
end
2018-01-31 01:20:06 +00:00
def self.start(args)
2018-02-01 07:27:51 +00:00
if (args & %w{-v --version}).any?
puts "Iris #{Config::VERSION}"
exit(0)
end
if (args & %w{-h --help}).any?
puts_help
exit(0)
end
if (args & %w{-s --stats}).any?
Corpus.load
puts "Iris #{Config::VERSION}"
2018-02-07 03:22:08 +00:00
puts "#{Corpus.topics.size} #{'topic'.pluralize(Corpus.topics.size)}, #{Corpus.unread_topics.size} unread."
puts "#{Corpus.size} #{'message'.pluralize(Corpus.size)}, #{Corpus.unread_messages.size} unread."
2018-02-01 07:27:51 +00:00
puts "#{Corpus.all.map(&:author).uniq.size} authors."
exit(0)
end
puts "Unrecognized option(s) #{args.join(', ')}"
puts "Try -h for help"
2018-01-31 01:20:06 +00:00
end
end
2018-01-28 01:16:09 +00:00
2018-01-31 01:20:06 +00:00
class Startupper
def initialize(args)
perform_startup_checks
if (args & %w{-i --interactive}).any? || args.empty?
Interface.start(args)
else
CLI.start(args)
end
end
def perform_startup_checks
unless File.exists?(Config::MESSAGE_FILE)
puts "You don't have a message file at #{Config::MESSAGE_FILE}."
response = Readline.readline 'Would you like me to create it for you? (y/n) ', true
if /[Yy]/ =~ response
IrisFile.create_message_file
else
puts 'Cannot run Iris without a message file!'
exit(1)
end
end
IrisFile.create_read_file unless File.exists?(Config::READ_FILE)
2018-01-31 01:20:06 +00:00
if File.stat(Config::MESSAGE_FILE).mode != 33188
puts '*' * 80
puts 'Your message file has incorrect permissions! Should be "-rw-r--r--".'
puts 'You can change this from the command line with:'
puts " chmod 644 #{Config::MESSAGE_FILE}"
puts 'Leaving your file with incorrect permissions could allow unauthorized edits!'
puts '*' * 80
end
if File.stat(Config::READ_FILE).mode != 33188
puts '*' * 80
puts 'Your read file has incorrect permissions! Should be "-rw-r--r--".'
puts 'You can change this from the command line with:'
puts " chmod 644 #{Config::READ_FILE}"
puts '*' * 80
end
2018-01-31 01:20:06 +00:00
if File.stat(__FILE__).mode != 33261
puts '*' * 80
puts 'The Iris file has incorrect permissions! Should be "-rwxr-xr-x".'
puts 'You can change this from the command line with:'
puts " chmod 755 #{__FILE__}"
puts 'If this file has the wrong permissions the program may be tampered with!'
puts '*' * 80
end
end
2018-01-28 01:16:09 +00:00
end
2018-01-26 05:59:23 +00:00
Startupper.new(ARGV) if __FILE__==$0