mailr/app/models/message.rb

100 lines
2.9 KiB
Ruby
Raw Normal View History

2011-08-26 22:59:43 +02:00
require 'iconv'
2011-07-27 20:34:30 +02:00
class Message < ActiveRecord::Base
2011-08-26 22:59:43 +02:00
2011-08-02 23:12:17 +02:00
belongs_to :user
2011-08-16 20:05:58 +02:00
belongs_to :folder
2011-08-02 23:12:17 +02:00
2011-08-26 22:59:43 +02:00
set_primary_key :uid
attr_accessible :unseen, :to_addr, :size, :content_type, :folder_id, :subject, :date, :uid, :from_addr, :user_id, :msg_id
def self.decode(text,unknown_encoding = $defaults["msg_unknown_encoding"])
begin
2011-08-27 22:00:06 +02:00
if text.=~(/=\?/).nil?
2011-08-26 22:59:43 +02:00
after = Iconv.conv('UTF-8',unknown_encoding,text)
else
2011-08-27 22:00:06 +02:00
# TODO support multiple showing of =?xxx?=
text =~ /(=\?\S+\?=)/
after = text
match = $1
logger.custom('match',match)
f = match.split(/\?/)
case f[2].downcase
when 'q':
replace = f[3].gsub(/_/," ").unpack("M").first
when 'b':
replace = f[3].gsub(/_/," ").unpack("m").first
else
replace = match
end
logger.custom('replace',replace)
match.gsub!(/\?/,'\?')
match.gsub!(/\)/,'\)')
after = text.gsub(/#{match}/,replace)
logger.custom('after',after)
2011-08-26 22:59:43 +02:00
if f[1].downcase != 'utf-8'
after = Iconv.conv('UTF-8',f[1],after)
end
end
return after
rescue
logger.error("Class Message: String decode error: #{text}")
return text
end
end
def self.addr_to_db(addr)
ret = ""
name = addr.name
name.nil? ? ret : ret << decode(name)
ret << "<" + addr.mailbox + "@" + addr.host
ret
end
2011-08-24 19:20:13 +02:00
2011-08-16 20:05:58 +02:00
def self.getPageForUser(user,folder,page,sort_field,sort_dir)
2011-08-02 23:12:17 +02:00
2011-08-16 20:05:58 +02:00
order = 'date desc'
if sort_field
if Message.attribute_method?(sort_field) == true
order = sort_field
sort_dir == 'desc' ? order += ' desc' : sort_dir
end
end
2011-08-02 23:12:17 +02:00
2011-08-16 20:05:58 +02:00
Message.paginate :page => page , :per_page => user.prefs.msgs_per_page.to_i, :conditions=> ['user_id = ? and folder_id = ?', user.id,folder.id],:order => order
end
2011-08-26 22:59:43 +02:00
def self.createForUser(user,folder,imap_message)
envelope = imap_message.attr['ENVELOPE']
from = addr_to_db(envelope.from[0])
to = addr_to_db(envelope.to[0])
envelope.subject.nil? ? subject = "" : subject = decode(envelope.subject)
2011-08-16 20:05:58 +02:00
create(
:user_id => user.id,
:folder_id => folder.id,
2011-08-26 22:59:43 +02:00
:msg_id => envelope.message_id,
:uid => imap_message.attr['UID'].to_i,
:from_addr => from,
:to_addr => to,
:subject => subject,
:content_type => imap_message.attr['BODYSTRUCTURE'].media_type.downcase,
:date => envelope.date,
:unseen => !(imap_message.attr['FLAGS'].member? :Seen),
:size => imap_message.attr['RFC822.SIZE']
)
end
2011-08-16 20:05:58 +02:00
def change_folder(folder)
update_attributes(:folder_id => folder.id)
2011-08-02 23:12:17 +02:00
end
2011-08-26 22:59:43 +02:00
2011-07-27 20:34:30 +02:00
end