From 7d69cf5a746903897ed93eaf9ed071ff4dfd4423 Mon Sep 17 00:00:00 2001 From: Beluga737 Date: Fri, 4 Dec 2026 22:22:23 +0700 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B0=D1=81=D0=BF=D0=B8=D1=81=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=98=D0=A1=D0=9F-24/9=20=D1=81=20achtng.?= =?UTF-8?q?ru=20=D0=B8=20=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BA=D0=B0=D1=80=D1=82=D0=BE=D1=87=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/main/AndroidManifest.xml | 1 + .../java/com/example/helponizer/Raspisanie.kt | 228 ++++++++++++++++++ .../example/helponizer/ScheduleRepository.kt | 120 +++++++++ app/src/main/res/layout/activity_main.xml | 1 + .../main/res/layout/activity_raspisanie.xml | 191 ++++----------- app/src/main/res/values/strings.xml | 23 +- 6 files changed, 420 insertions(+), 144 deletions(-) create mode 100644 app/src/main/java/com/example/helponizer/ScheduleRepository.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 329ba74..c269702 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,6 +1,7 @@ + val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) view.setPadding(systemBars.left, systemBars.top, systemBars.right, 0) insets } + + scheduleRetryButton.setOnClickListener { loadSchedule() } + loadSchedule() } override fun onResume() { super.onResume() TextSizeManager.applyTo(findViewById(R.id.main)) } + + override fun onDestroy() { + executor.shutdownNow() + super.onDestroy() + } + + private fun loadSchedule() { + scheduleProgress.visibility = View.VISIBLE + scheduleStatus.visibility = View.GONE + scheduleRetryButton.visibility = View.GONE + scheduleList.removeAllViews() + + executor.execute { + try { + val monday = LocalDate.now().with(DayOfWeek.MONDAY) + val days = ScheduleRepository.fetchWeek(monday, monday.plusDays(5)) + runOnUiThread { renderSchedule(days) } + } catch (e: Exception) { + runOnUiThread { renderError() } + } + } + } + + private fun renderSchedule(days: List) { + scheduleProgress.visibility = View.GONE + scheduleList.removeAllViews() + + if (days.isEmpty()) { + scheduleStatus.visibility = View.VISIBLE + scheduleStatus.setText(R.string.schedule_empty) + scheduleRetryButton.visibility = View.VISIBLE + applyTextSize() + return + } + + for (day in days) { + addDayHeader(day) + for (lesson in day.lessons) { + scheduleList.addView(createLessonCard(lesson)) + } + } + + scheduleStatus.visibility = View.GONE + scheduleRetryButton.visibility = View.GONE + applyTextSize() + } + + private fun renderError() { + scheduleProgress.visibility = View.GONE + scheduleList.removeAllViews() + scheduleStatus.visibility = View.VISIBLE + scheduleStatus.setText(R.string.schedule_error) + scheduleRetryButton.visibility = View.VISIBLE + applyTextSize() + } + + private fun applyTextSize() { + TextSizeManager.applyTo(findViewById(R.id.main)) + } + + private fun addDayHeader(day: ScheduleDay) { + val header = TextView(this).apply { + layoutParams = marginParams(topDp = 18, bottomDp = 8) + text = getString(R.string.schedule_day_header, getString(dayNameRes(day.dayOfWeek)), day.date.format(dayDateFormat)) + setTextColor(resolveColor(com.google.android.material.R.attr.colorOnSurface, Color.BLACK)) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f) + setTypeface(typeface, Typeface.BOLD) + gravity = Gravity.START + } + scheduleList.addView(header) + } + + private fun createLessonCard(lesson: ScheduleLesson): MaterialCardView { + val card = MaterialCardView(this).apply { + layoutParams = marginParams(topDp = 8, bottomDp = 8) + radius = 18f * resources.displayMetrics.density + cardElevation = 1f * resources.displayMetrics.density + strokeWidth = (1 * resources.displayMetrics.density).toInt() + strokeColor = resolveColor(com.google.android.material.R.attr.colorSurfaceVariant, Color.LTGRAY) + setCardBackgroundColor(resolveColor(com.google.android.material.R.attr.colorSurface, Color.WHITE)) + isClickable = false + } + + val content = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(18.dp, 16.dp, 18.dp, 16.dp) + } + + val titleRow = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + } + + titleRow.addView( + TextView(this).apply { + layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) + text = getString(R.string.schedule_pair, lesson.number) + setTextColor(resolveColor(androidx.appcompat.R.attr.colorPrimary, Color.DKGRAY)) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f) + setTypeface(typeface, Typeface.BOLD) + } + ) + + titleRow.addView( + TextView(this).apply { + text = getString(R.string.schedule_time, lesson.startAt, lesson.endAt) + setTextColor(resolveColor(com.google.android.material.R.attr.colorOnSurfaceVariant, Color.DKGRAY)) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f) + } + ) + content.addView(titleRow) + + for (line in lesson.lines) { + content.addView(createLineView(line)) + } + + card.addView(content) + return card + } + + private fun createLineView(line: ScheduleLine): LinearLayout { + val container = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(0, 10.dp, 0, 0) + } + + container.addView( + TextView(this).apply { + text = line.subject.ifBlank { getString(R.string.schedule_unknown) } + setTextColor(resolveColor(com.google.android.material.R.attr.colorOnSurface, Color.BLACK)) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f) + setTypeface(typeface, Typeface.BOLD) + setLineSpacing(3f * resources.displayMetrics.density, 1f) + } + ) + + val room = listOf(line.roomNumber, line.roomName).filter { it.isNotBlank() }.joinToString(" · ") + if (room.isNotBlank()) { + container.addView(metaText(getString(R.string.schedule_room, room))) + } + if (line.teacher.isNotBlank()) { + container.addView(metaText(getString(R.string.schedule_teacher, line.teacher))) + } + if (line.subgroup > 0) { + container.addView(metaText(getString(R.string.schedule_subgroup, line.subgroup))) + } + if (line.lineCode.isNotBlank()) { + container.addView(metaText(getString(R.string.schedule_line, line.lineCode))) + } + if (line.volName.isNotBlank()) { + container.addView(metaText(line.volName)) + } + + return container + } + + private fun metaText(text: String): TextView { + return TextView(this).apply { + this.text = text + setTextColor(resolveColor(com.google.android.material.R.attr.colorOnSurfaceVariant, Color.DKGRAY)) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f) + setLineSpacing(2f * resources.displayMetrics.density, 1f) + setPadding(0, 3.dp, 0, 0) + } + } + + private fun marginParams(topDp: Int, bottomDp: Int): LinearLayout.LayoutParams { + return LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ).apply { + topMargin = topDp.dp + bottomMargin = bottomDp.dp + } + } + + private fun dayNameRes(day: DayOfWeek): Int = when (day) { + DayOfWeek.MONDAY -> R.string.schedule_monday + DayOfWeek.TUESDAY -> R.string.schedule_tuesday + DayOfWeek.WEDNESDAY -> R.string.schedule_wednesday + DayOfWeek.THURSDAY -> R.string.schedule_thursday + DayOfWeek.FRIDAY -> R.string.schedule_friday + DayOfWeek.SATURDAY -> R.string.schedule_saturday + DayOfWeek.SUNDAY -> R.string.schedule_sunday + } + + private fun resolveColor(attr: Int, fallback: Int): Int { + val value = TypedValue() + if (!theme.resolveAttribute(attr, value, true)) return fallback + return if (value.resourceId != 0) ContextCompat.getColor(this, value.resourceId) else value.data + } + + private val Int.dp: Int + get() = (this * resources.displayMetrics.density).toInt() } diff --git a/app/src/main/java/com/example/helponizer/ScheduleRepository.kt b/app/src/main/java/com/example/helponizer/ScheduleRepository.kt new file mode 100644 index 0000000..540e3d0 --- /dev/null +++ b/app/src/main/java/com/example/helponizer/ScheduleRepository.kt @@ -0,0 +1,120 @@ +package com.example.helponizer + +import org.json.JSONArray +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +data class ScheduleLine( + val subject: String, + val roomNumber: String, + val roomName: String, + val teacher: String, + val subgroup: Int, + val lineCode: String, + val volName: String +) + +data class ScheduleLesson( + val number: Int, + val startAt: String, + val endAt: String, + val lines: List +) + +data class ScheduleDay( + val date: LocalDate, + val dayOfWeek: DayOfWeek, + val lessons: List +) + +object ScheduleRepository { + private const val BASE_URL = "https://www.achtng.ru" + private const val GROUP_ID = 10 // ИСП-24/9 + private val dateFormat = DateTimeFormatter.ISO_LOCAL_DATE + + class ScheduleException(message: String) : Exception(message) + + @Throws(ScheduleException::class) + fun fetchWeek(startDate: LocalDate, endDate: LocalDate): List { + val days = mutableListOf() + var totalDays = 0 + var failedDays = 0 + var date = startDate + while (!date.isAfter(endDate)) { + totalDays++ + val day = fetchDay(date) + if (day == null) { + failedDays++ + } else if (day.lessons.isNotEmpty()) { + days.add(day) + } + date = date.plusDays(1) + } + if (days.isEmpty() && totalDays > 0 && failedDays == totalDays) { + throw ScheduleException("Не удалось загрузить расписание с achtng.ru") + } + return days + } + + private fun fetchDay(date: LocalDate): ScheduleDay? { + val url = "$BASE_URL/rest/v1/profile/schedule/g/$GROUP_ID/${date.format(dateFormat)}" + var connection: HttpURLConnection? = null + return try { + connection = URL(url).openConnection() as HttpURLConnection + connection.apply { + requestMethod = "GET" + connectTimeout = 10_000 + readTimeout = 10_000 + setRequestProperty("Accept", "application/json") + setRequestProperty("User-Agent", "Helponizer/1.0") + } + if (connection.responseCode !in 200..299) return null + val body = connection.inputStream.bufferedReader().use { it.readText() } + parseDay(date, body) + } catch (e: Exception) { + null + } finally { + connection?.disconnect() + } + } + + private fun parseDay(date: LocalDate, body: String): ScheduleDay { + val json = JSONObject(body) + val lessons = mutableListOf() + val keys = json.keys() + while (keys.hasNext()) { + val key = keys.next() + val lessonJson = json.optJSONObject(key) ?: continue + val linesJson = lessonJson.optJSONArray("lines") ?: JSONArray() + val lines = mutableListOf() + for (i in 0 until linesJson.length()) { + val line = linesJson.optJSONObject(i) ?: continue + lines.add( + ScheduleLine( + subject = line.optString("subj_name", ""), + roomNumber = line.optString("room_num", ""), + roomName = line.optString("room_name", ""), + teacher = line.optString("employee_name", ""), + subgroup = line.optInt("sub_group", 0), + lineCode = line.optString("line_code", ""), + volName = line.optString("vol_name", "") + ) + ) + } + lessons.add( + ScheduleLesson( + number = key.toIntOrNull() ?: lessons.size + 1, + startAt = lessonJson.optString("start_at", ""), + endAt = lessonJson.optString("end_at", ""), + lines = lines + ) + ) + } + lessons.sortBy { it.number } + return ScheduleDay(date, date.dayOfWeek, lessons) + } +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 8c68fe9..55192b1 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -42,6 +42,7 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" + android:textSize="20sp" android:text="@string/home_title" /> - - + + + android:layout_marginTop="8dp" + android:gravity="center" + android:text="@string/schedule_source_achtng" + android:textColor="?attr/colorOnSurfaceVariant" + android:textSize="13sp" /> - - - - - + + + + + + + - - - - - - + android:orientation="vertical" /> + - - - - - - - - - - - - - - + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e286633..54e3139 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -16,15 +16,26 @@ Расписание занятий + Источник: achtng.ru, группа ИСП-24/9 Понедельник - "1 пара 08:30 - 10:00 \n Информатика \n Кабинет 205" - "2 пара 10:10 - 11:40 \n Математика \n Кабинет 310" Вторник - "1 пара 08:30 - 10:00 \n Основы алгоритмизации \n Кабинет 208" - "2 пара 10:10 - 11:40 \n Разработка приложений \n Кабинет 215" Среда - "1 пара 08:30 - 10:00 \n Базы данных \n Кабинет 212" - "2 пара 10:10 - 11:40 \n Иностранный язык \n Кабинет 305" + Четверг + Пятница + Суббота + Воскресенье + Загружаю расписание… + Не удалось загрузить расписание с achtng.ru + Попробовать снова + На эту неделю пар нет + %1$s, %2$s + %1$d пара + %1$s - %2$s + Кабинет: %1$s + Преподаватель: %1$s + Подгруппа %1$d + Линия: %1$s + Без названия Полезная Информация