feat: app standalone - ride of docker and api

This commit is contained in:
cstaelen committed 2024-01-26 13:01:52 +01:00
1 parent 3021a58409
commit 9bd61a4e52
182 files changed
+1080 -3222

No files matched your search

-16
View File
@@ -1,16 +0,0 @@
node_modules
.gitignore
Dockerfile
builder.Dockerfile
.dockerignore
Makefile
*.log*
.nitro
.cache
dist
app
compose.override.yml
CHANGELOG.md
README.md
.git
android
+7 -18
View File
@@ -8,29 +8,18 @@
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
.vscode
*.pem
__pycache__
.env.local
.env.development.local
.env.test.local
.env.production.local
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# docker
compose.override.yml
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
env-config.js
.idea
-29
View File
@@ -1,29 +0,0 @@
IMAGE=cstaelen/shazarr
IMAGE_API=cstaelen/shazarr-api
VERSION=0.0.1
DOCKERFILE_API=./docker/api.Dockerfile
api/dev:
docker compose up --build
api/build:
docker build --platform linux/amd64 -f ${DOCKERFILE_API} -t ${IMAGE_API}:${VERSION} -t ${IMAGE_API}:latest .
api/run:
docker run \
--rm \
--name shazarr \
--platform=linux/amd64 \
-p 12358:12358 \
${IMAGE_API}:${VERSION}
app/dev:
npm run android:serve --prefix ./app
android/build:
npm run android:build --prefix ./app
android/live:
npm run android:live --prefix ./app
ios/build:
npm run ios:build --prefix ./app
ios/live:
npm run ios:live --prefix ./app
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -11,6 +11,7 @@ apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-device')
implementation project(':capacitor-haptics')
implementation project(':capacitor-network')
implementation project(':capacitor-preferences')
implementation project(':capacitor-voice-recorder')
File renamed without changes.
+17
View File
@@ -0,0 +1,17 @@
<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:exported="true" android:label="@string/title_activity_main" android:launchMode="singleTask" android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBarLaunch">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true" android:name="androidx.core.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1,17 @@
<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:exported="true" android:label="@string/title_activity_main" android:launchMode="singleTask" android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBarLaunch">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true" android:name="androidx.core.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -8,6 +8,9 @@ project(':capacitor-device').projectDir = new File('../node_modules/@capacitor/d
include ':capacitor-haptics'
project(':capacitor-haptics').projectDir = new File('../node_modules/@capacitor/haptics/android')
include ':capacitor-network'
project(':capacitor-network').projectDir = new File('../node_modules/@capacitor/network/android')
include ':capacitor-preferences'
project(':capacitor-preferences').projectDir = new File('../node_modules/@capacitor/preferences/android')
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
-3
View File
@@ -1,3 +0,0 @@
{
"extends": "next/core-web-vitals"
}
-29
View File
@@ -1,29 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# project
/download
/settings/.tidal-dl.token.json
/settings/beets/*
/shared
/docker/mnt
# dependencies
/node_modules
/.pnp
.pnp.js
# production
/dist
# misc
.DS_Store
.vscode
*.pem
# debug
npm-debug.log*
# docker
compose.override.yml
# typescript
*.tsbuildinfo
-5
View File
@@ -1,5 +0,0 @@
export const ROOT_PATH = '/home/app/standalone/api';
export function replaceAll(str: string, find: string, replace: string) {
return str.replace(new RegExp(find, 'g'), replace);
}
-122
View File
@@ -1,122 +0,0 @@
import express, { Express, Request, Response } from "express";
import dotenv from "dotenv";
import { execSync } from "child_process";
import { ROOT_PATH } from "./constants";
const fs = require('fs');
dotenv.config({ path: ".env", override: true });
const port = process.env.API_PORT;
const hostname = process.env.HOSTNAME;
const app: Express = express();
app.use(express.json({ limit: "50mb" }));
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', (req: Request, res: Response) => {
res.sendfile('default.html', { root: __dirname + "/../static" } );
});
app.get('/config', (req: Request, res: Response) => {
const config = {
LIDARR_ENABLED: !!(process.env.LIDARR_API_KEY && process.env.LIDARR_URL && process.env.LIDARR_LIBRARY_PATH),
TIDARR_URL: process.env.TIDARR_URL,
}
res.send(config);
});
app.get('/search_lidarr', async (req: Request, res: Response) => {
if (!req.query.term) {
res.send("error");
return;
}
const command = `curl "${process.env.LIDARR_URL}/api/v1/album/lookup?term=${encodeURIComponent(req.query.term as string)}&apikey=${process.env.LIDARR_API_KEY}"`;
const response = await execSync(
command,
{ encoding: "utf-8" }
);
res.send(response);
});
app.get('/monitor_lidarr', async (req: Request, res: Response) => {
if (!req.query.albumData) {
res.send("error");
return;
}
const jsonReqData = JSON.parse(req.query.albumData as string);
const data = {
...jsonReqData,
"overview": "",
"artist": {
...jsonReqData.artist,
"overview": "",
"qualityProfileId": 3,
"rootFolderPath": process.env.LIDARR_LIBRARY_PATH,
"addOptions": {
"monitor": "none",
"albumsToMonitor": [
jsonReqData.releases[0].foreignReleaseId
],
"monitored": false,
"searchForMissingAlbums": false,
}
},
"addOptions": {
"addType": "automatic",
"searchForNewAlbum": false,
},
};
const command = `curl -0 -v ${process.env.LIDARR_URL}/api/v1/album?apikey=${process.env.LIDARR_API_KEY} \
-H 'Content-Type: application/json' \
-d '${JSON.stringify(data)}'`;
try {
const response = await execSync(
command,
);
res.send(response);
} catch (e) {
console.log(e);
}
});
app.post('/recognize', async (req: Request, res: Response) => {
const buf = Buffer.from(req.body.file, 'base64'); // decode
const filePath = `/tmp/data-${Date.now()}.mp3`;
fs.writeFile(filePath, buf, async function(err: any) {
if(err) {
console.log("err", err);
} else {
const command = `python ${ROOT_PATH}/scripts/shazarr.py ${filePath}`;
// const command = `python ${ROOT_PATH}/scripts/shazarr.py /home/app/standalone/api/scripts/test.m4a`;
console.log(`Executing: ${command}`);
const response = await execSync(
command,
{ encoding: "utf-8" }
);
const data = JSON.stringify(response);
await execSync(
`rm ${filePath}`,
{ encoding: "utf-8" }
);
res.send(data);
}
});
});
app.listen(port, () => {
console.log(`⚡️[server]: Server is running at http://${hostname}:${port}`);
});
-2254
View File
File diff suppressed because it is too large. Load diff
-22
View File
@@ -1,22 +0,0 @@
{
"name": "shazarr-api",
"version": "0.0.1",
"private": false,
"license": "MIT",
"scripts": {
"build": "npx tsc --project ./tsconfig.json",
"dev": "concurrently -n api,api \"npx tsc --project ./tsconfig.json --watch\" \"nodemon -q ./dist/index.js\"",
"prod": "node ./dist/index.js"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^20.10.5",
"eslint": "^8.56.0",
"nodemon": "^3.0.2",
"typescript": "^5.3.3"
},
"dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2"
}
}
-18
View File
@@ -1,18 +0,0 @@
import asyncio
import sys
import json
from shazamio import Shazam
if len(sys.argv) != 2:
raise ValueError('Please provide file url')
file = sys.argv[1]
async def main():
shazam = Shazam()
out = await shazam.recognize_song(file)
info = json.dumps(out)
print(info)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Binary file not shown.
-41
View File
@@ -1,41 +0,0 @@
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
</head>
<style>
body {
font-family: Arial, sans-serif;
}
a {
color: #555;
}
</style>
<body>
<center>
<h1>SHAZARR - API</h1>
<p><i>- Server running -</i></p>
<p>Download client APK :</p>
<div id="qrcode"></div>
<p>
<a href="https://github.com/cstaelen/docker-shazarr/raw/main/outputs/shazarr-app.apk" target="_blank">
Github direct link
</a>
&nbsp;
<a href="https://github.com/cstaelen/docker-shazarr" target="_blank">
Github project page
</a>
</p>
<code>
Server URL : <span id="server-url"></span>
</code>
<script>
new QRCode(document.getElementById("qrcode"), "https://github.com/cstaelen/docker-shazarr/raw/main/outputs/shazarr-app.apk");
document.getElementById("server-url").innerHTML = window.location.href;
</script>
</center>
</body>
</html>
-109
View File
@@ -1,109 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
-25
View File
@@ -1,25 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.idea
-46
View File
@@ -1,46 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
@@ -1,37 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:usesCleartextTraffic="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1 @@
{}
+4 -6
View File
@@ -1,7 +1,5 @@
{
"name": "shazarr",
"integrations": {
"capacitor": {}
},
"type": "react"
}
"name": "New Ionic App",
"integrations": {},
"type": "react"
}
-109
View File
@@ -1,109 +0,0 @@
import { Preferences } from "@capacitor/preferences";
import {
Box,
Input,
Button,
Paper,
Dialog,
DialogContent,
} from "@mui/material";
import { useState, useRef, useEffect } from "react";
import { useShazarrProvider } from "../Shazarr/Provider";
import ApiErrorAlert from "./Alert";
import styled from "@emotion/styled";
export default function FormApi() {
const [apiUrl, setApiUrl] = useState<string>();
const [showApiForm, setShowApiForm] = useState<boolean>();
const inputRef = useRef<HTMLInputElement>();
const {
recordingStatus,
recordingError,
apiError,
actions: { fetchConfig },
} = useShazarrProvider();
async function saveApiUrl() {
if (inputRef.current) {
const url = inputRef.current.querySelector("input")?.value;
if (url) {
setApiUrl(url);
await Preferences.set({ key: "shazarr_api_url", value: url });
}
setShowApiForm(false);
fetchConfig();
}
}
async function handleApiURL() {
const { value: existingUrl } = await Preferences.get({
key: "shazarr_api_url",
});
if (existingUrl) {
setApiUrl(existingUrl);
const input = inputRef?.current?.querySelector("input");
if (input) {
input.value = existingUrl;
}
}
}
useEffect(() => {
handleApiURL();
}, []);
return (
<>
{apiError && recordingStatus === "inactive" && <ApiErrorAlert />}
{recordingError && recordingStatus === "inactive" && (
<ApiErrorAlert message={recordingError} />
)}
<Dialog
fullWidth
maxWidth="xs"
open={!!showApiForm}
onClose={() => setShowApiForm(false)}
>
<DialogContent sx={{ padding: "0.5rem" }}>
<Box>
<Box marginBottom={2}>
<Paper sx={{ padding: "0.5rem" }}>
<Input
type="url"
sx={{ fontSize: "0.925rem" }}
defaultValue={apiUrl}
placeholder="Shazarr API URL (http://...:12358)"
fullWidth
ref={inputRef}
/>
</Paper>
</Box>
<Box>
<Button
fullWidth
type="submit"
variant="contained"
onClick={() => saveApiUrl()}
>
Save API URL
</Button>
</Box>
</Box>
</DialogContent>
</Dialog>
<ButtonConfig>
<Button
onClick={() => setShowApiForm(!showApiForm)}
disabled={recordingStatus !== "inactive"}
>
Server configuration
</Button>
</ButtonConfig>
</>
);
}
const ButtonConfig = styled.div`
margin-bottom: 1rem;
`;
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more