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
|
/* 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 https://mozilla.org/MPL/2.0/. */
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
Utils: "resource://services-settings/Utils.sys.mjs",
});
import {
actionTypes as at,
actionCreators as ac,
} from "resource://activity-stream/common/Actions.mjs";
const PREF_WALLPAPERS_ENABLED =
"browser.newtabpage.activity-stream.newtabWallpapers.enabled";
export class WallpaperFeed {
constructor() {
this.loaded = false;
this.wallpaperClient = "";
this.wallpaperDB = "";
this.baseAttachmentURL = "";
}
/**
* This thin wrapper around global.fetch makes it easier for us to write
* automated tests that simulate responses from this fetch.
*/
fetch(...args) {
return fetch(...args);
}
/**
* This thin wrapper around lazy.RemoteSettings makes it easier for us to write
* automated tests that simulate responses from this fetch.
*/
RemoteSettings(...args) {
return lazy.RemoteSettings(...args);
}
async wallpaperSetup(isStartup = false) {
const wallpapersEnabled = Services.prefs.getBoolPref(
PREF_WALLPAPERS_ENABLED
);
if (wallpapersEnabled) {
if (!this.wallpaperClient) {
this.wallpaperClient = this.RemoteSettings("newtab-wallpapers");
}
await this.getBaseAttachment();
this.wallpaperClient.on("sync", () => this.updateWallpapers());
this.updateWallpapers(isStartup);
}
}
async getBaseAttachment() {
if (!this.baseAttachmentURL) {
const SERVER = lazy.Utils.SERVER_URL;
const serverInfo = await (
await this.fetch(`${SERVER}/`, {
credentials: "omit",
})
).json();
const { base_url } = serverInfo.capabilities.attachments;
this.baseAttachmentURL = base_url;
}
}
async updateWallpapers(isStartup = false) {
const records = await this.wallpaperClient.get();
if (!records?.length) {
return;
}
if (!this.baseAttachmentURL) {
await this.getBaseAttachment();
}
const wallpapers = records.map(record => {
return {
...record,
wallpaperUrl: `${this.baseAttachmentURL}${record.attachment.location}`,
};
});
this.store.dispatch(
ac.BroadcastToContent({
type: at.WALLPAPERS_SET,
data: wallpapers,
meta: {
isStartup,
},
})
);
}
async onAction(action) {
switch (action.type) {
case at.INIT:
await this.wallpaperSetup(true /* isStartup */);
break;
case at.UNINIT:
break;
case at.SYSTEM_TICK:
break;
case at.PREF_CHANGED:
if (action.data.name === "newtabWallpapers.enabled") {
await this.wallpaperSetup(false /* isStartup */);
}
break;
case at.WALLPAPERS_SET:
break;
}
}
}
|