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

Communication: Fix broken link when referencing a lecture attachment in a post #10164

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

PaRangger
Copy link
Contributor

@PaRangger PaRangger commented Jan 17, 2025

Checklist

General

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 client coding and design guidelines.
  • Following the theming guidelines, I specified colors only in the theming variable files and checked that the changes look consistent in both the light and the dark theme.
  • I documented the TypeScript code using JSDoc style.
  • I added multiple screenshots/screencasts of my UI changes.

Motivation and Context

Currently, when referencing a lecture attachment in the markdown editor and creating a post, clicking the link results in a 404 error. However, the attachment itself is functional and accessible within the lecture.

Addresses #9943

Description

I changed the behaviour of generating the link so that it matches the behaviour inside the lecture. With this future posts will not run into the same issue when referencing lecture attachments.

If you rename the attachment after posting it will still break the link. We are currently working on a general update for uploaded files in #9970 and beyond.

Steps for Testing

Prerequisites:

  • 1 Student/Tutor/Instructor
  • 1 Course with communication enabled
  • 1 Lecture with atleast one published attachment (Manage Course -> Lectures -> Select Lecture -> Attachments)
  1. Log in to Artemis
  2. Navigate to course
  3. Navigate to the communication tab
  4. Select a channel
  5. Write a post and reference a lecture attachment
  6. Click on the lecture attachment reference
  7. Observe that it shows the proper attachment and no 404 error

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)
file.service.ts 100%
posting-markdown-editor.component.ts 83.33%
lecture-attachment-reference.action.ts 100%

Screenshots

Previous behaviour:
392764413-fb71289d-ae9e-424d-bfbf-101a69408d76

Summary by CodeRabbit

  • New Features

    • Enhanced file attachment handling with a new method for creating attachment file URLs
    • Improved URL generation for file downloads with more flexible options
  • Refactor

    • Modularized file URL creation logic across multiple components
    • Updated dependency injection to include FileService in relevant components
  • Tests

    • Added mock implementations and updated test cases to support new file handling functionality

@PaRangger PaRangger added client Pull requests that update TypeScript code. (Added Automatically!) communication Pull requests that affect the corresponding module labels Jan 17, 2025
@PaRangger PaRangger self-assigned this Jan 17, 2025
@github-actions github-actions bot added tests and removed communication Pull requests that affect the corresponding module labels Jan 17, 2025
@PaRangger PaRangger temporarily deployed to artemis-test4.artemis.cit.tum.de January 17, 2025 14:48 — with GitHub Actions Inactive
@PaRangger PaRangger marked this pull request as ready for review January 17, 2025 15:01
@PaRangger PaRangger requested a review from a team as a code owner January 17, 2025 15:01
Copy link

coderabbitai bot commented Jan 17, 2025

Walkthrough

The pull request introduces a new method createAttachmentFileUrl in the FileService class to improve file URL handling across multiple components. The changes involve modifying the LectureAttachmentReferenceAction, PostingMarkdownEditorComponent, and associated test files to incorporate this new method. The primary goal is to centralize and standardize the process of creating attachment file URLs, enhancing code modularity and maintainability.

Changes

File Change Summary
src/main/webapp/app/shared/http/file.service.ts Added createAttachmentFileUrl method for constructing attachment download URLs
src/main/webapp/app/shared/metis/posting-markdown-editor/posting-markdown-editor.component.ts Injected FileService and updated LectureAttachmentReferenceAction constructor
src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts Added FileService dependency and updated attachment link processing
src/test/javascript/spec/component/shared/metis/postings-markdown-editor/postings-markdown-editor.component.spec.ts Updated test setup to include FileService and mock implementation
src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts Added FileService to test configuration
src/test/javascript/spec/helpers/mocks/service/mock-file.service.ts Added mock implementation of createAttachmentFileUrl method

Sequence Diagram

sequenceDiagram
    participant Component as PostingMarkdownEditor
    participant Action as LectureAttachmentReferenceAction
    participant Service as FileService
    
    Component->>Action: Create with FileService
    Action->>Service: Request attachment file URL
    Service-->>Action: Return normalized URL
    Action->>Action: Process lecture attachments
Loading

Possibly related PRs

Suggested labels

bugfix, ready to merge, component:Communication, core

Suggested reviewers

  • HawKhiem
  • SimonEntholzer
  • florian-glombik
  • kevinfischer4
  • sachmii
  • Feras797

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

🧹 Nitpick comments (2)
src/main/webapp/app/shared/http/file.service.ts (1)

83-89: Add input validation to prevent potential errors.

The method should validate input parameters to prevent runtime errors.

Apply this diff to add input validation:

 createAttachmentFileUrl(downloadUrl: string, downloadName: string, encodeName: boolean) {
+    if (!downloadUrl || !downloadName) {
+        throw new Error('Download URL and name are required');
+    }
     const downloadUrlComponents = downloadUrl.split('/');
-    // take the last element
-    const extension = downloadUrlComponents.pop()!.split('.').pop();
+    const fileName = downloadUrlComponents.pop();
+    if (!fileName) {
+        throw new Error('Invalid download URL format');
+    }
+    const extension = fileName.split('.').pop();
+    if (!extension) {
+        throw new Error('File extension not found in URL');
+    }
     const restOfUrl = downloadUrlComponents.join('/');
     const encodedDownloadName = encodeName ? encodeURIComponent(downloadName + '.' + extension) : downloadName + '.' + extension;
     return restOfUrl + '/' + encodedDownloadName;
 }
src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts (1)

50-71: Add error handling for attachment processing.

The attachment processing logic should handle potential errors and provide meaningful feedback.

Apply this diff to improve error handling:

 .map((lecture) => {
-    let attachmentCopy = cloneDeep(lecture.attachments);
+    try {
+        let attachmentCopy = cloneDeep(lecture.attachments);
 
-    if (attachmentCopy) {
-        attachmentCopy = attachmentCopy.map((attachment) => {
-            if (attachment.link && attachment.name) {
-                attachment.link = this.fileService.createAttachmentFileUrl(attachment.link!, attachment.name!, false);
-            }
+        if (attachmentCopy) {
+            attachmentCopy = attachmentCopy.map((attachment) => {
+                try {
+                    if (attachment.link && attachment.name) {
+                        attachment.link = this.fileService.createAttachmentFileUrl(attachment.link!, attachment.name!, false);
+                    }
+                } catch (error) {
+                    console.error(`Failed to process attachment ${attachment.name}: ${error}`);
+                }
+                return attachment;
+            });
+        }
 
-            return attachment;
-        });
-    } else {
+        return {
+            id: lecture.id!,
+            title: lecture.title!,
+            attachmentUnits: lecture.lectureUnits?.filter((unit) => unit.type === LectureUnitType.ATTACHMENT),
+            attachments: attachmentCopy,
+        };
+    } catch (error) {
+        console.error(`Failed to process lecture ${lecture.title}: ${error}`);
         attachmentCopy = lecture.attachments;
-    }
-
-    return {
-        id: lecture.id!,
-        title: lecture.title!,
-        attachmentUnits: lecture.lectureUnits?.filter((unit) => unit.type === LectureUnitType.ATTACHMENT),
-        attachments: attachmentCopy,
-    };
+        return {
+            id: lecture.id!,
+            title: lecture.title!,
+            attachmentUnits: lecture.lectureUnits?.filter((unit) => unit.type === LectureUnitType.ATTACHMENT),
+            attachments: attachmentCopy,
+        };
+    }
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5941797 and b4ff379.

📒 Files selected for processing (6)
  • src/main/webapp/app/shared/http/file.service.ts (1 hunks)
  • src/main/webapp/app/shared/metis/posting-markdown-editor/posting-markdown-editor.component.ts (3 hunks)
  • src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.ts (2 hunks)
  • src/test/javascript/spec/component/shared/metis/postings-markdown-editor/postings-markdown-editor.component.spec.ts (5 hunks)
  • src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts (4 hunks)
  • src/test/javascript/spec/helpers/mocks/service/mock-file.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
src/test/javascript/spec/helpers/mocks/service/mock-file.service.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}}

src/main/webapp/app/shared/http/file.service.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

src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.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}}

src/test/javascript/spec/component/shared/metis/postings-markdown-editor/postings-markdown-editor.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}}

src/main/webapp/app/shared/metis/posting-markdown-editor/posting-markdown-editor.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

src/main/webapp/app/shared/monaco-editor/model/actions/communication/lecture-attachment-reference.action.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

📓 Learnings (1)
src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts (1)
Learnt from: pzdr7
PR: ls1intum/Artemis#9407
File: src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts:46-46
Timestamp: 2024-11-12T12:51:40.391Z
Learning: In integration tests, it's acceptable to import the actual `MonacoEditorComponent` instead of mocking it.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: server-tests-postgres
  • GitHub Check: server-tests-mysql
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (13)
src/main/webapp/app/shared/http/file.service.ts (1)

70-74: LGTM! Method refactored to use the new URL creation logic.

The refactoring improves code reusability by utilizing the new createAttachmentFileUrl method.

src/main/webapp/app/shared/metis/posting-markdown-editor/posting-markdown-editor.component.ts (2)

68-68: LGTM! Proper dependency injection and usage.

The FileService is correctly injected and properly passed to LectureAttachmentReferenceAction.

Also applies to: 124-124


Line range hint 1-1: Verify attachment link updates across the codebase.

Let's ensure all attachment references are updated consistently.

Run the following script to check for any remaining unhandled attachment references:

✅ Verification successful

Attachment references are consistently maintained across the codebase

The verification shows that attachment references follow consistent patterns and are properly handled in both backend services and frontend components. All references use standardized URL structures and markdown syntax.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential unhandled attachment references

# Search for attachment link patterns
echo "Searching for attachment link patterns..."
rg -A 2 "attachments/.*\.(pdf|png|jpg|jpeg|gif)"

# Search for potential attachment URL construction
echo "Searching for potential manual URL construction..."
rg -A 2 "downloadUrl.*split.*attachments"

# Search for potential attachment references in templates
echo "Searching for attachment references in templates..."
rg -A 2 '\[attachment\].*\(.*\)\[/attachment\]'

Length of output: 12162

src/test/javascript/spec/component/shared/monaco-editor/monaco-editor-communication-action.integration.spec.ts (5)

33-34: LGTM!

The imports are correctly placed and follow the established pattern.


40-40: LGTM!

The fileService variable declaration follows the pattern of other service declarations.


52-64: LGTM!

The test module configuration correctly includes the FileService provider with its mock implementation.


71-72: LGTM!

The fileService injection follows the pattern of other service injections.


301-304: LGTM!

The attachment mapping correctly uses fileService.createAttachmentFileUrl while preserving other attachment properties.

src/test/javascript/spec/component/shared/metis/postings-markdown-editor/postings-markdown-editor.component.spec.ts (5)

39-42: LGTM!

The imports are correctly placed and follow the established pattern. The ListAction import path has been corrected.


50-50: LGTM!

The fileService variable declaration follows the pattern of other service declarations.


126-126: LGTM!

The test module configuration correctly includes the FileService provider with its mock implementation.


141-141: LGTM!

The fileService injection follows the pattern of other service injections.


162-162: LGTM!

The LectureAttachmentReferenceAction instantiation is consistently updated with fileService across all test cases.

Also applies to: 169-169, 194-194, 202-202

Copy link
Contributor

@SimonEntholzer SimonEntholzer left a comment

Choose a reason for hiding this comment

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

Changes make sense, left one minor comment

Comment on lines +61 to +63
} else {
attachmentCopy = lecture.attachments;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't this step kind of redundant, as it's only reached when lecture.attachments is undefined, which means you are just overwriting the undefined with another undefined? Or am I missing something here

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 TS2. Works as described

image

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 TS4, works as described. It shows the proper attachment and no 404 error.

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!) ready for review tests
Projects
Status: Ready For Review
Status: Todo
Development

Successfully merging this pull request may close these issues.

4 participants