#!/usr/bin/python
from re import search, IGNORECASE
from time import monotonic
from flask import Flask, render_template, escape, request
from sys import argv, path
from os import getpid, getenv
from psutil import Process
from urllib.parse import quote
from datetime import datetime
from locale import setlocale, LC_ALL
path.append(".")
from travnik import glob, Type
setlocale(LC_ALL, "")
app = Flask("travnik")
zagon = datetime.now()
def mno(quantity, types):
if quantity % 100 == 1:
return types[1]
if quantity % 100 == 2:
return types[2]
if quantity % 100 == 3:
return types[3]
return types[0]
@app.route("/")
def index():
result = []
for hash, torrent in torrents.items():
if not request.args.get("regex"):
break
if torrent.matches(request.args.get("regex")):
try:
decodedname = torrent.dict.get(b'info').get(b'name').decode()
except UnicodeDecodeError:
decodedname = torrent.dict.get(b'info').get(b'name').decode("iso-8859-2")
this = {"tree": torrent.matching_files(request.args.get("regex") if sum(1 for name, size in torrent.paths()) > 10 else "", True), "files": sum(1 for name, size in torrent.paths()), "found": datetime.fromtimestamp(torrent.dict.get(b'creation date')), "size": sum(size for name, size in torrent.paths()), "name": decodedname, "magnet": "magnet:?dn=" + quote(torrent.dict.get(b'info').get(b'name'))
+ (("&xt=urn:btih:" + torrent.sha1.hex()) if torrent.type == Type.V1 or torrent.type == Type.HYBRID else "") + (("&xt=urn:btmh:1220" + torrent.sha256.hex()) if torrent.type == Type.V2 or torrent.type == Type.HYBRID else "")}
result.append(this)
result = sorted(result, reverse=(request.args.get("order") == "padajoče"), key=lambda x:x["found"].timestamp() if request.args.get("sort") == "datumu" else x["files" if request.args.get("sort") == "datotekah" else "size" if request.args.get("sort") == "velikosti" else "crash"])
return render_template("index.html", found_torrents=result, lentorrents=len(result))
if __name__ == "__main__":
print("zaganjam travnik", argv[0], "... zagon traja dolgo časa (~5 min za ~40k torrentov. za delovanje je potrebnih ~300 MiB RAM RES za ~40k torrentov. sharding je WIP.")
start = monotonic()
torrents = glob(getenv("TORRENTS") if getenv("TORRENTS") else ".")
app.jinja_env.globals.update(mno=mno, zagontekst=zagon.strftime("%c"), torrentov=len(torrents), rammib=round(Process(getpid()).memory_info().rss/(1024*1024)), roundstartuptime=round(monotonic()-start))
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
app.run(host="::", port=8080, debug=True)