-
Notifications
You must be signed in to change notification settings - Fork 1
/
tagapp.py
executable file
·203 lines (178 loc) · 6.15 KB
/
tagapp.py
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
#!/usr/bin/python
# -*- coding: utf8 -*-
################################################################################
##
## Copyright (C) 2012 Typhos
##
## This Source Code Form is subject to the terms of the Mozilla Public
## License, v. 2.0. If a copy of the MPL was not distributed with this
## file, You can obtain one at http://mozilla.org/MPL/2.0/.
##
################################################################################
import argparse
import functools
import json
import os
import os.path
import random
import string
import StringIO
import flask
from flask import request
import yaml
import bplib
import bplib.objects
import bpgen
files = {} # subreddit -> Subreddit
all_tags = [] # sorted set
css_cache = {} # subreddit -> str
def filter_file(file):
file.se = {}
for (name, emote) in file.emotes.items():
# Simple hack to essentially just remove +drop emotes, since all of
# r/mlp's are
if subreddit != "mylittlepony" and name in files["mylittlepony"].emotes:
continue
if hasattr(emote, "image_url"):
info = (emote.image_url, emote.offset[1], emote.offset[0], emote.size[0], emote.size[1])
else:
info = (-1, -1, -1, -1)
file.se.setdefault(info, []).append(emote)
if subreddit != "mylittlepony":
for name in files["mylittlepony"].emotes:
if name in file.emotes:
del file.emotes[name]
return file
def make_tag_list():
global all_tags
tmp = set()
for (subreddit, file) in files.items():
for (name, emote) in file.emotes.items():
tmp |= emote.tags
all_tags = sorted(tmp)
print("Loading emotes...")
config = bplib.load_yaml_file(open("data/rules.yaml"))
files = {}
loader = bplib.objects.SubredditLoader()
subreddits = config["Subreddits"]
subreddits.remove("mylittlepony")
subreddits.insert(0, "mylittlepony")
for subreddit in config["Subreddits"]:
file = loader.load_subreddit(subreddit)
if file is None:
continue
filter_file(file)
files[subreddit] = file
make_tag_list()
print("Done.")
def sync_tags(subreddit):
assert subreddit in files
path = "tags/%s.yaml" % (subreddit)
file = open(path, "w")
yaml.dump(files[subreddit].dump_tags(), file)
def get_css(subreddit):
if subreddit not in css_cache:
css_rules = bpgen.build_css(files[subreddit].emotes.values())
stream = StringIO.StringIO()
bpgen.dump_css(stream, css_rules)
css_cache[subreddit] = stream.getvalue()
return css_cache[subreddit]
app = flask.Flask(__name__, static_folder="tagapp-static", static_url_path="/static")
secret_key = "".join(random.choice(string.letters) for _ in range(32))
print("SECRET KEY: %s" % (secret_key))
def check_auth(username, password):
return str(username) == "admin" and str(password) == secret_key
def requires_auth(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return flask.Response("Access denied", 401, {"WWW-Authenticate": "Basic realm=\"Login Required\""})
return f(*args, **kwargs)
return decorated
@app.route("/")
def index():
return flask.render_template("index.html", subreddits=files.keys(), all_tags=all_tags)
@app.route("/r/<subreddit>/tag")
def tag(subreddit):
subreddit = str(subreddit)
# Used in template
flask.g.sorted = sorted
flask.g.list = list
flask.g.repr = repr
tags = {name: list(emote.tags) for (name, emote) in files[subreddit].emotes.items()}
return flask.render_template("tag.html", subreddit=subreddit, file=files[subreddit], tags=tags)
@app.route("/r/<subreddit>/write", methods=["POST"])
def write(subreddit):
subreddit = str(subreddit)
data = json.loads(request.form["tags"])
file = files[subreddit]
for (name, tags) in data.items():
assert isinstance(name, unicode)
assert isinstance(tags, list) and all([isinstance(r, unicode) for r in tags])
file.emotes[str(name)].tags = set(map(str, tags))
sync_tags(subreddit)
make_tag_list()
return flask.redirect(flask.url_for("index"))
@app.route("/r/<subreddit>/css")
def css(subreddit):
subreddit = str(subreddit)
return flask.Response(get_css(subreddit), mimetype="text/css")
@app.route("/tag/<tag>")
def taginfo(tag):
tag = str(tag)
data = {}
for (subreddit, file) in files.items():
data[subreddit] = []
for (name, emote) in file.emotes.items():
if tag in emote.tags:
data[subreddit].append(emote)
if not data[subreddit]:
del data[subreddit]
flask.g.sorted = sorted
return flask.render_template("taginfo.html", tag=tag, data=data)
@app.route("/tag/<tag>/rename", methods=["POST"])
@requires_auth
def rename_tag(tag):
tag = str(tag)
to = str(request.form["to"])
if not to.startswith("+"):
to = "+" + to
for (subreddit, file) in files.items():
dirty = False
for (name, emote) in file.emotes.items():
if tag in emote.tags:
emote.tags.remove(tag)
emote.tags.add(to)
dirty = True
if dirty:
sync_tags(subreddit)
all_tags.remove(tag)
if to not in all_tags:
all_tags.append(to)
all_tags.sort()
return flask.redirect(flask.url_for("taginfo", tag=to))
@app.route("/tag/<tag>/delete", methods=["POST"])
@requires_auth
def delete_tag(tag):
tag = str(tag)
if not tag.startswith("+"):
tag = "+" + tag
for (subreddit, file) in files.items():
dirty = False
for (name, emote) in file.emotes.items():
if tag in emote.tags:
emote.tags.remove(tag)
dirty = True
if dirty:
sync_tags(subreddit)
all_tags.remove(tag)
return flask.redirect(flask.url_for("index"))
def main():
parser = argparse.ArgumentParser(description="Emote tagger webapp")
parser.add_argument("-d", "--debug", help="Enable debug mode", default=False, action="store_true")
args = parser.parse_args()
app.debug = args.debug
app.run()
if __name__ == "__main__":
main()