main.py (view raw)
1#!/usr/local/bin/python3
2import os, csv, json
3from datetime import datetime
4from flask import Flask, request, render_template
5
6INPUT_PATH = os.path.join("tntvillage-release-dump", "tntvillage-release-dump.csv")
7CSV_SEPARATOR = ","
8HEADER = [ "DATA", "HASH", "TOPIC", "POST", "AUTORE", "TITOLO", "DESCRIZIONE", "DIMENSIONE", "CATEGORIA" ]
9TABLE_HEADER = [ "DATA", "CATEGORIA", "TITOLO", "DESCRIZIONE", "AUTORE", "DIMENSIONE", "HASH" ]
10CATEGORIE = {
11 1: "Film TV e programmi",
12 2: "Musica",
13 3: "E Books",
14 4: "Film",
15 6: "Linux",
16 7: "Anime",
17 8: "Cartoni",
18 9: "Macintosh",
19 10: "Windows Software",
20 11: "Pc Game",
21 12: "Playstation",
22 13: "Students Releases",
23 14: "Documentari",
24 21: "Video Musicali",
25 22: "Sport",
26 23: "Teatro",
27 24: "Wrestling",
28 25: "Varie",
29 26: "Xbox",
30 27: "Immagini sfondi",
31 28: "Altri Giochi",
32 29: "Serie TV",
33 30: "Fumetteria",
34 31: "Trash",
35 32: "Nintendo",
36 34: "A Book",
37 35: "Podcast",
38 36: "Edicola",
39 37: "Mobile"
40}
41MAGNET_STR = '<button onclick=\"location.href=\'magnet:?xt=urn:btih:{}\'\">m</button>'
42
43def handle_content(content: str):
44 return { x: content[idx] for idx, x in enumerate(HEADER) }
45
46def search_keyword(content, keyword: str, category=0):
47 results = [ x for x in content if keyword.lower() in x['TITOLO'].lower()]
48 if category == 0:
49 return results
50 return [ x for x in results if category == x['CATEGORIA']]
51
52def get_last_torrents(content, page=1, amt=50):
53 tmp = sorted(content, key=lambda x:x['DATA'])
54 tmp_length = len(content)
55
56 start_from = tmp_length - (amt * page)
57 end_with = tmp_length
58 return tmp[start_from:end_with]
59
60def load_content(input_path=INPUT_PATH):
61 with open(input_path, "r", encoding="utf-8") as in_file:
62 csv_iterator = csv.reader(in_file, quotechar='"', delimiter=',', quoting=csv.QUOTE_NONNUMERIC, skipinitialspace=True)
63 next(csv_iterator)
64 return [ handle_content(x) for x in csv_iterator ]
65
66def sizeof_fmt(num, suffix="B"):
67 for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
68 if abs(num) < 1024.0:
69 return f"{num:3.1f}{unit}{suffix}"
70 num /= 1024.0
71 return f"{num:.1f}Yi{suffix}"
72
73def parse_values(result):
74 tmp = result.copy()
75 tmp['DATA'] = datetime.strptime(tmp['DATA'], "%Y-%m-%dT%H:%M:%S").strftime("%d/%m/%Y")
76 tmp['CATEGORIA'] = CATEGORIE[int(tmp['CATEGORIA'])]
77 tmp['HASH'] = MAGNET_STR.format(tmp['HASH'])
78 tmp['DIMENSIONE'] = sizeof_fmt(tmp['DIMENSIONE'])
79 tmp['DESCRIZIONE'] = f"<span title='Autore: {tmp['AUTORE']}'>{tmp['DESCRIZIONE']}</span>"
80 return tmp
81
82def format_results(results, headers=HEADER):
83 print(len(results))
84 contents = [parse_values(x) for x in results]
85 return [[result[header] for header in headers] for result in contents]
86
87def get_args(args):
88 keywords = args.get("keywords") or ""
89 category = args.get("category") or 0
90 page = args.get("page") or 1
91 return keywords, category, page
92
93content = load_content()
94app = Flask(__name__)
95
96@app.route('/api/header')
97def route_api_header():
98 return json.dumps(HEADER)
99
100@app.route('/api')
101def route_api():
102 keywords, category, page = get_args(request.args)
103 results = search_keyword(content, keywords, int(category))
104 results = get_last_torrents(results, page=int(page))
105 return json.dumps(results)
106
107@app.route('/')
108def route_main():
109 keywords, category, page = get_args(request.args)
110 results = search_keyword(content, keywords, int(category))
111 results = get_last_torrents(results, page=int(page))
112 results = format_results(results, headers=TABLE_HEADER)
113 return render_template("index.html", headers=TABLE_HEADER, content=results, categories=CATEGORIE.items(), page=page)
114
115if __name__ == '__main__':
116 app.run()