summarylogtreecommitdiffstats
path: root/transmission-dlagent
blob: 2dfd129c89e13b231edb3ffa9cd8b469eff4ba00 (plain)
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#    transmission-dlagent
#
#    ----------------------------------------------------------------------
#    Copyright © 2022, 2023  Pellegrino Prevete
#
#    All rights reserved
#    ----------------------------------------------------------------------
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

from argparse import ArgumentParser
from os import getcwd
from os.path import basename
from os.path import join as path_join
from shutil import move as mv
from shutil import Error as MoveError
from subprocess import CalledProcessError, Popen, check_output, run

description = "Parse magnet link in makepkg format for Transmission"
version = 0.1

def makepkg_to_magnet(link):
    link = link.replace("://", ":?")
    path_marker = "#path="
    path = ""
    if path_marker in link:
        link, path = link.split(path_marker)
    return link, path

def magnet_makepkg(link, output_path, download_dir=getcwd()):
    output_file = output_path.replace(".part", "")
    magnet_link, torrent_path = makepkg_to_magnet(link)
    torrent_output_path = path_join(download_dir, torrent_path)
    output_path = path_join(download_dir, output_file)

    btt_cmd = ["/usr/bin/transmission-cli",
               f"{magnet_link}",
               f"--download-dir={download_dir}",
               "--portmap",
               f"--finish /usr/bin/transmission-quit",
               "|| echo 0"]    

    try:
        btt_out = check_output(btt_cmd)

    except CalledProcessError as err:
        if f"Failed opening torrent file `{magnet_link}" in str(err.stderr):
            print(f"Error in the magnet link '{magnet_link}'")
        else:
            if err.stderr:
                error = err.stderr.decode("utf-8")
                error = error.split("\n")
                for line in error:
                    print(line)

    try:
        mv(torrent_output_path, output_path)
    except MoveError as e:
        print(e)
        return e

def get_args():
    parser = ArgumentParser(description=description)
    version = {'args': ['-V', '--version'],
               'kwargs': {'dest': 'version',
                          'action': 'store_true',
                          'default': False,
                          'help': 'print version'}}
    magnet_link = {'args': ['magnet_link'],
                   'kwargs': {'nargs': '+',
                              'action': 'store',
                              'help': "magnet link in makepkg format"}}

    output_file = {'args': ['output_file'],
                   'kwargs': {'nargs': 1,
                              'action': 'store',
                              'default': [""],
                              'help': "output file"}}
    download_dir = {'args': ['--download-dir'],
                    'kwargs': {'nargs': 1,
                               'action': 'store',
                               'default': [getcwd()],
                               'help': "download directory"}}

    args = [version,
            magnet_link,
            output_file,
            download_dir]

    for arg in args:
        parser.add_argument(*arg['args'],
                            **arg['kwargs'])

    return parser, parser.parse_args()


def main():
    parser, args = get_args()

    if args.version:
        print(version)
        exit()

    return magnet_makepkg(args.magnet_link[0],
                          args.output_file[0],
                          download_dir=args.download_dir[0])

if __name__ == "__main__":
    main()