web / frontend /src /lib /storage.ts
Chandima Prabhath
update
beeb302
raw
history blame
6.38 kB
// Updated storage utility with additional functions
// Type for storing watch history and progress
export interface WatchProgress {
currentTime: number;
duration: number;
lastPlayed: string;
completed: boolean;
}
// Type for my list items
export interface MyListItem {
title: string;
type: 'movie' | 'tvshow';
addedAt: string;
posterPath?: string;
backdropPath?: string;
}
/**
* Save video watch progress
*/
export const saveVideoProgress = (
type: 'movie' | 'tvshow',
title: string,
seasonEpisode: string | null,
progress: WatchProgress
): void => {
try {
// Create a unique identifier for the content
const id = seasonEpisode ? `${type}-${title}-${seasonEpisode}` : `${type}-${title}`;
// Get existing watch history
const historyStr = localStorage.getItem('watch-history') || '{}';
const history = JSON.parse(historyStr);
// Update the history with new progress
history[id] = {
...progress,
title,
type,
seasonEpisode,
updatedAt: new Date().toISOString()
};
// Save back to localStorage
localStorage.setItem('watch-history', JSON.stringify(history));
} catch (error) {
console.error('Failed to save video progress:', error);
}
};
/**
* Get video watch progress
*/
export const getVideoProgress = (
type: 'movie' | 'tvshow',
title: string,
seasonEpisode: string | null
): WatchProgress | null => {
try {
// Create a unique identifier for the content
const id = seasonEpisode ? `${type}-${title}-${seasonEpisode}` : `${type}-${title}`;
// Get existing watch history
const historyStr = localStorage.getItem('watch-history') || '{}';
const history = JSON.parse(historyStr);
// Return the progress if it exists
return history[id] || null;
} catch (error) {
console.error('Failed to get video progress:', error);
return null;
}
};
/**
* Get watch history
*/
export const getWatchHistory = (limit: number = 0): Array<any> => {
try {
// Get existing watch history
const historyStr = localStorage.getItem('watch-history') || '{}';
const history = JSON.parse(historyStr);
// Convert object to array and sort by updatedAt (most recent first)
const historyArray = Object.values(history).sort((a: any, b: any) => {
return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
});
// Return all or limited number of items
return limit > 0 ? historyArray.slice(0, limit) : historyArray;
} catch (error) {
console.error('Failed to get watch history:', error);
return [];
}
};
/**
* Clear watch history
*/
export const clearWatchHistory = (): void => {
try {
localStorage.removeItem('watch-history');
} catch (error) {
console.error('Failed to clear watch history:', error);
}
};
/**
* Add item to My List
*/
export const addToMyList = (item: MyListItem): void => {
try {
// Get existing my list
const myListStr = localStorage.getItem('my-list') || '[]';
const myList = JSON.parse(myListStr);
// Check if item already exists
const exists = myList.some((listItem: MyListItem) =>
listItem.title === item.title && listItem.type === item.type
);
// Add item if it doesn't exist
if (!exists) {
myList.push({
...item,
addedAt: new Date().toISOString()
});
// Save back to localStorage
localStorage.setItem('my-list', JSON.stringify(myList));
}
} catch (error) {
console.error('Failed to add item to My List:', error);
}
};
/**
* Remove item from My List
*/
export const removeFromMyList = (title: string, type: 'movie' | 'tvshow'): void => {
try {
// Get existing my list
const myListStr = localStorage.getItem('my-list') || '[]';
const myList = JSON.parse(myListStr);
// Filter out the item
const newList = myList.filter((item: MyListItem) =>
!(item.title === title && item.type === type)
);
// Save back to localStorage
localStorage.setItem('my-list', JSON.stringify(newList));
} catch (error) {
console.error('Failed to remove item from My List:', error);
}
};
/**
* Check if item is in My List
*/
export const isInMyList = (title: string, type: 'movie' | 'tvshow'): boolean => {
try {
// Get existing my list
const myListStr = localStorage.getItem('my-list') || '[]';
const myList = JSON.parse(myListStr);
// Check if item exists
return myList.some((item: MyListItem) =>
item.title === title && item.type === type
);
} catch (error) {
console.error('Failed to check if item is in My List:', error);
return false;
}
};
/**
* Get all items from My List
*/
export const getAllFromMyList = (): Array<MyListItem> => {
try {
// Get existing my list
const myListStr = localStorage.getItem('my-list') || '[]';
return JSON.parse(myListStr);
} catch (error) {
console.error('Failed to get My List:', error);
return [];
}
};
/**
* Clear My List
*/
export const clearMyList = (): void => {
try {
localStorage.removeItem('my-list');
} catch (error) {
console.error('Failed to clear My List:', error);
}
};
// Example of a function that could be replaced with a database implementation
// This can be swapped out with a DB implementation later
export const storageService = {
// Video progress functions
saveVideoProgress,
getVideoProgress,
getWatchHistory,
clearWatchHistory,
// My list functions
addToMyList,
removeFromMyList,
isInMyList,
getAllFromMyList,
clearMyList,
// Generic storage functions that could be replaced
setItem: (key: string, value: any): void => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Failed to store ${key}:`, error);
}
},
getItem: <T>(key: string, defaultValue: T): T => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (error) {
console.error(`Failed to retrieve ${key}:`, error);
return defaultValue;
}
},
removeItem: (key: string): void => {
try {
localStorage.removeItem(key);
} catch (error) {
console.error(`Failed to remove ${key}:`, error);
}
}
};
export default storageService;