diff --git a/lib/modules/accountSwitcher.js b/lib/modules/accountSwitcher.js index a989ae4284..89e0ad74ac 100644 --- a/lib/modules/accountSwitcher.js +++ b/lib/modules/accountSwitcher.js @@ -6,6 +6,7 @@ import { Alert, BodyClasses, addFloater, + currentSubreddit, formatDate, formatDateDiff, getUserInfo, @@ -54,6 +55,25 @@ module.options = { description: 'accountSwitcherAccountsDesc', title: 'accountSwitcherAccountsTitle', }, + autoswitch: { + title: 'accountSwitcherAutoswitchTitle', + dependsOn: options => options.accounts.value !== 'undefined', + description: 'accountSwitcherAutoswitchDesc', + type: 'table', + addRowText: '+add subreddit', + fields: [{ + key: 'account', + name: 'account', + type: 'select', + get values() { return autoswitchAccounts(); }, + value: '', + }, { + key: 'subreddit', + name: 'subreddit', + type: 'text', + }], + value: ([]: Array<[string, string]>), + }, updateOtherTabs: { type: 'boolean', description: 'accountSwitcherUpdateOtherTabsDesc', @@ -128,6 +148,30 @@ const accounts = once(() => }, {}), ); +const typedAccounts = once(() => + module.options.accounts.value.reduce((acc, v) => { + acc[v[0]] = { + text: v[0], + storedPassword: v[1], + requiresOtp: v[2], + }; + return acc; + }, {}), +); + +const autoswitchAccounts = () => { + /* $FlowIgnore[1] */ + let newObject; + // eslint-disable-next-line no-unused-vars + for (const k of Object.entries(typedAccounts())) { + newObject = Object.entries(typedAccounts()).map(([k]) => ({ + name: k, + value: k, + })); + } + return newObject; +}; + module.contentStart = () => { const downArrow = module.options.dropDownStyle.value === 'alien' ? string.html`` : @@ -164,6 +208,23 @@ module.contentStart = () => { else manageAccounts(); }, ); + + if (module.options.autoswitch.value.length > 0) { + module.options.autoswitch.value.forEach(async (_e, i) => { + const subreddit = currentSubreddit(); + const user = loggedInUser(); + if (typeof module.options.autoswitch.value[i][0] !== 'undefined' && module.options.autoswitch.value[i][1] === subreddit && module.options.autoswitch.value[i][0] !== user) { + BodyClasses.add('res-accountSwitcher-in-progress'); + try { + const username = module.options.autoswitch.value[i][0]; + await switchTo(username.toLowerCase()); + } catch (e) { + BodyClasses.remove('res-accountSwitcher-in-progress'); + console.error(e); + } + } + }); + } }; async function createAccountMenu() { diff --git a/locales/locales/en.json b/locales/locales/en.json index ee83b04370..ec64d8a86d 100644 --- a/locales/locales/en.json +++ b/locales/locales/en.json @@ -1761,6 +1761,12 @@ "accountSwitcherAccountsDesc": { "message": "Set your usernames and passwords below. They are only stored in RES preferences." }, + "accountSwitcherAutoswitchTitle": { + "message": "Autoswitch" + }, + "accountSwitcherAutoswitchDesc": { + "message": "Automatically switch accounts based on subreddits" + }, "accountSwitcherUpdateOtherTabsTitle": { "message": "Update Other Tabs" },