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

Programming exercises: Use server time for exercise details dates #9755

Conversation

rabeatwork
Copy link
Contributor

@rabeatwork rabeatwork commented Nov 12, 2024

Checklist

General

  • This is a small issue that I tested locally and on a testserverand was confirmed by another developer on a test server.
  • I chose a title conforming to the naming conventions for pull requests.

Motivation and Context

If a student manually changes the time on their computer (without changing the time zone), the time until an exercise starts, is due, etc., was displayed incorrectly.

Description

To avoid this, the server time is fetched and used instead of using dayjs().

Steps for Testing

Prerequisites:

  • 1 Instructor/student
  • 1 Programming Exercise with dates (start date, due date, assessment date, complaint date)
  1. Log in to Artemis
  2. Navigate to Course Exercises
  3. See the current dates
  4. Change the date/time of your computer (manually and by changing the time zone)
  5. Verify that the dates are still displayed correctly

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

Screenshots

Summary by CodeRabbit

  • New Features

    • Introduced server time integration for enhanced date handling in the exercise headers component.
    • Updated date comparison logic to ensure consistency with server time.
  • Bug Fixes

    • Improved flexibility of date comparison functions to accept user-defined reference times.
  • Refactor

    • Centralized date logic to reduce redundancy and improve maintainability.
    • Enhanced synchronization checks in the server date service for improved accuracy.

@github-actions github-actions bot added the client Pull requests that update TypeScript code. (Added Automatically!) label Nov 12, 2024
@rabeatwork rabeatwork changed the title Programming Exercises: Use servertime for exercise details dates Programming exercises: Use servertime for exercise details dates Nov 12, 2024
@rabeatwork rabeatwork marked this pull request as ready for review November 12, 2024 13:58
@rabeatwork rabeatwork requested a review from a team as a code owner November 12, 2024 13:58
Copy link

coderabbitai bot commented Nov 12, 2024

Walkthrough

The changes in this pull request involve modifications to the ExerciseHeadersInformationComponent, the isDateLessThanAWeekInTheFuture utility function, and the ArtemisServerDateService. The component now imports and utilizes ArtemisServerDateService to fetch the current server date, which is stored in a new property now and used for various date comparisons. The utility function has been updated to accept an optional comparison time parameter, enhancing its flexibility. These changes aim to centralize date handling and improve consistency across the component's date-related logic.

Changes

File Change Summary
src/main/webapp/app/exercises/shared/exercise-headers/exercise-headers-information/exercise-headers-information.component.ts - Added now: dayjs.Dayjs property.
- Updated constructor to inject ArtemisServerDateService.
- Modified date comparison logic to use this.now.
src/main/webapp/app/utils/date.utils.ts - Updated isDateLessThanAWeekInTheFuture function to accept an optional compareTime parameter for flexible date comparison.
src/main/webapp/app/shared/server-date.service.ts - Updated updateTime method to use Math.abs for time difference checks, enhancing synchronization accuracy.

Possibly related PRs

Suggested labels

tests, programming

Suggested reviewers

  • SimonEntholzer
  • JohannesStoehr
  • FelixTJDietrich
  • egekurt123
  • coolchock

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 (4)
src/main/webapp/app/utils/date.utils.ts (1)

78-80: Add JSDoc documentation for the new parameter and clarify the function name.

The function implementation is correct, but there are a few improvements that could make it more maintainable:

  1. The function name isDateLessThanAWeekInTheFuture is slightly misleading as it checks if the date is between now and a week from now, not just if it's less than a week in the future.
  2. The new compareTime parameter needs documentation.

Consider applying these changes:

+/**
+ * Checks if a date falls between now (or a specified comparison time) and one week from that time
+ * @param date The date to check
+ * @param compareTime Optional reference time for comparison (defaults to current time)
+ * @returns true if the date is between the comparison time and one week from it
+ */
-export function isDateLessThanAWeekInTheFuture(date: dayjs.Dayjs, compareTime?: dayjs.Dayjs): boolean {
+export function isDateWithinNextWeek(date: dayjs.Dayjs, compareTime?: dayjs.Dayjs): boolean {
     const now = compareTime ?? dayjs();
-    return date.isBetween(now.add(1, 'week'), now);
+    return date.isBetween(now, now.add(1, 'week'));
}

The changes:

  1. Add comprehensive JSDoc documentation
  2. Rename function to better reflect its behavior
  3. Swap the order of arguments in isBetween to be more intuitive (from earlier to later date)
src/main/webapp/app/exercises/shared/exercise-headers/exercise-headers-information/exercise-headers-information.component.ts (3)

45-45: Consider implementing periodic server time updates

While the server time initialization is correct, the now property might become stale during long user sessions. Consider implementing a periodic refresh mechanism to keep the server time synchronized.

Example implementation:

+ private destroy$ = new Subject<void>();

  ngOnInit() {
    this.dueDate = getExerciseDueDate(this.exercise, this.studentParticipation);
-   this.now = this.serverDateService.now();
+   // Initial server time
+   this.updateServerTime();
+   // Refresh server time every minute
+   interval(60000).pipe(
+     takeUntil(this.destroy$)
+   ).subscribe(() => this.updateServerTime());
    // ... rest of the code
  }

+ private updateServerTime(): void {
+   this.now = this.serverDateService.now();
+ }

+ ngOnDestroy(): void {
+   this.destroy$.next();
+   this.destroy$.complete();
+ }

Also applies to: 57-57


Line range hint 120-145: Consider breaking down complex date-related logic

The method handles multiple date-related conditions and UI elements. Consider extracting these into separate methods for better maintainability.

Example refactoring:

- addDueDateItems() {
+ addDueDateItems() {
+   this.addBasicDueDateItem();
+   this.addAssessmentDueDateItem();
+   this.addComplaintDueDateItem();
+ }
+
+ private addBasicDueDateItem(): void {
+   const dueDateItem = this.getDueDateItem();
+   if (dueDateItem) {
+     this.informationBoxItems.push(dueDateItem);
+   }
+ }
+
+ private addAssessmentDueDateItem(): void {
    if (this.dueDate?.isBefore(this.now) && this.exercise.assessmentDueDate?.isAfter(this.now)) {
      const assessmentDueItem: InformationBox = {
        title: 'artemisApp.courseOverview.exerciseDetails.assessmentDue',
        content: {
          type: 'dateTime',
          value: this.exercise.assessmentDueDate,
        },
        isContentComponent: true,
        tooltip: 'artemisApp.courseOverview.exerciseDetails.assessmentDueTooltip',
        tooltipParams: { date: this.exercise.assessmentDueDate.format('lll') },
      };
      this.informationBoxItems.push(assessmentDueItem);
    }
+ }
+
+ private addComplaintDueDateItem(): void {
    if (this.exercise.assessmentDueDate?.isBefore(this.now) && this.individualComplaintDueDate?.isAfter(this.now)) {
      const complaintDueItem: InformationBox = {
        title: 'artemisApp.courseOverview.exerciseDetails.complaintDue',
        content: {
          type: 'dateTime',
          value: this.individualComplaintDueDate,
        },
        isContentComponent: true,
        tooltip: 'artemisApp.courseOverview.exerciseDetails.complaintDueTooltip',
        tooltipParams: { date: this.individualComplaintDueDate.format('lll') },
      };
      this.informationBoxItems.push(complaintDueItem);
    }
  }

Other components using direct Date usage found.

  • src/main/resources/templates/typescript/test/src/behavior.test.ts
  • src/main/webapp/app/shared/user-settings/ide-preferences/ide-settings.service.ts
  • src/main/webapp/app/shared/server-date.service.ts
  • src/test/javascript/spec/service/course-exercise.service.spec.ts
  • src/main/webapp/app/admin/audits/audits.component.ts
  • ... (additional file paths as identified)
🔗 Analysis chain

Line range hint 1-299: Verify time manipulation scenarios

While the implementation looks correct, please ensure comprehensive testing of the following scenarios:

  1. Time zone changes
  2. System time manipulation
  3. Browser time manipulation
  4. Long running sessions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other time-sensitive components that might need similar updates

# Search for dayjs usage in components
echo "Searching for other components using dayjs..."
rg -l "dayjs\(\)" --type ts

# Search for potential time manipulation vulnerabilities
echo "Searching for direct Date usage..."
rg "new Date\(\)" --type ts

# Search for time-related methods
echo "Searching for time-related methods..."
rg "\.(isBefore|isAfter|isBetween)\(" --type ts

Length of output: 67759

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between de36813 and cd8607a.

📒 Files selected for processing (2)
  • src/main/webapp/app/exercises/shared/exercise-headers/exercise-headers-information/exercise-headers-information.component.ts (7 hunks)
  • src/main/webapp/app/utils/date.utils.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/webapp/app/exercises/shared/exercise-headers/exercise-headers-information/exercise-headers-information.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/utils/date.utils.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 (3)
src/main/webapp/app/utils/date.utils.ts (1)

78-78: Verify the impact of function rename.

Let's check where this function is used to understand the scope of the rename change.

✅ Verification successful

Function rename impact verified.
All usages are accounted for in test specs and ExerciseHeadersInformationComponent.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of the function to assess the impact of renaming
rg "isDateLessThanAWeekInTheFuture" --type ts

Length of output: 1403

src/main/webapp/app/exercises/shared/exercise-headers/exercise-headers-information/exercise-headers-information.component.ts (2)

20-20: LGTM: Clean dependency injection implementation

The ArtemisServerDateService integration follows Angular best practices and style guidelines.

Also applies to: 50-53


151-155: LGTM: Consistent server time usage

The date comparison logic has been consistently updated to use server time across all methods, which effectively addresses the PR's objective of preventing time manipulation issues.

Also applies to: 183-185, 226-226

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

⚠️ Unable to deploy to test servers ⚠️

Testserver "artemis-test1.artemis.cit.tum.de" is already in use by PR #9728.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Nov 12, 2024
@HawKhiem HawKhiem added deploy:artemis-test3 and removed deployment-error Added by deployment workflows if an error occured labels Nov 12, 2024
@HawKhiem HawKhiem temporarily deployed to artemis-test3.artemis.cit.tum.de November 12, 2024 16:42 — with GitHub Actions Inactive
sachmii
sachmii previously approved these changes Nov 12, 2024
Copy link

@sachmii sachmii 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 TS3, works as described

HawKhiem
HawKhiem previously approved these changes Nov 12, 2024
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 TS3. Everything works as described

Copy link

@sachmii sachmii left a comment

Choose a reason for hiding this comment

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

re-approve

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.

Reapprove

@MaximilianAnzinger
Copy link
Collaborator

TestsWo

Copy link

@flbrgit flbrgit 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, everything works as described when changing time and time zone manually.

Copy link

@JerroyTan JerroyTan 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 TS5]
For me the time only automatically switched according to the changes on my computer system when I changed the time zone. However, when I changed the time manually (moved 5 minutes before, moved 2 hours before) it did not work as expected. The time on the exercise was shown according to the last time zone I set myself to.
Tested on Windows 11

@rabeatwork
Copy link
Contributor Author

[Tested on TS5] For me the time only automatically switched according to the changes on my computer system when I changed the time zone. However, when I changed the time manually (moved 5 minutes before, moved 2 hours before) it did not work as expected. The time on the exercise was shown according to the last time zone I set myself to. Tested on Windows 11

That's the intended behavior. Since we do not want the students to manipulate the time on their computer and, by doing so, trick the system (e.g., by setting their computer time to before the due date of an exercise).

@rabeatwork rabeatwork added ready to merge maintainer-approved The feature maintainer has approved the PR and removed ready for review labels Nov 25, 2024
@krusche krusche changed the title Programming exercises: Use servertime for exercise details dates Programming exercises: Use server time for exercise details dates Nov 28, 2024
@krusche krusche added this to the 7.7.3 milestone Nov 28, 2024
@krusche krusche merged commit 53553ae into develop Nov 28, 2024
94 of 99 checks passed
@krusche krusche deleted the bugfix/programming-exercises/use-servertime-for-exercise-details-dates branch November 28, 2024 20:08
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!) maintainer-approved The feature maintainer has approved the PR ready to merge small
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.