initial commit

This commit is contained in:
2025-05-04 12:29:59 +02:00
commit 01b3246533
10 changed files with 805 additions and 0 deletions

120
src/app.py Normal file
View File

@@ -0,0 +1,120 @@
from quart import Quart, render_template, request, jsonify
import httpx
from anilistapi.queries.manga import REQUESTS_QUERY, TAGS_QUERY, GENRES_QUERY
from anilistapi.schemas.manga import Manga
from komcache import KomCache
app = Quart(__name__)
cache = KomCache()
cache.create_table(
"CREATE TABLE IF NOT EXISTS manga_requests (id INTEGER PRIMARY KEY, manga_id INTEGER, manga_title TEXT)"
)
async def fetch_data(query):
# Simulated API response
async with httpx.AsyncClient() as client:
try:
response = await client.post(
f"https://graphql.anilist.co",
json={"query": REQUESTS_QUERY, "variables": {"search": query}},
)
response.raise_for_status()
data = response.json()
results = []
for item in data.get("data", {}).get("Page", {}).get("media", []):
manga = Manga(**item)
results.append(
{
"id": manga.id,
"title": manga.title.romaji if manga.title else "Untitled",
"image": manga.coverImage.get("large")
if manga.coverImage
else "https://demofree.sirv.com/nope-not-here.jpg",
"status": manga.status,
"type": manga.type,
"genres": manga.genres or [],
"tags": [tag.name for tag in (manga.tags or [])],
"description": manga.description.replace("<br>", "\n")
if manga.description
else "No description available",
"isAdult": manga.isAdult,
}
)
return results
except Exception as e:
print(f"Error fetching data: {e}")
return []
@app.route("/api/genres")
async def get_genres():
async with httpx.AsyncClient() as client:
try:
response = await client.post(
f"https://graphql.anilist.co",
json={"query": GENRES_QUERY},
)
response.raise_for_status()
data = response.json()
results = data.get("data", {}).get("genres", [])
return jsonify(results)
except Exception as e:
print(f"Error fetching genres: {e}")
return jsonify([])
@app.route("/api/tags")
async def get_tags():
async with httpx.AsyncClient() as client:
try:
response = await client.post(
f"https://graphql.anilist.co",
json={"query": TAGS_QUERY},
)
response.raise_for_status()
data = response.json()
results = data.get("data", {}).get("tags", [])
return jsonify(results)
except Exception as e:
print(f"Error fetching genres: {e}")
return jsonify([])
@app.route("/", methods=["GET", "POST"])
async def index():
query = None
results = []
if request.method == "POST":
form = await request.form
query = form.get("query")
if query:
results = await fetch_data(query)
return await render_template("index.html", results=results)
@app.route("/request", methods=["POST"])
async def log_request():
data = await request.get_json()
print(data)
item = data.get("item")
if item:
asynccache = KomCache()
manga_title = data.get("title")
asynccache.insert(
"INSERT INTO manga_requests (manga_id, manga_title) VALUES (?, ?)",
(item, manga_title),
)
return jsonify({"status": "success"})
return jsonify({"status": "failed"}), 400
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)

112
src/query.json Normal file
View File

@@ -0,0 +1,112 @@
{
"query": "query(
$page:Int = 1
$id:Int
$type:MediaType
$isAdult:Boolean = false
$search:String
$format: [MediaFormat
]
$status:MediaStatus
$countryOfOrigin:CountryCode
$source:MediaSource
$season:MediaSeason
$seasonYear:Int
$year:String
$onList:Boolean
$yearLesser:FuzzyDateInt
$yearGreater:FuzzyDateInt
$episodeLesser:Int
$episodeGreater:Int
$durationLesser:Int
$durationGreater:Int
$chapterLesser:Int
$chapterGreater:Int
$volumeLesser:Int
$volumeGreater:Int
$licensedBy: [Int
]
$isLicensed:Boolean
$genres: [String
]
$excludedGenres: [String
]
$tags: [String
]
$excludedTags: [String
]
$minimumTagRank:Int
$sort: [MediaSort
]=[POPULARITY_DESC,SCORE_DESC
])
{
Page(page:$page,perPage: 20)
{
pageInfo{
total
perPage
currentPage
lastPage
hasNextPage
}
media(
id:$id
type:$type
season:$season
format_in:$format
status:$status
countryOfOrigin:$countryOfOrigin
source:$source
search:$search
onList:$onList
seasonYear:$seasonYear
startDate_like:$year
startDate_lesser:$yearLesser
startDate_greater:$yearGreater
episodes_lesser:$episodeLesser
episodes_greater:$episodeGreater
duration_lesser:$durationLesser
duration_greater:$durationGreater
chapters_lesser:$chapterLesser
chapters_greater:$chapterGreater
volumes_lesser:$volumeLesser
volumes_greater:$volumeGreater
licensedById_in:$licensedBy
isLicensed:$isLicensed
genre_in:$genres
genre_not_in:$excludedGenres
tag_in:$tags
tag_not_in:$excludedTags
minimumTagRank:$minimumTagRank
sort:$sort
isAdult:$isAdult
)
{
id title{
userPreferred
}
coverImage{extraLarge large color
}
startDate{year month day
}
endDate{year month day
}
bannerImage season seasonYear description type format status(version: 2)episodes duration chapters volumes genres isAdult averageScore popularity nextAiringEpisode{airingAt timeUntilAiring episode
}
mediaListEntry{id status
}
studios(isMain:true){edges{isMain node{id name
}
}
}
}
}
}","variables": {"page": 1,"type": "MANGA",
"genres": [
"Action",
"Romance"
],
"sort": "SEARCH_MATCH",
"search": "Assassin"
}
}

122
src/static/style.css Normal file
View File

@@ -0,0 +1,122 @@
/* ========== GRID LAYOUT ========== */
.results {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 20px;
margin-top: 20px;
}
/* Responsive: show 1 per row on small screens */
@media screen and (max-width: 768px) {
.results {
grid-template-columns: 1fr;
}
}
/* ========== CARD STYLING ========== */
.card {
position: relative;
padding: 10px;
border: 1px solid #ccc;
background: #fafafa;
text-align: center;
transition: box-shadow 0.2s;
}
.card:hover {
box-shadow: 0 0 10px #aaa;
}
.card img {
width: 100%;
height: auto;
}
/* ========== ACTION BUTTONS ========== */
.actions {
margin-top: 10px;
display: flex;
justify-content: space-around;
}
/* ========== MODAL ========== */
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 5% auto;
padding: 20px;
border: 1px solid #888;
width: 50%;
border-radius: 10px;
}
.close {
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
/* ========== IMAGE CONTAINER ========== */
.image-container {
position: relative;
overflow: hidden;
}
.image-container img {
width: 100%;
height: auto;
display: block;
transition: filter 0.3s ease;
}
/* ========== BLUR CONTROL VIA BODY CLASS ========== */
body.nsfw-disabled .image-container.nsfw img {
filter: blur(8px);
}
body.nsfw-disabled .image-container.nsfw:hover img {
filter: none;
/* Remove blur on hover, set as important */
}
/* ========== BADGE ========== */
.adult-badge {
position: absolute;
top: 8px;
left: 8px;
background-color: rgba(255, 0, 0, 0.8);
color: white;
padding: 4px 8px;
font-size: 12px;
font-weight: bold;
border-radius: 4px;
z-index: 1;
pointer-events: none;
}
.search-bar {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 20px;
}
.search-bar select {
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}

174
src/templates/index.html Normal file
View File

@@ -0,0 +1,174 @@
<!doctype html>
<html>
<head>
<title>Anime Search and Request Page</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Search Manga</h1>
<div class="search-bar">
<input type="text" id="searchInput" placeholder="Search..." />
<div class="selectors">
<select id="genreSelect" multiple>
<!-- Populated dynamically -->
</select>
<select id="tagSelect" multiple>
<!-- Populated dynamically -->
</select>
</div>
<button onclick="performSearch()">Search</button>
</div>
{% if results %}
<div style="margin-bottom: 1em;">
<label>
<input type="checkbox" id="toggleNSFW" />
Show NSFW content
</label>
</div>
<div class="results">
{% for result in results %}
<div class="card">
<div class="image-container {{ 'nsfw' if result.isAdult else '' }}">
<img src="{{ result.image }}" alt="Cover">
{% if result.isAdult %}
<div class="adult-badge">18+</div>
{% endif %}
</div>
<p>{{ result.title }}</p>
<div class="actions">
<button onclick='showInfo({{ result | tojson | safe }})'>Info</button>
<!-- return title and id -->
<button onclick='sendRequest({{ result.id | tojson }})'>Request</button>
</div>
</div>
{% endfor %}
</div>
{% endif %}
<!-- Info Modal -->
<div id="infoModal" class="modal" style="display:none;">
<div class="modal-content">
<span class="close" onclick="closeModal()">&times;</span>
<h2 id="modalTitle"></h2>
<p><strong>Status:</strong> <span id="modalStatus"></span></p>
<p><strong>Type:</strong> <span id="modalType"></span></p>
<p><strong>Genres:</strong> <span id="modalGenres"></span></p>
<p><strong>Tags:</strong> <span id="modalTags"></span></p>
<p><strong>Adult Content:</strong> <span id="modalAdult"></span></p>
<p><strong>Description:</strong></p>
<p id="modalDescription"></p>
</div>
</div>
<script>
function sendRequest(item) {
fetch("/request", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ item: item })
})
.then(res => res.json())
.then(data => alert(data.status === "success" ? "Request logged!" : "Failed"));
}
function showInfo(data) {
document.getElementById("modalTitle").textContent = data.title;
document.getElementById("modalStatus").textContent = data.status || "Unknown";
document.getElementById("modalType").textContent = data.type || "Unknown";
document.getElementById("modalGenres").textContent = (data.genres || []).join(", ");
document.getElementById("modalTags").textContent = (data.tags || []).join(", ");
document.getElementById("modalAdult").textContent = data.isAdult ? "Yes" : "No";
document.getElementById("modalDescription").textContent = data.description || "No description available.";
document.getElementById("infoModal").style.display = "block";
}
function closeModal() {
document.getElementById("infoModal").style.display = "none";
}
// Blur effect for NSFW images
document.addEventListener("DOMContentLoaded", () => {
const checkbox = document.getElementById("toggleNSFW");
const body = document.body;
// Initial state
body.classList.add("nsfw-disabled");
// NSFW toggle
checkbox.addEventListener("change", () => {
const enabled = checkbox.checked;
body.classList.toggle("nsfw-disabled", !enabled);
body.classList.toggle("nsfw-enabled", enabled);
// Reset all image blur states when toggling
document.querySelectorAll('.image-container.nsfw img').forEach(img => {
img.dataset.blurred = "true";
img.style.filter = ""; // Remove inline filter style to respect CSS hover and CSS blur
});
});
// Fetch genres and tags on page load
fetchOptions("/api/genres", "genreSelect");
fetchOptions("/api/tags", "tagSelect");
});
// Mobile: click toggles blur when NSFW is disabled
async function fetchOptions(url, selectId) {
try {
const res = await fetch(url);
const data = await res.json();
const select = document.getElementById(selectId);
data.forEach(item => {
const option = document.createElement("option");
option.value = item;
option.textContent = item;
select.appendChild(option);
});
} catch (err) {
console.error("Error fetching " + selectId, err);
}
}
function performSearch() {
const searchTerm = document.getElementById("searchInput").value.trim();
const selectedGenres = Array.from(document.getElementById("genreSelect").selectedOptions).map(opt => opt.value);
const selectedTags = Array.from(document.getElementById("tagSelect").selectedOptions).map(opt => opt.value);
const query = {
query: searchTerm,
genres: selectedGenres,
tags: selectedTags
};
fetch("/search", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(query)
})
.then(res => res.json())
.then(data => displayResults(data))
.catch(err => console.error("Search failed", err));
}
function displayResults(data) {
// Replace this with your rendering logic
console.log(data);
}
</script>
</body>
</html>