Skip to content

chore: rm obsolete style block from myservers1.php#1435

Merged
pujitm merged 5 commits into
mainfrom
chore/git-conflicts
Jun 25, 2025
Merged

chore: rm obsolete style block from myservers1.php#1435
pujitm merged 5 commits into
mainfrom
chore/git-conflicts

Conversation

@pujitm

@pujitm pujitm commented Jun 24, 2025

Copy link
Copy Markdown
Member

Complement to unraid/webgui#2270

Compared our dynamix.my.servers with the webgui's and made the corresponding changes. activation code logic was omitted because it has already been written into the api.

python script used for comparison: https://gist.github.com/pujitm/43a4d2fc35c74f51c70cc66fe1909e6c

#!/usr/bin/env python3
"""
Directory comparison script that recursively compares two directories
and shows files that exist in one but not the other, plus diffs for common files.
"""

import os
import sys
import subprocess
from pathlib import Path
from typing import Set, Tuple


def get_all_files(directory: str) -> Set[str]:
    """Get all files in a directory recursively, returning relative paths."""
    files = set()
    dir_path = Path(directory)
    
    if not dir_path.exists():
        print(f"Error: Directory '{directory}' does not exist")
        return files
    
    for root, dirs, filenames in os.walk(directory):
        for filename in filenames:
            full_path = Path(root) / filename
            # Get relative path from the base directory
            relative_path = full_path.relative_to(dir_path)
            files.add(str(relative_path))
    
    return files


def compare_directories(dir1: str, dir2: str) -> Tuple[Set[str], Set[str], Set[str]]:
    """
    Compare two directories and return files in each directory.
    
    Returns:
        - files only in dir1
        - files only in dir2  
        - files in both directories
    """
    files1 = get_all_files(dir1)
    files2 = get_all_files(dir2)
    
    only_in_dir1 = files1 - files2
    only_in_dir2 = files2 - files1
    in_both = files1 & files2
    
    return only_in_dir1, only_in_dir2, in_both


def run_diff(file1_path: str, file2_path: str, relative_path: str) -> bool:
    """
    Run diff on two files and print the output.
    Returns True if files are different, False if identical.
    """
    try:
        # Use diff -u for unified diff format
        result = subprocess.run(
            ['diff', '-u', file1_path, file2_path],
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            # Files are identical
            return False
        elif result.returncode == 1:
            # Files are different
            print(f"\n--- Diff for: {relative_path} ---")
            print(result.stdout)
            return True
        else:
            # Error occurred
            print(f"\nError running diff on {relative_path}: {result.stderr}")
            return False
            
    except FileNotFoundError:
        print(f"\nError: 'diff' command not found. Please install diffutils.")
        return False
    except Exception as e:
        print(f"\nError comparing {relative_path}: {e}")
        return False


def compare_file_contents(dir1: str, dir2: str, common_files: Set[str]) -> Tuple[int, int]:
    """
    Compare contents of files that exist in both directories.
    Returns (identical_count, different_count).
    """
    identical_count = 0
    different_count = 0
    
    print(f"\nComparing contents of {len(common_files)} common files...")
    print("=" * 60)
    
    for relative_path in sorted(common_files):
        file1_path = os.path.join(dir1, relative_path)
        file2_path = os.path.join(dir2, relative_path)
        
        if run_diff(file1_path, file2_path, relative_path):
            different_count += 1
        else:
            identical_count += 1
    
    return identical_count, different_count


def main():
    if len(sys.argv) < 3:
        print("Usage: python compare_directories.py <directory1> <directory2> [--no-diff]")
        print("Example: python compare_directories.py /path/to/dir1 /path/to/dir2")
        print("Use --no-diff to skip content comparison")
        sys.exit(1)
    
    dir1 = sys.argv[1]
    dir2 = sys.argv[2]
    skip_diff = '--no-diff' in sys.argv
    
    print(f"Comparing directories:")
    print(f"  Directory 1: {dir1}")
    print(f"  Directory 2: {dir2}")
    print("=" * 60)
    
    only_in_dir1, only_in_dir2, in_both = compare_directories(dir1, dir2)
    
    print(f"\nFiles only in '{dir1}' ({len(only_in_dir1)} files):")
    if only_in_dir1:
        for file in sorted(only_in_dir1):
            print(f"  - {file}")
    else:
        print("  (none)")
    
    print(f"\nFiles only in '{dir2}' ({len(only_in_dir2)} files):")
    if only_in_dir2:
        for file in sorted(only_in_dir2):
            print(f"  - {file}")
    else:
        print("  (none)")
    
    print(f"\nFiles in both directories ({len(in_both)} files):")
    if in_both:
        for file in sorted(in_both):
            print(f"  - {file}")
    else:
        print("  (none)")
    
    # Compare file contents if requested and there are common files
    identical_count = 0
    different_count = 0
    if not skip_diff and in_both:
        identical_count, different_count = compare_file_contents(dir1, dir2, in_both)
    
    print("\n" + "=" * 60)
    print(f"Summary:")
    print(f"  Total files in '{dir1}': {len(only_in_dir1) + len(in_both)}")
    print(f"  Total files in '{dir2}': {len(only_in_dir2) + len(in_both)}")
    print(f"  Files only in '{dir1}': {len(only_in_dir1)}")
    print(f"  Files only in '{dir2}': {len(only_in_dir2)}")
    print(f"  Files in both: {len(in_both)}")
    
    if not skip_diff and in_both:
        print(f"  Identical files: {identical_count}")
        print(f"  Different files: {different_count}")


if __name__ == "__main__":
    main() 

Summary by CodeRabbit

  • New Features
    • Added support for extracting and displaying activation code data, including partner information and logos, when relevant.
  • Style
    • Removed embedded CSS styling from the server management interface header.

@pujitm pujitm requested a review from elibosley as a code owner June 24, 2025 20:58
@coderabbitai

coderabbitai Bot commented Jun 24, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

A new PHP class, ActivationCodeExtractor, has been added to handle reading, parsing, and managing activation code JSON files from a specified directory. The class provides methods for retrieving partner metadata, logo paths, and safely encoded data, and includes error handling for missing or invalid files. Additionally, support for this activation code data is integrated into the ServerState class. A CSS style block was removed from myservers1.php.

Changes

File(s) Change Summary
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php Added ActivationCodeExtractor class for extracting and managing activation code JSON files and assets.
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/state.php Added activation code detection and exposure in ServerState class using the new extractor.
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers1.php Removed embedded CSS style block related to header layout and icons.

Suggested reviewers

  • elibosley
  • mdatelle

Poem

In the land of code, a class appears,
Extracting secrets, calming fears.
JSON files and logos found,
Partner data all around.
With careful checks, it reads the way—
Activation made easy, hooray!
🗝️✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (1)
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php (1)

54-56: Simplify directory check logic.

The count check is unnecessary since scandir() always returns at least ['.', '..'] for valid directories.

-        if ($files === false || count($files) === 0) {
+        if ($files === false) {
             return $data;
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7bc583b and 53caba4.

📒 Files selected for processing (1)
  • plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Build Web App
  • GitHub Check: Build API
  • GitHub Check: Build Unraid UI Library (Webcomponent Version)
  • GitHub Check: Test API
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (actions)
  • GitHub Check: Cloudflare Pages

Comment on lines +118 to +121
public function getDataForHtmlAttr(): string {
$json = json_encode($this->getData());
return htmlspecialchars($json, ENT_QUOTES, 'UTF-8');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for JSON encoding.

json_encode() can fail and return false, which should be handled.

     public function getDataForHtmlAttr(): string {
         $json = json_encode($this->getData());
+        if ($json === false) {
+            return '';
+        }
         return htmlspecialchars($json, ENT_QUOTES, 'UTF-8');
     }
🤖 Prompt for AI Agents
In
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php
around lines 118 to 121, the getDataForHtmlAttr method calls json_encode without
checking for failure, which can return false. Modify the method to check if
json_encode returns false, and handle this error case appropriately, such as by
logging an error or returning an empty string or a safe fallback value, before
passing the result to htmlspecialchars.

* headermetacolor?: string,
* background?: string,
* showBannerGradient?: string,
* theme?: "azure" | "black" | "gray" | "white

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix syntax error in type annotation.

The theme type annotation is missing a closing quote.

-     * theme?: "azure" | "black" | "gray" | "white
+     * theme?: "azure" | "black" | "gray" | "white"
📝 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
* theme?: "azure" | "black" | "gray" | "white
* theme?: "azure" | "black" | "gray" | "white"
🤖 Prompt for AI Agents
In
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php
at line 25, the type annotation for the theme property is missing a closing
quote after "white". Add the missing closing quote to properly close the string
literal in the type annotation.

Comment on lines +128 to +134
public function getPartnerLogoRenderString(): string {
if (empty($this->partnerLogoPath)) { // default logo
return file_get_contents(self::DEFAULT_LOGO);
}

return file_get_contents($this->partnerLogoPath);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for file reading operations.

file_get_contents() can fail if files don't exist or are unreadable.

     public function getPartnerLogoRenderString(): string {
-        if (empty($this->partnerLogoPath)) { // default logo
-            return file_get_contents(self::DEFAULT_LOGO);
+        if (empty($this->partnerLogoPath)) {
+            $content = file_get_contents(self::DEFAULT_LOGO);
+            return $content !== false ? $content : '';
         }
 
-        return file_get_contents($this->partnerLogoPath);
+        $content = file_get_contents($this->partnerLogoPath);
+        return $content !== false ? $content : '';
     }
📝 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
public function getPartnerLogoRenderString(): string {
if (empty($this->partnerLogoPath)) { // default logo
return file_get_contents(self::DEFAULT_LOGO);
}
return file_get_contents($this->partnerLogoPath);
}
public function getPartnerLogoRenderString(): string {
if (empty($this->partnerLogoPath)) {
$content = file_get_contents(self::DEFAULT_LOGO);
return $content !== false ? $content : '';
}
$content = file_get_contents($this->partnerLogoPath);
return $content !== false ? $content : '';
}
🤖 Prompt for AI Agents
In
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php
around lines 128 to 134, the method getPartnerLogoRenderString uses
file_get_contents without checking for failure, which can cause issues if the
file is missing or unreadable. Modify the code to check the result of
file_get_contents calls, handle errors gracefully by returning a default value
or throwing an exception, and ensure the method never returns false or null
unexpectedly.

Comment on lines +63 to +70
$fileContent = file_get_contents($filePath);
$jsonData = json_decode($fileContent, true);

if (json_last_error() === JSON_ERROR_NONE) {
$data = $jsonData;
} else {
$data = ['error' => 'Invalid JSON format'];
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for file operations.

Missing error handling for file_get_contents() could cause issues if the file is unreadable.

         if (preg_match(self::FILE_PATTERN, $file, $matches)) {
             // $activationCode = $matches[1];
-            $fileContent = file_get_contents($filePath);
-            $jsonData = json_decode($fileContent, true);
+            $fileContent = file_get_contents($filePath);
+            if ($fileContent === false) {
+                $data = ['error' => 'Could not read file'];
+                break;
+            }
+            
+            $jsonData = json_decode($fileContent, true);
 
             if (json_last_error() === JSON_ERROR_NONE) {
                 $data = $jsonData;
📝 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
$fileContent = file_get_contents($filePath);
$jsonData = json_decode($fileContent, true);
if (json_last_error() === JSON_ERROR_NONE) {
$data = $jsonData;
} else {
$data = ['error' => 'Invalid JSON format'];
}
if (preg_match(self::FILE_PATTERN, $file, $matches)) {
// $activationCode = $matches[1];
- $fileContent = file_get_contents($filePath);
- $jsonData = json_decode($fileContent, true);
+ $fileContent = file_get_contents($filePath);
+ if ($fileContent === false) {
+ $data = ['error' => 'Could not read file'];
+ break;
+ }
+
+ $jsonData = json_decode($fileContent, true);
if (json_last_error() === JSON_ERROR_NONE) {
$data = $jsonData;
} else {
$data = ['error' => 'Invalid JSON format'];
}
}
🤖 Prompt for AI Agents
In
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/activation-code-extractor.php
around lines 63 to 70, the code uses file_get_contents() without checking if the
file was successfully read. Add error handling to verify that
file_get_contents() does not return false before proceeding to json_decode. If
file_get_contents() fails, set $data to an appropriate error message indicating
the file could not be read.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 53caba4 and 65df6e8.

📒 Files selected for processing (2)
  • plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers1.php (0 hunks)
  • plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/state.php (5 hunks)
💤 Files with no reviewable changes (1)
  • plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers1.php
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build Web App
  • GitHub Check: Build Unraid UI Library (Webcomponent Version)
  • GitHub Check: Build API
  • GitHub Check: Test API
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/state.php (5)

18-18: LGTM - Dependency inclusion follows existing pattern.

The require_once statement is correctly placed with other dependencies and uses the established path structure.


82-82: LGTM - Property declaration follows class conventions.

The public property follows the same pattern as other similar properties in the class with appropriate array initialization.


136-136: LGTM - Method call placement is appropriate.

The activation code detection is called after connect values are set, which makes sense for the initialization sequence.


358-360: LGTM - Server state integration follows established pattern.

The conditional addition of activation code data to the server state array follows the same pattern used for other optional data above it.


253-253: Verify the $_GET['c'] parameter dependency.

The logic depends on checking for a 'c' parameter in $_GET to determine callback installation state. Ensure this parameter usage is documented and consistent with other parts of the system.

#!/bin/bash
# Description: Search for other usages of $_GET['c'] parameter to verify consistency
# Expected: Find other references to this parameter in the codebase

rg -A 3 -B 3 "\\\$_GET\['c'\]"

Comment on lines +250 to +265
private function detectActivationCode()
{
// Fresh server and we're not loading with a callback param to install
if ($this->state !== 'ENOKEYFILE' || !empty($_GET['c'])) {
return;
}

$activationCodeData = new ActivationCodeExtractor();
$data = $activationCodeData->getData();

if (empty($data)) {
return;
}

$this->activationCodeData = $data;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for ActivationCodeExtractor instantiation.

The method logic is sound, but consider adding error handling around the ActivationCodeExtractor instantiation to prevent potential fatal errors if the class fails to load or instantiate.

 private function detectActivationCode()
 {
     // Fresh server and we're not loading with a callback param to install
     if ($this->state !== 'ENOKEYFILE' || !empty($_GET['c'])) {
         return;
     }

-    $activationCodeData = new ActivationCodeExtractor();
-    $data = $activationCodeData->getData();
+    try {
+        $activationCodeData = new ActivationCodeExtractor();
+        $data = $activationCodeData->getData();
+    } catch (Exception $e) {
+        error_log("Failed to extract activation code: " . $e->getMessage());
+        return;
+    }

     if (empty($data)) {
         return;
     }

     $this->activationCodeData = $data;
 }
📝 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
private function detectActivationCode()
{
// Fresh server and we're not loading with a callback param to install
if ($this->state !== 'ENOKEYFILE' || !empty($_GET['c'])) {
return;
}
$activationCodeData = new ActivationCodeExtractor();
$data = $activationCodeData->getData();
if (empty($data)) {
return;
}
$this->activationCodeData = $data;
}
private function detectActivationCode()
{
// Fresh server and we're not loading with a callback param to install
if ($this->state !== 'ENOKEYFILE' || !empty($_GET['c'])) {
return;
}
try {
$activationCodeData = new ActivationCodeExtractor();
$data = $activationCodeData->getData();
} catch (Exception $e) {
error_log("Failed to extract activation code: " . $e->getMessage());
return;
}
if (empty($data)) {
return;
}
$this->activationCodeData = $data;
}
🤖 Prompt for AI Agents
In
plugin/source/dynamix.unraid.net/usr/local/emhttp/plugins/dynamix.my.servers/include/state.php
around lines 250 to 265, add error handling when instantiating
ActivationCodeExtractor to avoid fatal errors if the class fails to load or
instantiate. Wrap the instantiation and subsequent method call in a try-catch
block to catch exceptions, and handle them gracefully, such as logging the error
or safely returning without breaking execution.

@elibosley elibosley left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This file can actually be deleted. We moved this logic entirely into the API

@pujitm pujitm requested a review from elibosley June 25, 2025 14:22
@pujitm pujitm changed the title chore: move activation code extractor here from webgui repo chore: rm obsolete style block from myservers1.php Jun 25, 2025
@github-actions

Copy link
Copy Markdown
Contributor

This plugin has been deployed to Cloudflare R2 and is available for testing.
Download it at this URL:

https://preview.dl.unraid.net/unraid-api/tag/PR1435/dynamix.unraid.net.plg

@pujitm pujitm merged commit 5ba4479 into main Jun 25, 2025
12 checks passed
@pujitm pujitm deleted the chore/git-conflicts branch June 25, 2025 16:57
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.

3 participants