Index: lib/subscriptionInit.js |
diff --git a/lib/subscriptionInit.js b/lib/subscriptionInit.js |
index 9cd17b48988b41eb21d071d7efcd7506557f0375..c14c4b3c971763c8c2ccd78d20576fd9091d5f14 100644 |
--- a/lib/subscriptionInit.js |
+++ b/lib/subscriptionInit.js |
@@ -81,6 +81,57 @@ function shouldAddDefaultSubscription() |
} |
/** |
+ * Finds the element for the default ad blocking filter subscription based |
+ * on the user's locale. |
+ * |
+ * @param {HTMLCollection} subscriptions |
+ * @return {Element} |
+ */ |
+function chooseFilterSubscription(subscriptions) |
+{ |
+ let selectedItem = null; |
+ let selectedPrefix = null; |
+ let matchCount = 0; |
+ for (let subscription of subscriptions) |
+ { |
+ if (!selectedItem) |
+ selectedItem = subscription; |
+ |
+ let prefixes = subscription.getAttribute("prefixes"); |
+ let prefix = prefixes && prefixes.split(",").find( |
+ lang => new RegExp("^" + lang + "\\b").test(Utils.appLocale) |
+ ); |
+ |
+ let subscriptionType = subscription.getAttribute("type"); |
+ |
+ if (prefix && subscriptionType == "ads") |
+ { |
+ if (!selectedPrefix || selectedPrefix.length < prefix.length) |
+ { |
+ selectedItem = subscription; |
+ selectedPrefix = prefix; |
+ matchCount = 1; |
+ } |
+ else if (selectedPrefix && selectedPrefix.length == prefix.length) |
+ { |
+ matchCount++; |
+ |
+ // If multiple items have a matching prefix of the same length: |
+ // Select one of the items randomly, probability should be the same |
+ // for all items. So we replace the previous match here with |
+ // probability 1/N (N being the number of matches). |
+ if (Math.random() * matchCount < 1) |
+ { |
+ selectedItem = subscription; |
+ selectedPrefix = prefix; |
+ } |
+ } |
+ } |
+ } |
+ return selectedItem; |
+} |
+ |
+/** |
* Gets the filter subscriptions to be added when the extnesion is loaded. |
* |
* @return {Promise|Subscription[]} |
@@ -119,7 +170,7 @@ function getSubscriptions() |
let doc = new DOMParser().parseFromString(text, "application/xml"); |
let nodes = doc.getElementsByTagName("subscription"); |
- let node = Utils.chooseFilterSubscription(nodes); |
+ let node = chooseFilterSubscription(nodes); |
if (node) |
{ |
let url = node.getAttribute("url"); |