runlight 0.5.6 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/assets/tracker.js CHANGED
@@ -1 +1 @@
1
- (function(){var n=window,t=document,w=navigator,s=location,j=t.currentScript;if(j){var h=e=>j.getAttribute("data-"+e),b=e=>h(e)!==null,y=Date.now,o=(e,r,a,i)=>e.addEventListener(r,a,i),N=j.src.replace(/s\.js(\?.*)?$/,""),E=N+"e",Y=E.indexOf(s.origin+"/")?"text/plain":"application/json",O=h("site"),z=b("hash"),R=b("manual"),B=h("before-send"),F=e=>new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$"),K=(h("exclude")||"").split(",").filter(Boolean).map(e=>F(e.trim())),M=!1,Q=n.runlight&&n.runlight.q||[],k="__RUNLIGHT_RULES__",W=typeof k=="object"&&(k[O]||k[s.hostname.replace(/^www\./,"")]||k["*"])||[],q=w.webdriver||b("dnt")&&(w.doNotTrack==1||n.doNotTrack==1),U=(/[?&]runlight=(ignore|track|pick)\b/.exec(s.search)||[])[1];try{var _=localStorage,A="runlight_ignore";U==="ignore"&&_.setItem(A,y()),U==="track"&&_.removeItem(A);var C=_.getItem(A);(C==1||y()-C<31536e6)&&(q=!0)}catch(e){}var D=()=>{f="",R||v()},H=U==="pick";if(H){var x=t.createElement("script");x.src=N+"pick.js"+s.search,x.onload=x.onerror=()=>{H=l.pick,D()},t.head.appendChild(x)}var I=(e,r)=>{if(!(M||q||H||t.prerendering)){var a=Object.assign({k:e,u:f},O&&{s:O},r);if(B!==null)try{if(a=n[B](a),!a||a.constructor!==Object)return}catch(d){return}var i=new Blob([JSON.stringify(a)],{type:Y});try{if(w.sendBeacon(E,i))return}catch(d){}n.fetch&&fetch(E,{method:"POST",body:i,keepalive:!0}).catch(()=>{})}},G=b("404"),f="",p="",g=0,m=0,S=0,J=()=>{m&&(g+=y()-m),m=0},u=()=>{!m&&!t.hidden&&t.hasFocus()&&(m=y())},L=()=>{J(),p&&g>=1e3&&(I("engagement",{i:p,e:g,d:S}),g=0)},P=()=>{var e=t.documentElement,r=Math.max(e.scrollHeight,t.body?t.body.scrollHeight:0),a=n.scrollY+n.innerHeight,i=r>0?Math.min(100,Math.round(a/r*100)):100;i>S&&(S=i)},v=e=>{if(t.prerendering)return o(t,"prerenderingchange",()=>v(e));var r=typeof e=="string"?new URL(e,s.href).href:s.origin+s.pathname+s.search+(z?s.hash:"");if(r!==f){var a=f||t.referrer;L(),f=r,M=K.some(i=>i.test(new URL(r).pathname)),p=Array.from(crypto.getRandomValues(new Uint8Array(6)),i=>(i+256).toString(36).slice(-2)).join(""),g=0,S=0,P(),u(),I("pageview",{i:p,r:a,t:t.title,w:screen.width,h:screen.height,l:w.language}),G&&l("404",{path:s.pathname}),G=!1}},l=(e,r)=>{typeof e!="string"||!e||I("event",{i:p,n:e,p:r&&typeof r=="object"?r:void 0})},V=(e,r)=>{var a=history[e];history[e]=function(){var i=s.pathname,d=a.apply(this,arguments);return(!r||i!==s.pathname)&&setTimeout(v),d}};R||(V("pushState"),V("replaceState",1),o(n,"popstate",v),z&&o(n,"hashchange",v),o(n,"pageshow",e=>e.persisted&&D())),o(t,"visibilitychange",()=>{t.hidden?L():u()}),o(n,"pagehide",L),o(n,"blur",J),o(n,"focus",u),o(n,"scroll",()=>{P(),u()},{passive:!0}),o(t,"pointerdown",u,!0),o(t,"keydown",u,!0);var X=/\.(pdf|zip|gz|tgz|dmg|pkg|exe|msi|apk|docx?|xlsx?|pptx?|csv|txt|rtf|epub|mp3|wav|mp4|mov|avi|mkv|psd|ai|svg|key|numbers|pages)$/i;o(t,"click",e=>{var r=e.target;if(!(!r||!r.closest)){var a=r.closest("a[href]");W.forEach(c=>{try{var $=c[1];(c[0]==="s"?r.closest($):a&&F($).test($[0]==="/"?a.pathname:a.href))&&l(c[2])}catch(Z){}});var i=r.closest("[data-runlight]");if(i){var d={};Array.from(i.attributes).forEach(c=>{c.name.indexOf("data-runlight-")||(d[c.name.slice(14)]=c.value)}),l(i.getAttribute("data-runlight"),d)}if(!(!a||i)){var T=a.href;/^https?:/.test(T)&&(h("downloads")!=="false"&&X.test(a.pathname)?l("File download",{url:T}):h("outbound")!=="false"&&a.host!==s.host&&l("Outbound link",{url:T}))}}},!0),n.runlight=l,l.pageview=v,R||v(),Q.forEach(e=>l.apply(null,e))}})();
1
+ (function(){var i=window,t=document,d=navigator,s=location,j=t.currentScript;if(j){var h=e=>j.getAttribute("data-"+e),y=e=>h(e)!==null,b=Date.now,o=(e,r,a,n)=>e.addEventListener(r,a,n),T=j.src.replace(/s\.js(\?.*)?$/,""),E=T+"e",Y=E.indexOf(s.origin+"/")?"text/plain":"application/json",O=h("site"),z=y("hash"),R=y("manual"),B=h("before-send"),F=e=>new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$"),K=(h("exclude")||"").split(",").filter(Boolean).map(e=>F(e.trim())),N=!1,Q=i.runlight&&i.runlight.q||[],k="__RUNLIGHT_RULES__",W=typeof k=="object"&&(k[O]||k[s.hostname.replace(/^www\./,"")]||k["*"])||[],q=d.webdriver||y("dnt")&&(d.doNotTrack==1||d.globalPrivacyControl),U=(/[?&]runlight=(ignore|track|pick)\b/.exec(s.search)||[])[1];try{var _=localStorage,H="runlight_ignore";U==="ignore"&&_.setItem(H,b()),U==="track"&&_.removeItem(H);var C=_.getItem(H);(C==1||b()-C<31536e6)&&(q=!0)}catch(e){}var P=()=>{p="",R||v()},I=U==="pick";if(I){var x=t.createElement("script");x.src=T+"pick.js"+s.search,x.onload=x.onerror=()=>{I=l.pick,P()},t.head.appendChild(x)}var L=(e,r)=>{if(!(N||q||I||t.prerendering)){var a=Object.assign({k:e,u:p},O&&{s:O},r);if(B!==null)try{if(a=i[B](a),!a||a.constructor!==Object)return}catch(f){return}var n=new Blob([JSON.stringify(a)],{type:Y});try{if(d.sendBeacon(E,n))return}catch(f){}i.fetch&&fetch(E,{method:"POST",body:n,keepalive:!0}).catch(()=>{})}},D=y("404"),p="",g="",m=0,w=0,S=0,G=()=>{w&&(m+=b()-w),w=0},u=()=>{!w&&!t.hidden&&t.hasFocus()&&(w=b())},$=()=>{G(),g&&m>=1e3&&(L("engagement",{i:g,e:m,d:S}),m=0)},J=()=>{var e=t.documentElement,r=Math.max(e.scrollHeight,(t.body||e).scrollHeight),a=i.scrollY+i.innerHeight,n=r>0?Math.min(100,Math.round(a/r*100)):100;S=Math.max(S,n)},v=e=>{if(t.prerendering)return o(t,"prerenderingchange",()=>v(e));var r=typeof e=="string"?new URL(e,s.href).href:s.origin+s.pathname+s.search+(z?s.hash:"");if(r!==p){var a=p||t.referrer;$(),p=r,N=K.some(n=>n.test(new URL(r).pathname)),g=Array.from(crypto.getRandomValues(new Uint8Array(6)),n=>(n+256).toString(36)).join(""),m=0,S=0,J(),u(),L("pageview",{i:g,r:a,t:t.title,w:screen.width,h:screen.height,l:d.language}),D&&l("404",{path:s.pathname}),D=!1}},l=(e,r)=>{typeof e!="string"||!e||L("event",{i:g,n:e,p:r&&typeof r=="object"?r:void 0})},V=(e,r)=>{var a=history[e];history[e]=function(){var n=s.pathname,f=a.apply(this,arguments);return(!r||n!==s.pathname)&&setTimeout(v),f}};R||(V("pushState"),V("replaceState",1),o(i,"popstate",v),z&&o(i,"hashchange",v),o(i,"pageshow",e=>e.persisted&&P())),o(t,"visibilitychange",()=>{t.hidden?$():u()}),o(i,"pagehide",$),o(i,"blur",G),o(i,"focus",u),o(i,"scroll",()=>{J(),u()},{passive:!0}),o(t,"pointerdown",u,!0),o(t,"keydown",u,!0);var X=/\.(pdf|zip|gz|tgz|dmg|pkg|exe|msi|apk|docx?|xlsx?|pptx?|csv|txt|rtf|epub|mp3|wav|mp4|mov|avi|mkv|psd|ai|svg|key|numbers|pages)$/i;o(t,"click",e=>{var r=e.target;if(!(!r||!r.closest)){var a=r.closest("a[href]");W.forEach(c=>{try{var M=c[1];(c[0]==="s"?r.closest(M):a&&F(M).test(M[0]==="/"?a.pathname:a.href))&&l(c[2])}catch(Z){}});var n=r.closest("[data-runlight]");if(n){var f={};Array.from(n.attributes).forEach(c=>{c.name.indexOf("data-runlight-")||(f[c.name.slice(14)]=c.value)}),l(n.dataset.runlight,f)}if(!(!a||n)){var A=a.href;/^https?:/.test(A)&&(h("downloads")!=="false"&&X.test(a.pathname)?l("File download",{url:A}):h("outbound")!=="false"&&a.host!==s.host&&l("Outbound link",{url:A}))}}},!0),i.runlight=l,l.pageview=v,R||v(),Q.forEach(e=>l.apply(null,e))}})();
@@ -45,7 +45,7 @@ module Runlight
45
45
  "fr" => "Avec plaisir. Demandez-moi autre chose sur vos statistiques.",
46
46
  "es" => "De nada. Pregúntame lo que quieras sobre tus estadísticas.",
47
47
  "de" => "Gern geschehen. Frag mich gern noch etwas zu deinen Statistiken.",
48
- "pt" => "De nada. Pergunte o que quiser sobre suas estatísticas.",
48
+ "pt" => "De nada. Pergunta o que quiseres sobre as tuas estatísticas.",
49
49
  }.freeze
50
50
 
51
51
  # ICU's root collation puts these marks in this order, before digits and letters.
data/lib/runlight/core.rb CHANGED
@@ -222,6 +222,9 @@ module Runlight
222
222
  # When statistics were last checked for staleness, which reports do at most hourly.
223
223
  @freshened_at = 0
224
224
  @link_domain_cache = nil
225
+ # Whether each site drops hits that ask not to be tracked, as tracker hits read it, and when it was read.
226
+ @signal_cache = {}
227
+ @signal_lock = Mutex.new
225
228
  # Each timezone's salts for its current day, so a lookup is a map read until midnight there.
226
229
  @salts = {}
227
230
  # Retention work asked for and not yet done: a site's id, or nil for every site.
@@ -487,7 +490,8 @@ module Runlight
487
490
  end
488
491
 
489
492
  # What a connected install says about its site: its last visit and how long it keeps visits, asked
490
- # at most once a minute. Retention is UNDEFINED while the install cannot be reached, and `connection`
493
+ # at most once a minute. Retention and privacy signals are UNDEFINED while the install cannot be reached
494
+ # (privacy signals also when the install does not say), and `connection`
491
495
  # says whether it answered ("ok"), refused this server's token ("refused"), or could not be reached
492
496
  # ("unreachable").
493
497
  def remote_info(id)
@@ -497,7 +501,7 @@ module Runlight
497
501
  cached = @remote_seen[id]
498
502
  return cached.except("at") if !cached.nil? && now - cached["at"] < 60_000
499
503
 
500
- info = { "lastSeen" => cached&.[]("lastSeen"), "retentionMonths" => UNDEFINED, "connection" => "unreachable" }
504
+ info = { "lastSeen" => cached&.[]("lastSeen"), "retentionMonths" => UNDEFINED, "privacySignals" => UNDEFINED, "connection" => "unreachable" }
501
505
  begin
502
506
  answer = Safefetch.owner_fetch("#{remote["url"]}/api/sites", {
503
507
  "headers" => { "authorization" => "Bearer #{remote["token"]}" }, "timeoutMs" => 8000, "maxBytes" => REMOTE_MAX_BYTES,
@@ -514,7 +518,8 @@ module Runlight
514
518
  end
515
519
  next unless s.key?("id") && s["id"] == remote["site"]
516
520
 
517
- info = { "lastSeen" => s["lastSeen"], "retentionMonths" => s["retentionMonths"], "connection" => "ok" }
521
+ signals = s.key?("privacySignals") ? s["privacySignals"] == true : UNDEFINED
522
+ info = { "lastSeen" => s["lastSeen"], "retentionMonths" => s["retentionMonths"], "privacySignals" => signals, "connection" => "ok" }
518
523
  break
519
524
  end
520
525
  rescue StandardError
@@ -575,6 +580,8 @@ module Runlight
575
580
 
576
581
  @store.delete_site(id)
577
582
  @store.set_setting("retention:#{id}", nil)
583
+ @store.set_setting("signals:#{id}", nil)
584
+ @signal_lock.synchronize { @signal_cache.delete(id) }
578
585
  @store.set_setting("observe-key:#{id}", nil)
579
586
  @store.set_setting("rollup-zone:#{id}", nil)
580
587
  @store.set_setting("orphans-swept:#{id}", nil)
@@ -625,6 +632,7 @@ module Runlight
625
632
  nxt["hostnames"] = hostnames_for(patch["hostnames"], id)
626
633
  end
627
634
  check_retention(id, patch["retentionMonths"]) if given?(patch, "retentionMonths")
635
+ check_privacy_signals(id, patch["privacySignals"]) if given?(patch, "privacySignals")
628
636
  zone_changed(id, timezone) if !timezone.nil? && timezone != site(id)&.[]("timezone")
629
637
  if @managed_sites
630
638
  @store.upsert_site(nxt, now)
@@ -635,9 +643,24 @@ module Runlight
635
643
  end
636
644
  sites_changed
637
645
  set_retention(id, patch["retentionMonths"]) if given?(patch, "retentionMonths")
646
+ set_privacy_signals(id, patch["privacySignals"]) if given?(patch, "privacySignals")
638
647
  site(id)
639
648
  end
640
649
 
650
+ # Whether a site drops hits from browsers that ask not to be tracked, with Do Not Track (`DNT: 1`)
651
+ # or Global Privacy Control (`Sec-GPC: 1`). Off unless it is turned on; the tracker's data-dnt
652
+ # stands down in such a browser before it sends anything, and this catches every other hit.
653
+ def privacy_signals(site)
654
+ @store.setting("signals:#{site}") == "1"
655
+ end
656
+
657
+ def set_privacy_signals(site, on)
658
+ check_privacy_signals(site, on)
659
+ @store.set_setting("signals:#{site}", on ? "1" : nil)
660
+ @signal_lock.synchronize { @signal_cache.delete(site) }
661
+ nil
662
+ end
663
+
641
664
  # How many months of visits a site keeps, or nil to keep everything (the default).
642
665
  def retention(site)
643
666
  value = Js.number(@store.setting("retention:#{site}"))
@@ -1178,6 +1201,27 @@ module Runlight
1178
1201
  end
1179
1202
  end
1180
1203
 
1204
+ def check_privacy_signals(site, on)
1205
+ raise SettingsError.new("Unknown site", "unknown_site") if site(site).nil? || @remotes.key?(site)
1206
+ raise SettingsError.new("privacySignals is true or false", "privacy_signals_bad") unless [true, false].include?(on)
1207
+ end
1208
+
1209
+ # Whether a request carries Do Not Track or Global Privacy Control, the browser's ask not to be tracked.
1210
+ def asks_not_to_track?(request)
1211
+ Js.trim(request.headers.get("sec-gpc").to_s) == "1" || Js.trim(request.headers.get("dnt").to_s) == "1"
1212
+ end
1213
+
1214
+ # The setting as tracker hits read it, kept for half a minute so a hit asking not to be tracked costs no query.
1215
+ def honours_signals?(site)
1216
+ at = now
1217
+ cached = @signal_lock.synchronize { @signal_cache[site] }
1218
+ return cached["on"] if !cached.nil? && at - cached["at"] < 30_000
1219
+
1220
+ on = privacy_signals(site)
1221
+ @signal_lock.synchronize { @signal_cache[site] = { "at" => at, "on" => on } }
1222
+ on
1223
+ end
1224
+
1181
1225
  def hostnames_for(input, except = nil)
1182
1226
  items = input.is_a?(Array) ? input : Js.string(input.nil? ? "" : input).split(/[#{Js::SPACE},]+/)
1183
1227
  hostnames = []
@@ -1508,6 +1552,8 @@ module Runlight
1508
1552
  url = payload["url"]
1509
1553
  site = site_for(url.hostname, payload["site"]) || setup_site(url.hostname, payload["site"])
1510
1554
  return if site.nil?
1555
+ # A browser that asks not to be tracked, on a site that honours it, is dropped like a bot.
1556
+ return if asks_not_to_track?(request) && honours_signals?(site["id"])
1511
1557
 
1512
1558
  if payload["kind"] == "engagement"
1513
1559
  engagement(site, payload, at, done)
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Runlight
4
+ # Why imported daily totals were refused, as a code the dashboard says in its own words.
5
+ class ImportRowsError < RangeError
6
+ attr_reader :code, :params
7
+
8
+ def initialize(message, code, params = {})
9
+ super(message)
10
+ @code = code
11
+ @params = params
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Runlight
6
+ # Daily totals imported from another service, such as Plausible, whose exports hold totals rather than
7
+ # visits. The dashboard turns an export into Runlight's own daily totals; here they are checked and held
8
+ # as an import in review, then kept (when they become built days every report reads) or thrown away.
9
+ # A kept import can be taken back later. Only days before the site's first visit here are taken, so
10
+ # nothing is counted twice.
11
+ #
12
+ # An import row is {id, site, source, state: "review"|"kept", createdAt, keptAt}, and a day's totals
13
+ # (ImportedRollup) {day, dim, value, visitors, visits, pageviews, bounced, duration, engaged, views,
14
+ # scrollSum, scrollN, events}, with dim "" for the day's own totals.
15
+ module Imports
16
+ # Where imported totals can come from.
17
+ SOURCES = %w[plausible].freeze
18
+
19
+ # Rows one request may carry.
20
+ MAX_ROWS = 50_000
21
+
22
+ # The reports a built day keeps: its own totals (""), pages, events, and each visit dimension.
23
+ DIMS = ["", "page", "event", *Query::SESSION_DIMENSIONS.keys].to_h { |dim| [dim, true] }.freeze
24
+ DAY = /\A(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\z/
25
+ METRICS = %w[visitors visits pageviews bounced duration engaged views scrollSum scrollN events].freeze
26
+ private_constant :DIMS, :DAY, :METRICS
27
+
28
+ module_function
29
+
30
+ # An import as the API shows it, with its days and totals.
31
+ def summary(rl, row)
32
+ totals = rl.store.import_totals(row["site"], row["id"])
33
+ {
34
+ "id" => row["id"],
35
+ "source" => row["source"],
36
+ "state" => row["state"],
37
+ "createdAt" => row["createdAt"],
38
+ "keptAt" => row["keptAt"],
39
+ "from" => totals["from"],
40
+ "to" => totals["to"],
41
+ "days" => totals["days"],
42
+ "visitors" => totals["visitors"],
43
+ "visits" => totals["visits"],
44
+ "pageviews" => totals["pageviews"],
45
+ }
46
+ end
47
+
48
+ # Starts an import in review. One left in review before is thrown away, since only the newest is reviewed.
49
+ def start(rl, site, source)
50
+ unless source.is_a?(String) && SOURCES.include?(source)
51
+ named = source.nil? || source.equal?(UNDEFINED) ? "" : Js.string(source)
52
+ raise ImportRowsError.new("Runlight cannot import from #{named}", "import_source", { "source" => named })
53
+ end
54
+ rl.store.imports(site).each { |old| rl.store.delete_import(site, old["id"]) if old["state"] == "review" }
55
+ row = { "id" => Hashing.random_id, "site" => site, "source" => source, "state" => "review", "createdAt" => rl.now, "keptAt" => nil }
56
+ rl.store.create_import(row)
57
+ row
58
+ end
59
+
60
+ # A row as it was sent, checked, or nil when it cannot be taken.
61
+ def read_row(raw)
62
+ return nil unless raw.is_a?(Hash)
63
+
64
+ # A real date: the shape, and a day the month has.
65
+ day = raw["day"]
66
+ return nil unless day.is_a?(String) && (parts = DAY.match(day)) && Date.valid_date?(*parts.captures.map(&:to_i))
67
+
68
+ dim = raw["dim"]
69
+ return nil unless dim.is_a?(String) && DIMS.key?(dim)
70
+
71
+ value = raw["value"].nil? || raw["value"].equal?(UNDEFINED) ? "" : raw["value"]
72
+ return nil if !value.is_a?(String) || Js.length(value) > 1000 || (dim == "") != (value == "")
73
+
74
+ row = { "day" => day, "dim" => dim, "value" => value }
75
+ METRICS.each do |k|
76
+ v = raw[k].nil? || raw[k].equal?(UNDEFINED) ? 0 : raw[k]
77
+ # A whole number, as JSON.parse reads 1.0 or 1e3.
78
+ v = v.to_i if v.is_a?(Float) && v.finite? && v == v.floor
79
+ return nil if !v.is_a?(Integer) || v.negative? || v > 1_000_000_000_000
80
+
81
+ row[k] = v
82
+ end
83
+ row
84
+ end
85
+
86
+ # Adds rows to an import in review, every day sent whole. A day is taken only when it comes before the
87
+ # site's first visit here and before today, and no other import or built day has it; rows of other days
88
+ # are left out, and their days counted as skipped.
89
+ def add_rows(rl, site, row, raw)
90
+ raise ImportRowsError.new("This import is kept already", "import_kept") if row["state"] != "review"
91
+ raise ImportRowsError.new("Send 0 to #{MAX_ROWS} rows at a time", "import_rows_bad", { "row" => "0" }) if !raw.is_a?(Array) || raw.length > MAX_ROWS
92
+
93
+ # Two rows for one value of one day are added together, as a day's rows are one total each.
94
+ rows = {}
95
+ raw.each_with_index do |item, i|
96
+ r = read_row(item)
97
+ raise ImportRowsError.new("Row #{i} is not a day's totals", "import_rows_bad", { "row" => i.to_s }) if r.nil?
98
+
99
+ key = [r["day"], r["dim"], r["value"]]
100
+ before = rows[key]
101
+ if before
102
+ METRICS.each { |k| before[k] += r[k] }
103
+ else
104
+ rows[key] = r
105
+ end
106
+ end
107
+ timezone = rl.site(site)["timezone"]
108
+ first = rl.store.first_seen(site)
109
+ today = Dates.local_date(rl.now, timezone)
110
+ until_day = first.nil? ? today : [Dates.local_date(first, timezone), today].min
111
+ built = rl.store.built_days(site)
112
+ taken = rl.store.imported_days(site)
113
+ days = rows.values.map { |r| r["day"] }.uniq.sort
114
+ keep = days.select { |day| day < until_day && !built.key?(day) && taken.fetch(day, row["id"]) == row["id"] }
115
+ kept = keep.to_h { |day| [day, true] }
116
+ chosen = rows.values.select { |r| kept.key?(r["day"]) }
117
+ rl.store.put_import_days(
118
+ site,
119
+ row["id"],
120
+ keep.map { |day| { "day" => day, "start" => Dates.start_of(day, timezone), "end" => Dates.start_of(Dates.add_days(day, 1), timezone) } },
121
+ chosen,
122
+ )
123
+ { "addedDays" => keep.length, "skippedDays" => days.length - keep.length, "rows" => chosen.length }
124
+ end
125
+ end
126
+ end
data/lib/runlight/intl.rb CHANGED
@@ -10,7 +10,7 @@ module Runlight
10
10
  # Numbers round as ICU does, half away from zero on the number's shortest decimal form, so 2.05 to one
11
11
  # place is 2.1, though the double just under it is what is stored.
12
12
  module Intl
13
- GROUP = { "en" => ",", "de" => ".", "es" => ".", "fr" => " ", "pt" => "." }.freeze
13
+ GROUP = { "en" => ",", "de" => ".", "es" => ".", "fr" => " ", "pt" => "\u00a0" }.freeze
14
14
  DECIMAL = { "en" => ".", "de" => ",", "es" => ",", "fr" => ",", "pt" => "," }.freeze
15
15
  PERCENT = { "en" => "%s%%", "de" => "%s %%", "es" => "%s %%", "fr" => "%s %%", "pt" => "%s%%" }.freeze
16
16
 
@@ -28,13 +28,14 @@ module Runlight
28
28
  "fr" => %w[janv. févr. mars avr. mai juin juil. août sept. oct. nov. déc.],
29
29
  "pt" => %w[jan. fev. mar. abr. mai. jun. jul. ago. set. out. nov. dez.],
30
30
  }.freeze
31
- # { month: "long", year: "numeric" }, then { month: "short", day: "numeric" } without and with the year.
31
+ # { month: "long", year: "numeric" }, then { month: "short", day: "numeric" } without and with the year. {n} is the
32
+ # month as two digits, which Portugal's Portuguese writes in place of its short name.
32
33
  DATE_PATTERNS = {
33
34
  "en" => ["{M} {y}", "{m} {d}", "{m} {d}, {y}"],
34
35
  "de" => ["{M} {y}", "{d}. {m}", "{d}. {m} {y}"],
35
36
  "es" => ["{M} de {y}", "{d} {m}", "{d} {m} {y}"],
36
37
  "fr" => ["{M} {y}", "{d} {m}", "{d} {m} {y}"],
37
- "pt" => ["{M} de {y}", "{d} de {m}", "{d} de {m} de {y}"],
38
+ "pt" => ["{M} de {y}", "{d}/{n}", "{d}/{n}/{y}"],
38
39
  }.freeze
39
40
  private_constant :GROUP, :DECIMAL, :PERCENT, :MONTHS, :SHORT_MONTHS, :DATE_PATTERNS
40
41
 
@@ -51,8 +52,8 @@ module Runlight
51
52
  return "#{n.negative? ? "-" : ""}∞" if n.is_a?(Float) && n.infinite?
52
53
 
53
54
  negative, whole, fraction = rounded(n, min_fraction, max_fraction)
54
- # Spanish groups only from five digits on (CLDR's minimum grouping digits of 2).
55
- whole = whole.gsub(/\B(?=(\d{3})+\z)/, GROUP[lang]) unless lang == "es" && whole.length < 5
55
+ # Spanish and Portugal's Portuguese group only from five digits on (CLDR's minimum grouping digits of 2).
56
+ whole = whole.gsub(/\B(?=(\d{3})+\z)/, GROUP[lang]) unless %w[es pt].include?(lang) && whole.length < 5
56
57
  "#{negative ? "-" : ""}#{whole}#{fraction.empty? ? "" : DECIMAL[lang] + fraction}"
57
58
  end
58
59
 
@@ -93,8 +94,8 @@ module Runlight
93
94
  def date(lang, date, pattern)
94
95
  lang = lang(lang)
95
96
  y, m, d = date.split("-").map(&:to_i)
96
- values = { "{M}" => MONTHS[lang][m - 1], "{m}" => SHORT_MONTHS[lang][m - 1], "{d}" => d.to_s, "{y}" => y.to_s }
97
- DATE_PATTERNS[lang][pattern].gsub(/\{[Mmdy]\}/, values)
97
+ values = { "{M}" => MONTHS[lang][m - 1], "{m}" => SHORT_MONTHS[lang][m - 1], "{n}" => format("%02d", m), "{d}" => d.to_s, "{y}" => y.to_s }
98
+ DATE_PATTERNS[lang][pattern].gsub(/\{[Mmndy]\}/, values)
98
99
  end
99
100
 
100
101
  # new Intl.DisplayNames(lang, { type: "region" }).of(code), or the code where that throws. Only an upper case
@@ -65,8 +65,8 @@ module Runlight
65
65
  # digits i and visible decimals v are read from that. Any other language answers "other".
66
66
  #
67
67
  # - en, de: one when i = 1 and v = 0
68
- # - es: one when n = 1; many when i is a non-zero multiple of a million and v = 0
69
- # - fr, pt: one when i is 0 or 1; many as in es
68
+ # - es, pt (Portugal's): one when n = 1; many when i is a non-zero multiple of a million and v = 0
69
+ # - fr: one when i is 0 or 1; many as in es
70
70
  def plural(lang, n)
71
71
  return "other" if n.is_a?(Float) && (n.nan? || n.infinite?)
72
72
 
@@ -76,11 +76,11 @@ module Runlight
76
76
  case lang
77
77
  when "en", "de"
78
78
  i == "1" && v.zero? ? "one" : "other"
79
- when "es"
79
+ when "es", "pt"
80
80
  return "one" if i == "1" && v.zero?
81
81
 
82
82
  million && v.zero? ? "many" : "other"
83
- when "fr", "pt"
83
+ when "fr"
84
84
  return "one" if %w[0 1].include?(i)
85
85
 
86
86
  million && v.zero? ? "many" : "other"
@@ -80,7 +80,7 @@ module Runlight
80
80
 
81
81
  monthly = frequency == "monthly"
82
82
  when_text = monthly ? t.call("email.when.month", { "month" => month_name.call(period["fromDate"]) }) : t.call("email.when.week")
83
- against = monthly ? month_name.call(period["previousFrom"]) : t.call("email.before.week")
83
+ against = monthly ? t.call("email.before.month", { "month" => month_name.call(period["previousFrom"]) }) : t.call("email.before.week")
84
84
  who = tn.call("headline.who", now["visitors"], { "n" => number.call(now["visitors"]) })
85
85
  verb = tn.call("headline.visited", now["visitors"])
86
86
  change = Js.truthy?(prev["visitors"]) ? (now["visitors"] - prev["visitors"]).fdiv(prev["visitors"]) : nil
@@ -1819,6 +1819,58 @@ module Runlight
1819
1819
  end
1820
1820
  end
1821
1821
 
1822
+ # Daily totals from another service: started, sent a few days at a time, reviewed, then kept or thrown
1823
+ # away. A kept import can be taken back. The store must keep daily totals.
1824
+ if (import_match = path.match(%r{\A/api/imports(?:/([a-f0-9]{24})(?:/(rows|keep))?)?\z}))
1825
+ id, action = import_match.captures
1826
+ allowed = if id.nil? then %w[GET POST]
1827
+ elsif action.nil? then %w[GET DELETE]
1828
+ else %w[POST]
1829
+ end
1830
+ return coded("Method not allowed", "method_not_allowed", 405) unless allowed.include?(method)
1831
+
1832
+ access = can_read(request)
1833
+ return denied(access) if access != true
1834
+
1835
+ rl.init
1836
+ site = query_site(url)
1837
+ return site if site.is_a?(Http::Response)
1838
+ return coded("This store keeps no daily totals to import into", "imports_unsupported", 400) unless store.respond_to?(:keeps_rollups?) && store.keeps_rollups?
1839
+
1840
+ begin
1841
+ if id.nil?
1842
+ return json({ "imports" => store.imports(site["id"]).map { |row| Imports.summary(rl, row) } }) if method == "GET"
1843
+
1844
+ body = read_json(request)
1845
+ return body if body.is_a?(Http::Response)
1846
+
1847
+ return json({ "import" => Imports.summary(rl, Imports.start(rl, site["id"], Js.get(body, "source"))) }, 201)
1848
+ end
1849
+ row = store.import_by_id(site["id"], id)
1850
+ return coded("Unknown import", "unknown_import", 404) if row.nil?
1851
+
1852
+ if action == "rows"
1853
+ body = read_json(request)
1854
+ return body if body.is_a?(Http::Response)
1855
+
1856
+ return json(Imports.add_rows(rl, site["id"], row, Js.get(body, "rows")))
1857
+ end
1858
+ if action == "keep"
1859
+ store.keep_import(site["id"], row["id"], rl.now) if row["state"] == "review"
1860
+ return json({ "import" => Imports.summary(rl, store.import_by_id(site["id"], id)) })
1861
+ end
1862
+ if method == "DELETE"
1863
+ store.delete_import(site["id"], row["id"])
1864
+ return json({ "ok" => true })
1865
+ end
1866
+ totals = store.import_totals(site["id"], row["id"])
1867
+ view = { "id" => row["id"], "source" => row["source"], "state" => row["state"], "createdAt" => row["createdAt"], "keptAt" => row["keptAt"] }
1868
+ return json({ "import" => view.merge(totals.except("months")), "months" => totals["months"] })
1869
+ rescue ImportRowsError => e
1870
+ return coded(e.message, e.code, e.code == "import_kept" ? 409 : 400, e.params)
1871
+ end
1872
+ end
1873
+
1822
1874
  # Each site's agents key, for CMS plugins reporting AI agent fetches: made on first ask, replaced on request.
1823
1875
  if (path == "/api/observe-key" && method == "GET") || (path == "/api/observe-key/new" && method == "POST")
1824
1876
  access = can_read(request)
@@ -2254,6 +2306,10 @@ module Runlight
2254
2306
  months = RETENTION_MONTHS.join(", ")
2255
2307
  return coded("Keep visits for #{months} months, or forever", "retention_bad", 400, { "months" => months })
2256
2308
  end
2309
+ signals = Js.get(body, "privacySignals")
2310
+ unless signals.equal?(UNDEFINED) || signals == true || signals == false
2311
+ return coded("privacySignals is true or false", "privacy_signals_bad", 400)
2312
+ end
2257
2313
  id = decode_part(raw_id)
2258
2314
  return coded("Unknown site", "unknown_site", 404) if id.nil?
2259
2315
 
@@ -2263,6 +2319,7 @@ module Runlight
2263
2319
  # settings: this server passes them on, and changes its own row only once the install took them.
2264
2320
  forward = {}
2265
2321
  forward["retentionMonths"] = retention unless retention.equal?(UNDEFINED)
2322
+ forward["privacySignals"] = signals unless signals.equal?(UNDEFINED)
2266
2323
  if given?(body, "timezone") && Js.string(Js.get(body, "timezone")) != rl.site(id)&.[]("timezone")
2267
2324
  forward["timezone"] = Js.string(Js.get(body, "timezone"))
2268
2325
  end
@@ -2282,6 +2339,7 @@ module Runlight
2282
2339
  # update_site checks every field, hostnames too, before it changes anything.
2283
2340
  patch = {}
2284
2341
  patch["retentionMonths"] = retention.nil? ? nil : Js.number(retention) if remote.nil? && !retention.equal?(UNDEFINED)
2342
+ patch["privacySignals"] = signals == true if remote.nil? && !signals.equal?(UNDEFINED)
2285
2343
  patch["name"] = Js.string(Js.get(body, "name")) if given?(body, "name")
2286
2344
  patch["timezone"] = Js.string(Js.get(body, "timezone")) if given?(body, "timezone")
2287
2345
  patch["hostnames"] = plain(Js.get(body, "hostnames")) if given?(body, "hostnames") && rl.managed_sites
@@ -2354,6 +2412,8 @@ module Runlight
2354
2412
  row["lastSeen"] = remote.nil? ? store.last_seen(site["id"]) : rl.remote_last_seen(site["id"])
2355
2413
  # Left out for a connected install that cannot be reached, so nobody reads "forever" by mistake.
2356
2414
  row["retentionMonths"] = remote.nil? ? rl.retention(site["id"]) : field(rl.remote_info(site["id"]), "retentionMonths") if shared.nil?
2415
+ # Whether hits asking not to be tracked are dropped; left out like retention when a connected install does not say.
2416
+ row["privacySignals"] = remote.nil? ? rl.privacy_signals(site["id"]) : field(rl.remote_info(site["id"]), "privacySignals") if shared.nil?
2357
2417
  # Whether a connected install still takes this server's token, so the dashboard offers to connect it
2358
2418
  # again only when it no longer does.
2359
2419
  row["connection"] = field(rl.remote_info(site["id"]), "connection") if !remote.nil? && shared.nil?
@@ -40,7 +40,7 @@ module Runlight
40
40
  # Runlight's tables drops these by name, never every table that starts with the prefix.
41
41
  TABLES = %w[
42
42
  meta sites salts sessions events links link_domains shares goals settings
43
- reports tokens funnels rollup_days rollups users invites
43
+ reports tokens funnels rollup_days rollups imports import_days users invites
44
44
  ].freeze
45
45
 
46
46
  PIECE_MS = 86_400_000
@@ -55,7 +55,7 @@ module Runlight
55
55
  # Engaged time, or for imported visits with none, first to last request.
56
56
  DURATION = "COALESCE(s.engaged_ms, s.last_at - s.started_at)"
57
57
 
58
- SCHEMA_VERSION = 11
58
+ SCHEMA_VERSION = 12
59
59
 
60
60
  # MySQL's text collation: UTF-8 compared and sorted by code point, case and trailing spaces included,
61
61
  # as SQLite and Postgres's "C" collation do. MariaDB has it too, from 11.4.
@@ -208,6 +208,16 @@ module Runlight
208
208
  engaged BIGINT NOT NULL DEFAULT 0, views BIGINT NOT NULL DEFAULT 0, scroll_sum BIGINT NOT NULL DEFAULT 0, scroll_n BIGINT NOT NULL DEFAULT 0,
209
209
  events BIGINT NOT NULL DEFAULT 0,
210
210
  #{my ? "KEY rl_rollups_day (site, dim, day)" : "PRIMARY KEY (site, dim, day, value)"})#{table}",
211
+ # Version 12: daily totals imported from another service. An import stays in review until it is kept,
212
+ # its rows waiting in rl_rollups with no built mark; a day belongs to one import at most.
213
+ "CREATE TABLE IF NOT EXISTS rl_imports (
214
+ id #{key} PRIMARY KEY, site #{site} NOT NULL, source #{str.(32)} NOT NULL, state #{str.(16)} NOT NULL,
215
+ created_at BIGINT NOT NULL, kept_at BIGINT)#{table}",
216
+ "CREATE INDEX IF NOT EXISTS rl_imports_site ON rl_imports (site, created_at)",
217
+ "CREATE TABLE IF NOT EXISTS rl_import_days (
218
+ site #{site} NOT NULL, day #{str.(32)} NOT NULL, import_id #{key} NOT NULL, start_at BIGINT NOT NULL, end_at BIGINT NOT NULL,
219
+ PRIMARY KEY (site, day))#{table}",
220
+ "CREATE INDEX IF NOT EXISTS rl_import_days_import ON rl_import_days (import_id)",
211
221
  ]
212
222
  end
213
223