Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add block win audio base on tiers #1533

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

MCozhusheck
Copy link
Collaborator

@MCozhusheck MCozhusheck commented Feb 17, 2025

Description

Implements #1514
Add multiple audio sources to the app that plays when user wins block or replays one from his wallet history. There is also notification sound that precedes before the main block win sound plays.

Motivation and Context

Give users audio feedback when new block is mined.

How Has This Been Tested?

build new glApp.js from this branch https://github.com/shanimal08/TARI_MINER_APP_VISUAL/pull/9
replace the glApp.js in public/assets/glApp.js

test sound when:

  • actually mined block (It is easier to do on esmeralda)
  • replay some win animation in wallet history

What process can a PR reviewer use to test or verify this change?

same as above

Breaking Changes

  • None
  • Requires data directory on base node to be deleted
  • Requires hard fork
  • Other - Please specify

Summary by CodeRabbit

  • New Features

    • Enhanced audio support now delivers real-time notification and success sounds.
    • Introduced an audio toggle in settings, letting users enable or disable audio feedback.
    • Expanded localization to include audio functionality across different languages.
    • Integrated event-driven audio playback for a more engaging user experience.
    • Added support for managing audio settings dynamically through the application interface.
    • New audio resources included in the application bundle.
  • Chores

    • Updated build configurations and dependencies to smooth the integration of audio features and resource management.

Copy link

coderabbitai bot commented Feb 17, 2025

📝 Walkthrough

Walkthrough

This pull request integrates comprehensive audio functionality into the application. It updates build configurations, adds audio elements in HTML, and introduces a new dependency. Localization files are enhanced with an "audio-enabled" entry, and Tauri configuration files are updated with new features, permissions, and resource entries. New backend commands, configuration fields, and UI components handle audio settings and playback. Additionally, type definitions and state management files receive updates to support the audio features.

Changes

File(s) Changed Change Summary
.github/workflows/release.yml Updated build arguments to include the "audio" feature in the Tauri build process.
index.html Added four new <audio> elements with unique IDs and sources for notification and success sounds.
package.json Added a new dependency: @tauri-apps/plugin-fs.
public/locales/.../settings.json (af, cn, de, en, fr, hi, id, ja, ko, pl, ru, tr) Added a new key "audio-enabled": "Audio enabled" to expand localization support.
src-tauri/Cargo.toml
src-tauri/capabilities/default.json
src-tauri/tauri.conf.json
Introduced new features (protocol-asset, audio), a dependency (tauri-plugin-fs), and added resource and permission entries for audio functionality.
src-tauri/src/app_config.rs
src-tauri/src/commands.rs
src-tauri/src/main.rs
Added audio_enabled field, new backend commands (is_audio_feature_enabled, set_audio_enabled, get_audio_enabled), integrated FS plugin, and removed an obsolete command.
src/App/AppEffects.tsx
src/containers/floating/Settings/sections/general/AudioSettings.tsx
src/containers/floating/Settings/sections/general/GeneralSettings.tsx
Updated UI components to fetch audio settings, initialize audio animations, and conditionally render an AudioSettings toggle component.
src/glApp.d.ts
src/types/app-status.ts
src/types/invoke.ts
Extended type definitions with the new initAudio method, added an audio_enabled property, and new invoke function signatures for audio control.
src/store/useAppConfigStore.ts
src/store/useBlockchainVisualisationStore.ts
Enhanced state management by adding functions to set/fetch audio settings and encapsulated audio playback logic based on success tiers.

Possibly related PRs

  • feat: block win sound and CSP #1497: Related changes that introduce audio playback functionality and modifications in audio file management, complementing the enhancements in this PR.

Suggested reviewers

  • brianp
  • peps
  • Misieq01
  • mmrrnn

Poem

I'm a bunny in code, hopping with delight,
Adding audio magic to brighten the night.
With toggles and sounds that play on cue,
Each line of code sings something new.
I dance through commits with whiskered glee,
Celebrating changes—oh, how fun it can be! 🐇

Hop, hop, code on!


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MCozhusheck MCozhusheck marked this pull request as ready for review February 17, 2025 15:38
@MCozhusheck MCozhusheck requested a review from a team as a code owner February 17, 2025 15:38
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (14)
src/containers/floating/Settings/sections/general/AudioSettings.tsx (2)

14-14: Consider adding fallback translation.

The useSuspense: false option prevents suspense during translation loading, but you should also consider adding a fallback text in case the translation fails to load.

-    const { t } = useTranslation(['settings'], { useSuspense: false });
+    const { t, ready } = useTranslation(['settings'], { useSuspense: false });
+    const audioEnabledText = ready ? t('audio-enabled') : 'Audio enabled';

21-34: Consider adding aria-label for accessibility.

The implementation looks good, but could be enhanced with accessibility attributes.

-                    <ToggleSwitch checked={audioEnabled} onChange={(event) => setAudioEnabled(event.target.checked)} />
+                    <ToggleSwitch 
+                        checked={audioEnabled} 
+                        onChange={(event) => setAudioEnabled(event.target.checked)}
+                        aria-label={t('audio-enabled')}
+                    />
src/glApp.d.ts (1)

27-27: Add JSDoc comments for better documentation.

The new method should be documented with parameter descriptions and example usage.

+    /**
+     * Initializes audio functionality with callback handlers.
+     * @param notificationCB - Callback function triggered for notification sounds
+     * @param blockWinCB - Callback function triggered when a block is won
+     * @param blockWinCB.tier - The tier level of the block win (1-3)
+     */
     initAudio: (notificationCB: () => void, blockWinCB: (tier: number) => void) => void;
src/store/useBlockchainVisualisationStore.ts (1)

56-67: Consider using an enum for success tiers.

Using an enum for success tiers would improve type safety and maintainability.

+enum SuccessTier {
+  Level1 = 1,
+  Level2 = 2,
+  Level3 = 3,
+}

-function selectAudioAssetOnSuccessTier(tier: number) {
+function selectAudioAssetOnSuccessTier(tier: SuccessTier) {
   switch (tier) {
-      case 1:
+      case SuccessTier.Level1:
         return 'assets/Success_Level_01.wav';
-      case 2:
+      case SuccessTier.Level2:
         return 'assets/Success_Level_02.wav';
-      case 3:
+      case SuccessTier.Level3:
         return 'assets/Success_Level_03.wav';
       default:
         throw new Error('Invalid tier');
   }
}
src-tauri/src/commands.rs (1)

1402-1426: Fix error message in telemetry logging.

The error message incorrectly refers to "get_audio_enabled" instead of "set_audio_enabled".

-                "error at sending telemetry data for get_audio_enabled {:?}",
+                "error at sending telemetry data for set_audio_enabled {:?}",
src-tauri/capabilities/default.json (1)

21-28: Consider scoping directory permission more precisely.

While the file permission is correctly scoped to block_win.mp3, the directory permission for the entire audio directory might be broader than necessary if only one audio file is needed.

If only block_win.mp3 is needed, you could remove the directory permission:

-        {
-            "identifier": "fs:allow-read-dir",
-            "allow": [{ "path": "$RESOURCE/audio" }]
-        }
public/locales/cn/settings.json (1)

7-7: Localization Entry for Audio Feature
The new key "audio-enabled": "Audio enabled" has been added to the Chinese localization file. Consider verifying whether the value should be translated—for example, to "音频已启用"—to better suit a native Chinese-speaking audience.

public/locales/ko/settings.json (1)

7-7: Localization Update for Audio Feature
The added key "audio-enabled": "Audio enabled" in the Korean locale file currently retains the English phrase. It may be worthwhile to check if a localized Korean translation would provide a more consistent user experience (for example, using an appropriate Korean phrase).

public/locales/ja/settings.json (1)

7-7: New Localization Key Added (Japanese).
The key "audio-enabled": "Audio enabled" has been added to support the new audio feature. Consider using a Japanese translation (e.g. "オーディオが有効") to maintain full localization consistency.

public/locales/tr/settings.json (1)

7-7: New Localization Key Added (Turkish).
The new key "audio-enabled": "Audio enabled" appears in the Turkish locale; however, it remains in English. For a consistent user experience, consider providing a Turkish translation (e.g. "Ses etkin").

public/locales/id/settings.json (1)

7-7: New Localization Key Added (Indonesian).
The key "audio-enabled": "Audio enabled" is now included for Indonesian users. To improve localization quality, you might consider translating it (e.g. "Audio diaktifkan").

public/locales/ru/settings.json (1)

7-7: New Localization Key Added (Russian).
The key "audio-enabled": "Audio enabled" has been added; consider translating it into Russian (for example, "Аудио включено") to enhance the localization.

public/locales/pl/settings.json (1)

7-7: New Audio Setting Entry Added
The key "audio-enabled": "Audio enabled" has been added for the Polish locale. Verify that the English phrasing is intentional for this locale; if a translated value is preferred for consistency with the rest of the file, consider updating it accordingly.

public/locales/de/settings.json (1)

7-7: New Audio Setting Entry in German Locale
A new entry "audio-enabled": "Audio enabled" has been introduced. Please confirm whether this English text is intentional for the German locale. If a localized translation is desired, you might consider using a phrase such as "Audio aktiviert".

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5414403 and 670e025.

⛔ Files ignored due to path filters (7)
  • package-lock.json is excluded by !**/package-lock.json
  • public/assets/Notification.wav is excluded by !**/*.wav
  • public/assets/Success_Level_01.wav is excluded by !**/*.wav
  • public/assets/Success_Level_02.wav is excluded by !**/*.wav
  • public/assets/Success_Level_03.wav is excluded by !**/*.wav
  • src-tauri/Cargo.lock is excluded by !**/*.lock
  • src-tauri/audio/block_win.mp3 is excluded by !**/*.mp3
📒 Files selected for processing (29)
  • .github/workflows/release.yml (1 hunks)
  • index.html (1 hunks)
  • package.json (1 hunks)
  • public/locales/af/settings.json (1 hunks)
  • public/locales/cn/settings.json (1 hunks)
  • public/locales/de/settings.json (1 hunks)
  • public/locales/en/settings.json (2 hunks)
  • public/locales/fr/settings.json (1 hunks)
  • public/locales/hi/settings.json (1 hunks)
  • public/locales/id/settings.json (1 hunks)
  • public/locales/ja/settings.json (1 hunks)
  • public/locales/ko/settings.json (1 hunks)
  • public/locales/pl/settings.json (1 hunks)
  • public/locales/ru/settings.json (1 hunks)
  • public/locales/tr/settings.json (2 hunks)
  • src-tauri/Cargo.toml (3 hunks)
  • src-tauri/capabilities/default.json (1 hunks)
  • src-tauri/src/app_config.rs (7 hunks)
  • src-tauri/src/commands.rs (3 hunks)
  • src-tauri/src/main.rs (2 hunks)
  • src-tauri/tauri.conf.json (4 hunks)
  • src/App/AppEffects.tsx (2 hunks)
  • src/containers/floating/Settings/sections/general/AudioSettings.tsx (1 hunks)
  • src/containers/floating/Settings/sections/general/GeneralSettings.tsx (2 hunks)
  • src/glApp.d.ts (1 hunks)
  • src/store/useAppConfigStore.ts (3 hunks)
  • src/store/useBlockchainVisualisationStore.ts (3 hunks)
  • src/types/app-status.ts (1 hunks)
  • src/types/invoke.ts (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • public/locales/fr/settings.json
  • public/locales/af/settings.json
  • public/locales/hi/settings.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: tauri-build
  • GitHub Check: cargo checks (fmt, clippy, check)
🔇 Additional comments (18)
src/containers/floating/Settings/sections/general/AudioSettings.tsx (1)

16-19: LGTM! Clean state management implementation.

Good use of selector function to minimize re-renders by only subscribing to required state.

src/types/invoke.ts (1)

99-101: LGTM!

The new function signatures for audio-related features are well-defined and follow the existing pattern in the file.

src/types/app-status.ts (1)

51-51: LGTM!

The new audio_enabled property is correctly typed and well-placed within the AppConfig interface.

src/store/useAppConfigStore.ts (1)

42-44: LGTM!

The audio settings implementation follows the established patterns in the codebase:

  • Proper state management with initial values
  • Error handling with state rollback
  • Clear separation of concerns between feature flag and user preference

Also applies to: 74-74, 79-79, 313-321, 324-327

src-tauri/src/app_config.rs (2)

120-121: LGTM! Audio configuration field added.

The audio_enabled field is properly added with serde serialization and appropriate default value.


551-559: LGTM! Audio configuration methods implemented.

The getter and setter methods are well-implemented, following the established pattern in the file and ensuring proper error handling.

src-tauri/src/main.rs (2)

1069-1069: LGTM! File system plugin initialization added.

The tauri_plugin_fs is properly initialized in the application builder.


1293-1296: LGTM! Audio-related commands added to invoke handler.

The new audio-related commands are properly registered in the invoke handler.

src-tauri/src/commands.rs (2)

247-250: LGTM! Feature flag check implemented.

Simple and effective implementation to check if the audio feature is enabled.


1396-1400: LGTM! Audio enabled getter implemented.

Clean implementation following the established pattern of other getters in the file.

package.json (1)

22-22: New Dependency Addition for Tauri FS Plugin
The addition of "@tauri-apps/plugin-fs": "^2.2.0" is in line with the PR’s objective to support audio functionality through enhanced file system operations. The specified version is consistent with the project’s other Tauri dependencies.

src-tauri/tauri.conf.json (2)

34-35: Bundling the Audio Resource and Updater Artifacts
The new "createUpdaterArtifacts": "v1Compatible" entry and the inclusion of "resources": ["audio/block_win.mp3"] ensure that the audio asset is correctly bundled with the application. This setup facilitates proper deployment of the new audio feature.


53-56: Asset Protocol Configuration for Audio
By adding the "assetProtocol": { "enable": true, "scope": ["$RESOURCE/audio"] } block, you are enabling secure and scoped access to audio resources. Please ensure that testing covers scenarios where the asset is retrieved via the asset protocol.

src-tauri/Cargo.toml (3)

71-79: Enable Protocol-Asset Feature in Tauri Dependency
Introducing the "protocol-asset" feature in the Tauri dependency is a robust approach to extend asset handling capabilities. This enhancement directly supports the integration of audio features and aligns well with existing dependency configurations.


100-102: Inclusion of Tauri Plugin FS Dependency
The addition of tauri-plugin-fs = "2" is essential for advanced file system interactions needed for managing audio assets. This dependency complements the corresponding JavaScript plugin added in package.json and solidifies the underlying architecture for audio operations.


130-130: New Audio Feature Flag
The new feature flag "audio = []" in the [features] section provides modular control over the audio functionality during builds. This approach supports feature toggling and maintains flexibility for different build environments.

public/locales/en/settings.json (1)

7-7: New Localization Key Added (English).
The key "audio-enabled": "Audio enabled" is correctly added in the English locale. The text is clear and appropriate for English users.

.github/workflows/release.yml (1)

236-236: Include Audio Feature in Build Arguments
The build arguments have been updated to include the "audio" feature, now using:

args: ${{ matrix.args }} --features "audio ${{ env.TS_FEATURES }}"

This change aligns with the new audio functionality. Please verify that concatenating "audio ${{ env.TS_FEATURES }}" behaves correctly, particularly if TS_FEATURES might ever be empty.

Comment on lines 28 to +31
await fetchAppConfig();
await fetchAudioFeatureEnabled();
await setMiningNetwork();
initAnimationAudio();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for initialization sequence.

The initialization sequence should handle potential failures gracefully.

-            await fetchAppConfig();
-            await fetchAudioFeatureEnabled();
-            await setMiningNetwork();
-            initAnimationAudio();
+            try {
+                await fetchAppConfig();
+                await fetchAudioFeatureEnabled();
+                await setMiningNetwork();
+                initAnimationAudio();
+            } catch (error) {
+                console.error('Failed to initialize app:', error);
+                // Consider showing a user-friendly error message
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await fetchAppConfig();
await fetchAudioFeatureEnabled();
await setMiningNetwork();
initAnimationAudio();
try {
await fetchAppConfig();
await fetchAudioFeatureEnabled();
await setMiningNetwork();
initAnimationAudio();
} catch (error) {
console.error('Failed to initialize app:', error);
// Consider showing a user-friendly error message
}


export const GeneralSettings = () => {
const isAudioFeatureEnabled = useAppConfigStore.getState().isAudioFeatureEnabled;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using store selector hook instead of direct state access.

Using getState() directly might miss updates. Consider using the hook pattern for consistency.

-    const isAudioFeatureEnabled = useAppConfigStore.getState().isAudioFeatureEnabled;
+    const isAudioFeatureEnabled = useAppConfigStore(state => state.isAudioFeatureEnabled);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const isAudioFeatureEnabled = useAppConfigStore.getState().isAudioFeatureEnabled;
const isAudioFeatureEnabled = useAppConfigStore(state => state.isAudioFeatureEnabled);

Comment on lines 92 to 113
const playAudio = async (eleId: string, track: string) => {
try {
const { audio_enabled, isAudioFeatureEnabled } = useAppConfigStore.getState();
if (!audio_enabled || !isAudioFeatureEnabled) {
return;
}

const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
const blockWinAudioElement = document.getElementById(eleId) as HTMLAudioElement;
if (blockWinAudioElement) {
blockWinAudioElement.setAttribute('src', blobUrl); // Rquired to make it work on an AppImage bundle
}

if (blockWinAudioElement.currentTime !== 0) return;
blockWinAudioElement.onended = () => {
blockWinAudioElement.currentTime = 0;
};
blockWinAudioElement.play();
} catch (err) {
console.error(`Failed to play block win sound: ${err}`);
}
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix issues in the audio playback logic.

  1. Fix the typo in the comment: "Rquired" -> "Required".
  2. Add cleanup for the blob URL to prevent memory leaks.
  3. Add error handling for missing audio elements.
 const playAudio = async (eleId: string, track: string) => {
   try {
     const { audio_enabled, isAudioFeatureEnabled } = useAppConfigStore.getState();
     if (!audio_enabled || !isAudioFeatureEnabled) {
       return;
     }

-    const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
     const blockWinAudioElement = document.getElementById(eleId) as HTMLAudioElement;
+    if (!blockWinAudioElement) {
+      throw new Error(`Audio element with id ${eleId} not found`);
+    }
+
+    const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
     if (blockWinAudioElement) {
-      blockWinAudioElement.setAttribute('src', blobUrl); // Rquired to make it work on an AppImage bundle
+      blockWinAudioElement.setAttribute('src', blobUrl); // Required to make it work on an AppImage bundle
     }

     if (blockWinAudioElement.currentTime !== 0) return;
     blockWinAudioElement.onended = () => {
       blockWinAudioElement.currentTime = 0;
+      URL.revokeObjectURL(blobUrl);
     };
     blockWinAudioElement.play();
   } catch (err) {
     console.error(`Failed to play block win sound: ${err}`);
   }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const playAudio = async (eleId: string, track: string) => {
try {
const { audio_enabled, isAudioFeatureEnabled } = useAppConfigStore.getState();
if (!audio_enabled || !isAudioFeatureEnabled) {
return;
}
const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
const blockWinAudioElement = document.getElementById(eleId) as HTMLAudioElement;
if (blockWinAudioElement) {
blockWinAudioElement.setAttribute('src', blobUrl); // Rquired to make it work on an AppImage bundle
}
if (blockWinAudioElement.currentTime !== 0) return;
blockWinAudioElement.onended = () => {
blockWinAudioElement.currentTime = 0;
};
blockWinAudioElement.play();
} catch (err) {
console.error(`Failed to play block win sound: ${err}`);
}
};
const playAudio = async (eleId: string, track: string) => {
try {
const { audio_enabled, isAudioFeatureEnabled } = useAppConfigStore.getState();
if (!audio_enabled || !isAudioFeatureEnabled) {
return;
}
const blockWinAudioElement = document.getElementById(eleId) as HTMLAudioElement;
if (!blockWinAudioElement) {
throw new Error(`Audio element with id ${eleId} not found`);
}
const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
blockWinAudioElement.setAttribute('src', blobUrl); // Required to make it work on an AppImage bundle
if (blockWinAudioElement.currentTime !== 0) return;
blockWinAudioElement.onended = () => {
blockWinAudioElement.currentTime = 0;
URL.revokeObjectURL(blobUrl);
};
blockWinAudioElement.play();
} catch (err) {
console.error(`Failed to play block win sound: ${err}`);
}
};

index.html Outdated
Comment on lines 195 to 207

<audio id="notification-player" preload="auto">
<source src="/assets/Notification.wav" type="audio/mpeg" />
</audio>
<audio id="success1-player" preload="auto">
<source src="/assets/Success_Level_01.wav" type="audio/mpeg" />
</audio>
<audio id="success2-player" preload="auto">
<source src="/assets/Success_Level_02.wav" type="audio/mpeg" />
</audio>
<audio id="success3-player" preload="auto">
<source src="/assets/Success_Level_03.wav" type="audio/mpeg" />
</audio>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Audio Elements Implementation – MIME Type Mismatch
Four new <audio> elements have been added for notification and success sounds. However, each <source> tag specifies type="audio/mpeg" while the file extensions are .wav. For WAV files, the correct MIME type is typically "audio/wav". Please update the MIME types to ensure proper playback across browsers.

Suggested Diff:

-            <audio id="notification-player" preload="auto">
-                <source src="/assets/Notification.wav" type="audio/mpeg" />
-            </audio>
-            <audio id="success1-player" preload="auto">
-                <source src="/assets/Success_Level_01.wav" type="audio/mpeg" />
-            </audio>
-            <audio id="success2-player" preload="auto">
-                <source src="/assets/Success_Level_02.wav" type="audio/mpeg" />
-            </audio>
-            <audio id="success3-player" preload="auto">
-                <source src="/assets/Success_Level_03.wav" type="audio/mpeg" />
-            </audio>
+            <audio id="notification-player" preload="auto">
+                <source src="/assets/Notification.wav" type="audio/wav" />
+            </audio>
+            <audio id="success1-player" preload="auto">
+                <source src="/assets/Success_Level_01.wav" type="audio/wav" />
+            </audio>
+            <audio id="success2-player" preload="auto">
+                <source src="/assets/Success_Level_02.wav" type="audio/wav" />
+            </audio>
+            <audio id="success3-player" preload="auto">
+                <source src="/assets/Success_Level_03.wav" type="audio/wav" />
+            </audio>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<audio id="notification-player" preload="auto">
<source src="/assets/Notification.wav" type="audio/mpeg" />
</audio>
<audio id="success1-player" preload="auto">
<source src="/assets/Success_Level_01.wav" type="audio/mpeg" />
</audio>
<audio id="success2-player" preload="auto">
<source src="/assets/Success_Level_02.wav" type="audio/mpeg" />
</audio>
<audio id="success3-player" preload="auto">
<source src="/assets/Success_Level_03.wav" type="audio/mpeg" />
</audio>
<audio id="notification-player" preload="auto">
<source src="/assets/Notification.wav" type="audio/wav" />
</audio>
<audio id="success1-player" preload="auto">
<source src="/assets/Success_Level_01.wav" type="audio/wav" />
</audio>
<audio id="success2-player" preload="auto">
<source src="/assets/Success_Level_02.wav" type="audio/wav" />
</audio>
<audio id="success3-player" preload="auto">
<source src="/assets/Success_Level_03.wav" type="audio/wav" />
</audio>

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/App/AppEffects.tsx (1)

28-31: ⚠️ Potential issue

Add error handling for initialization sequence.

The initialization sequence should handle potential failures gracefully.

Apply this diff to improve error handling:

-            await fetchAppConfig();
-            await fetchAudioFeatureEnabled();
-            await setMiningNetwork();
-            initAnimationAudio();
+            try {
+                await fetchAppConfig();
+                await fetchAudioFeatureEnabled();
+                await setMiningNetwork();
+                initAnimationAudio();
+            } catch (error) {
+                console.error('Failed to initialize app:', error);
+                // Consider showing a user-friendly error message
+            }
src/store/useBlockchainVisualisationStore.ts (1)

92-118: ⚠️ Potential issue

Fix issues in the audio playback logic.

Apply this diff to fix the issues:

 const playAudio = async (eleId: string, track: string) => {
   try {
     const { audio_enabled, isAudioFeatureEnabled } = useAppConfigStore.getState();
     if (!audio_enabled || !isAudioFeatureEnabled) {
       return;
     }

-    const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
     const blockWinAudioElement = document.getElementById(eleId) as HTMLAudioElement;
+    if (!blockWinAudioElement) {
+      throw new Error(`Audio element with id ${eleId} not found`);
+    }
+
+    const blobUrl = URL.createObjectURL(await fetch(track).then((res) => res.blob()));
     if (blockWinAudioElement) {
-      blockWinAudioElement.setAttribute('src', blobUrl); // Rquired to make it work on an AppImage bundle
+      blockWinAudioElement.setAttribute('src', blobUrl); // Required to make it work on an AppImage bundle
     }

     if (blockWinAudioElement.currentTime !== 0) return;
     blockWinAudioElement.onended = () => {
       blockWinAudioElement.currentTime = 0;
+      URL.revokeObjectURL(blobUrl);
     };
     blockWinAudioElement.play();
   } catch (err) {
     console.error(`Failed to play block win sound: ${err}`);
   }
 };
🧹 Nitpick comments (3)
src/App/AppEffects.tsx (1)

33-33: Enhance error logging.

The current error logging could be more descriptive to aid in debugging.

Apply this diff to improve error logging:

-        void initialize().catch((e) => console.error('Failed to initialize UI config: ', e));
+        void initialize().catch((e) => {
+            const errorMessage = e instanceof Error ? e.message : String(e);
+            console.error(`Failed to initialize UI config: ${errorMessage}`, {
+                stack: e instanceof Error ? e.stack : undefined,
+                cause: e instanceof Error ? e.cause : undefined
+            });
+        });
src/store/useBlockchainVisualisationStore.ts (2)

56-80: Consider using an enum for audio tiers.

The current implementation uses magic numbers for tiers. Using an enum would improve type safety and maintainability.

Add this enum at the beginning of the file:

enum AudioTier {
    Level1 = 1,
    Level2 = 2,
    Level3 = 3
}

Then update the functions:

-function selectAudioAssetOnSuccessTier(tier: number) {
+function selectAudioAssetOnSuccessTier(tier: AudioTier) {
     switch (tier) {
-        case 1:
+        case AudioTier.Level1:
             return 'assets/Success_Level_01.wav';
-        case 2:
+        case AudioTier.Level2:
             return 'assets/Success_Level_02.wav';
-        case 3:
+        case AudioTier.Level3:
             return 'assets/Success_Level_03.wav';
         default:
             throw new Error('Invalid tier');
     }
 }

-function getAudioElementId(tier: number) {
+function getAudioElementId(tier: AudioTier) {
     switch (tier) {
-        case 1:
+        case AudioTier.Level1:
             return 'success1-player';
-        case 2:
+        case AudioTier.Level2:
             return 'success2-player';
-        case 3:
+        case AudioTier.Level3:
             return 'success3-player';
         default:
             throw new Error('Invalid tier');
     }
 }

124-153: Add debouncing for audio playback in win handler.

Multiple rapid wins could cause audio playback issues. Consider adding debouncing to prevent overlapping sounds.

Add this utility at the beginning of the file:

import debounce from 'lodash/debounce';

const debouncedPlayAudio = debounce((tier: number) => {
    void playBlockWinAudio(tier);
}, 500, { leading: true, trailing: false });

Then update the win handler:

 const handleWin = async (coinbase_transaction: TransactionInfo, balance: WalletBalance, canAnimate: boolean) => {
     const blockHeight = Number(coinbase_transaction?.mined_in_block_height);
     const earnings = coinbase_transaction.amount;

     console.info(`Block #${blockHeight} mined! Earnings: ${earnings}`);
     const successTier = getSuccessTier(earnings);

     if (canAnimate) {
         useMiningStore.getState().setMiningControlsEnabled(false);

         setAnimationState(successTier);
+        debouncedPlayAudio(successTier);
         useBlockchainVisualisationStore.setState({ earnings });
         // ... rest of the code
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 670e025 and 1be818c.

📒 Files selected for processing (4)
  • index.html (1 hunks)
  • src/App/AppEffects.tsx (2 hunks)
  • src/containers/floating/Settings/sections/general/GeneralSettings.tsx (2 hunks)
  • src/store/useBlockchainVisualisationStore.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/containers/floating/Settings/sections/general/GeneralSettings.tsx
  • index.html
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: tauri-build
  • GitHub Check: cargo checks (fmt, clippy, check)
  • GitHub Check: Check signed commits
  • GitHub Check: Check i18n

Comment on lines +120 to +122
export const initAnimationAudio = () => {
window.glApp.initAudio(playNotificationAudio, (tier: number) => playBlockWinAudio(tier));
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for audio initialization.

The initAnimationAudio function should handle potential initialization failures.

Apply this diff to improve error handling:

 export const initAnimationAudio = () => {
+    if (typeof window.glApp?.initAudio !== 'function') {
+        console.error('Audio initialization failed: window.glApp.initAudio is not available');
+        return;
+    }
     window.glApp.initAudio(playNotificationAudio, (tier: number) => playBlockWinAudio(tier));
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const initAnimationAudio = () => {
window.glApp.initAudio(playNotificationAudio, (tier: number) => playBlockWinAudio(tier));
};
export const initAnimationAudio = () => {
if (typeof window.glApp?.initAudio !== 'function') {
console.error('Audio initialization failed: window.glApp.initAudio is not available');
return;
}
window.glApp.initAudio(playNotificationAudio, (tier: number) => playBlockWinAudio(tier));
};

Comment on lines +82 to +90
async function playNotificationAudio() {
playAudio('notification-player', 'assets/Notification.wav');
}

async function playBlockWinAudio(successTier: number) {
const asset = selectAudioAssetOnSuccessTier(successTier);
const player = getAudioElementId(successTier);
playAudio(player, asset);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add retry logic for audio playback.

The audio playback functions should handle network failures gracefully.

Apply this diff to add retry logic:

+const MAX_RETRIES = 3;
+const RETRY_DELAY = 1000;

+async function retryWithDelay<T>(fn: () => Promise<T>, retries = MAX_RETRIES): Promise<T> {
+    try {
+        return await fn();
+    } catch (error) {
+        if (retries > 0) {
+            await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
+            return retryWithDelay(fn, retries - 1);
+        }
+        throw error;
+    }
+}

 async function playNotificationAudio() {
-    playAudio('notification-player', 'assets/Notification.wav');
+    await retryWithDelay(() => playAudio('notification-player', 'assets/Notification.wav'));
 }

 async function playBlockWinAudio(successTier: number) {
     const asset = selectAudioAssetOnSuccessTier(successTier);
     const player = getAudioElementId(successTier);
-    playAudio(player, asset);
+    await retryWithDelay(() => playAudio(player, asset));
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function playNotificationAudio() {
playAudio('notification-player', 'assets/Notification.wav');
}
async function playBlockWinAudio(successTier: number) {
const asset = selectAudioAssetOnSuccessTier(successTier);
const player = getAudioElementId(successTier);
playAudio(player, asset);
}
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
async function retryWithDelay<T>(fn: () => Promise<T>, retries = MAX_RETRIES): Promise<T> {
try {
return await fn();
} catch (error) {
if (retries > 0) {
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
return retryWithDelay(fn, retries - 1);
}
throw error;
}
}
async function playNotificationAudio() {
await retryWithDelay(() => playAudio('notification-player', 'assets/Notification.wav'));
}
async function playBlockWinAudio(successTier: number) {
const asset = selectAudioAssetOnSuccessTier(successTier);
const player = getAudioElementId(successTier);
await retryWithDelay(() => playAudio(player, asset));
}

Copy link
Collaborator

@shanimal08 shanimal08 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1be818c and bd633ca.

⛔ Files ignored due to path filters (2)
  • package-lock.json is excluded by !**/package-lock.json
  • src-tauri/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src-tauri/Cargo.toml (3 hunks)
  • src-tauri/src/main.rs (2 hunks)
  • src-tauri/tauri.conf.json (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • package.json
  • src-tauri/Cargo.toml
  • src-tauri/tauri.conf.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tauri-build
🔇 Additional comments (2)
src-tauri/src/main.rs (2)

1314-1314: Inconsistency with AI-generated summary.

The get_airdrop_tokens command is still present in the code, but the AI summary indicated it was removed.

Likely an incorrect or invalid review comment.


1315-1318: LGTM! Audio-related commands are properly integrated.

The new commands for audio functionality are well-organized and follow the existing command naming patterns.

@@ -1066,6 +1066,7 @@ fn main() {
};
let app_state_clone = app_state.clone();
let app = tauri::Builder::default()
.plugin(tauri_plugin_fs::init())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify file system permissions for audio files.

The addition of tauri_plugin_fs requires proper configuration of file system permissions to ensure secure access to audio files.

Run the following script to check the file system permissions configuration:


🏁 Script executed:

#!/bin/bash
# Description: Check file system permissions in Tauri configuration.

# Test: Search for file system permissions in capabilities configuration.
rg -A 5 "fs" src-tauri/capabilities/

Length of output: 614


Action Required: Update Inconsistent Command & Confirm Permission Scope

  • Verified that the Tauri capabilities configuration (in src-tauri/capabilities/default.json) includes proper file system permissions for audio files. The settings for "fs:allow-read-file" and "fs:allow-read-dir" correctly limit access to the audio directory/resource.
  • The get_airdrop_tokens command is still present (line 1314 in src-tauri/src/main.rs), which contradicts the AI summary that indicated its removal. Please review whether this command should be removed or if the summary needs updating.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants