misc: init

This commit is contained in:
2026-01-03 16:04:07 -05:00
Unverified
parent b091bd50e8
commit ec2425f2b7
27 changed files with 2470 additions and 709 deletions

View File

@@ -0,0 +1,92 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import api from '../services/api';
import { AuthResponse, User } from '../types';
interface AuthContextType {
user: User | null;
token: string | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (identity: string, password: string, isSuperuser?: boolean) => Promise<void>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
loadAuth();
}, []);
const loadAuth = async () => {
try {
const storedToken = await AsyncStorage.getItem('auth_token');
const storedUser = await AsyncStorage.getItem('auth_user');
if (storedToken && storedUser) {
setToken(storedToken);
api.setToken(storedToken);
setUser(JSON.parse(storedUser));
}
} catch (error) {
console.error('Failed to load auth', error);
} finally {
setIsLoading(false);
}
};
const login = async (identity: string, password: string, isSuperuser = false) => {
try {
const response: AuthResponse = await api.authenticate(identity, password, isSuperuser);
await AsyncStorage.setItem('auth_token', response.token);
await AsyncStorage.setItem('auth_user', JSON.stringify(response.record));
setToken(response.token);
setUser(response.record);
} catch (error) {
throw error;
}
};
const logout = async () => {
try {
await AsyncStorage.removeItem('auth_token');
await AsyncStorage.removeItem('auth_user');
api.clearToken();
setToken(null);
setUser(null);
} catch (error) {
console.error('Failed to logout', error);
}
};
return (
<AuthContext.Provider
value={{
user,
token,
isAuthenticated: !!token && !!user,
isLoading,
login,
logout,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};

245
src/services/api.ts Normal file
View File

@@ -0,0 +1,245 @@
import { Device, AuthResponse, NetworkScanResult } from '../types';
const API_BASE_URL = 'https://wol.f6knight.duckdns.org/api';
class UpSnapAPI {
private token: string | null = null;
setToken(token: string) {
this.token = token;
}
getToken(): string | null {
return this.token;
}
clearToken() {
this.token = null;
}
private getHeaders(): HeadersInit {
const headers: HeadersInit = {
'Content-Type': 'application/json',
};
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
return headers;
}
async authenticate(identity: string, password: string, isSuperuser = false): Promise<AuthResponse> {
const endpoint = isSuperuser
? `${API_BASE_URL}/collections/_superusers/auth-with-password`
: `${API_BASE_URL}/collections/users/auth-with-password`;
const response = await fetch(endpoint, {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Authentication failed');
}
const data: AuthResponse = await response.json();
this.token = data.token;
return data;
}
async getDevices(page = 1, perPage = 30): Promise<Device[]> {
const response = await fetch(
`${API_BASE_URL}/collections/devices/records?page=${page}&perPage=${perPage}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to fetch devices');
}
const data = await response.json();
return data.items;
}
async getDevice(id: string): Promise<Device> {
const response = await fetch(
`${API_BASE_URL}/collections/devices/records/${id}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to fetch device');
}
return response.json();
}
async createDevice(device: Partial<Device>): Promise<Device> {
const response = await fetch(
`${API_BASE_URL}/collections/devices/records`,
{
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(device),
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to create device');
}
return response.json();
}
async updateDevice(id: string, device: Partial<Device>): Promise<Device> {
const response = await fetch(
`${API_BASE_URL}/collections/devices/records/${id}`,
{
method: 'PATCH',
headers: this.getHeaders(),
body: JSON.stringify(device),
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to update device');
}
return response.json();
}
async deleteDevice(id: string): Promise<void> {
const response = await fetch(
`${API_BASE_URL}/collections/devices/records/${id}`,
{
method: 'DELETE',
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to delete device');
}
}
async wakeDevice(id: string): Promise<void> {
const response = await fetch(
`${API_BASE_URL}/upsnap/wake/${id}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to wake device');
}
}
async wakeGroup(id: string): Promise<void> {
const response = await fetch(
`${API_BASE_URL}/upsnap/wakegroup/${id}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to wake group');
}
}
async sleepDevice(id: string): Promise<void> {
const response = await fetch(
`${API_BASE_URL}/upsnap/sleep/${id}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to sleep device');
}
}
async rebootDevice(id: string): Promise<void> {
const response = await fetch(
`${API_BASE_URL}/upsnap/reboot/${id}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to reboot device');
}
}
async shutdownDevice(id: string): Promise<void> {
const response = await fetch(
`${API_BASE_URL}/upsnap/shutdown/${id}`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to shutdown device');
}
}
async scanNetwork(): Promise<NetworkScanResult[]> {
const response = await fetch(
`${API_BASE_URL}/upsnap/scan`,
{
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error('Failed to scan network');
}
const data = await response.json();
console.log('Raw scan data:', data);
if (data.devices && Array.isArray(data.devices)) {
return data.devices.map((item: any) => ({
name: item.name || item.hostname || 'Unknown',
ip: item.ip || item.ip_address || '',
mac: item.mac || item.mac_address || '',
mac_vendor: item.mac_vendor || 'Unknown',
}));
}
if (Array.isArray(data)) {
return data.map((item: any) => ({
name: item.name || item.hostname || 'Unknown',
ip: item.ip || item.ip_address || '',
mac: item.mac || item.mac_address || '',
mac_vendor: item.mac_vendor || 'Unknown',
}));
}
if (data.items && Array.isArray(data.items)) {
return data.items.map((item: any) => ({
name: item.name || item.hostname || 'Unknown',
ip: item.ip || item.ip_address || '',
mac: item.mac || item.mac_address || '',
mac_vendor: item.mac_vendor || 'Unknown',
}));
}
return [];
}
}
export default new UpSnapAPI();

50
src/types/index.ts Normal file
View File

@@ -0,0 +1,50 @@
export interface Device {
id: string;
collectionId: string;
collectionName: string;
name: string;
mac: string;
ip: string;
netmask: string;
broadcast: string;
secureOnPassword: string;
port: number;
groups: string[];
status: string;
created: string;
updated: string;
}
export interface AuthResponse {
token: string;
record: User;
}
export interface User {
id: string;
collectionId: string;
collectionName: string;
username: string;
verified: boolean;
emailVisibility: boolean;
email: string;
created: string;
updated: string;
name: string;
avatar: number;
}
export interface DeviceGroup {
id: string;
name: string;
}
export interface NetworkScanResult {
name?: string;
hostname?: string;
ip?: string;
ip_address?: string;
mac?: string;
mac_address?: string;
mac_vendor?: string;
}