Skip to content

Commit

Permalink
Basics #2 PR #5
Browse files Browse the repository at this point in the history
  • Loading branch information
PetrBodunov authored Feb 25, 2025
2 parents b608c65 + f8c2b5b commit 4ee83a5
Show file tree
Hide file tree
Showing 11 changed files with 209 additions and 0 deletions.
27 changes: 27 additions & 0 deletions playground/shlyahtin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Прототип локального прокторинга

## Client

### 1. Подготовьте папку с расширением

- `manifest.json`
- `background.js`
- `popup.html`
- `popup.js`
- `icon.png`
### 2. Откройте Google Chrome
### 3. Перейдите в раздел "Расширения"
Адрес `chrome://extensions`
### 4. Включите режим разработчика
### 5. Загрузите распакованное расширение
### 6. Откройте расширение

## Server

### 1. Соберите и запустите контейнеры:

`docker-compose up --build`

### 2. После запуска откройте браузер и перейдите по адресу:

`http://localhost:5000/`
3 changes: 3 additions & 0 deletions playground/shlyahtin/client/background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
chrome.action.onClicked.addListener((tab) => {
chrome.tabs.create({ url: chrome.runtime.getURL("popup.html") });
});
Binary file added playground/shlyahtin/client/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions playground/shlyahtin/client/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"manifest_version": 3,
"name": "Screen Recorder Extension",
"version": "1.0",
"description": "Расширение для записи экрана",
"permissions": [
"tabs",
"activeTab"
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
}
}
}
34 changes: 34 additions & 0 deletions playground/shlyahtin/client/popup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Запись экрана</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
min-width: 600px;
min-height: 500px;
}
button, input {
padding: 10px;
font-size: 16px;
margin: 10px;
}
#stop-btn { display: none; } /* Скрываем кнопку остановки по умолчанию */
</style>
</head>
<body>
<h2>Запись экрана</h2>

<label for="username">Имя пользователя:</label>
<input type="text" id="username" placeholder="Введите имя" required>

<button id="start-btn">Начать запись</button>
<button id="stop-btn">Остановить запись</button>

<script src="popup.js"></script>
</body>
</html>
52 changes: 52 additions & 0 deletions playground/shlyahtin/client/popup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const startBtn = document.getElementById("start-btn");
const stopBtn = document.getElementById("stop-btn");
const usernameInput = document.getElementById("username");

let mediaRecorder;
let chunks = [];

startBtn.addEventListener("click", async () => {
const username = usernameInput.value.trim();

if (!username) {
alert("Введите имя пользователя!");
return;
}

try {
const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });

mediaRecorder = new MediaRecorder(stream);
chunks = [];

mediaRecorder.ondataavailable = event => chunks.push(event.data);
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);

const a = document.createElement('a');
a.href = url;
a.download = `${username}_recording.webm`; // Имя пользователя в названии файла
a.click();

stopBtn.style.display = "none";
startBtn.style.display = "inline-block";
};

mediaRecorder.start();
console.log("Запись началась");

startBtn.style.display = "none";
stopBtn.style.display = "inline-block";

} catch (error) {
console.error("Ошибка при получении доступа к экрану:", error);
}
});

stopBtn.addEventListener("click", () => {
if (mediaRecorder && mediaRecorder.state !== "inactive") {
mediaRecorder.stop();
console.log("Запись остановлена");
}
});
3 changes: 3 additions & 0 deletions playground/shlyahtin/server/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MONGO_URI=mongodb://mongodb:27017/testdb
MONGO_PORT=27017
FLASK_PORT=5000
9 changes: 9 additions & 0 deletions playground/shlyahtin/server/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM python:3.12

WORKDIR /app

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

CMD ["python", "app.py"]
39 changes: 39 additions & 0 deletions playground/shlyahtin/server/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import os
from flask import Flask, jsonify
from flask_pymongo import PyMongo

app = Flask(__name__)

# Подключение к локальной MongoDB
app.config["MONGO_URI"] = os.getenv("MONGO_URI")
mongo = PyMongo(app)


@app.route("/")
def home():
return jsonify({"message": "Flask + MongoDB works!"})


@app.route("/insert")
def insert_data():
"""Тестовая вставка данных в коллекцию 'users'"""
try:
users = mongo.db.users
user_id = users.insert_one({"name": "Test user", "age": 25}).inserted_id
return jsonify({"message": "User was added", "id": str(user_id)})
except Exception as e:
return f"Error while inserting data : {e}"


@app.route("/get_users")
def get_users():
"""Получение всех пользователей из коллекции 'users'"""
try:
users = mongo.db.users.find()
result = [{"id": str(user["_id"]), "name": user["name"], "age": user["age"]} for user in users]
return jsonify(result)
except Exception as e:
return f"Error while extracting data : {e}"

if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
22 changes: 22 additions & 0 deletions playground/shlyahtin/server/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
version: '3.8'

services:
mongodb:
image: mongo:6.0 # Фиксируем версию, чтобы избежать неожиданных обновлений
container_name: mongodb
restart: always
env_file:
- .env # Переменные теперь загружаются из .env
ports:
- ${MONGO_PORT}:${MONGO_PORT} # Используем переменную из .env

flask_app:
build: .
container_name: flask_app
restart: always
ports:
- ${FLASK_PORT}:${FLASK_PORT}
depends_on:
- mongodb
env_file:
- .env
2 changes: 2 additions & 0 deletions playground/shlyahtin/server/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
flask
flask-pymongo

0 comments on commit 4ee83a5

Please sign in to comment.