6 Commits

5 changed files with 55 additions and 259 deletions

View File

@@ -1,81 +0,0 @@
#!/bin/bash
# Description: Скрипт для корректной загрузки и установки программы RPIVirusScanner
# Author: Шафеев "Thiflict" Марат
# Date: 2026-04-14
# Так как скрипт не тестировался должным образом, необходимо запросить у пользователя о его намерениях продолжать выполнение скрипта.
read -p "ВНИМАНИЕ!!! Данный скрипт установки не тестировался должным образом! Это значит, что скрипт может поломать некоторые конфиги ClamAV и Samba КАК МИНИМУМ! Для продолжения введите: 'i understand all the risks and want to continue'. Это будет означать, что вы понимаете риски и хотите продолжить выполнение программы! " answer
answer=${answer,,}
if [[ "$answer" != "i understand all the risks and want to continue" ]]; then
echo "Неправильно набрана фраза для продолжения. Отменяю..."
exit 0
fi
echo "Выполняю..."
# Обновление списков пакетов и зарузка зависимостей
apt update;
apt install openjdk-21-jdk gpiod libgpiod-dev clamav clamav-daemon ntfs-3g usbmount samba -y; # Загрузка нужных пактов
# Настройка либы для взаимодействия с GPIO
echo "Подготовка библиотек взаимодействия с GPIO..."
sudo usermod -a -G gpio,spi,i2c $USER;
newgrp gpio;
# Настройка ClamAV
echo "Настройка ClamAV"
{
echo "PrivateMirror https://clamav-mirror.ru";
echo "PrivateMirror https://mirror.truenetwork.ru/clamav/";
echo "PrivateMirror http://mirror.truenetwork.ru/clamav/";
echo "ScriptedUpdates no";
} >> /etc/clamav/freshclam.conf;
rm /var/lib/clamav/freshclam.dat;
freshclam -vvv;
CONFIG_FILE="/etc/clamav/clamd.conf"; # Путь к файлу конфига
NEW_VALUE_MT="10"; # Новое значение MaxThreads
NEW_VALUE_MF="10M"; # Новое значение MaxFileSize
NEW_VALUE_MS="30M"; # Новое значение MaxScanSize
cp "$CONFIG_FILE" "$CONFIG_FILE.bak"; # Создание бекапа конфига
sed -i -E "
s/^(MaxThreads[[:space:]]+).*/\1$NEW_VALUE_MT/
s/^(MaxFileSize[[:space:]]+).*/\1$NEW_VALUE_MF/
s/^(MaxScanSize[[:space:]]+).*/\1$NEW_VALUE_MS/
" "$CONFIG_FILE"; # Изменение конфига
# Загрузка временных файлов
echo "Загрузка необходиых временных файлов..."
rm -rf /tmp/rpivs;
mkdir /tmp/rpivs;
wget https://static1.thiflict.ru/raspberrypi_virus_scanner/v2.0/smb_conf -o /tmp/rpivs/smb.conf
wget https://static1.thiflict.ru/raspberrypi_virus_scanner/v2.0/rpivirusscanner.jar -o /tmp/rpivs/rpivirusscanner.jar;
wget https://static1.thiflict.ru/raspberrypi_virus_scanner/v2.0/rpi_virus_scanner_service -o /tmp/rpivs/rpi_virus_scanner.service;
# Настройка Samba
echo "Выполняется настройка Samba"
systemctl stop smbd
systemctl disable smbd
cp /tmp/rpivs/smb.conf /etc/samba/smb.conf
testparm # Для дебага
# Установка программы
echo "Установка программы..."
rm -rf /opt/thiflict-dev/rpi-virus-scanner/
mkdir -p /opt/thiflict-dev/rpi-virus-scanner/
mv /tmp/rpivs/rpivirusscanner.jar /opt/thiflict-dev/rpi-virus-scanner/;
# Создание демона
echo "Создание демона RPIVirusScanner..."
mv /tmp/rpivs/rpi_virus_scanner.service /etc/systemd/system/;
systemctl daemon-reload;
systemctl enable rpi_virus_scanner.service;
# Авторство:
echo "RaspberryPi успешно установлен! Рекомендуется перезагрузить устройство.";
echo " ";
echo "==== Об авторе: ====";
echo "Репозиторий проекта: https://git.ds1.thiflict.ru/Shafeev-CourseWork/Practice-Part";
echo "Телеграм-канал: https://t.me/Thiflict_tg";
echo "YouTube канал: https://youtube.com/@Thiflict";

View File

@@ -1,3 +1,6 @@
# РЕПОЗИТОРИЙ АРХИВИРОВАН И ЗДЕСЬ БОЛЬШЕ *НЕ* БУДЕТ ОБНОВЛЕНИЙ!
Этот форк разрабатывался в рамках курсовой работы и дальнейшие изменения проекта будут проходить в его [оригинальном репозитории](https://git.ds1.thiflict.ru/Thiflict/RPIVirusScaner)
# Raspberry Pi virus checker for USB volumes. # Raspberry Pi virus checker for USB volumes.
## Сканер вирусов на USB флеш-накопителях на базе Raspberry Pi ## Сканер вирусов на USB флеш-накопителях на базе Raspberry Pi
@@ -33,14 +36,3 @@
> - Первый контакт тактовой кнопки: GPIO 24 (Физический пин 18) > - Первый контакт тактовой кнопки: GPIO 24 (Физический пин 18)
> - Второй контакт тактовой кнопки: Любой из GND (Физические пины: 6, 9, 14, 20, 25, 30, 34, 39) > - Второй контакт тактовой кнопки: Любой из GND (Физические пины: 6, 9, 14, 20, 25, 30, 34, 39)
Для загрузки можно также воспользоваться скриптом установки. **(НЕ ТЕСТИРОВАН!)**
Для этого его необходимо загрузить из релиза или из исходника, затем сделать его executable
```bash
sudo chmod +x install_script.sh
```
Затем, выполнить его от имени суперпользователя:
```bash
sudo ./install_script.sh
```

View File

@@ -6,6 +6,7 @@ import ru.thiflict.PinConfig.BUTTON
import java.io.BufferedReader import java.io.BufferedReader
import java.io.InputStreamReader import java.io.InputStreamReader
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import kotlin.time.Duration.Companion.milliseconds
class ButtonClickEvent class ButtonClickEvent
class ButtonLongPressEvent class ButtonLongPressEvent
@@ -31,18 +32,10 @@ class ButtonListener(
clickListeners.add(listener) clickListeners.add(listener)
} }
fun removeClickListener(listener: ButtonClickListener) {
clickListeners.remove(listener)
}
fun addLongPressListener(listener: ButtonLongPressListener) { fun addLongPressListener(listener: ButtonLongPressListener) {
longPressListeners.add(listener) longPressListeners.add(listener)
} }
fun removeLongPressListener(listener: ButtonLongPressListener) {
longPressListeners.remove(listener)
}
private fun notifyClick() { private fun notifyClick() {
println("=== [CLICK] Короткое нажатие ===") println("=== [CLICK] Короткое нажатие ===")
val event = ButtonClickEvent() val event = ButtonClickEvent()
@@ -93,7 +86,6 @@ class ButtonListener(
onStateChange?.invoke(false) onStateChange?.invoke(false)
println(if (isDebug) "Кнопка отпущена, длительность: ${pressDuration}ms" else "") println(if (isDebug) "Кнопка отпущена, длительность: ${pressDuration}ms" else "")
// Определяем тип нажатия по длительности
when { when {
pressDuration >= longPressThresholdMs -> { pressDuration >= longPressThresholdMs -> {
println(if (isDebug) "Длинное нажатие (${pressDuration}ms)" else "") println(if (isDebug) "Длинное нажатие (${pressDuration}ms)" else "")
@@ -118,10 +110,9 @@ class ButtonListener(
println("Процесс завершён ($exitCode)") println("Процесс завершён ($exitCode)")
isListening.set(false) isListening.set(false)
// Автоматически перезапускаем прослушивание, если оно должно быть активно
if (isListening.get()) { if (isListening.get()) {
println("Перезапуск прослушивания...") println("Перезапуск прослушивания...")
delay(100) delay(100.milliseconds)
startListeningInternal(onStateChange) startListeningInternal(onStateChange)
} }
} }
@@ -130,17 +121,4 @@ class ButtonListener(
isListening.set(false) isListening.set(false)
} }
} }
fun stopListening() {
isListening.set(false)
listenerJob?.cancel()
process?.destroy()
process = null
}
fun restartListening(onStateChange: ((Boolean) -> Unit)? = null) {
stopListening()
Thread.sleep(200)
startListening(onStateChange)
}
} }

View File

@@ -6,18 +6,15 @@ class GPIOController(private val pin: Int) {
fun setValue(value: Int) { fun setValue(value: Int) {
try { try {
// Пробуем разные варианты синтаксиса gpioset
val commands = listOf("gpioset", "--chip=0", "$pin=$value") val commands = listOf("gpioset", "--chip=0", "$pin=$value")
try {
try { val process = ProcessBuilder(commands)
val process = ProcessBuilder(commands) .redirectErrorStream(true)
.redirectErrorStream(true) .start()
.start() Thread.sleep(30)
Thread.sleep(50) process.destroy()
process.destroy() } catch (_: Exception) {
} catch (e: Exception) { }
// Пробуем следующую команду
}
} catch (e: Exception) { } catch (e: Exception) {
println(if (isDebug) "Ошибка установки GPIO $pin = $value: ${e.message}" else "") println(if (isDebug) "Ошибка установки GPIO $pin = $value: ${e.message}" else "")
@@ -38,10 +35,4 @@ class GPIOController(private val pin: Int) {
0 0
} }
} }
fun close() {
// Ничего не делаем
}
} }

View File

@@ -10,7 +10,6 @@ import java.util.*
import java.util.concurrent.* import java.util.concurrent.*
import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.milliseconds
// Конфигурация GPIO (BCM номера)
object PinConfig { object PinConfig {
const val GREEN_LED = 17 const val GREEN_LED = 17
const val YELLOW_LED = 27 const val YELLOW_LED = 27
@@ -26,7 +25,6 @@ object DebugMode {
} }
} }
// Состояния системы
enum class SystemState { enum class SystemState {
IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT, SAMBA IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT, SAMBA
} }
@@ -48,22 +46,19 @@ class USBVirusScanner {
println(if (isDebug) "Инициализация..." else "") println(if (isDebug) "Инициализация..." else "")
try { try {
// Проверяем доступность gpiod checkLibgpiod() // Проверка установленных библиотек
checkLibgpiod()
greenLed = GPIOController(PinConfig.GREEN_LED) greenLed = GPIOController(PinConfig.GREEN_LED)
yellowLed = GPIOController(PinConfig.YELLOW_LED) yellowLed = GPIOController(PinConfig.YELLOW_LED)
redLed = GPIOController(PinConfig.RED_LED) redLed = GPIOController(PinConfig.RED_LED)
// Выключаем все светодиоды
greenLed.setValue(0) greenLed.setValue(0)
yellowLed.setValue(0) yellowLed.setValue(0)
redLed.setValue(0) redLed.setValue(0)
// Запускаем индикацию состояния startStateIndication() // Запуск системы индикации
startStateIndication()
antivirusDatabaseUpdater() antivirusDatabaseUpdater() // Первоначальная проверка обновлений антивирусных баз данных
Thread.sleep(1000) Thread.sleep(1000)
@@ -73,7 +68,7 @@ class USBVirusScanner {
} catch (e: Exception) { } catch (e: Exception) {
currentState = SystemState.ERROR currentState = SystemState.ERROR
println(if (isDebug) "Ошибка инициализации: ${e.message}" else "") println(if (isDebug) "Ошибка инициализации: ${e.message}" else "")
e.printStackTrace() e.printStackTrace()
throw e throw e
} }
@@ -89,30 +84,16 @@ class USBVirusScanner {
} }
val output = process.inputStream.bufferedReader().readText() val output = process.inputStream.bufferedReader().readText()
println(if (isDebug) "libgpiod найден" else "") println(if (isDebug) "libgpiod найден" else "")
if (output.isNotBlank()) { if (output.isNotBlank()) {
println(if (isDebug) "Доступные чипы: ${output.trim()}" else "") println(if (isDebug) "Доступные чипы: ${output.trim()}" else "")
} }
} catch (e: Exception) { } catch (_: Exception) {
throw Exception(if (isDebug) "libgpiod Не установлен!" else "") throw Exception(if (isDebug) "libgpiod Не установлен" else "")
} }
} }
fun buttonPress(defaultButtonState: Boolean): Boolean {
var finalButtonState = defaultButtonState
println(if (isDebug) "Начало finalButtonState: $finalButtonState" else "")
val buttonListener = ButtonListener()
val initialState = buttonListener.startListening { isPressed ->
if (isPressed) {
finalButtonState = true
}
}
println(if (isDebug) "finalButtonState: $finalButtonState" else "")
return finalButtonState
}
private fun startStateIndication() { private fun startStateIndication() {
indicationJob = scope.launch { indicationJob = scope.launch {
while (isRunning) { while (isRunning) {
@@ -205,7 +186,7 @@ class USBVirusScanner {
return@launch return@launch
} }
println(if (isDebug) "📀 Найдены USB-устройства:" else "") println(if (isDebug) "Найдены USB-устройства:" else "")
usbDevices.forEach { device -> usbDevices.forEach { device ->
println(" - ${device.mountPoint}") println(" - ${device.mountPoint}")
} }
@@ -215,31 +196,28 @@ class USBVirusScanner {
val scanResults = mutableListOf<ScanResult>() val scanResults = mutableListOf<ScanResult>()
for (device in usbDevices) { for (device in usbDevices) {
println(if (isDebug) "🔍 Сканирование: ${device.mountPoint}" else "") println(if (isDebug) "Сканирование: ${device.mountPoint}" else "")
val result = scanWithClamAV(device.mountPoint) val result = scanWithClamAV(device.mountPoint)
scanResults.add(result) scanResults.add(result)
if (result.isInfected) { if (result.isInfected) {
hasVirus = true hasVirus = true
println(if (isDebug) "⚠️ ВНИМАНИЕ! Найдены угрозы!" else "") println(if (isDebug) "ВНИМАНИЕ! Найдены угрозы!" else "")
result.infectedFiles.take(10).forEach { file -> result.infectedFiles.take(10).forEach { file ->
println(" 🦠 ${file.take(100)}") println(" - ${file.take(100)}")
} }
if (result.infectedFiles.size > 10) { if (result.infectedFiles.size > 10) {
println(if (isDebug) " ... и ещё ${result.infectedFiles.size - 10} файлов" else "") println(if (isDebug) " ... и ещё ${result.infectedFiles.size - 10} файлов" else "")
} }
unmount() unmount()
} else if (result.error != null) { } else if (result.error != null) {
println(if (isDebug) "Ошибка сканирования: ${result.error}" else "") println(if (isDebug) "Ошибка сканирования: ${result.error}" else "")
} else { } else {
println(if (isDebug) "Сканирование завершено: угроз не найдено" else "") println(if (isDebug) "Сканирование завершено: угроз не найдено" else "")
} }
println() println()
} }
// Сохраняем лог
saveScanLog(scanResults)
currentState = if (hasVirus) { currentState = if (hasVirus) {
SystemState.INFECTED SystemState.INFECTED
} else { } else {
@@ -247,14 +225,13 @@ class USBVirusScanner {
} }
val message = if (hasVirus) { val message = if (hasVirus) {
if (isDebug) "🦠 Найдены вирусы! Красный LED горит" else "" if (isDebug) "Debug: Найдены вирусы" else ""
} else { } else {
if (isDebug) " Флешка чиста! Зелёный LED горит" else "" if (isDebug) "Debug: Флешка чиста" else ""
} }
println(if (isDebug) message else "") println(if (isDebug) message else "")
// Держим состояние 5 секунд delay(10000.milliseconds) // Удерживание состояния на 10 секунд
delay(10000.milliseconds)
if (!hasVirus) { if (!hasVirus) {
currentState = SystemState.SAMBA currentState = SystemState.SAMBA
@@ -263,7 +240,7 @@ class USBVirusScanner {
val buttonListener = ButtonListener() val buttonListener = ButtonListener()
var isEventHappened = false var isEventHappened = false
buttonListener.addLongPressListener { event -> buttonListener.addLongPressListener { _ ->
isEventHappened = true isEventHappened = true
} }
buttonListener.startListening() buttonListener.startListening()
@@ -274,8 +251,12 @@ class USBVirusScanner {
currentState = SystemState.IDLE currentState = SystemState.IDLE
} catch (e: Exception) { } catch (_: kotlinx.coroutines.CancellationException) {
println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "") currentState = SystemState.IDLE
println(if (isDebug) "Программа получила CancellationException. Возврат к состоянию IDLE." else "")
}
catch (e: Exception) {
println(if (isDebug) "Критическая ошибка: ${e.message}" else "")
e.printStackTrace() e.printStackTrace()
currentState = SystemState.ERROR currentState = SystemState.ERROR
delay(10000.milliseconds) delay(10000.milliseconds)
@@ -289,8 +270,7 @@ class USBVirusScanner {
private fun findUSBDevices(): List<USBDevice> { private fun findUSBDevices(): List<USBDevice> {
val devices = mutableListOf<USBDevice>() val devices = mutableListOf<USBDevice>()
try { try { // Проверка директории /media
// Проверяем /media директории
val mediaDirs = listOf("/media", "/media/pi") val mediaDirs = listOf("/media", "/media/pi")
for (mediaDirPath in mediaDirs) { for (mediaDirPath in mediaDirs) {
@@ -315,7 +295,7 @@ class USBVirusScanner {
} }
} }
// Проверяем /proc/mounts для дополнительных точек монтирования // Проверка /proc/mounts не предмет дополнительных точек монтирования
val mountsFile = File("/proc/mounts") val mountsFile = File("/proc/mounts")
if (mountsFile.exists()) { if (mountsFile.exists()) {
mountsFile.readLines().forEach { line -> mountsFile.readLines().forEach { line ->
@@ -347,7 +327,7 @@ class USBVirusScanner {
try { try {
// Проверяем установлен ли ClamAV // Проверяем установлен ли ClamAV
val checkProcess = ProcessBuilder("which", "clamscan").start() val checkProcess = ProcessBuilder("which", "clamdscan").start()
val checkExitCode = checkProcess.waitFor() val checkExitCode = checkProcess.waitFor()
if (checkExitCode != 0) { if (checkExitCode != 0) {
@@ -356,11 +336,11 @@ class USBVirusScanner {
infectedFiles = emptyList(), infectedFiles = emptyList(),
virusNames = emptyMap(), virusNames = emptyMap(),
exitCode = -1, exitCode = -1,
error = if (isDebug) "ClamAV не установлен. Установите: sudo apt install clamav" else "" error = if (isDebug) "ClamAV не установлен." else ""
) )
} }
// Проверяем существование пути // Проверка существования пути
val pathFile = File(path) val pathFile = File(path)
if (!pathFile.exists() || !pathFile.isDirectory) { if (!pathFile.exists() || !pathFile.isDirectory) {
return ScanResult( return ScanResult(
@@ -372,9 +352,9 @@ class USBVirusScanner {
) )
} }
println(if (isDebug) " Запуск clamscan (это может занять некоторое время)..." else "") println(if (isDebug) " Запуск clamdcan..." else "")
// Запускаем ClamAV // Запуск непосредственной антивирусной проверки
val processBuilder = ProcessBuilder( val processBuilder = ProcessBuilder(
"clamdscan", "clamdscan",
"--multiscan", "--multiscan",
@@ -389,7 +369,7 @@ class USBVirusScanner {
val output = process.inputStream.bufferedReader().readText() val output = process.inputStream.bufferedReader().readText()
val exitCode = process.waitFor() val exitCode = process.waitFor()
// Парсим вывод // Парс вывода
output.lines().forEach { line -> output.lines().forEach { line ->
if (line.contains(" FOUND")) { if (line.contains(" FOUND")) {
val colonIndex = line.indexOf(": ") val colonIndex = line.indexOf(": ")
@@ -411,7 +391,7 @@ class USBVirusScanner {
) )
} catch (e: Exception) { } catch (e: Exception) {
println(if (isDebug) "Ошибка при выполнении clamscan: ${e.message}" else "") println(if (isDebug) "Ошибка при выполнении clamdscan: ${e.message}" else "")
return ScanResult( return ScanResult(
isInfected = false, isInfected = false,
infectedFiles = emptyList(), infectedFiles = emptyList(),
@@ -422,47 +402,6 @@ class USBVirusScanner {
} }
} }
private fun saveScanLog(results: List<ScanResult>) {
try {
val logDir = File("/home/${System.getProperty("user.name")}/usb-scanner-logs")
if (!logDir.exists()) {
logDir.mkdirs()
}
val timestamp = System.currentTimeMillis()
val logFile = File(logDir, "scan_$timestamp.log")
logFile.bufferedWriter().use { writer ->
writer.write("=== USB Virus Scanner Log ===\n")
writer.write("Time: ${java.time.LocalDateTime.now()}\n\n")
results.forEachIndexed { index, result ->
writer.write("Device ${index + 1}:\n")
if (result.isInfected) {
writer.write("Status: INFECTED\n")
writer.write("Found ${result.infectedFiles.size} infected files:\n")
result.infectedFiles.take(20).forEach { file ->
writer.write(" $file: ${result.virusNames[file]}\n")
}
if (result.infectedFiles.size > 20) {
writer.write(" ... and ${result.infectedFiles.size - 20} more files\n")
}
} else if (result.error != null) {
writer.write("Status: ERROR\n")
writer.write("Error: ${result.error}\n")
} else {
writer.write("Status: CLEAN\n")
}
writer.write("\n")
}
}
println(if (isDebug) "📝 Лог сохранён: ${logFile.absolutePath}" else "")
} catch (e: Exception) {
println(if (isDebug) "Ошибка сохранения лога: ${e.message}" else "")
}
}
suspend fun sambaStartSharing() { suspend fun sambaStartSharing() {
try { try {
currentState = SystemState.SAMBA currentState = SystemState.SAMBA
@@ -492,10 +431,9 @@ class USBVirusScanner {
process = processBuilder.start() process = processBuilder.start()
scanJob?.cancel() scanJob?.cancel()
currentState = SystemState.IDLE currentState = SystemState.IDLE
} catch (e: Exception) {} } catch (_: Exception) {}
} }
fun unmount() { fun unmount() {
for (i in 0..9) { for (i in 0..9) {
val path = if (i == 0) "/media/usb" else "/media/usb$i" val path = if (i == 0) "/media/usb" else "/media/usb$i"
@@ -523,17 +461,13 @@ class USBVirusScanner {
scope.cancel() scope.cancel()
// Выключаем все светодиоды
try { try {
if (::greenLed.isInitialized) { if (::greenLed.isInitialized) {
greenLed.setValue(0) greenLed.setValue(0)
yellowLed.setValue(0) yellowLed.setValue(0)
redLed.setValue(0) redLed.setValue(0)
} }
} catch (e: Exception) { } catch (_: Exception) {}
// Игнорируем ошибки при закрытии
}
println(if (isDebug) "✅ Система остановлена" else "") println(if (isDebug) "✅ Система остановлена" else "")
} }
} }
@@ -577,7 +511,7 @@ fun scheduleUpdaterAt3AM() {
TimeUnit.MILLISECONDS TimeUnit.MILLISECONDS
) )
println("Планировщик запущен. Первый запуск через ${initialDelay / 1000 / 60} минут") println(if (isDebug) "Планировщик обновления антивирусных баз запущен." else "")
} }
fun antivirusDatabaseUpdater() { fun antivirusDatabaseUpdater() {
@@ -601,14 +535,7 @@ fun main(args: Array<String>) {
if (args.contains("--debug")) { if (args.contains("--debug")) {
DebugMode.enableDebugging() DebugMode.enableDebugging()
} }
scheduleUpdaterAt3AM() scheduleUpdaterAt3AM()
println(if (isDebug) "Зелёный - ${PinConfig.GREEN_LED}" else "")
println(if (isDebug) "Жёлтый - ${PinConfig.YELLOW_LED}" else "")
println(if (isDebug) "Красный - ${PinConfig.RED_LED}" else "")
println(if (isDebug) "Кнопка - ${PinConfig.BUTTON}" else "")
val scanner = USBVirusScanner() val scanner = USBVirusScanner()
Runtime.getRuntime().addShutdownHook(Thread { Runtime.getRuntime().addShutdownHook(Thread {
@@ -619,37 +546,26 @@ fun main(args: Array<String>) {
scanner.initialize() scanner.initialize()
val buttonListener = ButtonListener() val buttonListener = ButtonListener()
buttonListener.addClickListener { _ ->
buttonListener.addClickListener { event ->
scanner.startScan() scanner.startScan()
} }
buttonListener.addLongPressListener { _ ->
buttonListener.addLongPressListener { event ->
scanner.sambaShutdown() scanner.sambaShutdown()
} }
buttonListener.startListening() buttonListener.startListening()
println( println(
if (isDebug) """ if (isDebug) "!!! ПРОГРАММА ПОЛНОСТЬЮ ГОТОВА К РАБОТЕ !!!" else ""
═══════════════════════════════════════
USB Virus Scanner готов к работе
═══════════════════════════════════════
📌 Вставьте флешку и нажмите кнопку
📌 Зелёный LED мигает - режим ожидания
📌 Жёлтый LED мигает - идёт проверка
📌 Зелёный LED горит - флешка чиста
📌 Красный LED горит - найдены вирусы
📌 Для выхода нажмите Ctrl+C
""".trimIndent() else ""
) )
while (true) { while (true) {
Thread.sleep(1000) Thread.sleep(1000)
} }
} catch (e: Exception) { } catch (e: Exception) {
println(if (isDebug) "Критическая ошибка: ${e.message}" else "") println(if (isDebug) "Критическая ошибка: ${e.message}" else "")
e.printStackTrace() if (isDebug) e.printStackTrace()
if (isDebug) println("Общий Exception")
scanner.shutdown() scanner.shutdown()
exitProcess(1) exitProcess(1)
} }