From 80ab8d76eb6708610da377a58b15ee22f1e780be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E8=AF=9A?= Date: Thu, 27 Feb 2025 16:58:21 +0800 Subject: [PATCH] init --- .dockerignore | 25 ++ .gitignore | 402 ++++++++++++++++++ .gitlab-ci.yml | 34 ++ Dockerfile | 26 ++ LICENSE | 201 +++++++++ NasRobot.sln | 48 +++ NasRobot.sln.DotSettings | 2 + README.md | 93 ++++ docker-compose.yml | 32 ++ src/Core/Command.cs | 23 + src/Core/Core.csproj | 15 + src/Core/Tools.cs | 9 + src/Core/WxNotify.cs | 53 +++ src/Interface/Interface.csproj | 9 + src/Interface/Jobs/IChineseNfoRegistry.cs | 6 + .../Jobs/IDiskActionMonitorRegistry.cs | 6 + src/Interface/Jobs/IHealthyTaskRegistry.cs | 6 + .../Jobs/ILogTotalNotifyJobRegistry.cs | 6 + src/Interface/Jobs/IRSyncTaskRegistry.cs | 6 + src/Interface/Jobs/IShutdownRegistry.cs | 8 + src/Interface/Jobs/IStartupRegistry.cs | 6 + src/Service/Jobs/ChineseNfoRegistry.cs | 245 +++++++++++ src/Service/Jobs/DiskActionMonitorRegistry.cs | 174 ++++++++ src/Service/Jobs/HealthyTaskRegistry.cs | 95 +++++ src/Service/Jobs/LogTotalNotifyJobRegistry.cs | 106 +++++ src/Service/Jobs/RSyncTaskRegistry.cs | 69 +++ src/Service/Jobs/ShutdownRegistry.cs | 61 +++ src/Service/Jobs/StartupRegistry.cs | 46 ++ src/Service/Service.csproj | 18 + src/WebApi/Controllers/BaseController.cs | 9 + .../Controllers/JobTriggerController.cs | 101 +++++ src/WebApi/Controllers/NotifyController.cs | 319 ++++++++++++++ src/WebApi/Controllers/XiaoController.cs | 34 ++ src/WebApi/Program.cs | 51 +++ src/WebApi/Properties/launchSettings.json | 15 + src/WebApi/WebApi.csproj | 20 + src/WebApi/appsettings.Development.json | 36 ++ src/WebApi/appsettings.json | 65 +++ src/WebApi/mocks/disk_sdb/stat.txt | 1 + src/WebApi/mocks/disk_sdc1/stat.txt | 1 + 40 files changed, 2482 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 NasRobot.sln create mode 100644 NasRobot.sln.DotSettings create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 src/Core/Command.cs create mode 100644 src/Core/Core.csproj create mode 100644 src/Core/Tools.cs create mode 100644 src/Core/WxNotify.cs create mode 100644 src/Interface/Interface.csproj create mode 100644 src/Interface/Jobs/IChineseNfoRegistry.cs create mode 100644 src/Interface/Jobs/IDiskActionMonitorRegistry.cs create mode 100644 src/Interface/Jobs/IHealthyTaskRegistry.cs create mode 100644 src/Interface/Jobs/ILogTotalNotifyJobRegistry.cs create mode 100644 src/Interface/Jobs/IRSyncTaskRegistry.cs create mode 100644 src/Interface/Jobs/IShutdownRegistry.cs create mode 100644 src/Interface/Jobs/IStartupRegistry.cs create mode 100644 src/Service/Jobs/ChineseNfoRegistry.cs create mode 100644 src/Service/Jobs/DiskActionMonitorRegistry.cs create mode 100644 src/Service/Jobs/HealthyTaskRegistry.cs create mode 100644 src/Service/Jobs/LogTotalNotifyJobRegistry.cs create mode 100644 src/Service/Jobs/RSyncTaskRegistry.cs create mode 100644 src/Service/Jobs/ShutdownRegistry.cs create mode 100644 src/Service/Jobs/StartupRegistry.cs create mode 100644 src/Service/Service.csproj create mode 100644 src/WebApi/Controllers/BaseController.cs create mode 100644 src/WebApi/Controllers/JobTriggerController.cs create mode 100644 src/WebApi/Controllers/NotifyController.cs create mode 100644 src/WebApi/Controllers/XiaoController.cs create mode 100644 src/WebApi/Program.cs create mode 100644 src/WebApi/Properties/launchSettings.json create mode 100644 src/WebApi/WebApi.csproj create mode 100644 src/WebApi/appsettings.Development.json create mode 100644 src/WebApi/appsettings.json create mode 100644 src/WebApi/mocks/disk_sdb/stat.txt create mode 100644 src/WebApi/mocks/disk_sdc1/stat.txt diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..cd967fc --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.idea +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..593bd61 --- /dev/null +++ b/.gitignore @@ -0,0 +1,402 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + + + +.idea/ \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..f42680c --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,34 @@ +# This file is a template, and might need editing before it works on your project. +# This is a sample GitLab CI/CD configuration file that should run without any modifications. +# It demonstrates a basic 3 stage CI/CD pipeline. Instead of real tests or scripts, +# it uses echo commands to simulate the pipeline execution. +# +# A pipeline is composed of independent jobs that run scripts, grouped into stages. +# Stages run in sequential order, but jobs within stages run in parallel. +# +# For more information, see: https://docs.gitlab.com/ee/ci/yaml/index.html#stages +# +# You can copy and paste this template into a new `.gitlab-ci.yml` file. +# You should not add this template to an existing `.gitlab-ci.yml` file by using the `include:` keyword. +# +# To contribute improvements to CI/CD templates, please follow the Development guide at: +# https://docs.gitlab.com/ee/development/cicd/templates.html +# This specific template is located at: +# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Getting-Started.gitlab-ci.yml + +stages: # List of stages for jobs, and their order of execution + - build + - deploy + +build-job: # This job runs in the build stage, which runs first. + stage: build + script: + - docker compose down || true + - docker rmi nasrobot-nas_robot || true + - docker build -t nasrobot . + +deploy-job: # This job runs in the deploy stage. + stage: deploy # It only runs when *both* jobs in the test stage complete successfully. + environment: production + script: + - docker compose up -d diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..862cdc0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +USER $APP_UID +WORKDIR /app +EXPOSE 8080 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build + +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["src/Core/Core.csproj", "src/Core/"] +COPY ["src/Interface/Interface.csproj", "src/Interface/"] +COPY ["src/Service/Service.csproj", "src/Service/"] +COPY ["src/WebApi/WebApi.csproj", "src/WebApi/"] +RUN dotnet restore "src/WebApi/WebApi.csproj" +COPY . . +WORKDIR "/src/src/WebApi" +RUN dotnet build "WebApi.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "WebApi.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "WebApi.dll"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NasRobot.sln b/NasRobot.sln new file mode 100644 index 0000000..a10c299 --- /dev/null +++ b/NasRobot.sln @@ -0,0 +1,48 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service", "src\Service\Service.csproj", "{29086FBF-8355-49A5-92B6-43FD6BF581F0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "src\Core\Core.csproj", "{DEFCBF73-B2BF-4032-99FD-122A71B51032}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi", "src\WebApi\WebApi.csproj", "{F80D68C6-9C66-4564-9D48-988BC10F825A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D89A3F4D-DFEA-4061-8924-CA8B2424ADA0}" + ProjectSection(SolutionItems) = preProject + docker-compose.yml = docker-compose.yml + Dockerfile = Dockerfile + .dockerignore = .dockerignore + .gitlab-ci.yml = .gitlab-ci.yml + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interface", "src\Interface\Interface.csproj", "{204D20C6-39DE-4F64-8392-C8032F3FA417}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {29086FBF-8355-49A5-92B6-43FD6BF581F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {29086FBF-8355-49A5-92B6-43FD6BF581F0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {29086FBF-8355-49A5-92B6-43FD6BF581F0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {29086FBF-8355-49A5-92B6-43FD6BF581F0}.Release|Any CPU.Build.0 = Release|Any CPU + {DEFCBF73-B2BF-4032-99FD-122A71B51032}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DEFCBF73-B2BF-4032-99FD-122A71B51032}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DEFCBF73-B2BF-4032-99FD-122A71B51032}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DEFCBF73-B2BF-4032-99FD-122A71B51032}.Release|Any CPU.Build.0 = Release|Any CPU + {F80D68C6-9C66-4564-9D48-988BC10F825A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F80D68C6-9C66-4564-9D48-988BC10F825A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F80D68C6-9C66-4564-9D48-988BC10F825A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F80D68C6-9C66-4564-9D48-988BC10F825A}.Release|Any CPU.Build.0 = Release|Any CPU + {204D20C6-39DE-4F64-8392-C8032F3FA417}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {204D20C6-39DE-4F64-8392-C8032F3FA417}.Debug|Any CPU.Build.0 = Debug|Any CPU + {204D20C6-39DE-4F64-8392-C8032F3FA417}.Release|Any CPU.ActiveCfg = Release|Any CPU + {204D20C6-39DE-4F64-8392-C8032F3FA417}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/NasRobot.sln.DotSettings b/NasRobot.sln.DotSettings new file mode 100644 index 0000000..900cec7 --- /dev/null +++ b/NasRobot.sln.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..896c2ae --- /dev/null +++ b/README.md @@ -0,0 +1,93 @@ +# NasRobot + + + +## Getting started + +To make it easy for you to get started with GitLab, here's a list of recommended next steps. + +Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + +## Add your files + +- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files +- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: + +``` +cd existing_repo +git remote add origin http://c1283ff797ac/root/nasrobot.git +git branch -M main +git push -uf origin main +``` + +## Integrate with your tools + +- [ ] [Set up project integrations](http://c1283ff797ac/root/nasrobot/-/settings/integrations) + +## Collaborate with your team + +- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) +- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) +- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) +- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) +- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) +- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) +- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) +- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) +- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) + +*** + +# Editing this README + +When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. + +## Suggestions for a good README + +Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + +## Name +Choose a self-explaining name for your project. + +## Description +Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + +## Badges +On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + +## Visuals +Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + +## Installation +Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +## Usage +Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. + +## Support +Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. + +## Roadmap +If you have ideas for releases in the future, it is a good idea to list them in the README. + +## Contributing +State if you are open to contributions and what your requirements are for accepting them. + +For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + +You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. + +## Authors and acknowledgment +Show your appreciation to those who have contributed to the project. + +## License +For open source projects, say how it is licensed. + +## Project status +If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..2995091 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,32 @@ +services: + nas_robot: + build: + context: . + dockerfile: Dockerfile + container_name: nas_robot + restart: always + networks: + - all_in + environment: + - TZ=Asia/Shanghai + volumes: + - /etc/localtime:/etc/localtime:ro + - /wd/volc/media/tv:/data/tv + + nas_robot_proxy: + image: beevelop/nginx-basic-auth:v2023.10.1 + container_name: nas_robot_proxy + restart: always + networks: + - all_in + ports: + - 35642:80 # 开放端口 + environment: + - TZ=Asia/Shanghai + - HTPASSWD=suncheng:$$apr1$$2QX32QHP$$HIGAbCuTt8jxdc4uDzNLI1 + - FORWARD_PORT=8080 + - FORWARD_HOST=nas_robot + +networks: + all_in: + external: true \ No newline at end of file diff --git a/src/Core/Command.cs b/src/Core/Command.cs new file mode 100644 index 0000000..10da212 --- /dev/null +++ b/src/Core/Command.cs @@ -0,0 +1,23 @@ +using System.Net; +using System.Net.Http.Json; + +namespace Core; + +public static class Command +{ + public static async Task<(HttpStatusCode responseCode, string responseStr)> ExecAsync(params string[] commands) + { + var execUrl = "http://192.168.31.14:45321/exec"; + + var client = new HttpClient(); + var content = JsonContent.Create(new + { + Token = "4CeVaIQGbB4Qln9%V@Bh8bMYSpHIUV66", + Script = commands + }); + + var response = await client.PostAsync(execUrl, content); + + return (response.StatusCode, await response.Content.ReadAsStringAsync()); + } +} \ No newline at end of file diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj new file mode 100644 index 0000000..200c948 --- /dev/null +++ b/src/Core/Core.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/src/Core/Tools.cs b/src/Core/Tools.cs new file mode 100644 index 0000000..0edb4cc --- /dev/null +++ b/src/Core/Tools.cs @@ -0,0 +1,9 @@ +namespace Core; + +public static class Tools +{ + public static long ToUnixTimeMilliseconds(this DateTime dateTime) + { + return new DateTimeOffset(dateTime).ToUnixTimeMilliseconds(); + } +} \ No newline at end of file diff --git a/src/Core/WxNotify.cs b/src/Core/WxNotify.cs new file mode 100644 index 0000000..a629344 --- /dev/null +++ b/src/Core/WxNotify.cs @@ -0,0 +1,53 @@ +using System.Text; + +namespace Core; + +public static class WxNotify +{ + public static async Task SendDiskInfoAsync(string msg) + { + // 晚上11点到早上8点不通知,输出到控制台 + if (DateTime.Now.Hour >= 23 || DateTime.Now.Hour < 8) + { + Console.WriteLine("======================Skip WxNotify======================"); + Console.WriteLine(msg); + Console.WriteLine("======================Skip WxNotify======================"); + return; + } + + var wxRebotUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=96f9fa23-a959-4492-ac3a-7415fae19680"; + var client = new HttpClient(); + var requestBody = + """ + { + "msgtype": "markdown", + "markdown": { + "content": "{Msg}" + } + } + """; + + // 转义 + requestBody = requestBody.Replace("{Msg}", msg.Replace("\r\n", "\n")); + await client.PostAsync(wxRebotUrl, new StringContent(requestBody, Encoding.UTF8, "application/json")); + } + + public static async Task SendCommonAsync(string msg) + { + var wxRebotUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=96f9fa23-a959-4492-ac3a-7415fae19680"; + var client = new HttpClient(); + var requestBody = + """ + { + "msgtype": "markdown", + "markdown": { + "content": "{Msg}" + } + } + """; + + // 转义 + requestBody = requestBody.Replace("{Msg}", msg.Replace("\r\n", "\n")); + await client.PostAsync(wxRebotUrl, new StringContent(requestBody, Encoding.UTF8, "application/json")); + } +} \ No newline at end of file diff --git a/src/Interface/Interface.csproj b/src/Interface/Interface.csproj new file mode 100644 index 0000000..3a63532 --- /dev/null +++ b/src/Interface/Interface.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/src/Interface/Jobs/IChineseNfoRegistry.cs b/src/Interface/Jobs/IChineseNfoRegistry.cs new file mode 100644 index 0000000..9c9b544 --- /dev/null +++ b/src/Interface/Jobs/IChineseNfoRegistry.cs @@ -0,0 +1,6 @@ +namespace Interface.Jobs; + +public interface IChineseNfoRegistry +{ + void Job(bool ignoreLocked, bool ignoreCompleted); +} \ No newline at end of file diff --git a/src/Interface/Jobs/IDiskActionMonitorRegistry.cs b/src/Interface/Jobs/IDiskActionMonitorRegistry.cs new file mode 100644 index 0000000..68de15a --- /dev/null +++ b/src/Interface/Jobs/IDiskActionMonitorRegistry.cs @@ -0,0 +1,6 @@ +namespace Interface.Jobs; + +public interface IDiskActionMonitorRegistry +{ + void Job(); +} \ No newline at end of file diff --git a/src/Interface/Jobs/IHealthyTaskRegistry.cs b/src/Interface/Jobs/IHealthyTaskRegistry.cs new file mode 100644 index 0000000..0a5560e --- /dev/null +++ b/src/Interface/Jobs/IHealthyTaskRegistry.cs @@ -0,0 +1,6 @@ +namespace Interface.Jobs; + +public interface IHealthyTaskRegistry +{ + void Job(); +} \ No newline at end of file diff --git a/src/Interface/Jobs/ILogTotalNotifyJobRegistry.cs b/src/Interface/Jobs/ILogTotalNotifyJobRegistry.cs new file mode 100644 index 0000000..afc29c5 --- /dev/null +++ b/src/Interface/Jobs/ILogTotalNotifyJobRegistry.cs @@ -0,0 +1,6 @@ +namespace Interface.Jobs; + +public interface ILogTotalNotifyJobRegistry +{ + void Job(); +} \ No newline at end of file diff --git a/src/Interface/Jobs/IRSyncTaskRegistry.cs b/src/Interface/Jobs/IRSyncTaskRegistry.cs new file mode 100644 index 0000000..030bf7e --- /dev/null +++ b/src/Interface/Jobs/IRSyncTaskRegistry.cs @@ -0,0 +1,6 @@ +namespace Interface.Jobs; + +public interface IRSyncTaskRegistry +{ + void Job(); +} \ No newline at end of file diff --git a/src/Interface/Jobs/IShutdownRegistry.cs b/src/Interface/Jobs/IShutdownRegistry.cs new file mode 100644 index 0000000..2bebb9e --- /dev/null +++ b/src/Interface/Jobs/IShutdownRegistry.cs @@ -0,0 +1,8 @@ +namespace Interface.Jobs; + +public interface IShutdownRegistry +{ + void Job(); + + Task CancelShutdown(); +} \ No newline at end of file diff --git a/src/Interface/Jobs/IStartupRegistry.cs b/src/Interface/Jobs/IStartupRegistry.cs new file mode 100644 index 0000000..22d44ed --- /dev/null +++ b/src/Interface/Jobs/IStartupRegistry.cs @@ -0,0 +1,6 @@ +namespace Interface.Jobs; + +public interface IStartupRegistry +{ + void Job(); +} \ No newline at end of file diff --git a/src/Service/Jobs/ChineseNfoRegistry.cs b/src/Service/Jobs/ChineseNfoRegistry.cs new file mode 100644 index 0000000..3697448 --- /dev/null +++ b/src/Service/Jobs/ChineseNfoRegistry.cs @@ -0,0 +1,245 @@ +using System.Net; +using System.Text.Json.Nodes; +using System.Xml; +using FluentScheduler; +using Interface.Jobs; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace Service.Jobs; + +public class ChineseNfoRegistry : Registry, IChineseNfoRegistry +{ + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + private readonly HttpClient _client; + + public ChineseNfoRegistry(IConfiguration configuration, ILogger logger) + { + _configuration = configuration; + _logger = logger; + + var proxyAddress = _configuration["ChineseNfo:HttpProxy"]; + var httpClientHandler = new HttpClientHandler + { + Proxy = string.IsNullOrEmpty(proxyAddress) ? null : new WebProxy(proxyAddress, false), + UseProxy = !string.IsNullOrEmpty(proxyAddress) + }; + + _client = new HttpClient(httpClientHandler); + _client.BaseAddress = new Uri("https://api.themoviedb.org"); + + Schedule(() => Job(true, true)).ToRunEvery(1).Days(); + } + + public async void Job(bool ignoreLocked, bool ignoreCompleted) + { + try + { + await JobExecute(ignoreLocked, ignoreCompleted); + } + catch (Exception e) + { + _logger.LogError(e, "ChineseNfoRegistry.Job() error"); + } + } + + + private async Task JobExecute(bool ignoreLocked, bool ignoreCompleted) + { + // 读取环境变量 tv folder + var tvFolder = _configuration["ChineseNfo:TvFolder"]; + if (string.IsNullOrEmpty(tvFolder)) + { + Console.WriteLine("请设置环境变量 tv_folder"); + return; + } + + // 扫描 tvshow.nfo 文件 + var tvShowFiles = Directory.GetFiles(tvFolder, "tvshow.nfo", SearchOption.AllDirectories); + + foreach (var tvShowFile in tvShowFiles) + { + var nfoContent = File.ReadAllText(tvShowFile); + + // 读取 使用XML解析器 读取 60059 + var tvXml = new XmlDocument(); + tvXml.LoadXml(nfoContent); + var uniqueIdNode = tvXml.SelectSingleNode("//uniqueid[@type='tmdb']"); + if (uniqueIdNode == null) + { + Console.WriteLine($"{tvShowFile} & 未找到 tmdb id"); + continue; + } + + if (!int.TryParse(uniqueIdNode.InnerText, out var tmdbId)) + { + Console.WriteLine($"{tvShowFile} & tmdb id 不是数字"); + continue; + } + + // 获取 tvShowFile 的文件夹 + var folderPath = Path.GetDirectoryName(tvShowFile); + + if (folderPath == null) + { + Console.WriteLine($"{tvShowFile} & 未找到文件夹"); + continue; + } + + // 扫描文件夹下其他 nfo 文件 + var seasonFiles = Directory.GetFiles(folderPath, "*.nfo", SearchOption.AllDirectories); + + seasonFiles = seasonFiles.Where(x => !x.EndsWith("tvshow.nfo")).ToArray(); + + foreach (var seasonFile in seasonFiles) + { + var episodeContent = File.ReadAllText(seasonFile); + var episodeXml = new XmlDocument(); + episodeXml.LoadXml(episodeContent); + + // 判断有无 completed 节点 + var completedNode = episodeXml.SelectSingleNode("//completed"); + if (completedNode != null && ignoreCompleted == false) + { + Console.WriteLine($"{seasonFile} & 已完成"); + continue; + } + + // 判断 locked == true + var lockedNode = episodeXml.SelectSingleNode("//lockdata"); + if (lockedNode != null && lockedNode.InnerText == "true" && ignoreLocked == false) + { + Console.WriteLine($"{seasonFile} & 已锁定"); + continue; + } + + // 读取 1 + var seasonNode = episodeXml.SelectSingleNode("//season"); + if (seasonNode == null) + { + Console.WriteLine($"{seasonFile} & 未找到 season"); + continue; + } + + // 读取 1 + var episodeNode = episodeXml.SelectSingleNode("//episode"); + if (episodeNode == null) + { + Console.WriteLine($"{seasonFile} & 未找到 episode"); + continue; + } + + if (!int.TryParse(seasonNode.InnerText, out var season)) + { + Console.WriteLine($"{seasonFile} & season 不是数字"); + continue; + } + + if (!int.TryParse(episodeNode.InnerText, out var episode)) + { + Console.WriteLine($"{seasonFile} & episode 不是数字"); + continue; + } + + // 设置 title + var titleNode = episodeXml.SelectSingleNode("//title"); + if (titleNode == null) + { + Console.WriteLine($"{seasonFile} & 未找到 title"); + continue; + } + + var json = await GetTmdbEpisode(tmdbId, season, episode); + + if (json == null) + { + continue; + } + + var title = json["name"]?.ToString(); + var overview = json["overview"]?.ToString(); + + var isUpdate = false; + if (!string.IsNullOrEmpty(title)) + { + title = $""; + + if (titleNode.InnerXml != title) + { + isUpdate = true; + // 写入且不转义 + titleNode.InnerXml = title; + } + } + + var plotNode = episodeXml.SelectSingleNode("//plot"); + + if (!string.IsNullOrEmpty(overview) && plotNode != null) + { + overview = $""; + if (plotNode.InnerXml != overview) + { + isUpdate = true; + plotNode.InnerXml = overview; + } + } + + if (isUpdate) + { + // 添加一个已完成节点 + if (completedNode == null) + { + episodeXml.DocumentElement?.AppendChild(episodeXml.CreateElement("completed")); + } + + // 锁定 + if (lockedNode == null) + { + lockedNode = episodeXml.CreateElement("lockdata"); + episodeXml.DocumentElement?.AppendChild(lockedNode); + lockedNode.InnerText = "true"; + } + else + { + lockedNode.InnerText = "true"; + } + + episodeXml.Save(seasonFile); + Console.WriteLine($"{seasonFile} & {title} & {overview}"); + } + else + { + Console.WriteLine($"{seasonFile} & 无更新"); + } + + await Task.Delay(10000); + } + } + } + + private async Task GetTmdbEpisode(int tmdbId, int season, int episode) + { + try + { + const string episodeUrl = "/3/tv/{0}/season/{1}/episode/{2}?api_key=e28e1bc408db7adefc8bacce225c5085&language=zh-CN"; + + var requestUrl = string.Format(episodeUrl, tmdbId, season, episode); + var response = await _client.GetAsync(requestUrl); + if (!response.IsSuccessStatusCode) + { + Console.WriteLine($"{requestUrl} & {response.StatusCode}"); + return null; + } + + var content = await response.Content.ReadAsStringAsync(); + var json = JsonNode.Parse(content); + return json as JsonObject; + } + catch (Exception e) + { + Console.WriteLine($"{tmdbId} & {season} & {episode} & {e.Message}"); + return null; + } + } +} \ No newline at end of file diff --git a/src/Service/Jobs/DiskActionMonitorRegistry.cs b/src/Service/Jobs/DiskActionMonitorRegistry.cs new file mode 100644 index 0000000..3202638 --- /dev/null +++ b/src/Service/Jobs/DiskActionMonitorRegistry.cs @@ -0,0 +1,174 @@ +using Core; +using FluentScheduler; +using Interface.Jobs; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace Service.Jobs; + +public enum DiskNotifyType +{ + Action, + Sleep +} + +public class DiskActionMonitorRegistry : Registry, IDiskActionMonitorRegistry +{ + private readonly IConfiguration _configuration; + private static Dictionary _lastReadCount = new(); + private static Dictionary _lastWriteCount = new(); + private readonly ILogger _logger; + private static readonly Dictionary> LatestNotifyTimes = new(); + private static readonly Dictionary LastChangedTimes = new(); + + public DiskActionMonitorRegistry(IConfiguration configuration, ILogger logger) + { + _configuration = configuration; + _logger = logger; + Schedule(Job).ToRunEvery(5).Seconds(); + } + + public async void Job() + { + try + { + await JobExecute(); + } + catch (Exception e) + { + _logger.LogError(e, "DiskActionMonitorRegistry.Job() error"); + } + } + + private async Task JobExecute() + { + var filePath = _configuration["DiskActionMonitor:FilePath"] ?? throw new ArgumentNullException($"DiskActionMonitor:FilePath"); + var disks = _configuration + .GetSection("DiskActionMonitor:Disks") + .GetChildren() + .Select(x => x.Value); + + + foreach (var disk in disks) + { + if (string.IsNullOrEmpty(disk)) + { + continue; + } + + if (!_lastReadCount.ContainsKey(disk)) + { + _lastReadCount.Add(disk, 0); + } + + if (!_lastWriteCount.ContainsKey(disk)) + { + _lastWriteCount.Add(disk, 0); + } + + if (!LatestNotifyTimes.ContainsKey(disk)) + { + LatestNotifyTimes.Add(disk, new()); + } + + if (!LastChangedTimes.ContainsKey(disk)) + { + LastChangedTimes.Add(disk, DateTime.Now); + } + + var content = await File.ReadAllTextAsync(string.Format(filePath, disk)); + + var cols = content.Split(" ", StringSplitOptions.RemoveEmptyEntries); + + var readCount = TryGetByIndex(cols, 2); + var writeCount = TryGetByIndex(cols, 6); + + if (!int.TryParse(readCount, out var read) || !int.TryParse(writeCount, out var write)) + { + continue; // 读取失败 + } + + var readDiff = read - _lastReadCount[disk]; + var writeDiff = write - _lastWriteCount[disk]; + + _lastReadCount[disk] = read; + _lastWriteCount[disk] = write; + + if (readDiff > 0 || writeDiff > 0) + { + _logger.LogInformation($"[{disk}] ReadDiff: {readDiff}, WriteDiff: {writeDiff}"); + } + + if (readDiff > 10 || writeDiff > 10) + { + // 上一次通知的是休眠或者没有通知 发现有变换通知变化 + if (LatestNotifyTimes[disk].Any() == false + || LatestNotifyTimes[disk].Last().Item2 == DiskNotifyType.Sleep) + { + LatestNotifyTimes[disk].Add((DateTime.Now, DiskNotifyType.Action)); + + await WxNotify.SendDiskInfoAsync(@$" +## 磁盘 {disk} 刚发生读写操作 🙋 + +> 当前累计读: {GetEasyReadNumber(read)} 、新增读: {GetEasyReadNumber(readDiff)} +> 当前累计写: {GetEasyReadNumber(write)} 、新增写: {GetEasyReadNumber(writeDiff)} + +当前时间: {DateTime.Now:yyyy-M-d H:m:s} "); + } + else if (DateTime.Now - LatestNotifyTimes[disk].Last().Item1 > TimeSpan.FromHours(1)) + { + LatestNotifyTimes[disk].Add((DateTime.Now, DiskNotifyType.Action)); + + await WxNotify.SendDiskInfoAsync(@$" +## 磁盘 {disk} 连续运行超一小时 👨‍💻 + +> 当前累计读: {GetEasyReadNumber(read)} +> 当前累计写: {GetEasyReadNumber(write)} + +当前时间: {DateTime.Now:yyyy-M-d H:m:s} "); + } + + _lastReadCount[disk] = read; + _lastWriteCount[disk] = write; + LastChangedTimes[disk] = DateTime.Now; + + continue; + } + + // 没有变化 上一次是启动通知且超过10分钟,通知休眠 + if (LatestNotifyTimes[disk].Any() == false + || (LatestNotifyTimes[disk].Last().Item2 == DiskNotifyType.Action + && DateTime.Now - LastChangedTimes[disk] > TimeSpan.FromMinutes(10))) + { + LatestNotifyTimes[disk].Add((DateTime.Now, DiskNotifyType.Sleep)); + + await WxNotify.SendDiskInfoAsync(@$" +## 磁盘 {disk} 长时间无读写变化 😪 + +> 上一次读写时间:{LatestNotifyTimes[disk].Last(x => x.Item2 == DiskNotifyType.Action).Item1:yyyy-M-d H:m:s} + +> 当前累计读: {GetEasyReadNumber(read)} +> 当前累计写: {GetEasyReadNumber(write)} + +当前时间: {DateTime.Now:yyyy-M-d H:m:s} "); + } + } + } + + private string TryGetByIndex(string[] arr, int index) => index < arr.Length ? arr[index] : string.Empty; + + private string GetEasyReadNumber(int number) + { + if (number < 10000) + { + return number.ToString(); + } + + if (number < 100000000) + { + return $"{number / 10000M:0.##} 万"; + } + + return $"{number / 100000000M:0.##} 亿"; + } +} \ No newline at end of file diff --git a/src/Service/Jobs/HealthyTaskRegistry.cs b/src/Service/Jobs/HealthyTaskRegistry.cs new file mode 100644 index 0000000..af3c99c --- /dev/null +++ b/src/Service/Jobs/HealthyTaskRegistry.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using Core; +using FluentScheduler; +using Interface.Jobs; +using Microsoft.Extensions.Configuration; + +namespace Service.Jobs; + +public class HealthyTaskRegistry : Registry, IHealthyTaskRegistry +{ + private readonly IConfiguration _configuration; + + public HealthyTaskRegistry(IConfiguration configuration) + { + _configuration = configuration; + Schedule(Job).ToRunNow().AndEvery(2).Minutes(); + } + + public async void Job() + { + try + { + await JobExecute(); + } + catch (Exception e) + { + Console.WriteLine(e); + await WxNotify.SendCommonAsync($"HealthyTaskRegistry.Job() error: {e}"); + } + } + + private async Task JobExecute() + { + // 获取 配置 是个 KV 集合 + var configs = _configuration.GetSection("HealthyTasks"); + + // 遍历配置 + foreach (var item in configs.GetChildren()) + { + // 获取配置的 containerName 和 url + var containerName = item["ContainerName"]; + var url = item["Url"]; + + // 执行 + await ExecuteItem(containerName!, url!); + } + } + + private async Task ExecuteItem(string containerName, string url) + { + try + { + var client = new HttpClient(); + + // basic auth + string authInfo = Convert.ToBase64String(Encoding.ASCII.GetBytes("suncheng:SCsunch940622")); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo); + + var response = await client.GetAsync(url); + + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"StatusCode: {response.StatusCode}"); + } + + Console.WriteLine($"ContainerName: {containerName}, Url: {url}, StatusCode: {response.StatusCode}"); + } + catch (Exception e) + { + Console.WriteLine(e); + await WxNotify.SendCommonAsync($"ExecuteItem {containerName} error: {e.Message}"); + await ExecuteReboot(containerName); + } + } + + private async Task ExecuteReboot(string containerName) + { + var command = $"docker restart {containerName}"; + + var (responseCode, message) = await Command.ExecAsync(command); + + if (responseCode != HttpStatusCode.OK) + { + await WxNotify.SendCommonAsync($"ExecuteReboot {containerName} error: {responseCode} message: {message}"); + } + else + { + await WxNotify.SendCommonAsync($"ContainerName: {containerName}"); + } + } +} \ No newline at end of file diff --git a/src/Service/Jobs/LogTotalNotifyJobRegistry.cs b/src/Service/Jobs/LogTotalNotifyJobRegistry.cs new file mode 100644 index 0000000..e7101d0 --- /dev/null +++ b/src/Service/Jobs/LogTotalNotifyJobRegistry.cs @@ -0,0 +1,106 @@ +using System.Text; +using Core; +using FluentScheduler; +using Interface.Jobs; +using Microsoft.Extensions.Configuration; +using Newtonsoft.Json.Linq; + +namespace Service.Jobs; + +public class LogTotalNotifyJobRegistry : Registry, ILogTotalNotifyJobRegistry +{ + private readonly IConfiguration _configuration; + + public LogTotalNotifyJobRegistry(IConfiguration configuration) + { + _configuration = configuration; + Schedule(Job).ToRunEvery(1).Days().At(8, 30); + } + + public async void Job() + { + try + { + // await JobExecute(); + } + catch (Exception e) + { + Console.WriteLine(e); + await WxNotify.SendCommonAsync($"LogTotalNotifyJobRegistry.Job() error: {e}"); + } + } + + private async Task JobExecute() + { + var client = new HttpClient(); + + client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_configuration["Grafana:Token"]}"); + var requestBody = + """ + { + "queries": [ + { + "datasource": { + "type": "loki", + "uid": "edf5cwf6n6i2oe" + }, + "editorMode": "builder", + "expr": "sum by(container_name) (count_over_time({compose_project=~\"dockers|immich|nasrobot|elasticsearch|webui-docker\"} [1h]))", + "queryType": "range", + "refId": "A", + "datasourceId": 2, + "intervalMs": 3600000 + } + ], + "from": "1708963200000", + "to": "1709049600000" + } + """; + + requestBody = requestBody.Replace("1708963200000", DateTime.Today.AddDays(-2).ToUnixTimeMilliseconds().ToString()); + requestBody = requestBody.Replace("1709049600000", DateTime.Today.AddDays(-1).ToUnixTimeMilliseconds().ToString()); + + var content = new StringContent(requestBody, Encoding.UTF8, "application/json"); + var response = await client.PostAsync(_configuration["Grafana:LokiUrl"], content); + + var result = await response.Content.ReadAsStringAsync(); + + var jObject = JObject.Parse(result); + var frames = jObject["results"]?["A"]?["frames"]; + + if (frames == null) + { + throw new Exception("frames is null"); + } + + var msg = new StringBuilder(); + msg.AppendLine($"## {DateTime.Today.AddDays(-1):yyyy-MM-dd}日志明细如下:"); + var total = 0; + var kv = new Dictionary(); + foreach (var item in frames) + { + var name = item["schema"]?["fields"]?.LastOrDefault()?["labels"]?["container_name"]?.ToString(); + + if (string.IsNullOrEmpty(name)) + { + continue; + } + + var values = item["data"]?["values"]?.LastOrDefault()?.ToObject(); + + var value = values?.Sum() ?? 0; + total += value; + kv[name] = value; + } + + foreach (var (key, value) in kv.OrderByDescending(x => x.Value)) + { + msg.AppendLine($"**{key}**: {value}"); + } + + msg.AppendLine(""); + msg.AppendLine($"> **总计**: {total}"); + + await WxNotify.SendCommonAsync(msg.ToString()); + } +} \ No newline at end of file diff --git a/src/Service/Jobs/RSyncTaskRegistry.cs b/src/Service/Jobs/RSyncTaskRegistry.cs new file mode 100644 index 0000000..a8488c9 --- /dev/null +++ b/src/Service/Jobs/RSyncTaskRegistry.cs @@ -0,0 +1,69 @@ +using System.Diagnostics; +using System.Net.Http.Json; +using Core; +using FluentScheduler; +using Interface.Jobs; +using Microsoft.Extensions.Configuration; + +namespace Service.Jobs; + +public class RSyncTaskRegistry : Registry, IRSyncTaskRegistry +{ + private readonly IConfiguration _configuration; + + public RSyncTaskRegistry(IConfiguration configuration) + { + _configuration = configuration; + Schedule(Job).ToRunEvery(1).Days().At(10, 0); + } + + public async void Job() + { + try + { + // await JobExecute(); + } + catch (Exception e) + { + Console.WriteLine(e); + await WxNotify.SendCommonAsync($"RSyncTaskRegistry.Job() error: {e}"); + } + } + + private async Task JobExecute() + { + var config = _configuration.GetSection("SyncTask"); + + foreach (var item in config.GetSection("SyncPaths").GetChildren()) + { + var source = Path.Combine(config["SourceRoot"]!, item["Source"]!); + var isDeleteAfter = item["DeleteAfter"] == "true"; + await ExecuteItem(source, config["TargetRoot"]!, item["Target"]!, isDeleteAfter); + } + } + + private async Task ExecuteItem(string source, string remote, string destination, bool isDeleteAfter) + { + var logName = $"rclone_output_{destination.Replace("/", "_")}{DateTime.Now:yyMMddHHmm}.log"; + + var commands = new[] + { + $"rclone sync " + + $"{source} " + + $"{remote}:{destination} " + + $"--fast-list " + + $"--size-only " + + $"{(isDeleteAfter ? "--delete-after" : "--delete-excluded")} " + + $"> /wd/logs/{logName} 2>&1" + }; + + await WxNotify.SendCommonAsync($@"RSyncTaskRegistry.ExecuteItem() + +`{commands[0]}` + +> {DateTime.Now:yyyy-MM-dd HH:mm:ss} +"); + + _ = Command.ExecAsync(commands); + } +} \ No newline at end of file diff --git a/src/Service/Jobs/ShutdownRegistry.cs b/src/Service/Jobs/ShutdownRegistry.cs new file mode 100644 index 0000000..94e84f6 --- /dev/null +++ b/src/Service/Jobs/ShutdownRegistry.cs @@ -0,0 +1,61 @@ +using System.Net; +using Core; +using FluentScheduler; +using Interface.Jobs; + +namespace Service.Jobs; + +public class ShutdownRegistry : Registry, IShutdownRegistry +{ + public ShutdownRegistry() + { + Schedule(Job).ToRunEvery(1).Days().At(23, 30); + } + + public async void Job() + { + try + { + await JobExecute(); + } + catch (Exception e) + { + Console.WriteLine(e); + await WxNotify.SendCommonAsync($"ShutdownRegistry.Job() error: {e}"); + } + } + + private async Task JobExecute() + { + var command = "shutdown 9"; + + var (responseCode, msg) = await Command.ExecAsync(command); + + var wxMsg = $@" +# 定时关机指令执行 + +> 执行结果:{responseCode} +> 执行消息:{msg} + +如需取消关机请点击:[取消关机](http://suncheng.online:35642/api/JobTrigger/CancelShutdown) + +"; + + await WxNotify.SendCommonAsync(wxMsg); + + if (responseCode == HttpStatusCode.OK) + { + // 每三分钟提醒一次 + _ = Task.Delay(3 * 60 * 1000).ContinueWith(async _ => await WxNotify.SendCommonAsync(wxMsg)); + } + } + + public async Task CancelShutdown() + { + var command = "shutdown -c"; + + var (responseCode, _) = await Command.ExecAsync(command); + + await WxNotify.SendCommonAsync($"取消关机指令执行完成 {responseCode}"); + } +} \ No newline at end of file diff --git a/src/Service/Jobs/StartupRegistry.cs b/src/Service/Jobs/StartupRegistry.cs new file mode 100644 index 0000000..aabefb7 --- /dev/null +++ b/src/Service/Jobs/StartupRegistry.cs @@ -0,0 +1,46 @@ +using System.Net; +using Core; +using FluentScheduler; +using Interface.Jobs; + +namespace Service.Jobs; + +public class StartupRegistry : Registry, IStartupRegistry +{ + public StartupRegistry() + { + Schedule(Job).ToRunNow(); + } + + public async void Job() + { + try + { + // await JobExecute(); + } + catch (Exception e) + { + Console.WriteLine(e); + await WxNotify.SendCommonAsync($"StartupRegistry.Job() error: {e}"); + } + } + + private async Task JobExecute() + { + var commands = new[] + { + "chmod 777 /var/run/docker.sock", + }; + + var (responseCode, _) = await Command.ExecAsync(commands); + + if (responseCode != HttpStatusCode.OK) + { + await WxNotify.SendCommonAsync($"StartupRegistry.Job() error: {responseCode}"); + } + else + { + await WxNotify.SendCommonAsync("StartupRegistry.Job() success"); + } + } +} \ No newline at end of file diff --git a/src/Service/Service.csproj b/src/Service/Service.csproj new file mode 100644 index 0000000..721a80e --- /dev/null +++ b/src/Service/Service.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/src/WebApi/Controllers/BaseController.cs b/src/WebApi/Controllers/BaseController.cs new file mode 100644 index 0000000..1bb4777 --- /dev/null +++ b/src/WebApi/Controllers/BaseController.cs @@ -0,0 +1,9 @@ +using Microsoft.AspNetCore.Mvc; + +namespace WebApi.Controllers; + +[ApiController] +[Route("/api/[controller]/[action]")] +public class BaseController : ControllerBase +{ +} \ No newline at end of file diff --git a/src/WebApi/Controllers/JobTriggerController.cs b/src/WebApi/Controllers/JobTriggerController.cs new file mode 100644 index 0000000..010f50e --- /dev/null +++ b/src/WebApi/Controllers/JobTriggerController.cs @@ -0,0 +1,101 @@ +using Interface.Jobs; +using Microsoft.AspNetCore.Mvc; + +namespace WebApi.Controllers; + +public class JobTriggerController : BaseController +{ + private readonly ILogTotalNotifyJobRegistry _logTotalNotifyJobRegistry; + private readonly IDiskActionMonitorRegistry _diskActionMonitorRegistry; + private readonly IHealthyTaskRegistry _healthyTaskRegistry; + private readonly IRSyncTaskRegistry _rSyncTaskRegistry; + private readonly IStartupRegistry _startupRegistry; + private readonly IShutdownRegistry _shutdownRegistry; + private readonly IChineseNfoRegistry _chineseNfoRegistry; + + /// + /// ctor + /// + public JobTriggerController( + ILogTotalNotifyJobRegistry logTotalNotifyJobRegistry, + IDiskActionMonitorRegistry diskActionMonitorRegistry, + IHealthyTaskRegistry healthyTaskRegistry, + IRSyncTaskRegistry rSyncTaskRegistry, + IStartupRegistry startupRegistry, + IShutdownRegistry shutdownRegistry, + IChineseNfoRegistry chineseNfoRegistry) + { + _logTotalNotifyJobRegistry = logTotalNotifyJobRegistry; + _diskActionMonitorRegistry = diskActionMonitorRegistry; + _healthyTaskRegistry = healthyTaskRegistry; + _rSyncTaskRegistry = rSyncTaskRegistry; + _startupRegistry = startupRegistry; + _shutdownRegistry = shutdownRegistry; + _chineseNfoRegistry = chineseNfoRegistry; + } + + [HttpGet] + public string LogTotalNotify() + { + _logTotalNotifyJobRegistry.Job(); + + return "OK"; + } + + [HttpGet] + public string DiskActionMonitor() + { + _diskActionMonitorRegistry.Job(); + + return "OK"; + } + + [HttpGet] + public string HealthyTask() + { + _healthyTaskRegistry.Job(); + + return "OK"; + } + + + [HttpGet] + public string RSyncTask() + { + _rSyncTaskRegistry.Job(); + + return "OK"; + } + + [HttpGet] + public string Startup() + { + _startupRegistry.Job(); + + return "OK"; + } + + [HttpGet] + public string Shutdown() + { + _shutdownRegistry.Job(); + + return "OK"; + } + + [HttpGet] + public string CancelShutdown() + { + _shutdownRegistry.CancelShutdown(); + + return "OK"; + } + + [HttpGet] + public string ConvertChineseNfo(bool ignoreLocked = false, bool ignoreCompleted = false) + { + _chineseNfoRegistry.Job(ignoreLocked, ignoreCompleted); + + return "OK"; + } +} \ No newline at end of file diff --git a/src/WebApi/Controllers/NotifyController.cs b/src/WebApi/Controllers/NotifyController.cs new file mode 100644 index 0000000..06afe69 --- /dev/null +++ b/src/WebApi/Controllers/NotifyController.cs @@ -0,0 +1,319 @@ +using Core; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace WebApi.Controllers; + +public class NotifyController : BaseController +{ + public NotifyController() + { + } + + [HttpPost] + public async Task Radarr() + { + var body = Request.Body; + + using var reader = new StreamReader(body); + var text = await reader.ReadToEndAsync(); + + Console.WriteLine(text); + + /* + { + "movie": { + "id": 1, + "title": "Test Title", + "year": 1970, + "releaseDate": "1970-01-01", + "folderPath": "C:\\testpath", + "tmdbId": 0, + "tags": [ + "test-tag" + ] + }, + "remoteMovie": { + "tmdbId": 1234, + "imdbId": "5678", + "title": "Test title", + "year": 1970 + }, + "release": { + "quality": "Test Quality", + "qualityVersion": 1, + "releaseGroup": "Test Group", + "releaseTitle": "Test Title", + "indexer": "Test Indexer", + "size": 9999999, + "customFormatScore": 0 + }, + "eventType": "Test", + "instanceName": "Radarr", + "applicationUrl": "" +} + */ + + var jsonObj = JsonConvert.DeserializeObject(text); + + var notify = @$"# Radarr通知: +> 时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} + +电影: {jsonObj!["movie"]!["title"]}({jsonObj["movie"]!["releaseDate"]}) +标签: {string.Join(",", jsonObj["movie"]!["tags"]?.ToObject() ?? Array.Empty())} +事件: {jsonObj["eventType"]} +"; + + var file = jsonObj["release"] ?? jsonObj["movieFile"]; + + if (file != null) + { + var size = file["size"]?.ToObject() ?? 0M; + + var gb = (size / 1024M / 1024M / 1024M).ToString("0.##"); + + notify += @$" +索引器: {file["indexer"]} +发布组: {file["releaseGroup"]}({file["quality"]}) +发布标题: {file["releaseTitle"] ?? file["relativePath"]} +占用空间: {gb}GB "; + } + + await WxNotify.SendCommonAsync(notify); + + return "OK"; + } + + + [HttpPost] + public async Task Sonarr() + { + var body = Request.Body; + + using var reader = new StreamReader(body); + var text = await reader.ReadToEndAsync(); + + Console.WriteLine(text); + + /* +{ + "series": { + "id": 86, + "title": "Demon Slayer: Kimetsu no Yaiba", + "titleSlug": "demon-slayer-kimetsu-no-yaiba", + "path": "/data/anime/Demon Slayer - Kimetsu no Yaiba", + "tvdbId": 348545, + "tvMazeId": 41469, + "tmdbId": 85937, + "imdbId": "tt9335498", + "type": "anime", + "year": 2019, + "genres": [ + "Action", + "Adventure", + "Animation", + "Anime", + "Drama", + "Fantasy", + "Thriller" + ], + "images": [ + { + "coverType": "banner", + "url": "/MediaCover/86/banner.jpg?lastWrite=638509998968281535", + "remoteUrl": "https://artworks.thetvdb.com/banners/graphical/5ccd960cc3aa0.jpg" + }, + { + "coverType": "poster", + "url": "/MediaCover/86/poster.jpg?lastWrite=638509998969561521", + "remoteUrl": "https://artworks.thetvdb.com/banners/v4/series/348545/posters/60908d475f49a.jpg" + }, + { + "coverType": "fanart", + "url": "/MediaCover/86/fanart.jpg?lastWrite=638509998971801497", + "remoteUrl": "https://artworks.thetvdb.com/banners/fanart/original/5c93cbb2b60b6.jpg" + }, + { + "coverType": "clearlogo", + "url": "/MediaCover/86/clearlogo.png?lastWrite=638509998972921485", + "remoteUrl": "https://artworks.thetvdb.com/banners/v4/series/348545/clearlogo/611c7fa8222d6.png" + } + ], + "tags": [ + "anime" + ] + }, + "episodes": [ + { + "id": 2716, + "episodeNumber": 2, + "seasonNumber": 5, + "title": "Water Hashira Giyu Tomioka's Pain", + "overview": "Kagaya's Kasugai Crow suddenly appears in front of Tamayo and invites her to the Demon Slayer headquarters — even though she is a demon. Meanwhile, Tanjiro, who is recovering at the Butterfly Mansion, receives a letter from Kagaya...", + "airDate": "2024-05-19", + "airDateUtc": "2024-05-19T14:15:00Z", + "seriesId": 86, + "tvdbId": 10445764 + } + ], + "release": { + "quality": "WEBDL-1080p", + "qualityVersion": 1, + "releaseGroup": "ToonsHub", + "releaseTitle": "[ToonsHub] Demon Slayer Kimetsu no Yaiba S05E02 1080p CR WEB-DL AAC2.0 x264 (Multi-Subs)", + "indexer": "Knaben ", + "size": 1395864320, + "customFormatScore": 0, + "customFormats": [] + }, + "downloadClient": "aria2", + "downloadClientType": "Aria2", + "downloadId": "915718C3A8A5B15BD3C32A2B05885953D96AFADD", + "customFormatInfo": { + "customFormats": [], + "customFormatScore": 0 + }, + "eventType": "Grab", + "instanceName": "Sonarr", + "applicationUrl": "" +} + + +-------------------------- + +{ + "series": { + "id": 86, + "title": "Demon Slayer: Kimetsu no Yaiba", + "titleSlug": "demon-slayer-kimetsu-no-yaiba", + "path": "/data/anime/Demon Slayer - Kimetsu no Yaiba", + "tvdbId": 348545, + "tvMazeId": 41469, + "tmdbId": 85937, + "imdbId": "tt9335498", + "type": "anime", + "year": 2019, + "genres": [ + "Action", + "Adventure", + "Animation", + "Anime", + "Drama", + "Fantasy", + "Thriller" + ], + "images": [ + { + "coverType": "banner", + "url": "/MediaCover/86/banner.jpg?lastWrite=638509998968281535", + "remoteUrl": "https://artworks.thetvdb.com/banners/graphical/5ccd960cc3aa0.jpg" + }, + { + "coverType": "poster", + "url": "/MediaCover/86/poster.jpg?lastWrite=638509998969561521", + "remoteUrl": "https://artworks.thetvdb.com/banners/v4/series/348545/posters/60908d475f49a.jpg" + }, + { + "coverType": "fanart", + "url": "/MediaCover/86/fanart.jpg?lastWrite=638509998971801497", + "remoteUrl": "https://artworks.thetvdb.com/banners/fanart/original/5c93cbb2b60b6.jpg" + }, + { + "coverType": "clearlogo", + "url": "/MediaCover/86/clearlogo.png?lastWrite=638509998972921485", + "remoteUrl": "https://artworks.thetvdb.com/banners/v4/series/348545/clearlogo/611c7fa8222d6.png" + } + ], + "tags": [ + "anime" + ] + }, + "episodes": [ + { + "id": 2716, + "episodeNumber": 2, + "seasonNumber": 5, + "title": "Water Hashira Giyu Tomioka's Pain", + "overview": "Kagaya's Kasugai Crow suddenly appears in front of Tamayo and invites her to the Demon Slayer headquarters — even though she is a demon. Meanwhile, Tanjiro, who is recovering at the Butterfly Mansion, receives a letter from Kagaya...", + "airDate": "2024-05-19", + "airDateUtc": "2024-05-19T14:15:00Z", + "seriesId": 86, + "tvdbId": 10445764 + } + ], + "downloadInfo": { + "quality": "WEBDL-1080p", + "qualityVersion": 1, + "title": "Demon.Slayer.Kimetsu.no.Yaiba.S57E02.Water.Hashira.Giyu.Tomiokas.Pain.1080p.CR.WEB-DL.JPN.AAC2.0.H.264.MSubs-ToonsHub.mkv", + "size": 1446462408 + }, + "downloadClient": "aria2", + "downloadClientType": "Aria2", + "downloadId": "915718C3A8A5B15BD3C32A2B05885953D96AFADD", + "downloadStatus": "Warning", + "downloadStatusMessages": [ + { + "title": "One or more episodes expected in this release were not imported or missing from the release", + "messages": [] + }, + { + "title": "Demon.Slayer.Kimetsu.no.Yaiba.S57E02.Water.Hashira.Giyu.Tomiokas.Pain.1080p.CR.WEB-DL.JPN.AAC2.0.H.264.MSubs-ToonsHub.mkv", + "messages": [ + "Invalid season or episode" + ] + } + ], + "customFormatInfo": { + "customFormats": [], + "customFormatScore": 0 + }, + "release": { + "releaseTitle": "[ToonsHub] Demon Slayer Kimetsu no Yaiba S05E02 1080p CR WEB-DL AAC2.0 x264 (Multi-Subs)", + "indexer": "Knaben ", + "size": 1395864320 + }, + "eventType": "ManualInteractionRequired", + "instanceName": "Sonarr", + "applicationUrl": "" +} + */ + + var jsonObj = JsonConvert.DeserializeObject(text); + + var notify = @$"# Sonarr通知: + > 时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} + + 剧集: {jsonObj!["series"]!["title"]} + 标签: {string.Join(",", jsonObj["series"]!["tags"]?.ToObject() ?? Array.Empty())} + 事件: {jsonObj["eventType"]} + "; + + var episodes = jsonObj["episodes"]; + + if (episodes != null) + { + foreach (var item in episodes) + { + notify += @$" +集数: 第{item["seasonNumber"]}季-第{item["episodeNumber"]}集 "; + } + } + + if (jsonObj["release"] != null) + { + var gb = (jsonObj["release"]!.ToObject() / 1024M / 1024M / 1024M).ToString("0.##"); + notify += @$" +索引器: {jsonObj["release"]!["indexer"]} +发布组: {jsonObj["release"]!["releaseGroup"]}({jsonObj["release"]!["quality"] ?? jsonObj["downloadInfo"]!["quality"]}) +发布标题: {jsonObj["release"]!["releaseTitle"]} +占用空间: {gb}GB +"; + } + + + await WxNotify.SendCommonAsync(notify); + + return "OK"; + } +} \ No newline at end of file diff --git a/src/WebApi/Controllers/XiaoController.cs b/src/WebApi/Controllers/XiaoController.cs new file mode 100644 index 0000000..cd89497 --- /dev/null +++ b/src/WebApi/Controllers/XiaoController.cs @@ -0,0 +1,34 @@ +using Core; +using Microsoft.AspNetCore.Mvc; + +namespace WebApi.Controllers; + +public class XiaoController : BaseController +{ + private readonly ILogger _logger; + + public XiaoController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public async Task GotoHomeGame() + { + await WxNotify.SendCommonAsync("接收到启动游戏机指令"); + + var commands = new[] + { + "grub-reboot 2", + "reboot" + }; + + _ = Task.Run(async () => + { + await Task.Delay(3000); + _ = await Command.ExecAsync(commands); + }); + + return "OK"; + } +} \ No newline at end of file diff --git a/src/WebApi/Program.cs b/src/WebApi/Program.cs new file mode 100644 index 0000000..a844823 --- /dev/null +++ b/src/WebApi/Program.cs @@ -0,0 +1,51 @@ +using System.Reflection; +using FluentScheduler; +using Interface.Jobs; +using Service.Jobs; + +var builder = WebApplication.CreateBuilder(args); + +var interfaces = Assembly.Load("Interface"); +var services = Assembly.Load("Service"); + +foreach (var type in interfaces.GetTypes().Where(x => x.Namespace?.StartsWith("Interface") == true)) +{ + var serviceType = services.GetTypes().FirstOrDefault(x => type.IsAssignableFrom(x)); + if (serviceType != null) + { + builder.Services.AddSingleton(type, serviceType); + } +} + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddHttpContextAccessor(); + +var app = builder.Build(); + +app.UseSwagger(); +app.UseSwaggerUI(); +app.MapControllers(); + +#if !DEBUG +var logTotalNotifyJobRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((LogTotalNotifyJobRegistry)logTotalNotifyJobRegistry); +var diskActionMonitorRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((DiskActionMonitorRegistry)diskActionMonitorRegistry); +var syncTaskRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((RSyncTaskRegistry)syncTaskRegistry); +var healthyTaskRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((HealthyTaskRegistry)healthyTaskRegistry); +var rsyncTaskRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((RSyncTaskRegistry)rsyncTaskRegistry); +var startupRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((StartupRegistry)startupRegistry); +var shutdownRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((ShutdownRegistry)shutdownRegistry); +var chineseNfoRegistry = app.Services.GetRequiredService(); +JobManager.Initialize((ChineseNfoRegistry)chineseNfoRegistry); +#endif + +app.Run(); \ No newline at end of file diff --git a/src/WebApi/Properties/launchSettings.json b/src/WebApi/Properties/launchSettings.json new file mode 100644 index 0000000..a56a3a4 --- /dev/null +++ b/src/WebApi/Properties/launchSettings.json @@ -0,0 +1,15 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://0.0.0.0:5236", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/WebApi/WebApi.csproj b/src/WebApi/WebApi.csproj new file mode 100644 index 0000000..0c366c9 --- /dev/null +++ b/src/WebApi/WebApi.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + true + Linux + + + + + + + + + + + + diff --git a/src/WebApi/appsettings.Development.json b/src/WebApi/appsettings.Development.json new file mode 100644 index 0000000..e0e9ff5 --- /dev/null +++ b/src/WebApi/appsettings.Development.json @@ -0,0 +1,36 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Grafana": { + "Token": "glsa_qNYNV1vbjTXVQKIFxM43nIRGlnNE1x0x_c59dd21d", + "LokiUrl": "http://suncheng.online:3000/api/ds/query?ds_type=loki" + }, + "DiskActionMonitor": { + "FilePath": "D:\\OneDrive\\Desktop\\SC\\NasRobot\\src\\WebApi\\mocks\\disk_{0}\\stat.txt", + "Disks": [ + "sdb", + "sdc1" + ] + }, + "SyncTask": { + "SourceRoot": "", + "TargetRoot": "", + "SyncPaths": [ + { + "Source": "", + "Target": "" + } + ] + }, + "HealthyTasks": [ + + ], + "ChineseNfo": { + "TvFolder": "D:\\codes\\others\\ConvertChineseNfo", + "HttpProxy": "http://suncheng.online:47890" + } +} diff --git a/src/WebApi/appsettings.json b/src/WebApi/appsettings.json new file mode 100644 index 0000000..ce9abfb --- /dev/null +++ b/src/WebApi/appsettings.json @@ -0,0 +1,65 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Grafana": { + "Token": "glsa_qNYNV1vbjTXVQKIFxM43nIRGlnNE1x0x_c59dd21d", + "LokiUrl": "http://192.168.31.14:3000/api/ds/query?ds_type=loki" + }, + "DiskActionMonitor": { + "FilePath": "/sys/block/{0}/stat", + "Disks": [ + "sda", + "sdc" + ] + }, + "SyncTask": { + "SourceRoot": "/wd", + "TargetRoot": "aliyun", + "SyncPaths": [ + { + "Source": "apps", + "Target": "/homenas/apps" + }, + { + "Source": "volb/media/others", + "Target": "/homenas/jav", + "DeleteAfter": "true" + }, + { + "Source": "vola/media/other", + "Target": "/homenas/other" + }, + { + "Source": "volb/media/tv", + "Target": "/homenas/tv" + }, + { + "Source": "vola/media/anime", + "Target": "/homenas/anime" + }, + { + "Source": "vola/media/movies", + "Target": "/homenas/movie" + } + ] + }, + "HealthyTasks": [ + { + "ContainerName": "netdata_proxy", + "Url": "http://192.168.31.14:19999" + }, + { + "ContainerName": "nas_robot_proxy", + "Url": "http://192.168.31.14:35642/swagger/index.html" + } + ], + "ChineseNfo": { + "TvFolder": "/data/tv", + "HttpProxy": "http://192.168.31.14:47890" + } +} diff --git a/src/WebApi/mocks/disk_sdb/stat.txt b/src/WebApi/mocks/disk_sdb/stat.txt new file mode 100644 index 0000000..f27a512 --- /dev/null +++ b/src/WebApi/mocks/disk_sdb/stat.txt @@ -0,0 +1 @@ +219020 20383 38271508 2978589 12631 1972 20214944 78461 0 2973824 3057050 0 0 0 0 0 0 \ No newline at end of file diff --git a/src/WebApi/mocks/disk_sdc1/stat.txt b/src/WebApi/mocks/disk_sdc1/stat.txt new file mode 100644 index 0000000..f27a512 --- /dev/null +++ b/src/WebApi/mocks/disk_sdc1/stat.txt @@ -0,0 +1 @@ +219020 20383 38271508 2978589 12631 1972 20214944 78461 0 2973824 3057050 0 0 0 0 0 0 \ No newline at end of file