1
0
Fork 0

Compare commits

...

13 Commits

7 changed files with 804 additions and 397 deletions

View File

@ -1,2 +1,50 @@
# parser_from_interneturok # parser_from_interneturok
Chat-robot Telegram for parsing homeworks by subject name, grade and number of the week
## Funny story of development
The customer of this project **refused to pay** the second half of the payment for the work and wanted to steal my code.<br>
<br>
I managed to delete all the code from the server, then i changed passwords on all **40 accounts** that were planned to be used in this chat-robot.<br>
Thus **i destroyed the entire mini-business** of this customer.
## Dependencies
1. [PHP 8.4](https://www.php.net/releases/8.4/en.php)
2. [Composer](https://getcomposer.org/) (php package manager)
3. [MINIMAL](https://git.svoboda.works/mirzaev/minimal) (PHP framework)
5. [Zanzara](https://github.com/badfarm/zanzara) (Telegram framework + ReactPHP)
6. [Baza](https://git.svoboda.works/mirzaev/baza) (binary database)
7. [NGINX](https://nginx.org/en/) (web server) *(can be replaced)*
8. [SystemD](https://systemd.io/) (service manager) *(can be replaced)*
<small>You can find other dependencies in the file `/composer.json`</small>
## Installation
### SystemD (or any alternative you like)
You can copy an example of systemd file from here: `/examples/systemd/ parser_from_interneturok-telegram.service`<br><br>
**Execute:** `sudo cp parser_from_interneturok-telegram.service /etc/systemd/system/ parser_from_interneturok-telegram.service && sudo chmod +x /etc/systemd/system/ parser_from_interneturok-telegram.service`<br><br>
*before you execute the command think about **what it does** and whether the **paths** are specified correctly*<br>
*the configuration file is very simple and you can remake it for any alternative to SystemD that you like*
### InternetUrok accounts
Fill in the file: `/mirzaev/parser_from_interneturok/system/storage/accounts.csv`<br><br>
**Format:** "mail password" (**separated by 1 space symbol**)
```CSV
mail password
mail password
mail password
```
### Authorized Telegram accounts
Fill in the file: `/mirzaev/parser_from_interneturok/system/settings/accounts.php`
```php
return [
1053489457, // Arsen Mirzaev Tatyano-Muradovich @redloser
]
```
<small>You can get the telegram account identifier by [@RawDataBot](https://t.me/RawDataBot)</small>
### Chat-robot Telegram token
Fill in the file: `/mirzaev/parser_from_interneturok/system/settings/telegram.php`<br>
<small>You can get the chat-robot telegram token by [@BotFather](https://t.me/BotFather)</small>

View File

@ -5,7 +5,7 @@ Wants=network.target
After=syslog.target network-online.target After=syslog.target network-online.target
[Service] [Service]
ExecStart=sudo -u www-data /usr/bin/php /var/www/project/mirzaev/parser_from_interneturok/system/public/telegram.php ExecStart=sudo -u www-data /usr/bin/php /var/www/parser_from_interneturok/mirzaev/parser_from_interneturok/system/public/telegram.php
PIDFile=/var/run/php/parser_from_interneturok-telegram.pid PIDFile=/var/run/php/parser_from_interneturok-telegram.pid
RemainAfterExit=no RemainAfterExit=no
RuntimeMaxSec=3600s RuntimeMaxSec=3600s

View File

@ -70,6 +70,17 @@ final class interneturok extends core
*/ */
public const string USER = 'https://api-gw.interneturok.ru/api/v2/homeschool/current_user'; public const string USER = 'https://api-gw.interneturok.ru/api/v2/homeschool/current_user';
/**
* TARIFFS
*
* Method: GET
* Authrorization: Bearer
*
* @var const string TARIFFS The user tariffs API URL
*/
public const string TARIFFS = 'https://api-gw.interneturok.ru/api/v2/schedules/users/current/tariffs';
/** /**
* SCHEDULES * SCHEDULES
* *
@ -163,11 +174,12 @@ final class interneturok extends core
* *
* @param subject $subject The subject * @param subject $subject The subject
* @param int $grade The grade * @param int $grade The grade
* @param datetime $date The date
* @param int $waiting Interval for processing requests (seconds) * @param int $waiting Interval for processing requests (seconds)
* *
* @return array|false Downloaded homework files * @return array|false Downloaded homework files
*/ */
public function parse(subject $subject, int $grade, int $waiting = 3): array|false public function parse(subject $subject, int $grade, datetime $date, int $week, int $waiting = 3): array|false
{ {
// Initializing accounts // Initializing accounts
$accounts = static::accounts(); $accounts = static::accounts();
@ -175,151 +187,144 @@ final class interneturok extends core
if (!empty($accounts)) { if (!empty($accounts)) {
// Initialized accounts // Initialized accounts
/* if (shuffle($accounts)) { */ if (shuffle($accounts)) {
// Shuffled accounts // Shuffled accounts
foreach ($accounts as $account) { foreach ($accounts as $account) {
// Iterating over accounts // Iterating over accounts
// Waiting for processing the request
sleep($waiting);
if ($this->authentication($account)->wait()) {
// Authenticated the account
// Writing into the output buffer
echo 'Аутентифицирован: ' . $account['mail'] . "\n";
// Waiting for processing the request // Waiting for processing the request
sleep($waiting); sleep($waiting);
// Initializing the user journal try {
$journal = $this->journal(grade: $grade)->wait(); if ($this->authentication($account)->wait()) {
// Authenticated the account
if (!empty($journal)) { // Writing into the output buffer
// Initialized the user journal echo 'Аутентифицирован: ' . $account['mail'] . "\n";
// Writing into the output buffer // Waiting for processing the request
echo "Инициализирован журнал\n"; sleep($waiting);
// Initializing the actual date // Initializing the user journal
$date = new datetime(); $journal = $this->journal(grade: $grade, week: $week)->wait();
// Initializing the homeworks database if (!empty($journal)) {
$model = new homework(); // Initialized the user journal
// Initializing the schedule subject events // Writing into the output buffer
$schedule = $journal?->schedule_events; echo "Инициализирован журнал\n";
foreach ($schedule as $_subject) { // Initializing the homeworks database
// Iterating over scheduled subject events $model = new homework();
if ($_subject->subject?->name === $subject->value) { // Initializing the schedule subject events
// Found the target suject $schedule = $journal?->schedule_events;
foreach ($_subject->events as $event) { foreach ($schedule as $_subject) {
// Iterating over the target subject events // Iterating over scheduled subject events
// Normalizing the event variable (events can be more than one) if ($_subject->subject?->name === $subject->value) {
$event = $event[0] ?? null; // Found the target suject
if (!empty($event)) { foreach ($_subject->events as $event) {
// Initialized the target subject event (the homework exists) // Iterating over the target subject events
if (new datetime($event->date) <= $date && new datetime($event->date)->modify('+6 days') >= $date) { // Normalizing the event variable (events can be more than one)
// Found the current event $event = $event[0] ?? null;
if ($event->subject?->name === $subject->value && $event->subject->grade === $grade) { if (!empty($event)) {
// Found the target subject // Initialized the target subject event (the homework exists)
// Writing into the output buffer if (new datetime($event->date) <= $date && new datetime($event->date)->modify('+6 days') >= $date) {
echo "Найден школьный предмет: $subject->value для $grade класса (с " . new datetime($event->date)->format('d.m') . ' по ' . new datetime($event->date)->modify('+6 days')->format('d.m') . ")\n"; // Found the target event week
// Initializing the unblock time if ($event->subject?->name === $subject->value && $event->subject->grade === $grade) {
$unblock = svoboda::timestamp() - 31536000; // Found the target subject
foreach ($event->homeworks as $homework) { // Writing into the output buffer
// Iterating over scheduled event homeworks echo "Найден школьный предмет: $subject->value для $grade класса (с " . new datetime($event->date)->format('d.m') . ' по ' . new datetime($event->date)->modify('+6 days')->format('d.m') . ")\n";
if ($homework->status === 'checked' && $homework->mark === 5) { // Initializing the current time
// Homework checked and completed for a grade of 5 $now = svoboda::timestamp();
// Checking for the block record foreach ($event->homeworks as $homework) {
$blocked = $model->database->read( // Iterating over scheduled event homeworks
filter: fn(record $record) => $record->identifier === $homework->item_id && $record->created > $unblock,
amount: 1
)[0] ?? null;
if ($blocked instanceof record) { if ($homework->status === 'checked' && $homework->mark === 5) {
// The account homework has been downloaded for 1 year // Homework checked and completed for a grade of 5
continue 3;
} else {
// The account homework has not been downloaded for 1 year
// Writing into the output buffer
echo "Найдено домашнее задание: $homework->item_id с оценкой $homework->mark\n";
// Waiting for processing the request
sleep($waiting);
// Initializing the homework files
$files = $this->homework(lesson: $event->lesson->id, homework: $homework->item_id)->wait();
if (!empty($files)) {
// Initialized the homework files
// Writing into the output buffer // Writing into the output buffer
echo "Получено домашнее задание\n"; echo "Найдено домашнее задание: $homework->item_id с оценкой $homework->mark\n";
// Blocking the homework downloading for 1 year // Waiting for processing the request
$blocked = $model->create(identifier: $homework->item_id); sleep($waiting);
if ($blocked !== false) { // Initializing the homework files
// The homework was blocked for 1 year $files = $this->homework(lesson: $event->lesson->id, homework: $homework->item_id)->wait();
// Writing into the output buffer if (!empty($files)) {
echo "Заблокировано на 1 год домашнее задание\n"; // Initialized the homework files
// Writing into the output buffer
echo "Получено домашнее задание\n";
// Declaring the homework downloads for 1 last year counter
$year = 0;
// Counting the homework downloading for 1 last year
$model->database->read(
filter: function (record $record) use ($homework, $now, &$year) {
if ($record->identifier === $homework->item_id && $now - $record->created < 31536000) {
// Found a downloading for 1 last year
// Increasing the homework downloads for 1 last year counter
++$year;
}
// Exit (success)
return false;
},
amount: 100
);
// Writing the homework downloading record
$model->create(identifier: $homework->item_id);
// Exit (success) // Exit (success)
return $files; return ['downloads' => ['year' => $year], 'files' => $files];
} }
} }
} }
} }
} }
} }
// Stopping processing events and starting processing the next account
break 2;
} }
} }
} }
} else {
// Not initialized the user journal
// Stopping processing events and starting processing the next account // Writing into the output buffer
break; echo "Аккаунт не подходит под требования\n";
// Proceed to processing the next account
continue;
} }
} else {
// Not authenticated the account
// Writing into the output buffer
echo "Не аутентифицирован\n";
// Proceed to processing the next account
continue;
} }
} else { } catch (exception $exception) {
// Not initialized the user journal
// Writing into the output buffer
echo "Аккаунт не подходит под требования\n";
// Proceed to processing the next account
continue; continue;
} }
} else {
// Not authenticated the account
// Writing into the output buffer
echo "Не аутентифицирован\n";
// Proceed to processing the next account
continue;
} }
} }
/* } */
} }
// Exit (fail) // Exit (fail)
@ -453,10 +458,11 @@ final class interneturok extends core
* Search for the user homeworks journal * Search for the user homeworks journal
* *
* @param int $grade The grade * @param int $grade The grade
* @param int $week Number of the week
* *
* @return promise|null The journal data (object) * @return promise|null The journal data (object)
*/ */
private function journal(int $grade): promise|null private function journal(int $grade, int $week): promise|null
{ {
if (!empty($this->token)) { if (!empty($this->token)) {
// Initialized the account authorization token // Initialized the account authorization token
@ -471,141 +477,159 @@ final class interneturok extends core
); );
return $this->browser->sendAsync($request) return $this->browser->sendAsync($request)
->then(function ($response) use ($grade) { ->then(function ($response) use ($grade, $week) {
// Sended the request and received the response // Sended the request and received the response
// Initializing the user data // Initializing the user data
$user = json_decode((string) $response->getBody())?->data?->homeschool?->response?->user; $user = json_decode((string) $response->getBody())?->data?->homeschool?->response?->user;
if ($user->grade + 1 === $grade) { if (!empty($user)) {
// Matched the account grade with the grade // Initialized the user data
// Initialiint the user identifier // Initializing the request to the user data API
$identifier = $user?->id; $request = new request(
'GET',
static::TARIFFS,
[
'Authorization' => "Bearer $this->token"
]
);
if (!empty($identifier)) { return $this->browser->sendAsync($request)
// Initialized the user identifier ->then(function ($response) use ($grade, $week, $user) {
// Sended the request and received the response
// Initializing the request to the user schedules API // Initializing the tariffs data
$request = new request( $tariffs = json_decode((string) $response->getBody())?->data?->tariffs?->response;
'GET',
static::SCHEDULES,
[
'Authorization' => "Bearer $this->token"
]
);
return $this->browser->sendAsync($request) foreach ($tariffs as $tariff) {
->then(function ($response) use ($grade, $identifier) { // Iterating over tariffs
// Sended the request and received the response
// Initializing the user schedules if ($tariff->grade === $grade) {
$schedules = json_decode((string) $response->getBody())?->data?->schedules?->response?->data; // Matched the tariff grade with the target grade
// Initializing the study years registry // Initializing the user identifier
$years = $schedules?->study_years; $identifier = $user?->id;
if (!empty($years)) { if (!empty($identifier)) {
// Initialized the study years registry // Initialized the user identifier
foreach ($years as $year) { // Initializing the request to the user schedules API
// Iterating over study years $request = new request(
'GET',
static::SCHEDULES,
[
'Authorization' => "Bearer $this->token"
]
);
if ($year->status === 'current') { return $this->browser->sendAsync($request)
// The current study year ->then(function ($response) use ($grade, $identifier, $week) {
// Sended the request and received the response
// Initializing the request to the moscow time API // Initializing the user schedules
$request = new request( $schedules = json_decode((string) $response->getBody())?->data?->schedules?->response?->data;
'GET',
static::TIME,
[
'Authorization' => "Bearer $this->token"
]
);
return $this->browser->sendAsync($request) // Initializing the study years registry
->then(function ($response) use ($grade, $identifier, $year) { $years = $schedules?->study_years;
// Sended the request and received the response
// Initializing the moscow time if (!empty($years)) {
$time = json_decode((string) $response->getBody())?->data?->time?->response; // Initialized the study years registry
if (!empty($time)) { foreach ($years as $year) {
// Initialized the moscow time // Iterating over study years
// Implementing the moscow time if ($year->status === 'current') {
$now = new datetime($time); // The current study year
// Declaring the quarter buffer // Initializing the request to the moscow time API
$quarter = null; $request = new request(
'GET',
static::TIME,
[
'Authorization' => "Bearer $this->token"
]
);
foreach ($year->quarters as $value) { return $this->browser->sendAsync($request)
// Iterating over study year quarters ->then(function ($response) use ($grade, $identifier, $year, $week) {
// Sended the request and received the response
// Implementing the quarter start time and end time // Initializing the moscow time
$start = new datetime($value->starts_at); $time = json_decode((string) $response->getBody())?->data?->time?->response;
$end = new datetime($value->ends_at);
if ($now > $start && $now < $end) { if (!empty($time)) {
// Found the current quarter // Initialized the moscow time
// Writing the current quarter identifier into the quarter buffer // Implementing the moscow time
$quarter = $value->quarter; $now = new datetime($time);
// Stopping iterating over study year quarters // Declaring the quarter buffer
break; $quarter = static::quarter(number: $week);
}
if ($quarter !== false) {
// Initialized number of the quarter
// Initializing the request to the user journal API
$request = new request(
'GET',
static::JOURNAL . "?grade=$grade&quarter=$quarter&year_id=$year->id&user_id=$identifier&token=$this->token"
);
return $this->browser->sendAsync($request)
->then(function ($response) {
// Sended the request and received the response
// Initializing the user journal
$journal = json_decode((string) $response->getBody());
if (!empty($journal)) {
// Initialized the user journal
// Exit (success)
return $journal;
} else {
// Not initialized the user journal
// Exit (fail)
return false;
}
})->wait();
} else {
// Not initialized number of the quarter
// Exit (fail)
return false;
}
} else {
// Not initialized the moscow time
// Exit (fail)
return false;
}
})->wait();
} }
// Initializing the request to the user journal API
$request = new request(
'GET',
static::JOURNAL . "?grade=$grade&quarter=$quarter&year_id=$year->id&user_id=$identifier&token=$this->token"
);
return $this->browser->sendAsync($request)
->then(function ($response) {
// Sended the request and received the response
// Initializing the user journal
$journal = json_decode((string) $response->getBody());
if (!empty($journal)) {
// Initialized the user journal
// Exit (success)
return $journal;
} else {
// Not initialized the user journal
// Exit (fail)
return false;
}
})->wait();
} else {
// Not initialized the moscow time
// Exit (fail)
return false;
} }
})->wait(); } else {
} // Not initialized the study years registry
// Exit (fail)
return false;
}
})->wait();
} else {
// Not initialized the user identifier
// Exit (fail)
return false;
} }
} else {
// Not initialized the study years registry
// Exit (fail)
return false;
} }
})->wait(); }
} else { // Exit (fail)
// Not initialized the user identifier return false;
});
// Exit (fail)
return false;
}
} else { } else {
// Not matched the account grade with the grade // Not initialized the user data
// Exit (fail) // Exit (fail)
return false; return false;
@ -642,124 +666,29 @@ final class interneturok extends core
); );
return $this->browser->sendAsync($request) return $this->browser->sendAsync($request)
->then(function ($response) use ($homework) { ->then(
// Sended the request and received the response function ($response) use ($homework) {
// Sended the request and received the response
// Initializing the lesson // Initializing the lesson
$lesson = json_decode((string) $response->getBody())?->data?->homeschool?->response; $lesson = json_decode((string) $response->getBody())?->data?->homeschool?->response;
foreach ($lesson->items as $section) { foreach ($lesson->items as $section) {
// Iterating over the lesson sections // Iterating over the lesson sections
if ($section->id === $homework && $section->item_type === 'homework' && $section->homework_kind === 'homework_base') { if ($section->id === $homework && $section->item_type === 'homework' && $section->homework_kind === 'homework_base') {
// Found the base homework section // Found the base homework section
// Initializng the test identifier (string) // Initializng the test identifier (string)
$test = $section->homework_attributes?->parsed_content?->evo_test_id ?? null; $test = $section->homework_attributes?->parsed_content?->evo_test_id ?? null;
if (!empty($test)) { if (!empty($test)) {
// Initialized the test identifier // Initialized the test identifier
// Initializing the request to the test data API
$request = new request(
'GET',
static::TESTS . "/$test/result",
[
'Authorization' => "Bearer $this->token"
]
);
return $this->browser->sendAsync($request)
->then(function ($response) use ($homework) {
// Sended the request and received the response
// Initializing the test result
$result = json_decode((string) $response->getBody())?->data?->tests?->response?->data;
if (!empty($result)) {
// Initialized the test result
// Initializing paths to the homework storage folder
$storage = STORAGE . DIRECTORY_SEPARATOR . 'homeworks' . DIRECTORY_SEPARATOR . $homework;
// Initializing the homework storage folder
if (!file_exists($storage)) mkdir($storage, 0775, true);
// Initializing the excel document
$excel = excel::create(['Домашнее задание']);
// Initializing the excel document sheet
$sheet = $excel->sheet();
// Writing settings of the excel document sheet
$sheet->setColWidths(['A' => 10, 'B' => 80, 'C' => 50]);
// Writing title
$sheet->writeRow(
['Номер', 'Задание', 'Ответ'],
[
'font' => [
'style' => 'bold'
],
'text-align' => 'center',
'vertical-align' => 'center',
'border' => 'thin',
'height' => 24,
]
);
foreach ($result->test?->questions as $question) {
// Iterating over questions
foreach ($question->answer_results as $answer) {
// Iterating over question answers
if ($answer->is_correct) {
// The answer is correct
if (!empty($answer->section)) {
// Several sections for answers (expected)
// Writing questions and answers
$sheet->writeRow([$question->test_question_position, $question->name, $answer->section->name . ' - ' . $answer->value]);
} else {
// One single answer (expected)
// Writing questions and answers
$sheet->writeRow([$question->test_question_position, $question->name, $answer->value]);
}
}
}
}
// Initializing path to the excel document file
$path = $storage . DIRECTORY_SEPARATOR . 'homework.xlsx';
// Writing the excel document file to the storage
$excel->save($path);
// Exit (success)
return [$path];
} else {
// Not initialized the test result
// Exit (fail)
return false;
}
})->wait();
} else {
// Not initialized the test identifier
// Initializing the attachment identifier
$attachment = $section->result?->id;
if (!empty($attachment)) {
// Initialized the attachment identifier
// Initializing the request to the test data API // Initializing the request to the test data API
$request = new request( $request = new request(
'GET', 'GET',
static::ATTACHMENTS . "?attachable_id=$attachment&attachable_type=Result::Homework", static::TESTS . "/$test/result",
[ [
'Authorization' => "Bearer $this->token" 'Authorization' => "Bearer $this->token"
] ]
@ -769,71 +698,179 @@ final class interneturok extends core
->then(function ($response) use ($homework) { ->then(function ($response) use ($homework) {
// Sended the request and received the response // Sended the request and received the response
// Initializing attachments // Initializing the test result
$attachments = json_decode((string) $response->getBody())?->data?->homeschool?->response?->attachments; $result = json_decode((string) $response->getBody())?->data?->tests?->response?->data;
if (!empty($attachments)) { if (!empty($result)) {
// Initialized attachmetns // Initialized the test result
// Initializing paths to the homework attachments storage folder // Initializing paths to the homework storage folder
$storage = STORAGE . DIRECTORY_SEPARATOR . 'homeworks' . DIRECTORY_SEPARATOR . $homework . DIRECTORY_SEPARATOR . 'attachments'; $storage = STORAGE . DIRECTORY_SEPARATOR . 'homeworks' . DIRECTORY_SEPARATOR . $homework;
// Initializing the homework attachments storage folder // Initializing the homework storage folder
if (!file_exists($storage)) mkdir($storage, 0775, true); if (!file_exists($storage)) mkdir($storage, 0775, true);
// Declaring the buffer of files // Initializing the excel document
$files = []; $excel = excel::create(['Домашнее задание']);
foreach ($attachments as $attachment) { // Initializing the excel document sheet
// Iteration over attachments $sheet = $excel->sheet();
if ($attachment->uploader_role === 'student' && $attachment->attachable_type === 'Result::Homework') { // Writing settings of the excel document sheet
// Found the homework attachment $sheet->setColWidths(['A' => 10, 'B' => 80, 'C' => 50]);
// Initializing path to the downloaded file // Writing title
$path = $storage . DIRECTORY_SEPARATOR . $attachment->attach_path; $sheet->writeRow(
['Номер', 'Задание', 'Ответ'],
[
'font' => [
'style' => 'bold'
],
'text-align' => 'center',
'vertical-align' => 'center',
'border' => 'thin',
'height' => 24,
]
);
// Downloading the file foreach ($result->test?->questions as $question) {
$this->browser->request('GET', $attachment->attach, ['sink' => $path]); // Iterating over questions
// Writing path to the downloaded file into the buffer of files foreach ($question->answer_results as $answer) {
$files[] = $path; // Iterating over question answers
if ($answer->is_correct) {
// The answer is correct
if (!empty($answer->section)) {
// Several sections for answers (expected)
// Writing questions and answers
$sheet->writeRow([$question->test_question_position, $question->name, $answer->section->name . ' - ' . $answer->value]);
} else {
// One single answer (expected)
// Writing questions and answers
$sheet->writeRow([$question->test_question_position, $question->name, $answer->value]);
}
}
} }
} }
// Initializing path to the excel document file
$path = $storage . DIRECTORY_SEPARATOR . 'homework.xlsx';
// Writing the excel document file to the storage
$excel->save($path);
// Exit (success) // Exit (success)
return $files; return [$path];
} else { } else {
// Not initialized attachments // Not initialized the test result
// Exit (fail) // Exit (fail)
return false; return false;
} }
})->wait(); })->wait();
} else { } else {
// Not initialized the attachment identifier // Not initialized the test identifier
// Exit (fail) // Initializing the attachment identifier
return false; $attachment = $section->result?->id;
if (!empty($attachment)) {
// Initialized the attachment identifier
// Initializing the request to the test data API
$request = new request(
'GET',
static::ATTACHMENTS . "?attachable_id=$attachment&attachable_type=Result::Homework",
[
'Authorization' => "Bearer $this->token"
]
);
return $this->browser->sendAsync($request)
->then(function ($response) use ($homework) {
// Sended the request and received the response
// Initializing attachments
$attachments = json_decode((string) $response->getBody())?->data?->homeschool?->response?->attachments;
if (!empty($attachments)) {
// Initialized attachmetns
// Initializing paths to the homework attachments storage folder
$storage = STORAGE . DIRECTORY_SEPARATOR . 'homeworks' . DIRECTORY_SEPARATOR . $homework . DIRECTORY_SEPARATOR . 'attachments';
// Initializing the homework attachments storage folder
if (!file_exists($storage)) mkdir($storage, 0775, true);
// Declaring the buffer of files
$files = [];
foreach ($attachments as $attachment) {
// Iteration over attachments
if ($attachment->uploader_role === 'student' && $attachment->attachable_type === 'Result::Homework') {
// Found the homework attachment
// Searching for number of the attachment and the file extension
preg_match('/^(\d+).*(\.\w{3,4})$/', $attachment->attach_path, $matches);
try {
// Initializing the name of the attachment file
$name = $matches[1] . $matches[2];
} catch (exception $exception) {
// Initializing the name of the attachment file
$name = uniqid() . '.jpg';
}
// Initializing path to the downloaded file
$path = $storage . DIRECTORY_SEPARATOR . ($name ?? uniqid() . '.jpg');
// Downloading the file
$this->browser->request('GET', $attachment->attach, ['sink' => $path]);
// Writing path to the downloaded file into the buffer of files
$files[] = $path;
}
}
// Exit (success)
return $files;
} else {
// Not initialized attachments
// Exit (fail)
return false;
}
})->wait();
} else {
// Not initialized the attachment identifier
// Exit (fail)
return false;
}
} }
} }
} }
}
// Exit (fail) // Exit (fail)
return false; return false;
}, },
function ($response) use ($homework) { function ($exception) use ($homework) {
if ($response->getStatusCode() === 402) { if ($exception->getResponse()?->getStatusCode() === 402) {
// Fail (received the "Payment Required" status code) // Fail (received the "Payment Required" status code)
// Writing into the output buffer // Writing into the output buffer
echo "Не удалось скачать домашнее задание $homework потому, что не оплачен тариф\n"; echo "Не удалось скачать домашнее задание $homework потому, что не оплачен тариф\n";
}
// Exit (fail) // Exit (fail)
return false; return false;
} }
}); );
} }
// Exit (fail) // Exit (fail)
@ -898,16 +935,70 @@ final class interneturok extends core
*/ */
public static function amount(): int public static function amount(): int
{ {
// Opening the interneturok accounts file try {
$file = new spl(INTERNETUROK_ACCOUNTS_FILE, 'r'); // Opening the interneturok accounts file
$file = new spl(INTERNETUROK_ACCOUNTS_FILE, 'r');
// Move the cursor to the last row // Move the cursor to the last row
$file->seek(PHP_INT_MAX); $file->seek(PHP_INT_MAX);
// Initializing number of the last row // Initializing number of the last row
$rows = $file->key(); $rows = $file->key();
// Exit (success)
return $rows;
} catch (exception $exception) {
// Exit (fail)
return 0;
}
}
/**
* Week
*
* Generate datetime by number of the week (by 6 days)
*
* @param int $number Number of the week
*
* @return datetime The date
*/
public static function week(int $number = 2): datetime
{
// Initializing the date
$date = new datetime('first day of september last year');
// Normalizing number of the week
if ($number < 2) $number = 2;
else if ($number > 37) $number = 37;
// Offsetting number of the week for calculating
$number = $number - 1;
// Calculating days for offsetting the date
$days = 6 * $number;
// Exit (success) // Exit (success)
return $rows; return $date->modify("+$days days +$number days");
}
/**
* Quarter
*
* Generate number of the quarter by number of the week
*
* @param int $number Number of the week
*
* @return int|false Number of the quarter
*/
public static function quarter(int $number = 2): int|false
{
// Exit (success)
return match (true) {
$number >= 2 && $number <= 9 => 1,
$number >= 11 && $number <= 18 => 2,
$number >= 21 && $number <= 30 => 3,
$number >= 32 && $number <= 38 => 4,
default => false
};
} }
} }

View File

@ -17,6 +17,10 @@ use Zanzara\Context as context,
// Framework for asynchronous PHP // Framework for asynchronous PHP
use function React\Async\await; use function React\Async\await;
// Built-in libraries
use Exception as exception,
DateTime as datetime;
/** /**
* Telegram shcool subjects parser * Telegram shcool subjects parser
* *
@ -49,7 +53,9 @@ final class parser extends core
// Initializing the parsing target buffer // Initializing the parsing target buffer
$target = [ $target = [
'subject' => $subject, 'subject' => $subject,
'grade' => null 'grade' => null,
'date' => null,
'week' => null
]; ];
// Writing to the telegram user buffer // Writing to the telegram user buffer
@ -111,7 +117,7 @@ final class parser extends core
/** /**
* Grade * Grade
* *
* Write grade to the buffer and request confirmation for starting the parsing process * Write grade to the buffer and request date
* *
* @param context $context Request data from Telegram * @param context $context Request data from Telegram
* @param int $grade The grade * @param int $grade The grade
@ -131,6 +137,207 @@ final class parser extends core
// Initializing the grade // Initializing the grade
$target['grade'] = $grade; $target['grade'] = $grade;
// Writing to the telegram user buffer
$context->setUserDataItem(static::PROCESS, $target)
->then(function () use ($context, $target) {
// Writed to the telegram user buffer
// Sending the message
$context->sendMessage(
'📅 *Выберите номер недели*',
[
'reply_markup' => [
'inline_keyboard' => [
[
[
'text' => '2',
'callback_data' => 'week_2'
],
[
'text' => '3',
'callback_data' => 'week_3'
],
[
'text' => '4',
'callback_data' => 'week_4'
],
[
'text' => '5',
'callback_data' => 'week_5'
],
[
'text' => '6',
'callback_data' => 'week_6'
],
[
'text' => '7',
'callback_data' => 'week_7'
],
[
'text' => '8',
'callback_data' => 'week_8'
],
[
'text' => '9',
'callback_data' => 'week_9'
]
],
[
[
'text' => '11',
'callback_data' => 'week_11'
],
[
'text' => '12',
'callback_data' => 'week_12'
],
[
'text' => '13',
'callback_data' => 'week_13'
],
[
'text' => '14',
'callback_data' => 'week_14'
],
[
'text' => '15',
'callback_data' => 'week_15'
],
[
'text' => '16',
'callback_data' => 'week_16'
],
[
'text' => '17',
'callback_data' => 'week_17'
],
[
'text' => '18',
'callback_data' => 'week_18'
]
],
[
[
'text' => '21',
'callback_data' => 'week_21'
],
[
'text' => '22',
'callback_data' => 'week_22'
],
[
'text' => '23',
'callback_data' => 'week_23'
],
[
'text' => '24',
'callback_data' => 'week_24'
],
[
'text' => '25',
'callback_data' => 'week_25'
]
],
[
[
'text' => '26',
'callback_data' => 'week_26'
],
[
'text' => '27',
'callback_data' => 'week_27'
],
[
'text' => '28',
'callback_data' => 'week_28'
],
[
'text' => '29',
'callback_data' => 'week_29'
],
[
'text' => '30',
'callback_data' => 'week_30'
]
],
[
[
'text' => '32',
'callback_data' => 'week_32'
],
[
'text' => '33',
'callback_data' => 'week_33'
],
[
'text' => '34',
'callback_data' => 'week_34'
],
[
'text' => '35',
'callback_data' => 'week_35'
],
[
'text' => '36',
'callback_data' => 'week_36'
],
[
'text' => '37',
'callback_data' => 'week_37'
],
[
'text' => '38',
'callback_data' => 'week_38'
]
]
],
'disable_notification' => true,
'remove_keyboard' => true
]
]
);
});
} else {
// Not initialized the parsing process
// Sending the message
$context->sendMessage('⚠️ *Не запущен процесс генерации парсинга*')
->then(function (message $message) use ($context) {
// Sended the message
// Sending the menu with subjects
commands::menu($context);
});
}
});
}
/**
* Date
*
* Write date and request confirmation for starting the parsing process
*
* @param context $context Request data from Telegram
* @param int $week Number of the week
*
* @return void
*/
public static function date(context $context, int $week): void
{
// Reading from the telegram user buffer
$context->getUserDataItem(static::PROCESS)
->then(function (?array $target) use ($context, $week) {
// Readed from the telegram user buffer
if ($target) {
// Initialized the parsing process
// Initializing the week
$target['week'] = $week;
// Initializing the date
$target['date'] = interneturok::week($week);
// Writing to the telegram user buffer // Writing to the telegram user buffer
$context->setUserDataItem(static::PROCESS, $target) $context->setUserDataItem(static::PROCESS, $target)
->then(function () use ($context, $target) { ->then(function () use ($context, $target) {
@ -142,14 +349,21 @@ final class parser extends core
// Initializing the grade // Initializing the grade
$grade = $target['grade']; $grade = $target['grade'];
// Reinigitlizing the date
$date = $target['date']->format('Y\\\.m\\\.d');
// Inigitlizing number the week
$week = $target['week'];
// Sending the message // Sending the message
$context->sendMessage( $context->sendMessage(
<<<TXT <<<TXT
📦 *Генерация запроса* 📦 *Генерация запроса*
*Предмет:* $subject *Предмет:* $subject
*Класс:* $grade *Класс:* $grade
TXT, *Дата:* $date \($week\)
TXT,
[ [
'reply_markup' => [ 'reply_markup' => [
'inline_keyboard' => [ 'inline_keyboard' => [
@ -198,40 +412,71 @@ final class parser extends core
if ($target) { if ($target) {
// Initialized the parsing process // Initialized the parsing process
// Initializing variables for the parsing process // Sending the message
$subject = $target['subject']; $context->sendMessage('⚡️ *Запущен процесс парсинга домашнего задания*')
$grade = $target['grade']; ->then(function (message $message) use ($context, $target) {
// Sended the message
// Initializing the parser // Initializing variables for the parsing process
$parser = new interneturok(); $subject = $target['subject'];
$grade = $target['grade'];
$date = $target['date'];
$week = $target['week'];
// Parsing homework files // Initializing the parser
$files = $parser->parse(subject: $subject, grade: $grade, waiting: 0); $parser = new interneturok();
if (!empty($files)) { try {
// Initialized homework files // Parsing homework
$homework = $parser->parse(subject: $subject, grade: $grade, date: $date, week: $week, waiting: 2);
foreach ($files as $file) { if (!empty($homework)) {
// Iterating over files in the storage // Initialized homework
// Sending the file foreach ($homework['files'] as $file) {
await($context->sendDocument(new file_input($file))); // Iterating over homework files in the storage
}
// Deleting in the telegram user buffer // Sending the file
$context->deleteUserDataItem(static::PROCESS); await($context->sendDocument(new file_input($file)));
} else { }
// Not initialized homework files
// Sending the message if ($homework['downloads']['year'] <= 100) {
$context->sendMessage('❌ *Не найдены домашние задания') // The homework was downloadsd 100 or less times for 1 last year
->then(function (message $message) use ($context) {
// Sended the message
// Sending the menu with subjects // Sending the message
commands::menu($context); $context->sendMessage('Домашнее задание было скачано *' . $homework['downloads']['year'] . ' раз* за последний год');
}); } else {
} // The homework was downloaded more than 100 times for 1 last year
// Sending the message
$context->sendMessage('Домашнее задание было скачано *более чем 100 раз*) за последний год');
}
// Deleting in the telegram user buffer
$context->deleteUserDataItem(static::PROCESS);
} else {
// Not initialized homework files
// Sending the message
$context->sendMessage('❌ *Не найдены домашние задания*')
->then(function (message $message) use ($context) {
// Sended the message
// Sending the menu with subjects
commands::menu($context);
});
}
} catch (exception $exception) {
// Sending the message
$context->sendMessage('⚠️ *Произошла ошибка при обработке домашних заданий*')
->then(function (message $message) use ($context) {
// Sended the message
// Sending the menu with subjects
commands::menu($context);
});
}
});
} else { } else {
// Not initialized the parsing process // Not initialized the parsing process

View File

@ -32,9 +32,6 @@ define('VIEWS', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'view
// Initializing path to the directory of settings // Initializing path to the directory of settings
define('SETTINGS', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'settings'); define('SETTINGS', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'settings');
// Initializing system settings
require SETTINGS . DIRECTORY_SEPARATOR . 'system.php';
// Initializing path to the directory of the storage // Initializing path to the directory of the storage
define('STORAGE', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'storage'); define('STORAGE', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'storage');
@ -83,6 +80,34 @@ for ($i = 4; $i <= 11; ++$i) {
$robot->onCbQueryData(["grade_$i"], fn(context $context) => parser::grade(context: $context, grade: $i)); $robot->onCbQueryData(["grade_$i"], fn(context $context) => parser::grade(context: $context, grade: $i));
} }
for ($i = 32; $i <= 38; ++$i) {
// Generating buttons from 32 to 38 numbers of weeks
// Initializing numbers of weeks buttons
$robot->onCbQueryData(["week_$i"], fn(context $context) => parser::date(context: $context, week: $i));
}
for ($i = 21; $i <= 30; ++$i) {
// Generating buttons from 21 to 30 numbers of weeks
// Initializing numbers of weeks buttons
$robot->onCbQueryData(["week_$i"], fn(context $context) => parser::date(context: $context, week: $i));
}
for ($i = 11; $i <= 18; ++$i) {
// Generating buttons from 11 to 18 numbers of weeks
// Initializing numbers of weeks buttons
$robot->onCbQueryData(["week_$i"], fn(context $context) => parser::date(context: $context, week: $i));
}
for ($i = 2; $i <= 9; ++$i) {
// Generating buttons from 2 to 9 numbers of weeks
// Initializing numbers of weeks buttons
$robot->onCbQueryData(["week_$i"], fn(context $context) => parser::date(context: $context, week: $i));
}
// Initializing the parse button // Initializing the parse button
$robot->onCbQueryData(['parse'], [parser::class, 'parse']); $robot->onCbQueryData(['parse'], [parser::class, 'parse']);

View File

@ -5,5 +5,7 @@
*/ */
return [ return [
1053489457 // Arsen Mirzaev Tatyano-Muradovich @redloser 1053489457, // Arsen Mirzaev Tatyano-Muradovich @redloser
6831961323, // @IU_K1LLER777
1142807069 // @kysakapro
]; ];

View File

@ -1,4 +0,0 @@
<?php
// Initializing default theme for the views templater
define('THEME', 'default');