summaryrefslogtreecommitdiff
path: root/utab/__main__.py
blob: 6dddd0b0290b48dd031865280b66f4be8f3b519f (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
from flask import Flask, Response, request, redirect, abort
from appdirs import user_data_dir
from pathlib import Path
import urllib
from mimetypes import guess_type
import sys
import yaml
import csv
from .pyfav import get_favicon_url
from .rendering import *

app = Flask(__name__)

# locate page template at e.g. $XDG_CONFIG_HOME/utab/index.html
# and sites json file at utab/sites.json
data_dir = user_data_dir(appname="utab")
template_fp = Path(data_dir) / "index.html"
site_form_fp = Path(data_dir) / "site.html"
css_dir = Path(data_dir) / "css"
icons_dir = Path(data_dir) / "icons"
try:
    with open(template_fp) as f:
        template = f.read()
        f.close()
    with open(site_form_fp) as f:
        site_form = f.read()
        f.close()
except FileNotFoundError:
    print("One or more template files are not found.")
    sys.exit(1)


sites_fp = Path(data_dir) / "sites.csv"
config_fp = Path(data_dir) / "config.yml"
with open(config_fp) as f:
    config = yaml.load(f.read(), Loader=yaml.FullLoader)
    f.close()

sites_grid_dimensions = {"columns": config["columns"], "rows": config["rows"]}


def read_sites():
    with open(sites_fp) as f:
        sites = list(csv.reader(f))
        f.close()
        return sites


def write_sites(data):
    with open(sites_fp, "w") as f:
        csv.writer(f).writerows(data)
        f.close()


def append_site(site):
    with open(sites_fp, "a") as f:
        csv.writer(f).writerow(site)
        f.close()


@app.route("/")
def index():
    # render sites in a grid.
    # each cell links to /go/<escaped_url>
    return render_page(
        template,
        site_heading="Top Sites",
        sites=render_sites(read_sites(), **sites_grid_dimensions),
    )


@app.route("/go/<path:url>")
def visit_site(url):
    # log this visit, then redirect to the unescaped url
    sites = read_sites()
    for i, s in enumerate(sites):
        if s[URL] == url:
            sites[i][VISITS] = str(int(sites[i][VISITS]) + 1)
            write_sites(sites)
            return redirect(url, 302)
    return abort(404)


@app.route("/new")
def add_site():
    # /new => a page asking for url, title, etc.
    # /new?url=<escaped_url>&title=<title>&... => add this site if it DNE, else abort
    url, title, favicon = (
        request.args.get("url"),
        request.args.get("title"),
        request.args.get("favicon"),
    )
    if url:
        sites = read_sites()
        for s in sites:
            if s[URL] == url:
                return "A site with the same URL already exists.", 403
        # now we have ensured there isn't such URL in sites
        if favicon:
            favicon_src = favicon
        else:
            # get its favicon url
            # fetch favicon url from the root page (w/o path):
            url_split = urllib.parse.urlsplit(url)
            root = url_split.scheme + "://" + url_split.netloc
            favicon_src = get_favicon_url(root)

        append_site([url, title, favicon_src, 0])
        return redirect("/", 302)
    else:  # no request params; let user fill form
        return render_page(
            site_form,
            site_heading="Add site",
            url="https://",
            url_esc="",
            title="",
            favicon_src="",
            favicon_placeholder="Leave blank to auto-retrieve favicon. Base64 is allowed.",
            delete_button_visibility="hidden",
            action="new",
        )


@app.route("/edit/<path:url>")
def edit_site(url):
    # /edit/ => /edit
    # /edit/<escaped_url> => form with original data pre-filled for user to modify
    # /edit/<escaped_url>?url=<escaped_new_url>&... => edit this site in database
    if not url:
        return redirect("/edit", 301)
    sites = read_sites()
    for i, s in enumerate(sites):
        if s[URL] == url:
            new_url, new_title, new_favicon = (
                request.args.get("url"),
                request.args.get("title"),
                request.args.get("favicon"),
            )
            if not new_url:
                return render_page(
                    site_form,
                    site_heading="Edit site",
                    url=s[URL],
                    url_esc=urllib.parse.quote(s[URL], safe=""),
                    title=s[TITLE],
                    favicon_src=s[FAVICON],
                    favicon_placeholder="Base64 is allowed.",
                    delete_button_visibility="visible",
                    action="edit/" + urllib.parse.quote(s[URL], safe=""),
                )
            sites[i][URL] = new_url
            sites[i][TITLE] = new_title
            sites[i][FAVICON] = new_favicon
            write_sites(sites)
            return redirect("/", 302)
    return abort(404)


@app.route("/edit")
def select_site_to_edit():
    # render sites in a grid.
    # each cell links to /edit/<escaped_url>
    return render_page(
        template,
        site_heading="Select site to edit",
        sites=render_sites(read_sites(), action="edit", **sites_grid_dimensions),
    )


@app.route("/delete/<path:url>")
def delete_site(url):
    sites = read_sites()
    for i, s in enumerate(sites):
        if s[URL] == url:
            sites = sites[:i] + sites[i + 1 :]
            write_sites(sites)
            return redirect("/", 302)
    return "No site with such URL exists", 403


@app.route("/css/<string:filename>")
def serve_css(filename):
    # serve static CSS because browsers forbid file:// scheme
    try:
        with open(css_dir / filename) as f:
            resp = Response(f.read(), 200, {"Content-Type": "text/css"})
            f.close()
            return resp
    except FileNotFoundError:
        return abort(404)
    except:
        return abort(500)


@app.route("/icons/<string:filename>")
def serve_icon(filename):
    try:
        fp = icons_dir / filename
        with open(fp, "rb") as f:
            resp = Response(f.read(), 200, {"Content-Type": guess_type(fp)[0]})
            f.close()
            return resp
    except FileNotFoundError:
        return abort(404)
    except:
        return abort(500)


# run on localhost only
app.run("127.0.0.1", 64366)