Passed
Push — master ( c6341d...de23cd )
by torrua
01:14
created

app.site.generate_content()   A

Complexity

Conditions 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 20
rs 9.8
c 0
b 0
f 0
cc 4
nop 1
1
# pylint: disable=C0116
2
3
"""
4
App's routes module
5
"""
6
7
import os
8
9
from flask import Blueprint, jsonify, render_template, request, redirect, url_for
10
from loglan_core import Event
11
12
from app.engine import Session
13
from app.site.compose.english_item import EnglishItem
14
from app.site.compose.loglan_item import LoglanItem, Composer
15
from app.site.functions import get_data
16
17
site_blueprint = Blueprint("site", __name__, template_folder="site/templates")
18
19
DEFAULT_SEARCH_LANGUAGE = os.getenv("DEFAULT_SEARCH_LANGUAGE", "log")
20
DEFAULT_HTML_STYLE = os.getenv("DEFAULT_HTML_STYLE", "normal")
21
MAIN_SITE = "http://www.loglan.org/"
22
23
24
@site_blueprint.route("/Articles/")
25
def redirect_articles():
26
    return redirect(url_for("articles"))
27
28
29
@site_blueprint.route("/Texts/")
30
def redirect_texts():
31
    return redirect(url_for("texts"))
32
33
34
@site_blueprint.route("/Sanpa/")
35
@site_blueprint.route("/Lodtua/")
36
def redirect_columns():
37
    return redirect(url_for("columns"))
38
39
40
@site_blueprint.route("/")
41
@site_blueprint.route("/home")
42
def home():
43
    article = get_data(MAIN_SITE).get("content").body.find("div", {"id": "content"})
44
    for bq in article.findAll("blockquote"):
45
        bq["class"] = "blockquote"
46
47
    for img in article.findAll("img"):
48
        img["src"] = MAIN_SITE + img["src"]
49
50
    return render_template("home.html", article="")
51
52
53
@site_blueprint.route("/articles")
54
def articles():
55
    article_block = get_data(MAIN_SITE).get("content")
56
    title = article_block.find("a", {"name": "articles"}).find_parent("h2")
57
    content = title.find_next("ol")
58
    return render_template("articles.html", articles=content, title=title.get_text())
59
60
61
@site_blueprint.route("/texts")
62
def texts():
63
    article_block = get_data(MAIN_SITE).get("content")
64
    title = article_block.find("a", {"name": "texts"}).find_parent("h2")
65
    content = title.find_next("ol")
66
    return render_template("articles.html", articles=content, title=title.get_text())
67
68
69
@site_blueprint.route("/columns")
70
def columns():
71
    article_block = get_data(MAIN_SITE)["content"]
72
    title = article_block.find("a", {"name": "columns"}).find_parent("h2")
73
    content = title.find_next("ul")
74
    return render_template("articles.html", articles=content, title=title.get_text())
75
76
77
@site_blueprint.route("/dictionary")
78
@site_blueprint.route("/dictionary/")
79
def dictionary():
80
    session = Session()
81
    events = session.query(Event).all()
82
    events = {event.id: event.name for event in reversed(events)}
83
    content = generate_content(request.args)
84
    return render_template("dictionary.html", content=content, events=events)
85
86
87
@site_blueprint.route("/how_to_read")
88
def how_to_read():
89
    return render_template("reading.html")
90
91
92
@site_blueprint.route("/submit_search", methods=["POST"])
93
def submit_search():
94
    return generate_content(request.form)
95
96
97
def strtobool(val):
98
    val = val.lower()
99
    if val in ("yes", "true", "t", "y", "1"):
100
        return True
101
    if val in ("no", "false", "f", "n", "0"):
102
        return False
103
    raise ValueError("Invalid boolean value")
104
105
106
def generate_content(data):
107
    word = data.get("word", str())
108
    search_language = data.get("language_id", DEFAULT_SEARCH_LANGUAGE)
109
    event_id = data.get("event_id", 1)
110
    is_case_sensitive = data.get("case_sensitive", False)
111
112
    if not word or not data:
113
        return jsonify(result="<div></div>")
114
115
    nothing = """
116
<div class="alert alert-secondary" role="alert" style="text-align: center;">
117
  %s
118
</div>
119
    """
120
121
    if isinstance(is_case_sensitive, str):
122
        is_case_sensitive = strtobool(is_case_sensitive)
123
124
    result = search_all(search_language, word, event_id, is_case_sensitive, nothing)
125
    return jsonify(result=result)
126
127
128
def search_all(search_language, word, event_id, is_case_sensitive, nothing):
129
    if search_language == "log":
130
        result = search_log(word, event_id, is_case_sensitive, nothing)
131
132
    elif search_language == "eng":
133
        result = search_eng(word, event_id, is_case_sensitive, nothing)
134
    else:
135
        result = nothing % f"Sorry, but nothing was found for <b>{word}</b>."
136
    return result
137
138
139
def search_eng(word, event_id, is_case_sensitive, nothing):
140
    definitions_statement = EnglishItem.select_definitions_by_key(
141
        key=word, event_id=event_id, case_sensitive=is_case_sensitive
142
    )
143
    with Session() as session:
144
        definitions_result = session.execute(definitions_statement).scalars().all()
145
146
        result = EnglishItem(
147
            definitions=definitions_result, key=word, style=DEFAULT_HTML_STYLE
148
        ).export_as_html()
149
    if not result:
150
        result = (
151
            nothing
152
            % f"There is no word <b>{word}</b> in English. Try switching to Loglan"
153
            f"{' or disable Case sensitive search' if is_case_sensitive else ''}."
154
        )
155
    return result
156
157
158
def search_log(word, event_id, is_case_sensitive, nothing):
159
    word_statement = LoglanItem.query_select_words(
160
        name=word, event_id=event_id, case_sensitive=is_case_sensitive
161
    )
162
    with Session() as session:
163
        word_result = session.execute(word_statement).scalars().all()
164
        result = Composer(words=word_result, style=DEFAULT_HTML_STYLE).export_as_html()
165
    if not result:
166
        result = (
167
            nothing
168
            % f"There is no word <b>{word}</b> in Loglan. Try switching to English"
169
            f"{' or disable Case sensitive search' if is_case_sensitive else ''}."
170
        )
171
    return result
172
173
174
@site_blueprint.route("/<string:section>/", methods=["GET"])
175
@site_blueprint.route("/<string:section>/<string:article>", methods=["GET"])
176
def proxy(section: str = "", article: str = ""):
177
    url = f"{MAIN_SITE}{section}/{article}"
178
    content = get_data(url).get("content").body
179
180
    for bq in content.findAll("blockquote"):
181
        bq["class"] = "blockquote"
182
183
    for img in content.findAll("img"):
184
        img["src"] = MAIN_SITE + section + "/" + img["src"]
185
186
    name_of_article = content.h1.extract().get_text()
187
    return render_template(
188
        "article.html", name_of_article=name_of_article, article=content, title=section
189
    )
190