This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 441
/
NTPDataSource.swift
230 lines (192 loc) · 8.64 KB
/
NTPDataSource.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import Shared
import Preferences
import BraveCore
import os.log
enum NTPWallpaper {
case image(NTPBackgroundImage)
case sponsoredImage(NTPSponsoredImageBackground)
case superReferral(NTPSponsoredImageBackground, code: String)
var backgroundImage: UIImage? {
let imagePath: URL
switch self {
case .image(let background):
imagePath = background.imagePath
case .sponsoredImage(let background):
imagePath = background.imagePath
case .superReferral(let background, _):
imagePath = background.imagePath
}
return UIImage(contentsOfFile: imagePath.path)
}
var logoImage: UIImage? {
let imagePath: URL?
switch self {
case .image:
imagePath = nil
case .sponsoredImage(let background):
imagePath = background.logo.imagePath
case .superReferral(let background, _):
imagePath = background.logo.imagePath
}
return imagePath.flatMap { UIImage(contentsOfFile: $0.path) }
}
var focalPoint: CGPoint? {
switch self {
case .image:
return nil // Will eventually return a real value
case .sponsoredImage(let background):
return background.focalPoint
case .superReferral(let background, _):
return background.focalPoint
}
}
}
public class NTPDataSource {
private(set) var privateBrowsingManager: PrivateBrowsingManager
var initializeFavorites: ((_ sites: [NTPSponsoredImageTopSite]?) -> Void)?
/// Custom homepage spec requirement:
/// If we fail to fetch super referrer, and it succeeds at later time,
/// default favorites are going to be replaced with the ones from the super referrer.
/// This happens only if the user has not changed default favorites.
var replaceFavoritesIfNeeded: ((_ sites: [NTPSponsoredImageTopSite]?) -> Void)?
// Data is static to avoid duplicate loads
/// This is the number of backgrounds that must appear before a background can be repeated.
/// So if background `3` is shown, it cannot be shown until this many backgrounds are shown, then `3` can be shown again.
/// This does not apply to sponsored images.
/// This is reset on each launch, so `3` can be shown again if app is removed from memory.
/// This number _must_ be less than the number of backgrounds!
private static let numberOfDuplicateAvoidance = 6
let service: NTPBackgroundImagesService
public init(service: NTPBackgroundImagesService, privateBrowsingManager: PrivateBrowsingManager) {
self.service = service
self.privateBrowsingManager = privateBrowsingManager
Preferences.NewTabPage.selectedCustomTheme.observe(from: self)
self.service.sponsoredImageDataUpdated = { [weak self] _ in
self?.sponsorComponentUpdated()
}
}
deinit {
self.service.sponsoredImageDataUpdated = nil
}
// This is used to prevent the same handful of backgrounds from being shown.
// It will track the last N pictures that have been shown and prevent them from being shown
// until they are 'old' and dropped from this array.
// Currently only supports normal backgrounds, as sponsored images are not supposed to be duplicate.
// This can 'easily' be adjusted to support both sets by switching to String, and using filePath to identify uniqueness.
private var lastBackgroundChoices = [Int]()
private enum ImageRotationStrategy {
/// Special strategy for sponsored images, uses in-memory property to keep track of which image to show.
case sponsoredRotation
/// Uses random images, keeps in-memory list of recently viewed images to avoid showing it too often.
case randomOrderAvoidDuplicates
}
func newBackground() -> NTPWallpaper? {
if !Preferences.NewTabPage.backgroundImages.value { return nil }
// Identifying the background array to use
let (backgroundSet, strategy) = {
() -> ([NTPWallpaper], ImageRotationStrategy) in
if let theme = service.superReferralImageData,
case let refCode = service.superReferralCode,
!refCode.isEmpty,
Preferences.NewTabPage.selectedCustomTheme.value != nil {
return (theme.campaigns.flatMap(\.backgrounds).map { NTPWallpaper.superReferral($0, code: refCode) }, .randomOrderAvoidDuplicates)
}
if let sponsor = service.sponsoredImageData {
let attemptSponsored =
Preferences.NewTabPage.backgroundSponsoredImages.value
&& Preferences.NewTabPage.backgroundRotationCounter.value == service.initialCountToBrandedWallpaper
&& !privateBrowsingManager.isPrivateBrowsing
if attemptSponsored {
// Pick the campaign randomly
let campaignIndex: Int = Int.random(in: 0..<sponsor.campaigns.count)
if let campaign = sponsor.campaigns[safe: campaignIndex] {
return (campaign.backgrounds.map(NTPWallpaper.sponsoredImage), .sponsoredRotation)
}
}
}
if service.backgroundImages.isEmpty {
return ([NTPWallpaper.image(.fallback)], .randomOrderAvoidDuplicates)
}
return (service.backgroundImages.map(NTPWallpaper.image), .randomOrderAvoidDuplicates)
}()
if backgroundSet.isEmpty { return nil }
// Choosing the actual index / item to use
let backgroundIndex = { () -> Int in
switch strategy {
case .sponsoredRotation:
return Int.random(in: 0..<backgroundSet.count)
case .randomOrderAvoidDuplicates:
let availableRange = 0..<backgroundSet.count
// This takes all indeces and filters out ones that were shown recently
let availableBackgroundIndeces = availableRange.filter {
!self.lastBackgroundChoices.contains($0)
}
// Due to how many display modes currently exist, the background avoidance counter may get utilized on a smaller subset.
// This can be repro by swapping between normal backgrounds and a super referrer, where all available indeces get squeezed out, resulting in an empty set.
// To avoid issues, first fallback results in full set.
// Chooses a new random index to use from the available indeces
let chosenIndex = availableBackgroundIndeces.randomElement() ?? availableRange.randomElement() ?? -1
assert(chosenIndex >= 0, "NTP index was nil, this is terrible.")
assert(chosenIndex < backgroundSet.count, "NTP index is too large, BAD!")
// This index is now added to 'past' tracking list to prevent duplicates
self.lastBackgroundChoices.append(chosenIndex)
// Trimming to fixed length to release older backgrounds
self.lastBackgroundChoices = self.lastBackgroundChoices
.suffix(min(backgroundSet.count - 1, NTPDataSource.numberOfDuplicateAvoidance))
return chosenIndex
}
}()
// Force back to `0` if at end
Preferences.NewTabPage.backgroundRotationCounter.value %= service.countToBrandedWallpaper
// Increment regardless, this is a counter, not an index, so smallest should be `1`
Preferences.NewTabPage.backgroundRotationCounter.value += 1
guard let bgWithIndex = backgroundSet[safe: backgroundIndex] else { return nil }
return bgWithIndex
}
func sponsorComponentUpdated() {
if let superReferralImageData = service.superReferralImageData, superReferralImageData.isSuperReferral {
if Preferences.NewTabPage.preloadedFavoritiesInitialized.value {
replaceFavoritesIfNeeded?(superReferralImageData.topSites)
} else {
initializeFavorites?(superReferralImageData.topSites)
}
} else {
// Force to set up basic favorites if it hasn't been done already.
initializeFavorites?(nil)
}
}
}
extension NTPDataSource: PreferencesObserver {
public func preferencesDidChange(for key: String) {
let customThemePref = Preferences.NewTabPage.selectedCustomTheme
let installedThemesPref = Preferences.NewTabPage.installedCustomThemes
switch key {
case customThemePref.key:
let installedThemes = installedThemesPref.value
if let theme = customThemePref.value, !installedThemes.contains(theme) {
installedThemesPref.value = installedThemesPref.value + [theme]
}
default:
break
}
}
}
extension NTPSponsoredImageTopSite {
var asFavoriteSite: FavoriteSite? {
guard let url = destinationURL else {
return nil
}
return FavoriteSite(url, name)
}
}
extension NTPBackgroundImage {
static let fallback: NTPBackgroundImage = .init(
imagePath: Bundle.module.url(forResource: "corwin-prescott-3", withExtension: "jpg")!,
author: "Corwin Prescott",
link: URL(string: "https://www.brave.com")!
)
}