forked from fach/NZB-Sorter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnzb_sorter.py
executable file
·59 lines (48 loc) · 1.64 KB
/
nzb_sorter.py
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
#!/usr/bin/env python2
import xml.etree.ElementTree as ET
import sys
def get_tag_uri(element):
if element.tag[0] == "{":
uri = element.tag[1:].partition("}")[0]
else:
uri = None
return uri
def main():
# Take in nzb file as first argument
tree = ET.parse(sys.argv[1])
# Get root of XML ElementTree
root = tree.getroot()
# Try to find the URI associated with the namespace
try:
uri = get_tag_uri(root[0])
except:
print "Whoops, it looks like there are no files in this nzb."
sys.exit(-1)
# Set namespace to null so we get a properly formatted xml file on output
ET.register_namespace('', uri)
# Sort root by subject into new list
sorted_list = sorted(root, key=lambda child: child.attrib['subject'])
# Move things around so that *rar comes before *r00
rar_index = -1
r00_index = -1
# Find the indices of rar and r00
for index, child in enumerate(sorted_list):
if ".rar" in child.attrib['subject']:
rar_index = index
if ".r00" in child.attrib['subject']:
r00_index = index
# If we found both, move rar infront of r00
if rar_index >= 0 and r00_index >= 0:
rar_element = sorted_list[rar_index]
sorted_list.remove(rar_element)
sorted_list.insert(r00_index, rar_element)
# Remove all child elements from the root and add them back in order
for child in sorted_list:
root.remove(child)
root.append(child)
# Rebuild element tree
tree = ET.ElementTree(root)
# Output the new sorted nzb
tree.write(sys.argv[1])
if __name__ == "__main__":
main()