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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
# File 'lib/shared_count/cli.rb', line 23
def run(lines)
configure_shared_count_client
logger.info "Using #{concurrency} threads"
logger.info "The iteration size is #{iteration_size} URLs"
iterations, mod = lines.length.divmod(iteration_size)
iterations += 1 if mod > 0
results = Queue.new
iterations.times do |iteration|
logger.error "Iteration ##{iteration + 1}"
queue = Queue.new
from = iteration_size * iteration
lines[from, iteration_size].each { |url| queue.push(url) }
thread_count = [MAX_CONCURRENCY, lines.length].min
threads = (0...thread_count).map do |thread|
Thread.new(thread) do |thread|
error = 0
url = begin
queue.pop(true)
rescue ThreadError; end
while url do
url.chomp!
uri = URI(url)
host = uri.host || url[/\Ahttps?:\/\/([^\/]+)/, 1]
url = "#{uri.scheme}://#{host}"
response = nil
begin
response = SharedCountApi::Client.new(url).response
rescue SharedCountApi::Error
logger.error "[Thread ##{thread}] - error while processing '#{url}'"
rescue => err
logger.error "[Thread ##{thread}] - error while processing '#{url}', retry: ##{error} - #{err.inspect}"
error += 1
sleep(SLEEP_TIME)
if error <= MAX_RETRIES
retry
else
queue.push(url)
break
end
else
error = 0
end
if response
logger.debug "[Thread ##{thread}] - #{url}"
facebook_metrics = response.delete("Facebook")
facebook_metrics = {} unless facebook_metrics.is_a?(Hash)
values = response.values.unshift(url)
results.push(values.concat(facebook_metrics.values))
else
logger.warn "[Thread ##{thread}] - no response for '#{url}'"
end
url = begin
queue.pop(true)
rescue ThreadError; end
end
end
end
threads.each do |thread|
begin
thread.join(JOIN_TIMEOUT)
rescue => err
logger.error "[Thread ##{thread}] - error while joining main thread: #{err.inspect}"
logger.error "[Thread ##{thread}] - #{err.backtrace.join("\n")}"
end
end
end
CSV.generate do |csv|
csv << %w(URL StumbleUpon Reddit Delicious GooglePlusOne Buzz Twitter Diggs Pinterest LinkedIn commentsbox_count click_count total_count comment_count like_count share_count)
csv << []
loop do
begin
arr = results.pop(true)
csv << arr
rescue ThreadError
break
end
end
end
end
|