aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/raw_email.rb
blob: 6e073aa2704b330ed4fd5042447ef54e133c6088 (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
# == Schema Information
# Schema version: 108
#
# Table name: raw_emails
#
#  id :integer         not null, primary key
#

# models/raw_email.rb:
# The fat part of models/incoming_message.rb
#
# Copyright (c) 2008 UK Citizens Online Democracy. All rights reserved.
# Email: francis@mysociety.org; WWW: http://www.mysociety.org/
#
# $Id: raw_email.rb,v 1.12 2009-09-17 21:10:05 francis Exp $

class RawEmail < ActiveRecord::Base
    # deliberately don't strip_attributes, so keeps raw email properly
    
    has_one :incoming_message

    # We keep the old data_text field (which is of type text) for backwards
    # compatibility. We use the new data_binary field because only it works
    # properly in recent versions of PostgreSQL (get seg faults escaping
    # some binary strings).

    def directory
        request_id = self.incoming_message.info_request.id.to_s
        if ENV["RAILS_ENV"] == "test"
            return 'files/raw_email_test'
        else
            return File.join(MySociety::Config.get('RAW_EMAILS_LOCATION',
                                                   'files/raw_emails'), 
                             request_id[0..2], request_id)
        end
    end

    def filepath
        File.join(self.directory, self.incoming_message.id.to_s)
    end

    def data=(d)
        if !File.exists?(self.directory)
            FileUtils.mkdir_p self.directory
        end
        File.atomic_write(self.filepath) { |file|
            file.write d
        }
    end

    def data
        if !File.exists?(self.filepath)
            dbdata
        else
            File.open(self.filepath, "rb" ).read
        end
    end

    def destroy_file_representation!
        File.delete(self.filepath)
    end

    def dbdata=(d)
        write_attribute(:data_binary, d)
    end

    def dbdata
        d = read_attribute(:data_binary)
        if !d.nil?
            return d
        end

        d = read_attribute(:data_text)
        if !d.nil?
            return d
        end

        raise "internal error, double nil value in RawEmail"
    end

end