hypothesis-annotations (2240B)
1 #!/usr/bin/env ruby 2 require 'open-uri' 3 require 'json' 4 class Hypothesis 5 class Annotation 6 attr_reader :title, :uri 7 def initialize(text,comment,title,uri) 8 @text = text 9 @comment = comment 10 @title = title 11 @uri = uri 12 end 13 14 def to_markdown 15 str = @text.split("\n").reduce("") { |acc, line| acc += "> #{line}\n" } 16 str += "\n" 17 str += "#{@comment}\n" if @comment 18 str 19 end 20 21 def to_markdown_title_url 22 "[#{@title}](#{@uri})\n" 23 end 24 end 25 def initialize 26 ['HYPOTHESIS_API_KEY', 'HYPOTHESIS_USERNAME'].each do |var| 27 if ENV[var].nil? 28 warn "Please set the #{var} environment variable." 29 exit 1 30 end 31 end 32 33 @apikey = ENV['HYPOTHESIS_API_KEY'] 34 @username = ENV['HYPOTHESIS_USERNAME'] 35 @headers = {'Host' => 'hypothes.is', 'Accept' => 'application/json', 'Authorization' => "Bearer #{@apikey}"} 36 @baseurl = "https://hypothes.is/api" 37 38 begin 39 URI.open("#{@baseurl}/", @headers) 40 rescue 41 warn "Could not access the API #{@baseurl}" 42 exit 1 43 end 44 end 45 46 def request(endpoint) 47 begin 48 URI.open(@baseurl+endpoint, @headers) do |response| 49 JSON.parse(response.read)['rows'] 50 end 51 rescue 52 warn "Error getting data from #{endpoint}" 53 [] 54 end 55 end 56 57 def annotations(uri_search_str) 58 data = request "/search?user=acct:#{@username}@hypothes.is&#{uri_search_str}&limit=200&order=asc" 59 data.reduce([]) do |arr, annot| 60 arr << Annotation.new(annot['target'].first['selector'].select {|f| f['type'] == 'TextQuoteSelector'}.first['exact'], 61 annot['text'].empty? ? nil : annot['text'], 62 annot['document']['title'].first, 63 annot['uri']) 64 end 65 66 end 67 68 def search_host(host) 69 annotations "wildcard_uri=http://#{host}/*" 70 end 71 72 def search_uri(uri) 73 annotations "uri=#{uri}" 74 end 75 end 76 77 if ARGV.empty? 78 puts "Argument required: URL or host" 79 exit 1 80 end 81 82 h = Hypothesis.new 83 site = ARGV.first 84 annotations = (site.start_with? "http") ? h.search_uri(site) : h.search_host(site) 85 puts annotations.first.to_markdown_title_url+"\n"+annotations.reduce("") { |str, annot| str += annot.to_markdown }