Move files from Scripts/ to src/ and add 'on' to start server. #144
@ -3,8 +3,7 @@
|
||||
"browser": true,
|
||||
"commonjs": true,
|
||||
"es2021": true,
|
||||
"node": true,
|
||||
"shelljs": true
|
||||
"node": true
|
||||
},
|
||||
"globals": {
|
||||
"bds_log_string": "writable",
|
||||
@ -24,6 +23,7 @@
|
||||
"error",
|
||||
"double"
|
||||
],
|
||||
"eqeqeq": 0
|
||||
"eqeqeq": 0,
|
||||
"no-async-promise-executor": "off"
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,15 @@
|
||||
#!/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 bds = require("../index");
|
||||
const { valid_platform } = require("../lib/BdsSystemInfo");
|
||||
const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings");
|
||||
const commandExits = require("../lib/commandExist");
|
||||
const download = require("../src/download");
|
||||
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
|
||||
|
||||
// Bds Maneger ArgV
|
||||
const argv = require("minimist")(process.argv.slice(2));
|
||||
if (Object.getOwnPropertyNames(argv).length <= 1) argv.help = true
|
||||
@ -56,9 +59,22 @@ function StartServer(){
|
||||
|
||||
// CLI Commands
|
||||
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("close", ()=>{console.log("CTRL + C closed readline, stopping server");bds_server.stop()})
|
||||
bds_server.exit(function(c){if (c !== 0) rl.close()})
|
||||
rl.on("line", (input) => {
|
||||
// Stop
|
||||
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();
|
||||
} catch (err) {
|
||||
console.log(`Bds Maneger Start Server Error: \n******\n${err}`);
|
||||
|
4
index.js
4
index.js
@ -76,7 +76,7 @@ module.exports.BdsSettigs = require("./lib/BdsSettings");
|
||||
const { World_BAckup } = require("./src/backups");
|
||||
const { config, get_config, config_example } = require("./src/ServerSettings");
|
||||
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
|
||||
@ -180,4 +180,4 @@ module.exports.tmphost = require("./lib/tempHost")
|
||||
/**
|
||||
* Load Crontab Backup
|
||||
*/
|
||||
module.exports.Cron_Loaded = require("./src/LoadCronBackup")
|
||||
module.exports.Cron_Loaded = CronBackups;
|
@ -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");
|
||||
})
|
||||
}
|
||||
})
|
@ -3,6 +3,9 @@ const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { resolve, join } = require("path");
|
||||
const { randomUUID } = require("crypto");
|
||||
const { CronJob } = require("cron");
|
||||
const { GetCronBackup } = require("../lib/BdsSettings");
|
||||
const { Backup } = require("./backups");
|
||||
|
||||
// Bds Maneger Inports
|
||||
const commandExists = require("../lib/commandExist");
|
||||
@ -14,76 +17,6 @@ const BdsInfo = require("../BdsManegerInfo.json");
|
||||
// Set bdsexec functions
|
||||
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() {
|
||||
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, "");
|
||||
|
||||
// Player JSON File
|
||||
ServerExec.stdout.on("data", Player_Json);
|
||||
ServerExec.stderr.on("data", Player_Json);
|
||||
ServerExec.stdout.on("data", data => Player_Json(data, UpdateUserJSON));
|
||||
ServerExec.stderr.on("data", data => Player_Json(data, UpdateUserJSON));
|
||||
|
||||
// Log File
|
||||
ServerExec.stdout.on("data", LogSaveFunction);
|
||||
@ -193,7 +126,7 @@ function start() {
|
||||
const returnFuntion = {
|
||||
uuid: randomUUID(),
|
||||
stop: function (){
|
||||
ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop);
|
||||
ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop+"\n");
|
||||
return BdsInfo.Servers[GetPlatform()].stop;
|
||||
},
|
||||
command: async function (command = "list", callback = data => console.log(data)){
|
||||
@ -222,13 +155,109 @@ function start() {
|
||||
exit: function (exitCallback = process.exit){if (
|
||||
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]});
|
||||
global.BdsExecs[returnFuntion.uuid] = 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(){
|
||||
const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs)
|
||||
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 = {
|
||||
start,
|
||||
BdsCommand,
|
||||
stop
|
||||
stop,
|
||||
CronBackups: CurrentBackups,
|
||||
Player_Search,
|
||||
}
|
||||
|
@ -1,44 +1,39 @@
|
||||
const fs = require("fs");
|
||||
const { join } = require("path")
|
||||
const { google } = require("googleapis");
|
||||
const { bds_dir } = require("../../../lib/BdsSettings")
|
||||
const { randomUUID } = require("crypto");
|
||||
const express = require("express");
|
||||
const app = express();
|
||||
var cors = require("cors");
|
||||
const rateLimit = require("express-rate-limit");
|
||||
const bodyParser = require("body-parser");
|
||||
const fetchSync = require("@the-bds-maneger/fetchsync");
|
||||
const Ips = require("../../external_ip");
|
||||
const DefaultLoginDrive = {
|
||||
const { google } = require("googleapis");
|
||||
|
||||
const ip_andress = require("../../external_ip");
|
||||
const { bds_dir } = require("../../../lib/BdsSettings");
|
||||
|
||||
const PathToToken = join(bds_dir, "google_user_token.json");
|
||||
|
||||
// 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",
|
||||
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");
|
||||
|
||||
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.use(bodyParser.urlencoded({ extended: true }));
|
||||
app.use(limiter);
|
||||
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) => {
|
||||
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
|
||||
const code = req.query.code
|
||||
|
||||
const oAuth2Client = global.GoogleAuth[SessionUUID];
|
||||
oAuth2Client.getToken(code, (err, save_token) => {
|
||||
if (err) return console.error("Error accessing keys and saving, Error:", err);
|
||||
oAuth2Client.setCredentials(save_token);
|
||||
@ -46,40 +41,58 @@ function expressGetGoogleDriveToken(callback){
|
||||
fs.writeFile(PathToToken, JSON.stringify(save_token, null, 4), function (err){
|
||||
if (err) {
|
||||
console.error("We were unable to save json, please try again later");
|
||||
return close_server();
|
||||
return closer();
|
||||
}
|
||||
|
||||
callback(oAuth2Client);
|
||||
res.json({
|
||||
"token": save_token,
|
||||
status: "success"
|
||||
})
|
||||
close_server();
|
||||
closer.close()
|
||||
resolve(oAuth2Client);
|
||||
});
|
||||
});
|
||||
});
|
||||
app.get("*", (req, res)=>{res.redirect("/request")});
|
||||
})
|
||||
const saver = app.listen(6658)
|
||||
function close_server() {saver.close()}
|
||||
return 6658
|
||||
app.all("*", ({res}) => res.redirect("/request"));
|
||||
}));
|
||||
}
|
||||
|
||||
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_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);
|
||||
fs.readFile(PathToToken, (err, user_cred) => {
|
||||
fs.readFile(PathToToken, async (err, user_cred) => {
|
||||
if (err) {
|
||||
var GetReturn = expressGetGoogleDriveToken(callback);
|
||||
if (process.argv0 === "electron") open("http://localhost:6658/request")
|
||||
console.log("Open one of these links in your browser:");
|
||||
console.log("http://localhost:6658/request");
|
||||
for (let index of Ips.internal_ip) console.log(`http://${index}:6658/request`)
|
||||
return GetReturn
|
||||
}
|
||||
const app = express();
|
||||
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));
|
||||
callback(oAuth2Client);
|
||||
resolve(oAuth2Client);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
authorize,
|
||||
}
|
@ -1,23 +1,28 @@
|
||||
const { resolve } = require("path");
|
||||
const path = require("path");
|
||||
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
|
||||
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 sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey);
|
||||
const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container)
|
||||
if (!(blobClient.exists())) await blobClient.create();
|
||||
const containerClient = blobClient.getBlockBlobClient(resolve(object))
|
||||
try {
|
||||
await containerClient.uploadFile(fileLocation, {
|
||||
const containerClient = blobClient.getBlockBlobClient(path.resolve(object));
|
||||
const Reponse = await containerClient.uploadFile(fileLocation, {
|
||||
blockSize: 4 * 1024 * 1024,
|
||||
concurrency: 20,
|
||||
onProgress: (env) => console.log(env)
|
||||
})
|
||||
console.log("Upload Sucess")
|
||||
if (typeof callback === "function") callback()
|
||||
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 = {
|
||||
|
@ -3,10 +3,9 @@ const { google } = require("googleapis");
|
||||
const { authorize } = require("./Auth/Google");
|
||||
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
|
||||
return authorize(function (auth) {
|
||||
const drive = google.drive({version: "v3", auth});
|
||||
const UploadFile = {
|
||||
resource: {
|
||||
name: file_name
|
||||
@ -20,14 +19,16 @@ module.exports.Uploadbackups = function (file_name = "Backup.zip", fileLocation
|
||||
// Driver Root ID Backups
|
||||
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) => {
|
||||
if (err) throw Error(err)
|
||||
if (err) reject(err)
|
||||
else {
|
||||
console.log(`File URL: https://drive.google.com/file/d/${file.data.id}/`);
|
||||
if (typeof BackupCallback === "function") BackupCallback(file);
|
||||
resolve(`https://drive.google.com/file/d/${file.data.id}/`);
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
// End Upload Backup
|
||||
};
|
@ -4,18 +4,14 @@ const fs = require("fs");
|
||||
const { resolve } = require("path");
|
||||
const { CloudConfig } = require("../../lib/BdsSettings");
|
||||
|
||||
const Uploadbackups = async function (
|
||||
object = "Backup.zip",
|
||||
fileLocation = resolve(__dirname, "../Backup.zip"),
|
||||
callback = function (data){console.log(data)}
|
||||
){
|
||||
async function Uploadbackups(object = "Backup.zip", fileLocation = resolve(__dirname, "../Backup.zip"), callback = function (data){console.log(data)}){
|
||||
return new Promise(async function (resolve, reject){
|
||||
try {
|
||||
const bucket = CloudConfig.Oracle().Bucket;
|
||||
const provider = new oci_common.ConfigFileAuthenticationDetailsProvider();
|
||||
const client = new oci_storage.ObjectStorageClient({
|
||||
authenticationDetailsProvider: provider
|
||||
});
|
||||
|
||||
try {
|
||||
const request = {};
|
||||
const response = await client.getNamespace(request);
|
||||
const namespace = response.value;
|
||||
@ -32,10 +28,12 @@ const Uploadbackups = async function (
|
||||
const putObjectResponse = await client.putObject(putObjectRequest);
|
||||
console.log("File upload successful");
|
||||
if (typeof callback === "function") return callback(putObjectResponse);
|
||||
return putObjectResponse;
|
||||
resolve(putObjectResponse);
|
||||
} catch (error) {
|
||||
console.log("Error ", error);
|
||||
reject(error)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
Reference in New Issue
Block a user