/
attachment.rb
98 lines (82 loc) 路 2.38 KB
/
attachment.rb
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
# == Schema Information
#
# Table name: attachments
#
# id :integer not null, primary key
# coordinates_lat :float default(0.0)
# coordinates_long :float default(0.0)
# extension :string
# external_url :string
# fallback_title :string
# file_type :integer default("image")
# created_at :datetime not null
# updated_at :datetime not null
# account_id :integer not null
# message_id :integer not null
#
class Attachment < ApplicationRecord
include Rails.application.routes.url_helpers
belongs_to :account
belongs_to :message
has_one_attached :file
validate :acceptable_file
enum file_type: [:image, :audio, :video, :file, :location, :fallback]
def push_event_data
return base_data.merge(location_metadata) if file_type.to_sym == :location
return base_data.merge(fallback_data) if file_type.to_sym == :fallback
base_data.merge(file_metadata)
end
def file_url
file.attached? ? url_for(file) : ''
end
def thumb_url
if file.attached? && file.representable?
url_for(file.representation(resize: '250x250'))
else
''
end
end
private
def file_metadata
{
extension: extension,
data_url: file_url,
thumb_url: thumb_url
}
end
def location_metadata
{
coordinates_lat: coordinates_lat,
coordinates_long: coordinates_long,
fallback_title: fallback_title,
data_url: external_url
}
end
def fallback_data
{
fallback_title: fallback_title,
data_url: external_url
}
end
def base_data
{
id: id,
message_id: message_id,
file_type: file_type,
account_id: account_id
}
end
def should_validate_file?
return unless file.attached?
# we are only limiting attachment types in case of website widget
return unless message.inbox.channel_type == 'Channel::WebWidget'
true
end
def acceptable_file
should_validate_file?
errors.add(:file, 'is too big') if file.byte_size > 40.megabytes
acceptable_types = ['image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/tiff', 'application/pdf', 'audio/mpeg', 'video/mp4', 'audio/ogg',
'text/csv'].freeze
errors.add(:file, 'filetype not supported') unless acceptable_types.include?(file.content_type)
end
end