Skip to content

Commit

Permalink
Merge pull request #115 from nomandhoni-cs/develop
Browse files Browse the repository at this point in the history
testing new feature
  • Loading branch information
nomandhoni-cs authored Nov 27, 2024
2 parents 4b0b5f3 + ef64043 commit 4c89da3
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 84 deletions.
4 changes: 4 additions & 0 deletions src/components/ConfigDataLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ const ConfigDataLoader: React.FC = () => {
"usingStrictMode",
"false",
]);
await db.execute(`INSERT INTO config (key, value) VALUES (?, ?);`, [
"showPauseButton",
"false",
]);
console.log("Database initialized with default configuration.");
} else {
console.log("Database already exists. No action needed.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@ import Database from "@tauri-apps/plugin-sql";
interface ConfigRow {
value: string;
}
interface TogglePropsType {
functionalityButton: string;
title: string;
description: string;
}

const StrictModeToggle = () => {
const FunctionalitySwitchToggle = (props: TogglePropsType) => {
const [isStrictModeEnabled, setIsStrictModeEnabled] = useState(false);
const { functionalityButton, title, description } = props;

useEffect(() => {
const initializeStrictMode = async () => {
Expand All @@ -18,7 +24,7 @@ const StrictModeToggle = () => {

// Retrieve the 'usingStrictMode' value from the config table
const result: ConfigRow[] = await db.select(
"SELECT value FROM config WHERE key = 'usingStrictMode';"
`SELECT value FROM config WHERE key = '${functionalityButton}';`
);

if (result.length > 0) {
Expand All @@ -38,7 +44,7 @@ const StrictModeToggle = () => {
// Use an `INSERT OR REPLACE` or `UPDATE` query
await db.execute(
`
INSERT INTO config (key, value) VALUES ('usingStrictMode', ?)
INSERT INTO config (key, value) VALUES ('${functionalityButton}', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value;
`,
[checked ? "true" : "false"]
Expand All @@ -54,22 +60,20 @@ const StrictModeToggle = () => {
<div className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label
htmlFor="strictmode"
htmlFor={`${functionalityButton}`}
className="font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Use Strict Mode
{title}
</Label>
<p className="text-sm text-muted-foreground">
This will hide the 'Skip this time' button to force follow the break.
</p>
<p className="text-sm text-muted-foreground">{description}</p>
</div>
<Switch
id="strictmode"
id={`${functionalityButton}`}
checked={isStrictModeEnabled}
onCheckedChange={handleCheckboxChange}
/>
</div>
);
};

export default StrictModeToggle;
export default FunctionalitySwitchToggle;
77 changes: 32 additions & 45 deletions src/components/LicenseValidationComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@ import Database from "@tauri-apps/plugin-sql";
import toast from "react-hot-toast";
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { useLicenseKey } from "../hooks/useLicenseKey";
import { useTrigger } from "../contexts/TriggerReRender";

const LicenseValidationComponent: React.FC = () => {
const [licenseKey, setLicenseKey] = useState<string>("");
const [isDataLoaded, setIsDataLoaded] = useState(false); // Track loading status
const { licenseData, refreshLicenseData } = useLicenseKey();
const { triggerUpdate } = useTrigger();

// Function to check if a date is today
const isNotToday = (dateString: string): boolean => {
Expand All @@ -24,25 +21,21 @@ const LicenseValidationComponent: React.FC = () => {

useEffect(() => {
const validateLicense = async () => {
console.log("Running License Validator");
await refreshLicenseData(); // Ensure data is refreshed
setIsDataLoaded(true); // Mark data as loaded
};
validateLicense();
}, []);

useEffect(() => {
console.log(isNotToday("2024-11-27"), "is not Today");
if (
isDataLoaded &&
licenseData &&
isNotToday(licenseData.last_validated) // Add the new condition
) {
console.log(licenseData);
setLicenseKey(licenseData.license_key);
handleLicenseValidation(
licenseData.last_validated,
licenseData.status,
licenseData.license_key
);
}
Expand All @@ -51,7 +44,6 @@ const LicenseValidationComponent: React.FC = () => {
// Function to handle license validation and activation status
const handleLicenseValidation = async (
lastValidated: string,
status: string,
licenseKey: string
) => {
if (!licenseKey) {
Expand All @@ -76,41 +68,25 @@ const LicenseValidationComponent: React.FC = () => {

const data = await response.json();
console.log(data);

// Proceed only if store_id matches and data is valid
if (
(data.meta?.store_id === 134128 || data.meta?.store_id === 132851) &&
data.valid
) {
// If the license is valid and last validated is different from today
if (lastValidated !== today) {
await updateLicenseStatus(data.license_key.status);
await updateLastValidatedDate(today);
} else if (status !== data.license_key.status) {
// Update the status if it has changed
await updateLicenseStatus(data.license_key.status);
}
await updateLicenseStatus(data.license_key.status);
await updateLastValidatedDate(today);
} else if (
(data.meta?.store_id === 134128 || data.meta?.store_id === 132851) &&
!data.valid
) {
// If the license is invalid but store_id matches, update status
if (lastValidated !== today) {
// If the response is not ok, check the number of days since last validation
const diffInDays = getDateDiffInDays(lastValidated, today);
if (diffInDays > 7) {
// If more than 7 days, update status to what was received in the response
await updateLicenseStatus("disabled");
triggerUpdate();
} else {
// If less than 7 days, update status
await updateLicenseStatus(data.license_key.status);
}
return;
} else if (status !== data.license_key.status) {
// Update the status if it has changed
const diffInDays = getDateDiffInDays(lastValidated, today);
if (diffInDays > 7) {
// If more than 7 days, update status to what was received in the response
await updateLicenseStatus(data.license_key.status);
} else {
return;
}
return;
} else {
console.log(
"Store ID does not match required values. Validation skipped."
Expand All @@ -127,37 +103,48 @@ const LicenseValidationComponent: React.FC = () => {
return;
}
} catch (error) {
toast.error("Failed to validate license. Please try again.");
return error;
// toast.error("Failed to validate license. Please try again.");
}
};

// Function to update the license status in the database
const updateLicenseStatus = async (status: string) => {
const db = await Database.load("sqlite:blink_eye_license.db"); // Use the same db connection
if (db) {
await db.execute(
`
try {
// Update the status for the first row (where id = 1)
await db.execute(
`
UPDATE licenses
SET status = $1
WHERE license_key = $2`,
[status, licenseKey] // Update the status in the database
);
toast.success(`License status updated to ${status}`);
WHERE id = 1`,
[status] // Only update the status field
);
// toast.success(`License status updated to ${status}`);
} catch (error) {
console.error("Failed to update status:", error);
toast.error("Failed to update license status.");
}
}
};

// Function to update the last validated date in the database
const updateLastValidatedDate = async (today: string) => {
const db = await Database.load("sqlite:blink_eye_license.db"); // Use the same db connection
if (db) {
await db.execute(
`
try {
await db.execute(
`
UPDATE licenses
SET last_validated = $1
WHERE license_key = $2`,
[today, licenseKey] // Update the last validated date in the database
);
toast.success("License last validated date updated");
WHERE id = 1`,
[today]
);
} catch (error) {
console.error("Failed to update last validated date:", error);
toast.error("Failed to update license last validated date.");
}
}
};

Expand Down
5 changes: 2 additions & 3 deletions src/components/LoadingSpinner.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Loader2 } from "lucide-react";
import { Loader } from "lucide-react";

export function LoadingSpinner() {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<Loader2 className="h-12 w-12 animate-spin text-gray-500 mx-auto mb-4" />
<p className="text-gray-600 font-medium">Initializing application...</p>
<Loader className="h-8 w-8 animate-spin text-gray-300 dark:text-gray-700 mx-auto mb-4" />
</div>
</div>
);
Expand Down
13 changes: 11 additions & 2 deletions src/components/window/AllSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import AutoStartToggle from "../AutoStartToggle";
import StrictModeToggle from "../StrictModeToggle";
import FunctionalitySwitchToggle from "../FunctionalitySwitchToggle";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
Expand Down Expand Up @@ -72,7 +72,16 @@ const AllSettings = () => {
<div className="space-y-4">
<AutoStartToggle />
<PomodoroTimerToggle />
<StrictModeToggle />
<FunctionalitySwitchToggle
functionalityButton="usingStrictMode"
title=" Use Strict Mode"
description="This will hide the 'Skip this time' button to force follow the break."
/>
<FunctionalitySwitchToggle
functionalityButton="showPauseButton"
title="Hide pause button"
description="This will hide Pause button from the reminder screen to pause the reminder."
/>
<div className="rounded-lg border border-muted p-6 space-y-4">
{/* Input and Button Section */}
<div className="flex flex-col sm:flex-row sm:items-center sm:space-x-4">
Expand Down
70 changes: 48 additions & 22 deletions src/components/window/Reminder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { load } from "@tauri-apps/plugin-store";
import CurrentTime from "../CurrentTime";
import ScreenOnTime from "../ScreenOnTime";
import { CloudDownload } from "lucide-react";
import { CloudDownload, PauseIcon, Play } from "lucide-react";
import { Progress } from "../ui/progress";
import * as path from "@tauri-apps/api/path";
import { convertFileSrc } from "@tauri-apps/api/core";
Expand Down Expand Up @@ -39,6 +39,9 @@ const Reminder: React.FC = () => {
const [reminderDuration, setReminderDuration] = useState<number>(20);
const [reminderText, setStoredReminderText] = useState<string>("");
const [isUsingStictMode, setIsUsingStrictMode] = useState<boolean>(false);
const [isShowingPauseButton, setIsShowingPauseButton] =
useState<boolean>(false);
const [isPaused, setIsPaused] = useState<boolean>(false);

useEffect(() => {
const fetchReminderScreenInfo = async () => {
Expand Down Expand Up @@ -90,6 +93,13 @@ const Reminder: React.FC = () => {
if (strictModeResult.length > 0) {
setIsUsingStrictMode(strictModeResult[0].value === "true");
}
const pauseModeResult: ConfigRow[] = await db.select(
"SELECT value FROM config WHERE key = 'showPauseButton';"
);

if (pauseModeResult.length > 0) {
setIsShowingPauseButton(pauseModeResult[0].value === "true");
}
};

fetchReminderScreenInfo();
Expand All @@ -107,20 +117,22 @@ const Reminder: React.FC = () => {
};

useEffect(() => {
if (timeLeft <= 1) {
if (timeLeft <= 1 && canAccessPremiumFeatures) {
handlePlayAudio();
}
if (timeLeft <= 0) {
appWindow.close();
return;
}

const timer = setInterval(() => {
setTimeLeft((prevTime) => prevTime - 1);
}, 1000);
if (!isPaused) {
const timer = setInterval(() => {
setTimeLeft((prevTime) => prevTime - 1);
}, 1000);

return () => clearInterval(timer);
}, [timeLeft]);
return () => clearInterval(timer);
}
}, [timeLeft, isPaused]);

const renderBackground = () => {
switch (backgroundStyle) {
Expand Down Expand Up @@ -168,22 +180,36 @@ const Reminder: React.FC = () => {
<div className="text-5xl font-semibold text-center px-4 pb-4">
{reminderText || "Look 20 feet far away to protect your eyes."}
</div>
{!isUsingStictMode && (
<Button
onClick={() => appWindow.close()}
className="bg-[#FE4C55] rounded-full hover:bg-[#e9464e] text-base px-6 space-x-2 flex items-center transform transition-transform hover:scale-105"
>
<span className="text-base">Skip this Time</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="h-6 w-6"
<div className="flex space-x-4">
{!isUsingStictMode && (
<Button
onClick={() => appWindow.close()}
className="bg-[#FE4C55] rounded-full hover:bg-[#e9464e] text-base px-6 space-x-2 flex items-center transform transition-transform hover:scale-105"
>
<span className="text-base">Skip this Time</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="h-6 w-6"
>
<path d="M5.055 7.06C3.805 6.347 2.25 7.25 2.25 8.69v8.122c0 1.44 1.555 2.343 2.805 1.628L12 14.471v2.34c0 1.44 1.555 2.343 2.805 1.628l7.108-4.061c1.26-.72 1.26-2.536 0-3.256l-7.108-4.061C13.555 6.346 12 7.249 12 8.689v2.34L5.055 7.061Z" />
</svg>
</Button>
)}
{!isShowingPauseButton && (
<Button
onClick={() => setIsPaused((prev) => !prev)}
className="bg-[#FE4C55] rounded-full hover:bg-[#e9464e] text-base items-center justify-center transform transition-transform hover:scale-105"
>
<path d="M5.055 7.06C3.805 6.347 2.25 7.25 2.25 8.69v8.122c0 1.44 1.555 2.343 2.805 1.628L12 14.471v2.34c0 1.44 1.555 2.343 2.805 1.628l7.108-4.061c1.26-.72 1.26-2.536 0-3.256l-7.108-4.061C13.555 6.346 12 7.249 12 8.689v2.34L5.055 7.061Z" />
</svg>
</Button>
)}
{isPaused ? (
<Play className="fill-current h-6 w-6" />
) : (
<PauseIcon className="fill-current h-6 w-6" />
)}
</Button>
)}
</div>
</div>
<Toaster />
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/window/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import toast from "react-hot-toast";
import { useTrigger } from "../../contexts/TriggerReRender";

const Settings = () => {
const { triggerUpdate } = useTrigger(); // Access triggerUpdate from the context
const { triggerUpdate } = useTrigger();
const [interval, setInterval] = useState<number>(20);
const [duration, setDuration] = useState<number>(20);
const [reminderText, setReminderText] = useState<string>("");
Expand Down
Loading

0 comments on commit 4c89da3

Please sign in to comment.