summaryrefslogtreecommitdiff
path: root/helpers.rb
blob: ad0bd42aa3b6522ed77de5839719073359f70520 (plain)
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
require_relative '/home/ch/src/wgen/lib'
require 'English'
helpers do
  def save_inbox(item)
    return unless item['id']

    path = File.join(INBOX_DIR, item['id'].sub('https://', ''))
    FileUtils.mkdir_p File.dirname(path)
    File.open(path, 'w+') { |f| f.puts item.to_json }
  end

  def save_outbox(item)
    return unless item['id']

    path = item['id'].sub(SOCIAL_URL, SOCIAL_DIR)
    FileUtils.mkdir_p File.dirname(path)
    File.open(path, 'w+') { |f| f.puts item.to_json }
  end

  def create_activity(type, object, to)
    date = Time.now.utc.iso8601
    rel_path = File.join(type.downcase, "#{date}.json")
    activity = {
      '@context' => 'https://www.w3.org/ns/activitystreams',
      'id' => File.join(OUTBOX_URL, rel_path),
      'type' => type,
      'actor' => ACTOR,
      'published' => date,
      'to' => to,
      'object' => object
    }

    unless activity['object'].is_a? String
      object_rel_path = File.join('object', object['type'].downcase, "#{date}.json")
      object = activity['object']
      object['@context'] = 'https://www.w3.org/ns/activitystreams'
      object['id'] = File.join(OUTBOX_URL, object_rel_path)
      object['published'] = date
      save_outbox activity['object']
      if object['tag']
        object['tag'].each do |tag|
          next unless tag['type'] == 'Hashtag'

          tag_path = File.join(TAGS[:dir], tag['name'].sub('#', '')) + '.json'
          tag_collection = if File.exist? tag_path
                             JSON.load_file(tag_path)
                           else
                             {
                               '@context' => 'https://www.w3.org/ns/activitystreams',
                               'id' => tag['href'],
                               'type' => 'OrderedCollection',
                               'totalItems' => 0,
                               'orderedItems' => []
                             }
                           end
          tag_collection['orderedItems'] << object['id']
          tag_collection['totalItems'] = tag_collection['orderedItems'].size
          File.open(tag_path, 'w+') do |f|
            f.puts tag_collection.to_json
          end
        end
      end
    end
    save_outbox activity
    pid = fork do
      settings.running_server = nil # http://stackoverflow.com/a/38934866/1021515
      send_activity activity, File.join(OUTBOX_DIR, rel_path)
    end
    Process.detach pid
  end

  def send_activity(activity, activity_path)
    to = activity['to'].is_a?(String) ? [activity['to']] : activity['to']
    inboxes = []
    to.uniq.each do |url|
      next if [ACTOR, 'https://www.w3.org/ns/activitystreams#Public'].include? url

      if url == FOLLOWERS_URL
        JSON.load_file(FOLLOWERS)['orderedItems'].each do |follower|
          inboxes << actor_inbox(follower)
        end
        next
      end
      inboxes << actor_inbox(url)
    end

    sha256 = OpenSSL::Digest.new('SHA256')
    digest = "SHA-256=#{sha256.base64digest(File.read(activity_path))}"
    keypair = OpenSSL::PKey::RSA.new(File.read('private.pem'))

    inboxes.compact.uniq.each do |inbox|
      uri = URI(inbox)
      httpdate = Time.now.utc.httpdate
      string = "(request-target): post #{uri.request_uri}\nhost: #{uri.host}\ndate: #{httpdate}\ndigest: #{digest}\ncontent-type: #{CONTENT_TYPE}"
      signature = Base64.strict_encode64(keypair.sign(OpenSSL::Digest.new('SHA256'), string))
      signed_header = "keyId=\"#{ACTOR}#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"#{signature}\""

      curl( # Net::HTTP fails with OpenSSL error
        "-X POST -H 'Host: #{uri.host}' -H 'Date: #{httpdate}' -H 'Digest: #{digest}' -H 'Signature: #{signed_header}' --data-binary '@#{activity_path}'", inbox
      )
    end
  end

  def actor_inbox(url)
    actor = fetch url
    return unless actor

    if actor['endpoints'] and actor['endpoints']['sharedInbox']
      actor['endpoints']['sharedInbox']
    elsif actor['inbox']
      actor['inbox']
    end
  end

  def update_collection(path, objects, action = 'add')
    objects = [objects] unless objects.is_a? Array
    File.open(path, 'r+') do |f|
      f.flock(File::LOCK_EX)
      json = f.read
      collection = JSON.parse(json)
      objects.each do |object|
        id = object['id'] || object
        if action == 'delete'
          collection['orderedItems'].delete_if { |o| o['id'] == id or o == id }
        elsif action == 'add'
          ids = collection['orderedItems'].collect { |i| i['id'] }
          collection['orderedItems'] << object unless ids.include?(id) or collection['orderedItems'].include?(id)
        end
      end
      collection['orderedItems'].uniq!
      collection['totalItems'] = collection['orderedItems'].size
      f.rewind
      f.puts collection.to_json
      f.truncate(f.pos)
    end
  end

  def fetch(url, accept = 'application/activity+json')
    begin
      uri = URI(url)
    rescue StandardError => e
      p url, e
      return nil
    end
    httpdate = Time.now.utc.httpdate
    keypair = OpenSSL::PKey::RSA.new(File.read('private.pem'))
    string = "(request-target): get #{uri.request_uri}\nhost: #{uri.host}\ndate: #{httpdate}"
    signature = Base64.strict_encode64(keypair.sign(OpenSSL::Digest.new('SHA256'), string))
    signed_header = "keyId=\"#{ACTOR}#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date\",signature=\"#{signature}\""
    response = curl(
      "-H 'Accept: #{accept}' -H 'Host: #{uri.host}' -H 'Date: #{httpdate}' -H 'Signature: #{signed_header}' ", url
    )
    return unless response

    begin
      JSON.parse(response)
    rescue StandardError => e
      p url, e
      nil
    end
  end

  def curl(ext, url)
    response = `/run/current-system/sw/bin/curl -H 'Content-Type: #{CONTENT_TYPE}' -H 'Accept: #{CONTENT_TYPE}' --fail-with-body -sSL #{ext} #{url}`
    if $CHILD_STATUS.success?
      response
    else
      p 'Curl Error:', url, response
      nil
    end
  end

  def mention(actor)
    person = people.select { |p| p[1] == actor }
    if person.empty?
      a = fetch(actor)
      return nil unless a

      mention = "@#{a['preferredUsername']}@#{URI(actor).host}"
      cache mention, actor, a
      mention
    else
      person[0][0]
    end
  end

  def actor(mention)
    mention = mention.chomp
    actors = people.select { |p| p[0] == mention }
    if actors.empty?
      server = mention.split('@').last
      a = fetch("https://#{server}/.well-known/webfinger?resource=acct:#{mention.sub(/^@/, '')}",
                'application/jrd+json')
      return nil unless a

      actor = a['links'].select do |l|
        l['rel'] == 'self'
      end[0]['href']
      cache mention, actor, a
      actor
    else
      actors[0][1]
    end
  end

  def people
    File.read('public/people.tsv').split("\n").collect { |l| l.chomp.split("\t") }
  end

  def cache(mention, actor, a)
    sharedInbox = a['endpoints']['sharedInbox'] if a['endpoints'] && a['endpoints']['sharedInbox']
    File.open('public/people.tsv', 'a') { |f| f.puts "#{mention}\t#{actor}\t#{sharedInbox}" }
  end

  def media_type(url) # TODO: extend extensions
    extensions = {
      image: %w[jpeg jpg png tiff webp],
      audio: %w[flac wav mp3 ogg aiff],
      video: %w[mp4 webm]
    }
    ext = File.extname(url).sub('.', '').downcase
    type = extensions.find { |_k, v| v.include? ext }
    "#{type[0]}/#{ext}"
  end

  def outbox_html(activity)
    html = File.read(File.join(SNIPPETS, 'head.html'))
    html += nav 'social'
    html += "<h1><a href='https://social.pdp8.info/pdp8'>@pdp8@social.pdp8.info</a></h1><h2>"
    html += if activity == 'create'
              "posts&nbsp;|&nbsp;<a href='/social/announce.html'>boosts</a>"
            elsif activity == 'announce'
              "<a href='/social/create.html'>posts</a>&nbsp;|&nbsp;boosts"
            end
    html += '</h2>'
    Dir[File.join(SOCIAL_DIR, 'outbox', activity, '*.json')].collect do |f|
      JSON.load_file(f)
    end.select { |a| a['to'].include?('https://www.w3.org/ns/activitystreams#Public') }.sort_by { |a| a['published'] }.reverse.collect { |a| a['object'] }.each do |object|
      object = fetch(object) if object.is_a? String
      if object
        mention = mention object['attributedTo']
        html += '<section>'
        html += "<h3>#{object['published']}</h3>"
        if activity == 'announce'
          html += "<b><a href='#{object['attributedTo']}' target='_blank'>#{mention}</a></b>&nbsp;"
        end
        html += object['content']
        if object['attachment']
          object['attachment'].each do |att|
            case att['mediaType']
            when /audio/
              html += "<p><audio controls><source src='#{att['url']}' type='#{att['mediaType']}'></audio>"
            when /image/
              html += "<p><a href='#{att['url']}'><img loading='lazy' "
              alt = att['name'] ? att['name'].gsub("'", '&apos;').gsub('"', '&quot;') : ''
              html += "alt='#{alt}' src='#{att['url']}'></a>"
            when /video/
              html += "<p><video controls><source src='#{att['url']}' type='#{att['mediaType']}'></video>"
            end
          end
        end
      end
      html += '</section>'
    end
    html += File.read(File.join(SNIPPETS, 'tail.html'))
    %w[pdp8 pdp8-test].each do |d|
      outdir = "/srv/www/#{d}/social"
      out = File.join(outdir, activity + '.html')
      File.open(out, 'w+') { |f| f.puts(html) }
      puts `/etc/profiles/per-user/ch/bin/tidy -iqm -w 0 #{out} 2>&1`
    end
  end
end