Compare commits

..

8 commits
v1.0 ... main

14 changed files with 816900 additions and 1609 deletions

View file

@ -1,22 +1,22 @@
# Используем официальный образ Python как базовый # Используем официальный образ Python как базовый
FROM python:3.11-slim FROM python:3.11-slim
# Устанавливаем системные зависимости для работы с анимацией и SQLite # Устанавливаем системные зависимости для работы с анимацией и SQLite
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
libmagic1 \ libmagic1 \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Устанавливаем рабочую директорию # Устанавливаем рабочую директорию
WORKDIR /app WORKDIR /app
# Копируем файлы приложения в контейнер # Копируем файлы приложения в контейнер
COPY . /app COPY . /app
# Устанавливаем необходимые Python библиотеки # Устанавливаем необходимые Python библиотеки
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
# Открываем порты для работы приложения # Открываем порты для работы приложения
EXPOSE 5000 EXPOSE 5000
# Запускаем приложение # Запускаем приложение
CMD ["hypercorn", "main:app", "--bind", "0.0.0.0:5000"] CMD ["hypercorn", "main:app", "--bind", "0.0.0.0:5000"]

202
LICENSE Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Binary file not shown.

View file

@ -1,14 +1,14 @@
services: services:
web: web:
build: . # Путь к Dockerfile (в текущей директории) build: . # Путь к Dockerfile (в текущей директории)
ports: ports:
- "80:5000" # Проброс портов - "80:5000" # Проброс портов
volumes: volumes:
- nas-share:/data - nas-share:/data
volumes: volumes:
nas-share: nas-share:
driver_opts: driver_opts:
type: cifs type: cifs
o: "username=Shaman,password=" o: "username=Shaman,password="
device: "//192.168.31.3/share/public/complete/workshop" device: "//192.168.31.3/share/public/complete/workshop"

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View file

@ -1,247 +1,269 @@
body { body {
background-color: #1B2838; background-color: #1B2838;
color: white; color: white;
margin: 0; margin: 0;
padding: 0; padding: 0;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: flex-start; align-items: flex-start;
height: 100vh; min-height: 100vh;
overflow: auto; overflow: auto;
} font-family: Arial, sans-serif;
}
.main-container {
display: flex; .main-container {
justify-content: center; display: flex;
align-items: flex-start; justify-content: center;
width: 100%; align-items: flex-start;
padding-top: 50px; width: 100%;
box-sizing: border-box; max-width: 1200px;
} padding: 20px;
box-sizing: border-box;
.image-wrapper { }
background-color: #233B53;
width: 950px; .image-wrapper {
min-height: 555px; background-color: #233B53;
display: flex; width: 100%;
flex-direction: row; max-width: 950px;
justify-content: flex-start; min-height: 555px;
align-items: flex-start; display: flex;
position: relative; flex-direction: row;
border-radius: 5px; justify-content: flex-start;
overflow: hidden; align-items: flex-start;
flex-wrap: wrap; position: relative;
height: auto; border-radius: 5px;
} overflow: hidden;
flex-wrap: wrap;
.image-container { height: auto;
position: relative; box-sizing: border-box;
width: 635px; }
height: 360px;
padding-top: 15px; .image-container {
padding-left: 15px; position: relative;
} width: 635px;
height: 360px;
.image-container img { padding: 15px 15px 0 15px;
width: 100%; }
height: 100%;
object-fit: contain; .image-container img {
} width: 100%;
height: 100%;
.details-container { object-fit: cover;
width: 635px; border-radius: 5px;
height: auto; }
background-color: #19222C;
border: 3px solid #35465E; .details-container {
box-sizing: border-box; width: 635px;
margin-top: 20px; height: auto;
display: flex; background-color: #19222C;
flex-direction: column; border: 3px solid #35465E;
justify-content: flex-start; box-sizing: border-box;
padding: 10px 15px 10px 15px; margin-top: 20px;
margin-left: 15px; display: flex;
position: relative; flex-direction: column;
} justify-content: flex-start;
padding: 15px;
.card-title { margin-left: 15px;
font-size: 20px; position: relative;
font-family: Arial, sans-serif; }
font-weight: bold;
margin: 0; .card-title {
} font-size: 20px;
font-weight: bold;
.description { margin: 0;
font-size: 16px; }
font-family: Arial, sans-serif;
color: #A1B0C7; .description {
margin-top: 10px; font-size: 15px;
line-height: 1.5; color: #A1B0C7;
} margin-top: 10px;
line-height: 1.5;
.download-btn { word-wrap: break-word;
width: 138px; text-align: center;
height: 35px; }
background: linear-gradient(to bottom, #A4D007, #536904);
color: white; .description img {
border: none; max-width: 100%;
border-radius: 2px; height: auto;
font-family: Arial, sans-serif; display: block;
font-size: 19px; margin: 10px 0;
cursor: pointer; border-radius: 5px;
position: absolute; }
top: 10px;
right: 15px; .download-btn {
} width: 138px;
height: 35px;
.download-btn:hover { background: linear-gradient(to bottom, #A4D007, #536904);
background: linear-gradient(to bottom, #8DC50E, #475F2D); color: white;
} border: none;
border-radius: 2px;
.game-mode { font-size: 19px;
position: absolute; cursor: pointer;
top: 15px; position: absolute;
left: 660px; top: 15px;
font-size: 13px; right: 15px;
color: #A1B0C7; }
font-family: Arial, sans-serif;
font-weight: normal; .download-btn:hover {
padding-left: 5px; background: linear-gradient(to bottom, #8DC50E, #475F2D);
} }
.dynamic-data { .game-mode,
font-size: 14px; .tags,
font-weight: normal; .file-size,
color: white; .added-time {
} font-size: 13px;
color: #A1B0C7;
.tags { font-weight: normal;
position: absolute; padding-left: 5px;
top: 100px; margin-top: 10px;
left: 660px; }
font-size: 13px;
color: #A1B0C7; .game-mode { position: absolute; top: 15px; left: 660px; }
font-family: Arial, sans-serif; .tags { position: absolute; top: 100px; left: 660px; }
font-weight: normal; .file-size { position: absolute; top: 150px; left: 660px; }
padding-left: 5px; .added-time { position: absolute; top: 170px; left: 660px; }
}
.dynamic-data {
.file-size { font-size: 14px;
position: absolute; font-weight: normal;
top: 150px; color: white;
left: 660px; margin-left: 5px;
font-size: 13px; }
color: #A1B0C7;
font-family: Arial, sans-serif; .file-size .dynamic-data,
font-weight: normal; .added-time .dynamic-data {
padding-left: 5px; color: #A1B0C7;
} }
.file-size .dynamic-data { .youtube-container {
font-size: 13px; margin-top: 15px;
font-weight: normal; width: 265px;
color: #A1B0C7; height: 150px;
margin-left: 16px; position: absolute;
} top: 210px;
left: 660px;
.added-time { }
position: absolute;
top: 170px; /* Мобильная адаптация */
left: 660px; @media screen and (max-width: 768px) {
font-size: 13px; body {
color: #A1B0C7; padding: 10px;
font-family: Arial, sans-serif; align-items: center;
font-weight: normal; }
padding-left: 5px;
} .main-container {
padding: 10px 0;
.added-time .dynamic-data { }
font-size: 13px;
font-weight: normal; .image-wrapper {
color: #A1B0C7; width: 100%;
margin-left: 45px; max-width: 100%;
} min-height: auto;
flex-direction: column;
.youtube-container { padding: 10px;
margin-top: 15px; }
width: 265px;
height: 150px; .image-container {
display: flex; width: 100%;
justify-content: center; height: auto;
align-items: center; padding: 0;
position: absolute; }
top: 210px;
left: 660px; .image-container img {
} width: 100%;
height: auto;
max-height: 300px;
@media screen and (max-width: 768px) { object-fit: cover;
body { }
flex-direction: column;
align-items: center; .details-container {
padding: 0 10px; width: 100%;
} margin: 10px 0 0 0;
padding: 15px;
.main-container { position: static;
padding-top: 20px; }
}
.card-title {
.image-wrapper { font-size: 18px;
width: 100%; }
flex-direction: column;
align-items: center; .description {
padding: 10px; font-size: 14px;
} }
.image-container { .description img {
width: 100%; max-width: 100%;
height: auto; height: auto;
padding: 0; }
}
.download-btn {
.image-container img { position: static;
width: 100%; width: 100%;
height: auto; height: 45px;
} font-size: 16px;
margin-top: 15px;
.details-container { }
width: 100%;
margin-top: 15px; .game-mode,
margin-left: 0; .tags,
padding: 15px; .file-size,
} .added-time {
position: static;
.download-btn { margin-top: 10px;
position: static; padding-left: 0;
margin-top: 15px; }
width: 100%;
height: 40px; .dynamic-data {
font-size: 18px; display: block;
} margin-left: 0;
font-size: 13px;
.game-mode, }
.tags,
.file-size, .youtube-container {
.added-time { position: static;
position: static; width: 100%;
margin-top: 10px; height: auto;
width: 100%; margin-top: 15px;
text-align: left; }
}
.youtube-container iframe {
.dynamic-data { width: 100%;
margin-left: 0; height: 200px;
font-size: 14px; }
} }
.youtube-container { @media screen and (max-width: 480px) {
position: static; .card-title {
margin-top: 15px; font-size: 16px;
width: 100%; }
height: auto;
} .description {
font-size: 13px;
.youtube-container iframe { }
width: 100%;
height: auto; .description img {
} max-width: 100%;
} height: auto;
}
.download-btn {
height: 40px;
font-size: 14px;
}
.game-mode,
.tags,
.file-size,
.added-time {
font-size: 12px;
}
.dynamic-data {
font-size: 12px;
}
.youtube-container iframe {
height: 180px;
}
}

View file

@ -1,66 +1,64 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru"> <html lang="ru">
<head>
<head> <meta charset="UTF-8">
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title data-i18n="title">workshop</title>
<title>workshop</title> <link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}"> <link rel="icon" href="https://csgoworkshop.ru/favicon.ico" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='assets/steam-120.ico') }}" type="image/x-icon"> <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head> <script src="{{ url_for('static', filename='main.js') }}" defer></script>
</head>
<body>
<body> <div class="main-container">
<div class="main-container"> <div class="image-wrapper">
<div class="image-wrapper"> <div class="image-container">
<div class="image-container"> <img src="{{ image_url }}" alt="Map Image">
<img src="{{ image_url }}" alt="Map Image"> </div>
</div>
<div class="details-container">
<div class="details-container"> <div class="card-title">{{ map_title }}</div>
<div class="card-title">{{ map_title }}</div> <div class="description">
<div class="description"> {{ description }}
{{ description }} </div>
</div> <a href="{{ url_for('download_bsp', image_path=image_url) }}">
<a href="{{ url_for('download_bsp', image_path=image_url) }}"> <button class="download-btn" data-i18n="download">Скачать</button>
<button class="download-btn">🡇 Скачать</button> </a>
</a> </div>
</div>
<div class="game-mode">
<div class="game-mode"> <span data-i18n="game_mode_label">Режим игры:</span>
<span>Режим игры:</span> <span class="dynamic-data">{{ game_mode | default('Не указан') }}</span>
<span class="dynamic-data">{{ game_mode | default('Не указан') }}</span> </div>
</div>
<div class="tags">
<div class="tags"> <span data-i18n="tags_label">Метки:</span>
<span>Метки:</span> <span class="dynamic-data">{{ tags | default('Не указаны') }}</span>
<span class="dynamic-data">{{ tags | default('Не указаны') }}</span> </div>
</div>
<div class="file-size">
<div class="file-size"> <span data-i18n="file_size_label">Размер файла:</span>
<span>Размер файла:</span> <span class="dynamic-data">{{ file_size | default('Не указан') }}</span>
<span class="dynamic-data">{{ file_size | default('Не указан') }}</span> </div>
</div>
<div class="added-time">
<div class="added-time"> <span data-i18n="added_time_label">Добавлен:</span>
<span>Добавлен:</span> <span class="dynamic-data">{{ added_time | default('Не указано') }}</span>
<span class="dynamic-data">{{ added_time | default('Не указано') }}</span> </div>
</div>
{% if youtube_link %}
{% if youtube_link %} <div class="youtube-container">
<div class="youtube-container"> <iframe
<iframe width="265"
width="265" height="150"
height="150" src="{{ youtube_link | replace('watch?v=', 'embed/') }}"
src="{{ youtube_link | replace('watch?v=', 'embed/') }}" frameborder="0"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
allowfullscreen> </iframe>
</iframe> </div>
</div> {% endif %}
{% endif %} </div>
</div> </div>
</div> </body>
</body> </html>
</html>

View file

@ -1,8 +1,75 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const cards = document.querySelectorAll('.card'); const translations = {
cards.forEach(card => { ru: {
card.addEventListener('click', () => { title: "workshop",
window.location.href = '/main'; download: "Скачать",
}); game_mode_label: "Режим игры:",
}); tags_label: "Метки:",
}); file_size_label: "Размер файла:",
added_time_label: "Добавлен:"
},
en: {
title: "Workshop",
download: "Download",
game_mode_label: "Game Mode:",
tags_label: "Tags:",
file_size_label: "File Size:",
added_time_label: "Added:"
}
};
const savedLang = localStorage.getItem('selectedLanguage');
const browserLang = (navigator.language || navigator.userLanguage).split('-')[0];
const defaultLang = savedLang && translations[savedLang] ? savedLang : (translations[browserLang] ? browserLang : 'ru');
function translatePage(lang) {
document.querySelectorAll('[data-i18n]').forEach(element => {
const key = element.getAttribute('data-i18n');
if (translations[lang][key]) {
element.innerHTML = translations[lang][key];
} else {
console.warn(`Translation missing for key: ${key} in language: ${lang}`);
}
});
document.documentElement.lang = lang;
localStorage.setItem('selectedLanguage', lang);
}
function convertBBCodeToMarkdown(text) {
let converted = text
.replace(/\n\s*\n/g, '\n\n') // Убираем лишние пробелы между строками
.trim();
// Преобразование [h1] и [h3] в Markdown-заголовки
converted = converted.replace(/\[h1\](.*?)\[\/h1\]/g, '# $1');
converted = converted.replace(/\[h3\](.*?)\[\/h3\]/g, '### $1');
// Преобразование изображений и ссылок
converted = converted.replace(/\[url=([^\]]+)\]\[img\]([^\[]+)\[\/img\]\[\/url\]/g, '[![]($2)]($1)');
converted = converted.replace(/\[img\]([^\[]+)\[\/img\]/g, '![]($1)');
converted = converted.replace(/\[url=([^\]]+)\]([^\[]+)\[\/url\]/g, '[$2]($1)');
return converted;
}
function renderDescription() {
const descriptionElement = document.querySelector('.description');
if (descriptionElement && window.marked) {
const rawText = descriptionElement.textContent;
const markdownText = convertBBCodeToMarkdown(rawText);
descriptionElement.innerHTML = marked.parse(markdownText);
} else {
console.warn('Marked.js не загружен или элемент .description не найден');
}
}
translatePage(defaultLang);
renderDescription();
const cards = document.querySelectorAll('.card');
cards.forEach(card => {
card.addEventListener('click', () => {
window.location.href = '/main';
});
});
});

File diff suppressed because it is too large Load diff

View file

@ -1,149 +1,157 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru"> <html lang="ru">
<!-- НЕ ЛЕЗЬ СЮДА -->
<head> <head>
<meta charset="UTF-8"> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
<meta name="viewport" content="width=device-width, initial-scale=1.0"> new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
<title>workshop</title> j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
<link rel="icon" href="{{ url_for('static', filename='assets/steam-120.ico') }}" type="image/x-icon"> 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
<link rel="stylesheet" href="{{ url_for('static', filename='workshop.css') }}"> })(window,document,'script','dataLayer','GTM-5CSFWZX5');</script>
<script src="{{ url_for('static', filename='workshop.js') }}" defer></script>
</head> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body> <title data-i18n="title">workshop</title>
<div class="top-bar"> <link rel="icon" href="https://csgoworkshop.ru/favicon.ico" type="image/x-icon">
<div class="left-text"> <link rel="canonical" href="https://csgoworkshop.ru/">
<p>Сделал: ©️𝙎𝙃∆𝙈∆𝙉©️</p> <link rel="stylesheet" href="{{ url_for('static', filename='workshop.css') }}">
<p>Неофициальный сайт<br>с картами для CS:GO<br>из мастерской Steam</p> <script src="{{ url_for('static', filename='workshop.js') }}" defer></script>
</div>
<h1 class="center-text">Добро пожаловать в Workshop</h1> <script async src="https://www.googletagmanager.com/gtag/js?id=G-PGN3XJFDFF"></script>
<a href="https://cloud.s.shsr.ru/apps/forms/s/xr8NyqdpsodwcNnRBSrMzJ4N" class="contact-button" target="_blank">Связаться</a> <!-- Добавлен target="_blank" --> <script>
</div> window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-PGN3XJFDFF');
</script>
</head>
<body>
<div class="main-container"> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5CSFWZX5"
<div class="cards-container"> height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
{% for map in maps_data %}
<div class="card"> <div class="top-bar">
<a href="/main?image_url={{ get_image_path(map[0]) }}&map_title={{ map[1] }}&{{ filters }}"> <div class="left-text">
<img src="{{ get_image_path(map[0]) }}" alt="Map Image" width="200" height="110"> <p data-i18n="made_by">Сделал: ©️𝙎𝙃∆𝙈∆𝙉©️</p>
</a> <p data-i18n="description">Неофициальный сайт<br>с картами для CS:GO<br>из мастерской Steam</p>
<img src="{{ get_star_image(map[2]) }}" alt="{{ map[2] }} stars" class="stars" width="81" height="14"> </div>
<div class="card-title">{{ map[1] }}</div> <h1 class="center-text" data-i18n="header">CS:GO Workshop</h1>
<div class="description-popup"> <a href="https://cloud.shsr.ru/apps/forms/s/xr8NyqdpsodwcNnRBSrMzJ4N" class="contact-button" target="_blank" data-i18n="contact">Связаться</a>
<strong>{{ map[1] }}</strong> </div>
<p>{{ map[3] }}</p>
</div> <div class="main-container">
</div> <div class="cards-container">
{% endfor %} {% for map in maps_data %}
</div> <div class="card">
<a href="/main?image_url={{ get_image_path(map[0]) }}&map_title={{ map[1] }}&{{ filters }}">
<div class="right-rectangle"> <img src="{{ get_image_path(map[0]) }}" alt="Map Image" width="200" height="110">
<div class="sort-button-container"> </a>
<button class="sort-button">Сортировать по дате</button> <img src="{{ get_star_image(map[2]) }}" alt="{{ map[2] }} stars" class="stars" width="81" height="14">
</div> <div class="card-title">{{ map[1] }}</div>
<div class="game-modes"> <div class="description-popup">
<div class="show-products-title"> <strong>{{ map[1] }}</strong>
Показать продукты, попадающие в каждую из выбранных категорий: <p>{{ map[3] }}</p>
</div> </div>
</div>
<div class="game-modes-title">РЕЖИМ ИГРЫ</div> {% endfor %}
</div>
{% for mode, label in {
"Classic": "Классический", <div class="right-rectangle">
"Deathmatch": "Бой насмерть", <div class="sort-button-container">
"Demolition": "Уничтожение объекта", <button class="sort-button" data-i18n="sort_by_date">Сортировать по дате</button>
"Armsrace": "Гонка вооружений", </div>
"Custom": "Пользовательский", <div class="game-modes">
"Training": "Обучение", <div class="show-products-title" data-i18n="show_products">Показать продукты, попадающие в каждую из выбранных категорий:</div>
"Co-op Strike": "Совместный налёт", <div class="game-modes-title" data-i18n="game_modes">РЕЖИМ ИГРЫ</div>
"Wingman": "Напарники",
"Flying Scoutsman": "Перелётные снайперы" {% for mode, label in {
}.items() %} "Classic": "Классический",
<label class="game-mode"> "Deathmatch": "Бой насмерть",
<input type="checkbox" class="game-mode-checkbox" value="{{ mode }}" {% if mode in filters %}checked{% endif %}> "Demolition": "Уничтожение объекта",
{{ label }} "Armsrace": "Гонка вооружений",
</label> "Custom": "Пользовательский",
{% endfor %} "Training": "Обучение",
</div> "Co-op Strike": "Совместный налёт",
<div class="search-container"> "Wingman": "Напарники",
<form method="get" action="/"> "Flying_Scoutsman": "Перелётные снайперы"
<div class="search-input-container"> }.items() %}
<input type="text" id="search" class="search-input" name="search_title" placeholder="Поиск по названию" value="{{ request.args.get('search_title', '') }}"> <label class="game-mode">
<button class="search-button" type="submit"> <input type="checkbox" class="game-mode-checkbox" value="{{ mode }}" {% if mode in filters %}checked{% endif %}>
<img src="/images/search-icon.png" alt="Поиск"> <span data-i18n="game_mode_{{ mode }}">{{ label }}</span>
</button> </label>
</div> {% endfor %}
</form> </div>
</div> <div class="search-container">
</div> <form method="get" action="/">
<div class="search-input-container">
<div id="sortModal" class="modal"> <input type="text" id="search" class="search-input" name="search_title" data-i18n-placeholder="search_placeholder" placeholder="Поиск по названию" value="{{ request.args.get('search_title', '') }}">
<div class="modal-content"> <button class="search-button" type="submit">
<span class="close-btn">&times;</span> <img src="/images/search-icon.png" alt="Поиск">
<h2>Сортировать по дате</h2> </button>
<div class="modal-rectangle"> </div>
<span class="text-left">С</span> </form>
<div class="first-rectangle"> </div>
<input type="date" class="date-input" /> </div>
</div>
<span class="text-center">ПО</span> <div id="sortModal" class="modal">
<div class="second-rectangle"> <div class="modal-content">
<input type="date" class="date-input" /> <span class="close-btn">×</span>
</div> <h2 data-i18n="sort_by_date">Сортировать по дате</h2>
</div> <div class="modal-rectangle">
<button class="ok-button">ОК</button> <span class="text-left" data-i18n="from">С</span>
<button class="cancel-button">Отмена</button> <div class="first-rectangle">
</div> <input type="date" class="date-input" />
</div> </div>
<span class="text-center" data-i18n="to">ПО</span>
<div class="filter-stars"> <div class="second-rectangle">
<div class="filter-title"> <input type="date" class="date-input" />
<label>Фильтр по количеству звезд:</label> </div>
</div> </div>
<div class="stars-filter"> <button class="ok-button" data-i18n="ok">ОК</button>
<label><input type="checkbox" name="stars" value="1" {% if 'stars' in request.args and '1' in request.args.getlist('stars') %}checked{% endif %}> 1</label> <button class="cancel-button" data-i18n="cancel">Отмена</button>
<label><input type="checkbox" name="stars" value="2" {% if 'stars' in request.args and '2' in request.args.getlist('stars') %}checked{% endif %}> 2</label> </div>
<label><input type="checkbox" name="stars" value="3" {% if 'stars' in request.args and '3' in request.args.getlist('stars') %}checked{% endif %}> 3</label> </div>
<label><input type="checkbox" name="stars" value="4" {% if 'stars' in request.args and '4' in request.args.getlist('stars') %}checked{% endif %}> 4</label>
<label><input type="checkbox" name="stars" value="5" {% if 'stars' in request.args and '5' in request.args.getlist('stars') %}checked{% endif %}> 5</label> <div class="filter-stars">
</div> <div class="filter-title">
</div> <label data-i18n="filter_by_stars">Фильтр по количеству звезд:</label>
</div>
<div class="pagination"> <div class="stars-filter">
{% if page > 1 %} <label><input type="checkbox" name="stars" value="1" {% if 'stars' in request.args and '1' in request.args.getlist('stars') %}checked{% endif %}> 1</label>
<a class="pagebtn" href="/?page={{ page - 1 }}&{{ filters }}">&#60;</a> <label><input type="checkbox" name="stars" value="2" {% if 'stars' in request.args and '2' in request.args.getlist('stars') %}checked{% endif %}> 2</label>
{% endif %} <label><input type="checkbox" name="stars" value="3" {% if 'stars' in request.args and '3' in request.args.getlist('stars') %}checked{% endif %}> 3</label>
<label><input type="checkbox" name="stars" value="4" {% if 'stars' in request.args and '4' in request.args.getlist('stars') %}checked{% endif %}> 4</label>
{% if page > 3 %} <label><input type="checkbox" name="stars" value="5" {% if 'stars' in request.args and '5' in request.args.getlist('stars') %}checked{% endif %}> 5</label>
<a class="pagelink" href="/?page=1&{{ filters }}">1</a> </div>
<span class="pagination_space">...</span> </div>
{% endif %}
<div class="pagination">
{% for p in range(1, total_pages + 1) %} {% if page > 1 %}
{% if p >= page - 1 and p <= page + 2 %} <a class="pagebtn" href="/?page={{ page - 1 }}&{{ filters }}"><</a>
{% if p == page %} {% endif %}
<span class="pagelink" style="color: #417A9B;">{{ p }}</span>
{% else %} {% if page > 3 %}
<a class="pagelink" href="/?page={{ p }}&{{ filters }}">{{ p }}</a> <a class="pagelink" href="/?page=1&{{ filters }}">1</a>
{% endif %} <span class="pagination_space">...</span>
{% endif %} {% endif %}
{% endfor %}
{% for p in range(1, total_pages + 1) %}
{% if total_pages > 3 and page < total_pages - 2 %} {% if p >= page - 1 and p <= page + 2 %}
<span class="pagination_space">...</span> {% if p == page %}
<a class="pagelink" href="/?page={{ total_pages }}&{{ filters }}">{{ total_pages }}</a> <span class="pagelink" style="color: #417A9B;">{{ p }}</span>
{% endif %} {% else %}
<a class="pagelink" href="/?page={{ p }}&{{ filters }}">{{ p }}</a>
{% if page < total_pages %} {% endif %}
<a class="pagebtn" href="/?page={{ page + 1 }}&{{ filters }}">&#62;</a> {% endif %}
{% endif %} {% endfor %}
</div>
</div> {% if total_pages > 3 and page < total_pages - 2 %}
</body> <span class="pagination_space">...</span>
<a class="pagelink" href="/?page={{ total_pages }}&{{ filters }}">{{ total_pages }}</a>
</html> {% endif %}
{% if page < total_pages %}
<a class="pagebtn" href="/?page={{ page + 1 }}&{{ filters }}">></a>
{% endif %}
</div>
</div>
</body>
</html>

View file

@ -1,144 +1,198 @@
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
const sortButton = document.querySelector('.sort-button'); const translations = {
const modal = document.getElementById('sortModal'); ru: {
const closeButton = document.querySelector('.close-btn'); title: "workshop",
const cancelButton = document.querySelector('.cancel-button'); made_by: "Сделал: ©️𝙎𝙃∆𝙈∆𝙉©️",
const okButton = document.querySelector('.ok-button'); description: "Неофициальный сайт<br>с картами для CS:GO<br>из мастерской Steam",
const startDateInput = document.querySelector('.first-rectangle .date-input'); header: "CS:GO Workshop",
const endDateInput = document.querySelector('.second-rectangle .date-input'); contact: "Связаться",
const checkboxes = document.querySelectorAll('.game-mode-checkbox'); sort_by_date: "Сортировать по дате",
const params = new URLSearchParams(window.location.search); show_products: "Показать продукты, попадающие в каждую из выбранных категорий:",
game_modes: "РЕЖИМ ИГРЫ",
// Устанавливаем состояние чекбоксов при загрузке страницы game_mode_Classic: "Классический",
checkboxes.forEach(checkbox => { game_mode_Deathmatch: "Бой насмерть",
checkbox.checked = params.getAll('game_modes').includes(checkbox.value); game_mode_Demolition: "Уничтожение объекта",
}); game_mode_Armsrace: "Гонка вооружений",
game_mode_Custom: "Пользовательский",
// Открыть модальное окно при нажатии на кнопку game_mode_Training: "Обучение",
sortButton.addEventListener('click', function () { "game_mode_Co-op Strike": "Совместный налёт",
modal.style.display = 'block'; game_mode_Wingman: "Напарники",
}); game_mode_Flying_Scoutsman: "Перелётные снайперы",
search_placeholder: "Поиск по названию",
// Закрыть модальное окно при нажатии на крестик from: "С",
closeButton.addEventListener('click', function () { to: "ПО",
modal.style.display = 'none'; ok: "ОК",
}); cancel: "Отмена",
filter_by_stars: "Фильтр по количеству звезд:"
// Закрыть модальное окно при нажатии на кнопку "Отмена" },
cancelButton.addEventListener('click', function () { en: {
modal.style.display = 'none'; title: "Workshop",
}); made_by: "Made by: ©️𝙎𝙃∆𝙈∆𝙉©️",
description: "Unofficial site<br>with CS:GO maps<br>from Steam Workshop",
// Применить фильтры по дате и режимам игры при нажатии на кнопку "OK" header: "CS:GO Workshop",
okButton.addEventListener('click', function () { contact: "Contact",
const startDate = startDateInput.value; sort_by_date: "Sort by date",
const endDate = endDateInput.value; show_products: "Show products matching all selected categories:",
game_modes: "GAME MODES",
// Фильтры по датам game_mode_Classic: "Classic",
if (startDate) params.set('start_date', startDate); game_mode_Deathmatch: "Deathmatch",
else params.delete('start_date'); game_mode_Demolition: "Demolition",
game_mode_Armsrace: "Arms Race",
if (endDate) params.set('end_date', endDate); game_mode_Custom: "Custom",
else params.delete('end_date'); game_mode_Training: "Training",
"game_mode_Co-op Strike": "Co-op Strike",
// Фильтры по режимам игры game_mode_Wingman: "Wingman",
const selectedGameModes = Array.from(checkboxes) game_mode_Flying_Scoutsman: "Flying Scoutsman",
.filter(checkbox => checkbox.checked) search_placeholder: "Search by title",
.map(checkbox => checkbox.value); from: "From",
to: "To",
// Обновляем параметры для выбранных режимов ok: "OK",
params.delete('game_modes'); // Удаляем старые значения cancel: "Cancel",
selectedGameModes.forEach(mode => params.append('game_modes', mode)); filter_by_stars: "Filter by number of stars:"
}
params.set('page', 1); // Сбрасываем на первую страницу };
modal.style.display = 'none'; // Закрываем модальное окно
window.location.search = params.toString(); // Перезагружаем страницу с новыми параметрами const savedLang = localStorage.getItem('selectedLanguage');
}); const browserLang = (navigator.language || navigator.userLanguage).split('-')[0];
const defaultLang = savedLang && translations[savedLang] ? savedLang : (translations[browserLang] ? browserLang : 'ru');
// Обновление параметров при изменении чекбоксов
checkboxes.forEach(checkbox => { function translatePage(lang) {
checkbox.addEventListener('change', function () { document.querySelectorAll('[data-i18n]').forEach(element => {
const selectedGameModes = Array.from(checkboxes) const key = element.getAttribute('data-i18n');
.filter(checkbox => checkbox.checked) if (translations[lang][key]) {
.map(checkbox => checkbox.value); element.innerHTML = translations[lang][key];
} else {
// Обновляем параметры URL console.warn(`Translation missing for key: ${key} in language: ${lang}`);
params.delete('game_modes'); // Удаляем старые значения }
selectedGameModes.forEach(mode => params.append('game_modes', mode)); });
document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
params.set('page', 1); // Сбрасываем на первую страницу const key = element.getAttribute('data-i18n-placeholder');
window.location.search = params.toString(); // Перезагружаем страницу с новыми параметрами if (translations[lang][key]) {
}); element.placeholder = translations[lang][key];
}); } else {
}); console.warn(`Placeholder translation missing for key: ${key} in language: ${lang}`);
}
});
document.addEventListener('DOMContentLoaded', function () { document.documentElement.lang = lang;
const searchInput = document.querySelector('.search-input'); localStorage.setItem('selectedLanguage', lang);
}
// Функция для обработки поиска
function performSearch() { translatePage(defaultLang);
const query = searchInput.value.toLowerCase();
const cards = document.querySelectorAll('.card'); const sortButton = document.querySelector('.sort-button');
const modal = document.getElementById('sortModal');
cards.forEach(card => { const closeButton = document.querySelector('.close-btn');
const title = card.querySelector('.card-title').textContent.toLowerCase(); const cancelButton = document.querySelector('.cancel-button');
if (title.includes(query)) { const okButton = document.querySelector('.ok-button');
card.style.display = 'block'; // Показываем карточку, если название соответствует запросу const startDateInput = document.querySelector('.first-rectangle .date-input');
} else { const endDateInput = document.querySelector('.second-rectangle .date-input');
card.style.display = 'none'; // Скрываем карточку, если название не соответствует запросу const checkboxes = document.querySelectorAll('.game-mode-checkbox');
} const params = new URLSearchParams(window.location.search);
});
} checkboxes.forEach(checkbox => {
checkbox.checked = params.getAll('game_modes').includes(checkbox.value);
// Поиск по нажатию клавиши Enter });
searchInput.addEventListener('keydown', function (event) {
if (event.key === 'Enter') { sortButton.addEventListener('click', function () {
performSearch(); modal.style.display = 'block';
} });
});
closeButton.addEventListener('click', function () {
// Поиск по клику на лупу (если такая кнопка добавлена) modal.style.display = 'none';
const searchButton = document.querySelector('.search-button'); });
if (searchButton) {
searchButton.addEventListener('click', performSearch); cancelButton.addEventListener('click', function () {
} modal.style.display = 'none';
}); });
document.addEventListener('DOMContentLoaded', function () { okButton.addEventListener('click', function () {
const starsCheckboxes = document.querySelectorAll('input[name="stars"]'); const startDate = startDateInput.value;
const params = new URLSearchParams(window.location.search); const endDate = endDateInput.value;
// Устанавливаем состояние чекбоксов при загрузке страницы if (startDate) params.set('start_date', startDate);
const selectedStars = params.get('stars'); else params.delete('start_date');
if (selectedStars) {
starsCheckboxes.forEach(checkbox => { if (endDate) params.set('end_date', endDate);
if (checkbox.value === selectedStars) { else params.delete('end_date');
checkbox.checked = true;
} const selectedGameModes = Array.from(checkboxes)
}); .filter(checkbox => checkbox.checked)
} .map(checkbox => checkbox.value);
// Обновление параметров при изменении чекбоксов для звезд params.delete('game_modes');
starsCheckboxes.forEach(checkbox => { selectedGameModes.forEach(mode => params.append('game_modes', mode));
checkbox.addEventListener('change', function () {
// Снимаем отметки с других чекбоксов params.set('page', 1);
starsCheckboxes.forEach(otherCheckbox => { modal.style.display = 'none';
if (otherCheckbox !== checkbox) { window.location.search = params.toString();
otherCheckbox.checked = false; });
}
}); checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function () {
const selectedStar = checkbox.checked ? checkbox.value : null; const selectedGameModes = Array.from(checkboxes)
.filter(checkbox => checkbox.checked)
// Обновляем параметры URL .map(checkbox => checkbox.value);
params.delete('stars');
if (selectedStar) { params.delete('game_modes');
params.set('stars', selectedStar); // Устанавливаем выбранную звезду selectedGameModes.forEach(mode => params.append('game_modes', mode));
}
params.set('page', 1);
params.set('page', 1); // Сбрасываем на первую страницу window.location.search = params.toString();
window.location.search = params.toString(); // Перезагружаем страницу с новыми параметрами });
}); });
});
}); const searchInput = document.querySelector('.search-input');
function performSearch() {
const query = searchInput.value.toLowerCase();
const cards = document.querySelectorAll('.card');
cards.forEach(card => {
const title = card.querySelector('.card-title').textContent.toLowerCase();
if (title.includes(query)) {
card.style.display = 'block';
} else {
card.style.display = 'none';
}
});
}
searchInput.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
performSearch();
}
});
const searchButton = document.querySelector('.search-button');
if (searchButton) {
searchButton.addEventListener('click', performSearch);
}
const starsCheckboxes = document.querySelectorAll('input[name="stars"]');
const selectedStars = params.get('stars');
if (selectedStars) {
starsCheckboxes.forEach(checkbox => {
if (checkbox.value === selectedStars) {
checkbox.checked = true;
}
});
}
starsCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', function () {
starsCheckboxes.forEach(otherCheckbox => {
if (otherCheckbox !== checkbox) {
otherCheckbox.checked = false;
}
});
const selectedStar = checkbox.checked ? checkbox.value : null;
params.delete('stars');
if (selectedStar) {
params.set('stars', selectedStar);
}
params.set('page', 1);
window.location.search = params.toString();
});
});
});

582
main.py
View file

@ -1,291 +1,291 @@
import os import os
import time import time
import asyncio import asyncio
import aiosqlite import aiosqlite
from quart import Quart, render_template, request, send_from_directory, Response from quart import Quart, render_template, request, send_from_directory, Response
from datetime import datetime from datetime import datetime
from babel.dates import format_datetime from babel.dates import format_datetime
app = Quart(__name__, template_folder='frontend', static_folder='frontend') app = Quart(__name__, template_folder='frontend', static_folder='frontend')
DB_PATH = 'maps.db' DB_PATH = 'maps.db'
DATA = "/data" DATA = "/data"
GAME_MODES = { GAME_MODES = {
"Classic": "Классический", "Classic": "Классический",
"Deathmatch": "Бой насмерть", "Deathmatch": "Бой насмерть",
"Demolition": "Уничтожение объекта", "Demolition": "Уничтожение объекта",
"Armsrace": "Гонка вооружений", "Armsrace": "Гонка вооружений",
"Custom": "Пользовательский", "Custom": "Пользовательский",
"Training": "Обучение", "Training": "Обучение",
"Co-op Strike": "Совместный налёт", "Co-op Strike": "Совместный налёт",
"Wingman": "Напарники", "Wingman": "Напарники",
"Flying Scoutsman": "Перелётные снайперы" "Flying Scoutsman": "Перелётные снайперы"
} }
last_download_times = {} last_download_times = {}
DOWNLOAD_COOLDOWN = 10 DOWNLOAD_COOLDOWN = 10
async def get_maps(page=1, per_page=30): async def get_maps(page=1, per_page=30):
async with aiosqlite.connect(DB_PATH) as conn: async with aiosqlite.connect(DB_PATH) as conn:
cursor = await conn.cursor() cursor = await conn.cursor()
offset = (page - 1) * per_page offset = (page - 1) * per_page
await cursor.execute(''' await cursor.execute('''
SELECT FilePath, Title, COALESCE(Stars, 0) as Stars, Description SELECT FilePath, Title, COALESCE(Stars, 0) as Stars, Description
FROM maps FROM maps
ORDER BY DateTime DESC ORDER BY DateTime DESC
LIMIT ? OFFSET ? LIMIT ? OFFSET ?
''', (per_page, offset)) ''', (per_page, offset))
maps = await cursor.fetchall() maps = await cursor.fetchall()
return maps return maps
def get_image_path(filepath): def get_image_path(filepath):
image_path = os.path.join(DATA, filepath) image_path = os.path.join(DATA, filepath)
if not os.path.exists(image_path): if not os.path.exists(image_path):
return "/images/image.jpg" return "/images/image.jpg"
return f"/images/{filepath.split('/')[0]}/{filepath.split('/')[1]}/{filepath.split('/')[1]}.jpg" return f"/images/{filepath.split('/')[0]}/{filepath.split('/')[1]}/{filepath.split('/')[1]}.jpg"
def get_star_image(stars): def get_star_image(stars):
if stars is None or stars == 0: if stars is None or stars == 0:
return "/stars/0-star.png" return "/stars/0-star.png"
return f"/stars/{stars}-star.png" return f"/stars/{stars}-star.png"
@app.route('/images/<path:filename>') @app.route('/images/<path:filename>')
async def serve_image(filename): async def serve_image(filename):
image_path = os.path.join(DATA, filename) image_path = os.path.join(DATA, filename)
if os.path.exists(image_path): if os.path.exists(image_path):
return await send_from_directory(DATA, filename) return await send_from_directory(DATA, filename)
else: else:
default_image_path = os.path.join(DATA, 'image.jpg') default_image_path = os.path.join(DATA, 'image.jpg')
if os.path.exists(default_image_path): if os.path.exists(default_image_path):
return await send_from_directory(DATA, 'image.jpg') return await send_from_directory(DATA, 'image.jpg')
return "Default image not found", 404 return "Default image not found", 404
@app.route('/stars/<filename>') @app.route('/stars/<filename>')
async def serve_star_image(filename): async def serve_star_image(filename):
stars = os.path.join(DATA, 'stars') stars = os.path.join(DATA, 'stars')
star_path = os.path.join(stars, filename) star_path = os.path.join(stars, filename)
if os.path.exists(star_path): if os.path.exists(star_path):
return await send_from_directory(stars, filename) return await send_from_directory(stars, filename)
else: else:
return "Star image not found", 404 return "Star image not found", 404
@app.route('/download_bsp') @app.route('/download_bsp')
async def download_bsp(): async def download_bsp():
user_ip = request.remote_addr user_ip = request.remote_addr
current_time = time.time() current_time = time.time()
last_time = last_download_times.get(user_ip, 0) last_time = last_download_times.get(user_ip, 0)
if current_time - last_time < DOWNLOAD_COOLDOWN: if current_time - last_time < DOWNLOAD_COOLDOWN:
wait_time = DOWNLOAD_COOLDOWN - (current_time - last_time) wait_time = DOWNLOAD_COOLDOWN - (current_time - last_time)
return f"Please wait {int(wait_time)} seconds before downloading again.", 429 return f"Please wait {int(wait_time)} seconds before downloading again.", 429
last_download_times[user_ip] = current_time last_download_times[user_ip] = current_time
image_path = request.args.get('image_path') image_path = request.args.get('image_path')
if not image_path: if not image_path:
return "No image path provided", 400 return "No image path provided", 400
image_folder = os.path.dirname(image_path.replace("/images/", "")) image_folder = os.path.dirname(image_path.replace("/images/", ""))
bsp_filename = None bsp_filename = None
for file in os.listdir(os.path.join(DATA, image_folder)): for file in os.listdir(os.path.join(DATA, image_folder)):
if file.endswith('.bsp'): if file.endswith('.bsp'):
bsp_filename = file bsp_filename = file
break break
if not bsp_filename: if not bsp_filename:
return "No .bsp file found in the same directory", 404 return "No .bsp file found in the same directory", 404
file_path = os.path.join(DATA, image_folder, bsp_filename) file_path = os.path.join(DATA, image_folder, bsp_filename)
SPEED_LIMIT = 40 * 1024 * 1024 // 8 SPEED_LIMIT = 40 * 1024 * 1024 // 8
async def file_stream(): async def file_stream():
with open(file_path, 'rb') as f: with open(file_path, 'rb') as f:
while chunk := f.read(SPEED_LIMIT): while chunk := f.read(SPEED_LIMIT):
yield chunk yield chunk
await asyncio.sleep(1) await asyncio.sleep(1)
headers = { headers = {
"Content-Disposition": f"attachment; filename={bsp_filename}" "Content-Disposition": f"attachment; filename={bsp_filename}"
} }
return Response(file_stream(), headers=headers, content_type='application/octet-stream') return Response(file_stream(), headers=headers, content_type='application/octet-stream')
@app.route('/main') @app.route('/main')
async def main_page(): async def main_page():
image_url = request.args.get('image_url', 'default_image.jpg') image_url = request.args.get('image_url', 'default_image.jpg')
map_title = request.args.get('map_title', 'Default Map Title') map_title = request.args.get('map_title', 'Default Map Title')
async with aiosqlite.connect(DB_PATH) as conn: async with aiosqlite.connect(DB_PATH) as conn:
cursor = await conn.cursor() cursor = await conn.cursor()
await cursor.execute(''' await cursor.execute('''
SELECT GameMode, Tags, FilePath, DateTime, YoutubeLink, Description SELECT GameMode, Tags, FilePath, DateTime, YoutubeLink, Description
FROM maps FROM maps
WHERE Title = ? WHERE Title = ?
''', (map_title,)) ''', (map_title,))
row = await cursor.fetchone() row = await cursor.fetchone()
game_mode = row[0] if row else None game_mode = row[0] if row else None
tags = row[1] if row else None tags = row[1] if row else None
file_path = row[2] if row else None file_path = row[2] if row else None
date_time = row[3] if row else None date_time = row[3] if row else None
youtube_link = row[4] if row else None youtube_link = row[4] if row else None
description = row[5] if row else "Нет описания" description = row[5] if row else "Нет описания"
if date_time: if date_time:
dt = datetime.fromisoformat(date_time) dt = datetime.fromisoformat(date_time)
added_time = format_datetime(dt, format='d MMM yг., HH:mm', locale='ru_RU') added_time = format_datetime(dt, format='d MMM yг., HH:mm', locale='ru_RU')
else: else:
added_time = 'Не найдено' added_time = 'Не найдено'
if game_mode: if game_mode:
game_modes = game_mode.split(', ') game_modes = game_mode.split(', ')
game_modes = [GAME_MODES.get(mode, mode) for mode in game_modes] game_modes = [GAME_MODES.get(mode, mode) for mode in game_modes]
game_mode = ', '.join(game_modes) game_mode = ', '.join(game_modes)
else: else:
game_mode = 'Не найден' game_mode = 'Не найден'
if tags: if tags:
tags_list = tags.split(', ') tags_list = tags.split(', ')
tags_list = [GAME_MODES.get(tag, tag) for tag in tags_list] tags_list = [GAME_MODES.get(tag, tag) for tag in tags_list]
tags = ', '.join(tags_list) tags = ', '.join(tags_list)
else: else:
tags = 'Не найдено' tags = 'Не найдено'
if file_path: if file_path:
file_size = os.path.getsize(os.path.join(DATA, file_path)) file_size = os.path.getsize(os.path.join(DATA, file_path))
file_size_mb = file_size / (1024 * 1024) file_size_mb = file_size / (1024 * 1024)
file_size_display = f"{file_size_mb:.2f} MB" file_size_display = f"{file_size_mb:.2f} MB"
else: else:
file_size_display = 'Не найден' file_size_display = 'Не найден'
return await render_template( return await render_template(
'main.html', 'main.html',
image_url=image_url, image_url=image_url,
map_title=map_title, map_title=map_title,
game_mode=game_mode, game_mode=game_mode,
tags=tags, tags=tags,
file_size=file_size_display, file_size=file_size_display,
added_time=added_time, added_time=added_time,
youtube_link=youtube_link, youtube_link=youtube_link,
description=description description=description
) )
@app.route('/') @app.route('/')
async def index(): async def index():
page = int(request.args.get('page', 1)) page = int(request.args.get('page', 1))
selected_game_modes = request.args.getlist('game_modes') selected_game_modes = request.args.getlist('game_modes')
start_date = request.args.get('start_date') start_date = request.args.get('start_date')
end_date = request.args.get('end_date') end_date = request.args.get('end_date')
search_title = request.args.get('search_title') search_title = request.args.get('search_title')
selected_stars = request.args.get('stars') selected_stars = request.args.get('stars')
maps_data = await get_maps_filtered(page, selected_game_modes, start_date, end_date, search_title, selected_stars) maps_data = await get_maps_filtered(page, selected_game_modes, start_date, end_date, search_title, selected_stars)
async with aiosqlite.connect(DB_PATH) as conn: async with aiosqlite.connect(DB_PATH) as conn:
cursor = await conn.cursor() cursor = await conn.cursor()
query = 'SELECT COUNT(*) FROM maps WHERE 1=1' query = 'SELECT COUNT(*) FROM maps WHERE 1=1'
params = [] params = []
if selected_game_modes: if selected_game_modes:
placeholders = ', '.join('?' for _ in selected_game_modes) placeholders = ', '.join('?' for _ in selected_game_modes)
query += f' AND GameMode IN ({placeholders})' query += f' AND GameMode IN ({placeholders})'
params.extend(selected_game_modes) params.extend(selected_game_modes)
if start_date: if start_date:
query += ' AND DateTime >= ?' query += ' AND DateTime >= ?'
params.append(start_date) params.append(start_date)
if end_date: if end_date:
query += ' AND DateTime <= ?' query += ' AND DateTime <= ?'
params.append(end_date) params.append(end_date)
if search_title: if search_title:
query += ' AND Title LIKE ?' query += ' AND Title LIKE ?'
params.append(f'%{search_title}%') params.append(f'%{search_title}%')
if selected_stars: if selected_stars:
query += ' AND Stars = ?' query += ' AND Stars = ?'
params.append(selected_stars) params.append(selected_stars)
await cursor.execute(query, params) await cursor.execute(query, params)
total_maps = await cursor.fetchone() total_maps = await cursor.fetchone()
total_maps = total_maps[0] total_maps = total_maps[0]
per_page = 30 per_page = 30
total_pages = (total_maps + per_page - 1) // per_page total_pages = (total_maps + per_page - 1) // per_page
filters = '&'.join( filters = '&'.join(
[f'game_modes={mode}' for mode in selected_game_modes] + [f'game_modes={mode}' for mode in selected_game_modes] +
([f'start_date={start_date}'] if start_date else []) + ([f'start_date={start_date}'] if start_date else []) +
([f'end_date={end_date}'] if end_date else []) + ([f'end_date={end_date}'] if end_date else []) +
([f'search_title={search_title}'] if search_title else []) + ([f'search_title={search_title}'] if search_title else []) +
([f'stars={selected_stars}'] if selected_stars else []) ([f'stars={selected_stars}'] if selected_stars else [])
) )
return await render_template( return await render_template(
'workshop.html', 'workshop.html',
maps_data=maps_data, maps_data=maps_data,
page=page, page=page,
total_pages=total_pages, total_pages=total_pages,
get_image_path=get_image_path, get_image_path=get_image_path,
get_star_image=get_star_image, get_star_image=get_star_image,
selected_game_modes=selected_game_modes, selected_game_modes=selected_game_modes,
filters=filters, filters=filters,
selected_stars=selected_stars selected_stars=selected_stars
) )
async def get_maps_filtered(page=1, selected_game_modes=None, start_date=None, end_date=None, search_title=None, selected_stars=None): async def get_maps_filtered(page=1, selected_game_modes=None, start_date=None, end_date=None, search_title=None, selected_stars=None):
async with aiosqlite.connect(DB_PATH) as conn: async with aiosqlite.connect(DB_PATH) as conn:
cursor = await conn.cursor() cursor = await conn.cursor()
offset = (page - 1) * 30 offset = (page - 1) * 30
query = ''' query = '''
SELECT FilePath, Title, COALESCE(Stars, 0) as Stars, Description SELECT FilePath, Title, COALESCE(Stars, 0) as Stars, Description
FROM maps FROM maps
WHERE 1=1 WHERE 1=1
''' '''
params = [] params = []
if selected_stars: if selected_stars:
query += ' AND Stars = ?' query += ' AND Stars = ?'
params.append(selected_stars) params.append(selected_stars)
if search_title: if search_title:
query += ' AND Title LIKE ?' query += ' AND Title LIKE ?'
params.append(f'%{search_title}%') params.append(f'%{search_title}%')
if selected_game_modes: if selected_game_modes:
query += ' AND GameMode IN ({})'.format(','.join('?' for _ in selected_game_modes)) query += ' AND GameMode IN ({})'.format(','.join('?' for _ in selected_game_modes))
params.extend(selected_game_modes) params.extend(selected_game_modes)
if start_date: if start_date:
query += ' AND DateTime >= ?' query += ' AND DateTime >= ?'
params.append(start_date) params.append(start_date)
if end_date: if end_date:
query += ' AND DateTime <= ?' query += ' AND DateTime <= ?'
params.append(end_date) params.append(end_date)
query += ' ORDER BY DateTime DESC LIMIT ? OFFSET ?' query += ' ORDER BY DateTime DESC LIMIT ? OFFSET ?'
params.extend([30, offset]) params.extend([30, offset])
await cursor.execute(query, params) await cursor.execute(query, params)
maps = await cursor.fetchall() maps = await cursor.fetchall()
return maps return maps
if __name__ == '__main__': if __name__ == '__main__':
import hypercorn.asyncio import hypercorn.asyncio
from hypercorn.config import Config from hypercorn.config import Config
config = Config() config = Config()
config.bind = ["0.0.0.0:5000"] config.bind = ["0.0.0.0:5000"]
hypercorn.asyncio.run(app, config) hypercorn.asyncio.run(app, config)

View file

@ -1,4 +1,4 @@
aiosqlite~=0.20.0 aiosqlite~=0.20.0
Hypercorn~=0.17.3 Hypercorn~=0.17.3
Quart~=0.19.6 Quart~=0.19.6
babel~=2.16.0 babel~=2.16.0

814875
sitemap.xml Normal file

File diff suppressed because it is too large Load diff