Browse Source

rewrite update scripts Wiki for API support

Dmitriev Roman 2 months ago
parent
commit
a42440b827
2 changed files with 76 additions and 75 deletions
  1. 39 11
      scripts/utils/wiki/update_eye_wiki.pl
  2. 37 64
      scripts/utils/wiki/update_wiki_eye.pl

+ 39 - 11
scripts/utils/wiki/update_eye_wiki.pl

@@ -15,7 +15,7 @@ no warnings 'utf8';
 use strict;
 use English;
 use FindBin '$Bin';
-use lib "$Bin/";
+use lib "/opt/Eye/scripts";
 use Data::Dumper;
 use eyelib::config;
 use File::Find;
@@ -37,16 +37,22 @@ my $api_key  = $config_ref{api_key}  || die "Ошибка: не настроен
 my $api_login = $config_ref{api_login} || die "Ошибка: не настроен параметр api_login в конфигурации\n";
 
 # Базовые параметры аутентификации для всех запросов
-my $auth_params = "api_key=" . uri_escape($api_key) . "&login=" . uri_escape($api_login);
+my $auth_params = "api_key=" . uri_escape($api_key) . "&api_login=" . uri_escape($api_login);
 
 # Инициализация HTTP-клиента
 my $ua = LWP::UserAgent->new(
     timeout => 30,
-    agent   => 'WikiSync/1.0'
+    agent   => 'EyeWikiSync/1.0'
 );
 
+my $api_request_url = $api_base."?".$auth_params;
+
+my $option_filter = encode_json({ option_id => '61' });
+
 # === Получение пути к вики из таблицы config (id=61) ===
-my $config_record = api_call('GET', "$api_base?get_table_record&table=config&id=61&$auth_params");
+my $api_request = $api_request_url."&get=table_record&table=config&filter=".uri_escape($option_filter);
+
+my $config_record = api_call('GET', $api_request);
 if (!$config_record || $config_record->{error}) {
     die "Ошибка: не удалось получить путь к вики из таблицы config (id=61)\n";
 }
@@ -90,7 +96,7 @@ foreach my $fname (sort keys %content) {
     next unless $ip && is_valid_ipv4($ip);
 
     # Получение записи из БД через API
-    my $auth = api_call('GET', "$api_base/user_auth.php?get=user_auth&ip=" . uri_escape($ip) . "&$auth_params");
+    my $auth = api_call('GET', $api_request_url. "&get=user_auth&ip=" . uri_escape($ip));
     if (!$auth || $auth->{error}) {
         print "Запись не найдена для IP $ip (файл: $fname)\n";
         next;
@@ -98,20 +104,19 @@ foreach my $fname (sort keys %content) {
 
     # Обновление поля WikiName через метод обновления user_auth
     my $update_data = {
-        wiki_name => $fname  # Используем нижний регистр как принято в БД
+        wikiname => $fname
     };
 
     my $json_data = encode_json($update_data);
-    my $update_url = "$api_base/user_auth.php?send=update_user_auth&id=$auth->{id}&$auth_params";
-    
+    my $update_url = $api_request_url. "&send=update_user_auth&id=$auth->{id}";
     my $update_req = HTTP::Request->new(POST => $update_url);
     $update_req->header('Content-Type' => 'application/json');
     $update_req->content($json_data);
-    
+
     my $update_res = $ua->request($update_req);
-    
+
     if ($update_res->is_success) {
-        my $result = decode_json(decode_utf8($update_res->decoded_content));
+        my $result = decode_json($update_res->decoded_content);
         if (!$result->{error}) {
             print "Обновлено: id=$auth->{id} IP=$ip => WikiName=$fname\n";
             $updated++;
@@ -132,3 +137,26 @@ print "Ошибок: $errors\n";
 print "Синхронизация завершена.\n";
 
 exit 0;
+
+sub api_call {
+    my ($method, $url) = @_;
+    my $req = HTTP::Request->new($method => $url);
+    my $res = $ua->request($req);
+    return undef unless $res->is_success;
+    return decode_json($res->decoded_content);
+}
+
+sub wanted {
+    my $filename = $File::Find::name;
+    my $dev_name = basename($filename);
+    if ($dev_name =~ /\.txt$/ && $dev_name =~ /^(Device|Switch|Ups|Sensor|Gateway|Router|Server|Bras)/) {
+        $dev_name =~ s/\.txt$//;
+        $content{$dev_name} = $filename;
+    }
+    return;
+}
+
+sub is_valid_ipv4 {
+    my ($ip) = @_;
+    return $ip =~ /^([0-9]{1,3}\.){3}[0-9]{1,3}$/ && !grep { $_ > 255 } split(/\./, $ip);
+}

+ 37 - 64
scripts/utils/wiki/update_wiki_eye.pl

@@ -13,8 +13,8 @@ no warnings 'utf8';
 
 use strict;
 use English;
+use lib "/opt/Eye/scripts";
 use FindBin '$Bin';
-use lib "$Bin/";
 use eyelib::config;
 use Data::Dumper;
 use File::Find;
@@ -35,17 +35,23 @@ my $api_base = $config_ref{api_base} || 'http://localhost/api.php';
 my $api_key  = $config_ref{api_key}  || die "Ошибка: не настроен параметр api_key в конфигурации\n";
 my $api_login = $config_ref{api_login} || die "Ошибка: не настроен параметр api_login в конфигурации\n";
 
+# Базовые параметры аутентификации для всех запросов
+my $auth_params = "api_key=" . uri_escape($api_key) . "&api_login=" . uri_escape($api_login);
+
 # Инициализация HTTP-клиента
 my $ua = LWP::UserAgent->new(
-    timeout => 60,
-    agent   => 'EyeWikiUpdater/1.0'
+    timeout => 30,
+    agent   => 'EyeWikiSync/1.0'
 );
 
-# Базовые параметры аутентификации для всех запросов
-my $auth_params = "api_key=" . uri_escape($api_key) . "&login=" . uri_escape($api_login);
+my $api_request_url = $api_base."?".$auth_params;
+
+my $option_filter = encode_json({ option_id => '61' });
 
 # === Получение пути к вики из таблицы config (id=61) ===
-my $config_record = api_call('GET', "$api_base?get_table_record&table=config&id=61&$auth_params");
+my $api_request = $api_request_url."&get=table_record&table=config&filter=".uri_escape($option_filter);
+
+my $config_record = api_call('GET', $api_request);
 if (!$config_record || $config_record->{error}) {
     die "Ошибка: не удалось получить путь к вики из таблицы config (id=61)\n";
 }
@@ -65,6 +71,7 @@ my $processed = 0;
 my $errors    = 0;
 
 foreach my $fname (sort keys %content) {
+    print "Analyze $content{$fname}...";
     # Чтение файла
     open(my $fh, '<:encoding(UTF-8)', $content{$fname}) or do {
         warn "Не удалось открыть файл $content{$fname}: $!\n";
@@ -85,17 +92,18 @@ foreach my $fname (sort keys %content) {
             }
         }
     }
+    print "IP not found!\n" and next unless $ip && is_valid_ipv4($ip);
 
-    next unless $ip && is_valid_ipv4($ip);
+    print "$ip \n";
 
     # Получение записи из user_auth по IP через API
-    my $auth = api_call('GET', "$api_base/user_auth.php?get=user_auth&ip=" . uri_escape($ip) . "&$auth_params");
-    if (!$auth || $auth->{error} || !$auth->{WikiName}) {
+    my $auth = api_call('GET', $api_request_url. "&get=user_auth&ip=" . uri_escape($ip));
+    if (!$auth || $auth->{error} || !$auth->{wikiname}) {
         next;
     }
 
     # Пропускаем шлюзы
-    next if $auth->{WikiName} =~ /^Gateway/;
+    next if $auth->{wikiname} =~ /^Gateway/;
 
     print "Found: $auth->{ip} $auth->{mac} ";
 
@@ -104,72 +112,42 @@ foreach my $fname (sort keys %content) {
 
     # Определение типа устройства и получение родительских данных
     eval {
-        if ($auth->{WikiName} =~ /^(Switch|Router)/) {
+        if ($auth->{wikiname} =~ /^(Switch|Router)/) {
             # Для коммутаторов/маршрутизаторов: получаем данные через цепочку устройств
-            my $device = api_call('GET', "$api_base/user_auth.php?get_table_list&table=devices&filter=" . 
-                uri_escape(encode_json({ ip => $ip })) . "&$auth_params");
-            
-            die "Unknown device" unless $device && ref($device) eq 'ARRAY' && @{$device} > 0;
-            $device = $device->[0];
-            
+            my $device = api_call('GET', $api_request_url. "&get=table_record&table=devices&filter=" . uri_escape(encode_json({ ip => $ip })));
+            die "Unknown device" unless $device;
             # Получаем аплинк-порт
-            my $uplink_ports = api_call('GET', "$api_base/user_auth.php?get_table_list&table=device_ports&filter=" . 
-                uri_escape(encode_json({ device_id => $device->{id}, uplink => 1 })) . "&$auth_params");
-            
-            die "Unknown connection" unless $uplink_ports && ref($uplink_ports) eq 'ARRAY' && @{$uplink_ports} > 0;
-            my $parent_connect = $uplink_ports->[0];
-            
+            my $uplink_ports = api_call('GET', $api_request_url . "&get=table_record&table=device_ports&filter=" . uri_escape(encode_json({ device_id => $device->{id}, uplink => 1 })));
+            die "Unknown connection" unless $uplink_ports;
+            my $parent_connect = $uplink_ports;
             # Получаем целевой порт
-            my $parent_port = api_call('GET', "$api_base/user_auth.php?get_table_record&table=device_ports&id=" . 
-                $parent_connect->{target_port_id} . "&$auth_params");
-            
+            my $parent_port = api_call('GET', $api_request_url . "&get=table_record&table=device_ports&id=" . $parent_connect->{target_port_id});
             die "Unknown port connection" unless $parent_port;
-            
             # Получаем родительское устройство
-            my $device_parent = api_call('GET', "$api_base/user_auth.php?get_table_record&table=devices&id=" . 
-                $parent_port->{device_id} . "&$auth_params");
-            
+            my $device_parent = api_call('GET', $api_request_url . "&get=table_record&table=devices&id=" . $parent_port->{device_id});
             die "Unknown parent device" unless $device_parent;
-            
             # Получаем авторизацию родительского устройства
-            my $auth_parent = api_call('GET', "$api_base/user_auth.php?get=user_auth&ip=" . 
-                uri_escape($device_parent->{ip}) . "&$auth_params");
-            
-            die "Unknown auth for device" unless $auth_parent && $auth_parent->{WikiName};
-            
-            $device_name  = $auth_parent->{WikiName};
+            my $auth_parent = api_call('GET', $api_request_url . "&get=user_auth&ip=" . uri_escape($device_parent->{ip}));
+            die "Unknown auth for device" unless $auth_parent && $auth_parent->{wikiname};
+            $device_name  = $auth_parent->{wikiname};
             $device_port  = $parent_port->{port};
         }
         else {
             # Для других устройств: получаем данные через соединения
-            my $connections = api_call('GET', "$api_base/user_auth.php?get_table_list&table=connections&filter=" . 
-                uri_escape(encode_json({ auth_id => $auth->{id} })) . "&$auth_params");
-            
-            die "Unknown connection" unless $connections && ref($connections) eq 'ARRAY' && @{$connections} > 0;
-            my $conn = $connections->[0];
-            
+            my $conn = api_call('GET', $api_request_url . "&get=table_record&table=connections&filter=" . uri_escape(encode_json({ auth_id => $auth->{id} })));
+            die "Unknown connection" unless $conn;
             # Получаем порт устройства
-            my $device_port_rec = api_call('GET', "$api_base/user_auth.php?get_table_record&table=device_ports&id=" . 
-                $conn->{port_id} . "&$auth_params");
-            
+            my $device_port_rec = api_call('GET', $api_request_url . "&get=table_record&table=device_ports&id=" . $conn->{port_id});
             die "Unknown device port" unless $device_port_rec;
-            
             # Получаем устройство
-            my $device = api_call('GET', "$api_base/user_auth.php?get_table_record&table=devices&id=" . 
-                $device_port_rec->{device_id} . "&$auth_params");
-            
+            my $device = api_call('GET', $api_request_url . "&get=table_record&table=devices&id=" . $device_port_rec->{device_id});
             die "Unknown device" unless $device && $device->{user_id};
-            
             # Получаем авторизацию устройства по user_id и IP
-            my $device_auth_list = api_call('GET', "$api_base/user_auth.php?get_table_list&table=user_auth&filter=" . 
-                uri_escape(encode_json({ user_id => $device->{user_id}, ip => $device->{ip} })) . "&$auth_params");
-            
+            my $device_auth_list = api_call('GET', $api_request_url . "&get=table_list&table=user_auth&filter=" . uri_escape(encode_json({ user_id => $device->{user_id}, ip => $device->{ip} })));
             die "Unknown device auth" unless $device_auth_list && ref($device_auth_list) eq 'ARRAY' && @{$device_auth_list} > 0;
             my $device_auth = $device_auth_list->[0];
-            
-            die "Device auth has no WikiName" unless $device_auth->{WikiName};
-            
-            $device_name = $device_auth->{WikiName};
+            die "Device auth has no wikiname" unless $device_auth->{wikiname};
+            $device_name = $device_auth->{wikiname};
             $device_port = $device_port_rec->{port};
         }
     };
@@ -248,14 +226,10 @@ exit 0;
 
 sub api_call {
     my ($method, $url) = @_;
-    
     my $req = HTTP::Request->new($method => $url);
     my $res = $ua->request($req);
-    
     return undef unless $res->is_success;
-    
-    my $content = decode_utf8($res->decoded_content);
-    return decode_json($content);
+    return decode_json($res->decoded_content);
 }
 
 sub is_valid_ipv4 {
@@ -267,7 +241,6 @@ sub is_valid_ipv4 {
 sub wanted {
     my $filename = $File::Find::name;
     my $dev_name = basename($filename);
-    
     if ($dev_name =~ /\.txt$/ && $dev_name =~ /^(Device|Switch|Ups|Sensor|Gateway|Router|Server|Bras)/) {
         $dev_name =~ s/\.txt$//;
         $content{$dev_name} = $filename;