Class: Stats::EventReport

Inherits:
Report
  • Object
show all
Extended by:
ActionView::Helpers::NumberHelper, ActionView::Helpers::TextHelper, ActiveSupport::Inflector
Defined in:
lib/stats/event_report.rb

Defined Under Namespace

Classes: Pluralizer

Constant Summary collapse

SUPPRESSED_LABELS =
{ 
  :id                => %w[domain metropolitan-area],
  :title             => %w[country domain metropolitan-area tag browser device profile],
  :hits              => %w[],
  :plays             => %w[profile],
  :downloads         => %w[domain profile],
  :bytes_transferred => %w[profile],
}
PRECISION_DURATION =
2
PRECISION_GB =
2
AMMAP_COUNTRIES =
[ "AF", "AX", "AL", "DZ", "AD", "AO", "AI", "AG",
"AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY",
"BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BR", "BN", "BG",
"BF", "BI", "KH", "CM", "CA", "CV", "CF", "TD", "CL", "CN", "CO",
"KM", "CG", "CD", "CR", "CI", "HR", "CU", "CY", "CZ", "DK", "DJ",
"DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FO", "FK",
"FJ", "FI", "FR", "GF", "GA", "GM", "GE", "DE", "GH", "GR", "GL",
"GD", "GP", "GT", "GN", "GW", "GY", "HT", "HN", "HK", "HU", "IS",
"IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP", "JO", "KZ",
"KE", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY",
"LI", "LT", "LU", "MK", "MG", "MW", "MY", "ML", "MT", "MQ", "MR",
"MU", "MX", "MD", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NP",
"NL", "NC", "NZ", "NI", "NE", "NG", "NO", "OM", "PK", "PW", "PS",
"PA", "PG", "PY", "PE", "PH", "PL", "PT", "PR", "QA", "RE", "RO",
"RU", "RW", "KN", "LC", "WS", "ST", "SA", "SN", "RS", "SL", "SG",
"SK", "SI", "SB", "SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ",
"SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TO",
"TT", "TN", "TR", "TM", "TC", "UG", "UA", "AE", "GB", "US", "UY",
"UZ", "VU", "VE", "VN", "VG", "EH", "YE", "ZM", "ZW", ]
MinimumMapBubbleSize =
7

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Report

#==, #[], array_to_csv, array_to_xml, csv_labels, format_csv_value, #initialize, pad_reports, set_attributes, set_numeric_attributes, strip_label, #the_csv_keys

Constructor Details

This class inherits a constructor from Stats::Report

Class Method Details

.calculate_bubble_size(value) ⇒ Object



332
333
334
335
# File 'lib/stats/event_report.rb', line 332

def self.calculate_bubble_size value
  return 0 if value == 0
  (MinimumMapBubbleSize + 5.0 * Math.log10(value)).to_i
end

.csv_keysObject



134
135
136
# File 'lib/stats/event_report.rb', line 134

def self.csv_keys
  [ :id, :name, :title, :hits, :plays, :downloads, :bytes_transferred, :date, :start_date, :end_date ]
end

.format_duration(value) ⇒ Object



350
351
352
# File 'lib/stats/event_report.rb', line 350

def self.format_duration(value)
  format_float(value, PRECISION_DURATION)
end

.format_float(value, precision) ⇒ Object



346
347
348
# File 'lib/stats/event_report.rb', line 346

def self.format_float(value, precision)
  value.round(precision)
end

.format_gb(value) ⇒ Object



354
355
356
# File 'lib/stats/event_report.rb', line 354

def self.format_gb(value)
  format_float(value, PRECISION_GB)
end

.get_url(r) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/stats/event_report.rb', line 109

def self.get_url(r)
  if 'image' == r.stats_type
    prepend = 'image_'
    type    = 'albums'
  elsif 'track' == r.stats_type
    prepend = ''
    type    = 'tracks'
  else
    prepend = ''
    type    = 'videos'
  end

  url = if r.id.nil?
          nil
        else
          case r.label
          when "company" then "/companies/#{r.id}/#{prepend}statistics"
          when "video"   then "/videos/#{r.id}/statistics"
          when "track"   then "/tracks/#{r.id}/statistics"
          end
        end
  url ||= (r.title.blank? ? nil : "/#{type}/#{r.id}/statistics")

end

.make_title_value(metric, value) ⇒ Object



337
338
339
340
341
342
343
344
# File 'lib/stats/event_report.rb', line 337

def self.make_title_value metric, value
  if [:bytes_transferred].include? metric
    title_value = number_with_delimiter(number_to_human_size(value))  + ' transferred'
  else
    title_value = Pluralizer.pluralize(number_with_delimiter(value), singularize(metric))
  end
  title_value
end

.to_amcharts(reports, show_date, show_date_range, options = {}) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/stats/event_report.rb', line 138

def self.to_amcharts(reports, show_date, show_date_range, options = {})
  options["fields"] ||= [ :hits, :plays, :downloads ].reject { |field| SUPPRESSED_LABELS[field].include?(options["group"]) }.map(&:to_s)
  complete_labels = []
  labels          = []
  hits            = []
  plays           = []
  downloads       = []
  urls            = []
  guids           = []
  reports         = pad_reports(reports, options) if options["pad"]
  reports         = reports.reverse if options[:reverse]

  reports.each do |r|
    if show_date and !r.date.blank?
      label = "#{r.date.month}/#{r.date.day}"
    elsif show_date_range and !r.start_date.blank? and !r.end_date.blank?
      label = if r.start_date.month == r.end_date.month && r.start_date.day == r.start_date.beginning_of_month.day && r.end_date.day == r.end_date.end_of_month.day
                "#{r.start_date.strftime("%b \'%y")}"
              else
                "#{r.start_date.month}/#{r.start_date.day}-#{r.end_date.month}/#{r.end_date.day}"
              end
    elsif !r.title.blank?
      label = r.title
    elsif !r.name.blank?
      label = r.name
    else
      label = r.id.to_s
    end

    complete_labels << label
    labels          << label.previewize((options[:max_label_length] || 15).to_i)
    hits            << r.hits
    if r.stats_type != 'image'
      plays     << r.plays
      downloads << r.downloads
    end

    guids << r.id
    if !options.has_key?(:video_id) && !options.has_key?(:track_id)
      urls << get_url(r)
    else
      urls << nil
    end
  end

  show_screenshots = false # && reports.length <= 10

  max_labels = 40
  # frequency == 1 if we can display all labels, or a number greater
  # than 1 if we can't
  if show_date || show_date_range
    frequency = 1
  else
    frequency = (labels.length / max_labels.to_f).ceil
  end

  xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => 2)
  xml.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
  xml.chart do
    xml.series do
      labels.each_with_index do |value, index|
        # only display every nth value where n depends the total
        # number of labels and the max labels we are allowed to
        # display, otherwise clear out the value
        value = "" if index % frequency != 0
        xml.value value, :xid => index
      end
    end

    xml.graphs do
      #the gid is used in the settings file to set different settings just for this graph
      level = "Hits"
      if options[:fields].include?("hits")
        xml.graph :gid => 'hits' do
          hits.each_with_index do |value, index|
            if value != 0 || complete_labels[index].blank? || show_date || show_date_range
              opts = { :xid => index, :description => complete_labels[index] }
              opts[:url] = urls[index] unless urls[index].blank?
              xml.value value, opts
            end
          end
        end
      end

      if options[:fields].include?("plays")
        xml.graph :gid => 'plays' do
          plays.each_with_index do |value, index|
            if value != 0 || complete_labels[index].blank? || show_date || show_date_range
              opts = { :xid => index, :description => complete_labels[index] }
              opts[:url] = urls[index] unless urls[index].blank?
              opts[:bullet] = "../videos/#{guids[index]}/screenshots/32w.jpg" if !guids[index].blank? && show_screenshots
              xml.value value, opts
            end
          end
        end
      end

      if options[:fields].include?("downloads")
        xml.graph :gid => 'downloads' do
          downloads.each_with_index do |value, index|
            if value != 0 || complete_labels[index].blank? || show_date || show_date_range
              opts = { :xid => index, :description => complete_labels[index] }
              opts[:url] = urls[index] unless urls[index].blank?
              xml.value value, opts
            end
          end
        end
      end
    end
  end
end

.to_ammap_country_data(reports, metric) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/stats/event_report.rb', line 270

def self.to_ammap_country_data(reports, metric)
  xml = Builder::XmlMarkup.new(:indent => 2)
  zoom, zoom_x, zoom_y = zoom_levels
  xml.map :map_file => 'maps/world.swf', :zoom_x => zoom_x, :zoom_y => zoom_y, :zoom => zoom do
    xml.areas do
      AMMAP_COUNTRIES.each do |country_code|
        report      = reports.find { |report| report.id == country_code }
        value       = report && report.send(metric) || 0
        title_value = make_title_value(metric, value)

        attributes = {
          :title =>  "#{TZInfo::Country.code_to_name(country_code)}: #{title_value}",
          :mc_name => country_code,
          :value => value == 0 ? 0 : sprintf('%.8f', Math.log(value + 1))
        }
        xml.area attributes
      end
      xml.area :mc_name => "borders", :color => "#AAAAAA"
    end
  end
  xml.target!
end

.to_ammap_metro_data(reports, metric) ⇒ Object



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/stats/event_report.rb', line 297

def self.to_ammap_metro_data(reports, metric)
  xml = Builder::XmlMarkup.new(:indent => 2)
  zoom, zoom_x, zoom_y = zoom_levels
  color = "Graphs::#{metric.to_s.capitalize}".constantize.new.color1 rescue '85E006'
  xml.map :map_file => 'maps/world.swf', :tl_long => "-168.49", :tl_lat => "83.63", :br_long => "190.3", :br_lat => "-55.58", :zoom_x => zoom_x, :zoom_y => zoom_y, :zoom => zoom do
    xml.movies do
      reports.select { |report| not report.id.blank? }.each do |report|
        latitude, longitude = report.id.split(';')
        bubble_size = calculate_bubble_size(report.send(metric))
        title_value = make_title_value metric, report.send(metric)
        xml.movie(:title      =>  "#{report.name}: #{title_value}",
                  :lat        => latitude, 
                  :long       => longitude,
                  :file       => 'target',
                  :width      => bubble_size, 
                  :height     => bubble_size,
                  :color      => color,
                  :alpha      => 65,
                  :fixed_size => true)
      end
    end

    xml.areas do
      AMMAP_COUNTRIES.each do |country_code|
        xml.area :mc_name => country_code, :value => 0
      end
      xml.area :mc_name => "borders", :color => "#AAAAAA"
    end
  end

  xml.target!
end

.zoom_levelsObject



293
294
295
# File 'lib/stats/event_report.rb', line 293

def self.zoom_levels
  return "115%", "-0%", "-20%"
end

Instance Method Details

#get_start_date(scope) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/stats/event_report.rb', line 44

def get_start_date(scope)
  case scope
  when nil, :daily
    @date
  when :monthly, :weekly
    @start_date
  end
end

#set_date(time, scope = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/stats/event_report.rb', line 28

def set_date(time, scope = nil)
  t = Time.parse time.to_s
  case scope
  when nil
    @date = t
  when :daily
    @date = t.beginning_of_day
  when :monthly
    @start_date = t.beginning_of_month
    @end_date = t.end_of_month
  when :weekly
    @start_date = t.beginning_of_week
    @end_date = @start_date.next_week.yesterday
  end
end

#to_csv(options = {}) ⇒ Object



76
77
78
79
80
81
82
83
# File 'lib/stats/event_report.rb', line 76

def to_csv(options = {})
  klass_keys = options[:images] ? Stats::ImageReport.csv_keys : self.class.csv_keys 
  the_csv_keys = strip_keys_by_label(klass_keys, @label)

  the_csv_keys.map do |k|
    self.class.format_csv_value(send(k))
  end.join(',')
end

#to_json(options = {}) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/stats/event_report.rb', line 85

def to_json(options = {})
  report          = HashWithIndifferentAccess.new
  report['id']    = @id   if @id and not SUPPRESSED_LABELS[:id].include?(@label)
  report['name']  = @name if @name
  report['title'] = @title unless SUPPRESSED_LABELS[:title].include?(@label)

  report['hits'] = @hits
  if @stats_type != 'image'
    [ :plays, :downloads ].each do |key|
      report[key.to_s] = self[key.to_s] unless SUPPRESSED_LABELS[key].include?(@label)
    end
  end

  report['date']       = pretty_time(@date)       if @date
  report['start_date'] = pretty_time(@start_date) if @start_date
  report['end_date']   = pretty_time(@end_date)   if @end_date

  unless SUPPRESSED_LABELS[:bytes_transferred].include?(@label)
    report['bytes_transferred'] = @bytes_transferred.to_i
  end

  report.to_json
end

#to_xml(options = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/stats/event_report.rb', line 53

def to_xml options = {}
  xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
  xml.instruct! unless options[:skip_instruct]

  xml.__send__(@label) do
    xml.id @id if @id and not SUPPRESSED_LABELS[:id].include?(@label)
    xml.name @name if @name
    xml.title @title unless SUPPRESSED_LABELS[:title].include?(@label)
    xml.hits @hits
    if @stats_type != 'image'
      [ :plays, :downloads ].each do |key|
        xml.tag!(key, self[key]) unless SUPPRESSED_LABELS[key].include?(@label)
      end
    end
    xml.date(pretty_time(@date)) if @date
    xml.start_date(pretty_time(@start_date)) if @start_date
    xml.end_date(pretty_time(@end_date)) if @end_date
    unless SUPPRESSED_LABELS[:bytes_transferred].include?(@label)
      xml.bytes_transferred @bytes_transferred.to_i
    end
  end
end