handle cookie through text form, #856

This commit is contained in:
Simon
2025-01-10 17:09:11 +07:00
parent 5cc40315c4
commit d1a42c4b57
6 changed files with 143 additions and 30 deletions

View File

@@ -189,32 +189,28 @@ class CookieView(ApiBaseView):
GET: check if cookie is enabled
POST: verify validity of cookie
PUT: import cookie
DELETE: revoke the cookie
"""
permission_classes = [AdminOnly]
@staticmethod
def get(request):
def get(self, request):
"""handle get request"""
# pylint: disable=unused-argument
config = AppConfig().config
valid = RedisArchivist().get_message_dict("cookie:valid")
response = {"cookie_enabled": config["downloads"]["cookie_import"]}
response.update(valid)
validation = self._get_cookie_validation()
return Response(response)
return Response(validation)
@staticmethod
def post(request):
"""handle post request"""
def post(self, request):
"""handle cookie validation request"""
# pylint: disable=unused-argument
config = AppConfig().config
validated = CookieHandler(config).validate()
_ = CookieHandler(config).validate()
validation = self._get_cookie_validation()
return Response({"cookie_validated": validated})
return Response(validation)
@staticmethod
def put(request):
def put(self, request):
"""handle put request"""
# pylint: disable=unused-argument
config = AppConfig().config
@@ -230,12 +226,30 @@ class CookieView(ApiBaseView):
validated = handler.validate()
if not validated:
handler.revoke()
message = {"cookie_import": "fail", "cookie_validated": validated}
print(f"cookie: {message}")
return Response({"message": message}, status=400)
print("cookie import failed, not valid")
status = 400
else:
status = 200
message = {"cookie_import": "done", "cookie_validated": validated}
return Response(message)
validation = self._get_cookie_validation()
return Response(validation, status=status)
def delete(self, request):
"""delete the cookie"""
config = AppConfig().config
handler = CookieHandler(config)
handler.revoke()
return Response({"cookie_enabled": False})
@staticmethod
def _get_cookie_validation():
"""get current cookie validation"""
config = AppConfig().config
validation = RedisArchivist().get_message_dict("cookie:valid")
is_enabled = {"cookie_enabled": config["downloads"]["cookie_import"]}
validation.update(is_enabled)
return validation
class TokenView(ApiBaseView):

View File

@@ -0,0 +1,10 @@
import APIClient from '../../functions/APIClient';
import { CookieStateType } from '../loader/loadCookie';
const deleteCookie = async (): Promise<CookieStateType> => {
return APIClient('/api/appsettings/cookie/', {
method: 'DELETE',
});
};
export default deleteCookie;

View File

@@ -1,16 +1,10 @@
import APIClient from '../../functions/APIClient';
import { CookieStateType } from '../loader/loadCookie';
export type ValidatedCookieType = {
cookie_enabled: boolean;
status: boolean;
validated: number;
validated_str: string;
cookie_validated?: boolean;
};
const updateCookie = async (): Promise<ValidatedCookieType> => {
const updateCookie = async (cookie: string): Promise<CookieStateType> => {
return APIClient('/api/appsettings/cookie/', {
method: 'POST',
method: 'PUT',
body: { cookie },
});
};

View File

@@ -0,0 +1,10 @@
import APIClient from '../../functions/APIClient';
import { CookieStateType } from '../loader/loadCookie';
const validateCookie = async (): Promise<CookieStateType> => {
return APIClient('/api/appsettings/cookie/', {
method: 'POST',
});
};
export default validateCookie;

View File

@@ -0,0 +1,14 @@
import APIClient from '../../functions/APIClient';
export type CookieStateType = {
cookie_enabled: boolean;
status?: boolean;
validated?: number;
validated_str?: string;
};
const loadCookie = async (): Promise<CookieStateType> => {
return APIClient('/api/appsettings/cookie/');
};
export default loadCookie;

View File

@@ -13,6 +13,10 @@ import updateAppsettingsConfig from '../api/actions/updateAppsettingsConfig';
import loadApiToken from '../api/loader/loadApiToken';
import InputConfig from '../components/InputConfig';
import ToggleConfig from '../components/ToggleConfig';
import updateCookie from '../api/actions/updateCookie';
import loadCookie, { CookieStateType } from '../api/loader/loadCookie';
import deleteCookie from '../api/actions/deleteCookie';
import validateCookie from '../api/actions/validateCookie';
type SnapshotType = {
id: string;
@@ -35,6 +39,7 @@ type SettingsApplicationReponses = {
snapshots?: SnapshotListType;
appSettingsConfig?: AppSettingsConfigType;
apiToken?: string;
cookieState: CookieStateType;
};
const SettingsApplication = () => {
@@ -74,6 +79,8 @@ const SettingsApplication = () => {
const [commentsSort, setCommentsSort] = useState<string>('');
// Cookie
const [cookieFormData, setCookieFormData] = useState<string>('');
const [showCookieForm, setShowCookieForm] = useState<boolean>(false);
// const [cookieImport, setCookieImport] = useState(false);
// const [validatingCookie, setValidatingCookie] = useState(false);
// const [cookieResponse, setCookieResponse] = useState<ValidatedCookieType>();
@@ -92,6 +99,7 @@ const SettingsApplication = () => {
const snapshotResponse = await loadSnapshots();
const appSettingsConfig = await loadAppsettingsConfig();
const apiToken = await loadApiToken();
const cookieState = await loadCookie();
// Subscriptions
setVideoPageSize(appSettingsConfig.subscriptions.channel_size);
@@ -135,6 +143,7 @@ const SettingsApplication = () => {
snapshots: snapshotResponse,
appSettingsConfig,
apiToken: apiToken.token,
cookieState,
});
};
@@ -146,6 +155,23 @@ const SettingsApplication = () => {
setRefresh(true);
};
const handleCookieUpdate = async () => {
await updateCookie(cookieFormData);
setCookieFormData('');
setShowCookieForm(false);
setRefresh(true);
};
const handleCookieRevoke = async () => {
await deleteCookie();
setRefresh(true);
};
const handleCookieValidate = async () => {
await validateCookie();
setRefresh(true);
};
useEffect(() => {
fetchData();
}, []);
@@ -436,7 +462,52 @@ const SettingsApplication = () => {
</div>
<div className="info-box-item">
<h2 id="cookie">Cookie</h2>
<div className="settings-box-wrapper"></div>
<div className="settings-box-wrapper">
<div>
<p>Use your cookie for yt-dlp</p>
</div>
<div>
{response?.cookieState?.cookie_enabled ? (
<>
<p>
Cookie enabled. Last validation:{' '}
<span className="settings-current">
{response.cookieState.validated_str}
</span>
.
</p>
<div className="button-box">
<button className="danger-button" onClick={handleCookieRevoke}>
Revoke
</button>
<button onClick={handleCookieValidate}>Validate</button>
</div>
</>
) : (
<p>Cookie disabled</p>
)}
{showCookieForm ? (
<>
<textarea
value={cookieFormData}
onChange={e => {
setCookieFormData(e.currentTarget.value);
}}
/>
<div className="button-box">
<button onClick={handleCookieUpdate} type="submit">
Submit
</button>
<button onClick={() => setShowCookieForm(false)}>Cancel</button>
</div>
</>
) : (
<div>
<button onClick={() => setShowCookieForm(true)}>Update Cookie</button>
</div>
)}
</div>
</div>
</div>
<div className="info-box-item">
<h2 id="sntegrations">Integrations</h2>