summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/test/RemoteImagesTestUtils.jsm
blob: bc8594549dfec1f9636fa2a97588813cac870bfd (plain)
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");
const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const { RemoteImages, REMOTE_IMAGES_PATH } = ChromeUtils.import(
  "resource://activity-stream/lib/RemoteImages.jsm"
);

// This pref is used to override the Remote Settings server URL in tests.
// See SERVER_URL in services/settings/Utils.jsm for more details.
const RS_SERVER_PREF = "services.settings.server";

class RemoteSettingsRecord {
  constructor(id) {
    this.data = {
      id,
      last_modified: Date.now(),
    };
  }

  set(attrs) {
    const { id } = this.data;
    Object.assign(this.data, attrs, {
      id,
      last_modified: Date.now(),
    });
  }

  toJSON() {
    return { data: this.data };
  }
}

class RemoteSettingsCollection {
  get ChildType() {
    return RemoteSettingsRecord;
  }

  constructor(id) {
    this.data = {
      id,
      last_modified: Date.now(),
    };

    this.children = new Map();
  }

  get(id) {
    return this.children.get(id);
  }

  getOrCreate(id, { update = false } = {}) {
    return (update ? this.update(id) : this.get(id)) ?? this.create(id);
  }

  create(id) {
    if (this.get(id)) {
      throw new Error(`already have child ${id}`);
    }

    let child = new this.ChildType(id);
    this.children.set(id, child);
    this.data.last_modified = Date.now();
    return child;
  }

  update(id) {
    let child = this.get(id);
    if (child) {
      this.data.last_modified = Date.now();
    }
    return child;
  }

  toJSON() {
    return {
      data: Array.from(this.children.values()).map(child => ({
        id: child.data.id,
        last_modified: child.data.last_modified,
      })),
    };
  }
}

class RemoteSettingsBucket extends RemoteSettingsCollection {
  get ChildType() {
    return RemoteSettingsCollection;
  }
}

class RemoteSettingsRoot extends RemoteSettingsCollection {
  get ChildType() {
    return RemoteSettingsBucket;
  }
  constructor() {
    super("root");
  }
}

class RemoteSettingsAttachment {
  constructor(attrs) {
    Object.assign(this, attrs);
  }

  writeTo(response) {
    const stream = NetUtil.newChannel({
      uri: NetUtil.newURI(this.url),
      loadUsingSystemPrincipal: true,
    }).open();

    try {
      response.setHeader("Content-Type", this.mimetype);
      response.bodyOutputStream.writeFrom(stream, this.size);
      response.setStatusLine(null, 200, "OK");
    } finally {
      stream.close();
    }
  }
}

class RemoteSettingsServer {
  constructor() {
    this.server = new HttpServer();
    this.buckets = new RemoteSettingsRoot();
    this.attachments = new Map();

    this._originalServerlURL = null;

    this.server.registerPathHandler("/v1/", (request, response) => {
      response.setHeader("Content-Type", "application/json; charset=UTF-8");
      response.setStatusLine(null, 200, "OK");
      response.write(
        JSON.stringify({
          capabilities: {
            attachments: {
              base_url: `${this.baseURL}attachments`,
            },
          },
        })
      );
    });

    const recordRegex = new RegExp(
      "/v1/buckets/(?<bucketId>[^/]+)/collections/(?<collectionId>[^/]+)/records/(?<recordId>[^/]+)"
    );
    this.server.registerPrefixHandler("/v1/buckets/", (request, response) => {
      const match = recordRegex.exec(request.path);
      if (!match) {
        response.setStatusLine(null, 404, "Not Found");
        response.write("404");
        return;
      }

      const record = this.buckets
        .get(match.groups.bucketId)
        ?.get(match.groups.collectionId)
        ?.get(match.groups.recordId);
      if (!record) {
        response.setStatusLine(null, 404, "Not Found");
        response.write("404");
        return;
      }

      response.setHeader("Content-Type", "application/json; charset=UTF-8");
      response.setStatusLine(null, 200, "OK");
      response.write(JSON.stringify(record));
    });

    const ATTACHMENTS_PREFIX = "/attachments/";
    this.server.registerPrefixHandler(
      ATTACHMENTS_PREFIX,
      (request, response) => {
        const attachmentId = request.path.substring(ATTACHMENTS_PREFIX.length);
        const attachment = this.attachments.get(attachmentId);

        if (!attachment) {
          response.setStatusLine(null, 400, "Not Found");
          response.write("404");
          return;
        }

        attachment.writeTo(response);
      }
    );
  }

  start() {
    this.server.start(-1);

    this._originalServerlURL = Services.prefs.getCharPref(RS_SERVER_PREF);
    Services.prefs.setCharPref(RS_SERVER_PREF, `${this.baseURL}v1`);
  }

  async stop() {
    await new Promise(resolve => this.server.stop(resolve));

    // If we use clearUserPref, then we will reset to the default branch value
    // (i.e., the *real* RS server) which will cause test failures due to trying
    // to access an outside URL.
    Services.prefs.setCharPref(RS_SERVER_PREF, this._originalServerlURL);
    this._originalServerlURL = null;
  }

  get baseURL() {
    return `http://localhost:${this.server.identity.primaryPort}/`;
  }

  addRemoteImage(imageInfo) {
    const { filename, recordId, mimetype, hash, url, size } = imageInfo;

    const location = `main/ms-images/${recordId}`;

    this.buckets
      .getOrCreate("main", { update: true })
      .getOrCreate("ms-images", { update: true })
      .create(recordId)
      .set({
        attachment: {
          filename,
          location,
          hash,
          mimetype,
          size,
        },
      });

    this.attachments.set(
      location,
      new RemoteSettingsAttachment({
        mimetype,
        size,
        url,
      })
    );
  }
}

const RemoteImagesTestUtils = {
  /**
   * Serve a mock Remote Settings server with content for Remote Images
   *
   * @param imageInfo An entry describing the image. Should be one of
   *        |RemoteImagesTestUtils.images|.
   *
   * @returns A promise yielding a cleanup function. This function will stop the
   *          internal HTTP server and clean up all Remote Images state.
   */
  serveRemoteImages(...imageInfos) {
    const server = new RemoteSettingsServer();

    for (const imageInfo of imageInfos) {
      server.addRemoteImage(imageInfo);
    }

    server.start();

    return async () => {
      await server.stop();
      await RemoteImagesTestUtils.wipeCache();
    };
  },

  /**
   * Wipe the Remote Images cache.
   */
  async wipeCache() {
    await RemoteImages.reset();

    const children = await IOUtils.getChildren(REMOTE_IMAGES_PATH);
    for (const child of children) {
      await IOUtils.remove(child);
    }
  },

  /**
   * Trigger RemoteImages cleanup.
   */
  triggerCleanup() {
    return RemoteImages.forceCleanup();
  },

  /**
   * Write an image into the remote images directory.
   *
   * @param imageInfo An entry describing the image. Should be one of
   *                 |RemoteImagesTestUtils.images|.
   *
   * @param filename An optional filename to save as inside the directory. If
   *                 not provided, |imageInfo.recordId| will be used.
   */
  async writeImage(imageInfo, filename = undefined) {
    const data = new Uint8Array(
      await fetch(imageInfo.url, { credentials: "omit" }).then(rsp =>
        rsp.arrayBuffer()
      )
    );

    await IOUtils.write(
      PathUtils.join(REMOTE_IMAGES_PATH, filename ?? imageInfo.recordId),
      data
    );
  },

  /**
   * Return a RemoteImages database entry for the given image info.
   *
   * @param imageInfo An entry describing the image. Should be one of
   *                 |RemoteImagesTestUtils.images|.
   *
   * @param lastLoaded The timestamp to use for when the image was last loaded
   *                   (in UTC). If not provided, the current time is used.
   */
  dbEntryFor(imageInfo, lastLoaded = undefined) {
    return {
      [imageInfo.recordId]: {
        recordId: imageInfo.recordId,
        hash: imageInfo.hash,
        mimetype: imageInfo.mimetype,
        lastLoaded: lastLoaded ?? Date.now(),
      },
    };
  },

  /**
   * Remote Image entries.
   */
  images: {
    AboutRobots: {
      filename: "about-robots.png",
      recordId: "about-robots",
      mimetype: "image/png",
      hash: "29f1fe2cb5181152d2c01c0b2f12e5d9bb3379a61b94fb96de0f734eb360da62",
      url: "chrome://browser/content/aboutRobots-icon.png",
      size: 7599,
    },

    Mountain: {
      filename: "mountain.svg",
      recordId: "mountain",
      mimetype: "image/svg+xml",
      hash: "96902f3d784e1b5e49547c543a5c121442c64b180deb2c38246fada1d14597ac",
      url:
        "chrome://activity-stream/content/data/content/assets/remote/mountain.svg",
      size: 1650,
    },
  },
};

const EXPORTED_SYMBOLS = ["RemoteImagesTestUtils", "RemoteSettingsServer"];