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 PathToToken = join(bds_dir, "google_user_token.json");
const DefaultLoginDrive = {
// Urls
global.GoogleAuth = {}
async function LoadExpress(GoogleDriveCredentials, app = express(), closer = express().listen(1221)){
return new Promise((resolve => {
app.get("/request", (req, res) => {
const SessionUUID = randomUUID();
const secret = GoogleDriveCredentials.installed.client_secret;
const client = GoogleDriveCredentials.installed.client_id;
const redirect = `${req.protocol}://${req.headers.host}/${SessionUUID}/save`;
const oAuth2Client = new google.auth.OAuth2(client, secret, redirect);
global.GoogleAuth[SessionUUID] = oAuth2Client;
res.redirect(oAuth2Client.generateAuthUrl({
access_type: "offline", access_type: "offline",
scope: [ scope: [
"https://www.googleapis.com/auth/drive" "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");
function expressGetGoogleDriveToken(callback){
// Settings
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // minutes
max: 100 // limit each IP to 100 requests per windowMs
}); });
app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */ app.get("/:SessionUUID/save", (req, res) => {
app.use(bodyParser.urlencoded({ extended: true })); const { code } = req.query;
app.use(limiter); const { SessionUUID } = req.params;
app.use(cors());
// Urls
app.get("/request", (req, res) => {
const secret = GoogleDriveCredentials.installed.client_secret;
const client = GoogleDriveCredentials.installed.client_id;
const redirect = `${req.protocol}://${req.headers.host}/save`;
const oAuth2Client = new google.auth.OAuth2(client, secret, redirect);
res.redirect(oAuth2Client.generateAuthUrl(DefaultLoginDrive))
app.get("/save", (req, res) => {
// 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(){
let Port = parseInt(Math.random().toString().replace(/[01]\./, "").slice(0, 4));
if (Port > 1024 && Port < 2542) return Port; else return RandomPort();
}
async function authorize() {
return new Promise(async resolve => {
const GoogleDriveCredentials = (await (await fetch("https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Credentials/Google.json")).json())
const client_secret = GoogleDriveCredentials.installed.client_secret; const client_secret = GoogleDriveCredentials.installed.client_secret;
const client_id = GoogleDriveCredentials.installed.client_id; const client_id = GoogleDriveCredentials.installed.client_id;
const redirect_uris = GoogleDriveCredentials.installed.redirect_uris[0].split("@PORT_REDIRECT").join(6658).split("@URLREDIRECT").join("localhost"); const redirect_uris = "http://localhost:1932/SaveToken"
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris); const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
fs.readFile(PathToToken, (err, user_cred) => { fs.readFile(PathToToken, async (err, user_cred) => {
if (err) { if (err) {
var GetReturn = expressGetGoogleDriveToken(callback); const app = express();
if (process.argv0 === "electron") open("http://localhost:6658/request") app.use(require("body-parser").json());
console.log("Open one of these links in your browser:"); app.use(require("body-parser").urlencoded({ extended: true }));
console.log("http://localhost:6658/request"); app.use(require("express-rate-limit")({windowMs: 1 * 60 * 1000, max: 100}));
for (let index of Ips.internal_ip) console.log(`http://${index}:6658/request`) app.use(require("cors")());
return GetReturn 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)); oAuth2Client.setCredentials(JSON.parse(user_cred));
callback(oAuth2Client); 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 (){}) {
// Upload Function
async function Uploadbackups(object = "Backup.zip", fileLocation = "Backup.zip", callback = function (){}) {
return new Promise(async function(resolve, reject){
try {
const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure"); const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure");
const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey); const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey);
const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container) const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container)
if (!(blobClient.exists())) await blobClient.create(); if (!(blobClient.exists())) await blobClient.create();
const containerClient = blobClient.getBlockBlobClient(resolve(object)) const containerClient = blobClient.getBlockBlobClient(path.resolve(object));
try { const Reponse = await containerClient.uploadFile(fileLocation, {
await containerClient.uploadFile(fileLocation, {
blockSize: 4 * 1024 * 1024, blockSize: 4 * 1024 * 1024,
concurrency: 20, concurrency: 20,
onProgress: (env) => console.log(env) onProgress: (env) => console.log(env)
}) })
console.log("Upload Sucess") if (typeof callback === "function") callback(Reponse);
if (typeof callback === "function") callback() resolve(Reponse);
} catch (err) { } catch (err) {
console.log(`uploadFile failed, requestId - ${err.details.requestId}, statusCode - ${err.statusCode}, errorCode - ${err.details.errorCode}`); 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){
return new Promise(async function (resolve, reject){
const parent_id = GetCloudConfig("Driver").RootID const parent_id = GetCloudConfig("Driver").RootID
return authorize(function (auth) {
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,18 +4,14 @@ 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 bucket = CloudConfig.Oracle().Bucket;
const provider = new oci_common.ConfigFileAuthenticationDetailsProvider(); const provider = new oci_common.ConfigFileAuthenticationDetailsProvider();
const client = new oci_storage.ObjectStorageClient({ const client = new oci_storage.ObjectStorageClient({
authenticationDetailsProvider: provider authenticationDetailsProvider: provider
}); });
try {
const request = {}; const request = {};
const response = await client.getNamespace(request); const response = await client.getNamespace(request);
const namespace = response.value; const namespace = response.value;
@ -32,10 +28,12 @@ const Uploadbackups = async function (
const putObjectResponse = await client.putObject(putObjectRequest); const putObjectResponse = await client.putObject(putObjectRequest);
console.log("File upload successful"); console.log("File upload successful");
if (typeof callback === "function") return callback(putObjectResponse); if (typeof callback === "function") return callback(putObjectResponse);
return putObjectResponse; resolve(putObjectResponse);
} catch (error) { } catch (error) {
console.log("Error ", error); console.log("Error ", error);
reject(error)
} }
});
} }
module.exports = { module.exports = {