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

Lectures: Fix lecture unit file attachment names #9721

Merged
merged 8 commits into from
Nov 10, 2024

Conversation

SimonEntholzer
Copy link
Contributor

@SimonEntholzer SimonEntholzer commented Nov 9, 2024

Checklist

General

  • I tested all changes and their related features with all corresponding user types on a test server.
  • This is a small issue that I tested locally and was confirmed by another developer on a test server.
  • I chose a title conforming to the naming conventions for pull requests.

Client

  • Important: I implemented the changes with a very good performance, prevented too many (unnecessary) REST calls and made sure the UI is responsive, even with large data (e.g. using paging).
  • I strictly followed the principle of data economy for all client-server REST calls.
  • I strictly followed the client coding and design guidelines.
  • I documented the TypeScript code using JSDoc style.

Motivation and Context

The file names in the lecture unit have long cryptic prefixes, which are not relevant for users:
image
When the user downloads the file, it's named like shown.
image

Description

This PR removes the prefix for the displayed name, and for the downloaded file.
image
image

Steps for Testing

Prerequisites:

  1. Create a lecture unit and add a file (with spaces)
  2. View the lecture unit, and download the file
  3. Make sure there is no 'Attachment_date' prefix

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Client

Class/File Line Coverage Confirmation (assert/expect)
lecture-attachments.component.ts 96.39% ✅ ❌
attachment-unit.component.ts 94.11% ✅ ❌
course-lecture-details.component.ts 98.61% ✅ ❌

Server

Class/File Line Coverage Confirmation (assert/expect)
AttachmentResource.java 99% ✅ ❌

Screenshots

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Improved file name readability for attachments by removing prefixes and replacing underscores with spaces.
    • Enhanced download functionality to ensure consistent formatting of file names and links.
    • Expanded icon support for various file types, improving visual representation in the interface.
  • Bug Fixes

    • Updated error handling during file deletions to manage exceptions related to attachment database entries.

These changes aim to provide a better user experience when handling and downloading attachment files.

@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Nov 9, 2024
@SimonEntholzer SimonEntholzer changed the title Fix attachment file name prefixes Lectures: Fix attachment file names Nov 9, 2024
@SimonEntholzer SimonEntholzer changed the title Lectures: Fix attachment file names Lectures: Fix lecture unit file attachment names Nov 9, 2024
@SimonEntholzer SimonEntholzer marked this pull request as ready for review November 9, 2024 16:15
@SimonEntholzer SimonEntholzer requested a review from a team as a code owner November 9, 2024 16:15
Copy link

coderabbitai bot commented Nov 9, 2024

Walkthrough

The changes in this pull request focus on enhancing file name handling and downloading functionality within the AttachmentUnitComponent class. A new private method, replaceAttachmentPrefixAndUnderscores, has been introduced to improve the readability of file names by removing specific prefixes and replacing underscores with spaces. This method is utilized in both the getFileName and handleDownload methods to ensure consistent formatting of file names and download links. The FileResource and AttachmentResource classes have also been modified to improve file handling and error management. Additionally, the test suite for the component has been updated to include new icon mappings for various file types.

Changes

File Change Summary
src/main/webapp/app/overview/course-lectures/attachment-unit/... - Modified AttachmentUnitComponent class to enhance file name handling and downloading functionality.
- Added private method replaceAttachmentPrefixAndUnderscores(link: string): string for processing file names.
- Updated getFileName and handleDownload methods to utilize the new method for consistent formatting.
src/test/javascript/spec/component/lecture-unit/attachment-unit/... - Expanded test suite for AttachmentUnitComponent to include additional FontAwesome icons for various file types.
- Updated test cases to verify correct icon mappings for new file extensions.
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java - Updated getLectureAttachment method to replace spaces in the filename parameter with underscores for better matching.
- Improved filename matching logic using endsWith method.
src/main/java/de/tum/cit/aet/artemis/lecture/web/AttachmentResource.java - Altered createAttachment and updateAttachment methods to change file-saving behavior by passing true instead of false.
- Added error handling for deleteAttachment method to catch RuntimeException.
src/main/webapp/app/lecture/lecture-attachments.component.ts - Modified downloadAttachment method to process downloadUrl through replaceLectureAttachmentPrefixAndUnderscores before passing to downloadFile.
src/main/webapp/app/shared/http/file.service.ts - Added methods replaceAttachmentPrefixAndUnderscores(link: string): string and replaceLectureAttachmentPrefixAndUnderscores(link: string): string for processing file names.
src/test/javascript/spec/helpers/mocks/service/mock-file.service.ts - Added mock methods replaceAttachmentPrefixAndUnderscores(link: string) and replaceLectureAttachmentPrefixAndUnderscores(link: string) in MockFileService.

Possibly related PRs

Suggested labels

ready for review, small

Suggested reviewers

  • JohannesStoehr
  • krusche
  • az108
  • HanyangXu0508

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 or @coderabbitai title 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

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

🧹 Outside diff range and nitpick comments (2)
src/main/webapp/app/overview/course-lectures/attachment-unit/attachment-unit.component.ts (2)

40-41: LGTM! Consider adding null check for better defensive programming.

The filename extraction logic is correct and aligns with the PR objective of cleaning up file names.

Consider adding a null check before substring operation:

-const filename = link.substring(link.lastIndexOf('/') + 1);
+const filename = link?.substring(link.lastIndexOf('/') + 1) ?? '';

59-65: Consider making the prefix pattern more maintainable and robust.

While the regex implementation works correctly, there are a few improvements that could make it more maintainable:

Consider these enhancements:

-private replaceAttachmentPrefixAndUnderscores(link: string): string {
-    return link.replace(/AttachmentUnit_\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}_/, '').replace(/_/g, ' ');
+private readonly ATTACHMENT_PREFIX_PATTERN = /AttachmentUnit_\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}_/;
+
+private replaceAttachmentPrefixAndUnderscores(link: string): string {
+    if (!link) return '';
+    return link
+        .replace(this.ATTACHMENT_PREFIX_PATTERN, '')
+        .replace(/_/g, ' ')
+        .trim();
}

Benefits:

  1. The regex pattern is now configurable and reusable
  2. Added null check for defensive programming
  3. Trim whitespace from the result
  4. Better readability with method chaining
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 64f95cd and b7c0bb4.

📒 Files selected for processing (1)
  • src/main/webapp/app/overview/course-lectures/attachment-unit/attachment-unit.component.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/webapp/app/overview/course-lectures/attachment-unit/attachment-unit.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

🔇 Additional comments (1)
src/main/webapp/app/overview/course-lectures/attachment-unit/attachment-unit.component.ts (1)

54-54: Verify safe handling of modified file paths in FileService.

While the filename cleanup improves user experience, we need to ensure that the FileService correctly handles the modified paths and maintains the proper mapping to actual files.

Let's check the FileService implementation:

✅ Verification successful

Based on the FileService implementation shown in the output, I can now generate the final response:

File path handling in FileService is secure and appropriate

The FileService's downloadFile method (lines 74-83) implements proper URL handling:

  • Splits the URL into components and handles the filename separately
  • Uses encodeURIComponent() on the filename part to safely encode special characters
  • Reconstructs the URL with proper encoding before initiating the download
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for FileService's downloadFile method implementation
ast-grep --pattern 'class FileService {
  $$$
  downloadFile($$$) {
    $$$
  }
  $$$
}'

# Look for any path handling or validation in FileService
rg -A 5 'class FileService'

Length of output: 12037

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 9, 2024
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: 0

🧹 Outside diff range and nitpick comments (2)
src/test/javascript/spec/component/lecture-unit/attachment-unit/attachment-unit.component.spec.ts (2)

98-104: LGTM! Icon mappings are comprehensive.

The test cases cover a good range of file types with appropriate icon mappings.

Consider adding test cases to verify the new file name formatting functionality mentioned in the PR objectives:

it('should remove prefix from file name', () => {
    component.lectureUnit().attachment!.name = 'prefix_test_file.pdf';
    fixture.detectChanges();
    expect(component.getFileName()).toBe('test file.pdf');
});

Based on the findings, I can now generate the final response since I've found the implementation of the prefix removal functionality in the component that needs test coverage.

Add test coverage for file name formatting functionality

The test file is missing coverage for the replaceAttachmentPrefixAndUnderscores functionality which:

  1. Removes timestamp prefixes matching pattern AttachmentUnit_YYYY-MM-DDThh-mm-ss-SSS_
  2. Replaces underscores with spaces

Add test cases like:

  • 'AttachmentUnit_2024-01-01T12-00-00-000_test_file.pdf''test file.pdf'
  • 'test_file.pdf''test file.pdf'
🔗 Analysis chain

Line range hint 1-143: Add test coverage for file name prefix removal.

While the test file is well-structured and follows best practices, it's missing coverage for the main PR objective - removing prefixes from file attachment names. Consider adding test cases to verify:

  1. Prefix removal from displayed file names
  2. Prefix removal from downloaded file names
  3. Underscore replacement in file names

Let me gather more information about the file name formatting functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any existing tests for file name formatting

# Test: Search for test cases related to file name formatting
rg -A 5 "getFileName|replaceAttachmentPrefixAndUnderscores" "src/test/javascript/spec"

Length of output: 4215


Script:

#!/bin/bash
# Search for the implementation of file name formatting in the component
ast-grep --pattern 'getFileName() {
  $$$
}'

# Search for any prefix removal or underscore replacement logic
rg -A 5 "replacePrefix|replaceUnderscores|replace.*Prefix|replace.*Underscore" "src"

Length of output: 3153

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b7c0bb4 and 5ebcfb2.

📒 Files selected for processing (1)
  • src/test/javascript/spec/component/lecture-unit/attachment-unit/attachment-unit.component.spec.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/test/javascript/spec/component/lecture-unit/attachment-unit/attachment-unit.component.spec.ts (1)

Pattern src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

🔇 Additional comments (1)
src/test/javascript/spec/component/lecture-unit/attachment-unit/attachment-unit.component.spec.ts (1)

12-25: LGTM! Icon imports are well-organized.

The FontAwesome icon imports follow best practices by using named imports and grouping related icons together.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 9, 2024
Copy link

@ItsaaaMeMario ItsaaaMeMario left a comment

Choose a reason for hiding this comment

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

Tested on TS1, I uploaded a PDF named 'Artemis 1 TEST PDF.pdf' and downloaded it via Artemis. The 'attachment_date' prefix is still visible.
Bildschirmfoto 2024-11-09 um 18 17 23

@SimonEntholzer
Copy link
Contributor Author

SimonEntholzer commented Nov 9, 2024

Tested on TS1, I uploaded a PDF named 'Artemis 1 TEST PDF.pdf' and downloaded it via Artemis. The 'attachment_date' prefix is still visible. Bildschirmfoto 2024-11-09 um 18 17 23

Ah I see, you're downloading it from the instructor's lecture attachment view. That's a different component, I'll fix it there too

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS1. Both the lecture unit and the lecture attachment worked as described

Screenshot 2024-11-09 210735
Screenshot 2024-11-09 210903

Copy link

@ahbitaqu ahbitaqu left a comment

Choose a reason for hiding this comment

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

[Tested on TS1]
works on both, lecture and attachment-unit. Re-approve

Copy link
Member

@BBesrour BBesrour left a comment

Choose a reason for hiding this comment

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

code lgtm

Copy link

⚠️ Unable to deploy to test servers ⚠️

The docker build needs to run through before deploying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix client Pull requests that update TypeScript code. (Added Automatically!) core Pull requests that affect the corresponding module deployment-error Added by deployment workflows if an error occured lecture Pull requests that affect the corresponding module server Pull requests that update Java code. (Added Automatically!) tests
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

6 participants