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

Dk2 sync logic and UI and other fixes #1105

Merged
merged 4 commits into from
Oct 18, 2024
Merged

Dk2 sync logic and UI and other fixes #1105

merged 4 commits into from
Oct 18, 2024

Conversation

mdmohsin7
Copy link
Collaborator

@mdmohsin7 mdmohsin7 commented Oct 18, 2024

  • Improve grouped mems ui (reported on instabug)
  • check for currentStorageFiles.length only while setting storage offset (v2.0.1 does not return the offset, only 2.0.2 does)
  • use separate variables to track current sdcard progress (tested on both 2.0.1 and 2.0.2)
  • reduce the tween end to 0.0 so that it flips right after pressing button

Summary by CodeRabbit

  • New Features

    • Enhanced memory display with improved tracking of non-discarded memories.
    • Updated progress tracking for SD card transfers, focusing on current metrics for better accuracy.
  • Bug Fixes

    • Improved responsiveness of the SD card transfer animation.
  • Refactor

    • Streamlined logic for storage management and data streaming in the capture provider.

@mdmohsin7 mdmohsin7 marked this pull request as ready for review October 18, 2024 16:24
Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on the MemoriesPage, SdCardCapturePage, and CaptureProvider classes. Key modifications include the addition of new properties to facilitate the tracking of non-discarded memories and updates to the UI components to enhance data presentation. The logic for progress tracking in the SD card transfer process has been refined to utilize current metrics, improving the responsiveness of the UI. Overall, the changes enhance the structure and clarity of the code while updating the functionality of memory and storage management.

Changes

File Path Change Summary
app/lib/pages/memories/page.dart Added hasNonDiscarded boolean variable to track non-discarded memories. Updated MemoriesGroupWidget constructor to include hasNonDiscardedMemories and isFirst parameters.
app/lib/pages/memories/widgets/memories_group_widget.dart Updated constructor and properties in MemoriesGroupWidget to accommodate new parameters for non-discarded memories and first index indication.
app/lib/pages/sdcard/page.dart Replaced Container with SizedBox for layout modification. Updated SdCardTransferProgress calculations to use current metrics for percentage and time remaining.
app/lib/pages/sdcard/sdcard_transfer_progress.dart Modified TweenAnimationBuilder condition to trigger animation on progress greater than 0.0 instead of 0.01.
app/lib/providers/capture_provider.dart Added properties for tracking currentTotalBytesReceived and currentSdCardSecondsReceived. Simplified storage file update logic and modified methods to enhance clarity and efficiency in handling storage management and data streaming.

Possibly related PRs

🐰 In a garden of memories, I hop and play,
With non-discarded tales brightening the day.
A widget so clever, with parameters anew,
Capturing moments, both old and true.
In progress we trust, as bytes dance in cheer,
Let’s celebrate changes, for memories are dear! 🌼✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (5)
app/lib/pages/memories/page.dart (1)

145-148: LGTM: Enhanced MemoriesGroupWidget with additional parameters

The updates to the MemoriesGroupWidget constructor improve the widget's ability to render based on its position and the presence of non-discarded memories. This aligns well with the PR objective of enhancing the Grouped MEMS UI.

Consider a minor readability improvement:

For better code readability, consider reordering the parameters to group related ones together:

 MemoriesGroupWidget(
   isFirst: index == 0,
   memories: memoriesForDate,
   date: date,
   hasNonDiscardedMemories: hasNonDiscarded,
   showDiscardedMemories: memoryProvider.showDiscardedMemories,
   hasDiscardedMemories: hasDiscarded,
+  // Reorder parameters
+  memories: memoriesForDate,
+  date: date,
+  isFirst: index == 0,
+  hasNonDiscardedMemories: hasNonDiscarded,
+  hasDiscardedMemories: hasDiscarded,
+  showDiscardedMemories: memoryProvider.showDiscardedMemories,
 ),

This grouping puts related parameters (memories and date) together, followed by boolean flags.

app/lib/pages/sdcard/page.dart (1)

59-69: LGTM! Consider adding comments for clarity.

The changes to the SdCardTransferProgress widget improve the accuracy of the progress tracking by using 'current' variables, which aligns with the PR objectives. This should provide a more precise representation of the ongoing transfer.

Consider adding brief comments to explain the significance of using currentTotalBytesReceived and currentSdCardSecondsReceived. This would help future developers understand the reasoning behind these specific variables.

For example:

// Use current variables for real-time progress tracking
displayPercentage: provider.totalStorageFileBytes == 0
    ? '0.0'
    : ((provider.currentTotalBytesReceived) / provider.totalStorageFileBytes * 100)
        .toStringAsFixed(2),
app/lib/pages/memories/widgets/memories_group_widget.dart (1)

12-13: Consider adding documentation for new properties.

The properties hasNonDiscardedMemories and isFirst have been added to the MemoriesGroupWidget class. It's advisable to include documentation comments (///) explaining their purpose and how they affect the widget's behavior.

app/lib/providers/capture_provider.dart (2)

692-692: Avoid using magic numbers; define constants for better readability

The calculation uses hard-coded numbers like 80.0, 100.0, and 2.2. Consider defining these as constants with descriptive names to improve code readability and maintainability.

Apply this diff:

+ const double CHUNK_SIZE = 80.0;
+ const double TOTAL_CHUNKS = 100.0;
+ const double DOWNLOAD_SPEED_FACTOR = 2.2;

- currentSdCardSecondsReceived = ((currentTotalBytesReceived.toDouble() / 80.0) / 100.0) * 2.2;
+ currentSdCardSecondsReceived = ((currentTotalBytesReceived.toDouble() / CHUNK_SIZE) / TOTAL_CHUNKS) * DOWNLOAD_SPEED_FACTOR;

Line range hint 610-710: Refactor the sendStorage method to improve readability

The sendStorage method is lengthy and contains complex nested logic. Consider breaking it down into smaller helper methods with descriptive names to enhance readability and maintainability.

For example, you can extract parts of the method into private helper methods like _handleValueLengthOne(), _handleLargeValueLength(), and _handleDisconnection().

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b6edad1 and 03730c6.

📒 Files selected for processing (5)
  • app/lib/pages/memories/page.dart (1 hunks)
  • app/lib/pages/memories/widgets/memories_group_widget.dart (1 hunks)
  • app/lib/pages/sdcard/page.dart (1 hunks)
  • app/lib/pages/sdcard/sdcard_transfer_progress.dart (1 hunks)
  • app/lib/providers/capture_provider.dart (5 hunks)
🧰 Additional context used
🔇 Additional comments (7)
app/lib/pages/sdcard/sdcard_transfer_progress.dart (1)

77-77: LGTM! Improved responsiveness for the flip animation.

This change lowers the threshold for triggering the flip animation from 1% progress to any progress greater than 0. This aligns perfectly with the PR objective of allowing an immediate flip effect right after the button is pressed. The modification enhances the responsiveness of the UI, providing a more immediate visual feedback to the user when the transfer begins.

app/lib/pages/memories/page.dart (2)

138-138: LGTM: Improved memory filtering logic

The addition of the hasNonDiscarded variable enhances the filtering logic for memories. This change aligns with the PR objective of improving the Grouped MEMS UI by providing a way to check for the presence of non-discarded memories.


138-148: Summary: Improved memory filtering and UI rendering logic

The changes in this file enhance the handling of discarded and non-discarded memories, directly addressing the PR objective of improving the Grouped MEMS UI. The introduction of the hasNonDiscarded variable and the updates to the MemoriesGroupWidget constructor provide more granular control over how memory groups are displayed.

These modifications should result in a more refined user interface, particularly in scenarios where both discarded and non-discarded memories are present. The changes are well-implemented and consistent with the overall goals of the pull request.

app/lib/pages/memories/widgets/memories_group_widget.dart (2)

29-32: Double-check the conditional logic for displaying DateListItem.

Ensure that the condition accurately reflects the intended behavior, especially when showDiscardedMemories is false, hasDiscardedMemories is true, and hasNonDiscardedMemories is false. Verify that the DateListItem is displayed or hidden as expected in all scenarios.


39-42: Verify the display logic for the bottom SizedBox.

Similar to the previous condition, confirm that the logic for rendering the bottom SizedBox aligns with the intended UI behavior. Ensure that the spacing is correctly applied or omitted based on the conditional checks.

app/lib/providers/capture_provider.dart (2)

651-654: Clarify the logic for incrementing currentTotalBytesReceived

When value.length == 83, currentTotalBytesReceived is incremented by 80; otherwise, it's incremented by value.length. This may lead to inconsistency if the additional 3 bytes are overhead or headers. Ensure that this logic accurately reflects the actual data received. Consider documenting why 80 is used in this calculation when value.length == 83.


572-572: Verify the initialization of currentSdCardSecondsReceived

currentSdCardSecondsReceived is reset to 0.0 here. Ensure that this aligns with the expected behavior for progress tracking and does not conflict with progress calculations elsewhere. Confirm that resetting this variable here is necessary.

Comment on lines +29 to +32
if (!showDiscardedMemories && hasDiscardedMemories && !hasNonDiscardedMemories)
const SizedBox.shrink()
else
const SizedBox.shrink(),
DateListItem(date: date, isFirst: isFirst),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider simplifying repeated conditional logic for better readability.

The condition if (!showDiscardedMemories && hasDiscardedMemories && !hasNonDiscardedMemories) is used multiple times. For improved readability and maintainability, consider extracting this condition into a helper method or a local variable with a meaningful name.

For example, you can introduce a helper method:

bool shouldHideGroup() {
  return !showDiscardedMemories && hasDiscardedMemories && !hasNonDiscardedMemories;
}

Then update the code as follows:

if (shouldHideGroup())
  const SizedBox.shrink()
else
  DateListItem(date: date, isFirst: isFirst),

And similarly for the bottom SizedBox:

if (shouldHideGroup())
  const SizedBox.shrink()
else
  const SizedBox(height: 16),

Also applies to: 39-42

Comment on lines +18 to +21
required this.hasNonDiscardedMemories,
required this.showDiscardedMemories,
required this.hasDiscardedMemories});
required this.hasDiscardedMemories,
required this.isFirst});
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing Required Parameters in MemoriesGroupWidget Instantiations

The following instances of MemoriesGroupWidget are missing one or more required parameters:

  • app/lib/pages/memories/widgets/memories_group_widget.dart:

    const MemoriesGroupWidget(
        {super.key,
        required this.memories,

    Missing parameters: hasNonDiscardedMemories, isFirst

  • app/lib/pages/memories/page.dart:

    MemoriesGroupWidget(
        isFirst: index == 0,
        memories: memoriesForDate,

    Missing parameter: hasNonDiscardedMemories

Please update these instantiations to include all required parameters to prevent potential compilation errors.

🔗 Analysis chain

Verify all usages of MemoriesGroupWidget are updated with new required parameters.

Since hasNonDiscardedMemories and isFirst are now required parameters in the constructor, ensure that all instances where MemoriesGroupWidget is instantiated have been updated to include these new parameters to prevent compilation errors.

You can run the following script to find instantiations that may be missing the new parameters:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all instances of MemoriesGroupWidget that may not include the new required parameters.

# Search for MemoriesGroupWidget instantiations not containing 'hasNonDiscardedMemories' or 'isFirst'.
rg --type dart 'MemoriesGroupWidget\(' | rg -v 'hasNonDiscardedMemories|isFirst'

Length of output: 249


Script:

#!/bin/bash
# Description: Retrieve lines containing MemoriesGroupWidget instantiations with surrounding context for review.

rg --context 2 --type dart 'MemoriesGroupWidget\(' app/lib/pages/memories/page.dart app/lib/pages/memories/widgets/memories_group_widget.dart

Length of output: 995

Comment on lines 523 to +524
currentStorageFiles = await _getStorageList(_recordingDevice!.id);
if (currentStorageFiles.isEmpty || currentStorageFiles.length < 2) {
if (currentStorageFiles.isEmpty) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Possible null pointer exception when accessing _recordingDevice

In the updateStorageList() method, _recordingDevice may be null, which would cause a null pointer exception when accessing _recordingDevice!.id. Consider adding a null check before using _recordingDevice.

Apply this diff to fix the issue:

+ if (_recordingDevice == null) {
+   debugPrint('No recording device connected');
+   return;
+ }
  currentStorageFiles = await _getStorageList(_recordingDevice!.id);
📝 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
currentStorageFiles = await _getStorageList(_recordingDevice!.id);
if (currentStorageFiles.isEmpty || currentStorageFiles.length < 2) {
if (currentStorageFiles.isEmpty) {
if (_recordingDevice == null) {
debugPrint('No recording device connected');
return;
}
currentStorageFiles = await _getStorageList(_recordingDevice!.id);
if (currentStorageFiles.isEmpty) {

Comment on lines +541 to +552
if (currentStorageFiles.isEmpty) {
debugPrint('No storage files found');
SharedPreferencesUtil().deviceIsV2 = false;
debugPrint('Device is not V2');

return;
}
SharedPreferencesUtil().deviceIsV2 = true;
debugPrint('Device is V2');
debugPrint('Device model name: ${_recordingDevice!.name}');
debugPrint('Storage files: $currentStorageFiles');
totalStorageFileBytes = currentStorageFiles[0];
var storageOffset = currentStorageFiles[1];
var storageOffset = currentStorageFiles.length < 2 ? 0 : currentStorageFiles[1];
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicated code for retrieving storage files

The logic for retrieving currentStorageFiles and handling cases when it's empty is duplicated in both updateStorageList() and initiateStorageBytesStreaming() methods. Consider extracting this logic into a shared private method to reduce code duplication and improve maintainability.

Apply this diff to refactor the code:

+ Future<bool> _retrieveAndValidateStorageFiles() async {
+   currentStorageFiles = await _getStorageList(_recordingDevice!.id);
+   if (currentStorageFiles.isEmpty) {
+     debugPrint('No storage files found');
+     SharedPreferencesUtil().deviceIsV2 = false;
+     debugPrint('Device is not V2');
+     return false;
+   }
+   return true;
+ }

  Future<void> updateStorageList() async {
+   if (_recordingDevice == null) {
+     debugPrint('No recording device connected');
+     return;
+   }
-   currentStorageFiles = await _getStorageList(_recordingDevice!.id);
-   if (currentStorageFiles.isEmpty) {
-     debugPrint('No storage files found');
-     SharedPreferencesUtil().deviceIsV2 = false;
-     debugPrint('Device is not V2');
-     return;
-   }
+   if (!await _retrieveAndValidateStorageFiles()) {
+     return;
+   }
    totalStorageFileBytes = currentStorageFiles[0];
    var storageOffset = currentStorageFiles.length < 2 ? 0 : currentStorageFiles[1];
    totalBytesReceived = storageOffset;
    notifyListeners();
  }

  Future<void> initiateStorageBytesStreaming() async {
    debugPrint('initiateStorageBytesStreaming');

    if (_recordingDevice == null) return;
-   currentStorageFiles = await _getStorageList(_recordingDevice!.id);
-   if (currentStorageFiles.isEmpty) {
-     debugPrint('No storage files found');
-     SharedPreferencesUtil().deviceIsV2 = false;
-     debugPrint('Device is not V2');
-     return;
-   }
+   if (!await _retrieveAndValidateStorageFiles()) {
+     return;
+   }
    SharedPreferencesUtil().deviceIsV2 = true;
    // ... rest of the code ...
  }

Committable suggestion was skipped due to low confidence.

@beastoin beastoin merged commit 44a99cf into main Oct 18, 2024
1 check passed
@beastoin beastoin deleted the dk2-sync-ui branch October 18, 2024 21:20
@beastoin
Copy link
Collaborator

lgtm 🥳

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