focus.rb/lib/focus/host.rb

66 lines
1.8 KiB
Ruby

module Focus
class Host
def initialize(file = "/etc/hosts")
@file = file
read!
end
def get_index
start_index = @all_lines.find_index { |line| /### FOCUS:start \(automaticaly generated\) ###/i === line }
stop_index = @all_lines.find_index { |line| /### FOCUS:stop \(automaticaly generated\) ###/i === line }
{ start: start_index + 1, stop: stop_index - 1 } if start_index && stop_index
end
def read!
@all_lines = File.read(@file).split("\n")
index = get_index
@data = []
if index
selected_lines = @all_lines[index[:start]..index[:stop]]
@data = selected_lines.map { |line| line.split(/\s+/) }.map { |ip, host| { ip: ip, host: host } }
end
end
def overwrite!
index = get_index
if index
count = index[:stop] - index[:start]
@all_lines << "" if @all_lines[index[:start] - 2] != ""
@all_lines.slice!(index[:start] - 1, count + 3)
else
@all_lines << "" if @all_lines.last != ""
end
@all_lines << "### FOCUS:start (automaticaly generated) ###"
@data.each do |managed|
@all_lines << "#{managed[:ip]} #{managed[:host]}"
end
@all_lines << "### FOCUS:stop (automaticaly generated) ###"
@all_lines << ""
command = "sudo su -c 'echo \"#{@all_lines.join("\n")}\" > #{@file}'"
`#{command}`
end
def block!(config)
puts "Blocking the hosts".green
read!
config.block_hosts.each do |block_host|
puts block_host.red
@data << { host: block_host, ip: "127.0.0.1" }
@data << { host: "www.#{block_host}", ip: "127.0.0.1" }
end
@data.uniq!
overwrite!
puts "Done!".green
end
def restore!(config)
puts "Restoring blocked hosts".green
@data = []
overwrite!
puts "Done!".green
end
end
end