Files
intaleq/loction_server/api_get_nearby.php
T

131 lines
5.1 KiB
PHP
Executable File

<?php
// api_get_nearby.php (Updated)
require_once __DIR__ . '/vendor/autoload.php';
use Predis\Client;
header('Content-Type: application/json');
function getInternalKey(): string {
$envKey = getenv('INTERNAL_SOCKET_KEY');
if ($envKey) return trim($envKey);
$path = getenv('INTERNAL_SOCKET_KEY_PATH');
if ($path && file_exists($path)) return trim((string)@file_get_contents($path));
if (file_exists(__DIR__ . '/../loction-keys/.internal_socket_key')) return trim((string)@file_get_contents(__DIR__ . '/../loction-keys/.internal_socket_key'));
if (file_exists('/keys/.internal_socket_key')) return trim((string)@file_get_contents('/keys/.internal_socket_key'));
if (file_exists('/home/location/.internal_socket_key')) return trim((string)@file_get_contents('/home/location/.internal_socket_key'));
return '';
}
function getRedisPass(): ?string {
$envPass = getenv('REDIS_MAIN_PASSWORD') ?: ($_ENV['REDIS_MAIN_PASSWORD'] ?? (getenv('REDIS_PASSWORD') ?: ($_ENV['REDIS_PASSWORD'] ?? null)));
if ($envPass) return trim($envPass);
$path = getenv('REDIS_PASS_KEY_PATH');
if ($path && file_exists($path)) return trim((string)@file_get_contents($path));
if (file_exists('/keys/.reds_pass_key')) return trim((string)@file_get_contents('/keys/.reds_pass_key'));
if (file_exists('/home/location/.reds_pass_key')) return trim((string)@file_get_contents('/home/location/.reds_pass_key'));
return null;
}
$INTERNAL_KEY = getInternalKey();
$PASS_REDIS = getRedisPass();
$headers = getallheaders();
$receivedKey = $headers['x-internal-key'] ?? $_SERVER['HTTP_X_INTERNAL_KEY'] ?? '';
if (!empty($INTERNAL_KEY) && $receivedKey !== $INTERNAL_KEY) {
error_log("[api_get_nearby] Unauthorized: receivedKey ($receivedKey) != expectedKey ($INTERNAL_KEY)");
http_response_code(403);
echo json_encode(['status' => false, 'msg' => 'Unauthorized']);
exit;
}
$lat = $_REQUEST['lat'] ?? null;
$lng = $_REQUEST['lng'] ?? null;
$radius = $_REQUEST['radius'] ?? 5;
$limit = $_REQUEST['limit'] ?? 100;
if (!$lat || !$lng) {
echo json_encode(['status' => false, 'msg' => 'Invalid Coordinates']); exit;
}
try {
$redisHost = getenv('REDIS_HOST') ?: ($_ENV['REDIS_HOST'] ?? (file_exists('/.dockerenv') ? 'redis' : '127.0.0.1'));
$redisConfig = [
'scheme' => 'tcp',
'host' => $redisHost,
'port' => 6379,
'database' => 0
];
if (!empty($PASS_REDIS)) {
$redisConfig['password'] = $PASS_REDIS;
}
$redis = new Client($redisConfig);
$redis->connect();
// 🔥 التعديل هنا: إضافة WITHCOORD لجلب الإحداثيات من الريدز مباشرة
$geoResults = $redis->georadius(
'geo:drivers:available',
$lng, $lat, $radius, 'km',
['WITHDIST' => true, 'WITHCOORD' => true, 'COUNT' => $limit * 2, 'SORT' => 'ASC']
);
$validDrivers = [];
$currentTime = time();
$max_silence = 300;
foreach ($geoResults as $res) {
// هيكل النتيجة مع WITHCOORD يختلف قليلاً
$d_id = $res[0]; // ID
$d_dist = $res[1]; // Distance
$d_coord= $res[2]; // [0=>lng, 1=>lat] 🔥 الإحداثيات هنا
$profile = $redis->hgetall("driver:profile:$d_id");
$lastUpdate = isset($profile['updated_at']) ? (int)$profile['updated_at'] : 0;
if (empty($profile)) {
error_log("[api_get_nearby] Driver $d_id skipped: profile is empty in Redis.");
$redis->zrem('geo:drivers:available', $d_id);
$redis->zrem('geo:drivers:busy', $d_id);
continue;
}
if (($currentTime - $lastUpdate) > $max_silence) {
error_log("[api_get_nearby] Driver $d_id skipped: lastUpdate ($lastUpdate) is older than max_silence ($max_silence).");
$redis->zrem('geo:drivers:available', $d_id);
$redis->zrem('geo:drivers:busy', $d_id);
continue;
}
// 🆕 فحص driver:public cache (بيانات السائق الثابتة)
$public = $redis->hgetall("driver:public:$d_id");
$hasCache = !empty($public) && !empty($public['first_name']);
$validDrivers[] = $hasCache ? array_merge($public, [
'id' => $d_id,
'driver_id' => $d_id,
'latitude' => $d_coord[1],
'longitude' => $d_coord[0],
'heading' => $profile['heading'] ?? $public['heading'] ?? 0,
'speed' => $profile['speed'] ?? $public['speed'] ?? 0,
'distance' => $d_dist,
'cached' => true
]) : [
'id' => $d_id,
'driver_id' => $d_id,
'distance' => $d_dist,
'heading' => $profile['heading'] ?? 0,
'speed' => $profile['speed'] ?? 0,
'latitude' => $d_coord[1],
'longitude' => $d_coord[0],
'cached' => false
];
if (count($validDrivers) >= $limit) break;
}
echo json_encode(['status' => true, 'data' => $validDrivers]);
} catch (Exception $e) {
echo json_encode(['status' => false, 'msg' => $e->getMessage()]);
}
?>