-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathlinks.rb
More file actions
68 lines (59 loc) · 2.59 KB
/
Copy pathlinks.rb
File metadata and controls
68 lines (59 loc) · 2.59 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
# encoding: UTF-8
require 'addressable/uri'
require 'uri'
class Links < Linkbot::Plugin
attr_reader :config, :whitelist
def initialize
register :regex => Regexp.new('(?i)\b((?:[a-z][\w-]+:(?:/{2,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))')
@config = Linkbot::Config["plugins"].fetch("links", {})
whitelist_strings = @config.fetch("whitelist", [])
@whitelist = whitelist_strings.map do |link|
uri = URI.parse(link)
Regexp.new("^#{uri.host}#{uri.path}")
end
if Linkbot.db.table_info('links').empty?
Linkbot.db.execute('CREATE TABLE links (user_id STRING, dt DATETIME, url TEXT)');
end
if Linkbot.db.table_info('trans').empty?
Linkbot.db.execute('CREATE TABLE trans (user_id STRING, karma INTEGER, trans TEXT)');
end
end
def on_message(message, matches)
# matches[0] is the first HTTP(S) URL found in a message
# Slack detects domains without a protocol and rewrites the message
# using Slack's markup, e.g. foxnews.com -> <http://foxnews.com|foxnews.com>
# the gnarly regex in this plugin detects the URL, but also slurps up the
# markup's pipe and link text, e.g.:bad URI(is not URI?): http://foxnews.com|foxnews.com>
# So, split on the pipe and take the first thing until we get around to
# chopping up that regex
url = matches[0].split('|')[0]
url = Addressable::URI.unescape(url)
uri = URI.parse(url)
# First, make sure this is a HTTP or HTTPS scheme
if uri.scheme.downcase == "http" || uri.scheme.downcase == "https"
# Make sure this link has not been whitelisted
whitelist.each do |whitelist_regex|
if whitelist_regex.match("#{uri.host}#{uri.path}")
return ''
end
end
messages = []
rows = Linkbot.db.execute("select username, dt from links, users where links.user_id=users.user_id and url = ?", url)
if rows.empty?
Linkbot::Plugin.plugins.each {|plugin|
messages << plugin.on_newlink(message, url).join("\n") if(plugin.respond_to?(:on_newlink))
}
# Add the link to the dupe table
Linkbot.db.execute("insert into links (user_id, dt, url) VALUES (?, ?, ?)",
message.user_id, Time.now.to_s, url)
else
Linkbot::Plugin.plugins.each {|plugin|
messages << plugin.on_dupe(message, url, rows[0][0], rows[0][1]) if(plugin.respond_to?(:on_dupe))
}
end
messages.join("\n")
else
''
end
end
end