-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtorrents-get
executable file
·149 lines (114 loc) · 5.27 KB
/
torrents-get
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/usr/bin/python3
import time
from sys import argv
import os
import re
import requests
import urllib.parse
import subprocess
import bs4
import logging
logger = logging.getLogger(__name__)
to_do_list = [] # (when, showtuple)
def enqueue_magnet_link(magnet_link):
assert magnet_link.startswith("magnet:"), magnet_link
result = subprocess.run(["/usr/bin/deluge-console", "add %s" % magnet_link], stdout=subprocess.DEVNULL, timeout=10, check=True)
def search(show, season, episode):
urlformat = "https://thepiratebay.org/search/%s/0/7/205"
search_phrase = "%s S%02dE%02d" % (show, season, episode)
url = urlformat % (urllib.parse.quote(search_phrase),)
r = requests.get(url)
if "No hits. Try adding an asterisk in you search phrase." in r.text:
return
if "Database maintenance, please check back" in r.text:
logger.debug("Rescheduling %s %s %s for later. %s", show, season, episode, url)
to_do_list.append((time.time() + (10*60), (show, season, episode)))
return
soup = bs4.BeautifulSoup(r.text, "lxml", from_encoding="UTF-8")
table = soup.find("table", id="searchResult")
if not table:
logger.error("Didn't find a table in result. %r", r.text)
return
for tr in table.find_all("tr", recursive=False):
tds = tr.find_all("td")
if not tds:
logger.warn("Found no tds in tr %r", tr)
continue
tdcategory, tdbody, tdseeder, tdleecher = tds
if int(tdseeder.string) < 50:
logger.debug("Hoping for %s %s %s but only %s seeders.", show, season, episode, tdseeder.string)
continue
if not tdbody.find_all("img", alt=("VIP", "Trusted", "Helper")):
logger.debug("Skipping entry by an untrusted joe. %s", tdbody)
continue
r = ".{0,3}".join(map(str, show.split())) + r".{0,3}(?:[12]\d\d\d\b.{0,3})?" + ".{0,3}".join(map(str, [season, episode])) + ".{0,45}$"
if not re.match(r, tdbody.div.a.string, re.I):
logger.debug("Search result %s too loose match for %s.", tdbody.div.a.string, r,)
continue
got.add(search_phrase)
logger.info("Enqueueing %s %s %s", show, season, episode)
enqueue_magnet_link(tdbody.find("a", recursive=False)["href"])
return
def next_ep_this_season(show, season, ep):
return (show, season, ep+1)
def next_ep_next_season(show, season, ep):
return (show,season+1, 1)
got = set()
def discover(root):
# discover what we have on disk
have = set()
want = set()
for dirpath, dirnames, filenames in os.walk(root):
for filename in filenames:
match = re.match(r"^(.*?) \(s(\d\d)e(\d\d)-(\d\d)\)", filename)
if match:
have.add((match.group(1), int(match.group(2)), int(match.group(3))))
want.add(next_ep_this_season(match.group(1), int(match.group(2)), int(match.group(4))))
want.add(next_ep_next_season(match.group(1), int(match.group(2)), int(match.group(4))))
else:
match = re.match(r"^(.*?) \(s(\d\d)e(\d\d)\)", filename)
if match:
have.add((match.group(1), int(match.group(2)), int(match.group(3))))
want.add(next_ep_this_season(match.group(1), int(match.group(2)), int(match.group(3))))
want.add(next_ep_next_season(match.group(1), int(match.group(2)), int(match.group(3))))
else:
pass
# discover what we are already downloading
p = subprocess.Popen(["/usr/bin/deluge-console", "info"], stdout=subprocess.PIPE)
for line in p.stdout:
line = line.decode("UTF-8")
if not line.startswith("Name: "):
continue
for i in want:
if re.search(".{1,3}".join(map(str, tuple(i[0].split())+i[1:])), line, re.I):
#print "# want", i, "but I think I'm already downloading", line,
have.add(i)
old = set()
for showname, seriesnumber, episodenumber in want:
if len([1 for h in have if h[0] == showname and h > (showname, seriesnumber, episodenumber)]) > 3:
old.add((showname, seriesnumber, episodenumber))
wanted = want - have
return wanted - old
def process_wanted(wanted):
for i, (name, season, episode) in enumerate(wanted):
to_do_list.append((time.time() + (i*20), (name, season, episode)))
start = time.time()
while to_do_list and time.time() < (start + 60*60*8):
to_do_list.sort()
while to_do_list and to_do_list[0][0] < time.time():
when, nse = to_do_list.pop(0)
search(nse[0], nse[1], nse[2])
time.sleep(5)
if got and "dmsid" in os.environ:
requests.get("http://dms.chad.org/switch/ping/{}?note=got%20".format(os.environ["dmsid"]) + ",%20".join(urllib.parse.quote("%s (s%02de%02d)" % (n, s, e)) for n, s, e in sorted(got)))
if __name__ == "__main__":
logging.basicConfig(level=logging.ERROR)
logger.setLevel(logging.DEBUG)
if len(argv) == 2:
wanted = discover(argv[1])
elif len(argv) == 5:
root = argv[1]
wanted = { (argv[2], int(argv[3]), int(argv[4]),) }
else:
raise ValueError("expected params, either of\n dir\n dir showname seasonnumber episodenumber")
process_wanted(wanted)