Skip to content

Commit

Permalink
Sidebar timer for OC 2. (#831)
Browse files Browse the repository at this point in the history
* Load organized crime data.

* Sidebar timer for OC 2.
  • Loading branch information
DeKleineKobini authored Jan 15, 2025
1 parent 53098bc commit 3d68b7e
Show file tree
Hide file tree
Showing 8 changed files with 181 additions and 7 deletions.
2 changes: 1 addition & 1 deletion extension/changelog.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": { "major": 7, "minor": 4, "build": 3 },
"title": "Beta",
"date": false,
"logs": { "features": [], "fixes": [], "changes": [], "removed": [] }
"logs": { "features": [{ "message": "Sidebar timer for OC 2.", "contributor": "DeKleineKobini" }], "fixes": [], "changes": [], "removed": [] }
},
{
"version": { "major": 7, "minor": 4, "build": 2 },
Expand Down
2 changes: 2 additions & 0 deletions extension/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
"exclude_matches": ["https://www.torn.com/logout.php*", "https://www.torn.com/loader.php?sid=attack&*"],
"css": [
"scripts/features/oc-time/ttOCTime.css",
"scripts/features/oc2-time/ttOC2Time.css",
"scripts/features/faction-oc-time/ttFactionOCTime.css",
"scripts/features/custom-links/ttCustomLinks.css",
"scripts/features/update-notice/ttUpdateNotice.css",
Expand All @@ -193,6 +194,7 @@
"resources/images/svg-icons/back.js",
"scripts/features/hide-level-upgrade/ttHideLevelUpgrade.js",
"scripts/features/oc-time/ttOCTime.js",
"scripts/features/oc2-time/ttOC2Time.js",
"scripts/features/faction-oc-time/ttFactionOCTime.js",
"scripts/features/jobpoints-tooltip/ttJobPointsToolTip.js",
"scripts/features/company-addiction/ttCompanyAddiction.js",
Expand Down
15 changes: 15 additions & 0 deletions extension/pages/settings/settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,13 @@ <h2>
<input id="api_usage-user_properties" type="checkbox" />
<label for="api_usage-user_properties">Properties</label>
</div>

<div class="header">User Selections V2</div>
<div class="note">Disabling certain selections will silently disable certain features that rely on that api selection.</div>
<div class="option">
<input id="api_usage-userV2_organizedcrime" type="checkbox" />
<label for="api_usage-userV2_organizedcrime">Organized Crime</label>
</div>
</section>
<section name="chat">
<div class="header">Chat</div>
Expand Down Expand Up @@ -482,6 +489,14 @@ <h2>
<input id="sidebar-ocTimer" type="checkbox" />
<label for="sidebar-ocTimer">Show OC ready time in sidebar.</label>
</div>
<div class="option no-mobile">
<input id="sidebar-oc2Timer" type="checkbox" />
<label for="sidebar-oc2Timer">Show OC 2.0 ready time in sidebar.</label>
</div>
<div class="option tabbed no-mobile">
<input id="sidebar-oc2TimerPosition" type="checkbox" />
<label for="sidebar-oc2TimerPosition">Include the crime and position.</label>
</div>
<div class="option no-mobile">
<input id="sidebar-factionOCTimer" type="checkbox" />
<label for="sidebar-factionOCTimer">Show your Faction's next OC ready time in sidebar.</label>
Expand Down
4 changes: 2 additions & 2 deletions extension/pages/settings/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,7 @@ async function setupPreferences(requireCleanup) {
_preferences.find("#api_usage-essential").value = settings.apiUsage.delayEssential;
_preferences.find("#api_usage-basic").value = settings.apiUsage.delayBasic;
_preferences.find("#api_usage-stakeouts").value = settings.apiUsage.delayStakeouts;
for (const type of ["user"]) {
for (const type of ["user", "userV2"]) {
for (const selection in settings.apiUsage[type]) {
if (_preferences.find(`#api_usage-${type}_${selection}`))
_preferences.find(`#api_usage-${type}_${selection}`).checked = settings.apiUsage[type][selection];
Expand Down Expand Up @@ -1071,7 +1071,7 @@ async function setupPreferences(requireCleanup) {
settings.apiUsage.delayEssential = parseInt(_preferences.find("#api_usage-essential").value);
settings.apiUsage.delayBasic = parseInt(_preferences.find("#api_usage-basic").value);
settings.apiUsage.delayStakeouts = parseInt(_preferences.find("#api_usage-stakeouts").value);
for (const type of ["user"]) {
for (const type of ["user", "userV2"]) {
for (const selection in settings.apiUsage[type]) {
if (_preferences.find(`#api_usage-${type}_${selection}`))
settings.apiUsage[type][selection] = _preferences.find(`#api_usage-${type}_${selection}`).checked;
Expand Down
31 changes: 27 additions & 4 deletions extension/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,7 @@ async function updateUserdata() {
!hasTimePassed(userdata?.last_action?.timestamp * 1000, TO_MILLIS.MINUTES * 5)));

const selections = [];
const selectionsV2 = [];
if (updateEssential) {
selections.push("profile", "timestamp");

Expand Down Expand Up @@ -529,6 +530,11 @@ async function updateUserdata() {

selections.push(selection);
}
for (const selection of ["organizedcrime"]) {
if (!settings.apiUsage.userV2[selection]) continue;

selectionsV2.push(selection);
}

if (settings.apiUsage.user.education && !hasFinishedEducation()) selections.push("education");

Expand All @@ -540,10 +546,16 @@ async function updateUserdata() {
updatedTypes.push("attack history");
}
console.log("Time elapsed:", Date.now() - userdata.date);
if (!selections.length) return { updated: false };
if (!selections.length && !selectionsV2.length) return { updated: false };

const oldUserdata = { ...userdata };
userdata = await fetchData("torn", { section: "user", selections });
const newUserdata = selections.length ? await fetchData("torn", { section: "user", selections }) : {};
const newUserdataV2 = selectionsV2.length ? await fetchData("tornv2", { section: "user", selections: selectionsV2 }) : {};

userdata = {
...newUserdata,
...newUserdataV2,
};
if (!userdata || !Object.keys(userdata).length) throw new Error("Aborted updating due to an unexpected response.");
userdata.date = now;
userdata.dateBasic = updateBasic ? now : (oldUserdata?.dateBasic ?? now);
Expand All @@ -560,7 +572,13 @@ async function updateUserdata() {
if (newEventsCount < 0) newEventsCount = userdata?.notifications?.events ?? 0;
else if (newEventsCount > 0) {
const category = newEventsCount <= 25 ? "newevents" : "events";
userdata.events = (await fetchData("torn", { section: "user", selections: [category], params: { limit: newEventsCount } })).events;
userdata.events = (
await fetchData("torn", {
section: "user",
selections: [category],
params: { limit: newEventsCount },
})
).events;
selections.push(category);
}
}
Expand Down Expand Up @@ -1297,7 +1315,12 @@ async function updateFactionStakeouts() {
const oldData = factionStakeouts[factionId]?.info ?? false;
let data;
try {
data = await fetchData("torn", { section: "faction", selections: ["basic", "chain"], id: factionId, silent: true });
data = await fetchData("torn", {
section: "faction",
selections: ["basic", "chain"],
id: factionId,
silent: true,
});
if (!data) {
console.log("Unexpected result during faction stakeout updating.");
failed++;
Expand Down
14 changes: 14 additions & 0 deletions extension/scripts/features/oc2-time/ttOC2Time.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.tt-sidebar-information .title {
font-weight: bold;
text-decoration: none;
color: inherit;
margin: inherit;
}

.tt-sidebar-information .countdown.short {
color: var(--tt-color-red);
}

.tt-sidebar-information .countdown.medium {
color: var(--tt-color-orange);
}
101 changes: 101 additions & 0 deletions extension/scripts/features/oc2-time/ttOC2Time.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"use strict";

(async () => {
const { hasSidebar } = await checkDevice();
if (!hasSidebar) return "Not supported on mobiles or tablets!";

featureManager.registerFeature(
"OC2 Time",
"sidebar",
() => settings.pages.sidebar.oc2Timer && (userdata?.faction?.faction_id > 0 ?? false),
null,
showTimer,
removeTimer,
{
storage: ["settings.pages.sidebar.oc2Timer", "settings.pages.sidebar.oc2TimerPosition", "userdata.organizedCrime"],
},
() => {
if (!hasAPIData()) return "No API access.";
else if (!userdata.organizedCrime) return "No OC data (still on OC 1?).";
}
);

async function showTimer() {
await requireSidebar();

removeTimer();
addInformationSection();
showInformationSection();

const elements = [];

const inCrime = ["Recruiting", "Planning"].includes(userdata.organizedCrime.status);
if (inCrime) {
elements.push(buildTimeLeftElement());
if (settings.pages.sidebar.oc2TimerPosition) {
elements.push(document.newElement({ type: "span", class: "countdown", text: " - " }));
elements.push(buildPositionElement());
}
} else {
elements.push(document.newElement({ type: "span", class: "countdown", text: "No crime joined." }));
}

document.find(".tt-sidebar-information").appendChild(
document.newElement({
type: "section",
id: "oc2Timer",
children: [document.newElement({ type: "a", class: "title", text: "OC: ", href: LINKS.organizedCrimes }), ...elements],
})
);
}

function buildTimeLeftElement() {
const timeLeftElement = document.newElement({ type: "span", class: "countdown" });

const readyAt = userdata.organizedCrime.ready_at * 1000;
const timeLeft = readyAt - Date.now();

if (timeLeft <= TO_MILLIS.HOURS * 8) timeLeftElement.classList.add("short");
else if (timeLeft <= TO_MILLIS.HOURS * 12) timeLeftElement.classList.add("medium");

if (timeLeft > 0) {
const formatOptions = { type: "wordTimer", extraShort: true, showDays: true, truncateSeconds: true };
timeLeftElement.textContent = formatTime({ milliseconds: timeLeft }, formatOptions);

timeLeftElement.dataset.end = readyAt;
timeLeftElement.dataset.timeSettings = JSON.stringify(formatOptions);
countdownTimers.push(timeLeftElement);
} else {
timeLeftElement.textContent = `Ready ${userdata.organizedCrime.status}`;
}

return timeLeftElement;
}

function buildPositionElement() {
// const position = userdata.organizedCrime.slots.find(({ user_id }) => user_id === userdata.user_id)?.position ?? "???";
const position = userdata.organizedCrime.slots.find(({ user_id }) => user_id === 1043377)?.position ?? "???";
const name = userdata.organizedCrime.name;
const level = userdata.organizedCrime.difficulty;

return document.newElement({ type: "span", class: "position", text: `${position} in ${name} (Lvl ${level})` });
}

function removeTimer() {
document.find("#oc2Timer")?.remove();
}

function addInformationSection() {
if (document.find(".tt-sidebar-information")) return;

const parent = document.find("#sidebarroot div[class*='user-information_'] div[class*='toggle-content_'] div[class*='content_']");

parent.appendChild(document.newElement({ type: "hr", class: "tt-sidebar-information-divider tt-delimiter tt-hidden" }));
parent.appendChild(document.newElement({ type: "div", class: "tt-sidebar-information tt-hidden" }));
}

function showInformationSection() {
document.find(".tt-sidebar-information-divider").classList.remove("tt-hidden");
document.find(".tt-sidebar-information").classList.remove("tt-hidden");
}
})();
19 changes: 19 additions & 0 deletions extension/scripts/global/globalData.js
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,9 @@ const DEFAULT_STORAGE = {
weaponexp: new DefaultSetting({ type: "boolean", defaultValue: true }),
properties: new DefaultSetting({ type: "boolean", defaultValue: true }),
},
userV2: {
organizedcrime: new DefaultSetting({ type: "boolean", defaultValue: true }),
},
},
themes: {
pages: new DefaultSetting({ type: "string", defaultValue: "default" }),
Expand Down Expand Up @@ -435,6 +438,8 @@ const DEFAULT_STORAGE = {
highlightEnergy: new DefaultSetting({ type: "boolean", defaultValue: true }),
highlightNerve: new DefaultSetting({ type: "boolean", defaultValue: false }),
ocTimer: new DefaultSetting({ type: "boolean", defaultValue: true }),
oc2Timer: new DefaultSetting({ type: "boolean", defaultValue: true }),
oc2TimerPosition: new DefaultSetting({ type: "boolean", defaultValue: true }),
factionOCTimer: new DefaultSetting({ type: "boolean", defaultValue: false }),
collapseAreas: new DefaultSetting({ type: "boolean", defaultValue: true }),
settingsLink: new DefaultSetting({ type: "boolean", defaultValue: true }),
Expand Down Expand Up @@ -1057,6 +1062,20 @@ const API_USAGE = {
color: true,
until: true,
},
organizedCrime: {
created_at: false,
difficulty: true,
executed_at: false,
expired_at: false,
id: false,
initiated_at: false,
name: true,
planning_at: false,
ready_at: true,
rewards: false,
slots: true,
status: false,
},
travel: {
destination: true,
method: true,
Expand Down

0 comments on commit 3d68b7e

Please sign in to comment.