forked from linuxfrorg/linuxfr.org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage.rb
More file actions
92 lines (75 loc) · 2.14 KB
/
image.rb
File metadata and controls
92 lines (75 loc) · 2.14 KB
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
# encoding: UTF-8
##
# When a user use an image from an external domain on LinuxFr.org, we keep some
# infos about this image in redis, so it can served by our proxy/cache daemon, img.
#
class Image < Struct.new(:link, :title, :alt_text, :blocked)
LATEST_KEY = "img/latest"
NB_IMG_IN_LATEST = 100
BLOCKED_KEY = "img/blocked"
E403 = "/images/403.png"
def self.latest(nb=NB_IMG_IN_LATEST)
links = $redis.lrange LATEST_KEY, 0, nb
links.map {|l| Image.new(l, l, l, ($redis.hget "img/#{l}", "status") == "Blocked") }
end
def self.blocked(nb)
links = $redis.lrange BLOCKED_KEY, 0, nb
links.map {|l| Image.new(l, l, l, ($redis.hget "img/#{l}", "status") == "Blocked") }
end
def self.decoded_link(encoded_link)
[encoded_link].pack('H*')
end
def self.destroy(encoded_link)
link = decoded_link(encoded_link)
if $redis.hset "img/#{link}", "status", "Blocked"
$redis.lpush BLOCKED_KEY, link
end
end
def self.original_link(link)
decoded_link link.split('/')[-2]
end
def register_in_redis
if $redis.exists? "img/#{link}"
$redis.del "img/err/#{link}"
return
end
$redis.hsetnx "img/#{link}", "created_at", Time.now.to_i
$redis.lpush LATEST_KEY, link
$redis.ltrim LATEST_KEY, 0, NB_IMG_IN_LATEST - 1
end
def internal_link?
uri = URI.join(link)
!uri.host || uri.host == MY_DOMAIN || uri.host == IMG_DOMAIN
end
def blacklisted?
uri = URI.join(link)
uri.host =~ /^(10|127|169\.254|192\.168)\./
end
def encoded_link
link.unpack('H*').first
end
def filename
File.basename link
end
def src(type="img")
return link if internal_link?
return E403 if blacklisted?
register_in_redis
"#{IMG_PUBLIC_URL}/#{type}/#{encoded_link}/#{filename}"
end
def src_attr
"src=\"#{CGI.escapeHTML src.to_s}\""
end
def alt_attr
"alt=\"#{CGI.escapeHTML alt_text.to_s}\""
end
def title_attr
parts = [title]
parts << "Source : #{link}" unless internal_link?
parts.compact!
parts.empty? ? "" : "title=\"#{CGI.escapeHTML parts.join(' | ')}\" "
end
def to_html
"<img #{src_attr} #{alt_attr} #{title_attr}/>"
end
end