Passed
Pull Request — master (#44)
by torrua
02:00
created

app.site   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 180
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 28
eloc 118
dl 0
loc 180
rs 10
c 0
b 0
f 0

13 Functions

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