Files
api/plugin/plugins/dynamix.unraid.net.plg
Zack Spear 309d221542 feat / OEM whitelabel support (#973)
* feat: begin fixing dark mode in the webcomponents

* feat: lots of progress on colors

* feat: begin nuking alpha beta gamma

* feat: set background color on webcomponents

* fix: more color work

* feat: eliminate all alpha beta gamma variable usage

* feat: move variable declarations to theme.ts

* feat: begin fixing dark mode in the webcomponents

* feat: lots of progress on colors

* feat: begin nuking alpha beta gamma

* feat: set background color on webcomponents

* fix: more color work

* feat: eliminate all alpha beta gamma variable usage

* feat: download nodejs and install on legacy OS versions

* feat: do not move upgradepkg

* feat: array iteration for restoring files

* feat: separate install process

* feat: extract node to usr/local/

* feat: move variable declarations to theme.ts

* feat: remove nghttp3 and only bundle nodejs

* feat: validate entries correctly

* fix: upgradepkg

* feat: copy only needed files for nodejs

* fix: install syntax error

* fix: strip components from tar line

* feat: error when nodejs download fails

* feat(php): add OEM data extraction functionality

* feat(web): WIP add OEM activation modal and integrate OEM data handling

* refactor: replace oem etamology with activation

* feat(web): enhance activation modal with header and main title options

* refactor(web): update activation modal title to handle partner name conditionally

* feat: make partnerName optional in activation code data

* refactor: remove activationCodeStore from UserProfile component

* feat: integrate activation code data into server store

* feat: enhance activation code store to include callback actions and improve modal visibility logic

* refactor: remove unused theme reference from ColorSwitcher component

* fix: update partnerName in activationCodeData for clarity

* refactor: adjust gap spacing in Modal component for improved layout

* feat: enhance Activation Modal component with dynamic title and description, and add documentation buttons

* feat: implement localization for Activation Modal component titles and button texts

* feat: add new translations for activation prompts and welcome messages in the WebComponentTranslations class

* feat: implement key sequence to close Activation Modal and persist visibility state

* feat: update activation logic to conditionally activate or redeem based on activation code presence

* feat(plg): plg install / remove partner banner

* feat(plg): on install update config to enable display settings banner and on remove banner setting if no custom banner used

* fix(plg): plg remove, display banner no if no custom image

* feat(plg): implement partner banner handling and system model identification from activation JSON

* feat(web): add loading and error states to notification sidebar

* refactor(web): add container for loading & error states

* feat(web): add count labels to notification tabs

* refactor(web): lift notifications overview query to Sidebar from Indicator

* fix(web): refetch notifications for sidebar when new notifications arrive

* feat(web): move notification indicator icons to top-right of bell icon

previously, icons were placed next to bell icon because the status indicators
were not accessible to color-blind users. this commit replaces circular
status indicators with the icons.

* feat(web): remove notification indicator pulse

the pulse was initially added to provide visual feedback when:

1. a new notification arrived
2. an alert notification was unread

because we began using the legacy notify script, we now get a toast
on new notifications. re:2, feedback on the pulse was mixed, so i'm
removing it.

* refactor(plg): improve conditional for activation & partner setup

* feat(plg): add case model icon handling based on activation JSON

* feat(plg): enhance partner setup process with detailed logging and system identification updates and setup flag

* feat(plg): add setup flag file creation and logging for activation changes

* feat(plg): update activation setup flag checks for banner, case model icon, and system identity

* fix(plg): add error handling for invalid activation JSON and improve conditional checks for setup flags

* fix(plg): improve partner banner and case model icon setup logic with enhanced checks and comments

* fix(plg): update case model icon configuration to prevent newline issues in parsing

* fix(plg): remove unnecessary echo debug statements and improve setup flag handling for partner details

* fix(plg): remove unnecessary registration page check from activation code modal logic

* fix(plg): add overlay opacity prop to modal components for customizable background transparency

* fix(plg): enhance modal component with vertical centering option and adjust max-width

* fix(plg): enhance configuration handling by dynamically updating multiple header parameters in the config file

* fix(plg): improve comments and enhance setup flag handling for custom icons in activation logic

* fix(translations): correct capitalization and punctuation in user prompts for consistency

* fix(store): enhance activation code data structure with additional properties and correct partner URL reference

* fix(modal): enhance activation modal with dynamic partner logo and improved title handling

* fix(store): update activation code data structure with additional properties and correct partner details

* fix(index): refactor badge and button color handling with typed constants for improved maintainability

* fix(dependencies): add vue-tsc for improved TypeScript support in Vue projects

* refactor(plugin): remove unnecessary comments and clean up code structure

* refactor(plugin): remove todo comment for custom header logo

* fix(Modal): add partnerUrl handling for logo link and improve code structure

* fix(serverState): update partnerLogoPath to use a placeholder image for development

* feat(plugin): add rsync activation script for testing activation modal & installs

* refactor(activationCode): remove debug log for modal visibility check

* feat(plugin): enhance activation process by adding logo and case model handling

* refactor(activationCode): rename partnerLogoPath to partnerLogo and update handling for logo file type

* refactor(activationCode): remove debug log for partnerLogo watcher

* chore(nuxt.config): add ignore rule for webGui images directory

* refactor(plugin): rename params array to DISPLAY_PARAMS and update handling for configuration updates

* fix(web): partner logo handling for themes

* fix(plg): activation oem, custom case icon cfg handling

* fix(plugin): replace sed with awk for config file updates in DISPLAY_PARAMS handling

* fix(web): add target and rel attributes to partner logo link for security

* feat(plugin): add theme parameter to DISPLAY_PARAMS and activation code interface

* fix(plugin): replace sed with parameter expansion and awk for config file updates

* fix(plugin): reboot logic for plg install to prevent settings overwrite

* feat(plugin): streamline activation and partner setup by abstracting scripts for better maintainability

* fix(plugin): update script source paths for activation and partner setup

* fix(plugin): update script source paths for activation and partner setup to use relative paths

* fix(plugin): update script source paths for activation and partner setup to use absolute paths

* fix(plugin): add debug mode support to activation scripts and update setup flag handling

* fix(plugin): enhance activation scripts with debug mode and conditional execution for safety

* refactor(plugin): reposition execution of activation_code setup / remove scripts

* fix(plugin): add checks for activation_code_setup script existence and improve deletion logging

* fix(plugin): add option to remove setup flag after script execution

* fix(plugin): streamline activation script execution by removing unnecessary checks

* fix(plugin): remove duplicate activation_code_setup script sourcing

* feat(modal): add overlay color prop and enhance class binding for modal background

* feat(activation): update modal overlay color and opacity

* feat(plg): add WebComponentsExtractor class for managing JS file retrieval

* feat(plugin): myservers1.phpintegrate WebComponentsExtractor for dynamic script tag generation

* feat(activation): enhance getData method to support JSON output and add getDataForHtmlAttr for HTML-safe JSON

* refactor(activation): simplify getData method by removing parameters

* feat(plugin): add welcome-modal.php for displaying server state and web components

* refactor(web): activation code store rename modal visibility variables for clarity

* feat(web): add WelcomeModal component for user onboarding and server setup

* feat(plugin): activation_code setup and remove script support welcome modal

* refactor(plugin): streamline activation code setup script by removing some comments

* fix(plugin): update activation code setup script to prepend items to auth request allow list array

* feat: enhance ActivationCodeExtractor with partner logo handling and metadata extraction

- Added constants for document root and web GUI images directory.
- Introduced properties for partner name, URL, logo path, and logo file type.
- Implemented methods to retrieve partner logo path, render logo string, partner name, and URL.
- Enhanced data extraction logic to include partner-related information from JSON data.
- Added debug method for outputting internal state for troubleshooting.

* refactor: update activation-data.php to include debug output for ActivationCodeExtractor

- Removed JSON response and replaced it with a debug output wrapped in <pre> tags.
- This change allows for easier troubleshooting by displaying internal state information directly on the page.

* feat: inject partner logo into DefaultPageLayout and update JS file paths

- Modified the activation code setup script to change the path of JavaScript files to be relative to the web GUI's webroot.
- Added functionality to inject a partner logo into the DefaultPageLayout by replacing the existing logo string.
- Implemented a conditional backup mechanism for the DefaultPageLayout file before making changes.
- Included debug output to confirm successful injection or report errors during the process.

* feat: add partner logo display functionality and style adjustments

- Introduced a new file for displaying the partner logo, which retrieves the logo and URL based on the activation code.
- Added CSS styles to adjust the display properties of the partner logo in the header, ensuring proper sizing and alignment.
- Enhanced the integration of the partner logo into the existing plugin structure.

* refactor: simplify partner logo injection debug output in activation code setup script

- Removed syntax check for the DefaultPageLayout file after injecting the partner logo.
- Streamlined debug output to confirm successful injection without additional checks, enhancing clarity and reducing complexity.

* style: adjust partner logo height in myservers1.php

* style: update partner logo width in PartnerLogoImg.vue

- Changed the CSS class for the partner logo image from a max height constraint to a fixed width of 72 units, ensuring better responsiveness and alignment in the layout.

* fix: update modal title attribute for conditional close behavior

- Modified the title attribute of the modal overlay to conditionally display the close instruction based on the showCloseX property. This change improves accessibility by ensuring the title is only set when the close button is visible.

* refactor: update partner logo handling in activation code scripts and extractor

- Changed the partner logo file name to 'partner-logo.svg' in ActivationCodeExtractor.
- Simplified logo path handling by removing unnecessary file type checks and directly using the SVG file.
- Updated CSS in myservers1.php to target only the SVG logo.
- Modified activation code setup and removal scripts to consistently reference the SVG logo, improving clarity and maintainability.

* feat: enhance activation code setup script to include server name handling

- Added logic to retrieve and set the server name from the activation JSON if the current system model or comment is not set, or if the current name is "Tower".
- Improved debug output to include the partner server name, enhancing visibility during the activation process.
- Sanitized the partner server name to remove quotes and backslashes for better handling.

* feat: validate activation JSON before proceeding with setup

- Added validation for the activation JSON file to ensure it is correctly formatted before executing the setup process.
- Enhanced debug output to indicate whether the JSON is valid or not, improving troubleshooting capabilities.
- The setup will now only proceed if the activation JSON is confirmed to be valid, preventing potential errors during execution.

* fix(plg): improve warning message for invalid activation JSON in setup script

* feat: enhance activation code handling with partner logo integration

- Added a new optional property 'partnerLogo' to the ActivationCodeExtractor class and updated related interfaces to support boolean values for logo display.
- Removed the PNG logo reference from the activation code setup script, streamlining the logo handling process.
- Updated the server state to utilize the new 'partnerLogo' property, ensuring consistent logo display logic across the application.
- Adjusted computed properties in the activation code store to reflect the changes in logo handling, improving clarity and maintainability.

* fix: correct activation JSON validation in setup script

- Updated the activation code setup script to use 'jq empty' for validating the activation JSON file, ensuring proper error handling and validation.
- This change improves the robustness of the setup process by accurately checking the JSON format before proceeding.

* fix: correct comment formatting in dynamix.unraid.net.plg

- Fixed a formatting issue in the comment regarding the use of myservers.cfg values to prevent conflicts during installation. This change improves code readability and clarity.

* chore: update rsync activation script comments for clarity

- Revised comments in the rsync-activation-dir.sh script to better describe its purpose and usage.
- Enhanced documentation with an example usage to improve user understanding of the script's functionality.

* refactor: clean up activation data and extractor files

- Removed outdated copyright comments from activation-data.php and activation-code-extractor.php for improved readability.
- Simplified the debug output in activation-data.php by using short PHP tags.
- Updated the comment in the ActivationCodeExtractor class to be more concise, enhancing clarity for future developers.

* fix: remove unnecessary CSS properties in myservers1.php

- Eliminated redundant display and margin properties from the CSS in myservers1.php to streamline the styling and improve code clarity.

* refactor: streamline WebComponentsExtractor class and update method names

- Removed outdated copyright comments from web-components-extractor.php for improved readability.
- Renamed method getJsFileUrl() to getJSFileRelativePath() to enhance clarity and consistency in naming conventions.
- Adjusted indentation for better code formatting and readability.

* refactor: simplify partner logo handling in activation code script

- Removed unnecessary variable initialization and included only essential requires for improved clarity.
- Streamlined the code in partner-logo.php to focus on the core functionality of displaying the partner logo.
- Enhanced maintainability by reducing complexity in the script.

* refactor: clean up activation and server state files

- Removed outdated copyright comments and unnecessary variable initializations from activation-data.php and server-state.php for improved readability.
- Streamlined the code by eliminating redundant require statements, focusing on essential functionality.
- Enhanced maintainability and clarity by simplifying the structure of both files.

* feat: add password creation prompts to translations

- Introduced new translation strings for password creation in both PHP and JSON files.
- Enhanced user guidance by providing detailed messages about the importance of the password for system access and management.
- Improved overall user experience by ensuring clarity in the password setup process.

* refactor: update activation code setup script comments

* refactor: enhance activation code removal script functionality

- Updated the activation code removal script to delete additional related files, including PHP and setup scripts, for a more thorough cleanup.
- Improved comments for clarity on script usage and options, particularly regarding the self-delete functionality.
- Streamlined the deletion process by using an array to manage files to be removed, enhancing maintainability and readability.

* fix: update WelcomeModal to disable close button

* refactor: reorganize activation code setup and improve script clarity

- Moved the activation and partner setup section to follow the web component timestamp check to ensure correct targeting during setup.
- Updated comments for better clarity regarding the activation code setup process.
- Retained the warning message about not closing the window yet for user guidance.

* refactor: enhance activation code setup script with improved comments and logic

- Updated comments to clarify the purpose of server name, model, and description checks.
- Modified conditional logic to include additional checks for server identification.
- Added a TODO note regarding the necessity of updating the ident.cfg file, ensuring future review for potential optimizations.

* refactor: update activation code scripts to use .done flag

* refactor: introduce constant for activation modal storage key

- Added a new constant for the activation code modal hidden storage key to improve code maintainability and clarity.
- Updated the activation code store to utilize the new constant, replacing hardcoded string references.

* feat: enhance user onboarding and modal components

- Added new translation strings for activating Unraid licenses and creating Unraid.net accounts to improve user onboarding experience.
- Updated the WelcomeModal and Activation Modal components to reflect new messaging and improved styling options, including the ability to disable shadows.
- Implemented a workaround in the WelcomeModal to address font-size inconsistencies between login and authenticated pages.
- Refactored the index page to correctly pass server data to the WelcomeModal component.

* chore: comment out WelcomeModalCe component for testing

* feat: add disableOverlayClose prop to Modal and WelcomeModal components

- Introduced a new prop `disableOverlayClose` to the Modal component, allowing users to prevent closing the modal by clicking on the overlay.
- Updated the WelcomeModal component to utilize the new `disableOverlayClose` prop, enhancing modal behavior customization.

* refactor: update activation code removal script to delete by default

- Changed the activation code removal script to use a dry-run flag instead of a self-delete flag, enhancing safety during execution.
- Updated the plugin file to reflect the removal of the --delete option, ensuring consistency with the new script behavior.

---------

Co-authored-by: Eli Bosley <ekbosley@gmail.com>
Co-authored-by: Pujit Mehrotra <pujit@lime-technology.com>
2025-01-09 16:06:10 -05:00

925 lines
35 KiB
XML
Executable File
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?xml version='1.0' standalone='yes'?>
<!DOCTYPE PLUGIN [
<!ENTITY name "">
<!ENTITY launch "Connect">
<!ENTITY author "limetech">
<!ENTITY env "">
<!ENTITY version "">
<!ENTITY pluginURL "">
<!ENTITY source "/boot/config/plugins/dynamix.my.servers/&name;">
<!ENTITY SHA256 "">
<!ENTITY API_version "">
<!ENTITY API_SHA256 "">
<!ENTITY NODEJS_FILENAME "node-v20.18.1-linux-x64.tar.xz">
<!ENTITY NODEJS_SHA256 "c6fa75c841cbffac851678a472f2a5bd612fff8308ef39236190e1f8dbb0e567">
<!ENTITY NODEJS_TXZ "https://nodejs.org/dist/v20.18.1/node-v20.18.1-linux-x64.tar.xz">
<!ENTITY MAIN_TXZ "">
<!ENTITY API_TGZ "">
]>
<PLUGIN name="&name;" author="&author;" version="&version;" pluginURL="&pluginURL;"
launch="&launch;" min="6.9.0-rc1" icon="globe">
<CHANGES>
##a long time ago in a galaxy far far away
- initial release
</CHANGES>
<!-- prevent prod plugin from installing when staging already installed, and vice versa -->
<FILE Run="/bin/bash" Method="install">
<INLINE>
name="&name;" version="&version;" API_version="&API_version;" PLGTYPE="&env;"
<![CDATA[
echo "Installing ${name}.plg ${version} with Unraid API ${API_version}"
if [ "${PLGTYPE}" = "production" ] && [ -f /boot/config/plugins/dynamix.unraid.net.staging.plg ]; then
echo "⚠️ Please uninstall the Unraid Connect staging plugin before installing the production version"
exit 1
fi
if [ "${PLGTYPE}" = "staging" ] && [ -f /boot/config/plugins/dynamix.unraid.net.plg ]; then
echo "⚠️ Please uninstall the Unraid Connect production plugin before installing the staging version"
exit 1
fi
exit 0
]]>
</INLINE>
</FILE>
<!-- gzip check, DNS check, then validate files before doing anything destructive -->
<FILE Run="/bin/bash" Method="install">
<INLINE>
<![CDATA[
version=
# shellcheck disable=SC1091
source /etc/unraid-version
# ensure gzip is available and executes, is needed by '/etc/rc.d/rc.unraid-api install'
if [ ! -x /bin/gzip ] || ! /bin/gzip -V &>/dev/null; then
echo "⚠️ Unable to install as gzip is not available on this system. For help, post your diagnostics.zip to a new support thread in the forum."
exit 1
fi
dnscheck() {
HOST=$1
if [ -x /usr/bin/host ] && ! /usr/bin/host -W 10 "${HOST}" &>/dev/null; then
echo "⚠️ Warning: Your DNS server (${DNS_SERVER1}) is unable to resolve '${HOST}'"
DNSERR=yes
fi
}
# shellcheck disable=SC1090
source <(grep "DNS_SERVER1" /usr/local/emhttp/state/network.ini 2>/dev/null)
DNSERR=no
echo "Checking DNS..."
dnscheck "mothership.unraid.net"
#dnscheck "wanip4.unraid.net"
#dnscheck "backup.unraid.net"
[[ "${DNSERR}" == "yes" && "${DNS_SERVER1}" != "8.8.8.8" ]] && echo " Recommend navigating to Settings -> Network Settings and changing your DNS server to 8.8.8.8"
# Note: DNS checks will fail if the network is not available at boot. Cannot exit the install when DNS checks fail.
echo
echo "⚠️ Do not close this window yet"
echo
# compare expected SHA256 to actual SHA256, if not equal delete file
# this is needed prior to Unraid 6.11.0
sha256check() {
FILE=$1
EXPECTED=$2
if [[ -f "${FILE}" ]]; then
echo -n "Validating ${FILE}... "
ACTUAL=$(sha256sum "${FILE}" 2>/dev/null | grep -Po '^\S+')
if [[ "$EXPECTED" != "$ACTUAL" ]]; then
rm "${FILE}"
echo " old. Deleted file."
else
echo " ok."
fi
fi
}
]]>
sha256check "&source;.txz" "&SHA256;"
sha256check "/boot/config/plugins/dynamix.my.servers/unraid-api.tgz" "&API_SHA256;"
exit 0
</INLINE>
</FILE>
<!-- download node - older OS releases -->
<FILE Name="/boot/config/plugins/dynamix.my.servers/&NODEJS_FILENAME;" max="7.0.0-beta.5">
<URL>&NODEJS_TXZ;</URL>
<SHA256>&NODEJS_SHA256;</SHA256>
</FILE>
<FILE Run="/bin/bash" Method="install">
<INLINE>
NODE_FILE="&NODEJS_FILENAME;"
<![CDATA[
if [[ -f "/boot/config/plugins/dynamix.my.servers/${NODE_FILE}" ]]; then
TEMP_DIR=$(mktemp -d)
tar --strip-components=1 -xf /boot/config/plugins/dynamix.my.servers/${NODE_FILE} -C ${TEMP_DIR};
if cp -rf "${TEMP_DIR}"/bin/* /usr/local/bin/ && \
cp -rf "${TEMP_DIR}"/lib/* /usr/local/lib/ && \
cp -rf "${TEMP_DIR}"/include/* /usr/local/include/ && \
cp -rf "${TEMP_DIR}"/share/* /usr/local/share/; then
echo "Node.js installation successful"
else
echo "Failed to copy Node.js files"
exit 1
fi
else
echo "Node.js download failed"
exit 1
fi
exit 0;
]]>
</INLINE>
</FILE>
<!-- download main txz -->
<FILE Name="&source;.txz">
<URL>&MAIN_TXZ;</URL>
<SHA256>&SHA256;</SHA256>
</FILE>
<!-- download unraid-api -->
<FILE Name="/boot/config/plugins/dynamix.my.servers/unraid-api.tgz">
<URL>&API_TGZ;</URL>
<SHA256>&API_SHA256;</SHA256>
</FILE>
<FILE Run="/bin/bash" Method="install">
<INLINE>
MAINTXZ="&source;.txz"
<![CDATA[
# before proceeding with install, doubly confirm downloaded files exist. just being pedantic.
FILE=${MAINTXZ} && [[ ! -f "$FILE" ]] && echo "⚠️ file missing - $FILE" && exit 1
FILE=/boot/config/plugins/dynamix.my.servers/unraid-api.tgz && [[ ! -f "$FILE" ]] && echo "⚠️ file missing - $FILE" && exit 1
exit 0
]]>
</INLINE>
</FILE>
<FILE Run="/bin/bash" Method="remove">
<INLINE>
<![CDATA[
version=
# shellcheck disable=SC1091
source /etc/unraid-version
# Undo some activation / partner setup
source /usr/local/emhttp/plugins/dynamix.my.servers/scripts/activation_code_remove
echo
echo "⚠️ Do not close this window yet"
echo
exit 0
]]>
</INLINE>
</FILE>
<!-- disable features on uninstall -->
<!-- NOTE: this script is PHP not bash -->
<FILE Run="/usr/bin/php" Method="remove">
<INLINE>
<![CDATA[
<?
$msini = @parse_ini_file('/boot/config/plugins/dynamix.my.servers/myservers.cfg', true);
# if no_delete_on_uninstall exists on flash drive then skip the rest of the cleanup (useful when switching between staging and production)
if (file_exists("/boot/config/plugins/dynamix.my.servers/no_delete_on_uninstall")) {
exit(0);
}
echo "\n";
echo "**********************************\n";
echo "🧹 CLEANING UP - may take a minute\n";
echo "**********************************\n";
if (file_exists("/boot/.git")) {
if (file_exists("/etc/rc.d/rc.flash_backup")) {
# stop flash backup service
echo "\nStopping flash backup service. Please wait…";
exec("/etc/rc.d/rc.flash_backup stop &>/dev/null");
}
if (file_exists("/usr/local/emhttp/plugins/dynamix.my.servers/include/UpdateFlashBackup.php")) {
# deactivate and delete local flash backup
echo "\nDeactivating flash backup. Please wait…";
passthru("/usr/bin/php /usr/local/emhttp/plugins/dynamix.my.servers/include/UpdateFlashBackup.php deactivate");
}
}
# set "Allow Remote Access" to "No" and sign out from Unraid Connect
if ($msini !== false) {
# stop unraid-api
echo "\nStopping unraid-api. Please wait…";
exec("/etc/rc.d/rc.unraid-api stop &>/dev/null");
if (!empty($msini['remote']['username'])) {
$var = parse_ini_file("/var/local/emhttp/var.ini");
$keyfile = @file_get_contents($var['regFILE']);
if ($keyfile !== false) {
echo "\nSigning out of Unraid Connect\n";
$ch = curl_init('https://keys.lime-technology.com/account/server/unregister');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['keyfile' => @base64_encode($keyfile)]);
curl_exec($ch);
curl_close($ch);
}
}
# remove myservers.cfg
unlink('/boot/config/plugins/dynamix.my.servers/myservers.cfg');
# reload nginx to disable Remote Access
echo "\n⚠ Reloading Web Server. If this window stops updating for two minutes please close it.\n";
exec("/etc/rc.d/rc.nginx reload &>/dev/null");
}
exit(0);
]]>
</INLINE>
</FILE>
<!-- disable features when upgrading on unsupported OS versions -->
<!-- duplicated from above because the script can't distinguish between install and remove -->
<!-- NOTE: this script is PHP not bash -->
<FILE Run="/usr/bin/php" Method="install">
<INLINE>
<![CDATA[
<?
$ver = @parse_ini_file('/etc/unraid-version', true)['version'];
$msini = @parse_ini_file('/boot/config/plugins/dynamix.my.servers/myservers.cfg', true);
// exit this install block if NOT isUnsupportedVersion
// must be 6.12.0 or higher (not 6.12.0-[beta|rc])
if (version_compare($ver,'6.12.0','>=')) {
exit(0);
}
echo "\n";
echo "**********************************\n";
echo "🧹 CLEANING UP - may take a minute\n";
echo "**********************************\n";
if (file_exists("/boot/.git")) {
if (file_exists("/etc/rc.d/rc.flash_backup")) {
# stop flash backup service
echo "\nStopping flash backup service. Please wait…";
exec("/etc/rc.d/rc.flash_backup stop &>/dev/null");
}
if (file_exists("/usr/local/emhttp/plugins/dynamix.my.servers/include/UpdateFlashBackup.php")) {
# deactivate and delete local flash backup
echo "\nDeactivating flash backup. Please wait…";
passthru("/usr/bin/php /usr/local/emhttp/plugins/dynamix.my.servers/include/UpdateFlashBackup.php deactivate");
}
}
# set "Allow Remote Access" to "No" and sign out from Unraid Connect
if ($msini !== false) {
# stop unraid-api
echo "\nStopping unraid-api. Please wait…";
exec("/etc/rc.d/rc.unraid-api stop &>/dev/null");
if (!empty($msini['remote']['username'])) {
$var = parse_ini_file("/var/local/emhttp/var.ini");
$keyfile = @file_get_contents($var['regFILE']);
if ($keyfile !== false) {
echo "\nSigning out of Unraid Connect\n";
$ch = curl_init('https://keys.lime-technology.com/account/server/unregister');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['keyfile' => @base64_encode($keyfile)]);
curl_exec($ch);
curl_close($ch);
}
}
# remove myservers.cfg
unlink('/boot/config/plugins/dynamix.my.servers/myservers.cfg');
# reload nginx to disable Remote Access
echo "\n⚠ Reloading Web Server. If this window stops updating for two minutes please close it.\n";
exec("/etc/rc.d/rc.nginx reload &>/dev/null");
}
exit(0);
]]>
</INLINE>
</FILE>
<!-- uninstall existing plugin during update or removal -->
<FILE Run="/bin/bash" Method="install remove">
<INLINE>
MAINNAME="&name;"
<![CDATA[
version=
# shellcheck disable=SC1091
source /etc/unraid-version
echo
echo "⚠️ Do not close this window yet"
echo
if [ -e /etc/rc.d/rc.unraid-api ]; then
# stop flash backup
/etc/rc.d/rc.flash_backup stop &>/dev/null
# stop the api gracefully
/etc/rc.d/rc.unraid-api stop &>/dev/null
# forcibly stop older clients
kill -9 `pidof unraid-api` &>/dev/null
# uninstall the api
rm -rf /usr/local/unraid-api
rm -rf /var/log/unraid-api/
rm -f /var/run/unraid-api.sock
# uninstall the main source package
[[ -f "/var/log/packages/${MAINNAME}" ]] && removepkg --terse "${MAINNAME}"
# restore stock files
FILES_TO_RESTORE=(
"/usr/local/emhttp/plugins/dynamix/DisplaySettings.page"
"/usr/local/emhttp/plugins/dynamix/Registration.page"
"/usr/local/emhttp/plugins/dynamix/include/DefaultPageLayout.php"
"/usr/local/emhttp/plugins/dynamix/include/ProvisionCert.php"
"/usr/local/emhttp/plugins/dynamix/include/UpdateDNS.php"
"/usr/local/emhttp/plugins/dynamix/include/Wrappers.php"
"/usr/local/emhttp/plugins/dynamix.plugin.manager/Downgrade.page"
"/usr/local/emhttp/plugins/dynamix.plugin.manager/Update.page"
"/usr/local/emhttp/plugins/dynamix.plugin.manager/include/ShowChanges.php"
"/usr/local/emhttp/plugins/dynamix.plugin.manager/scripts/showchanges"
"/usr/local/emhttp/plugins/dynamix.plugin.manager/scripts/unraidcheck"
"/usr/local/emhttp/plugins/dynamix.plugin.manager/include/UnraidCheck.php"
"/usr/local/emhttp/plugins/dynamix.my.servers/Connect.page"
"/usr/local/emhttp/plugins/dynamix.my.servers/MyServers.page"
"/usr/local/emhttp/plugins/dynamix.my.servers/Registration.page"
"/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers1.php"
"/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers2.php"
"/usr/local/emhttp/plugins/dynamix.my.servers/include/state.php"
"/usr/local/emhttp/plugins/dynamix.my.servers/data/server-state.php"
"/usr/local/emhttp/plugins/dynamix.my.servers/include/reboot-details.php"
"/usr/local/emhttp/plugins/dynamix.my.servers/include/translations.php"
)
for FILE in "${FILES_TO_RESTORE[@]}"; do
[[ -f "$FILE-" ]] && mv -f "$FILE-" "$FILE"
done
DIR=/usr/local/emhttp/plugins/dynamix.my.servers/unraid-components
# certain instances where the directory is not present and others where it is, ensure we delete it before we restore it
if [[ -d "$DIR" ]]; then
rm -rf "$DIR"
fi
if [[ -d "$DIR-" ]]; then
mv -f "$DIR-" "$DIR"
fi
# delete plugin files from flash drive and OS
rm -f /boot/config/plugins/dynamix.my.servers/.gitignore
rm -f /etc/rc.d/rc.unraid-api
rm -f /etc/rc.d/rc.flash_backup
rm -f /usr/local/sbin/unraid-api
rm -f /usr/local/bin/unraid-api
rm -rf /usr/local/emhttp/plugins/dynamix.unraid.net
rm -rf /usr/local/emhttp/plugins/dynamix.unraid.net.staging
rm -f /etc/rc.d/rc6.d/K10_flash_backup
rm -f /var/log/gitcount
rm -f /var/log/gitflash
rm -f /var/log/gitratelimit
rm -f /usr/local/emhttp/state/flashbackup.ini
rm -f /usr/local/emhttp/state/myservers.cfg
# delete any legacy files that may exist
rm -rf /boot/config/plugins/dynamix.my.servers/libvirt.node
rm -rf /boot/config/plugins/dynamix.my.servers/segfault-handler.node
rm -rf /boot/config/plugins/dynamix.my.servers/wc
rm -f /boot/config/plugins/Unraid.net/unraid-api.tgz
rm -f /boot/config/plugins/Unraid.net/.gitignore
rm -rf /boot/config/plugins/Unraid.net/webComps
rm -rf /boot/config/plugins/Unraid.net/wc
rm -f /usr/local/emhttp/webGui/javascript/vue.js
rm -f /usr/local/emhttp/webGui/javascript/vue.min.js
rm -rf /usr/local/emhttp/webGui/webComps
rm -rf /usr/local/emhttp/webGui/wc
# clean up our optional makestate modifications in rc.nginx (on 6.9 and 6.10.0-rc[12])
sed -i '/scripts\/makestate/d' /etc/rc.d/rc.nginx
# clean up extra origin for robots.txt
sed -i '#robots.txt any origin/d' /etc/rc.d/rc.nginx
fi
exit 0
]]>
</INLINE>
</FILE>
<!-- install all the things -->
<FILE Run="/bin/bash" Method="install">
<INLINE>
PLGTYPE="&env;" MAINTXZ="&source;.txz"
<![CDATA[
appendTextIfMissing() {
FILE="$1" TEXT="$2"
if test -f "${FILE}" && ! grep -q "${TEXT}" "${FILE}" &>/dev/null; then
echo "${TEXT}">>"${FILE}"
fi
}
version=
# shellcheck disable=SC1091
source /etc/unraid-version
# exit this install block on isUnsupportedVersion
# must be 6.12.0 or higher (not 6.12.0-[beta|rc]x)
if [[ "${version:0:3}" == "6.9" || "${version:0:4}" == "6.10" || "${version:0:4}" == "6.11" || "${version:0:7}" == "6.12.0-" ]]; then
echo
echo "⚠️ Please uninstall this plugin or upgrade to a newer version of Unraid to enjoy Unraid Connect"
echo
echo "✅ It is safe to close this window"
echo
PLGNAME=dynamix.unraid.net
[ "${PLGTYPE}" = "staging" ] && PLGNAME=dynamix.unraid.net.staging
DIR="/usr/local/emhttp/plugins/${PLGNAME}" && [[ ! -d "$DIR" ]] && mkdir "$DIR"
cat << EOF > "$DIR/README.md"
**Unraid Connect**
Please uninstall this plugin or upgrade to a newer version of Unraid to enjoy Unraid Connect
EOF
# exit 0 or else the original plugin will be reinstalled at boot
exit 0
fi
echo
echo "⚠️ Do not close this window yet"
echo
# NOTE: any 'exit 1' after this point will result in a broken install
# Loop through the array of preserveFilesDirs and perform actions
# string param format
# "{move|copy|move_dir}:{path}:{preventDowngrade|skip}"
# move: move the file to a backup file
# copy: copy the file to a backup file
# move_dir: move the directory to a backup directory
# preventDowngrade: during plg install, if the file exists, do not overwrite it if the plg manifest version is less than the installed webgui version
# skip: do not perform any action if there is a manifest version difference
preserveFilesDirs=(
"move:/usr/local/emhttp/plugins/dynamix/Registration.page:preventDowngrade"
"copy:/usr/local/emhttp/plugins/dynamix/Notifications.page:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix/include/UpdateDNS.php:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.plugin.manager/Downgrade.page:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.plugin.manager/Update.page:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.plugin.manager/scripts/unraidcheck:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.plugin.manager/include/UnraidCheck.php:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/MyServers.page:skip"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/Connect.page:skip"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/Registration.page:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers1.php:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/include/myservers2.php:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/include/state.php:preventDowngrade"
"move_dir:/usr/local/emhttp/plugins/dynamix.my.servers/unraid-components:move_dir:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/data/server-state.php:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/include/reboot-details.php:preventDowngrade"
"move:/usr/local/emhttp/plugins/dynamix.my.servers/include/translations.php:preventDowngrade"
"copy:/usr/local/emhttp/plugins/dynamix/include/DefaultPageLayout.php:preventDowngrade"
)
preserveAction() {
local action="$1"
local path="$2"
if [[ "$action" == "move" ]]; then
[[ -f "$path" ]] && mv -f "$path" "$path-"
elif [[ "$action" == "copy" ]]; then
[[ -f "$path" ]] && cp -f "$path" "$path-"
elif [[ "$action" == "move_dir" ]]; then
[[ -d "$path" ]] && mv -f "$path" "$path-"
fi
}
# Loop through the array of preserveFilesDirs and perform actions
for obj in "${preserveFilesDirs[@]}"
do
IFS=':' read -r action path preventType <<< "$obj"
preserveAction "$action" "$path" "$preventType"
done
# patch DefaultPageLayout.php
# search text: <?=_('Version')?>: <?=_var($var,'version','?')?><?=$notes?>
# <?=_('Version')?>: <?=$var['version']?><?=$notes?>
# replacement text: <unraid-i18n-host><unraid-header-os-version></unraid-header-os-version></unraid-i18n-host>
FILE=/usr/local/emhttp/plugins/dynamix/include/DefaultPageLayout.php
# get line number matching the search text
# shellcheck disable=SC2016
LINENUM=$(grep -n '<?=_('"'Version'"')?>: <?=_var($var,'"'version'"','"'?'"')?><?=$notes?>' "$FILE" | cut -d : -f 1)
# shellcheck disable=SC2016
[[ -z $LINENUM ]] && LINENUM=$(grep -n '<?=_('"'Version'"')?>: <?=$var\['"'version'"']?><?=$notes?>' "$FILE" | cut -d : -f 1)
if [[ -n $LINENUM ]]; then
# backup the file so it can be restored later
cp -f "$FILE" "$FILE-"
# sed should work, but it is very difficult to escape the search text
# instead, make a new file containing everything before LINENUM, then the replacement text, then everything after LINENUM
head -$((LINENUM-1)) "$FILE"> "$FILE~"
echo '<unraid-i18n-host><unraid-header-os-version></unraid-header-os-version></unraid-i18n-host>' >> "$FILE~"
tail +$((LINENUM+1)) "$FILE">> "$FILE~"
# disable these lines: <?$readme = @file_get_contents("$docroot/plugins/unRAIDServer/README.md",false,null,0,20)?:''?>
# <?$readme = @file_get_contents("$docroot/plugins/unRAIDServer/README.md",false,null,0,20)??'';?>
# <?$readme = @file_get_contents("$docroot/plugins/unRAIDServer/README.md",false,null,0,20);?>
# by replacing with: <?$readme ="removed by Connect";?>
sed -i '/unRAIDServer\/README\.md/c\<?$readme ="removed by Connect";?>' "$FILE~"
mv -f "$FILE~" "$FILE"
fi
# Remove lines containing id='bell' or #bell and write to intermediate temporary file.
# This effectively removes the old notification bell from the webgui (via DefaultPageLayout.php).
TMP_FILE=$(mktemp)
grep -Ev "id='bell'|#bell" "$FILE" > "$TMP_FILE"
mv "$TMP_FILE" "$FILE"
echo "Removed notification-bell-related lines from $FILE"
# patch: showchanges, starting with 6.11.0-rc1
# ShowChanges.php, in 6.10
# search text: $valid = ['/var/tmp/','/tmp/plugins/'];
# replacement text: $valid = ['/var/tmp/','/tmp/plugins/','/boot/previous'];
FILES=(/usr/local/emhttp/plugins/dynamix.plugin.manager/scripts/showchanges /usr/local/emhttp/plugins/dynamix.plugin.manager/include/ShowChanges.php)
for FILE in "${FILES[@]}"; do
if test -f "${FILE}" && ! grep -q "'/boot/previous'" "${FILE}" &>/dev/null; then
# backup the file so it can be restored later
cp -f "$FILE" "$FILE-"
sed -i '/$valid = \[/c$valid = ['"'/var/tmp/'"','"'/tmp/plugins/'"','"'/boot/previous'"'];' "$FILE"
fi
done
# patch: Notifications.page
#
# Remove date and time format settings from Notification Settings
# search text: _(Date format)_:
# search text: _(Time format)_:
FILE=/usr/local/emhttp/plugins/dynamix/Notifications.page
TMP_FILE=$(mktemp)
cp "$FILE" "$TMP_FILE"
sed -i '/_(Date format)_:/,/:notifications_date_format_help:/d' $TMP_FILE
sed -i '/_(Time format)_:/,/:notifications_time_format_help:/d' $TMP_FILE
mv "$TMP_FILE" "$FILE"
# remove keys.limetechnology.com from hosts file
# brings older versions of Unraid in sync with 6.12.12
# no need to restore original file on uninstall
if grep -q "keys.lime-technology.com" /etc/hosts &>/dev/null; then sed -i "/keys.lime-technology.com/d" /etc/hosts &>/dev/null; fi
# patch ProvisionCert.php
# search text: curl_init("https://keys.lime-technology.com/account/ssl/provisionwildcard")
# curl_init("https://keys.lime-technology.com/account/ssl/$endpoint");
# prepend text: see $ADDTEXT4
ADDTEXT4=$(
cat <<'END_HEREDOC'
// added by Unraid Connect
// ensure keys.lime-technology.com is not hard-coded in the hosts file
exec('if grep -q "keys.lime-technology.com" /etc/hosts &>/dev/null; then sed -i "/keys.lime-technology.com/d" /etc/hosts &>/dev/null; fi');
END_HEREDOC
)
FILE=/usr/local/emhttp/plugins/dynamix/include/ProvisionCert.php
# get line number matching the search text
# shellcheck disable=SC2016
LINENUM=$(grep -n 'curl_init("https://keys.lime-technology.com/account/ssl/provisionwildcard")' "$FILE" | cut -d : -f 1)
[[ -z $LINENUM ]] && LINENUM=$(grep -n 'curl_init("https://keys.lime-technology.com/account/ssl/$endpoint")' "$FILE" | cut -d : -f 1)
if [[ -n $LINENUM ]]; then
# backup the file so it can be restored later
cp -f "$FILE" "$FILE-"
# sed should work, but it is very difficult to escape
# instead, make a new file containing everything before LINENUM, then the new text, then everything including and after LINENUM
head -$((LINENUM-1)) "$FILE"> "$FILE~"
echo "$ADDTEXT4">> "$FILE~"
echo "">> "$FILE~"
tail +$LINENUM "$FILE">> "$FILE~"
mv -f "$FILE~" "$FILE"
fi
# move settings on flash drive
CFG_OLD=/boot/config/plugins/Unraid.net
CFG_NEW=/boot/config/plugins/dynamix.my.servers
[[ -d "$CFG_OLD" ]] && [[ ! -d "$CFG_NEW" ]] && mv "$CFG_OLD" "$CFG_NEW"
# relax restrictions on built-in Firefox so it can sign in to Unraid Connect
# brings older versions of Unraid in sync with 6.12.0
# no need to restore original file on uninstall
# note: if file is modified while Firefox is open it will have no effect, reboot to change the file before Firefox is loaded
# note: prior to 6.12, file will only exist if system is booted in GUI Mode
FILE=/usr/share/mozilla/firefox/9n35r0i1.default/user.js
if [[ -f "$FILE" ]]; then
cp -f "$FILE" "$FILE-"
appendTextIfMissing "${FILE}" 'user_pref("privacy.firstparty.isolate", false);'
appendTextIfMissing "${FILE}" 'user_pref("javascript.options.asmjs", true);'
appendTextIfMissing "${FILE}" 'user_pref("javascript.options.wasm", true);'
fi
# fix update.htm to work in an iframe
# brings older versions of Unraid in sync with 6.12.0
# no need to restore original file on uninstall, will cause issues if uninstall from within an iframe
FILE=/usr/local/emhttp/update.htm
if test -f "${FILE}" && grep -q "top.document" "${FILE}" &>/dev/null; then
cp -f "$FILE" "$FILE-"
sed -i 's/top.document/parent.document/gm' "${FILE}"
fi
# fix logging.htm (openBox) to work in an iframe
# brings older versions of Unraid in sync with 6.12.0
# no need to restore original file on uninstall
FILE=/usr/local/emhttp/logging.htm
if test -f "${FILE}" && grep -q "top.Shadowbox" "${FILE}" &>/dev/null; then
cp -f "$FILE" "$FILE-"
sed -i 's/top.Shadowbox/parent.Shadowbox/gm' "${FILE}"
fi
# ensure _var() is defined, brings older versions of Unraid in sync with 6.12.0
FILE=/usr/local/emhttp/plugins/dynamix/include/Wrappers.php
if test -f "${FILE}" && ! grep -q "function _var" "${FILE}" &>/dev/null; then
ADDTEXT1=$(
cat <<'END_HEREDOC'
// backported by Unraid Connect
function _var(&$name, $key=null, $default='') {
return is_null($key) ? ($name ?? $default) : ($name[$key] ?? $default);
}
END_HEREDOC
)
fi
# ensure my_logger() is defined, brings older versions of Unraid in sync with 6.13.0
if test -f "${FILE}" && ! grep -q "function my_logger" "${FILE}" &>/dev/null; then
ADDTEXT2=$(
cat <<'END_HEREDOC'
// backported by Unraid Connect
// ensure params passed to logger are properly escaped
function my_logger($message, $logger='webgui') {
exec('logger -t '.escapeshellarg($logger).' -- '.escapeshellarg($message));
}
END_HEREDOC
)
fi
# ensure http_get_contents() is defined, brings older versions of Unraid in sync with 6.13.0
if test -f "${FILE}" && ! grep -q "function http_get_contents" "${FILE}" &>/dev/null; then
ADDTEXT3=$(
cat <<'END_HEREDOC'
// backported by Unraid Connect
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
// https://www.the-art-of-web.com/php/http-get-contents/
// Modified for Unraid
/**
* Fetches URL and returns content
* @param string $url The URL to fetch
* @param array $opts Array of options to pass to curl_setopt()
* @param array $getinfo Empty array passed by reference, will contain results of curl_getinfo and curl_error
* @return string|false $out The fetched content
*/
function http_get_contents(string $url, array $opts = [], array &$getinfo = NULL) {
$ch = curl_init();
if(isset($getinfo)) {
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Unraid');
if(is_array($opts) && $opts) {
foreach($opts as $key => $val) {
curl_setopt($ch, $key, $val);
}
}
$out = curl_exec($ch);
if (curl_errno($ch) == 23) {
// error 23 detected, try CURLOPT_ENCODING = "deflate"
curl_setopt($ch, CURLOPT_ENCODING, "deflate");
$out = curl_exec($ch);
}
if (isset($getinfo)) {
$getinfo = curl_getinfo($ch);
}
if ($errno = curl_errno($ch)) {
$msg = "Curl error $errno: " . (curl_error($ch) ?: curl_strerror($errno)) . ". Requested url: '$url'";
if(isset($getinfo)) {
$getinfo['error'] = $msg;
}
my_logger($msg, "http_get_contents");
}
curl_close($ch);
return $out;
}
END_HEREDOC
)
fi
if [[ -n "${ADDTEXT1}" || -n "${ADDTEXT2}" || -n "${ADDTEXT3}" ]]; then
TMP="$FILE.$RANDOM"
cp -f "$FILE" "$TMP"
cp -f "$FILE" "$FILE-"
# delete last line of the file if it contains `?>`
if test $( tail -n 1 "${TMP}" ) = '?>' ; then
sed -i '$ d' "${TMP}"
fi
[[ -n "${ADDTEXT1}" ]] && echo "${ADDTEXT1}">>"${TMP}"
[[ -n "${ADDTEXT2}" ]] && echo "${ADDTEXT2}">>"${TMP}"
[[ -n "${ADDTEXT3}" ]] && echo "${ADDTEXT3}">>"${TMP}"
echo "?>">>"${TMP}"
mv "${TMP}" "${FILE}"
fi
# Restore the upgradepkg binary if it exists and the original does not
if [[ -f /sbin/upgradepkg- && ! -f /sbin/upgradepkg ]]; then
cp -f /sbin/upgradepkg- /sbin/upgradepkg
fi
# install the main txz
upgradepkg --install-new --reinstall "${MAINTXZ}"
# confirm an expected file now exists
# WARNING: failure here results in broken install
[[ ! -f /usr/local/emhttp/plugins/dynamix.my.servers/scripts/gitflash_log ]] && echo "⚠️ files missing from main txz" && exit 1
echo
echo "⚠️ Do not close this window yet"
echo
# setup env
if [ "${PLGTYPE}" = "production" ] || [ ! -f /boot/config/plugins/dynamix.my.servers/env ]; then
echo "env=\"${PLGTYPE}\"">/boot/config/plugins/dynamix.my.servers/env
fi
# Use myservers.cfg values to help prevent conflicts when installing
CFG=/boot/config/plugins/dynamix.my.servers/myservers.cfg
# shellcheck disable=SC1090
source <(grep 'email\|apikey="unraid_' "${CFG}" 2>/dev/null)
CFG_CLEANED=0
# If user is signed in but has no apikey, or if the apikey is not 64 chars, wipe the [remote] section from the cfg
if ([[ -n "${email}" && (-z "${apikey}" || "${#apikey}" -ne "64") ]]); then
# remove only the [remote] section
awk '{
if($0 ~ /\[remote\]/){output="off"; next}
if($0 ~ /\[/){output="on"; print; next}
if(output == "on"){print}
}' "${CFG}">"${CFG}-new" && mv "${CFG}-new" "${CFG}" CFG_CLEANED=1
echo "⚠️ Automatically signed out of Unraid.net"
fi
# if there wasn't an email or the CFG was cleaned
if [[ -z "${email}" ]] || [[ CFG_CLEANED -eq 1 ]]; then
echo "✨ Sign In to Unraid.net to use Unraid Connect ✨"
fi
# configure flash backup to stop when the system starts shutting down
[[ ! -d /etc/rc.d/rc6.d ]] && mkdir /etc/rc.d/rc6.d
[[ ! -h /etc/rc.d/rc0.d ]] && ln -s /etc/rc.d/rc6.d /etc/rc.d/rc0.d
[[ ! -h /etc/rc.d/rc6.d/K10_flash_backup ]] && ln -s /etc/rc.d/rc.flash_backup /etc/rc.d/rc6.d/K10_flash_backup
# allow webgui to be iframed only on Connect dashboard, only applies to 6.10+
# if needed, restart nginx before installing the unraid-api
CHANGED=no
FILE=/etc/nginx/nginx.conf
# brings older versions of Unraid in sync with 6.12.0
if grep -q "SAMEORIGIN" "${FILE}"; then
CHANGED=yes
cp "$FILE" "$FILE-" OLD="add_header X-Frame-Options 'SAMEORIGIN';" NEW="add_header Content-Security-Policy \"frame-ancestors 'self' https://connect.myunraid.net/\";"
sed -i "s#${OLD}#${NEW}#" "${FILE}"
fi
if [ "${PLGTYPE}" = "staging" ]; then
# staging plugin allows an additional origin
if ! grep -q "dev-my.myunraid.net:4000" "${FILE}"; then
CHANGED=yes
[[ ! -f "$FILE-" ]] && cp "$FILE" "$FILE-" OLD="add_header Content-Security-Policy \"frame-ancestors 'self' https://connect.myunraid.net/\";" NEW="add_header Content-Security-Policy \"frame-ancestors 'self' https://connect-staging.myunraid.net https://connect.myunraid.net/ https://dev-my.myunraid.net:4000/\";"
sed -i "s#${OLD}#${NEW}#" "${FILE}"
fi
fi
FILE=/etc/rc.d/rc.nginx
# brings older versions of Unraid in sync with 6.12.0
if ! grep -q "#robots.txt any origin" "${FILE}"; then
CHANGED=yes
cp "$FILE" "$FILE-" FIND="location = \/robots.txt {"
# escape tabs and spaces
ADD="\ \ \ \ \ add_header Access-Control-Allow-Origin *; #robots.txt any origin"
sed -i "/${FIND}/a ${ADD}" "${FILE}"
fi
if [[ "${CHANGED}" == "yes" ]]; then
if /etc/rc.d/rc.nginx status &>/dev/null; then
# if nginx is running, reload it to enable the changes above
# note: if this is being installed at boot, nginx will not yet be running
echo ""
echo "⚠️ Reloading Web Server. If this window stops updating for two minutes please close it."
/etc/rc.d/rc.nginx reload &>/dev/null
fi
fi
# Prevent web component file downgrade if the webgui version is newer than the plugin version
# Function to extract "ts" value from JSON file
extract_ts() {
local filepath="$1"
local ts_value=null
ts_value=$(jq -r '.ts' "$filepath" 2>/dev/null)
echo "$ts_value"
}
preventDowngradeAction() {
local action="$1"
local path="$2"
local preventType="$3" # preventDowngrade or skip
# if skip, do nothing
if [[ "$preventType" == "skip" ]]; then
return
fi
# restore the "backup" but keep the original backup for the uninstall plg script
# otherwise, the uninstall script will NOT be able to restore the original file
if [[ "$action" == "move" || "$action" == "copy" ]]; then
[[ -f "$path-" ]] && cp -f "$path-" "$path"
elif [[ "$action" == "move_dir" ]]; then
# if directory exists rm the original and copy the backup
# glob expansion via "$path-/"* …yes the * is necessary as we want to copy the contents of the directory
[[ -d "$path-" ]] && rm -rf "$path" && mkdir "$path" && cp -rf "$path-/"* "$path"
fi
}
# Extract "ts" values from both files
plgWebComponentPath="/usr/local/emhttp/plugins/dynamix.my.servers/unraid-components"
backupWebComponentPath="/usr/local/emhttp/plugins/dynamix.my.servers/unraid-components-"
plgManifestTs=$(extract_ts "$plgWebComponentPath/manifest.json")
webguiManifestTs=$(extract_ts "$backupWebComponentPath/manifest.json")
# Compare the "ts" values and return the file path of the higher value
if [[ "$webguiManifestTs" -gt "$plgManifestTs" ]]; then
# Loop through the array of preserveFilesDirs and perform actions
for obj in "${preserveFilesDirs[@]}"
do
IFS=':' read -r action path preventType <<< "$obj"
preventDowngradeAction "$action" "$path" "$preventType"
done
echo "♻️ Reverted to stock web component files"
fi
echo
echo "⚠️ Do not close this window yet"
echo
# Activation and partner setup
# - Must come after the web component timestamp check to avoid potentially targeting the wrong JS during this setup
source /usr/local/emhttp/plugins/dynamix.my.servers/scripts/activation_code_setup
# Install the API (previously in rc.d script)
echo "Extracting and installing the Unraid API"
flash="/boot/config/plugins/dynamix.my.servers"
[[ ! -d "${flash}" ]] && echo "Please reinstall the Unraid Connect plugin" && exit 1
[[ ! -f "${flash}/env" ]] && echo 'env=production' >"${flash}/env"
env=production
# shellcheck disable=SC1091
source "${flash}/env"
# Install the API to /usr/local/unraid-api
api_base_directory="/usr/local/unraid-api"
unraid_binary_path="/usr/local/bin/unraid-api"
# Ensure installation tgz exists
[[ ! -f "${flash}/unraid-api.tgz" ]] && echo "Missing unraid-api.tgz" && exit 1
# Stop old process
[[ -f "${unraid_binary_path}" ]] && ${unraid_binary_path} stop
# Install unraid-api
rm -rf "${api_base_directory}"
mkdir -p "${api_base_directory}"
# Create log directory (PM2 will not start without it)
mkdir -p /var/log/unraid-api
tar -C "${api_base_directory}" -xzf "${flash}/unraid-api.tgz" --strip 1
# Copy env file
cp "${api_base_directory}/.env.${env}" "${api_base_directory}/.env"
npm link "${api_base_directory}" --force
# Create symlink to unraid-api binary (to allow usage elsewhere)
ln -sf /usr/local/bin/unraid-api /usr/local/sbin/unraid-api
ln -sf /usr/local/bin/unraid-api /usr/bin/unraid-api
# bail if expected file does not exist
[[ ! -f "${api_base_directory}/package.json" ]] && echo "unraid-api install failed" && exit 1
logger "Starting flash backup (if enabled)"
echo "/etc/rc.d/rc.flash_backup start" | at -M now &>/dev/null
logger "Starting Unraid API"
${unraid_binary_path} start
echo
echo "✅ Installation is complete, it is safe to close this window"
echo
exit 0
]]>
</INLINE>
</FILE>
<FILE Run="/bin/bash" Method="remove">
<INLINE>
<![CDATA[
version=
# shellcheck disable=SC1091
source /etc/unraid-version
echo
echo "✅ Uninstall is complete, it is safe to close this window"
echo
exit 0
]]>
</INLINE>
</FILE>
</PLUGIN>