| 1 |
|
| 2 |
require 'cgi' |
| 3 |
|
| 4 |
module Plugin::Bitly |
| 5 |
USER = 'mikutter'.freeze |
| 6 |
APIKEY = 'R_70170ccac1099f3ae1818af3fa7bb311'.freeze |
| 7 |
SHRINKED_MATCHER = %r[\Ahttp://(bit\.ly|j\.mp)/].freeze |
| 8 |
|
| 9 |
extend self |
| 10 |
|
| 11 |
ザ名を返す |
| 12 |
def user |
| 13 |
if UserConfig[:bitly_user] == '' or not UserConfig[:bitly_user] |
| 14 |
USER |
| 15 |
else |
| 16 |
UserConfig[:bitly_user] |
| 17 |
end end |
| 18 |
|
| 19 |
返す |
| 20 |
def apikey |
| 21 |
if UserConfig[:bitly_apikey] == '' or not UserConfig[:bitly_apikey] |
| 22 |
APIKEY |
| 23 |
else |
| 24 |
UserConfig[:bitly_apikey] |
| 25 |
end end |
| 26 |
|
| 27 |
def expand_url_many(urls) |
| 28 |
query = "login=#{user}&apiKey=#{apikey}&" + urls.map{ |url| |
| 29 |
"shortUrl=#{CGI.escape(url)}" }.join('&') |
| 30 |
3.times do |
| 31 |
result = begin |
| 32 |
JSON.parse(Net::HTTP.get("api.bit.ly", "/v3/expand?#{query}")) |
| 33 |
rescue Exception |
| 34 |
nil end |
| 35 |
if result and result['status_code'].to_i == 200 |
| 36 |
return result['data']['expand'].to_h do |token| |
| 37 |
token.values_at('short_url', 'long_url') |
| 38 |
end |
| 39 |
end |
| 40 |
end |
| 41 |
end |
| 42 |
end |
| 43 |
|
| 44 |
Plugin.create :bitly do |
| 45 |
expand_mutex = Mutex.new |
| 46 |
waiting_expand_entities = TimeLimitedStorage.new(String, Set, 30) |
| 47 |
|
| 48 |
ntityを更新する |
| 49 |
トでexpandできる最大数は15 |
| 50 |
|
| 51 |
expand_queue = TimeLimitedQueue.new(15, 0.5, Set) do |set| |
| 52 |
Thread.new { |
| 53 |
expand_mutex.synchronize do |
| 54 |
Plugin::Bitly.expand_url_many(set).each do |shrinked, expanded| |
| 55 |
waiting_expand_entities[shrinked].each do |query| |
| 56 |
query.(expanded) |
| 57 |
rescue => exception |
| 58 |
error exception |
| 59 |
end |
| 60 |
end |
| 61 |
end |
| 62 |
}.trap{|exception| |
| 63 |
warn exception |
| 64 |
set.each do |url| |
| 65 |
waiting_expand_entities[url].each do |
| 66 |
query.call nil end end |
| 67 |
}.next { |
| 68 |
set.each do |url| |
| 69 |
waiting_expand_entities[url] = Set.new end |
| 70 |
}.terminate end |
| 71 |
|
| 72 |
on_gui_timeline_add_messages do |i_timeline, messages| |
| 73 |
messages.map(&:entity).each do |entity| |
| 74 |
entity.select{|_| |
| 75 |
:urls == _[:slug] and Plugin::Bitly::SHRINKED_MATCHER =~ _[:url] |
| 76 |
}.each do |link| |
| 77 |
expand_mutex.synchronize do |
| 78 |
(waiting_expand_entities[link[:url]] ||= Set.new) << ->expanded{ |
| 79 |
entity.add link.merge(url: expanded, face: expanded) } |
| 80 |
expand_queue.push link[:url] end end end end |
| 81 |
|
| 82 |
filter_expand_url do |urlset| |
| 83 |
divided = urlset.group_by{|url| !!(Plugin::Bitly::SHRINKED_MATCHER =~ url) } |
| 84 |
divided[false] ||= [] |
| 85 |
divided[true] ||= [] |
| 86 |
[divided[false] + divided[true].each_slice(15).map{|chunk|Plugin::Bitly.expand_url_many(chunk).values}.flatten] end |
| 87 |
end |