forked from pkreissel/fedialgo
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
961 lines (867 loc) · 39.4 KB
/
index.ts
File metadata and controls
961 lines (867 loc) · 39.4 KB
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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
/*
* Main class that handles scoring and sorting a feed made of Toot objects.
*/
import 'reflect-metadata'; // Required for class-transformer
import { Buffer } from 'buffer'; // Maybe Required for class-transformer though seems to be required in client?
import { mastodon } from "masto";
import { Mutex } from 'async-mutex';
import Account from './api/objects/account';
import AlreadyShownScorer from './scorer/toot/already_shown_scorer';
import AuthorFollowersScorer from './scorer/toot/author_followers_scorer';
import BooleanFilter from "./filters/boolean_filter";
import ChaosScorer from "./scorer/toot/chaos_scorer";
import DiversityFeedScorer from "./scorer/feed/diversity_feed_scorer";
import FavouritedTagsScorer from './scorer/toot/favourited_tags_scorer';
import FollowedAccountsScorer from './scorer/toot/followed_accounts_scorer';
import FollowedTagsScorer from "./scorer/toot/followed_tags_scorer";
import FollowersScorer from './scorer/toot/followers_scorer';
import HashtagParticipationScorer from "./scorer/toot/hashtag_participation_scorer";
import ImageAttachmentScorer from "./scorer/toot/image_attachment_scorer";
import InteractionsScorer from "./scorer/toot/interactions_scorer";
import MastoApi, { FULL_HISTORY_PARAMS } from "./api/api";
import MastodonServer from './api/mastodon_server';
import MentionsFollowedScorer from './scorer/toot/mentions_followed_scorer';
import MostFavouritedAccountsScorer from "./scorer/toot/most_favourited_accounts_scorer";
import MostRepliedAccountsScorer from "./scorer/toot/most_replied_accounts_scorer";
import MostRetootedAccountsScorer from "./scorer/toot/most_retooted_accounts_scorer";
import NumericFilter from './filters/numeric_filter';
import NumFavouritesScorer from "./scorer/toot/num_favourites_scorer";
import NumRepliesScorer from "./scorer/toot/num_replies_scorer";
import NumRetootsScorer from "./scorer/toot/num_retoots_scorer";
import RetootsInFeedScorer from "./scorer/toot/retoots_in_feed_scorer";
import Scorer from "./scorer/scorer";
import ScorerCache from './scorer/scorer_cache';
import Storage from "./Storage";
import TagList from './api/tag_list';
import TagsForFetchingToots from "./api/tags_for_fetching_toots";
import Toot, { earliestTootedAt, mostRecentTootedAt } from './api/objects/toot';
import TrendingLinksScorer from './scorer/toot/trending_links_scorer';
import TrendingTagsScorer from "./scorer/toot/trending_tags_scorer";
import TrendingTootScorer from "./scorer/toot/trending_toots_scorer";
import UserData from "./api/user_data";
import UserDataPoller from './api/user_data_poller';
import VideoAttachmentScorer from "./scorer/toot/video_attachment_scorer";
import type FeedScorer from './scorer/feed_scorer';
import type TootScorer from './scorer/toot_scorer';
import { AgeIn, ageString, sleep, timeString, toISOFormatIfExists } from './helpers/time_helpers';
import { buildNewFilterSettings, updateBooleanFilterOptions } from "./filters/feed_filters";
import { DEFAULT_FONT_SIZE, FEDIALGO, GIFV, VIDEO_TYPES, extractDomain, optionalSuffix } from './helpers/string_helpers';
import { isAccessTokenRevokedError, throwIfAccessTokenRevoked, throwSanitizedRateLimitError } from './api/errors';
import { isDebugMode, isDeepDebug, isLoadTest, isQuickMode } from './helpers/environment_helpers';
import { lockExecution } from './helpers/mutex_helpers';
import { Logger } from './helpers/logger';
import { MAX_ENDPOINT_RECORDS_TO_PULL, config } from './config';
import { rechartsDataPoints } from "./helpers/stats_helper";
import { WEIGHT_PRESETS, WeightPresetLabel, isWeightPresetLabel, type WeightPresets } from './scorer/weight_presets';
import { type ObjList } from "./api/counted_list";
import {
AlgorithmStorageKey,
BooleanFilterName,
CacheKey,
FediverseCacheKey,
LoadAction,
LogAction,
MediaCategory,
NonScoreWeightName,
ScoreName,
TagTootsCategory,
TrendingType,
TypeFilterName,
ALL_ACTIONS,
buildCacheKeyDict,
isValueInStringEnum,
type Action,
type ApiCacheKey,
} from "./enums";
import {
computeMinMax,
makeChunks,
makePercentileChunks,
sortKeysByValue,
truncateToLength,
} from "./helpers/collection_helpers";
import {
FILTER_OPTION_DATA_SOURCES,
type BooleanFilterOption,
type ConcurrencyLockRelease,
type FeedFilterSettings,
type FilterOptionDataSource,
type Hashtag,
type KeysOfValueType,
type MastodonInstance,
type MinMaxAvgScore,
type ScoreStats,
type StringNumberDict,
type TagWithUsageCounts,
type TrendingData,
type TrendingLink,
type TrendingObj,
type TrendingWithHistory,
type WeightInfoDict,
type WeightName,
type Weights,
} from "./types";
const EMPTY_TRENDING_DATA: Readonly<TrendingData> = {
links: [],
tags: new TagList([], TagTootsCategory.TRENDING),
servers: {},
toots: []
};
const DEFAULT_SET_TIMELINE_IN_APP = (_feed: Toot[]) => console.debug(`Default setTimelineInApp() called`);
const logger = new Logger(`TheAlgorithm`);
const loadCacheLogger = logger.tempLogger(`loadCachedData()`);
const saveTimelineToCacheLogger = logger.tempLogger(`saveTimelineToCache`);
const loggers: Record<Action | ApiCacheKey, Logger> = buildCacheKeyDict<Action, Logger, Record<Action, Logger>>(
(key) => new Logger(key as string),
ALL_ACTIONS.reduce(
(_loggers, action) => {
_loggers[action] = logger.tempLogger(action);
return _loggers;
},
{} as Record<Action, Logger>
)
);
interface AlgorithmArgs {
api: mastodon.rest.Client;
user: mastodon.v1.Account;
locale?: string; // Optional locale to use for date formatting
setTimelineInApp?: (feed: Toot[]) => void; // Optional callback to set the feed in the code using this package
};
/**
* Main class for scoring, sorting, and managing a Mastodon feed made of {@linkcode Toot} objects.
*
* {@linkcode TheAlgorithm} orchestrates fetching, scoring, filtering, and updating the user's timeline/feed.
* It manages feature and feed scorers, trending data, filters, user weights, and background polling. Key
* responsibilities:
*
* 1. Fetches and merges toots from multiple sources (home timeline, trending, hashtags, etc.).
* 2. Applies scoring algorithms and user-defined weights to rank toots.
* 3. Filters the feed based on user settings and filter options.
* 4. Handles background polling for new data and saving state to storage.
* 5. Provides methods for updating filters, weights, and retrieving current state.
* 6. Exposes utility methods for stats, server info, and tag URLs.
*
* @property {string[]} apiErrorMsgs - API error messages
* @property {FeedFilterSettings} filters - Current filter settings for the feed
* @property {boolean} isLoading - Whether a feed load is in progress*
* @property {number} [lastLoadTimeInSeconds] - Duration of the last load in seconds
* @property {string | null} loadingStatus - String describing load activity
* @property {Toot[]} timeline - The current filtered timeline
* @property {TrendingData} trendingData - Trending data (links, tags, servers, toots)
* @property {UserData} userData - User data for scoring and filtering
* @property {WeightInfoDict} weightsInfo - Info about all scoring weights
*/
export default class TheAlgorithm {
filters: FeedFilterSettings = buildNewFilterSettings();
lastLoadTimeInSeconds?: number;
loadingStatus: string | null = config.locale.messages[LogAction.INITIAL_LOADING_STATUS];
trendingData: TrendingData = EMPTY_TRENDING_DATA;
get apiErrorMsgs(): string[] { return MastoApi.instance.apiErrorMsgs() };
get isLoading(): boolean { return this.loadingMutex.isLocked() };
get timeline(): Toot[] { return [...this.feed] };
get userData(): UserData { return MastoApi.instance.userData || new UserData() };
// Constructor arguments
private setTimelineInApp: (feed: Toot[]) => void; // Optional callback to set the feed in the app using this package
// Other private variables
private feed: Toot[] = [];
private homeFeed: Toot[] = []; // Just the toots pulled from the home timeline
private hasProvidedAnyTootsToClient = false; // Flag to indicate if the feed has been set in the app
private loadStartedAt: Date | undefined = new Date(); // Timestamp of when the feed started loading
private totalNumTimesShown = 0; // Sum of timeline toots' numTimesShown
// Utility
private loadingMutex = new Mutex();
private mergeMutex = new Mutex();
private numUnscannedToots = 0; // Keep track of how many new toots were merged into the feed but not into the filter options
private numTriggers = 0; // How many times has a load been triggered, only matters for QUICK_LOAD mode
private _releaseLoadingMutex?: ConcurrencyLockRelease; // Mutex release function for loading state
// Background tasks
private cacheUpdater?: ReturnType<typeof setInterval>;
private userDataPoller = new UserDataPoller();
// These scorers require the complete feed to work properly
private feedScorers: FeedScorer[] = [
new DiversityFeedScorer(),
];
// These can score a toot without knowing about the rest of the toots in the feed
private tootScorers: TootScorer[] = [
new AlreadyShownScorer(),
new AuthorFollowersScorer(),
new ChaosScorer(),
new FavouritedTagsScorer(),
new FollowedAccountsScorer(),
new FollowedTagsScorer(),
new FollowersScorer(),
new HashtagParticipationScorer(),
new ImageAttachmentScorer(),
new InteractionsScorer(),
new MentionsFollowedScorer(),
new MostFavouritedAccountsScorer(),
new MostRepliedAccountsScorer(),
new MostRetootedAccountsScorer(),
new NumFavouritesScorer(),
new NumRepliesScorer(),
new NumRetootsScorer(),
new RetootsInFeedScorer(),
new TrendingLinksScorer(),
new TrendingTagsScorer(),
new TrendingTootScorer(),
new VideoAttachmentScorer(),
];
private weightedScorers: Scorer[] = [
...this.tootScorers,
...this.feedScorers,
];
weightsInfo: WeightInfoDict = this.weightedScorers.reduce(
(scorerInfos, scorer) => {
scorerInfos[scorer.name] = scorer.getInfo();
return scorerInfos;
},
Object.values(NonScoreWeightName).reduce(
(nonScoreWeights, weightName) => {
nonScoreWeights[weightName] = Object.assign({}, config.scoring.nonScoreWeightsConfig[weightName]);
nonScoreWeights[weightName].minValue = config.scoring.nonScoreWeightMinValue;
return nonScoreWeights;
},
{} as WeightInfoDict
)
);
/**
* Publicly callable constructor that instantiates the class and loads the feed from storage.
* @param {AlgorithmArgs} params - The parameters for algorithm creation.
* @param {mastodon.rest.Client} params.api - The Mastodon REST API client instance.
* @param {mastodon.v1.Account} params.user - The Mastodon user account for which to build the feed.
* @param {string} [params.locale] - Optional locale string for date formatting.
* @param {(feed: Toot[]) => void} [params.setTimelineInApp] - Optional callback to set the feed in the consuming app.
* @returns {Promise<TheAlgorithm>} TheAlgorithm instance.
*/
static async create(params: AlgorithmArgs): Promise<TheAlgorithm> {
config.setLocale(params.locale);
const user = Account.build(params.user);
await MastoApi.init(params.api, user);
await Storage.logAppOpen(user);
// Construct the algorithm object, set the default weights, load feed and filters
const algo = new TheAlgorithm(params);
ScorerCache.addScorers(algo.tootScorers, algo.feedScorers);
await algo.loadCachedData();
return algo;
}
/**
* Private constructor. Use {@linkcode TheAlgorithm.create} to instantiate.
* @param {AlgorithmArgs} params - Constructor params (API client, user, and optional timeline callback/locale).
*/
private constructor(params: AlgorithmArgs) {
this.setTimelineInApp = params.setTimelineInApp ?? DEFAULT_SET_TIMELINE_IN_APP;
}
/**
* Trigger the retrieval of the user's timeline from all the sources.
* @returns {Promise<void>}
*/
async triggerFeedUpdate(): Promise<void> {
if (this.shouldSkip()) return;
const action = LoadAction.FEED_UPDATE;
const hereLogger = loggers[action];
await this.startAction(action);
try {
const tootsForHashtags = async (key: TagTootsCategory): Promise<Toot[]> => {
hereLogger.trace(`Fetching toots for hashtags with key: ${key}`);
const tagList = await TagsForFetchingToots.create(key);
return await this.fetchAndMergeToots(tagList.getToots(), tagList.logger);
};
const dataLoads: Promise<unknown>[] = [
// Toot fetchers
this.getHomeTimeline().then((toots) => this.homeFeed = toots),
this.fetchAndMergeToots(MastoApi.instance.getHomeserverToots(), loggers[CacheKey.HOMESERVER_TOOTS]),
this.fetchAndMergeToots(MastodonServer.fediverseTrendingToots(), loggers[FediverseCacheKey.TRENDING_TOOTS]),
...Object.values(TagTootsCategory).map(async (key) => await tootsForHashtags(key)),
// Other data fetchers
MastodonServer.getTrendingData().then((trendingData) => this.trendingData = trendingData),
MastoApi.instance.getUserData(),
ScorerCache.prepareScorers(),
];
const allResults = await Promise.allSettled(dataLoads);
hereLogger.deep(`FINISHED promises, allResults:`, allResults);
await this.finishFeedUpdate();
} finally {
this.releaseLoadingMutex(action);
}
}
/**
* Trigger the fetching of additional earlier {@linkcode Toot}s from the server.
* @returns {Promise<void>}
*/
async triggerHomeTimelineBackFill(): Promise<void> {
await this.startAction(LoadAction.TIMELINE_BACKFILL);
try {
this.homeFeed = await this.getHomeTimeline(true);
await this.finishFeedUpdate();
} finally {
this.releaseLoadingMutex(LoadAction.TIMELINE_BACKFILL);
}
}
/**
* Manually trigger the loading of "moar" user data (recent toots, favourites, notifications, etc).
* Usually done by a background task on a set interval.
* @returns {Promise<void>}
*/
async triggerMoarData(): Promise<void> {
const shouldReenablePoller = this.userDataPoller.stop();
await this.startAction(LoadAction.GET_MOAR_DATA);
try {
await this.userDataPoller.getMoarData();
await this.recomputeScores();
} catch (error) {
throwSanitizedRateLimitError(error, `triggerMoarData() Error pulling user data:`);
} finally {
if (shouldReenablePoller) this.userDataPoller.start();
this.releaseLoadingMutex(LoadAction.GET_MOAR_DATA);
}
}
/**
* Collect **ALL** the user's history data from the server - past toots, favourites, etc.
* Use with caution!
* @returns {Promise<void>}
*/
async triggerPullAllUserData(): Promise<void> {
const action = LoadAction.PULL_ALL_USER_DATA;
const hereLogger = loggers[action];
this.startAction(action);
try {
this.userDataPoller.stop(); // Stop the dataPoller if it's running
const _allResults = await Promise.allSettled([
MastoApi.instance.getFavouritedToots(FULL_HISTORY_PARAMS),
// TODO: there's just too many notifications to pull all of them
MastoApi.instance.getNotifications({maxRecords: MAX_ENDPOINT_RECORDS_TO_PULL, moar: true}),
MastoApi.instance.getRecentUserToots(FULL_HISTORY_PARAMS),
]);
await this.recomputeScores();
} catch (error) {
throwSanitizedRateLimitError(error, hereLogger.line(`Error pulling user data:`));
} finally {
this.releaseLoadingMutex(action); // TODO: should we restart data poller?
}
}
/**
* Return an object describing the state of the world. Mostly for debugging.
* @returns {Promise<Record<string, any>>} State object.
*/
async getCurrentState(): Promise<Record<string, unknown>> {
return {
Algorithm: this.statusDict(),
Api: MastoApi.instance.currentState(),
Config: config,
Filters: this.filters,
Homeserver: await this.serverInfo(),
Storage: await Storage.storedObjsInfo(),
Trending: this.trendingData,
UserData: await MastoApi.instance.getUserData(),
};
}
/**
* Build array of objects suitable for charting timeline scoring data by quintile/decile/etc.
* with {@link https://recharts.org/ Recharts}.
* @param {number} numPercentiles - Number of percentiles for stats.
* @returns {object[]} Recharts data points.
*/
getRechartsStatsData(numPercentiles: number): object[] {
return rechartsDataPoints(this.feed, numPercentiles);
}
/**
* Return the user's current weightings for each score category.
* @returns {Promise<Weights>} The user's weights.
*/
async getUserWeights(): Promise<Weights> {
return await Storage.getWeights();
}
/**
* Return the timestamp of the most recent toot from followed accounts + hashtags ONLY.
* @returns {Date | null} The most recent toot date or null.
*/
mostRecentHomeTootAt(): Date | null {
// TODO: this.homeFeed is only set when fetchHomeFeed() is *finished*
if (this.homeFeed.length == 0 && this.numTriggers > 1) {
logger.warn(`mostRecentHomeTootAt() homeFeed is empty, falling back to full feed`);
return mostRecentTootedAt(this.feed);
}
return mostRecentTootedAt(this.homeFeed);
}
/**
* Return the number of seconds since the most recent home timeline {@linkcode Toot}.
* @returns {number | null} Age in seconds or null.
*/
mostRecentHomeTootAgeInSeconds(): number | null {
const mostRecentAt = this.mostRecentHomeTootAt();
if (!mostRecentAt) return null;
logger.trace(`feed is ${AgeIn.minutes(mostRecentAt).toFixed(2)} min old, most recent home toot: ${timeString(mostRecentAt)}`);
return AgeIn.seconds(mostRecentAt);
}
/**
* Pull the latest list of muted accounts from the server and use that to filter any newly muted
* accounts out of the timeline.
* @returns {Promise<void>}
*/
async refreshMutedAccounts(): Promise<void> {
const hereLogger = loggers[LoadAction.REFRESH_MUTED_ACCOUNTS];
hereLogger.log(`called (${Object.keys(this.userData.mutedAccounts).length} current muted accounts)...`);
// TODO: move refreshMutedAccounts() to UserData class?
const mutedAccounts = await MastoApi.instance.getMutedAccounts({bustCache: true});
hereLogger.log(`Found ${mutedAccounts.length} muted accounts after refresh...`);
this.userData.mutedAccounts = Account.buildAccountNames(mutedAccounts);
await Toot.completeToots(this.feed, hereLogger, LoadAction.REFRESH_MUTED_ACCOUNTS);
await this.finishFeedUpdate();
}
/**
* Clear everything from browser storage except the user's identity and weightings (unless complete is true).
* @param {boolean} [complete=false] - If true, remove user data as well.
* @returns {Promise<void>}
*/
async reset(complete: boolean = false): Promise<void> {
await this.startAction(LoadAction.RESET);
try {
this.userDataPoller.stop();
this.cacheUpdater && clearInterval(this.cacheUpdater!);
this.cacheUpdater = undefined;
this.hasProvidedAnyTootsToClient = false;
this.loadingStatus = config.locale.messages[LogAction.INITIAL_LOADING_STATUS];
this.loadStartedAt = new Date();
this.numTriggers = 0;
this.trendingData = EMPTY_TRENDING_DATA;
this.feed = [];
this.setTimelineInApp([]);
// Call other classes' reset methods
MastoApi.instance.reset();
ScorerCache.resetScorers();
await Storage.clearAll();
if (complete) {
await Storage.remove(AlgorithmStorageKey.USER); // Remove user data so it gets reloaded
} else {
await this.loadCachedData();
}
} finally {
this.releaseLoadingMutex(LoadAction.RESET);
}
}
/**
* Save the current timeline to the browser storage. Used to save the state of {@linkcode Toot.numTimesShown}.
* @returns {Promise<void>}
*/
async saveTimelineToCache(): Promise<void> {
const newTotalNumTimesShown = this.feed.reduce((sum, toot) => sum + (toot.numTimesShown ?? 0), 0);
if (this.isLoading || (this.totalNumTimesShown == newTotalNumTimesShown)) return;
try {
const numShownToots = this.feed.filter(toot => toot.numTimesShown).length;
const msg = `Saving ${this.feed.length} toots with ${newTotalNumTimesShown} times shown` +
` on ${numShownToots} toots (previous totalNumTimesShown: ${this.totalNumTimesShown})`;
saveTimelineToCacheLogger.debug(msg);
await Storage.set(AlgorithmStorageKey.TIMELINE_TOOTS, this.feed);
this.totalNumTimesShown = newTotalNumTimesShown;
} catch (error) {
saveTimelineToCacheLogger.error(`Error saving toots:`, error);
}
}
/**
* True if FediAlgo user is on a GoToSocial instance instead of plain vanilla Mastodon.
* @returns {boolean}
*/
async isGoToSocialUser(): Promise<boolean> {
return await MastoApi.instance.isGoToSocialUser();
}
/**
* Update {@linkcode this.trendingData} with latest available data.
* // TODO: this shouldn't be necessary but there's weirdness on initial load
* @returns {Promise<TrendingData>}
*/
async refreshTrendingData(): Promise<TrendingData> {
this.trendingData = await MastodonServer.getTrendingData();
return this.trendingData;
}
/**
* Returns info about the Fedialgo user's home Mastodon instance.
* @returns {Promise<mastodon.v2.Instance>} Instance info.
*/
async serverInfo(): Promise<mastodon.v2.Instance> {
return await MastoApi.instance.instanceInfo();
}
/**
* Get the URL for a tag on the user's home instance (aka "server").
* @param {string | Hashtag} tag - The tag or tag object.
* @returns {string} The tag URL.
*/
tagUrl(tag: string | Hashtag): string {
return MastoApi.instance.tagUrl(tag);
}
/**
* Update the feed filters and return the newly filtered feed.
* @param {FeedFilterSettings} newFilters - The new filter settings.
* @returns {Toot[]} The filtered feed.
*/
updateFilters(newFilters: FeedFilterSettings): Toot[] {
logger.info(`updateFilters() called with newFilters:`, newFilters);
this.filters = newFilters;
Storage.setFilters(newFilters);
return this.filterFeedAndSetInApp();
}
/**
* Update user weightings and rescore / resort the feed.
* @param {Weights} userWeights - The new user weights.
* @returns {Promise<Toot[]>} The filtered and rescored feed.
*/
async updateUserWeights(userWeights: Weights): Promise<Toot[]> {
logger.info("updateUserWeights() called with weights:", userWeights);
Scorer.validateWeights(userWeights);
await Storage.setWeightings(userWeights);
return this.scoreAndFilterFeed();
}
/**
* Update user weightings to one of the preset values and rescore / resort the feed.
* @param {WeightPresetLabel | string} presetName - The preset name.
* @returns {Promise<Toot[]>} The filtered and rescored feed.
*/
async updateUserWeightsToPreset(presetName: WeightPresetLabel | string): Promise<Toot[]> {
logger.info("updateUserWeightsToPreset() called with presetName:", presetName);
if (!isWeightPresetLabel(presetName)) {
logger.logAndThrowError(`Invalid weight preset: "${presetName}"`);
}
return await this.updateUserWeights(WEIGHT_PRESETS[presetName as WeightPresetLabel]);
}
///////////////////////////////
// Private Methods //
///////////////////////////////
/**
* Merge a new batch of {@linkcode Toot}s into the feed. Mutates {@linkcode this.feed}
* and returns whatever {@linkcode newToots} are retrieved by {@linkcode tootFetcher} argument.
* @private
* @param {Promise<Toot[]>} tootFetcher - Promise that resolves to an array of Toots.
* @param {Logger} logger Logger to use.
* @returns {Promise<Toot[]>} The new toots that were fetched and merged.
*/
private async fetchAndMergeToots(tootFetcher: Promise<Toot[]>, logger: Logger): Promise<Toot[]> {
const startedAt = new Date();
let newToots: Toot[] = [];
try {
newToots = await tootFetcher;
logger.logTelemetry(`Got ${newToots.length} toots for ${CacheKey.HOME_TIMELINE_TOOTS}`, startedAt);
} catch (e) {
throwIfAccessTokenRevoked(logger, e, `Error fetching toots ${ageString(startedAt)}`);
}
await this.lockedMergeToFeed(newToots, logger);
return newToots;
}
/**
* Filter the feed based on the user's settings. Has the side effect of calling the
* {@linkcode TheAlgorithm.setTimelineInApp} callback (if it exists) to send the client
* using this library the filtered subset of {@linkcode Toot} objects.
* ({@linkcode TheAlgorithm.feed} will always maintain the master unfiltered set of {@linkcode Toot}s).
* @private
* @returns {Toot[]} The filtered feed.
*/
private filterFeedAndSetInApp(): Toot[] {
const filteredFeed = this.feed.filter(toot => toot.isInTimeline(this.filters));
this.setTimelineInApp(filteredFeed);
if (!this.hasProvidedAnyTootsToClient && this.feed.length > 0) {
this.hasProvidedAnyTootsToClient = true;
logger.logTelemetry(`First ${filteredFeed.length} toots sent to client`, this.loadStartedAt);
}
return filteredFeed;
}
/**
* Do some final cleanup and scoring operations on the feed.
* @private
* @returns {Promise<void>}
*/
private async finishFeedUpdate(): Promise<void> {
const action = LogAction.FINISH_FEED_UPDATE;
const hereLogger = loggers[action];
this.loadingStatus = config.locale.messages[action];
// Now that all data has arrived go back over the feed and do the slow calculations of trendingLinks etc.
hereLogger.debug(`${this.loadingStatus}...`);
await Toot.completeToots(this.feed, hereLogger);
this.feed = await Toot.removeInvalidToots(this.feed, hereLogger);
await updateBooleanFilterOptions(this.filters, this.feed, true);
await this.scoreAndFilterFeed();
if (this.loadStartedAt) {
hereLogger.logTelemetry(`finished home TL load w/ ${this.feed.length} toots`, this.loadStartedAt);
this.lastLoadTimeInSeconds = AgeIn.seconds(this.loadStartedAt);
} else {
hereLogger.warn(`finished but loadStartedAt is null!`);
}
this.loadStartedAt = undefined;
this.loadingStatus = null;
this.launchBackgroundPollers();
}
/**
* Simple wrapper for triggering {@linkcode MastoApi.fetchHomeFeed}.
* @private
* @returns {Promise<Toot[]>}
*/
private async getHomeTimeline(moreOldToots?: boolean): Promise<Toot[]> {
return await MastoApi.instance.fetchHomeFeed({
mergeTootsToFeed: this.lockedMergeToFeed.bind(this),
moar: moreOldToots
});
}
/**
* Kick off the MOAR data poller to collect more user history data if it doesn't already exist
* as well as the cache updater that saves the current state of the timeline toots'
* {@linkcode alreadyShown} properties to storage.
* @private
*/
private launchBackgroundPollers(): void {
this.userDataPoller.start();
// The cache updater writes the current state of the feed to storage every few seconds
// to capture changes to the alreadyShown state of toots.
if (this.cacheUpdater) {
logger.trace(`cacheUpdater already exists, not starting another one`);
} else {
this.cacheUpdater = setInterval(
async () => await this.saveTimelineToCache(),
config.toots.saveChangesIntervalSeconds * 1000
);
}
}
/**
* Load cached data from {@linkcode Storage}. Called when the app is first opened and when
* {@linkcode TheAlgorithm.reset} is invoked.
* @private
* @returns {Promise<void>}
*/
private async loadCachedData(): Promise<void> {
this.homeFeed = await Storage.getCoerced<Toot>(CacheKey.HOME_TIMELINE_TOOTS);
this.feed = await Storage.getCoerced<Toot>(AlgorithmStorageKey.TIMELINE_TOOTS);
if (this.feed.length == config.toots.maxTimelineLength) {
const numToClear = config.toots.maxTimelineLength - config.toots.truncateFullTimelineToLength;
loadCacheLogger.info(`Timeline cache is full (${this.feed.length}), discarding ${numToClear} old toots`);
this.feed = truncateToLength(this.feed, config.toots.truncateFullTimelineToLength, logger);
await Storage.set(AlgorithmStorageKey.TIMELINE_TOOTS, this.feed);
}
this.trendingData = await Storage.getTrendingData();
this.filters = await Storage.getFilters() ?? buildNewFilterSettings();
await updateBooleanFilterOptions(this.filters, this.feed);
this.setTimelineInApp(this.feed);
loadCacheLogger.debugWithTraceObjs(`Loaded ${this.feed.length} cached toots + trendingData`, this.trendingData);
}
/**
* Apparently if the mutex lock is inside mergeTootsToFeed() then the state of {@linkcode TheAlgorithm.feed}
* is not consistent which can result in toots getting lost as threads try to merge {@linkcode newToots}
* into different {@linkcode TheAlgorithm.feed} states.
* Wrapping the entire function in a mutex seems to fix this (though i'm not sure why).
* @private
* @param {Toot[]} newToots - New toots to merge into this.feed
* @param {Logger} logger - Logger to use
* @returns {Promise<void>}
*/
private async lockedMergeToFeed(newToots: Toot[], logger: Logger): Promise<void> {
const hereLogger = logger.tempLogger('lockedMergeToFeed');
const releaseMutex = await lockExecution(this.mergeMutex, hereLogger);
try {
await this.mergeTootsToFeed(newToots, logger);
hereLogger.trace(`Merged ${newToots.length} newToots, released mutex`);
} finally {
releaseMutex();
}
};
/**
* Merge newToots into {@linkcode TheAlgorithm.feed}, score, and filter the feed.
* NOTE: Don't call this directly! Use {@linkcode TheAlgorithm.lockedMergeTootsToFeed} instead.
* @private
* @param {Toot[]} newToots - New toots to merge into this.feed
* @param {Logger} inLogger - Logger to use
* @returns {Promise<void>}
*/
private async mergeTootsToFeed(newToots: Toot[], inLogger: Logger): Promise<void> {
const hereLogger = inLogger.tempLogger('mergeTootsToFeed');
const numTootsBefore = this.feed.length;
const startedAt = new Date();
// Merge new Toots
this.feed = Toot.dedupeToots([...this.feed, ...newToots], hereLogger);
this.numUnscannedToots += newToots.length;
// Building filter options is expensive so we only do it when it's justifiable
if ((this.feed.length < config.toots.minToSkipFilterUpdates) || (this.numUnscannedToots > config.toots.filterUpdateBatchSize)) {
await updateBooleanFilterOptions(this.filters, this.feed);
this.numUnscannedToots = 0;
} else {
logger.trace(`Skipping filter update, feed length: ${this.feed.length}, unscanned toots: ${this.numUnscannedToots}`);
}
await this.scoreAndFilterFeed();
// Update loadingStatus and log telemetry
const statusMsgFxn = config.locale.messages[LoadAction.FEED_UPDATE];
this.loadingStatus = statusMsgFxn(this.feed, this.mostRecentHomeTootAt());
hereLogger.logTelemetry(`Merged ${newToots.length} new toots into ${numTootsBefore} timeline toots`, startedAt);
}
/**
* Recompute the scorers' computations based on user history etc. and trigger a rescore of the feed.
* @private
* @returns {Promise<void>}
*/
private async recomputeScores(): Promise<void> {
await ScorerCache.prepareScorers(true);
await this.scoreAndFilterFeed();
}
/**
* Release the loading mutex and reset the loading state variables.
* @private
* @param {LoadAction} logPrefix - Action for logging context.
* @returns {void}
*/
private releaseLoadingMutex(logPrefix: LoadAction): void {
this.loadingStatus = null;
if (this._releaseLoadingMutex) {
loggers[logPrefix].info(`Finished, releasing mutex...`);
this._releaseLoadingMutex();
} else {
loggers[logPrefix].warn(`releaseLoadingMutex() called but no mutex to release!`);
}
}
/**
* Score the feed, sort it, save it to storage, and call {@linkcode TheAlgorithm.filterFeedAndSetInApp}
* to update the feed in the app.
* @private
* @returns {Promise<Toot[]>} The filtered set of Toots (NOT the entire feed).
*/
private async scoreAndFilterFeed(): Promise<Toot[]> {
this.feed = await Scorer.scoreToots(this.feed, true);
this.feed = truncateToLength(
this.feed,
config.toots.maxTimelineLength,
logger.tempLogger('scoreAndFilterFeed()')
);
await Storage.set(AlgorithmStorageKey.TIMELINE_TOOTS, this.feed);
return this.filterFeedAndSetInApp();
}
/**
* Return true if we're in {@linkcode QUICK_MODE} and the feed is fresh enough that we don't
* need to retrieve any new data. Useful for testing UI changes without waiting
* for the full feed load every time.
* @private
* @returns {boolean} True if we should skip the feed update.
*/
private shouldSkip(): boolean {
const hereLogger = loggers[LoadAction.FEED_UPDATE];
hereLogger.debugWithTraceObjs(`${++this.numTriggers} triggers so far, state:`, this.statusDict());
let feedAgeInMinutes = this.mostRecentHomeTootAgeInSeconds();
if (feedAgeInMinutes) feedAgeInMinutes /= 60;
const maxAgeMinutes = config.minTrendingMinutesUntilStale();
if (isQuickMode && feedAgeInMinutes && feedAgeInMinutes < maxAgeMinutes && this.numTriggers <= 1) {
hereLogger.debug(`isQuickMode=${isQuickMode}, feed's ${feedAgeInMinutes.toFixed(0)}s old, skipping`);
// Needs to be called to update the feed in the app
ScorerCache.prepareScorers().then((_t) => this.filterFeedAndSetInApp());
return true;
} else {
return false;
}
}
/**
* Lock the mutex and set the {@linkcode TheAlgorithm.loadStartedAt} timestamp.
* @private
* @param {LoadAction} logPrefix - Action for logging context.
* @returns {Promise<void>}
* @throws {Error} If a load is already in progress.
*/
private async startAction(logPrefix: LoadAction): Promise<void> {
const hereLogger = loggers[logPrefix];
const status = config.locale.messages[logPrefix];
hereLogger.debugWithTraceObjs(`called`, this.statusDict());
if (this.isLoading) {
hereLogger.warn(`Load in progress already!`, this.statusDict());
throw new Error(config.locale.messages.isBusy);
}
this.loadStartedAt = new Date();
this._releaseLoadingMutex = await lockExecution(this.loadingMutex, logger);
this.loadingStatus = (typeof status === 'string') ? status : status(this.feed, this.mostRecentHomeTootAt());
}
/**
* Returns info about the state of this {@linkcode TheAlgorithm} instance.
* @private
* @returns {Record<string, unknown>} Status dictionary.
*/
private statusDict(): Record<string, unknown> {
const mostRecentTootAt = this.mostRecentHomeTootAt();
const oldestTootAt = earliestTootedAt(this.homeFeed);
let numHoursInHomeFeed: number | null = null;
if (mostRecentTootAt && oldestTootAt) {
numHoursInHomeFeed = AgeIn.hours(oldestTootAt, mostRecentTootAt);
}
return {
feedNumToots: this.feed.length,
homeFeedNumToots: this.homeFeed.length,
homeFeedMostRecentAt: toISOFormatIfExists(mostRecentTootAt),
homeFeedOldestAt: toISOFormatIfExists(oldestTootAt),
homeFeedTimespanHours: numHoursInHomeFeed ? Number(numHoursInHomeFeed.toPrecision(2)) : null,
isLoading: this.isLoading,
loadingStatus: this.loadingStatus,
loadStartedAt: toISOFormatIfExists(this.loadStartedAt),
minMaxScores: computeMinMax(this.feed, (toot) => toot.score),
};
}
///////////////////////////////
// Static Methods //
///////////////////////////////
/** True if {@linkcode FEDIALGO_DEBUG} environment var was set at run time. */
static get isDebugMode(): boolean { return isDebugMode };
/** True if {@linkcode FEDIALGO_DEEP_DEBUG} environment var was set at run time. */
static get isDeepDebug(): boolean { return isDeepDebug };
/** True if {@linkcode LOAD_TEST} environment var was set at run time. */
static get isLoadTest(): boolean { return isLoadTest };
/** True if {@linkcode QUICK_MODE} environment var was set at run time. */
static get isQuickMode(): boolean { return isQuickMode };
/**
* Dictionary of preset weight configurations that can be selected from to set weights.
* @returns {WeightPresets}
*/
static get weightPresets(): WeightPresets { return WEIGHT_PRESETS };
};
// Some strings we want to export from the config
const GET_FEED_BUSY_MSG = config.locale.messages[LoadAction.IS_BUSY];
const READY_TO_LOAD_MSG = config.locale.messages[LogAction.INITIAL_LOADING_STATUS];
// Export types and constants needed by apps using this package
export {
// Constants
DEFAULT_FONT_SIZE,
FILTER_OPTION_DATA_SOURCES,
FEDIALGO,
GET_FEED_BUSY_MSG,
GIFV,
READY_TO_LOAD_MSG,
VIDEO_TYPES,
// Classes
Account,
BooleanFilter,
Logger,
NumericFilter,
TagList,
Toot,
// Enums
BooleanFilterName,
MediaCategory,
NonScoreWeightName,
ScoreName,
TagTootsCategory,
TrendingType,
TypeFilterName,
WeightName,
// Helpers
AgeIn,
extractDomain,
isAccessTokenRevokedError,
isValueInStringEnum,
makeChunks,
makePercentileChunks, // TODO: unused in demo app (for now)
optionalSuffix,
sleep,
sortKeysByValue,
timeString,
// Types
type BooleanFilterOption,
type FeedFilterSettings,
type FilterOptionDataSource,
type KeysOfValueType,
type MastodonInstance,
type MinMaxAvgScore,
type ObjList,
type ScoreStats,
type StringNumberDict,
type TagWithUsageCounts,
type TrendingData,
type TrendingLink,
type TrendingObj,
type TrendingWithHistory,
type Weights,
};