364 lines
9.6 KiB
TypeScript
364 lines
9.6 KiB
TypeScript
import type { User } from '../shell/shell';
|
|
import { MD5 } from '../util/hash';
|
|
|
|
export class FileSystem {
|
|
static #instance: FileSystem;
|
|
private _fs: Map<number, TreeNode>;
|
|
private _root: number;
|
|
|
|
private constructor(fs: Map<number, TreeNode>) {
|
|
this._fs = fs;
|
|
this._root = this._fs.values().next().value!.inode;
|
|
|
|
if (!this._root) throw new Error('First entry in the filesystem map empty!');
|
|
}
|
|
|
|
public static async Init() {
|
|
let fsJson: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
|
|
const fsChecksum = MD5.hash(JSON.stringify(fsJson));
|
|
|
|
const cache: string | null = localStorage.getItem('fs-json');
|
|
if (cache) {
|
|
const fsCacheChecksum = MD5.hash(cache);
|
|
|
|
console.log(fsChecksum);
|
|
console.log(fsCacheChecksum);
|
|
|
|
if (fsChecksum !== fsCacheChecksum) {
|
|
//calculate version control difference to preserve user made changes (do a merge)
|
|
}
|
|
fsJson = JSON.parse(cache);
|
|
}
|
|
|
|
localStorage.setItem('fs-json', JSON.stringify(fsJson));
|
|
const fs: Map<number, TreeNode> = this._jsonToNodeTable(fsJson);
|
|
|
|
// This produces a different checksum!
|
|
|
|
// Find a way to produce the same hash from Map and a fetched json file or cached stringified json
|
|
console.log(MD5.hash(JSON.stringify(Array.from(fs))));
|
|
|
|
FileSystem.#instance = new FileSystem(fs);
|
|
}
|
|
|
|
private static async _fetchFileSystem(path: string): Promise<JSON> {
|
|
const response = await fetch(path);
|
|
if (!response.ok) throw new Error('Failed to fetch the file system json');
|
|
|
|
return await response.json();
|
|
}
|
|
|
|
private async _fetchFsSignature(path: string): Promise<any> {
|
|
try {
|
|
const response = await fetch(path);
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
const data = await response.text();
|
|
return data.slice(0, 36); //32 characters of uuid + 4 dashes
|
|
} catch (error) {
|
|
console.error('Failed to fetch the file system signature', error);
|
|
}
|
|
}
|
|
|
|
private _fsToJsonString(): string {}
|
|
|
|
private static async fetchFsJson(): Promise<JSON> {
|
|
const checksum: string | null = localStorage.getItem('fs-checksum');
|
|
|
|
if (checksum !== sig || signature === null || localStorage.getItem('fs') === null) {
|
|
const fs: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
|
|
localStorage.setItem('signature', sig);
|
|
localStorage.setItem('fs', JSON.stringify(fs));
|
|
|
|
console.info('FS fetched from file, new sinature:', sig);
|
|
|
|
return fs;
|
|
} else {
|
|
const fs: string | null = localStorage.getItem('fs');
|
|
if (fs === null) throw new Error('FS in LocalStorage is null!');
|
|
|
|
console.info('FS fetched from localStorage with signature:', sig);
|
|
|
|
return JSON.parse(fs);
|
|
}
|
|
}
|
|
|
|
private static _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
|
|
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
|
|
const entryList = Object.entries(data);
|
|
|
|
for (let i = 0; i < entryList.length; i++) {
|
|
const object: any = entryList[i][1];
|
|
const node: TreeNode = {
|
|
inode: object.Inode,
|
|
name: object.Name,
|
|
type: object.Type,
|
|
size: object.Size,
|
|
interactible: object.Interactible,
|
|
func: object.Func,
|
|
children: object.Children,
|
|
content: object.Content,
|
|
link: object.Target,
|
|
permission: {
|
|
user: {
|
|
r: object.Permission[0]?.Read,
|
|
w: object.Permission[0]?.Write,
|
|
x: object.Permission[0]?.Exec
|
|
},
|
|
group: {
|
|
r: object.Permission[1]?.Read,
|
|
w: object.Permission[1]?.Write,
|
|
x: object.Permission[1]?.Exec
|
|
},
|
|
other: {
|
|
r: object.Permission[2]?.Read,
|
|
w: object.Permission[2]?.Write,
|
|
x: object.Permission[2]?.Exec
|
|
}
|
|
},
|
|
owner: object.Owner,
|
|
group: object.Group,
|
|
timestamps: {
|
|
modified: new Date(object.TimeStamps.MTime),
|
|
changed: new Date(object.TimeStamps.CTime),
|
|
accessed: new Date(object.TimeStamps.ATime)
|
|
},
|
|
parent: object.Parent
|
|
};
|
|
|
|
FsTable.set(object.Inode, node);
|
|
}
|
|
return FsTable;
|
|
}
|
|
|
|
private _createNode(name: string, type: Type, path: number, user: User): void {
|
|
const currTime: Date = new Date();
|
|
|
|
const node: TreeNode = {
|
|
parent: path,
|
|
inode: this._fs.size + 1,
|
|
name: name,
|
|
type: type,
|
|
size: 4096,
|
|
children: [],
|
|
content: '',
|
|
link: -1,
|
|
permission: {
|
|
user: {
|
|
r: true,
|
|
w: true,
|
|
x: false
|
|
},
|
|
group: {
|
|
r: true,
|
|
w: false,
|
|
x: false
|
|
},
|
|
other: {
|
|
r: true,
|
|
w: false,
|
|
x: false
|
|
}
|
|
},
|
|
owner: user.uid,
|
|
group: user.gid,
|
|
timestamps: {
|
|
modified: currTime,
|
|
changed: currTime,
|
|
accessed: currTime
|
|
},
|
|
interactible: false,
|
|
func: null
|
|
};
|
|
|
|
this._fs.set(this._fs.size + 1, node);
|
|
}
|
|
|
|
private _deleteNode(inode: number): void {
|
|
this._fs.delete(inode);
|
|
}
|
|
|
|
private _iNodeToPathString(inode: number): string {
|
|
const currentNode = this._fs.get(inode);
|
|
|
|
if (!currentNode)
|
|
throw new Error(`Failed to parse the path from inode, inode doesnt exist - ${inode}`);
|
|
if (!currentNode.parent || currentNode.inode === this._root) return '/';
|
|
|
|
const parentPath: string | null = this._iNodeToPathString(currentNode.parent);
|
|
if (!parentPath)
|
|
throw new Error(
|
|
`Failed to parse the path from inode, inode doesnt exist - ${currentNode.parent}`
|
|
);
|
|
|
|
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
|
|
}
|
|
|
|
private _pathStringToNode(path: string): TreeNode {
|
|
// Truncates all slatshes at the start and end of the string
|
|
const normalizedPath: string = path.replace(/^\/+|\/+$/g, '');
|
|
|
|
// Splits the path to node names and filters them out from empty strings
|
|
const pathComponents: string[] = normalizedPath.split('/').filter((node) => node.length > 0);
|
|
|
|
let currentNode: TreeNode | undefined = this._fs.get(this._root);
|
|
if (!currentNode)
|
|
throw new Error(`WARNING! - Root node not found under FileSystem._root - ${this._root}`);
|
|
if (pathComponents.length === 0) return currentNode;
|
|
|
|
for (const component of pathComponents) {
|
|
const childINode: number = this._getChildNodeByName(currentNode!, component)?.inode;
|
|
|
|
if (!childINode)
|
|
throw new Error(`Failed to parse the child node from path, is the path correct?`);
|
|
|
|
const nextNode = this._fs.get(childINode);
|
|
if (!nextNode)
|
|
throw new Error(`Failed to parse the child node from path, is the path correct?`);
|
|
|
|
currentNode = nextNode;
|
|
}
|
|
|
|
return currentNode;
|
|
}
|
|
|
|
private _getChildNodeByName(node: TreeNode, name: string): TreeNode {
|
|
for (const inode of node.children) {
|
|
const child = this._fs.get(inode);
|
|
if (child && child.name === name) return child;
|
|
}
|
|
throw new Error(
|
|
`Node under the name ${name} not found in the child list of ${node.name} - ${node.inode}`
|
|
);
|
|
}
|
|
|
|
private _isAbsolutePath = (path: string): boolean => {
|
|
return typeof path === 'string' && path.startsWith('/');
|
|
};
|
|
|
|
public getPathByINode(inode: number): string {
|
|
return this._iNodeToPathString(inode);
|
|
}
|
|
|
|
public formatPath(path: string, user: User): string {
|
|
if (path.startsWith(user.home)) return path.replace(user.home, '~');
|
|
return path;
|
|
}
|
|
|
|
public getNodeByInode(inode: number): TreeNode {
|
|
const node: TreeNode | undefined = this._fs.get(inode);
|
|
if (!node) throw new Error(`No node exists under inode - ${inode}`);
|
|
return node;
|
|
}
|
|
|
|
public resolvePath(path: string, user: User): TreeNode {
|
|
if (path === '/') return this._fs.get(this._root)!;
|
|
|
|
let parsedPath: string = path;
|
|
|
|
if (!this._isAbsolutePath(path)) {
|
|
const trail = this._iNodeToPathString(user.cwd!);
|
|
if (!trail)
|
|
throw new Error('Somehow the current user has his cwd set to a nonexistant directory', {
|
|
cause: 'iNodeToPathString returned null from user.cwd'
|
|
});
|
|
parsedPath = `${trail}/${path}`;
|
|
}
|
|
if (path.startsWith('~')) {
|
|
const trail = user.home;
|
|
if (!trail)
|
|
throw new Error('User has his home directory set to a nonexistant one or is undefined', {
|
|
cause: 'iNodeToPathString returned null from user.home'
|
|
});
|
|
parsedPath = `${trail}/${path.replace('~', '')}`;
|
|
}
|
|
|
|
return this._pathStringToNode(parsedPath);
|
|
}
|
|
|
|
public recursiveTraversalPre(
|
|
node: TreeNode,
|
|
callback: (param: TreeNode) => void,
|
|
childIndex?: number[],
|
|
depthIndex?: number
|
|
): void {
|
|
if (!depthIndex) depthIndex = 0;
|
|
if (!childIndex) childIndex = [0];
|
|
|
|
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
|
|
let unNode = this._fs.get(node.children[childIndex[depthIndex]]);
|
|
if (!unNode)
|
|
throw new Error(`Node does not exist under inode ${node.children[childIndex[depthIndex]]}`);
|
|
node = unNode;
|
|
|
|
depthIndex++;
|
|
if (!childIndex[depthIndex]) childIndex[depthIndex] = 0;
|
|
|
|
callback(node);
|
|
} else {
|
|
let unNode = this._fs.get(node.parent);
|
|
if (!unNode) throw new Error(`Node does not exist under inode ${node.parent}`);
|
|
node = unNode;
|
|
|
|
childIndex[depthIndex] = 0;
|
|
depthIndex--;
|
|
childIndex[depthIndex]++;
|
|
}
|
|
|
|
if (depthIndex < 0) return;
|
|
|
|
this.recursiveTraversalPre(node, callback, childIndex, depthIndex);
|
|
}
|
|
|
|
public static get instance(): FileSystem {
|
|
if (!FileSystem.#instance) {
|
|
throw new Error(`FileSystem was not initialized properly!`);
|
|
}
|
|
|
|
return FileSystem.instance;
|
|
}
|
|
}
|
|
|
|
export type TreeNode = {
|
|
inode: number;
|
|
parent: number;
|
|
name: string;
|
|
type: Type;
|
|
size: number; //Size in Bytes
|
|
children: number[];
|
|
content: string; // GUID of the cache file that contains the file contents.
|
|
link: number; // Links
|
|
permission: NodePermission;
|
|
owner: number;
|
|
group: number;
|
|
timestamps: TimeStamps;
|
|
interactible: boolean;
|
|
func: any;
|
|
};
|
|
|
|
export enum Type {
|
|
Directory = 16384,
|
|
File = 32768,
|
|
SymbolicLink = 40960
|
|
}
|
|
|
|
export type NodePermission = {
|
|
user: Permission;
|
|
group: Permission;
|
|
other: Permission;
|
|
};
|
|
|
|
export type Permission = {
|
|
r: boolean;
|
|
w: boolean;
|
|
x: boolean;
|
|
};
|
|
|
|
export type TimeStamps = {
|
|
modified: Date;
|
|
changed: Date;
|
|
accessed: Date;
|
|
};
|