2019-11-23 15:10:51 +00:00
|
|
|
import { conf } from "../helpers/ConfigHelper";
|
|
|
|
import { join } from "path";
|
2019-11-30 17:28:27 +00:00
|
|
|
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
2019-11-30 17:34:21 +00:00
|
|
|
import { randomStr } from "./CryptUtils";
|
2019-11-23 15:10:51 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* User data utilities
|
|
|
|
*
|
|
|
|
* @author Pierre HUBERT
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get and returns the URL path to an userdata file
|
|
|
|
*
|
|
|
|
* @param uri Optionnal, defines the URI pointing on the file
|
|
|
|
* @param sysPath Optionnal, defines if system path is required instead of URL
|
|
|
|
* @return The full URL to the userdata file
|
|
|
|
*/
|
|
|
|
export function pathUserData(uri: string = "", sysPath: boolean = false) : string {
|
|
|
|
if(!sysPath)
|
2019-11-23 15:23:29 +00:00
|
|
|
return join(conf().storageURL, uri).replace(":/", "://");
|
2019-11-23 15:10:51 +00:00
|
|
|
else
|
|
|
|
return join(conf().storagePath, uri);
|
2019-11-30 17:28:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Prepare file creation
|
|
|
|
*
|
|
|
|
* @param userID Target user ID
|
|
|
|
* @param folderName The file directory (based on user_data folder)
|
|
|
|
*/
|
|
|
|
export function prepareFileCreation(userID: number, folderName: string) : string {
|
|
|
|
|
|
|
|
// Determine subfolder name
|
|
|
|
let subfolder : string;
|
|
|
|
if(userID != 0)
|
|
|
|
subfolder = join(folderName, userID.toString());
|
|
|
|
else
|
|
|
|
subfolder = folderName;
|
|
|
|
|
|
|
|
const subfolderPath = pathUserData(subfolder, true);
|
|
|
|
|
|
|
|
// Check if the path exists
|
|
|
|
if(!existsSync(subfolderPath)) {
|
|
|
|
|
|
|
|
// Create the directory
|
|
|
|
mkdirSync(subfolderPath, {
|
|
|
|
recursive: true
|
|
|
|
});
|
|
|
|
|
|
|
|
// Block directory listing
|
|
|
|
writeFileSync(join(subfolderPath, "index.html"), "");
|
|
|
|
}
|
|
|
|
|
|
|
|
return subfolder;
|
2019-11-30 17:34:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a new file name in order to create a new file
|
|
|
|
*
|
|
|
|
* @param dir Target directory
|
|
|
|
* @param ext File extension
|
|
|
|
* @returns Generated file name (including dir)
|
|
|
|
*/
|
|
|
|
export function generateNewUserDataFileName(dir: string, ext: string) : string {
|
|
|
|
const sys_dir = pathUserData(dir, true);
|
|
|
|
|
|
|
|
if(!existsSync(sys_dir))
|
|
|
|
throw Error("Trying to create file into " + sys_dir + " but this directory does not exists!");
|
|
|
|
|
|
|
|
// Generate random file name
|
|
|
|
let filename : string;
|
|
|
|
do {
|
|
|
|
filename = randomStr(25) + "." + ext;
|
|
|
|
} while(existsSync(join(sys_dir, filename)));
|
|
|
|
|
|
|
|
return join(dir, filename);
|
2019-11-23 15:10:51 +00:00
|
|
|
}
|