Skip to content

Commit

Permalink
Merge pull request #23 from MainKronos/beta
Browse files Browse the repository at this point in the history
Beta
  • Loading branch information
MainKronos authored May 21, 2021
2 parents 82a1567 + 8796c61 commit 8e62896
Show file tree
Hide file tree
Showing 7 changed files with 169 additions and 28 deletions.
43 changes: 32 additions & 11 deletions config/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

LOG = None # variabile usata per inviare messaggi a schermo

@app.template_filter()
def msgSafe(msg):
msg = re.sub(r"[^a-zA-Z]", "", msg)
Expand All @@ -22,13 +24,18 @@ def favicon():
@app.route('/append_anime', methods=['POST']) # Per aggiungere un anime
def append_anime():
res = request.form
print(res, file=sys.stderr)
data = {
"title": request.form['title'],
"season": request.form['season'],
"season": "absolute",
"absolute": ("absolute" in request.form),
"links": request.form.getlist('link')
}
appendAnime(data)
if not data["absolute"]:
data["season"]= request.form['season']
# print(data, file=sys.stderr)

global LOG
LOG = appendAnime(data)
return redirect(url_for('index'))

@app.route('/delete_anime', methods=['POST']) # Per cancellare un anime
Expand Down Expand Up @@ -63,9 +70,9 @@ def settings_update():
@app.route('/index')
@app.route('/')
def index():

log = get_log()
anime = readData()
return render_template('index.html', infos=anime)
return render_template('index.html', infos=anime, log=log)



Expand Down Expand Up @@ -97,30 +104,36 @@ def myOrder(serieInfo):
return serieInfo["title"]

table = readData()
log = None # In caso di errore viene segnalato a video


for anime in table:
if data["title"] == anime["title"]: # Se esiste già l'anime nella tabella

if data["season"] in anime["seasons"]: # Se esiste già la stagione
for link in data["links"]:
if link not in anime["seasons"][data["season"]]: # Se il link non è già presente
anime["seasons"][data["season"]].append(link) # aggiunge un'altro link
# print(f"\n-> È stata aggiunto un altro link per la stagione {season} della serie {SonarrTitle}.")
log = "Nuovo link aggiunto"
else:
anime["seasons"][data["season"]] = list(data["links"]) # inizializza una nuova stagione
# print(f"\n-> È stata aggiunta la stagione {season} per la serie {SonarrTitle}.")
if not anime["absolute"] and not data["absolute"]: # Se la numerazione non è assoluta
anime["seasons"][data["season"]] = list(data["links"]) # inizializza una nuova stagione
log = f"Stagione {data['seasons']} di {data['title']} aggiunta"
else:
log = "ERRORE"

break
else: # se non è stato trovato nessun anime
table.append({
"title": data["title"],
"seasons": {data["season"]: data["links"]}
"seasons": {data["season"]: data["links"]},
"absolute": data["absolute"]
})
log = f"{data['title']} aggiunto"
# print(f"\n-> È stata aggiunta la serie {SonarrTitle}.")

table.sort(key=myOrder)
writeData(table)

return log

### getenv

Expand Down Expand Up @@ -174,3 +187,11 @@ def WriteSettings(settings):
json_location = "json/settings.json"
with open(json_location, 'w') as f:
f.write(json.dumps(settings, indent='\t'))

### OTHER

def get_log():
global LOG
log = LOG
LOG = None
return log
30 changes: 30 additions & 0 deletions config/app/static/css/my.css
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,29 @@ input{

/*#########################*/

.row {
display: flex;
align-items: baseline;
}

[type="checkbox"].filled-in:checked+span:not(.lever):after{
top: 0;
width: 20px;
height: 20px;
border: 2px solid #9FA8DA;
background-color: #9FA8DA;
z-index: 0;
}

.dropdown-content li:hover,
.dropdown-content{
background-color: #242424 !important;
}

.dropdown-content li>a, .dropdown-content li>span{
color: #9FA8DA;
}

.tap-target{
background-color: #9FA8DA !important;
}
Expand All @@ -173,6 +196,13 @@ input{
background-color: #2c2c2c !important;
}

span.badge.new {
background-color: #9FA8DA !important;
margin-right: 20px;
}



/*### OTHER ###*/

/* width */
Expand Down
32 changes: 28 additions & 4 deletions config/app/static/js/my.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ document.addEventListener('DOMContentLoaded', function() {
});


function get_anime(){
var elems = document.querySelectorAll('.collapsible-header');
var data = {};


for (var i = 0; i < elems.length; i++) {
data[elems[i].textContent.trim().replace('movie', '')] = null;
}
return data;
}


document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems, {
data: get_anime()
});
});


document.getElementById("add_link").addEventListener("click", function (){
var parent = this.parentNode;
var input_links = document.querySelectorAll("#input_link");
Expand All @@ -54,9 +74,13 @@ document.getElementById("add_link").addEventListener("click", function (){
parent.insertBefore(clon, this);
})

document.getElementById("absolute").addEventListener("click", function () {
var elem = document.getElementById("season");

if (this.checked == true) {
elem.disabled = true;
} else {
elem.disabled = false;
}
})

// document.addEventListener('DOMContentLoaded', function() {
// var elems = document.querySelectorAll('.fixed-action-btn');
// var instances = M.FloatingActionButton.init(elems, {});
// });
22 changes: 20 additions & 2 deletions config/app/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,22 @@ <h5>Aggiungi un Anime</h5>
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix dark">movie</i>
<input placeholder="Sword Art Online" id="title" name="title" type="text" class="validate" maxlength="300" autocomplete="off" required>
<input placeholder="Sword Art Online" id="title" name="title" type="text" class="validate autocomplete" maxlength="300" autocomplete="off" required>
<label for="title">Nome Anime</label>
<span class="helper-text dark" data-error="wrong" data-success="right">Helper text</span>
</div>
<div class="input-field col s6">
<div class="input-field col s4">
<i class="material-icons prefix dark">turned_in</i>
<input placeholder="1" id="season" name="season" type="text" class="validate" pattern="[0-9]+" autocomplete="off" required>
<label for="season">Stagione</label>
<span class="helper-text dark" data-error="wrong" data-success="right">Helper text</span>
</div>
<div class="input-check col s2">
<label>
<input type="checkbox" class="filled-in" id="absolute" name="absolute" value="true"/>
<span>Absolute</span>
</label>
</div>
</div>
<div id="input_link" class="row">
<div class="input-field col s12">
Expand Down Expand Up @@ -97,6 +103,11 @@ <h5>Aggiungi un Anime</h5>
<div class='header-anime'>
<div class="collapsible-header dark">
<i class="material-icons">movie</i>{{ info.title }}
{% if info.absolute %}

<span class="new badge" data-badge-caption="Absolute"></span>

{% endif %}
</div>
<form class="delete-btn" method="post" action="/delete_anime">
<button class="btn-floating-delete dark" onclick="return confirm('Sei sicuro di voler rimuovere \'{{ info.title }}\'?')" type="submit" name="delete_anime" value="{{ info.title }}">
Expand Down Expand Up @@ -137,5 +148,12 @@ <h5>Aggiungi un Anime</h5>
<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="static/js/materialize.min.js"></script>
<script type="text/javascript" src="static/js/my.js"></script>
<script>
window.onload = function (){
if ("{{ log }}" != "None") {
M.toast({ html: "{{ log }}" })
}
};
</script>
</body>
</html>
33 changes: 22 additions & 11 deletions config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

import animeworld as aw
import requests
import os
import re
import json
import os, re, json
from copy import deepcopy
import schedule
import time
import shutil
Expand Down Expand Up @@ -99,14 +98,14 @@ def job():
logging.warning(f"\n{divider}")

try:
logging.warning("🔎 Ricerca anime '{}' per l'episodio S{}E{}.".format(info["SonarrTitle"], info["season"], info["episode"]))
logging.warning("🔎 Ricerca anime '{}' per l'episodio S{}E{}.".format(info["SonarrTitle"], info["season"], info["rawEpisode"]))
anime = [aw.Anime(link=x) for x in info["AnimeWorldLinks"]]

logging.info("🔎 Ricerca degli episodi per '{}'.".format(info["SonarrTitle"]))
epsArr = [x.getEpisodes() for x in anime] # array di episodi da accorpare
episodi = fixEps(epsArr)

logging.info("⚙️ Verifica se l'episodio 𝐒{}𝐄{} è disponibile.".format(info["season"], info["episode"]))
logging.info("⚙️ Verifica se l'episodio 𝐒{}𝐄{} è disponibile.".format(info["season"], info["rawEpisode"]))
ep = None
for episodio in episodi:
if episodio.number == str(info["episode"]):
Expand All @@ -117,16 +116,16 @@ def job():
logging.info("✖️ L'episodio NON è ancora uscito.")

if ep is not None: # Se l'episodio è disponibile
logging.warning("⏳ Download episodio 𝐒{}𝐄{}.".format(info["season"], info["episode"]))
title = f'{info["SonarrTitle"]} - S{info["season"]}E{info["episode"]}'
logging.warning("⏳ Download episodio 𝐒{}𝐄{}.".format(info["season"], info["rawEpisode"]))
title = f'{info["SonarrTitle"]} - S{info["season"]}E{info["rawEpisode"]}'
if ep.number == str(info["episode"]):
fileLink = ep.links[0]
title = fileLink.sanitize(title) # Sanitizza il titolo
if fileLink.download(title):
logging.info("✔️ Dowload Completato.")

if SETTINGS["MoveEp"]:
logging.info("⏳ Spostamento episodio 𝐒{}𝐄{} in {}.".format(info["season"], info["episode"], info["path"]))
logging.info("⏳ Spostamento episodio 𝐒{}𝐄{} in {}.".format(info["season"], info["rawEpisode"], info["path"]))
if move_file(title, info["path"]):
logging.info("✔️ Episodio spostato.")

Expand Down Expand Up @@ -175,8 +174,9 @@ def fixEps(epsArr): # accorpa 2 o più serie di animeworld
continue # lo salta perchè sicuramente uno speciale

if re.search(r'^\d+-\d+$', ep.number) is not None: # Episodio Doppio
ep1 = ep # Duplica l'episodio da sitemare la gestione.....
ep2 = ep # Non mi piace
ep1 = deepcopy(ep) # Duplica l'episodio da sitemare la gestione.....
ep2 = deepcopy(ep) # Non mi piace


ep1.number = str(int(ep.number.split('-')[0]) + up)
ep2.number = str(int(ep.number.split('-')[1]) + up)
Expand All @@ -203,7 +203,17 @@ def converting(series):
for anime in series:
for row in table:
if row["title"] == anime["SonarrTitle"]:
if str(anime["season"]) in row["seasons"].keys():
if row["absolute"]:
tmp = int(anime["episode"])
anime["episode"] = int(anime["rawEpisode"])
anime["rawEpisode"] = tmp

anime["AnimeWorldLinks"] = list(row["seasons"]["absolute"])
res.append(anime)
break
elif str(anime["season"]) in row["seasons"].keys():
anime["rawEpisode"] = int(anime["episode"])

anime["AnimeWorldLinks"] = list(row["seasons"][str(anime["season"])])
res.append(anime)
break
Expand Down Expand Up @@ -268,6 +278,7 @@ def get_missing_episodes():
info["AnimeWorldLinks"] = [] # season 1 di sonarr corrisponde a più season di AnimeWorld
info["season"] = int(serie["seasonNumber"])
info["episode"] = int(serie["episodeNumber"])
info["rawEpisode"] = int(serie["absoluteEpisodeNumber"])
info["episodeTitle"] = serie["title"]
info["path"] = serie["series"]["path"]

Expand Down
Loading

0 comments on commit 8e62896

Please sign in to comment.