aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: bc554b5fe68701d8f29aab9c0c2440c42412a2c8 (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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#include "buffer.h"
#include "fileutils.h"
#include "transmission.h"
#include "fileutils.h"
#include "stringutils.h"
#include "rss.h"
#include "html.h"
#include "json.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <dirent.h>
#include <libgen.h>

#define NAME_MAX_LEN 250

static void usage(void) {
    fprintf(stderr, "usage: automedia COMMAND\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "COMMANDS\n");
    fprintf(stderr, "  add           Add media to track\n");
    fprintf(stderr, "  sync          Start syncing tracked media\n");
    fprintf(stderr, "  downloaded    List downloaded media\n");
    exit(1);
}

static void usage_add(void) {
    fprintf(stderr, "usage: automedia add <type> <url|filename> [--name name] [--start-after start_after]\n");
    fprintf(stderr, "OPTIONS\n");
    fprintf(stderr, "  type             The type should be either rss or html\n");
    fprintf(stderr, "  url              The url to the rss or html\n");
    fprintf(stderr, "  filename         The filename of an episode of an existing serie to start track. Currently only works with rss on https://nyaa.si\n");
    fprintf(stderr, "  --name           The display name to be used for the media. Optional for rss, in which case the name will be the rss TITLE, required for html. The name can't be longer than 250 characters\n");
    fprintf(stderr, "  --start-after    The sync should start downloading media after this item. This --start-after value should be the title of the episode/chapter (Optional, default is to start from the first item)\n");
    fprintf(stderr, "EXAMPLES\n");
    fprintf(stderr, "  automedia add rss 'https://nyaa.si/?page=rss&q=Tejina-senpai+1080p&c=0_0&f=0&u=HorribleSubs'\n");
    fprintf(stderr, "  automedia add html 'https://manganelo.com/manga/read_naruto_manga_online_free3' --name Naruto\n");
    fprintf(stderr, "  automedia add rss '[Erai-raws] Saiki Kusuo no Psi Nan - Kanketsu-hen - 01 [1080p][Multiple Subtitle].mkv'\n");
    exit(1);
}

static void usage_sync(void) {
    fprintf(stderr, "usage: automedia sync <download_dir>\n");
    fprintf(stderr, "OPTIONS\n");
    fprintf(stderr, "  download_dir    The path where media should be downloaded to\n");
    fprintf(stderr, "EXAMPLES\n");
    fprintf(stderr, "  automedia sync /home/adam/Downloads/automedia\n");
    exit(1);
}

static struct json_value_s* json_object_get_field_by_name(struct json_object_s *json_obj, const char *name) {
    struct json_object_element_s *obj_element = json_obj->start;
    while(obj_element) {
        if(strcmp(obj_element->name->string, name) == 0)
            return obj_element->value;
        obj_element = obj_element->next;
    }
    return NULL;
}

typedef void (*DownloadedListCallback)(const char *title, double timestamp, void *userdata);

static void data_file_get_downloaded(const char *dir_name, const char *data_filepath, int is_html, DownloadedListCallback callback, void *userdata) {
    char *file_data;
    long file_size;
    if(file_get_content(data_filepath, &file_data, &file_size) != 0) {
        fprintf(stderr, "Failed to read the content of file %s\n", data_filepath);
        return;
    }

    struct json_value_s *json_root = json_parse(file_data, file_size);
    if(!json_root) {
        fprintf(stderr, "Failed to parse file %s as json\n", data_filepath);
        goto cleanup;
    }

    struct json_object_s *json_root_obj = json_value_as_object(json_root);
    if(!json_root_obj) {
        fprintf(stderr, "File %s contains malformed json. Expected json root element to be an object\n", data_filepath);
        goto cleanup;
    }

    struct json_value_s *downloaded_json = json_object_get_field_by_name(json_root_obj, "downloaded");
    if(!downloaded_json) {
        fprintf(stderr, "File %s contains malformed json. Expected json to contain \"downloaded\"\n", data_filepath);
        goto cleanup;
    }

    struct json_array_s *downloaded_json_arr = json_value_as_array(downloaded_json);
    if(!downloaded_json_arr) {
        fprintf(stderr, "File %s contains malformed json. Expected \"downloaded\" to be an array\n", data_filepath);
        goto cleanup;
    }

    size_t dir_name_len = strlen(dir_name);

    struct json_array_element_s *downloaded_item = downloaded_json_arr->start;
    for(; downloaded_item; downloaded_item = downloaded_item->next) {
        struct json_object_s *downloaded_item_obj = json_value_as_object(downloaded_item->value);
        if(!downloaded_item_obj)
            continue;

        struct json_value_s *time_json = json_object_get_field_by_name(downloaded_item_obj, "time");
        if(!time_json || time_json->type != json_type_string)
            continue;
        struct json_string_s *time_json_str = json_value_as_string(time_json);
        
        struct json_value_s *title_json = json_object_get_field_by_name(downloaded_item_obj, "title");
        struct json_string_s *title_str = NULL;
        if(title_json && title_json->type == json_type_string)
            title_str = json_value_as_string(title_json);

        struct json_value_s *filename_json = json_object_get_field_by_name(downloaded_item_obj, "filename");
        struct json_string_s *filename_str = NULL;
        if(filename_json && filename_json->type == json_type_string)
            filename_str = json_value_as_string(filename_json);

        /* Filename limit is 256, so this should be safe... */
        char title[256];
        if(filename_str) {
            strcpy(title, filename_str->string);
        } else if(title_str) {
            if(is_html) {
                strcpy(title, dir_name);
                title[dir_name_len] = '/';
                strcpy(title + dir_name_len + 1, title_str->string);
            } else {
                strcpy(title, title_str->string);
            }
        } else {
            continue;
        }

        callback(title, atof(time_json_str->string), userdata);
    }

    cleanup:
    free(json_root);
    free(file_data);
}

typedef struct {
    char *title;
    double timestamp;
} DownloadedListData;

static void downloaded_list_callback(const char *title, double timestamp, void *userdata) {
    DownloadedListData list_data;
    list_data.title = strdup(title);
    list_data.timestamp = timestamp;

    Buffer *buffer = userdata;
    buffer_append(buffer, &list_data, sizeof(list_data));
}

static void get_downloaded_items(const char *tracked_dir, int is_html, void *userdata) {
    struct dirent *dir;
    DIR *d = opendir(tracked_dir);
    if(!d)
        return;

    char data_filepath[PATH_MAX] = {0};
    strcat(data_filepath, tracked_dir);
    strcat(data_filepath, "/");
    int data_filepath_length = strlen(data_filepath);

    while((dir = readdir(d)) != NULL) {
        /* We dont want hidden files (and . ..) */
        if(dir->d_name[0] == '.')
            continue;

        strcpy(data_filepath + data_filepath_length, dir->d_name);
        strcpy(data_filepath + data_filepath_length + strlen(dir->d_name), "/data");
        data_file_get_downloaded(dir->d_name, data_filepath, is_html, downloaded_list_callback, userdata);
    }

    closedir(d);
}

static int compare_downloaded_item(const void *a, const void *b) {
    const DownloadedListData *list_data_a = a;
    const DownloadedListData *list_data_b = b;
    return list_data_a->timestamp - list_data_b->timestamp;
}

static void command_add(int argc, char **argv, char *rss_config_dir, char *html_config_dir, char *program_dir) {
    if(argc < 2)
        usage_add();
    
    char *media_type = argv[0];
    char *media_url = argv[1];
    char *media_name = NULL;
    char *start_after = NULL;

    const char *option = NULL;
    for(int i = 2; i < argc; ++i) {
        char *arg = argv[i];
        if(strcmp(arg, "--name") == 0 || strcmp(arg, "--start-after") == 0) {
            if(option)
                usage_add();
            option = arg;
        } else {
            if(!option)
                usage_add();
            
            if(strcmp(option, "--name") == 0)
                media_name = arg;
            else if(strcmp(option, "--start-after") == 0)
                start_after = arg;
            else {
                fprintf(stderr, "Invalid option %s\n", option);
                usage_add();
            }

            option = NULL;
        }
    }

    if(media_name) {
        string_replace(media_name, '/', '_');
        media_name = strip(media_name);

        int media_name_len = strlen(media_name);
        if(media_name_len > NAME_MAX_LEN) {
            fprintf(stderr, "--name value can't be longer than %d characters\n", NAME_MAX_LEN);
            exit(1);
        }
    }

    if(start_after) {
        string_replace(start_after, '/', '_');
        start_after = strip(start_after);
    }

    media_url = strip(media_url);

    if(strcmp(media_type, "rss") == 0) {
        int res = create_directory_recursive(rss_config_dir);
        if(res != 0) {
            fprintf(stderr, "Failed to create %s, error: %s\n", rss_config_dir, strerror(res));
            exit(1);
        }

        if(add_rss(media_name, media_url, rss_config_dir, start_after) != 0)
            exit(1);
    } else if(strcmp(media_type, "html") == 0) {
        int res = create_directory_recursive(html_config_dir);
        if(res != 0) {
            fprintf(stderr, "Failed to create %s, error: %s\n", html_config_dir, strerror(res));
            exit(1);
        }

        if(add_html(media_name, media_url, html_config_dir, program_dir, start_after) != 0)
            exit(1);
    } else {
        fprintf(stderr, "type should be either rss or html\n");
        usage_add();
    }
}

static void command_sync(int argc, char **argv) {
    if(argc < 2)
        usage_sync();

    (void)argv;
}

static void command_downloaded(const char *rss_config_dir, const char *html_config_dir) {
    char rss_tracked_dir[PATH_MAX];
    strcpy(rss_tracked_dir, rss_config_dir);
    strcat(rss_tracked_dir, "/tracked");

    char html_tracked_dir[PATH_MAX];
    strcpy(html_tracked_dir, html_config_dir);
    strcat(html_tracked_dir, "/tracked");

    Buffer downloaded_items;
    buffer_init(&downloaded_items);

    get_downloaded_items(rss_tracked_dir, 0, &downloaded_items);
    get_downloaded_items(html_tracked_dir, 1, &downloaded_items);

    qsort(downloaded_items.data, buffer_get_size(&downloaded_items, sizeof(DownloadedListData)), sizeof(DownloadedListData), compare_downloaded_item);
    DownloadedListData *list_it = buffer_begin(&downloaded_items);
    DownloadedListData *list_end = buffer_end(&downloaded_items);
    for(; list_it != list_end; ++list_it) {
        puts(list_it->title);
        free(list_it->title);
    }

    buffer_deinit(&downloaded_items);
}
/*
static void torrent_list_callback(int id, float percentage_finished, const char *name, void *userdata) {
    (void)userdata;
    fprintf(stderr, "id: |%d|, done: |%g|, name: |%s|\n", id, percentage_finished, name);
}
*/
int main(int argc, char **argv) {
    if(argc < 2)
        usage();

    const char *home_dir = get_home_dir();

    char rss_config_dir[PATH_MAX];
    strcpy(rss_config_dir, home_dir);
    strcat(rss_config_dir, "/.config/automedia/rss");

    char html_config_dir[PATH_MAX];
    strcpy(html_config_dir, home_dir);
    strcat(html_config_dir, "/.config/automedia/html");

    const char *command = argv[1];
    if(strcmp(command, "add") == 0) {
        command_add(argc - 2, argv + 2, rss_config_dir, html_config_dir, dirname(argv[0]));
    } else if(strcmp(command, "sync") == 0) {
        command_sync(argc - 2, argv + 2);
    } else if(strcmp(command, "downloaded") == 0) {
        command_downloaded(rss_config_dir, html_config_dir);
    } else {
        fprintf(stderr, "Error: Invalid command %s\n", command);
        usage();
    }

    /*transmission_get_all_torrents(torrent_list_callback, NULL);
    printf("is transmission daemon running? %s\n", transmission_is_daemon_running() == 0 ? "yes" : "no");*/

    return 0;
}