summaryrefslogtreecommitdiff
path: root/search.php
blob: b57c1f333faf1b29544d66b5a42fd9f7ef1b8580 (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
<?php

function getConfig()
{
    $config = false;

    if (!is_readable("config.ini")) {
        throw new Exception('File config.ini does not exist');
    }
    if (!$config = parse_ini_file("config.ini")) {
        throw new Exception('Could not parse ini file');
    }
    if (!isset($config["url"])) {
        throw new Exception('`url` not found in ini file');
    }
    if (!isset($config["command"])) {
        throw new Exception('`command` not found in ini file');
    }

    // Set default page size if it's not in the config
    if (!isset($config["pagesize"])) {
        $config["pagesize"] = 3;
    } elseif (!is_int((int)$config["pagesize"]) || $config["pagesize"] < 1) {
        throw new Exception('Page size ' . $config["pagesize"]  . ' not valid in config');
    }
    // hash the password
    if (isset($config['password'])) {
        $config['hash'] = hash("sha256", $config['password']);
    }
    return $config;
}

function getJsonFromUrl($config)
{
    $curl = curl_init($config["url"] . "?format=json");
    if (isset($config["hash"])) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: password=" . $config["hash"]));
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $output = json_decode(curl_exec($curl));
    curl_close($curl);
    return $output;
}

function getHelp($config)
{
    return "Usage: !" . $config["command"] . " [query] #[page] | "
        . "e.g: !" . $config["command"] . " intense | "
        . "!" . $config["command"] . " intense marcus | "
        . "!" . $config["command"] . " intense marcus #2 (returns the second page of results)";
}

function getVersion($config)
{
    return $config["command"] . " v" . "2.0";
}

function output($pieces, $glue = " - ")
{
    if (!is_array($pieces)) {
        echo $pieces . "\n";
    } else {
        echo implode($glue, $pieces) . "\n";
    }

    exit;
}

function read_stdin()
{
    $fr = fopen("php://stdin", "r");
    $input = fgets($fr, 128);
    $input = rtrim($input);
    fclose($fr);
    return $input;
}

function getPaginationBounds($page, $pagesize)
{
    return [
        "start" => ($page - 1) * $pagesize,
        "end" => (($page - 1) * $pagesize) + ($pagesize - 1)
    ];
}

function getFormattedArguments($config)
{
    $args = explode(" ", read_stdin());

    if (!isset($args) || empty($args)) {
        throw new Exception("No arguments found");
    }
    // Loop the raw arguments and create our formated argument array
    $formatArgs = [];
    $formatArgs["search"] = [];
    foreach ($args as $arg) {
        // Switch to check for special arguments
        // output should exit but incase it errors we double break
        switch ($arg) {
            case "--version":
            case "-v": // Flow through
                output(getVersion($config));
                break 2;
            case "--help":
            case "-h": // Flow through
                output(getHelp($config));
                break 2;
        }

        // Check to see if we have a page specified
        if (strpos($arg, "#") === 0) {
            $formatArgs["page"] = substr($arg, 1);
            continue;
        }

        // If we reach here, then the argument is a search term
        $formatArgs["search"][] = $arg;
    }

    // If we reach this point we must have at least one search term
    if (empty($formatArgs["search"])) {
        throw new Exception("Please Enter a search term");
    }

    if (!isset($formatArgs["page"])) {
        $formatArgs["page"] = 1;
    } elseif (!is_int((int)$formatArgs["page"]) || $formatArgs["page"] < 1) {
        throw new Exception("Page number `" . $formatArgs["page"] . "` is not valid");
    }

    return $formatArgs;
}

try {
    $config = getConfig();
    $content = getJsonFromUrl($config);
    $arguments = getFormattedArguments($config);

    // parse the arguments
    $page = $arguments["page"];

    $out = [];

    // Really slow search
    $results = [];
    foreach ($content as $upload) {
        $match = false;
        foreach ($arguments["search"] as $arg) {
            if (!is_null($arg) && stripos($upload->filename, $arg) === false) {
                $match = false;
                break;
            }
            $match = true;
        }
        if ($match) {
            $results[] = $config["url"] . "/" . rawurlencode($upload->filename);
        }
    }

    if (empty($results)) {
        output("No results found");
    }

    $count = count($results);
    $i = 0;
    $bounds = getPaginationBounds($page, $config["pagesize"]);

    if ($bounds["start"] > ($count - 1)) {
        throw new Exception("No results for this page");
    }

    foreach ($results as $result) {
        if ($i < $bounds["start"] || $i > $bounds["end"]) {
            $i++;
            continue;
        }
        $out[] = $i + 1 . ": " . $result;
        $i++;
    }

    if ($count > 3) {
        $out[] = "results (" . $count . ")";
    }

    output($out, " - ");

} catch (Exception $e) {
    echo $e->getMessage() . "\n";
    die();
}