Skip to content

Commit

Permalink
supoprt for discord link and banners from query
Browse files Browse the repository at this point in the history
  • Loading branch information
AmyrAhmady committed Jan 4, 2024
1 parent fa858b0 commit 520fc4e
Show file tree
Hide file tree
Showing 5 changed files with 183 additions and 68 deletions.
8 changes: 4 additions & 4 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,16 @@ async fn request_server_rules(ip: &str, port: i32) -> Result<String, String> {
}

#[tauri::command]
async fn request_server_is_omp(ip: &str, port: i32) -> Result<String, String> {
async fn request_server_omp_extra_info(ip: &str, port: i32) -> Result<String, String> {
match query::Query::new(ip, port).await {
Ok(q) => {
let _ = q.send('o').await;
match q.recv().await {
Ok(p) => Ok(format!("{}", p)),
Err(_) => Ok("{\"isOmp\": false}".to_string()),
Err(e) => Err(e.to_string()),
}
}
Err(_) => Ok("{\"isOmp\": false}".to_string()),
Err(e) => Err(e.to_string()),
}
}

Expand Down Expand Up @@ -146,7 +146,7 @@ fn main() {
request_server_info,
request_server_players,
request_server_rules,
request_server_is_omp,
request_server_omp_extra_info,
ping_server,
inject,
get_gtasa_path_from_samp,
Expand Down
45 changes: 43 additions & 2 deletions src-tauri/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ impl Default for Player {
}
}

#[derive(Serialize, Deserialize, Clone)]
pub struct ExtraInfoPacket {
pub discord_link: String,
pub light_banner_url: String,
pub dark_banner_url: String,
}

impl Default for ExtraInfoPacket {
fn default() -> Self {
Self {
discord_link: String::new(),
light_banner_url: String::new(),
dark_banner_url: String::new(),
}
}
}

impl Query {
pub async fn new(addr: &str, port: i32) -> Result<Self, std::io::Error> {
let regex = Regex::new(r"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$").unwrap();
Expand Down Expand Up @@ -108,7 +125,7 @@ impl Query {
packet.push((self.port >> 8 & 0xFF) as u8);
packet.push(query_type as u8);

if query_type == 'p' || query_type == 'o' {
if query_type == 'p' {
packet.push(0);
packet.push(0);
packet.push(0);
Expand Down Expand Up @@ -145,7 +162,7 @@ impl Query {
} else if query_type == 'r' {
self.build_rules_packet(packet)
} else if query_type == 'o' {
Ok(String::from("{\"isOmp\": true}"))
self.build_extra_info_packet(packet)
} else if query_type == 'p' {
Ok(String::from("pong"))
} else {
Expand Down Expand Up @@ -178,6 +195,30 @@ impl Query {
Ok(serde_json::to_string(&data).unwrap())
}

fn build_extra_info_packet(
&self,
mut packet: Cursor<Vec<u8>>,
) -> Result<String, std::io::Error> {
let mut data = ExtraInfoPacket::default();

let discord_link_len = packet.read_u32::<LittleEndian>().unwrap();
let mut discord_link_buf = vec![0u8; discord_link_len as usize];
packet.read_exact(&mut discord_link_buf).unwrap();
data.discord_link = helpers::decode_buffer(discord_link_buf).0;

let mut banner_url_len = packet.read_u32::<LittleEndian>().unwrap();
let mut banner_url_buf = vec![0u8; banner_url_len as usize];
packet.read_exact(&mut banner_url_buf).unwrap();
data.light_banner_url = helpers::decode_buffer(banner_url_buf).0;

banner_url_len = packet.read_u32::<LittleEndian>().unwrap();
banner_url_buf = vec![0u8; banner_url_len as usize];
packet.read_exact(&mut banner_url_buf).unwrap();
data.dark_banner_url = helpers::decode_buffer(banner_url_buf).0;

Ok(serde_json::to_string(&data).unwrap())
}

fn build_players_packet(&self, mut packet: Cursor<Vec<u8>>) -> Result<String, std::io::Error> {
let player_count = packet.read_u16::<LittleEndian>().unwrap();
let default_player = Player::default();
Expand Down
98 changes: 72 additions & 26 deletions src/containers/MainBody/ServerInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import AdditionalInfo from "./AdditionalInfo";
import PlayerList from "./PlayerList";

const ServerInfo = () => {
const { theme } = useTheme();
const { theme, themeType } = useTheme();
const { selected } = useServers();

const webUrl = useMemo(() => {
Expand All @@ -24,32 +24,59 @@ const ServerInfo = () => {
return "";
}, [selected]);

const bannerUrl = useMemo(() => {
if (selected) {
if (selected.omp) {
const dark = selected.omp.bannerDark;
const light = selected.omp.bannerLight;
if (themeType === "dark") {
if (dark) {
return dark;
} else {
if (light) {
return light;
} else {
return "";
}
}
} else {
if (light) {
return light;
} else {
if (dark) {
return dark;
} else {
return "";
}
}
}
}
}
return "";
}, [selected?.omp, themeType]);

return (
<View style={styles.serverInfoView}>
<PlayerList players={selected ? selected.players : []} />
<View
style={{
width: "100%",
height: selected?.omp && selected.omp.banner ? "12%" : sc(35),
marginVertical: sc(8),
height: bannerUrl.length ? "11.5%" : sc(35),
marginTop: sc(8),
marginBottom: sc(2),
borderRadius: sc(5),
overflow: "hidden",
}}
>
{selected?.omp && selected.omp.banner ? (
<Image
source={{ uri: selected.omp.banner }}
style={{
position: "absolute",
top: 0,
left: 0,
height: "100%",
width: "100%",
}}
/>
) : null}
{webUrl.length ? (
<div
title={webUrl}
style={{
width: "100%",
height: "100%",
}}
>
<Pressable
disabled={webUrl.length < 1}
style={{
alignItems: "center",
width: "100%",
Expand All @@ -61,17 +88,36 @@ const ServerInfo = () => {
shell.open(webUrl.includes("http") ? webUrl : "https://" + webUrl)
}
>
<Icon svg image={images.icons.link} size={sc(29)} />
<Text
semibold
size={1}
color={theme.textPrimary}
style={{ marginLeft: sc(5) }}
>
{webUrl}
</Text>
{bannerUrl.length ? (
<Image
source={{ uri: bannerUrl }}
style={{
position: "absolute",
top: 0,
left: 0,
height: "100%",
width: "100%",
}}
/>
) : (
<>
{webUrl.length ? (
<>
<Icon svg image={images.icons.link} size={sc(29)} />
<Text
semibold
size={1}
color={theme.textPrimary}
style={{ marginLeft: sc(5) }}
>
{webUrl}
</Text>
</>
) : null}
</>
)}
</Pressable>
) : null}
</div>
</View>
<AdditionalInfo server={selected} />
</View>
Expand Down
97 changes: 62 additions & 35 deletions src/utils/query.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { invoke } from "@tauri-apps/api";
import { usePersistentServers, useServers } from "../states/servers";
import { ListType, Server } from "./types";
import { Log } from "./logger";
import { ListType, Server } from "./types";

const OMP_EXTRA_INFO_CHECK_DELAY = 5000; // 10 seconds;
const ompExtraInfoLastCheck: { [x: string]: number } = {};

export const queryServer = (
server: Server,
Expand All @@ -17,7 +20,16 @@ export const queryServer = (

if (queryType === "all") {
getServerPlayers(ip, port, listType);
// getServerOmpStatus(ip, port, listType);
if (ompExtraInfoLastCheck[`${ip}:${port}`]) {
if (
Date.now() - ompExtraInfoLastCheck[`${ip}:${port}`] >
OMP_EXTRA_INFO_CHECK_DELAY
) {
getServerOmpExtraInfo(ip, port, listType);
}
} else {
getServerOmpExtraInfo(ip, port, listType);
}
}
} catch (error) {
Log.debug("[query.ts: queryServer]", error);
Expand Down Expand Up @@ -51,7 +63,6 @@ const getServerInfo = async (ip: string, port: number, listType: ListType) => {
let server = getServerFromList(ip, port, listType);
if (server) {
server = { ...server, ...data };

updateServerEveryWhere(server);
}
} catch (e) {
Expand Down Expand Up @@ -137,38 +148,54 @@ const getServerRules = async (ip: string, port: number, listType: ListType) => {
}
};

// const getServerOmpStatus = async (
// ip: string,
// port: number,
// listType: ListType
// ) => {
// try {
// const serverOmpStatus = await invoke<string>("request_server_is_omp", {
// ip: ip,
// port: port,
// });

// let server = getServerFromList(ip, port, listType);
// if (server) {
// if (
// serverOmpStatus === "no_data" ||
// JSON.parse(serverOmpStatus).isOmp == undefined
// ) {
// server = { ...server, usingOmp: false };
// updateServerEveryWhere(server);
// return;
// }

// if (!server.usingOmp) {
// server = {
// ...server,
// usingOmp: JSON.parse(serverOmpStatus).isOmp as boolean,
// };
// updateServerEveryWhere(server);
// }
// }
// } catch (e) {}
// };
const getServerOmpExtraInfo = async (
ip: string,
port: number,
listType: ListType
) => {
ompExtraInfoLastCheck[`${ip}:${port}`] = Date.now();

try {
const serverOmpExtraInfo = await invoke<string>(
"request_server_omp_extra_info",
{
ip: ip,
port: port,
}
);

console.log(serverOmpExtraInfo);

let server = getServerFromList(ip, port, listType);
if (server) {
if (serverOmpExtraInfo === "no_data") {
return;
}

const data = JSON.parse(serverOmpExtraInfo);
if (data) {
server = {
...server,
omp: {
bannerLight:
data.light_banner_url && data.light_banner_url.length
? data.light_banner_url
: undefined,
bannerDark:
data.dark_banner_url && data.dark_banner_url.length
? data.dark_banner_url
: undefined,
discordInvite:
data.discord_link && data.discord_link.length
? data.discord_link
: undefined,
},
};
updateServerEveryWhere(server);
}
}
} catch (e) {}
};

const getServerPing = async (ip: string, port: number, listType: ListType) => {
try {
Expand Down
3 changes: 2 additions & 1 deletion src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ export interface Server {
players: Player[];
password: string;
omp?: {
banner?: string;
bannerLight?: string;
bannerDark?: string;
discordInvite?: string;
discordStatus?: {
appId: string;
Expand Down

0 comments on commit 520fc4e

Please sign in to comment.