config.ru 2.65 KB
# -*- mode:ruby -*-

require 'sinatra'
require 'rack-flash'
require 'haml'

require './models'
require './maildrop_serializer'
require 'net/imap'

MAILSERVER = 'mail.sourceagency.net'

class App < Sinatra::Base
  enable :sessions
  use Rack::Flash
  
  set :public, 'public'
  
  before do 
    unless env['PATH_INFO'] =~ /^\/login/ || session[:user]
      redirect '/login'
    end
  end
  
  get '/' do 
    redirect '/filters'
  end
  
  get '/filters' do 
    @filters = filters
    haml :filters
  end
  
  get '/filter/:id' do 
    if params[:id] == 'new'
      @filter = Filter.new
    else
      @filter = filters.find(params[:id])
    end
    haml :filter
  end
    
  post '/filters' do 
    @filter = Filter.new(params[:filter])
    @filter.email = session[:user]
    @filter.save!
    flash[:success] = "Filter created"
    redirect("/filters")
  end
  
  post '/filter/:id' do 
    @filter = filters.find(params[:id])
    @filter.update_attributes(params[:filter])
    flash[:success] = "Filter updated"
    @filter.email = session[:user]
    @filter.save!
    redirect("/filters")
  end
  
  post '/filter/:id/delete' do 
    @filter = filters.find(params[:id])
    @filter.destroy
    flash[:notice] = "Filter deleted"
    redirect('/filters')
  end
  
  get '/expression/new' do 
    @expression = Expression.new
    partial(:expression, :expression => @expression)
  end
  
  get '/login' do 
    haml :login
  end
  
  get '/logout' do 
    session[:user] = session[:pass] = nil
    session[:notice] = "You're logged out now."
    redirect '/'
  end
  
  post '/login' do 
    begin
      imap(false).login(params[:email], params[:password])
      session[:user] = params[:email]
      session[:pass] = params[:password]
      flash[:success] = "Authentication successful"
      redirect '/'
    rescue => exc
      flash.now[:error] = "Authentication failed"
      haml :login
    end
  end
  
  helpers do 
    def partial(template, locals={}, options={})
      haml(template, options.merge(:locals => locals, :layout => false))
    end
    
    def option(value, label, selected)
      "<option value=\"#{value}\"#{selected && ' selected'}>#{label}</option>"
    end
    
    def filters
      Filter.where(:email => session[:user])
    end
    
    def folders(parent=nil)
      return @folders if @folders
      folders = (imap.list("", parent ? "#{parent}.%" : '%') || []).map { |f|
        [f.name] + folders(f.name)
      }.flatten
      unless parent
        @folders = folders
      end
      return folders
    end
    
    def imap(login=true)
      @imap ||= Net::IMAP.new(MAILSERVER).tap { |i|
        i.login(session[:user], session[:pass]) if login
      }
    end
  end
end

run App