summaryrefslogtreecommitdiffstats
path: root/browser/components/pocket/content/pktApi.sys.mjs
blob: b63e0f8f654a41e7bf738dddb2662dc45fca2f17 (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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
/*
 * LICENSE
 *
 * POCKET MARKS
 *
 * Notwithstanding the permitted uses of the Software (as defined below) pursuant to the license set forth below, "Pocket," "Read It Later" and the Pocket icon and logos (collectively, the “Pocket Marks”) are registered and common law trademarks of Read It Later, Inc. This means that, while you have considerable freedom to redistribute and modify the Software, there are tight restrictions on your ability to use the Pocket Marks. This license does not grant you any rights to use the Pocket Marks except as they are embodied in the Software.
 *
 * ---
 *
 * SOFTWARE
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Pocket API module
 *
 * Public API Documentation: http://getpocket.com/developer/
 *
 *
 * Definition of keys stored in preferences to preserve user state:
 *      premium_status:   Current premium status for logged in user if available
 *                        Can be 0 for no premium and 1 for premium
 *      latestSince:      Last timestamp a save happened
 *      tags:             All tags for logged in user
 *      usedTags:         All used tags from within the extension sorted by recency
 */

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  IndexedDB: "resource://gre/modules/IndexedDB.sys.mjs",
  NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
});

XPCOMUtils.defineLazyPreferenceGetter(
  lazy,
  "gCookieFirstPartyIsolate",
  "privacy.firstparty.isolate",
  false
);

const DB_NAME = "SaveToPocket";
const STORE_NAME = "pktAPI";
const DB_VERSION = 1;
const RECENT_SAVES_UPDATE_TIME = 5 * 60 * 1000; // 30 minutes

/**
 * Create a new connection to the database.
 */
function openDatabase() {
  return lazy.IndexedDB.open(DB_NAME, DB_VERSION, db => {
    db.createObjectStore(STORE_NAME);
  });
}

/**
 * Cache the database connection so that it is shared among multiple operations.
 */
let databasePromise;
function getDatabase() {
  if (!databasePromise) {
    databasePromise = openDatabase();
  }
  return databasePromise;
}

export var pktApi = (function () {
  /**
   * Configuration
   */

  // Base url for all api calls
  var pocketSiteHost = Services.prefs.getCharPref("extensions.pocket.site"); // getpocket.com

  /**
   *
   */
  var prefBranch = Services.prefs.getBranch("extensions.pocket.settings.");

  /**
   * Helper
   */

  var extend = function (out) {
    out = out || {};

    for (var i = 1; i < arguments.length; i++) {
      if (!arguments[i]) {
        continue;
      }

      for (var key in arguments[i]) {
        if (arguments[i].hasOwnProperty(key)) {
          out[key] = arguments[i][key];
        }
      }
    }
    return out;
  };

  var parseJSON = function (jsonString) {
    try {
      var o = JSON.parse(jsonString);

      // Handle non-exception-throwing cases:
      // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
      // but... JSON.parse(null) returns 'null', and typeof null === "object",
      // so we must check for that, too.
      if (o && typeof o === "object" && o !== null) {
        return o;
      }
    } catch (e) {}

    return undefined;
  };

  /**
   * Settings
   */

  /**
   * Wrapper for different plattforms to get settings for a given key
   * @param  {string} key A string containing the name of the key you want to
   *                  retrieve the value of
   * @return {string} String containing the value of the key. If the key
   *                  does not exist, null is returned
   */
  function getSetting(key) {
    // TODO : Move this to sqlite or a local file so it's not editable (and is safer)
    // https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions/XUL_School/Local_Storage

    if (!prefBranch.prefHasUserValue(key)) {
      return undefined;
    }

    return prefBranch.getStringPref(key);
  }

  /**
   * Wrapper for different plattforms to set a value for a given key in settings
   * @param {string} key     A string containing the name of the key you want
   *                         to create/update.
   * @param {string} value   String containing the value you want to give
   *                         the key you are creating/updating.
   */
  function setSetting(key, value) {
    // TODO : Move this to sqlite or a local file so it's not editable (and is safer)
    // https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions/XUL_School/Local_Storage

    if (!value) {
      prefBranch.clearUserPref(key);
    } else {
      // We use complexValue as tags can have utf-8 characters in them
      prefBranch.setStringPref(key, value);
    }
  }

  /**
   * Auth
   */

  /*
   *  All cookies from the Pocket domain
   *  The return format: { cookieName:cookieValue, cookieName:cookieValue, ... }
   */
  function getCookiesFromPocket() {
    var cookies = {};
    let oa = {};
    if (lazy.gCookieFirstPartyIsolate) {
      oa.firstPartyDomain = pocketSiteHost;
    }
    oa.privateBrowsingId = lazy.PrivateBrowsingUtils.permanentPrivateBrowsing
      ? 1
      : 0;
    for (let cookie of Services.cookies.getCookiesFromHost(
      pocketSiteHost,
      oa
    )) {
      if (cookie.host === pocketSiteHost) {
        cookies[cookie.name] = cookie.value;
      }
    }
    return cookies;
  }

  /**
   * Returns access token or undefined if no logged in user was found
   * @return {string | undefined} Access token for logged in user user
   */
  function getAccessToken() {
    var pocketCookies = getCookiesFromPocket();

    // If no cookie was found just return undefined
    if (typeof pocketCookies.ftv1 === "undefined") {
      return undefined;
    }

    // Check if a new user logged in in the meantime and clearUserData if so
    var sessionId = pocketCookies.fsv1;
    var lastSessionId = getSetting("fsv1");
    if (sessionId !== lastSessionId) {
      clearUserData();
      setSetting("fsv1", sessionId);
    }

    // Return access token
    return pocketCookies.ftv1;
  }

  /**
   * Get the current premium status of the user
   * @return {number | undefined} Premium status of user
   */
  function getPremiumStatus() {
    var premiumStatus = getSetting("premium_status");
    if (typeof premiumStatus === "undefined") {
      // Premium status is not in settings try get it from cookie
      var pocketCookies = getCookiesFromPocket();
      premiumStatus = pocketCookies.ps;
    }
    return premiumStatus;
  }

  /**
   * Helper method to check if a user is premium or not
   * @return {Boolean} Boolean if user is premium or not
   */
  function isPremiumUser() {
    return getPremiumStatus() == 1;
  }

  /**
   * Returns users logged in status
   * @return {Boolean} Users logged in status
   */
  function isUserLoggedIn() {
    return typeof getAccessToken() !== "undefined";
  }

  /**
   * API
   */

  /**
   * Helper function for executing api requests. It mainly configures the
   * ajax call with default values like type, headers or dataType for an api call.
   * This function is for internal usage only.
   * @param  {Object} options
   *     Possible keys:
   *      - {string} path: This should be the Pocket API
   *                       endpoint to call. For example providing the path
   *                       "/get" would result in a call to getpocket.com/v3/get
   *      - {Object|undefined} data: Gets passed on to the jQuery ajax
   *                                 call as data parameter
   *      - {function(Object data, XMLHttpRequest xhr) | undefined} success:
   *                        A function to be called if the request succeeds.
   *      - {function(Error errorThrown,  XMLHttpRequest xhr) | undefined} error:
   *                       A function to be called if the request fails.
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   *
   */
  function apiRequest(options, useBFF = false) {
    let baseAPIUrl;
    let oAuthConsumerKey;

    if (!useBFF) {
      baseAPIUrl = `https://${Services.prefs.getCharPref(
        "extensions.pocket.api"
      )}/v3`;

      oAuthConsumerKey = Services.prefs.getCharPref(
        "extensions.pocket.oAuthConsumerKey"
      );
    } else {
      baseAPIUrl = `https://${lazy.NimbusFeatures.saveToPocket.getVariable(
        "bffApi"
      )}/desktop/v1`;

      oAuthConsumerKey = lazy.NimbusFeatures.saveToPocket.getVariable(
        "oAuthConsumerKeyBff"
      );
    }

    if (typeof options === "undefined" || typeof options.path === "undefined") {
      return false;
    }

    var url = baseAPIUrl + options.path;
    var data = options.data || {};
    data.locale_lang = Services.locale.appLocaleAsBCP47;
    data.consumer_key = oAuthConsumerKey;

    var request = new XMLHttpRequest();

    if (!useBFF) {
      request.open("POST", url, true);
    } else {
      request.open("GET", url, true);
    }

    request.onreadystatechange = function (e) {
      if (request.readyState == 4) {
        // "done" is a completed XHR regardless of success/error:
        if (options.done) {
          options.done();
        }

        if (request.status === 200) {
          // There could still be an error if the response is no valid json
          // or does not have status = 1
          var response = parseJSON(request.response);

          // BFF doesn't return an appended `status` code in the returned data
          if (options.success && response && (response.status == 1 || useBFF)) {
            options.success(response, request);
            return;
          }
        }

        // Handle error case
        if (options.error) {
          // In case the user did revoke the access token or it's not
          // valid anymore clear the user data
          if (request.status === 401) {
            clearUserData();
          }

          // Handle error message
          var errorMessage;
          if (request.status !== 200) {
            errorMessage =
              request.getResponseHeader("X-Error") || request.statusText;
            errorMessage = JSON.parse('"' + errorMessage + '"');
          }
          var error = { message: errorMessage };
          options.error(error, request);
        }
      }
    };

    // Set headers
    request.setRequestHeader(
      "Content-Type",
      "application/x-www-form-urlencoded; charset=UTF-8"
    );
    request.setRequestHeader("X-Accept", " application/json");

    if (useBFF) {
      let cookies = getCookiesFromPocket();
      let serializedCookies = ``;

      for (const key in cookies) {
        serializedCookies += `${key}=${cookies[key]}; `;
      }

      serializedCookies = serializedCookies.substring(
        0,
        serializedCookies.length - 2
      );

      request.setRequestHeader("Cookie", serializedCookies);
      request.setRequestHeader("consumer_key", oAuthConsumerKey);
    }

    // Serialize and Fire off the request
    var str = [];
    for (var p in data) {
      if (data.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(data[p]));
      }
    }

    request.send(str.join("&"));

    return true;
  }

  /**
   * Cleans all settings for the previously logged in user
   */
  function clearUserData() {
    // Clear stored information
    setSetting("premium_status", undefined);
    setSetting("latestSince", undefined);
    setSetting("tags", undefined);
    // An old pref that is no longer used,
    // but the user data may still exist on some profiles.
    // So best to clean it up just in case.
    // Can probably remove this line in the future.
    setSetting("usedTags", undefined);

    setSetting("fsv1", undefined);

    _clearRecentSavesCache();
  }

  /**
   * Add a new link to Pocket
   * @param {string} url     URL of the link
   * @param {Object | undefined} options Can provide a string-based title, a
   *                                     `success` callback and an `error` callback.
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function addLink(url, options) {
    var since = getSetting("latestSince");
    var accessToken = getAccessToken();

    var sendData = {
      access_token: accessToken,
      url,
      since: since ? since : 0,
    };

    if (options.title) {
      sendData.title = options.title;
    }

    return apiRequest({
      path: "/firefox/save",
      data: sendData,
      success(data) {
        // Update premium status, tags and since
        var tags = data.tags;
        if (typeof tags !== "undefined" && Array.isArray(tags)) {
          // If a tagslist is in the response replace the tags
          setSetting("tags", JSON.stringify(data.tags));
        }

        // Update premium status
        var premiumStatus = data.premium_status;
        if (typeof premiumStatus !== "undefined") {
          // If a premium_status is in the response replace the premium_status
          setSetting("premium_status", premiumStatus);
        }

        // Save since value for further requests
        setSetting("latestSince", data.since);

        // Define variant for ho2
        if (data.flags) {
          var showHo2 =
            Services.locale.appLocaleAsBCP47 === "en-US"
              ? data.flags.show_ffx_mobile_prompt
              : "control";
          setSetting("test.ho2", showHo2);
        }
        data.ho2 = getSetting("test.ho2");

        _expireRecentSavesCache();
        if (options.success) {
          options.success.apply(options, Array.apply(null, arguments));
        }
      },
      error: options.error,
    });
  }

  /**
   * Gets a list of related recommendations for the item
   * @param  {string} itemId Item id of item
   * @param {Object | undefined} options Can provide a string-based title, a
   *                                     `success` callback and an `error` callback.
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function getRecsForItem(itemId, options) {
    return apiRequest({
      path: "/discover/recIt",
      data: {
        item_id: itemId,
        module: "ff_plugin",
        count: 3,
      },
      success(data) {
        if (options.success) {
          options.success.apply(options, Array.apply(null, arguments));
        }
      },
      error: options.error,
    });
  }

  /**
   * Get a preview for saved URL
   * @param {string} url     URL of the link
   * @param {Object | undefined} options Can provide a `success` callback and an `error` callback.
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function getArticleInfo(url, options) {
    return apiRequest({
      path: "/getItemPreview",
      data: {
        access_token: getAccessToken(),
        url,
      },
      success(data) {
        if (options.success) {
          options.success.apply(options, Array.apply(null, arguments));
        }
      },
      error: options.error,
      done: options.done,
    });
  }

  /**
   * Request a email for mobile apps
   * @param {Object | undefined} options Can provide a `success` callback and an `error` callback.
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function getMobileDownload(options) {
    return apiRequest({
      path: "/firefox/get-app",
      data: {
        access_token: getAccessToken(),
      },
      success(data) {
        if (options.success) {
          options.success.apply(options, Array.apply(null, arguments));
        }
      },
      error: options.error,
    });
  }

  /**
   * Delete an item identified by item id from the users list
   * @param  {string} itemId  The id from the item we want to remove
   * @param  {Object | undefined} options Can provide an actionInfo object with
   *                                      further data to send to the API. Can
   *                                      have success and error callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function deleteItem(itemId, options) {
    var action = {
      action: "delete",
      item_id: itemId,
    };
    return sendAction(action, options);
  }

  /**
   * Archive an item identified by item id from the users list
   * @param  {string} itemId  The id from the item we want to archive
   * @param  {Object | undefined} options Can provide an actionInfo object with
   *                                      further data to send to the API. Can
   *                                      have success and error callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function archiveItem(itemId, options) {
    var action = {
      action: "archive",
      item_id: itemId,
    };
    return sendAction(action, options);
  }

  /**
   * General function to send all kinds of actions like adding of links or
   * removing of items via the API
   * @param  {Object}  action  Action object
   * @param  {Object | undefined}  options Can provide an actionInfo object
   *                                       with further data to send to the
   *                                       API. Can have success and error
   *                                       callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function sendAction(action, options) {
    // Options can have an 'actionInfo' object. This actionInfo object gets
    // passed through to the action object that will be send to the API endpoint
    if (typeof options.actionInfo !== "undefined") {
      action = extend(action, options.actionInfo);
    }
    return sendActions([action], options);
  }

  /**
   * General function to send all kinds of actions like adding of links or
   * removing of items via the API
   * @param  {Array} actions Array of action objects
   * @param  {Object | undefined} options Can have success and error callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function sendActions(actions, options) {
    return apiRequest({
      path: "/send",
      data: {
        access_token: getAccessToken(),
        actions: JSON.stringify(actions),
      },
      success: options.success,
      error: options.error,
    });
  }

  /**
   * Handling Tags
   */

  /**
   * Add tags to the item identified by the url. Also updates the used tags
   * list
   * @param {string} itemId  The item identifier by item id
   * @param {Array}  tags    Tags adding to the item
   * @param {Object | undefined} options Can provide an actionInfo object with
   *                                     further data to send to the API. Can
   *                                     have success and error callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function addTagsToItem(itemId, tags, options) {
    return addTags({ item_id: itemId }, tags, options);
  }

  /**
   * Add tags to the item identified by the url. Also updates the used tags
   * list
   * @param {string} url     The item identifier by url
   * @param {Array}  tags    Tags adding to the item
   * @param {Object} options Can provide an actionInfo object with further
   *                         data to send to the API. Can have success and error
   *                         callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function addTagsToURL(url, tags, options) {
    return addTags({ url }, tags, options);
  }

  /**
   * Helper function to execute the add tags api call. Will be used from addTagsToURL
   * and addTagsToItem but not exposed outside
   * @param {string} actionPart Specific action part to add to action
   * @param {Array}  tags       Tags adding to the item
   * @param {Object | undefined} options Can provide an actionInfo object with
   *                                     further data to send to the API. Can
   *                                     have success and error callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function addTags(actionPart, tags, options) {
    if (tags.length) {
      addRecentTags(tags);
    }

    // Tags add action
    var action = {
      action: "tags_add",
      tags,
    };
    action = extend(action, actionPart);

    // Execute the action
    return sendAction(action, options);
  }

  /**
   * Return all cached tags and used tags.
   */
  function getTags() {
    var tagsFromSettings = function () {
      var tagsJSON = getSetting("tags");
      if (typeof tagsJSON !== "undefined") {
        return JSON.parse(tagsJSON);
      }
      return [];
    };

    return {
      tags: tagsFromSettings(),
    };
  }

  /**
   * Return all recent tags.
   */
  function getRecentTags() {
    var tagsFromSettings = function () {
      var tagsJSON = getSetting("recentTags");

      if (typeof tagsJSON !== "undefined") {
        let parsedTags;

        try {
          parsedTags = JSON.parse(tagsJSON);
        } catch {
          parsedTags = [];
        }

        return parsedTags;
      }

      return [];
    };

    return {
      recentTags: tagsFromSettings(),
    };
  }

  /**
   * Store recently used tags.
   * @param {Array}  tags   Newly used tags to store
   */
  function addRecentTags(tags) {
    var newRecentTags = tags || [];
    var cachedRecentTags = getRecentTags()?.recentTags;
    var mergedRecentTags = [];

    cachedRecentTags.forEach(tag => {
      if (!newRecentTags.includes(tag)) {
        mergedRecentTags.push(tag);
      }
    });

    mergedRecentTags = [...newRecentTags, ...mergedRecentTags];

    // update recent tags pref to store
    setSetting("recentTags", JSON.stringify(mergedRecentTags));
  }

  /**
   * Fetch suggested tags for a given item id
   * @param  {string} itemId Item id of
   * @param  {Object | undefined} options Can provide an actionInfo object
   *                                      with further data to send to the API.
   *                                      Can have success and error callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function getSuggestedTagsForItem(itemId, options) {
    return getSuggestedTags({ item_id: itemId }, options);
  }

  /**
   * Fetch suggested tags for a given URL
   * @param {string} url (required) The item identifier by url
   * @param {Object} options Can provide an actionInfo object with further
   *                         data to send to the API. Can have success and error
   *                         callbacks
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function getSuggestedTagsForURL(url, options) {
    return getSuggestedTags({ url }, options);
  }

  /**
   * Helper function to get suggested tags
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function getSuggestedTags(data, options) {
    data = data || {};
    options = options || {};

    data.access_token = getAccessToken();

    return apiRequest({
      path: "/getSuggestedTags",
      data,
      success: options.success,
      error: options.error,
    });
  }

  /**
   * Helper function to get a user's pocket stories
   * @return {Boolean} Returns Boolean whether the api call started sucessfully
   */
  function retrieve(data = {}, options = {}) {
    const requestData = Object.assign({}, data, {
      access_token: getAccessToken(),
    });

    const useBFF =
      lazy.NimbusFeatures.saveToPocket.getVariable("bffRecentSaves");

    return apiRequest(
      {
        path: useBFF ? `/recent-saves?count=${data.count}` : `/firefox/get`,
        data: requestData,
        success: options.success,
        error: options.error,
      },
      useBFF
    ); // Use BFF
  }

  async function _getRecentSavesCache() {
    const db = await getDatabase();
    return db.objectStore(STORE_NAME, "readonly").get("recentSaves");
  }
  async function _setRecentSavesCache(data) {
    const db = await getDatabase();
    db.objectStore(STORE_NAME, "readwrite").put(data, "recentSaves");
  }
  // Clears the cache time, so the next get forces an update.
  async function _expireRecentSavesCache() {
    const cache = await _getRecentSavesCache();
    _setRecentSavesCache({
      ...cache,
      lastUpdated: 0,
    });
  }
  // Clears the cache, for when a new user logs in.
  async function _clearRecentSavesCache() {
    const db = await getDatabase();
    db.objectStore(STORE_NAME, "readwrite").delete("recentSaves");
  }

  async function getRecentSavesCache() {
    // Get cache
    const cache = await _getRecentSavesCache();
    // Check age
    if (
      cache?.lastUpdated &&
      Date.now() - cache.lastUpdated < RECENT_SAVES_UPDATE_TIME
    ) {
      // Return cache if it's not too old.
      return cache.list;
    }
    return null;
  }

  async function getRecentSaves(options = {}) {
    pktApi.retrieve(
      { count: 4 },
      {
        success(data) {
          const useBFF =
            lazy.NimbusFeatures.saveToPocket.getVariable("bffRecentSaves");

          // Don't try to parse bad or missing data
          if (
            useBFF &&
            (typeof data !== `object` || typeof data?.data !== `object`)
          ) {
            return;
          }

          try {
            let list = useBFF ? [] : data.list;

            if (useBFF) {
              // Transform BFF list item schema to existing api schema
              data.data.forEach((item, index) => {
                list[index] = {
                  item_id: item.id,
                  id: item.id, // This can probably be deprecated when the old API is
                  resolved_url: item.resolvedUrl,
                  given_url: item.givenUrl,
                  resolved_title: item.title,
                  excerpt: item.excerpt,
                  word_count: item.wordCount,
                  time_to_read: item.timeToRead,
                  top_image_url: item.topImageUrl,
                };
              });
            } else {
              // We want these to show up in the same order as they saved,
              // so we need to do some work and sort.
              list = Object.values(list)
                .map(item => ({
                  ...item,
                  id: parseInt(item.item_id || item.resolved_id, 10),
                  time_added: parseInt(item.time_added),
                }))
                .sort((a, b) => b.time_added - a.time_added);
            }

            // Cache results
            const results = {
              lastUpdated: Date.now(),
              list,
            };

            _setRecentSavesCache(results);
            options.success?.(results.list);
          } catch {
            // If parsing fails, just leave existing recent saves cache intact
          }
        },
        error(error) {
          options.error?.(error);
        },
      }
    );
  }

  /**
   * Public functions
   */
  return {
    isUserLoggedIn,
    clearUserData,
    addLink,
    getRecsForItem,
    deleteItem,
    archiveItem,
    addTagsToItem,
    addTagsToURL,
    getTags,
    getRecentTags,
    isPremiumUser,
    getSuggestedTagsForItem,
    getSuggestedTagsForURL,
    retrieve,
    getRecentSavesCache,
    getRecentSaves,
    getArticleInfo,
    getMobileDownload,
  };
})();