@nka212bg/backend-utils 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/socket.js ADDED
@@ -0,0 +1,157 @@
1
+ const WebSocket = require("ws");
2
+ let http = null;
3
+ let https = null;
4
+ let socketsCount = 0;
5
+
6
+ exports.socket = ({ httpServer, httpsServer }) => {
7
+ if (httpServer) {
8
+ http = new WebSocket.Server({ server: httpServer });
9
+ http.on("connection", (ws, req) => {
10
+ ws.params = JSON.parse(`{"${decodeURI(req.url.replace(/\/\?/g, "")).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
11
+ });
12
+ } else if (httpsServer) {
13
+ https = new WebSocket.Server({ server: httpsServer });
14
+ https.on("connection", (ws, req) => {
15
+ ws.params = JSON.parse(`{"${decodeURI(req.url.replace(/\/\?/g, "")).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
16
+ });
17
+ }
18
+ };
19
+
20
+ exports.getUsersStatuses = (users) => {
21
+ if (typeof users == "string") users = users.split(/[, ]/g);
22
+ if (!Array.isArray(users)) return {};
23
+
24
+ const usersObj = {};
25
+ users.forEach((u) => {
26
+ usersObj[u] = { online: false };
27
+ for (const c of https.clients) {
28
+ if (c.params.userId == u) {
29
+ usersObj[u] = { online: true };
30
+ return;
31
+ }
32
+ }
33
+
34
+ for (const c of http.clients) {
35
+ if (c.params.userId == u) {
36
+ usersObj[u] = { online: true };
37
+ return;
38
+ }
39
+ }
40
+ });
41
+
42
+ return usersObj;
43
+ };
44
+
45
+ // exports.getUsersStatuses = (users = []) => {
46
+ // users = users.map((u) => {
47
+ // u = { id: u, online: false };
48
+ // for (const c of https.clients) {
49
+ // if (c.params.userId == u.id) {
50
+ // u.online = true;
51
+ // return u;
52
+ // }
53
+ // }
54
+
55
+ // for (const c of http.clients) {
56
+ // if (c.params.userId == u.id) {
57
+ // u.online = true;
58
+ // return u;
59
+ // }
60
+ // }
61
+
62
+ // return u;
63
+ // });
64
+
65
+ // return users;
66
+ // };
67
+
68
+ exports.sendSocketMessage = ({ userId, skipId, skipToken, data, broadcast } = {}) => {
69
+ let sentCount = 0;
70
+ let tempCount = 0;
71
+
72
+ if (!userId) return;
73
+ userId = !Array.isArray(userId) ? [String(userId)] : userId.map((e) => String(e));
74
+
75
+ if (skipId) skipId = !Array.isArray(skipId) ? [String(skipId)] : skipId.map((e) => String(e));
76
+ if (skipToken && !Array.isArray(skipToken)) skipToken = [String(skipToken)];
77
+
78
+ try {
79
+ if (typeof data != "string") data = JSON.stringify(data);
80
+ } catch {}
81
+
82
+ (https.clients || []).forEach(manageClient);
83
+ (http.clients || []).forEach(manageClient);
84
+
85
+ socketsCount = tempCount;
86
+ return sentCount;
87
+
88
+ function manageClient(client) {
89
+ tempCount += 1;
90
+
91
+ if (broadcast || userId.includes(client.params.userId)) {
92
+ if (skipId && skipId.includes(client.params.userId)) return;
93
+ if (skipToken && skipToken.includes(client.params.token)) return;
94
+
95
+ client.send(data);
96
+ sentCount += 1;
97
+ }
98
+ }
99
+ };
100
+
101
+ exports.socketStat = () => {
102
+ return {
103
+ socketsCount,
104
+ };
105
+ };
106
+
107
+ // "web-push": "^3.2.2", // package.json
108
+ // const webPush = require("web-push");
109
+ // const VAPID_KEYS = webPush.generateVAPIDKeys();
110
+
111
+ // webPush.setVapidDetails(process.env.VAPID_ORIGIN, process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY);
112
+
113
+ // module.exports = (app) => {
114
+ // app.get("vapidPublicKey", function (req, res) {
115
+ // res.send(process.env.VAPID_PUBLIC_KEY);
116
+ // });
117
+
118
+ // app.post("register", function (req, res) {
119
+ // // A real world application would store the subscription info.
120
+ // res.sendStatus(201);
121
+ // });
122
+
123
+ // app.post("sendNotification", function (req, res) {
124
+ // const subscription = req.body.subscription;
125
+ // const payload = req.body.payload;
126
+ // const options = {
127
+ // TTL: req.body.ttl,
128
+ // };
129
+
130
+ // setTimeout(function () {
131
+ // webPush
132
+ // .sendNotification(subscription, payload, options)
133
+ // .then(function () {
134
+ // res.sendStatus(201);
135
+ // })
136
+ // .catch(function (error) {
137
+ // console.log(error);
138
+ // res.sendStatus(500);
139
+ // });
140
+ // }, req.body.delay * 1000);
141
+
142
+ // fetch("./sendNotification", {
143
+ // method: "post",
144
+ // headers: {
145
+ // "Content-type": "application/json",
146
+ // },
147
+ // body: JSON.stringify({
148
+ // subscription: subscription,
149
+ // payload: payload,
150
+ // delay: delay,
151
+ // ttl: ttl,
152
+ // }),
153
+ // });
154
+ // });
155
+
156
+ // return app;
157
+ // };
package/stripe.js ADDED
@@ -0,0 +1,98 @@
1
+ const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY, {
2
+ appInfo: {
3
+ name: "buukmarks.com",
4
+ version: "1.0.0",
5
+ },
6
+ });
7
+
8
+ exports.balance = async () => {
9
+ return await stripe.balance.retrieve();
10
+ };
11
+
12
+ exports.createCustomer = async ({ name, email, source, metadata }) => {
13
+ try {
14
+ const data = await stripe.customers.create({ name, email, source, metadata });
15
+ return { data };
16
+ } catch (error) {
17
+ return { error };
18
+ }
19
+ };
20
+
21
+ exports.updateCustomer = async ({ stripe_id, source, metadata }) => {
22
+ try {
23
+ const data = await stripe.customers.update(stripe_id, { source, metadata });
24
+ return { data };
25
+ } catch (error) {
26
+ return { error };
27
+ }
28
+ };
29
+
30
+ exports.getCustomerSubscription = async (stripe_id) => {
31
+ try {
32
+ const customer = await stripe.customers.retrieve(stripe_id);
33
+ const paymentMethod = await stripe.customers.retrievePaymentMethod(customer.id, customer.default_source);
34
+
35
+ return { data: { customer, paymentMethod } };
36
+ } catch (error) {
37
+ return { error };
38
+ }
39
+ };
40
+
41
+ exports.getPayments = async (user_id) => {
42
+ if (!user_id) return { error: "missing_required" };
43
+
44
+ try {
45
+ let { data = [], ...rest } = await stripe.charges.search({ query: `metadata["user_id"]:"${user_id}"` });
46
+
47
+ data = data.map((e) => {
48
+ return {
49
+ id: e.id,
50
+ amount: e.amount / 100,
51
+ currency: e.currency,
52
+ paid_on: e.created,
53
+ description: e.description,
54
+ paid_until: e.metadata.paid_until,
55
+ card: {
56
+ brand: e.source.brand.toLowerCase(),
57
+ last4: e.source.last4,
58
+ country: e.source.country,
59
+ },
60
+ receipt_url: e.receipt_url,
61
+ status: e.status,
62
+ // raw: e,
63
+ };
64
+ });
65
+
66
+ return { data, rest };
67
+ } catch (error) {
68
+ return { error };
69
+ }
70
+ };
71
+
72
+ exports.chargeCustomer = async ({ stripe_id, description, amount, currency, metadata }) => {
73
+ amount = Number(amount);
74
+ if (!amount) return { error: "no_amount" };
75
+
76
+ try {
77
+ const data = await stripe.charges.create({
78
+ customer: stripe_id,
79
+ description: description || "OceanDIV undescribed payment from chat app.",
80
+ currency: currency || "usd",
81
+ amount,
82
+ metadata,
83
+ });
84
+
85
+ return { data };
86
+ } catch (error) {
87
+ return { error };
88
+ }
89
+ };
90
+
91
+ exports.unsubscribeStripe = async (stripe_id) => {
92
+ try {
93
+ const data = await stripe.customers.del(stripe_id);
94
+ return { data };
95
+ } catch (error) {
96
+ return { error };
97
+ }
98
+ };
package/systemLog.js ADDED
@@ -0,0 +1,72 @@
1
+ const { existsSync, writeFile, readFileSync, readdirSync, mkdirSync } = require("fs");
2
+ const { sep } = require("path");
3
+
4
+ const logDir = `${__basedir}/logs`;
5
+ !existsSync(logDir) && mkdirSync(logDir, { recursive: true });
6
+
7
+ const docStartTemplate = {
8
+ serverCounters: { ENOENT: {} },
9
+ //
10
+ };
11
+
12
+ const fileName = `${logDir}/activeLog.json`;
13
+ let ACTIVE_LOG = existsSync(fileName) ? JSON.parse(readFileSync(fileName, "utf8") || JSON.stringify(docStartTemplate)) : docStartTemplate;
14
+
15
+ exports.writeLog = () => {
16
+ const stringifiedLog = JSON.stringify(ACTIVE_LOG);
17
+ if (stringifiedLog.length < 300000) {
18
+ writeFile(fileName, stringifiedLog, (error) => error && console.error(error));
19
+ return;
20
+ }
21
+
22
+ writeFile(`${logDir}/${Date.now()}.json`, stringifiedLog, (error) => error && console.error(error));
23
+ ACTIVE_LOG = { serverCounters: ACTIVE_LOG.serverCounters };
24
+ };
25
+
26
+ setInterval(this.writeLog, 1000 * 60);
27
+
28
+ exports.getLog = (fileName) => {
29
+ let active;
30
+
31
+ if (!fileName || fileName == "activeLog.json") {
32
+ active = ACTIVE_LOG;
33
+ } else {
34
+ const file = `${logDir}/${fileName}`;
35
+ active = existsSync(file) ? JSON.parse(readFileSync(file, "utf8") || JSON.stringify(docStartTemplate)) : docStartTemplate;
36
+ }
37
+
38
+ return {
39
+ active,
40
+ available: readdirSync(logDir),
41
+ };
42
+ };
43
+
44
+ exports.setLogMsg = ({ from = "misc", arguments } = {}) => {
45
+ arguments = argumentsSanitize(arguments);
46
+
47
+ const matchMsg = arguments.match(/(enoent).*(users|challenges)/gi)?.[0];
48
+ if (matchMsg) {
49
+ ACTIVE_LOG.serverCounters.ENOENT[matchMsg] ? (ACTIVE_LOG.serverCounters.ENOENT[matchMsg] += 1) : (ACTIVE_LOG.serverCounters.ENOENT[matchMsg] = 1);
50
+ return;
51
+ }
52
+
53
+ from = from.split(sep).slice(-2).join(".");
54
+ if (!ACTIVE_LOG[from]) ACTIVE_LOG[from] = [];
55
+
56
+ ACTIVE_LOG[from].unshift({
57
+ msg: arguments,
58
+ date: Date.now(),
59
+ userIp: __userIp,
60
+ });
61
+
62
+ if (arguments.includes("forceWrite")) {
63
+ }
64
+ };
65
+
66
+ /* -------------------- helpers -------------------- */
67
+ function argumentsSanitize(args) {
68
+ if (!args) return [];
69
+ if (typeof args == "object") return JSON.stringify(Object.values(args));
70
+
71
+ return [String(args)];
72
+ }