Move files from Scripts/ to src/ and add 'on' to start server. #144

Merged
Sirherobrine23 merged 8 commits from Changes-and-move-Scripts-dir into main 2021-08-02 22:33:21 +00:00
9 changed files with 290 additions and 222 deletions
Showing only changes of commit d38904a753 - Show all commits

View File

@ -3,8 +3,7 @@
"browser": true, "browser": true,
"commonjs": true, "commonjs": true,
"es2021": true, "es2021": true,
"node": true, "node": true
"shelljs": true
}, },
"globals": { "globals": {
"bds_log_string": "writable", "bds_log_string": "writable",
@ -24,6 +23,7 @@
"error", "error",
"double" "double"
], ],
"eqeqeq": 0 "eqeqeq": 0,
"no-async-promise-executor": "off"
} }
} }

View File

@ -1,12 +1,15 @@
#!/usr/bin/env node #!/usr/bin/env node
if (process.platform === "win32") process.title = "Bds Maneger CLI";else process.title = "Bds_Manger_CLI" if (process.platform === "win32") process.title = "Bds Maneger CLI"; else process.title = "Bds_Manger_CLI";
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
// Inports
const readline = require("readline"); const readline = require("readline");
const bds = require("../index"); const bds = require("../index");
const { valid_platform } = require("../lib/BdsSystemInfo"); const { valid_platform } = require("../lib/BdsSystemInfo");
const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings"); const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings");
const commandExits = require("../lib/commandExist"); const commandExits = require("../lib/commandExist");
const download = require("../src/download"); const download = require("../src/download");
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
// Bds Maneger ArgV // Bds Maneger ArgV
const argv = require("minimist")(process.argv.slice(2)); const argv = require("minimist")(process.argv.slice(2));
if (Object.getOwnPropertyNames(argv).length <= 1) argv.help = true if (Object.getOwnPropertyNames(argv).length <= 1) argv.help = true
@ -56,9 +59,22 @@ function StartServer(){
// CLI Commands // CLI Commands
const rl = readline.createInterface({input: process.stdin,output: process.stdout}); const rl = readline.createInterface({input: process.stdin,output: process.stdout});
rl.on("line", (input) => {if (input === "@stop") {rl.close(); bds_server.stop()} else bds_server.command(input)}); rl.on("line", (input) => {
rl.on("close", ()=>{console.log("CTRL + C closed readline, stopping server");bds_server.stop()}) // Stop
bds_server.exit(function(c){if (c !== 0) rl.close()}) if (input.trim() === "@stop") {
rl.close();
bds_server.stop()
}
// Server input
else bds_server.command(input);
});
rl.on("close", ()=>{
console.log("CTRL + C closed readline, stopping server");
bds_server.stop();
})
bds_server.exit(function(c){
if (c !== 0) rl.close();
})
bds.api(); bds.api();
} catch (err) { } catch (err) {
console.log(`Bds Maneger Start Server Error: \n******\n${err}`); console.log(`Bds Maneger Start Server Error: \n******\n${err}`);

View File

@ -76,7 +76,7 @@ module.exports.BdsSettigs = require("./lib/BdsSettings");
const { World_BAckup } = require("./src/backups"); const { World_BAckup } = require("./src/backups");
const { config, get_config, config_example } = require("./src/ServerSettings"); const { config, get_config, config_example } = require("./src/ServerSettings");
const download = require("./src/download"); const download = require("./src/download");
const { start, stop, BdsCommand } = require("./src/basic_server") const { start, stop, BdsCommand, CronBackups } = require("./src/basic_server")
/** /**
* Register tokens to use in Bds Maneger REST and other supported applications * Register tokens to use in Bds Maneger REST and other supported applications
@ -180,4 +180,4 @@ module.exports.tmphost = require("./lib/tempHost")
/** /**
* Load Crontab Backup * Load Crontab Backup
*/ */
module.exports.Cron_Loaded = require("./src/LoadCronBackup") module.exports.Cron_Loaded = CronBackups;

View File

@ -1,21 +0,0 @@
const { CronJob } = require("cron");
const { GetCronBackup } = require("../lib/BdsSettings");
const { Backup } = require("./backups")
const Cloud = {
Azure: require("./clouds/Azure").Uploadbackups,
Driver: require("./clouds/GoogleDriver").Uploadbackups,
Oracle: require("./clouds/OracleCI").Uploadbackups,
}
const CurrentBackups = GetCronBackup();
module.exports = CurrentBackups.map(Crron => {
return {
CronFunction: new CronJob(Crron.cron, function(){
console.log("Starting Server and World Backup");
const CurrentBackup = Backup();
if (Crron.Azure) Cloud.Azure(CurrentBackup.file_name, CurrentBackup.file_path); else console.info("Azure Backup Disabled");
if (Crron.Driver) Cloud.Driver(CurrentBackup.file_name, CurrentBackup.file_path); else console.info("Google Driver Backup Disabled");
if (Crron.Oracle) Cloud.Oracle(CurrentBackup.file_name, CurrentBackup.file_path); else console.info("Oracle Bucket Backup Disabled");
})
}
})

View File

@ -3,6 +3,9 @@ const fs = require("fs");
const path = require("path"); const path = require("path");
const { resolve, join } = require("path"); const { resolve, join } = require("path");
const { randomUUID } = require("crypto"); const { randomUUID } = require("crypto");
const { CronJob } = require("cron");
const { GetCronBackup } = require("../lib/BdsSettings");
const { Backup } = require("./backups");
// Bds Maneger Inports // Bds Maneger Inports
const commandExists = require("../lib/commandExist"); const commandExists = require("../lib/commandExist");
@ -14,76 +17,6 @@ const BdsInfo = require("../BdsManegerInfo.json");
// Set bdsexec functions // Set bdsexec functions
global.BdsExecs = {}; global.BdsExecs = {};
const UpdateUserJSON = function (New_Object = new Array()){
const Player_Json_path = GetPaths("player");
const Current_platorm = GetPlatform();
let Players_Json = {
bedrock: [],
java: [],
pocketmine: [],
jsprismarine: [],
}
if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"));
// Array
Players_Json[Current_platorm] = Players_Json[Current_platorm].concat(New_Object)
fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2));
return Players_Json
}
const Player_Json = function (data = "aaaaaa\n\n\naa"){
const Current_platorm = GetPlatform();
// Bedrock
if (Current_platorm === "bedrock") {
// "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840",
// "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840",
let BedrockMap = data.split(/\n|\r/gi).map(line => {
if (line.includes("connected:")) {
let SplitLine = line.replace(/\[INFO\]\s+Player/, "").trim().split(/\s+/gi);
// player
let Player = line.trim().replace(/disconnected:|connected:/, "").trim().split(/,\s+xuid:/).filter(a=>a).map(a=>a.trim()).filter(a=>a);
// Object Map
const ObjectReturn = {
Player: Player[0],
Action: `${(()=>{if (SplitLine[0].trim() === "connected:") return "connect"; else if (SplitLine[0].trim() === "disconnected") return "disconect";})()}`,
xuid: Player[1] || null,
Date: new Date(),
}
// Return
return ObjectReturn;
} else return false;
}).filter(a=>a);
UpdateUserJSON(BedrockMap);
}
// Java
else if (Current_platorm === "java") {
let JavaMap = data.split(/\n|\r/gi).map(line => {
if (line.trim().includes("joined the game") || line.includes("left the game")) {
line = line.replace(/^\[.+\] \[.+\/.+\]: /, "").trim();
let Actions = null;
if (/joined/.test(line)) Actions = "connect";
else if (/left/.test(line)) Actions = "disconect";
// Player Object
const JavaObject = {
Player: line.replace(/joined the game|left the game/gi, "").trim(),
Action: Actions,
Date: new Date(),
}
// Return JSON
return JavaObject
} else return false;
}).filter(a=>a);
UpdateUserJSON(JavaMap);
}
}
function start() { function start() {
if (BdsDetect()){let ErrorReturn = "You already have a server running"; console.warn(ErrorReturn); throw new Error(ErrorReturn);} if (BdsDetect()){let ErrorReturn = "You already have a server running"; console.warn(ErrorReturn); throw new Error(ErrorReturn);}
@ -179,8 +112,8 @@ function start() {
fs.writeFileSync(LatestLog_Path, ""); fs.writeFileSync(LatestLog_Path, "");
// Player JSON File // Player JSON File
ServerExec.stdout.on("data", Player_Json); ServerExec.stdout.on("data", data => Player_Json(data, UpdateUserJSON));
ServerExec.stderr.on("data", Player_Json); ServerExec.stderr.on("data", data => Player_Json(data, UpdateUserJSON));
// Log File // Log File
ServerExec.stdout.on("data", LogSaveFunction); ServerExec.stdout.on("data", LogSaveFunction);
@ -193,7 +126,7 @@ function start() {
const returnFuntion = { const returnFuntion = {
uuid: randomUUID(), uuid: randomUUID(),
stop: function (){ stop: function (){
ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop); ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop+"\n");
return BdsInfo.Servers[GetPlatform()].stop; return BdsInfo.Servers[GetPlatform()].stop;
}, },
command: async function (command = "list", callback = data => console.log(data)){ command: async function (command = "list", callback = data => console.log(data)){
@ -222,13 +155,109 @@ function start() {
exit: function (exitCallback = process.exit){if ( exit: function (exitCallback = process.exit){if (
typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code)); typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code));
}, },
on: function(action = String, callback = Function) {} on: function(action = String(), callback = Function) {
if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect");
// Functions
const data = data => Player_Json(data, function (array_status){
for (let _player of array_status) {
if (action === "all") callback(_player);
else if (_player.Action === action) callback(_player)
}
});
ServerExec.stdout.on("data", data);
ServerExec.stderr.on("data", data);
}
} }
ServerExec.on("exit", ()=>{delete global.BdsExecs[returnFuntion.uuid]}); ServerExec.on("exit", ()=>{delete global.BdsExecs[returnFuntion.uuid]});
global.BdsExecs[returnFuntion.uuid] = returnFuntion; global.BdsExecs[returnFuntion.uuid] = returnFuntion;
return returnFuntion; return returnFuntion;
} }
function Player_Json(data = "aaaaaa\n\n\naa", callback = () => {}){
const Current_platorm = GetPlatform();
// Bedrock
if (Current_platorm === "bedrock") {
// "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840",
// "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840",
const BedrockMap = data.split(/\n|\r/gi).map(line => {
if (line.includes("connected") || line.includes("disconnected")) {
let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi);
// player
let Player = line.trim().replace(/\[.+\]\s+Player/gi, "").trim().replace(/disconnected:|connected:/, "").trim().split(/,\s+xuid:/).filter(a=>a).map(a=>a.trim()).filter(a=>a);
//
let Actions = null;
if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect";
else if (/^connected/.test(SplitLine[0].trim())) Actions = "connect";
// Object Map
const ObjectReturn = {
Player: Player[0],
Action: Actions,
xuid: Player[1] || null,
Date: new Date(),
}
// Return
return ObjectReturn
} else return false;
}).filter(a=>a);
callback(BedrockMap);
}
// Java
else if (Current_platorm === "java") {
const JavaMap = data.split(/\n|\r/gi).map(line => {
if (line.trim().includes("joined the game") || line.includes("left the game")) {
line = line.replace(/^\[.+\] \[.+\/.+\]:/, "").trim();
let Actions = null;
if (/joined/.test(line)) Actions = "connect";
else if (/left/.test(line)) Actions = "disconnect";
// Player Object
const JavaObject = {
Player: line.replace(/joined the game|left the game/gi, "").trim(),
Action: Actions,
Date: new Date(),
}
// Return JSON
return JavaObject
} else return false;
}).filter(a=>a);
callback(JavaMap);
}
}
const UpdateUserJSON = function (New_Object = new Array()){
const Player_Json_path = GetPaths("player");
const Current_platorm = GetPlatform();
let Players_Json = {
bedrock: [],
java: [],
pocketmine: [],
jsprismarine: [],
}
if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"));
// Array
Players_Json[Current_platorm] = Players_Json[Current_platorm].concat(New_Object)
fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2));
return Players_Json
}
// Search player in JSON
function Player_Search(player = "dontSteve") {
const Player_Json_path = GetPaths("player"), Current_platorm = GetPlatform();
const Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[Current_platorm]
for (let Player of Players_Json) {
if (Player.Player === player.trim()) return Player;
}
return {};
}
function GetSessions(){ function GetSessions(){
const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs) const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs)
if (ArraySessions.length === 0) throw "Start Server"; if (ArraySessions.length === 0) throw "Start Server";
@ -259,8 +288,35 @@ function stop(SessionID = null) {
} }
} }
const Cloud_Backup = {
Azure: require("./clouds/Azure").Uploadbackups,
Driver: require("./clouds/GoogleDriver").Uploadbackups,
Oracle: require("./clouds/OracleCI").Uploadbackups,
}
const CurrentBackups = GetCronBackup().map(Crron => {
return {
CronFunction: new CronJob(Crron.cron, async () => {
console.log("Starting Server and World Backup");
const CurrentBackup = Backup();
// Azure
if (Crron.Azure) Cloud_Backup.Azure(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Azure Backup Disabled");
// Google Driver
if (Crron.Driver) Cloud_Backup.Driver(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Google Driver Backup Disabled");
// Oracle Bucket
if (Crron.Oracle) Cloud_Backup.Oracle(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Oracle Bucket Backup Disabled");
})
}
});
module.exports = { module.exports = {
start, start,
BdsCommand, BdsCommand,
stop stop,
CronBackups: CurrentBackups,
Player_Search,
} }

View File

@ -1,44 +1,39 @@
const fs = require("fs"); const fs = require("fs");
const { join } = require("path") const { join } = require("path")
const { google } = require("googleapis"); const { randomUUID } = require("crypto");
const { bds_dir } = require("../../../lib/BdsSettings")
const express = require("express"); const express = require("express");
const app = express(); const { google } = require("googleapis");
var cors = require("cors");
const rateLimit = require("express-rate-limit"); const ip_andress = require("../../external_ip");
const bodyParser = require("body-parser"); const { bds_dir } = require("../../../lib/BdsSettings");
const fetchSync = require("@the-bds-maneger/fetchsync");
const Ips = require("../../external_ip");
const DefaultLoginDrive = {
access_type: "offline",
scope: [
"https://www.googleapis.com/auth/drive"
]
}
const GoogleDriveCredentials = fetchSync("https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Credentials/Google.json").json()
// -------------------------------------------------------------
const PathToToken = join(bds_dir, "google_user_token.json"); const PathToToken = join(bds_dir, "google_user_token.json");
function expressGetGoogleDriveToken(callback){ // Urls
// Settings global.GoogleAuth = {}
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // minutes async function LoadExpress(GoogleDriveCredentials, app = express(), closer = express().listen(1221)){
max: 100 // limit each IP to 100 requests per windowMs return new Promise((resolve => {
}); app.get("/request", (req, res) => {
app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */ const SessionUUID = randomUUID();
app.use(bodyParser.urlencoded({ extended: true })); const secret = GoogleDriveCredentials.installed.client_secret;
app.use(limiter); const client = GoogleDriveCredentials.installed.client_id;
app.use(cors()); const redirect = `${req.protocol}://${req.headers.host}/${SessionUUID}/save`;
// Urls const oAuth2Client = new google.auth.OAuth2(client, secret, redirect);
app.get("/request", (req, res) => { global.GoogleAuth[SessionUUID] = oAuth2Client;
const secret = GoogleDriveCredentials.installed.client_secret; res.redirect(oAuth2Client.generateAuthUrl({
const client = GoogleDriveCredentials.installed.client_id; access_type: "offline",
const redirect = `${req.protocol}://${req.headers.host}/save`; scope: [
const oAuth2Client = new google.auth.OAuth2(client, secret, redirect); "https://www.googleapis.com/auth/drive"
res.redirect(oAuth2Client.generateAuthUrl(DefaultLoginDrive)) ]
app.get("/save", (req, res) => { }));
});
app.get("/:SessionUUID/save", (req, res) => {
const { code } = req.query;
const { SessionUUID } = req.params;
// http://localhost:6899/save?code=********************************************************************&scope=https://www.googleapis.com/auth/drive // http://localhost:6899/save?code=********************************************************************&scope=https://www.googleapis.com/auth/drive
const code = req.query.code
const oAuth2Client = global.GoogleAuth[SessionUUID];
oAuth2Client.getToken(code, (err, save_token) => { oAuth2Client.getToken(code, (err, save_token) => {
if (err) return console.error("Error accessing keys and saving, Error:", err); if (err) return console.error("Error accessing keys and saving, Error:", err);
oAuth2Client.setCredentials(save_token); oAuth2Client.setCredentials(save_token);
@ -46,40 +41,58 @@ function expressGetGoogleDriveToken(callback){
fs.writeFile(PathToToken, JSON.stringify(save_token, null, 4), function (err){ fs.writeFile(PathToToken, JSON.stringify(save_token, null, 4), function (err){
if (err) { if (err) {
console.error("We were unable to save json, please try again later"); console.error("We were unable to save json, please try again later");
return close_server(); return closer();
} }
callback(oAuth2Client);
res.json({ res.json({
"token": save_token, "token": save_token,
status: "success" status: "success"
}) })
close_server(); closer.close()
resolve(oAuth2Client);
}); });
}); });
}); });
app.get("*", (req, res)=>{res.redirect("/request")}); app.all("*", ({res}) => res.redirect("/request"));
}) }));
const saver = app.listen(6658)
function close_server() {saver.close()}
return 6658
} }
module.exports.authorize = function (callback) { function RandomPort(){
const client_secret = GoogleDriveCredentials.installed.client_secret; let Port = parseInt(Math.random().toString().replace(/[01]\./, "").slice(0, 4));
const client_id = GoogleDriveCredentials.installed.client_id; if (Port > 1024 && Port < 2542) return Port; else return RandomPort();
const redirect_uris = GoogleDriveCredentials.installed.redirect_uris[0].split("@PORT_REDIRECT").join(6658).split("@URLREDIRECT").join("localhost"); }
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
fs.readFile(PathToToken, (err, user_cred) => { async function authorize() {
if (err) { return new Promise(async resolve => {
var GetReturn = expressGetGoogleDriveToken(callback); const GoogleDriveCredentials = (await (await fetch("https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Credentials/Google.json")).json())
if (process.argv0 === "electron") open("http://localhost:6658/request") const client_secret = GoogleDriveCredentials.installed.client_secret;
console.log("Open one of these links in your browser:"); const client_id = GoogleDriveCredentials.installed.client_id;
console.log("http://localhost:6658/request"); const redirect_uris = "http://localhost:1932/SaveToken"
for (let index of Ips.internal_ip) console.log(`http://${index}:6658/request`) const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
return GetReturn fs.readFile(PathToToken, async (err, user_cred) => {
} if (err) {
oAuth2Client.setCredentials(JSON.parse(user_cred)); const app = express();
callback(oAuth2Client); app.use(require("body-parser").json());
app.use(require("body-parser").urlencoded({ extended: true }));
app.use(require("express-rate-limit")({windowMs: 1 * 60 * 1000, max: 100}));
app.use(require("cors")());
const port = RandomPort()
ip_andress.internal_ip.forEach(ips => {
let { ipv4, ipv6 } = ips.Interna_IP;
console.log(`Open: http://${ipv4}:${port}/request`);
if (ipv6) console.log(`Open: http://[${ipv6}]:${port}/request`);
});
// Return auth
const AuthToken = await LoadExpress(GoogleDriveCredentials, app, app.listen(port));
resolve(AuthToken);
} else {
oAuth2Client.setCredentials(JSON.parse(user_cred));
resolve(oAuth2Client);
}
});
}); });
}
module.exports = {
authorize,
} }

View File

@ -1,23 +1,28 @@
const { resolve } = require("path"); const path = require("path");
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob"); const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
const NewBdsSettings = require("../../lib/BdsSettings"); const NewBdsSettings = require("../../lib/BdsSettings");
const Uploadbackups = async function (object = "Backup.zip", fileLocation = "Backup.zip", callback = function (){}) {
const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure"); // Upload Function
const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey); async function Uploadbackups(object = "Backup.zip", fileLocation = "Backup.zip", callback = function (){}) {
const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container) return new Promise(async function(resolve, reject){
if (!(blobClient.exists())) await blobClient.create(); try {
const containerClient = blobClient.getBlockBlobClient(resolve(object)) const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure");
try { const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey);
await containerClient.uploadFile(fileLocation, { const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container)
blockSize: 4 * 1024 * 1024, if (!(blobClient.exists())) await blobClient.create();
concurrency: 20, const containerClient = blobClient.getBlockBlobClient(path.resolve(object));
onProgress: (env) => console.log(env) const Reponse = await containerClient.uploadFile(fileLocation, {
}) blockSize: 4 * 1024 * 1024,
console.log("Upload Sucess") concurrency: 20,
if (typeof callback === "function") callback() onProgress: (env) => console.log(env)
} catch (err) { })
console.log(`uploadFile failed, requestId - ${err.details.requestId}, statusCode - ${err.statusCode}, errorCode - ${err.details.errorCode}`); if (typeof callback === "function") callback(Reponse);
} resolve(Reponse);
} catch (err) {
console.log(`uploadFile failed, requestId - ${err.details.requestId}, statusCode - ${err.statusCode}, errorCode - ${err.details.errorCode}`);
reject(err);
}
})
} }
module.exports = { module.exports = {

View File

@ -3,10 +3,9 @@ const { google } = require("googleapis");
const { authorize } = require("./Auth/Google"); const { authorize } = require("./Auth/Google");
const { GetCloudConfig } = require("../../lib/BdsSettings"); const { GetCloudConfig } = require("../../lib/BdsSettings");
module.exports.Uploadbackups = function (file_name = "Backup.zip", fileLocation = "Backup.zip", BackupCallback){ module.exports.Uploadbackups = async function (file_name = "Backup.zip", fileLocation = "Backup.zip", BackupCallback){
const parent_id = GetCloudConfig("Driver").RootID return new Promise(async function (resolve, reject){
return authorize(function (auth) { const parent_id = GetCloudConfig("Driver").RootID
const drive = google.drive({version: "v3", auth});
const UploadFile = { const UploadFile = {
resource: { resource: {
name: file_name name: file_name
@ -20,14 +19,16 @@ module.exports.Uploadbackups = function (file_name = "Backup.zip", fileLocation
// Driver Root ID Backups // Driver Root ID Backups
if (parent_id) UploadFile.resource.parents = [parent_id]; if (parent_id) UploadFile.resource.parents = [parent_id];
// Request const auth = await authorize();
const drive = google.drive({version: "v3", auth});
drive.files.create(UploadFile, (err, file) => { drive.files.create(UploadFile, (err, file) => {
if (err) throw Error(err) if (err) reject(err)
else { else {
console.log(`File URL: https://drive.google.com/file/d/${file.data.id}/`); console.log(`File URL: https://drive.google.com/file/d/${file.data.id}/`);
if (typeof BackupCallback === "function") BackupCallback(file); if (typeof BackupCallback === "function") BackupCallback(file);
resolve(`https://drive.google.com/file/d/${file.data.id}/`);
} }
}); });
}); });
// End Upload Backup
}; };

View File

@ -4,38 +4,36 @@ const fs = require("fs");
const { resolve } = require("path"); const { resolve } = require("path");
const { CloudConfig } = require("../../lib/BdsSettings"); const { CloudConfig } = require("../../lib/BdsSettings");
const Uploadbackups = async function ( async function Uploadbackups(object = "Backup.zip", fileLocation = resolve(__dirname, "../Backup.zip"), callback = function (data){console.log(data)}){
object = "Backup.zip", return new Promise(async function (resolve, reject){
fileLocation = resolve(__dirname, "../Backup.zip"), try {
callback = function (data){console.log(data)} const bucket = CloudConfig.Oracle().Bucket;
){ const provider = new oci_common.ConfigFileAuthenticationDetailsProvider();
const bucket = CloudConfig.Oracle().Bucket; const client = new oci_storage.ObjectStorageClient({
const provider = new oci_common.ConfigFileAuthenticationDetailsProvider(); authenticationDetailsProvider: provider
const client = new oci_storage.ObjectStorageClient({ });
authenticationDetailsProvider: provider const request = {};
const response = await client.getNamespace(request);
const namespace = response.value;
const stats = fs.statSync(fileLocation);
const nodeFsBlob = new oci_storage.NodeFSBlob(fileLocation, stats.size);
const objectData = await nodeFsBlob.getData();
const putObjectRequest = {
namespaceName: namespace,
bucketName: bucket,
putObjectBody: objectData,
objectName: object,
contentLength: stats.size
};
const putObjectResponse = await client.putObject(putObjectRequest);
console.log("File upload successful");
if (typeof callback === "function") return callback(putObjectResponse);
resolve(putObjectResponse);
} catch (error) {
console.log("Error ", error);
reject(error)
}
}); });
try {
const request = {};
const response = await client.getNamespace(request);
const namespace = response.value;
const stats = fs.statSync(fileLocation);
const nodeFsBlob = new oci_storage.NodeFSBlob(fileLocation, stats.size);
const objectData = await nodeFsBlob.getData();
const putObjectRequest = {
namespaceName: namespace,
bucketName: bucket,
putObjectBody: objectData,
objectName: object,
contentLength: stats.size
};
const putObjectResponse = await client.putObject(putObjectRequest);
console.log("File upload successful");
if (typeof callback === "function") return callback(putObjectResponse);
return putObjectResponse;
} catch (error) {
console.log("Error ", error);
}
} }
module.exports = { module.exports = {