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

Add rename function option to return activity ID from uploaded activity #89

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

Conversation

jat255
Copy link

@jat255 jat255 commented Jan 6, 2025

Resolves #88.

Not much to describe apart from the PR title.

I modified upload() to use Client.request to be able to access the "location" response header, which contains the URL needed to fetch the activity ID of the uploaded file. This is not returned initially when the file is uploaded, as it takes Garmin some time to process the activity. I implemented a simple polling process to check if the ID is ready, backing off by half a second with each try. If it doesn't return the value within 5 tries, it gives up.

The headers include with the rename() implementation are what I found to be the minimum required, but I'm not very experienced with the Garmin API, so maybe you have a better implementation.

I also edited the readme to describe the new functionality with a demo.

Summary by CodeRabbit

  • New Features
    • Added ability to retrieve Garmin Connect activity ID after uploading an activity.
    • Introduced method to rename activities on Garmin Connect.
  • Documentation
    • Updated README with new upload method usage and example code.
  • Improvements
    • Enhanced upload method with optional ID retrieval.
    • Implemented retry mechanism for fetching activity ID.
    • Noted potential delay in upload process due to server response time.

Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Walkthrough

The pull request introduces enhanced functionality for Garmin Connect activity management in the garth library. The changes focus on two main features: retrieving the internal activity ID after upload and renaming activities. The upload method now supports an optional return_id flag that allows users to obtain the Garmin-assigned activity identifier. A new rename method has been added to the Client class, enabling users to change the title of an uploaded activity directly through the library.

Changes

File Changes
README.md Updated upload method example to demonstrate return_id functionality
garth/http.py - Added return_id parameter to upload method
- Implemented ID retrieval mechanism with retry logic
- Added new rename method for changing activity titles

Assessment against linked issues

Objective Addressed Explanation
Support renaming activities [#88]
Retrieve activity ID after upload [#88]

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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.

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: 7

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 922f3c3 and 88abe86.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • garth/http.py (2 hunks)
🧰 Additional context used
🪛 Markdownlint (0.37.0)
README.md

315-315: Expected: 1; Actual: 2
Multiple consecutive blank lines

(MD012, no-multiple-blanks)


293-293: Expected: 80; Actual: 85
Line length

(MD013, line-length)

🔇 Additional comments (1)
garth/http.py (1)

188-192: 🧹 Nitpick (assertive)

Clarify the docstring for return_id.
The docstring is clear but might benefit from explicit mention of the five-attempt retry limit and half-second exponential backoff.

- (default: ``False``). This requires polling to see if Garmin
- Connect has finished processing the activity, so setting this
- option to ``True`` may introduce some delay
+ (default: ``False``). Setting ``True`` initiates a process that attempts 
+ to retrieve the Garmin Connect activity ID over up to five polls, 
+ each spaced out by an incremental half-second delay.

Likely invalid or redundant comment.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 88abe86 and 467c804.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • garth/http.py (2 hunks)
🧰 Additional context used
🪛 Markdownlint (0.37.0)
README.md

260-260: Expected: 80; Actual: 85
Line length

(MD013, line-length)

🔇 Additional comments (6)
garth/http.py (4)

4-4: Revisit selective import approach
A previous comment suggested that if you plan on using more functions from the time module, it might be consistent to just import time instead of only sleep; otherwise, importing just one function is fine.


188-192: Neat addition of the return_id parameter
The signature cleanly communicates the new functionality. No concerns; this looks great.


231-254: Handle unexpected status codes in ID retrieval loop
This loop only checks for 202 or 201. Consider explicitly handling 4xx or 5xx to provide clearer error messages when ID retrieval fails for other reasons (e.g., permission issues).


257-292: Offer a more informative error mechanism
Raising a generic GarthHTTPError on non-204 statuses is valid, but providing a custom exception or returning a status object can help users handle partial successes or parse more details efficiently.

README.md (2)

253-258: Good documentation of the new return_id feature
Adding these details clarifies how to retrieve the Garmin-internal activity ID. This is helpful for advanced usage.


294-317: Renaming workflow is clearly explained
The documentation nicely walks users through fetching the new ID and applying a rename. No issues.

@matin
Copy link
Owner

matin commented Mar 17, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

✅ Actions performed

Full review triggered.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 922f3c3 and 1008493.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • garth/http.py (2 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

260-260: Line length
Expected: 80; Actual: 85

(MD013, line-length)

🔇 Additional comments (6)
README.md (3)

263-267: Looks good overall.
The code snippet to demonstrate return_id=True is straightforward and aligns with the described workflow.


268-292: Clear and helpful example.
The sample JSON response effectively shows the structure for retrieving internalId; no issues found.


293-318: Renaming snippet is well-documented.
The explanation for fetching the ID and calling rename is concise and clear. No issues noted.

garth/http.py (3)

4-4: [Duplicate Comment] Consider importing the entire time module.
As previously mentioned, if you're likely to use other time functions, you might consider using import time and calling time.sleep(...) for consistency. Otherwise, keeping a single function-level import is also acceptable.


188-209: Documentation enhancement is solid.
The new docstring thoroughly explains the return_id parameter and potential wait time. Good job including the approximate delay.


262-297: Rename method looks fine.
The docstring is sufficient, and returning a 204 implies success. No critical concerns here.

Comment on lines +253 to +258
Using the `return_id` flag will make the code wait for Garmin to return
its internal identifier for the newly created activity, which can
be used for other methods such as renaming. The "internal ID" will
be contained within the resulting dictionary at
`result["detailedImportResult"]["successes"][0]["internalId"]`:

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider mentioning edge cases for empty successes array.
In practice, the "successes" array may be empty if Garmin fails to process the upload or if it’s still pending. It could be helpful to briefly clarify how users should handle a scenario in which "successes" is empty and no "internalId" is returned.

Comment on lines +259 to +262
> [!NOTE]
> Since this process waits for processing on the Garmin Connect server, be aware that
> it can make the upload process can take up to a few seconds longer than usual.

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Line length exceeds markdownlint's recommended limit.
Consider splitting this note into multiple lines to comply with the 80-character guideline:

-> Since this process waits for processing on the Garmin Connect server, be aware that
+> Since this process waits for processing on the Garmin Connect server,
+> be aware that
📝 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
> [!NOTE]
> Since this process waits for processing on the Garmin Connect server, be aware that
> it can make the upload process can take up to a few seconds longer than usual.
> [!NOTE]
> Since this process waits for processing on the Garmin Connect server,
> be aware that
> it can make the upload process can take up to a few seconds longer than usual.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

260-260: Line length
Expected: 80; Actual: 85

(MD013, line-length)

Comment on lines +236 to 260
if return_id:
tries = 0
# get internal activity ID from garmin connect, try five
# times with increasing waits (it takes some time for Garmin
# connect to return an ID)
while tries < 5:
wait = (tries + 1) * 0.5
sleep(wait)
if "location" in resp.headers:
id_resp = self.request(
"GET",
"connectapi",
resp.headers["location"].replace(
"https://connectapi.garmin.com",
"",
),
api=True
)
if id_resp.status_code == 202:
continue
elif id_resp.status_code == 201:
result["detailedImportResult"]["successes"] = \
id_resp.json()["detailedImportResult"]["successes"]
break
return result
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

No fallback if the ID remains unavailable after five tries.
If Garmin still hasn’t assigned an ID after five attempts, the code silently returns a result without the new "internalId". Consider throwing an exception or logging a warning to alert users that the upload may not be fully processed.

Comment on lines +220 to +235
resp = self.request(
"POST",
"connectapi",
path,
method="POST",
files=files,
)
assert result is not None, "No result from upload"
result = None if resp.status_code == 204 else resp.json()
if result is None:
raise GarthHTTPError(
msg=(
"Upload did not have expected status code of 204 "
f"(was: {resp.status_code})"
),
error=HTTPError(),
)

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

Potential confusion over status code check.
This block raises an error if resp.status_code is 204, yet the error message claims the upload “did not have expected status code of 204.” Verify whether 204 should indeed be an error or if it’s actually the expected success code. Otherwise, the error message may be misleading.

- if result is None:
-     raise GarthHTTPError(
-         msg=( "Upload did not have expected status code of 204 "
-               f"(was: {resp.status_code})" ),
-         error=HTTPError(),
-     )
+ # Re-check the intended status code expectations and revise accordingly.

Committable suggestion skipped: line range outside the PR's diff.

@matin matin self-requested a review March 17, 2025 23:33
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.

Renaming activities?
2 participants