Class: Murlsh::PopServer

Inherits:
Server
  • Object
show all
Defined in:
lib/murlsh/pop_server.rb

Overview

Pop mail from a pop3 server and add all urls in messages from murlsh users.

Instance Attribute Summary

Attributes inherited from Server

#config

Instance Method Summary collapse

Methods inherited from Server

#initialize

Constructor Details

This class inherits a constructor from Murlsh::Server

Instance Method Details

#parse_mail(mail) ⇒ Object

Parse date, from address and urls found in body from an email message.



62
63
64
65
66
67
68
69
70
# File 'lib/murlsh/pop_server.rb', line 62

def parse_mail(mail)
  parsed_mail = RMail::Parser.read(mail.gsub(/\r/, ''))

  {
    :date => parsed_mail.header.date.utc,
    :from => parsed_mail.header.from.first.address.downcase,
    :uris => PostRank::URI.extract(parsed_mail.body),
  }    
end

#post(req) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/murlsh/pop_server.rb', line 13

def post(req)
  response_body = []

  if req['secret'] == config['pop_secret']
    Net::POP3.enable_ssl
    Net::POP3.start(config.fetch('pop_server'), config.fetch('pop_port'),
      config.fetch('pop_user'), config.fetch('pop_password')) do |pop|
      pop.each_mail do |mail|
        begin
          response_body << process_mail(mail.pop)
        rescue Exception
        ensure
          mail.delete
        end
      end
      pop.finish
    end
  end

  Rack::Response.new response_body.to_json, 200,
    'Content-Type' => 'application/json'
end

#process_mail(mail) ⇒ Object

Authenticate the sender and add all urls extracted from the the email body.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/murlsh/pop_server.rb', line 38

def process_mail(mail)
  parsed_mail = parse_mail(mail)

  if user = Murlsh::Auth.new(config.fetch('auth_file')).by_email(
    parsed_mail[:from])
    parsed_mail[:uris].each do |uri|
      mu = Murlsh::Url.new do |u|
        u.url = uri
        u.email = user[:email]
        u.name = user[:name]
        u.time = parsed_mail[:date]
      end

      # validate before add_pre plugins have run and also after (in save!)
      raise ActiveRecord::RecordInvalid.new(mu)  unless mu.valid?
      Murlsh::Plugin.hooks('add_pre') { |p| p.run mu, config }
      mu.save!
      Murlsh::Plugin.hooks('add_post') { |p| p.run mu, config }
    end
  end
  parsed_mail
end