aboutsummaryrefslogtreecommitdiff
path: root/open_media.py
blob: 0e3fa99c46a8aa567567aa521cda4f61dc9b5f72 (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
#!/usr/bin/env python3

import os
import sys
import subprocess

script_dir = os.path.dirname(os.path.realpath(sys.argv[0]))

def run_dmenu(input):
    process = subprocess.Popen(["dmenu", "-l", "15", "-i", "-p", "Select media"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, stderr = process.communicate(input.encode())
    if process.returncode == 0:
        return stdout
    elif process.returncode != 1:
        print("Failed to launch dmenu, error: {}".format(stderr))
    return None

def add_seen(seen_filepath, media_name, seen_list):
    if media_name in seen_list:
        return
    with open(seen_filepath, "a") as seen_file:
        seen_file.write(media_name + "\n")

def sort_images(filename):
    idx = filename.find(".")
    if idx != -1:
        return int(filename[0:idx])
    return 0

def get_downloaded_list():
    process = subprocess.Popen(["automedia", "downloaded"], stdout=subprocess.PIPE)
    stdout, stderr = process.communicate()
    if process.returncode == 0:
        return stdout.decode().splitlines()
    else:
        print("Failed to list downloaded items, error: {}".format(stderr))
    return []

def get_manga_chapters_in_dir(manga_dir):
    files = []
    for filename in os.listdir(manga_dir):
        full_path = os.path.join(manga_dir, filename)
        if os.path.isdir(full_path) and not os.path.exists(os.path.join(full_path, ".in_progress")):
            files.append(full_path)
    return files

def get_files_in_download_dir(download_dir):
    files_in_media_path = []
    for filename in os.listdir(download_dir):
        full_path = os.path.join(download_dir, filename)
        if os.path.isdir(full_path):
            files_in_media_path.extend(get_manga_chapters_in_dir(full_path))
        if os.path.isfile(full_path):
            files_in_media_path.append(full_path)
    return files_in_media_path

def main():
    if len(sys.argv) < 2:
        print("usage: open_media.py <download_dir>")
        print("example: open_media.sh /home/user/Downloads/automedia")
        exit(1)

    download_dir = sys.argv[1]
    if not os.path.isdir(download_dir):
        print("No such directory: " % str(download_dir))
        exit(2)

    files_in_media_path = get_files_in_download_dir(download_dir)

    downloaded_list = get_downloaded_list()
    filtered_downloaded_list = []
    for item in downloaded_list:
        media_path = os.path.join(download_dir, item)
        if media_path in files_in_media_path:
            filtered_downloaded_list.append(item)
    
    seen_filepath = os.path.expanduser("~/.config/automedia/seen")
    seen_list = []
    try:
        with open(seen_filepath, "r") as seen_file:
            seen_list = seen_file.read().splitlines()
    except OSError as e:
        print("Failed to open {}, reason: {}".format(seen_filepath, str(e)))

    for seen in seen_list:
        for i, downloaded in enumerate(filtered_downloaded_list):
            if seen == downloaded:
                filtered_downloaded_list[i] = "✓ {}".format(downloaded)

    selected_media = run_dmenu("\n".join(filtered_downloaded_list[::-1]))
    if not selected_media:
        exit(0)
    selected_media = selected_media.decode().replace("✓ ", "").rstrip()
    
    media_path = os.path.join(download_dir, selected_media)
    if os.path.isdir(media_path):
        add_seen(seen_filepath, selected_media, seen_list)
        files = []
        for filename in os.listdir(media_path):
            if filename not in (".finished", ".session_id"):
                files.append(filename)

        files = sorted(files, key=sort_images)
        process = subprocess.Popen(["sxiv", "-a", "-i"], stdin=subprocess.PIPE)
        files_fullpath = []
        for filename in files:
            files_fullpath.append(os.path.join(media_path, filename))
        process.communicate("\n".join(files_fullpath).encode())
    elif os.path.isfile(media_path):
        add_seen(seen_filepath, selected_media, seen_list)
        subprocess.Popen(["mpv", "--", media_path])

main()