Compare commits
14
Commits
a264162aa9
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a23d67b72
|
||
|
|
387f9d6b8c
|
||
|
|
6467c79eac
|
||
|
|
41ef3db9e5
|
||
|
|
c30ee50898
|
||
|
|
540d990aeb
|
||
|
|
aa7f37500f
|
||
|
|
67509e9062
|
||
|
|
90b8f3f08a
|
||
|
|
4a8244466e
|
||
|
|
cc37d6bcb0
|
||
|
|
ff903413eb
|
||
|
|
29f4991235
|
||
|
|
6c82cc2225
|
No files matched your search
@@ -1,43 +0,0 @@
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
env:
|
||||
GIT__TOKEN: ${{ secrets.TOKEN }}
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: linux
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/cache/restore@v4
|
||||
with:
|
||||
key: gradle
|
||||
path: |
|
||||
~/.gradle/caches/
|
||||
~/.gradle/wrapper/
|
||||
~/.konan/
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '24'
|
||||
distribution: 'temurin'
|
||||
|
||||
- run: |
|
||||
./gradlew assemble
|
||||
mv ./build/bin/linuxX64/releaseExecutable/ddns.kexe ./ddns
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ddns
|
||||
path: ./ddns
|
||||
|
||||
- uses: actions/cache/save@v4
|
||||
with:
|
||||
key: gradle
|
||||
path: |
|
||||
~/.gradle/caches/
|
||||
~/.gradle/wrapper/
|
||||
~/.konan/
|
||||
+2
-10
@@ -1,10 +1,2 @@
|
||||
# IDE
|
||||
/.idea/
|
||||
|
||||
# Gradle
|
||||
/.gradle/
|
||||
/gradle.properties
|
||||
|
||||
# Kotlin
|
||||
/.kotlin/
|
||||
/build/
|
||||
# Rust
|
||||
/target/
|
||||
Generated
+1820
File diff suppressed because it is too large.
Load diff
+11
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "ddns"
|
||||
version = "1.0.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
reqwest = { version = "0.13.5", features = ["json"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
toml = "1.2.2"
|
||||
@@ -1,35 +0,0 @@
|
||||
group = "com.infendro"
|
||||
version = "1.0.0"
|
||||
|
||||
repositories {
|
||||
maven("https://git.infendro.com/api/packages/Infendro/maven")
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.multiplatform)
|
||||
alias(libs.plugins.serialization)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
linuxX64 {
|
||||
binaries.executable {
|
||||
entryPoint = "com.infendro.ddns.main"
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
commonMain.dependencies {
|
||||
implementation(libs.io)
|
||||
implementation(libs.serialization.json)
|
||||
implementation(libs.coroutines)
|
||||
implementation(libs.cli)
|
||||
implementation(libs.ktor.client)
|
||||
implementation(libs.ktor.client.contentNegotiation)
|
||||
implementation(libs.ktor.client.serialization.json)
|
||||
}
|
||||
nativeMain.dependencies {
|
||||
implementation(libs.ktor.client.curl)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
[versions]
|
||||
kotlin = "2.1.21"
|
||||
io = "0.7.0"
|
||||
coroutines = "1.10.2"
|
||||
serialization = "1.8.1"
|
||||
cli = "1.2.2"
|
||||
ktor = "3.1.2"
|
||||
|
||||
[plugins]
|
||||
multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
|
||||
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
|
||||
[libraries]
|
||||
io = { module = "org.jetbrains.kotlinx:kotlinx-io-core", version.ref = "io" }
|
||||
coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
|
||||
serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
|
||||
|
||||
cli = { module = "com.infendro:cli", version.ref = "cli" }
|
||||
|
||||
ktor-client = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
|
||||
ktor-client-curl = { module = "io.ktor:ktor-client-curl", version.ref = "ktor" }
|
||||
ktor-client-contentNegotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
|
||||
ktor-client-serialization-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
|
||||
Vendored
BIN
Binary file not shown.
-6
@@ -1,6 +0,0 @@
|
||||
#Tue Jun 03 12:27:11 CEST 2025
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -1,234 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# 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
|
||||
#
|
||||
# https://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.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
-89
@@ -1,89 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1 +0,0 @@
|
||||
rootProject.name = "ddns"
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::error::Error;
|
||||
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{config::AuthConfig, model::dns_record::DnsRecord};
|
||||
|
||||
const API: &str = "https://api.porkbun.com/api/json/v3";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DnsClient {
|
||||
auth_config: AuthConfig,
|
||||
client: Client,
|
||||
}
|
||||
|
||||
impl DnsClient {
|
||||
pub fn new(auth_config: AuthConfig, client: Client) -> Self {
|
||||
Self { auth_config, client }
|
||||
}
|
||||
|
||||
pub async fn get_records(&self, domain: &str) -> Result<Vec<DnsRecord>, Box<dyn Error>> {
|
||||
let body = GetRecordsRequest {
|
||||
apikey: self.auth_config.key.clone(),
|
||||
secretapikey: self.auth_config.secret_key.clone(),
|
||||
};
|
||||
let response = self.client.post(format!("{API}/dns/retrieve/{domain}"))
|
||||
.json(&body)
|
||||
.send().await?
|
||||
.error_for_status()?;
|
||||
let response_body = response.json::<GetRecordsResponse>().await?;
|
||||
let records = response_body.records.iter()
|
||||
.map(|it| {
|
||||
let subdomain = it.name
|
||||
.strip_suffix(domain).unwrap()
|
||||
.strip_suffix(".").unwrap_or("");
|
||||
|
||||
DnsRecord::new(
|
||||
it.id.clone(),
|
||||
it.type_.clone(),
|
||||
domain.to_string(),
|
||||
subdomain.to_string(),
|
||||
it.content.clone(),
|
||||
it.ttl.parse().unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
pub async fn update_record(&self, record: &DnsRecord, value: &str) -> Result<(), Box<dyn Error>> {
|
||||
let body = UpdateRecordRequest {
|
||||
apikey: self.auth_config.key.clone(),
|
||||
secretapikey: self.auth_config.secret_key.clone(),
|
||||
type_: record.type_.clone(),
|
||||
name: record.subdomain.clone(),
|
||||
content: value.to_string(),
|
||||
ttl: record.ttl,
|
||||
};
|
||||
self.client.post(format!("{API}/dns/edit/{domain}/{id}", domain = record.domain, id = record.id))
|
||||
.json(&body)
|
||||
.send().await?
|
||||
.error_for_status()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct GetRecordsRequest {
|
||||
pub apikey: String,
|
||||
pub secretapikey: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GetRecordsResponse {
|
||||
pub records: Vec<GetRecordsResponseRecord>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GetRecordsResponseRecord {
|
||||
pub id: String,
|
||||
#[serde(rename = "type")]
|
||||
pub type_: String,
|
||||
pub name: String,
|
||||
pub content: String,
|
||||
pub ttl: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct UpdateRecordRequest {
|
||||
pub apikey: String,
|
||||
pub secretapikey: String,
|
||||
#[serde(rename = "type")]
|
||||
pub type_: String,
|
||||
pub name: String,
|
||||
pub content: String,
|
||||
pub ttl: i32,
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use std::error::Error;
|
||||
|
||||
use reqwest::Client;
|
||||
|
||||
use crate::model::ip_address::IpAddress;
|
||||
|
||||
const API4: &str = "https://api4.ipify.org";
|
||||
const API6: &str = "https://api6.ipify.org";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct IpClient {
|
||||
client: Client,
|
||||
}
|
||||
|
||||
impl IpClient {
|
||||
pub fn new(client: Client) -> Self {
|
||||
Self { client: client.clone() }
|
||||
}
|
||||
|
||||
pub async fn get_ip(&self) -> Result<IpAddress, Box<dyn Error>> {
|
||||
let ipv4 = self.get_ipv4().await?;
|
||||
let ipv6 = self.get_ipv6().await?;
|
||||
let ip = IpAddress::new(ipv4, ipv6);
|
||||
Ok(ip)
|
||||
}
|
||||
|
||||
async fn get_ipv4(&self) -> Result<Option<String>, Box<dyn Error>> {
|
||||
let response = self.client.get(API4)
|
||||
.send().await;
|
||||
let response = match response {
|
||||
Ok(x) => x,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
let ipv4 = response.text().await?;
|
||||
Ok(Some(ipv4))
|
||||
}
|
||||
|
||||
async fn get_ipv6(&self) -> Result<Option<String>, Box<dyn Error>> {
|
||||
let response = self.client.get(API6)
|
||||
.send().await;
|
||||
let response = match response {
|
||||
Ok(x) => x,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
let ipv6 = response.text().await?;
|
||||
Ok(Some(ipv6))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod dns_client;
|
||||
pub mod ip_client;
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.infendro.ddns
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
|
||||
object Http {
|
||||
val client = HttpClient {
|
||||
install(ContentNegotiation) {
|
||||
json()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package com.infendro.ddns
|
||||
|
||||
import com.infendro.cli.argument.string
|
||||
import com.infendro.cli.argument.stringOrElse
|
||||
import com.infendro.cli.argument.strings
|
||||
import com.infendro.cli.cli
|
||||
import com.infendro.ddns.Argument.CONFIG
|
||||
import com.infendro.ddns.Argument.DOMAIN
|
||||
import com.infendro.ddns.Argument.IP_SERVICE
|
||||
import com.infendro.ddns.Argument.KEY
|
||||
import com.infendro.ddns.Argument.SECRET_KEY
|
||||
import com.infendro.ddns.Argument.SUBDOMAIN
|
||||
import com.infendro.ddns.argument.ipService
|
||||
import com.infendro.ddns.config.Config
|
||||
import com.infendro.ddns.dns.DnsService
|
||||
import com.infendro.ddns.dns.DnsServices.PORKBUN
|
||||
import com.infendro.ddns.dns.model.DnsRecord
|
||||
import com.infendro.ddns.dns.porkbun.Porkbun
|
||||
import com.infendro.ddns.ip.IpService
|
||||
|
||||
private object Argument {
|
||||
val CONFIG = stringOrElse("config", "/etc/ddns.conf")
|
||||
|
||||
val DOMAIN = string("domain")
|
||||
val SUBDOMAIN = strings("subdomain", min = 1)
|
||||
val IP_SERVICE = ipService("ip-service")
|
||||
|
||||
// Porkbun
|
||||
val KEY = string("key")
|
||||
val SECRET_KEY = string("secret-key")
|
||||
}
|
||||
|
||||
fun main(
|
||||
args: Array<String>,
|
||||
) {
|
||||
cli {
|
||||
arguments(CONFIG)
|
||||
|
||||
execute {
|
||||
val config by CONFIG
|
||||
|
||||
Config.get(config)
|
||||
.run {
|
||||
val domain by DOMAIN
|
||||
val subdomains by SUBDOMAIN
|
||||
val ipService by IP_SERVICE
|
||||
|
||||
val dnsService = when (name) {
|
||||
PORKBUN -> {
|
||||
val key by KEY
|
||||
val secretkey by SECRET_KEY
|
||||
|
||||
Porkbun(key, secretkey)
|
||||
}
|
||||
|
||||
else -> throw Exception()
|
||||
}
|
||||
|
||||
dnsService.update(ipService, domain, subdomains)
|
||||
}
|
||||
}
|
||||
|
||||
command(PORKBUN) {
|
||||
arguments(
|
||||
DOMAIN,
|
||||
SUBDOMAIN,
|
||||
IP_SERVICE,
|
||||
KEY,
|
||||
SECRET_KEY,
|
||||
)
|
||||
|
||||
execute {
|
||||
val domain by DOMAIN
|
||||
val subdomains by SUBDOMAIN
|
||||
val ipService by IP_SERVICE
|
||||
|
||||
val key by KEY
|
||||
val secretkey by SECRET_KEY
|
||||
val dnsService = Porkbun(key, secretkey)
|
||||
|
||||
dnsService.update(ipService, domain, subdomains)
|
||||
}
|
||||
}
|
||||
}.run(args)
|
||||
}
|
||||
|
||||
fun Config.run(
|
||||
block: Config.Service.() -> Unit,
|
||||
) {
|
||||
for (service in services) {
|
||||
service.block()
|
||||
}
|
||||
}
|
||||
|
||||
fun DnsService.update(
|
||||
ipService: IpService,
|
||||
domain: String,
|
||||
subdomains: List<String>,
|
||||
) {
|
||||
val (ipv4, ipv6) = ipService.ip
|
||||
|
||||
val records = getRecords(domain, subdomains)
|
||||
val aRecords = records
|
||||
.filter { it.type == DnsRecord.Type.A }
|
||||
val aaaaRecords = records
|
||||
.filter { it.type == DnsRecord.Type.AAAA }
|
||||
|
||||
updateRecords(aRecords, ipv4)
|
||||
updateRecords(aaaaRecords, ipv6)
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.infendro.ddns.argument
|
||||
|
||||
import com.infendro.cli.Command
|
||||
import com.infendro.cli.argument.Argument
|
||||
import com.infendro.cli.argument.Parser
|
||||
import com.infendro.ddns.ip.IpService
|
||||
import com.infendro.ddns.ip.IpServices
|
||||
|
||||
object IpServiceParser : Parser<IpService> {
|
||||
override fun parse(
|
||||
text: String?,
|
||||
): IpService {
|
||||
return IpServices.get(text!!)
|
||||
}
|
||||
}
|
||||
|
||||
class IpServiceOrDefaultArgument(
|
||||
override val name: String,
|
||||
) : Argument.SingleOrElse<IpService>() {
|
||||
override val other: IpService
|
||||
get() = IpServices.DEFAULT
|
||||
|
||||
override val parser: Parser<IpService>
|
||||
get() = IpServiceParser
|
||||
}
|
||||
|
||||
fun ipService(
|
||||
name: String,
|
||||
) = IpServiceOrDefaultArgument(name)
|
||||
|
||||
fun Command.Builder.ipService(
|
||||
name: String,
|
||||
) = IpServiceOrDefaultArgument(name)
|
||||
.also { argument(it) }
|
||||
@@ -1,128 +0,0 @@
|
||||
package com.infendro.ddns.config
|
||||
|
||||
import com.infendro.cli.argument.Argument.*
|
||||
import com.infendro.ddns.config.Regex.ARGUMENT
|
||||
import com.infendro.ddns.config.Regex.EMPTY_LINES
|
||||
import kotlin.reflect.KProperty
|
||||
import kotlinx.io.buffered
|
||||
import kotlinx.io.files.Path
|
||||
import kotlinx.io.files.SystemFileSystem
|
||||
import kotlinx.io.readString
|
||||
|
||||
class Config(
|
||||
val services: List<Service>,
|
||||
) {
|
||||
class Service(
|
||||
val name: String,
|
||||
val arguments: List<Argument>,
|
||||
) {
|
||||
class Argument(
|
||||
val name: String,
|
||||
val value: String,
|
||||
)
|
||||
|
||||
operator fun <T> Single<T>.getValue(
|
||||
thisRef: Any?,
|
||||
property: KProperty<*>,
|
||||
): T {
|
||||
return parser.parse(
|
||||
arguments
|
||||
.find { it.name == name }!!
|
||||
.value
|
||||
)
|
||||
}
|
||||
|
||||
operator fun <T> SingleOrElse<T>.getValue(
|
||||
thisRef: Any?,
|
||||
property: KProperty<*>,
|
||||
): T {
|
||||
return arguments
|
||||
.find { it.name == name }
|
||||
?.let { parser.parse(it.value) }
|
||||
?: other
|
||||
}
|
||||
|
||||
operator fun <T> SingleOrNull<T>.getValue(
|
||||
thisRef: Any?,
|
||||
property: KProperty<*>,
|
||||
): T? {
|
||||
return arguments
|
||||
.find { it.name == name }
|
||||
?.let { parser.parse(it.value) }
|
||||
}
|
||||
|
||||
operator fun <T> Multiple<T>.getValue(
|
||||
thisRef: Any?,
|
||||
property: KProperty<*>,
|
||||
): List<T> {
|
||||
return arguments
|
||||
.filter { it.name == name }
|
||||
.map { parser.parse(it.value) }
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun get(
|
||||
path: String,
|
||||
): Config {
|
||||
val path = Path(path)
|
||||
val source = SystemFileSystem.source(path).buffered()
|
||||
val text = source
|
||||
.readString()
|
||||
.process()
|
||||
|
||||
return parse(text)
|
||||
}
|
||||
|
||||
private fun String.process(): String {
|
||||
val builder = StringBuilder()
|
||||
for (line in lines()) {
|
||||
val comment = line.indexOf("""//""")
|
||||
if (comment != -1) {
|
||||
builder.appendLine(
|
||||
line
|
||||
.slice(0..<comment)
|
||||
.trim()
|
||||
)
|
||||
} else {
|
||||
builder.appendLine(
|
||||
line.trim()
|
||||
)
|
||||
}
|
||||
}
|
||||
return builder.toString().trim()
|
||||
}
|
||||
|
||||
private fun parse(
|
||||
text: String,
|
||||
): Config {
|
||||
val services = text
|
||||
.split(EMPTY_LINES)
|
||||
.map { parseService(it) }
|
||||
|
||||
return Config(services)
|
||||
}
|
||||
|
||||
private fun parseService(
|
||||
text: String,
|
||||
): Service {
|
||||
val lines = text.lines()
|
||||
val name = lines[0]
|
||||
val arguments = lines
|
||||
.drop(1)
|
||||
.map { parseArgument(it) }
|
||||
|
||||
return Service(name, arguments)
|
||||
}
|
||||
|
||||
private fun parseArgument(
|
||||
text: String,
|
||||
): Service.Argument {
|
||||
val match = ARGUMENT.find(text)!!
|
||||
val name = match.groups["name"]!!.value
|
||||
val value = match.groups["value"]!!.value
|
||||
|
||||
return Service.Argument(name, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.infendro.ddns.config
|
||||
|
||||
object Regex {
|
||||
val EMPTY_LINES = Regex("""\n{2,}""")
|
||||
val ARGUMENT = Regex("""(?<name>[a-z]+(?:-[a-z]+)*)(?:=(?<value>.*))?""")
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.infendro.ddns.dns
|
||||
|
||||
import com.infendro.ddns.dns.model.DnsRecord
|
||||
|
||||
abstract class DnsService {
|
||||
abstract fun getRecords(
|
||||
domain: String,
|
||||
subdomains: List<String>,
|
||||
): List<DnsRecord>
|
||||
|
||||
abstract fun updateRecord(
|
||||
record: DnsRecord,
|
||||
value: String,
|
||||
)
|
||||
|
||||
fun updateRecords(
|
||||
records: List<DnsRecord>,
|
||||
value: String,
|
||||
) {
|
||||
for (record in records) {
|
||||
if (record.value == value) continue
|
||||
updateRecord(record, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.infendro.ddns.dns
|
||||
|
||||
object DnsServices {
|
||||
const val PORKBUN = "porkbun"
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.infendro.ddns.dns
|
||||
|
||||
object Regex {
|
||||
val DOMAIN = Regex("""(?:(?<subdomain>(?:\w+\.)*\w+)\.)?(?<domain>\w+\.\w+)""")
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.infendro.ddns.dns.model
|
||||
|
||||
data class DnsRecord(
|
||||
val id: String,
|
||||
val type: Type,
|
||||
val domain: Domain,
|
||||
val value: String,
|
||||
val ttl: Int,
|
||||
val priority: Int?,
|
||||
) {
|
||||
data class Domain(
|
||||
val subdomain: String?,
|
||||
val domain: String,
|
||||
) {
|
||||
val full: String
|
||||
get() = if (subdomain != null) {
|
||||
"$subdomain.$domain"
|
||||
} else {
|
||||
domain
|
||||
}
|
||||
}
|
||||
|
||||
enum class Type {
|
||||
NS, A, AAAA, CNAME, MX, TXT;
|
||||
|
||||
companion object {
|
||||
val address: List<Type>
|
||||
get() = listOf(A, AAAA)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package com.infendro.ddns.dns.porkbun
|
||||
|
||||
import com.infendro.ddns.Http.client
|
||||
import com.infendro.ddns.dns.Regex.DOMAIN
|
||||
import com.infendro.ddns.dns.DnsService
|
||||
import com.infendro.ddns.dns.model.DnsRecord
|
||||
import com.infendro.ddns.dns.porkbun.dto.request.GetRecordsRequest
|
||||
import com.infendro.ddns.dns.porkbun.dto.request.UpdateRecordRequest
|
||||
import com.infendro.ddns.dns.porkbun.dto.response.GetRecordsResponse
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.contentType
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
class Porkbun(
|
||||
val key: String,
|
||||
val secretkey: String,
|
||||
) : DnsService() {
|
||||
override fun getRecords(
|
||||
domain: String,
|
||||
subdomains: List<String>,
|
||||
): List<DnsRecord> = runBlocking {
|
||||
val response = client.post("https://api.porkbun.com/api/json/v3/dns/retrieve/$domain") {
|
||||
val request = getRecordsRequest()
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(request)
|
||||
}
|
||||
val body = response.body<GetRecordsResponse>()
|
||||
|
||||
body.records
|
||||
.map { model(it) }
|
||||
.filter { it.type in DnsRecord.Type.address && (it.domain.subdomain ?: "") in subdomains }
|
||||
}
|
||||
|
||||
override fun updateRecord(
|
||||
record: DnsRecord,
|
||||
value: String,
|
||||
): Unit = runBlocking {
|
||||
client.post("https://api.porkbun.com/api/json/v3/dns/edit/${record.domain.domain}/${record.id}") {
|
||||
val request = updateRecordRequest(record, value)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(request)
|
||||
}
|
||||
}
|
||||
|
||||
private fun model(
|
||||
record: GetRecordsResponse.Record,
|
||||
): DnsRecord {
|
||||
val match = DOMAIN.matchEntire(record.name)!!
|
||||
val domain = match.groups["domain"]!!.value
|
||||
val subdomain = match.groups["subdomain"]?.value
|
||||
|
||||
return DnsRecord(
|
||||
id = record.id,
|
||||
type = DnsRecord.Type.valueOf(record.type),
|
||||
domain = DnsRecord.Domain(
|
||||
subdomain = subdomain,
|
||||
domain = domain,
|
||||
),
|
||||
value = record.content,
|
||||
ttl = record.ttl.toInt(),
|
||||
priority = record.prio?.toInt(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun getRecordsRequest(): GetRecordsRequest {
|
||||
return GetRecordsRequest(
|
||||
apikey = key,
|
||||
secretapikey = secretkey,
|
||||
)
|
||||
}
|
||||
|
||||
private fun updateRecordRequest(
|
||||
record: DnsRecord,
|
||||
ip: String,
|
||||
): UpdateRecordRequest {
|
||||
return UpdateRecordRequest(
|
||||
apikey = key,
|
||||
secretapikey = secretkey,
|
||||
type = record.type.toString(),
|
||||
name = record.domain.subdomain ?: "",
|
||||
content = ip,
|
||||
ttl = record.ttl.toString(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.infendro.ddns.dns.porkbun.dto.request
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class GetRecordsRequest(
|
||||
val apikey: String,
|
||||
val secretapikey: String,
|
||||
)
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.infendro.ddns.dns.porkbun.dto.request
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class UpdateRecordRequest(
|
||||
val apikey: String,
|
||||
val secretapikey: String,
|
||||
val type: String,
|
||||
val name: String,
|
||||
val content: String,
|
||||
val ttl: String,
|
||||
)
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.infendro.ddns.dns.porkbun.dto.response
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class GetRecordsResponse(
|
||||
val status: String,
|
||||
val cloudflare: String,
|
||||
val records: Array<Record>,
|
||||
) {
|
||||
@Serializable
|
||||
data class Record(
|
||||
val id: String,
|
||||
val type: String,
|
||||
val name: String,
|
||||
val content: String,
|
||||
val ttl: String,
|
||||
val prio: String?,
|
||||
val notes: String?,
|
||||
)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.infendro.ddns.ip
|
||||
|
||||
abstract class IpService {
|
||||
abstract val ipv4: String
|
||||
abstract val ipv6: String
|
||||
|
||||
val ip: List<String>
|
||||
get() = listOf(ipv4, ipv6)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.infendro.ddns.ip
|
||||
|
||||
import com.infendro.ddns.ip.ipify.Ipify
|
||||
|
||||
object IpServices {
|
||||
const val IPIFY = "ipify"
|
||||
val DEFAULT = Ipify
|
||||
|
||||
fun get(
|
||||
name: String,
|
||||
): IpService {
|
||||
return when (name) {
|
||||
IPIFY -> Ipify
|
||||
else -> throw Exception()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.infendro.ddns.ip.ipify
|
||||
|
||||
import com.infendro.ddns.Http
|
||||
import com.infendro.ddns.ip.IpService
|
||||
import com.infendro.ddns.ip.ipify.dto.response.GetIpResponse
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
object Ipify : IpService() {
|
||||
override val ipv4: String
|
||||
get() = runBlocking {
|
||||
val response = Http.client.get("https://api.ipify.org?format=json")
|
||||
val body = response.body<GetIpResponse>()
|
||||
body.ip
|
||||
}
|
||||
|
||||
override val ipv6: String
|
||||
get() = runBlocking {
|
||||
val response = Http.client.get("https://api64.ipify.org?format=json")
|
||||
val body = response.body<GetIpResponse>()
|
||||
body.ip
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.infendro.ddns.ip.ipify.dto.response
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class GetIpResponse(
|
||||
val ip: String,
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
use std::{error::Error, fs};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct Config {
|
||||
pub auth: AuthConfig,
|
||||
pub dns: DnsConfig,
|
||||
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct AuthConfig {
|
||||
pub key: String,
|
||||
pub secret_key: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct DnsConfig {
|
||||
pub entries: Vec<Entry>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub domain: String,
|
||||
pub subdomains: Vec<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load(path: &str) -> Result<Self, Box<dyn Error>> {
|
||||
let raw = fs::read_to_string(&path)?;
|
||||
let config = toml::from_str(&raw)?;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
pub mod client;
|
||||
pub mod config;
|
||||
pub mod model;
|
||||
pub mod service;
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use reqwest::Client;
|
||||
|
||||
use crate::{client::{dns_client::DnsClient, ip_client::IpClient}, config::Config, service::dns_service::DnsService};
|
||||
|
||||
const CONFIG: &str = "/etc/ddns.conf";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = Config::load(CONFIG)?;
|
||||
let client = Client::new();
|
||||
let ip_client = IpClient::new(client.clone());
|
||||
let dns_client = DnsClient::new(config.auth.clone(), client.clone());
|
||||
let dns_service = DnsService::new(config.dns.clone(), ip_client, dns_client);
|
||||
|
||||
dns_service.update_records().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
pub struct DnsRecord {
|
||||
pub id: String,
|
||||
pub type_: String,
|
||||
pub domain: String,
|
||||
pub subdomain: String,
|
||||
pub value: String,
|
||||
pub ttl: i32,
|
||||
}
|
||||
|
||||
impl DnsRecord {
|
||||
pub fn new(
|
||||
id: String,
|
||||
type_: String,
|
||||
domain: String,
|
||||
subdomain: String,
|
||||
value: String,
|
||||
ttl: i32,
|
||||
) -> Self {
|
||||
Self { id, type_, domain, subdomain, value, ttl }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
pub struct IpAddress {
|
||||
pub ipv4: Option<String>,
|
||||
pub ipv6: Option<String>,
|
||||
}
|
||||
|
||||
impl IpAddress {
|
||||
pub fn new(
|
||||
ipv4: Option<String>,
|
||||
ipv6: Option<String>
|
||||
) -> Self {
|
||||
Self { ipv4, ipv6 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod dns_record;
|
||||
pub mod ip_address;
|
||||
@@ -0,0 +1,51 @@
|
||||
use std::error::Error;
|
||||
|
||||
use crate::{client::{dns_client::DnsClient, ip_client::IpClient}, config::{DnsConfig}, model::{dns_record::DnsRecord, ip_address::IpAddress}};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DnsService {
|
||||
dns_config: DnsConfig,
|
||||
ip_client: IpClient,
|
||||
dns_client: DnsClient,
|
||||
}
|
||||
|
||||
impl DnsService {
|
||||
pub fn new(dns_config: DnsConfig, ip_client: IpClient, dns_client: DnsClient) -> Self {
|
||||
Self { dns_config, ip_client, dns_client }
|
||||
}
|
||||
|
||||
pub async fn update_records(&self) -> Result<(), Box<dyn Error>> {
|
||||
let ip = self.ip_client.get_ip().await?;
|
||||
for entry in &self.dns_config.entries {
|
||||
self.update_ip_records(&entry.domain, &entry.subdomains, &ip).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_ip_records(&self, domain: &str, subdomains: &[String], ip: &IpAddress) -> Result<(), Box<dyn Error>> {
|
||||
let records = self.dns_client.get_records(domain).await?;
|
||||
|
||||
if let Some(ipv4) = &ip.ipv4 {
|
||||
let ipv4_records: Vec<&DnsRecord> = records.iter()
|
||||
.filter(|it| it.type_ == "A" && subdomains.contains(&it.subdomain) && it.value != *ipv4)
|
||||
.collect();
|
||||
|
||||
for ipv4_record in ipv4_records {
|
||||
self.dns_client.update_record(&ipv4_record, ipv4).await?;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ipv6) = &ip.ipv6 {
|
||||
let ipv6_records: Vec<&DnsRecord> = records.iter()
|
||||
.filter(|it| it.type_ == "AAAA" && subdomains.contains(&it.subdomain) && it.value != *ipv6)
|
||||
.collect();
|
||||
|
||||
for ipv6_record in ipv6_records {
|
||||
self.dns_client.update_record(&ipv6_record, ipv6).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod dns_service;
|
||||
Reference in new issue
Block a user